streamit-player 1.0.1 → 1.0.3

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.
@@ -2024,11 +2024,11 @@ var StreamitPlayer=function(B){"use strict";/**
2024
2024
  * @license
2025
2025
  * Copyright 2017 Google LLC
2026
2026
  * SPDX-License-Identifier: BSD-3-Clause
2027
- */const $s={attribute:!0,type:String,converter:ht,reflect:!1,hasChanged:Ct},Os=(c=$s,e,t)=>{const{kind:i,metadata:s}=t;let r=globalThis.litPropertyMetadata.get(s);if(r===void 0&&globalThis.litPropertyMetadata.set(s,r=new Map),i==="setter"&&((c=Object.create(c)).wrapped=!0),r.set(t.name,c),i==="accessor"){const{name:a}=t;return{set(n){const l=e.get.call(this);e.set.call(this,n),this.requestUpdate(a,l,c,!0,n)},init(n){return n!==void 0&&this.C(a,void 0,c,n),n}}}if(i==="setter"){const{name:a}=t;return function(n){const l=this[a];e.call(this,n),this.requestUpdate(a,l,c,!0,n)}}throw Error("Unsupported decorator location: "+i)};function O(c){return(e,t)=>typeof t=="object"?Os(c,e,t):((i,s,r)=>{const a=s.hasOwnProperty(r);return s.constructor.createProperty(r,i),a?Object.getOwnPropertyDescriptor(s,r):void 0})(c,e,t)}/**
2027
+ */const $s={attribute:!0,type:String,converter:ht,reflect:!1,hasChanged:Ct},Os=(c=$s,e,t)=>{const{kind:i,metadata:s}=t;let r=globalThis.litPropertyMetadata.get(s);if(r===void 0&&globalThis.litPropertyMetadata.set(s,r=new Map),i==="setter"&&((c=Object.create(c)).wrapped=!0),r.set(t.name,c),i==="accessor"){const{name:a}=t;return{set(n){const l=e.get.call(this);e.set.call(this,n),this.requestUpdate(a,l,c,!0,n)},init(n){return n!==void 0&&this.C(a,void 0,c,n),n}}}if(i==="setter"){const{name:a}=t;return function(n){const l=this[a];e.call(this,n),this.requestUpdate(a,l,c,!0,n)}}throw Error("Unsupported decorator location: "+i)};function F(c){return(e,t)=>typeof t=="object"?Os(c,e,t):((i,s,r)=>{const a=s.hasOwnProperty(r);return s.constructor.createProperty(r,i),a?Object.getOwnPropertyDescriptor(s,r):void 0})(c,e,t)}/**
2028
2028
  * @license
2029
2029
  * Copyright 2017 Google LLC
2030
2030
  * SPDX-License-Identifier: BSD-3-Clause
2031
- */function j(c){return O({...c,state:!0,attribute:!1})}/**
2031
+ */function j(c){return F({...c,state:!0,attribute:!1})}/**
2032
2032
  * @license
2033
2033
  * Copyright 2017 Google LLC
2034
2034
  * SPDX-License-Identifier: BSD-3-Clause
@@ -2036,7 +2036,7 @@ var StreamitPlayer=function(B){"use strict";/**
2036
2036
  * @license
2037
2037
  * Copyright 2017 Google LLC
2038
2038
  * SPDX-License-Identifier: BSD-3-Clause
2039
- */function Us(c,e){return(t,i,s)=>{const r=a=>{var n;return((n=a.renderRoot)==null?void 0:n.querySelector(c))??null};return Fs(t,i,{get(){return r(this)}})}}var w=(c=>(c.IDLE="idle",c.REQUESTING="ad-requesting",c.LOADED="ad-loaded",c.PLAYING="ad-playing",c.PAUSED="ad-paused",c.BUFFERING="ad-buffering",c.SKIPPING="ad-skipping",c.ENDED="ad-ended",c.ERROR="ad-error",c.CONTENT_RESUMING="content-resuming",c))(w||{}),xi=(c=>(c.PREROLL="preroll",c.MIDROLL="midroll",c.POSTROLL="postroll",c))(xi||{}),Ai=(c=>(c.IMA="IMA",c.VAST="VAST",c.VMAP="VMAP",c.CUSTOM="CUSTOM",c))(Ai||{}),ze=(c=>(c.AUTO="auto",c.USER="user",c.DISABLED="disabled",c))(ze||{}),Pi=(c=>(c.LINEAR="linear",c.NON_LINEAR="non-linear",c.COMPANION="companion",c.OVERLAY="overlay",c))(Pi||{}),Ci=(c=>(c.IMPRESSION="impression",c.CREATIVE_VIEW="creativeView",c.START="start",c.FIRST_QUARTILE="firstQuartile",c.MIDPOINT="midpoint",c.THIRD_QUARTILE="thirdQuartile",c.COMPLETE="complete",c.PAUSE="pause",c.RESUME="resume",c.MUTE="mute",c.UNMUTE="unmute",c.CLICK="click",c.SKIP="skip",c.CLOSE="close",c.ERROR="error",c))(Ci||{}),ie=(c=>(c.CONFIGURATION="configuration",c.PROVIDER="provider",c.NETWORK="network",c.TIMEOUT="timeout",c.PARSING="parsing",c.PLAYBACK="playback",c.TRACKING="tracking",c.BLOCKED="blocked",c.UNKNOWN="unknown",c))(ie||{});class Mi{static validate(e){var s;const t={passed:!1,providerConfigured:!1,tagUrlValid:!1,errors:[]},i=(s=e.config)==null?void 0:s.ads;if(!i)return t.errors.push("No advertisement configuration provided."),t;if(i.enabled===!1)return t.errors.push("Ads subsystem is disabled in configuration."),t;if(i.provider?t.providerConfigured=!0:t.errors.push("No ad provider specified in config."),i.tagUrl)try{new URL(i.tagUrl),t.tagUrlValid=!0}catch{t.errors.push(`Invalid ad tag URL: "${i.tagUrl}"`)}else i.inlineXml||t.errors.push("Neither tagUrl nor inlineXml is configured.");return t.passed=t.errors.length===0,t}}function ce(c,e=!1){if(isNaN(c)||c===1/0)return e?"00:00:00":"00:00";const t=c<0,i=Math.abs(c),s=Math.floor(i%60),r=Math.floor(i/60%60),a=Math.floor(i/3600),n=o=>o.toString().padStart(2,"0"),l=a>0||e?`${n(a)}:${n(r)}:${n(s)}`:`${n(r)}:${n(s)}`;return t?`-${l}`:l}function Ii(c){if(!c||typeof window>"u")return!1;try{return new URL(c,window.location.href).origin===window.location.origin}catch{return!1}}const Bs=["script","iframe","object","embed","link","meta","base","form"],Ns=/^\s*(javascript:|data:text\/html)/i;function Vs(c){var e;if(!c)return"";if(typeof DOMParser>"u")return console.warn("[utils] DOMParser is not defined in this environment. Cannot sanitize HTML."),"";try{const t=new DOMParser().parseFromString(c,"text/html");for(const r of Bs){const a=t.body.getElementsByTagName(r);for(;a.length>0;)(e=a[0].parentNode)==null||e.removeChild(a[0])}const i=t.createTreeWalker(t.body,NodeFilter.SHOW_ELEMENT);let s=i.currentNode;for(;s;){for(const r of Array.from(s.attributes)){const a=r.name.toLowerCase();if(a.startsWith("on")){s.removeAttribute(r.name);continue}(a==="href"||a==="src"||a==="style")&&Ns.test(r.value)&&s.removeAttribute(r.name)}s=i.nextNode()}return t.body.innerHTML}catch(t){return console.warn("[utils] Failed to sanitize HTML overlay content:",t),""}}function Li(c,e){const t=c.split(/\s+/).filter(Boolean);return!t.includes("allow-same-origin")||!(!!e.isSrcDoc||Ii(e.srcUrl))?c:(console.warn("[utils] Stripping allow-same-origin from iframe sandbox: creative resolves to the host page's own origin, which would otherwise grant it full DOM access to the host document."),t.filter(s=>s!=="allow-same-origin").join(" "))}function zs(c){var l,o,d,h;if(!c)return null;let e=c.trim();if(e.length===0)return null;if(e.toLowerCase().includes("<iframe"))try{if(typeof DOMParser>"u")return console.warn("[utils] DOMParser is not defined in this environment. Cannot parse iframe HTML."),null;const f=new DOMParser().parseFromString(e,"text/html");if(f.getElementsByTagName("script").length>0)return console.warn("[utils] script tag detected inside iframe HTML. Rejecting."),null;const g=f.querySelector("iframe");if(!g)return console.warn("[utils] No iframe element found in input HTML."),null;const m=g.getAttribute("src");if(!m)return console.warn("[utils] iframe element has no src attribute."),null;e=m.trim()}catch(u){return console.error("[utils] Error parsing iframe HTML:",u),null}let t;try{t=new URL(e)}catch{return console.warn("[utils] Invalid URL format for embed: ",e),null}if(t.protocol!=="http:"&&t.protocol!=="https:")return console.warn("[utils] Protocol not allowed for embed: ",t.protocol),null;const i=t.hostname.toLowerCase();if(!["youtube.com","www.youtube.com","m.youtube.com","youtu.be","vimeo.com","www.vimeo.com","player.vimeo.com","dailymotion.com","www.dailymotion.com","geo.dailymotion.com","twitch.tv","player.twitch.tv","wistia.com","wistia.net","fast.wistia.com","fast.wistia.net","streamable.com","facebook.com","www.facebook.com"].some(u=>i===u||i.endsWith("."+u)))return console.warn("[utils] Host not approved for embed: ",i),null;let a=e;const n=e.toLowerCase();if(n.includes("youtube.com")||n.includes("youtu.be")){let u="";n.includes("youtube.com/watch")?u=t.searchParams.get("v")||"":n.includes("youtu.be/")?u=((l=e.split("youtu.be/")[1])==null?void 0:l.split("?")[0])||"":n.includes("youtube.com/embed/")&&(u=((o=e.split("youtube.com/embed/")[1])==null?void 0:o.split("?")[0])||""),u&&(a=`https://www.youtube.com/embed/${u}?autoplay=1&rel=0&modestbranding=1`)}else if(n.includes("vimeo.com")){let u="";n.includes("player.vimeo.com/video/")?u=((d=e.split("player.vimeo.com/video/")[1])==null?void 0:d.split("?")[0])||"":u=((h=e.split("vimeo.com/")[1])==null?void 0:h.split("?")[0])||"",u&&(a=`https://player.vimeo.com/video/${u}?autoplay=1`)}return a}function Ri(){const c=globalThis.Hls;return typeof c=="function"?Promise.resolve(c):import("https://cdn.jsdelivr.net/npm/hls.js@1/+esm").then(e=>e.default??e)}function Di(c){return!!c&&typeof c.MediaPlayer=="function"}function $i(){const c=globalThis.dashjs;return Di(c)?Promise.resolve(c):import("https://cdn.jsdelivr.net/npm/dashjs@5/+esm").then(e=>{const t=e.default;return Di(t)?t:e})}function tt(c){return c instanceof Error?c.message:String(c)}function ft(c){return c instanceof Error?c.name:void 0}let Oi=!1;const gt=new WeakMap,Dt=new WeakMap,Fi=new WeakMap,it=new WeakMap,Ui=new WeakSet;function Bi(){return{requestMediaKeySystemAccess:!1,mediaKeysCreated:!1,mediaKeysAttached:!1,encryptedEventsCount:0,challengesGenerated:0,licenseRequestsSent:0,licenseResponsesReceived:0,sessionsUpdated:0,keyStatusesChanges:0,usableKeysCount:0,expiredKeysCount:0,outputRestrictedCount:0,internalErrorsCount:0,closedSessionsCount:0,lastInternalError:null,certificatesLoaded:0,certificateLoadLatenciesMs:[],licenseRequestLatenciesMs:[],retryCount:0}}function _s(c){let e="";for(let i=0;i<c.byteLength;i++)e+=String.fromCharCode(c[i]);return(typeof window<"u"&&typeof window.btoa=="function"?window.btoa(e):Buffer.from(c).toString("base64")).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function Hs(c){const e=c.replace(/[\s:-]/g,"");return e.length>0&&e.length%2===0&&/^[0-9a-fA-F]+$/.test(e)}function $t(c){const e=c.trim();if(!e)return"";if(Hs(e)){const i=e.replace(/[\s:-]/g,"").match(/.{1,2}/g);if(!i)return"";const s=new Uint8Array(i.map(r=>parseInt(r,16)));return _s(s)}return e.replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function Ot(c){if(!c)return{};const e={};return Object.entries(c).forEach(([t,i])=>{e[$t(t)]=$t(i)}),e}function qs(){if(Oi||typeof window>"u"||typeof MediaKeys>"u"||typeof MediaKeys.prototype.createSession!="function")return;if(Oi=!0,typeof HTMLVideoElement<"u"&&HTMLVideoElement.prototype.setMediaKeys){const e=HTMLVideoElement.prototype.setMediaKeys;HTMLVideoElement.prototype.setMediaKeys=function(t){const i=Dt.get(this);return i&&t&&gt.set(t,i),e.call(this,t)}}if(typeof MediaKeySystemAccess<"u"&&MediaKeySystemAccess.prototype.createMediaKeys){const e=MediaKeySystemAccess.prototype.createMediaKeys;MediaKeySystemAccess.prototype.createMediaKeys=function(){const t=this.keySystem,i=e.call(this);return i.then(s=>{Fi.set(s,t)}).catch(()=>{}),i}}const c=MediaKeys.prototype.createSession;if(MediaKeys.prototype.createSession=function(e){const t=c.call(this,e),i=gt.get(this),s=Fi.get(this)||"unknown";if(i){it.set(t,i),i.registerSession(t),t.addEventListener("keystatuseschange",()=>{const a={};i.recordKeyStatusesChange(t),t.keyStatuses.forEach((l,o)=>{const d=i.bufferToHex(o);a[d]=l,l==="output-restricted"?i.triggerDrmError("Playback restricted by HDCP output requirements.","certificate"):l==="expired"&&i.triggerDrmError("Playback key has expired.","certificate")});const n=i.getController();n&&n.dispatchEvent("drmkeychange",{session:t,keyStatuses:a})}),t.addEventListener("message",a=>{i.recordChallengeGenerated();const n=i.getController();n&&n.dispatchEvent("drmmessage",{session:t,messageType:a.messageType,message:a.message})});const r=i.getController();r&&r.dispatchEvent("drmsessioncreated",{session:t,system:s})}return t},typeof MediaKeySession<"u"&&typeof MediaKeySession.prototype.update=="function"){const e=MediaKeySession.prototype.update;MediaKeySession.prototype.update=async function(t){const i=await e.call(this,t),s=it.get(this);return s&&s.recordSessionUpdated(),i}}if(typeof MediaKeySession<"u"&&typeof MediaKeySession.prototype.close=="function"){const e=MediaKeySession.prototype.close;MediaKeySession.prototype.close=async function(){const t=await e.call(this),i=it.get(this);return i&&!Ui.has(this)&&(Ui.add(this),i.recordClosedSession(this)),t}}}async function Re(c,e='video/mp4; codecs="avc1.640028"'){if(typeof window>"u"||typeof navigator>"u"||typeof navigator.requestMediaKeySystemAccess!="function")return!1;try{const t=[{initDataTypes:["cenc","keyids","webm","skd","sinf"],videoCapabilities:[{contentType:e}]}];return await navigator.requestMediaKeySystemAccess(c,t),!0}catch{return!1}}async function Ft(){return Re("com.widevine.alpha")}async function Ut(){const c=["com.microsoft.playready","com.microsoft.playready.recommendation","com.chromecast.playready"];for(const e of c)if(await Re(e))return!0;return!1}async function Bt(){if(typeof window>"u")return!1;const c=["com.apple.fps","com.apple.fps.1_0","com.apple.fps.2_0","com.apple.fps.3_0"];for(const e of c)if(await Re(e))return!0;if(typeof window.WebKitMediaKeys=="function"&&typeof window.WebKitMediaKeys.isTypeSupported=="function")try{return window.WebKitMediaKeys.isTypeSupported("com.apple.fps","video/mp4")}catch{return!1}return!1}async function Nt(){return Re("org.w3.clearkey")}async function Ks(){const[c,e,t,i]=await Promise.all([Ft(),Ut(),Bt(),Nt()]);return{widevine:c,playready:e,fairplay:t,clearkey:i}}const Ee=class Ee{constructor(){this.emeDiagnostics=Bi(),this.video=null,this.config=null,this.controller=null,this.mediaKeys=null,this.activeSessions=new Set,this.isDestroyed=!1,this.destroyAbortController=new AbortController,this.eventListeners=[],this.sessionToContentId=new WeakMap,this.pendingLicenseRequests=new Map}getConfig(){return this.config}getActiveSessions(){return this.activeSessions}load(e,t,i,s=!1){if(this.destroy(),this.video=e,this.config=t,this.controller=i,this.isDestroyed=!1,this.destroyAbortController=new AbortController,this.emeDiagnostics=Bi(),this.pendingLicenseRequests.clear(),Ee.activeManagers.add(this),Dt.set(e,this),qs(),!s){const r=n=>{this.handleEncryptedEvent(n)},a=n=>{const l=n.initData;if(l){const o=l instanceof Uint8Array?l:new Uint8Array(l);this.initializeLegacyWebKitSession(o)}};this.video.addEventListener("encrypted",r),this.video.addEventListener("webkitneedkey",a),this.eventListeners.push({target:this.video,type:"encrypted",listener:r}),this.eventListeners.push({target:this.video,type:"webkitneedkey",listener:a})}}registerSession(e){this.activeSessions.add(e),it.set(e,this)}unregisterSession(e){this.activeSessions.delete(e),it.delete(e)}triggerDrmError(e,t,i){this.handleDrmError(e,t,i)}async handleEncryptedEvent(e){if(this.isDestroyed||!this.video||!this.config)return;const t=e.initDataType,i=e.initData;i&&(this.emeDiagnostics.encryptedEventsCount+=1,await this.initializeSession(t,new Uint8Array(i)))}async selectSupportedKeySystem(){if(!this.config)return null;if(this.config.widevine&&await Ft())return{keySystem:"com.widevine.alpha",config:this.config.widevine};if(this.config.playready&&await Ut()){const e=["com.microsoft.playready","com.microsoft.playready.recommendation","com.chromecast.playready"];for(const t of e)if(await Re(t))return{keySystem:t,config:this.config.playready}}if(this.config.fairplay&&await Bt()){const e=["com.apple.fps","com.apple.fps.1_0","com.apple.fps.2_0","com.apple.fps.3_0"];for(const t of e)if(await Re(t))return{keySystem:t,config:this.config.fairplay};return{keySystem:"com.apple.fps",config:this.config.fairplay}}return this.config.clearkey&&await Nt()?{keySystem:"org.w3.clearkey",config:this.config.clearkey}:null}async ensureMediaKeys(e,t){var i,s,r,a,n,l,o,d,h,u;if(this.mediaKeys)return this.mediaKeys;if(!this.video)throw new Error("No video element attached.");try{this.emeDiagnostics.requestMediaKeySystemAccess=!0;const f=((s=(i=this.config)==null?void 0:i.robustness)==null?void 0:s.video)||"",p=((a=(r=this.config)==null?void 0:r.robustness)==null?void 0:a.audio)||"",g=[{contentType:'video/mp4; codecs="avc1.640028"',...f?{robustness:f}:{}},{contentType:'video/mp4; codecs="avc1.4d401e"',...f?{robustness:f}:{}},{contentType:"video/mp4",...f?{robustness:f}:{}},{contentType:'video/webm; codecs="vp9"',...f?{robustness:f}:{}}],m=[{contentType:'audio/mp4; codecs="mp4a.40.2"',...p?{robustness:p}:{}},{contentType:"audio/mp4",...p?{robustness:p}:{}},{contentType:'audio/webm; codecs="opus"',...p?{robustness:p}:{}}],v=[{initDataTypes:["cenc","keyids","webm","skd","sinf"],videoCapabilities:g,audioCapabilities:m,sessionTypes:["temporary"],persistentState:((n=this.config)==null?void 0:n.persistentState)||"optional",distinctiveIdentifier:((l=this.config)==null?void 0:l.distinctiveIdentifier)||"optional"},{initDataTypes:["cenc","keyids","webm","skd","sinf"],videoCapabilities:g,sessionTypes:["temporary"],persistentState:((o=this.config)==null?void 0:o.persistentState)||"optional",distinctiveIdentifier:((d=this.config)==null?void 0:d.distinctiveIdentifier)||"optional"},{initDataTypes:["cenc","keyids","webm","skd","sinf"],audioCapabilities:m,sessionTypes:["temporary"],persistentState:((h=this.config)==null?void 0:h.persistentState)||"optional",distinctiveIdentifier:((u=this.config)==null?void 0:u.distinctiveIdentifier)||"optional"},{initDataTypes:["cenc","keyids","webm","skd","sinf"],videoCapabilities:g,sessionTypes:["temporary"],persistentState:"not-allowed",distinctiveIdentifier:"not-allowed"}],y=await navigator.requestMediaKeySystemAccess(e,v);if(this.isDestroyed)throw new DOMException("Aborted","AbortError");const b=await y.createMediaKeys();if(this.emeDiagnostics.mediaKeysCreated=!0,this.isDestroyed)throw new DOMException("Aborted","AbortError");gt.set(b,this);const S=await this.loadCertificate(t);if(this.isDestroyed)throw new DOMException("Aborted","AbortError");if(S&&(await b.setServerCertificate(S),this.isDestroyed))throw new DOMException("Aborted","AbortError");if(!this.video)throw new DOMException("Aborted","AbortError");return await this.video.setMediaKeys(b),this.mediaKeys=b,this.emeDiagnostics.mediaKeysAttached=!0,b}catch(f){throw ft(f)==="AbortError"||this.handleDrmError(`Failed to initialize MediaKeys for ${e}: ${tt(f)}`,"key-system",f),f}}async fetchWithRetryAndTimeout(e,t,i=3,s=1e4){let r=0;const a=n=>new Promise(l=>setTimeout(l,n));for(;r<=i;){if(this.isDestroyed||this.destroyAbortController.signal.aborted)throw new DOMException("Aborted","AbortError");const n=new AbortController,l=n.signal,o=()=>n.abort();this.destroyAbortController.signal.addEventListener("abort",o);const d=setTimeout(()=>{n.abort()},s);try{const h=await fetch(e,{...t,signal:l});if(clearTimeout(d),this.destroyAbortController.signal.removeEventListener("abort",o),h.ok)return h;if(h.status>=500&&r<i){r++,await a(Math.pow(2,r)*100);continue}throw new Error(`Server returned HTTP status ${h.status}`)}catch(h){if(clearTimeout(d),this.destroyAbortController.signal.removeEventListener("abort",o),this.isDestroyed||this.destroyAbortController.signal.aborted)throw new DOMException("Aborted","AbortError");if(r<i){r++,await a(Math.pow(2,r)*100);continue}throw h}}throw new Error("Request failed after maximum retries")}async loadCertificate(e){var n,l;if(!e)return null;if(e.serverCertificate instanceof Uint8Array)return this.recordCertificateLoaded(0),e.serverCertificate;const t=e.serverCertificateUrl||e.certificateUrl;if(!t)return null;const i=Ee.certCache.get(t);if(i)return this.recordCertificateLoaded(0),i;const s=e.retryCount??((n=this.config)==null?void 0:n.retryCount)??3,r=e.timeout??((l=this.config)==null?void 0:l.timeout)??1e4,a=this.now();try{const d=await(await this.fetchWithRetryAndTimeout(t,{method:"GET"},s,r)).arrayBuffer(),h=new Uint8Array(d);return Ee.certCache.set(t,h),this.recordCertificateLoaded(this.now()-a),h}catch(o){throw ft(o)==="AbortError"||this.handleDrmError("Failed to load server certificate.","certificate",o),o}}async fetchLicense(e,t,i,s){var f,p;const r=this.getConfiguredSystemName(),a=this.resolveSystemConfig(r),n=(a==null?void 0:a.retryCount)??((f=this.config)==null?void 0:f.retryCount)??3,l=(a==null?void 0:a.timeout)??((p=this.config)==null?void 0:p.timeout)??1e4,o=this.recordLicenseRequest(r,e),h={method:"POST",headers:{"Content-Type":"application/octet-stream",...i},body:t};s&&(h.credentials="include");let u=!1;try{const g=await this.fetchWithRetryAndTimeout(e,h,n,l);return u=!0,await g.arrayBuffer()}catch(g){throw ft(g)==="AbortError",g}finally{this.recordLicenseResponse(o,u)}}resolveSystemConfig(e){if(this.config)switch(e){case"widevine":return this.config.widevine;case"playready":return this.config.playready;case"fairplay":return this.config.fairplay;case"clearkey":return this.config.clearkey;default:return}}async initializeSession(e,t){const i=await this.selectSupportedKeySystem();if(!i){this.handleDrmError("No supported key system found for DRM configuration.","key-system");return}const{keySystem:s,config:r}=i;let a=t,n="";if(s.includes("fps")||s.includes("apple")){const l=r;n=typeof l.extractContentId=="function"?l.extractContentId(t):this.getContentId(t),a=this.prepareFairPlayInitData(t)}try{const o=(await this.ensureMediaKeys(s,r)).createSession("temporary");this.activeSessions.add(o),n&&this.sessionToContentId.set(o,n);const d=async h=>{var u,f;try{const p=h.message,g=r.licenseUrl||"";if(s==="org.w3.clearkey"&&((f=(u=this.config)==null?void 0:u.clearkey)!=null&&f.clearkeys))await this.handleClearKeyInlineUpdate(o);else{if(!g)throw new Error("No license URL configured.");let m;if(s.includes("fps")||s.includes("apple")){const v=this.sessionToContentId.get(o)||"";m=await this.fetchFairPlayLicense(g,p,v,r.headers,r.withCredentials)}else m=await this.fetchLicense(g,p,r.headers,r.withCredentials);if(this.isDestroyed)return;await o.update(m)}}catch(p){this.handleDrmError(`License acquisition failed: ${tt(p)}`,"license",p)}};o.addEventListener("message",d),this.eventListeners.push({target:o,type:"message",listener:d}),await o.generateRequest(e,a)}catch(l){this.handleDrmError(`Failed to create or run MediaKeySession: ${tt(l)}`,"session",l)}}async initializeLegacyWebKitSession(e){var s;if(!this.video||!((s=this.config)!=null&&s.fairplay))return;const t=this.config.fairplay,i=typeof t.extractContentId=="function"?t.extractContentId(e):this.getContentId(e);try{const r=window.WebKitMediaKeys;if(!r)throw new Error("WebKitMediaKeys is unsupported on this browser.");const a=await this.loadCertificate(t);if(!a)throw new Error("FairPlay certificate is required.");const n=this.concatInitData(i,a),l=new r("com.apple.fps");this.video.webkitSetMediaKeys(l);const o=l.createSession("video/mp4",n);if(!o)throw new Error("Failed to create WebKitMediaKeySession.");const d=o;i&&this.sessionToContentId.set(d,i);const h=async p=>{const g=p,m=g.message,v=g.destinationURL||t.licenseUrl,y=this.sessionToContentId.get(d)||"";this.recordChallengeGenerated();try{if(!v)throw new Error("No FairPlay license URL configured.");const b=await this.fetchFairPlayLicense(v,m,y,t.headers,t.withCredentials);if(this.isDestroyed)return;o.update(new Uint8Array(b)),this.recordSessionUpdated()}catch(b){this.handleDrmError("Legacy FairPlay license request failed.","license",b)}},u=()=>{this.emeDiagnostics.keyStatusesChanges+=1,this.emeDiagnostics.usableKeysCount+=1,this.controller&&this.controller.dispatchEvent("drmkeychange",{session:d,keyStatuses:{all:"usable"}})},f=p=>{const g=p;this.handleDrmError(`Legacy FairPlay session error: ${g.code??"unknown"}`,"session",g)};o.addEventListener("webkitkeymessage",h),o.addEventListener("webkitkeyadded",u),o.addEventListener("webkitkeyerror",f),this.eventListeners.push({target:o,type:"webkitkeymessage",listener:h}),this.eventListeners.push({target:o,type:"webkitkeyadded",listener:u}),this.eventListeners.push({target:o,type:"webkitkeyerror",listener:f}),this.activeSessions.add(d),this.controller&&this.controller.dispatchEvent("drmsessioncreated",{session:d,system:"com.apple.fps (Legacy)"})}catch(r){this.handleDrmError(`Failed to initialize legacy FairPlay session: ${tt(r)}`,"session",r)}}prepareFairPlayInitData(e){return e}async handleClearKeyInlineUpdate(e){var s,r;const t=(r=(s=this.config)==null?void 0:s.clearkey)==null?void 0:r.clearkeys;if(!t)return;const i=this.recordLicenseRequest("clearkey","inline://clearkey");try{const a=Object.entries(Ot(t)).map(([o,d])=>({kty:"oct",kid:o,k:d})),n=JSON.stringify({keys:a,type:"temporary"}),l=new TextEncoder().encode(n);await e.update(l),this.recordLicenseResponse(i,!0)}catch(a){this.recordLicenseResponse(i,!1),this.handleDrmError(`Failed to load ClearKey inline values: ${tt(a)}`,"license",a)}}handleDrmError(e,t,i){if(this.isDestroyed)return;const s=this.config?Object.keys(this.config).find(a=>a!=="robustness"&&a!=="distinctiveIdentifier"&&a!=="persistentState"):void 0,r={message:`DRM: ${e}`,system:s,errorType:t,originalError:i};this.emeDiagnostics.internalErrorsCount+=1,this.emeDiagnostics.lastInternalError=r.message,console.error("[DrmManager] Mapped DRM Error:",r),this.controller&&(this.controller.dispatchEvent("drmerror",r),this.controller.updateStatePublic({error:`DRM: ${e}`}),this.controller.dispatchEvent("error",{message:`DRM: ${e}`}))}bufferToHex(e){let t;e instanceof ArrayBuffer?t=e:t=e.buffer;const i=new DataView(t);let s="";for(let r=0;r<i.byteLength;r++){const a=i.getUint8(r);s+=a.toString(16).padStart(2,"0")}return s}destroy(){if(!this.isDestroyed){this.isDestroyed=!0,this.destroyAbortController.abort(),Ee.activeManagers.delete(this);for(const e of this.eventListeners)try{e.target.removeEventListener(e.type,e.listener)}catch{}this.eventListeners=[];for(const e of this.activeSessions)try{e.close().then(()=>{this.controller&&this.controller.dispatchEvent("drmsessionclosed",{session:e,system:"unknown"})}).catch(t=>{console.warn("[DrmManager] Error closing session:",t)})}catch(t){console.warn("[DrmManager] Failed to close session:",t)}if(this.activeSessions.clear(),this.pendingLicenseRequests.clear(),this.video){Dt.delete(this.video),this.mediaKeys&&gt.delete(this.mediaKeys);try{this.video.setMediaKeys(null).catch(e=>{console.warn("[DrmManager] Failed to setMediaKeys(null):",e)})}catch{if(typeof this.video.webkitSetMediaKeys=="function")try{this.video.webkitSetMediaKeys(null)}catch{}}}this.video=null,this.config=null,this.controller=null,this.mediaKeys=null}}getController(){return this.controller}noteLicenseRequest(e,t){this.recordLicenseRequest(e,t)}noteLicenseResponse(e,t){this.recordLicenseResponse(this.createLicenseRequestKey(e,t),!0)}now(){return typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now()}getConfiguredSystemName(){return this.config&&Object.keys(this.config).find(e=>e!=="robustness"&&e!=="distinctiveIdentifier"&&e!=="persistentState"&&e!=="retryCount"&&e!=="timeout")||"unknown"}createLicenseRequestKey(e,t){return`${e}::${t}`}recordLicenseRequest(e,t){const i=this.createLicenseRequestKey(e,t),s=this.pendingLicenseRequests.get(i)||[];return s.push(this.now()),this.pendingLicenseRequests.set(i,s),this.emeDiagnostics.licenseRequestsSent+=1,i}recordLicenseResponse(e,t){const i=this.pendingLicenseRequests.get(e)||[],s=i.shift();i.length>0?this.pendingLicenseRequests.set(e,i):this.pendingLicenseRequests.delete(e),typeof s=="number"&&this.emeDiagnostics.licenseRequestLatenciesMs.push(this.now()-s),t&&(this.emeDiagnostics.licenseResponsesReceived+=1)}recordCertificateLoaded(e){this.emeDiagnostics.certificatesLoaded+=1,this.emeDiagnostics.certificateLoadLatenciesMs.push(Math.max(0,e))}recordChallengeGenerated(){this.emeDiagnostics.challengesGenerated+=1}recordSessionUpdated(){this.emeDiagnostics.sessionsUpdated+=1}recordClosedSession(e){this.emeDiagnostics.closedSessionsCount+=1}recordKeyStatusesChange(e){this.emeDiagnostics.keyStatusesChanges+=1,e.keyStatuses.forEach(t=>{t==="usable"?this.emeDiagnostics.usableKeysCount+=1:t==="expired"?this.emeDiagnostics.expiredKeysCount+=1:t==="output-restricted"&&(this.emeDiagnostics.outputRestrictedCount+=1)})}getContentId(e){let t="";try{t=new TextDecoder("utf-16").decode(e),t.includes("skd://")||(t=new TextDecoder("utf-8").decode(e))}catch{t=new TextDecoder("utf-8").decode(e)}const i=t.indexOf("skd://");if(i===-1)return"";let s=t.substring(i+6);const r=s.indexOf("?");r!==-1&&(s=s.substring(0,r));const a=s.indexOf("#");return a!==-1&&(s=s.substring(0,a)),s.replace(/\0/g,"").trim()}concatInitData(e,t){const i=new TextEncoder().encode(e),s=4+i.length+4+t.length,r=new Uint8Array(s),a=new DataView(r.buffer);let n=0;return a.setUint32(n,i.length),n+=4,r.set(i,n),n+=i.length,a.setUint32(n,t.length),n+=4,r.set(t,n),r}async fetchFairPlayLicense(e,t,i,s,r){var m,v,y;const a=this.recordLicenseRequest("fairplay",e),n=this.arrayBufferToBase64(t),l=s&&(s["Content-Type"]==="application/octet-stream"||s["content-type"]==="application/octet-stream");let o=JSON.stringify({spc:n,contentId:i,assetId:i}),d={"Content-Type":"application/json",...s};l&&(o=t,d={"Content-Type":"application/octet-stream",...s});const h={method:"POST",headers:d,body:o};r&&(h.credentials="include");const u=(m=this.config)==null?void 0:m.fairplay,f=(u==null?void 0:u.retryCount)??((v=this.config)==null?void 0:v.retryCount)??3,p=(u==null?void 0:u.timeout)??((y=this.config)==null?void 0:y.timeout)??1e4;let g=!1;try{const b=await this.fetchWithRetryAndTimeout(e,h,f,p);if(g=!0,l)return await b.arrayBuffer();const S=await b.text();try{const A=JSON.parse(S);if(A.ckc)return this.base64ToArrayBuffer(A.ckc);if(A.license)return this.base64ToArrayBuffer(A.license)}catch{}const T=S.trim();return/^[A-Za-z0-9+/=]+$/.test(T)?this.base64ToArrayBuffer(T):new TextEncoder().encode(S).buffer}catch(b){throw ft(b)==="AbortError",b}finally{this.recordLicenseResponse(a,g)}}arrayBufferToBase64(e){const t=new Uint8Array(e);let i="";for(let s=0;s<t.byteLength;s++)i+=String.fromCharCode(t[s]);return typeof window<"u"&&typeof window.btoa=="function"?window.btoa(i):Buffer.from(t).toString("base64")}base64ToArrayBuffer(e){const t=typeof window<"u"&&typeof window.atob=="function"?window.atob(e):Buffer.from(e,"base64").toString("binary"),i=new ArrayBuffer(t.length),s=new Uint8Array(i);for(let r=0;r<t.length;r++)s[r]=t.charCodeAt(r);return i}};Ee.activeManagers=new Set,Ee.certCache=new Map;let De=Ee;function Vt(c){try{return c.getLowLatencyModeEnabled()}catch{return!1}}const Ws=6;function mt(c){if(!c)return"";const e=c.trim().toLowerCase();try{const r=new Intl.DisplayNames(["en"],{type:"language"}).of(e);if(r&&r!==e)return r.charAt(0).toUpperCase()+r.slice(1)}catch{}const t={en:"English",eng:"English",hi:"Hindi",hin:"Hindi",fr:"French",fre:"French",fra:"French",nl:"Dutch",dut:"Dutch",nld:"Dutch",es:"Spanish",spa:"Spanish",de:"German",ger:"German",deu:"German",it:"Italian",ita:"Italian",ja:"Japanese",jpn:"Japanese",zh:"Chinese",zho:"Chinese",chi:"Chinese",pt:"Portuguese",por:"Portuguese",ru:"Russian",rus:"Russian",ar:"Arabic",ara:"Arabic",ko:"Korean",kor:"Korean",sv:"Swedish",swe:"Swedish",no:"Norwegian",nor:"Norwegian",fi:"Finnish",fin:"Finnish",da:"Danish",dan:"Danish",pl:"Polish",pol:"Polish",tr:"Turkish",tur:"Turkish",vi:"Vietnamese",vie:"Vietnamese"},i=e.split("-")[0];return t[i]||t[e]||c.toUpperCase()}function js(c,e){if(c&&c.trim().length>0){const t=c.trim();if(!(/^stream(_\d+)?$/i.test(t)||/^audio(_\d+)?$/i.test(t)||/^\d+$/.test(t))){if(!/^[a-zA-Z]{2,3}(-[a-zA-Z]{2,4})?$/.test(t))return t;const r=mt(t);if(r)return r}}return e&&e.trim().length>0?mt(e.trim()):"Unknown"}class Gs{constructor(){this.source=null,this.video=null,this.controller=null,this.syncTracksListener=null,this.uniqueAudioTracks=[],this.qualityRestoreListener=null,this.drmManager=null}getDrmManager(){return this.drmManager}load(e,t,i){var h;this.source=e,this.video=t,this.controller=i,t.srcObject=null;const s={...((h=i.config)==null?void 0:h.drm)||{},...e.drm||{}};Object.keys(s).length>0&&(this.drmManager=new De,this.drmManager.load(t,s,i,!1));const a=!!(e.variants&&e.variants.length>1),n=a?e.variants.map(u=>u.label):[];let l=e.src||"",o="";if(a){const u=e.variants.findIndex(p=>p.src===e.src),f=u!==-1?u:0;l=e.variants[f].src,o=e.variants[f].label}l&&(t.src=l,t.load()),i.updateStatePublic({qualities:n,activeQuality:o,audioTracks:[],activeAudioTrack:-1,error:null}),this.uniqueAudioTracks=[];const d=t;if(d.audioTracks){const u=()=>{this.syncAndDeduplicateTracks()};this.syncTracksListener=u,d.audioTracks.addEventListener("change",u),d.audioTracks.addEventListener("addtrack",u),d.audioTracks.addEventListener("removetrack",u),this.syncAndDeduplicateTracks()}}syncAndDeduplicateTracks(){if(!this.video||!this.controller)return;const e=this.video;if(!e.audioTracks)return;const t=e.audioTracks,i={},s=[];for(let n=0;n<t.length;n++){const l=t[n],o=l.language||"",d=l.label||"",h=l.kind||"",u=o.toLowerCase(),f=d.toLowerCase(),p=h.toLowerCase(),g=`${u}|${f}|${p}`;i[g]||(i[g]={label:"",rawIndices:[]},s.push(g)),i[g].rawIndices.push(n)}this.uniqueAudioTracks=s.map(n=>{const l=i[n],o=t[l.rawIndices[0]],d=mt(o.language);let h="";o.label&&(/^[a-zA-Z]{2,3}(-[a-zA-Z]{2,4})?$/.test(o.label.trim())||(h=o.label.trim())),h||(h=d||"Unknown");const u=[h],f=o.kind||"";return f&&f!=="main"&&f!=="alternative"&&u.push(f.charAt(0).toUpperCase()+f.slice(1)),{label:u.join(" "),rawIndices:l.rawIndices}});const r=this.uniqueAudioTracks.map(n=>n.label);let a=-1;for(let n=0;n<this.uniqueAudioTracks.length;n++)if(this.uniqueAudioTracks[n].rawIndices.some(d=>t[d].enabled)){a=n;break}this.controller.updateStatePublic({audioTracks:r,activeAudioTrack:a})}destroy(){if(this.video){if(this.syncTracksListener){const e=this.video;e.audioTracks&&(e.audioTracks.removeEventListener("change",this.syncTracksListener),e.audioTracks.removeEventListener("addtrack",this.syncTracksListener),e.audioTracks.removeEventListener("removetrack",this.syncTracksListener))}this.qualityRestoreListener&&this.video.removeEventListener("loadedmetadata",this.qualityRestoreListener)}this.drmManager&&(this.drmManager.destroy(),this.drmManager=null),this.syncTracksListener=null,this.qualityRestoreListener=null,this.source=null,this.video=null,this.controller=null,this.uniqueAudioTracks=[]}setQuality(e){if(this.source&&this.source.variants&&this.video&&this.controller&&e>=0&&e<this.source.variants.length){const t=this.source.variants[e],i=!this.video.paused,s=this.video.currentTime;this.qualityRestoreListener&&this.video.removeEventListener("loadedmetadata",this.qualityRestoreListener);const r=()=>{this.qualityRestoreListener=null,this.video&&(this.video.currentTime=s,i&&this.video.play().catch(a=>console.warn("Restore play failed:",a)))};this.qualityRestoreListener=r,this.video.addEventListener("loadedmetadata",r,{once:!0}),this.video.src=t.src,this.video.load(),this.controller.updateStatePublic({activeQuality:t.label})}}setAudioTrack(e){if(this.video&&e>=0&&e<this.uniqueAudioTracks.length){const t=this.video;if(t.audioTracks){const s=this.uniqueAudioTracks[e].rawIndices[0];for(let r=0;r<t.audioTracks.length;r++)t.audioTracks[r].enabled=r===s;this.controller&&this.controller.updateStatePublic({activeAudioTrack:e})}}}}class Qs{constructor(){this.hls=null,this.hlsRetryCount=0,this.mediaRecoveryCount=0,this.controller=null,this.video=null,this.lastLevelIndex=-1,this.isAutoMode=!0,this.uniqueAudioTracks=[],this.livePollInterval=null,this._isLive=!1,this._isLowLatency=!1,this._dvrWindow=0,this._hasDvr=!1,this.managesSubtitles=!0,this.drmManager=null}getDrmManager(){return this.drmManager}startLivePolling(){this.stopLivePolling(),this.livePollInterval=setInterval(()=>{this.pollLiveStats()},500)}stopLivePolling(){this.livePollInterval&&(clearInterval(this.livePollInterval),this.livePollInterval=null)}getLiveSyncPosition(){return this.hls?this.hls.liveSyncPosition:null}pollLiveStats(){if(!this.hls||!this.controller||!this.video||!this.controller.getState().isLive)return;this.controller.updateLiveState();const t=this.controller.getState();this.controller.dispatchEvent("live-sync-update",{latency:t.liveLatency||0,isAtLiveEdge:t.isAtLiveEdge,playbackRate:this.video.playbackRate})}getRawLiveInfo(){var e;return this._isLive?{isLive:this._isLive,isLowLatency:this._isLowLatency,hasDvr:this._hasDvr,dvrWindow:this._dvrWindow,liveEdgeTarget:((e=this.hls)==null?void 0:e.liveSyncPosition)??null}:null}seekToLiveEdge(){this.hls&&this.hls.liveSyncPosition!==null&&this.video&&(this.video.currentTime=this.hls.liveSyncPosition)}load(e,t,i){e.src&&(this.destroy(),this.controller=i,this.video=t,this.lastLevelIndex=-1,this.isAutoMode=!0,this.uniqueAudioTracks=[],this.hlsRetryCount=0,this.mediaRecoveryCount=0,Ri().then(s=>{var a,n;if(this.controller!==i)return;const r=s;if(r.isSupported()){const o=i.getState().liveMode==="live-only",d={...((a=i.config)==null?void 0:a.drm)||{},...e.drm||{}},h=Object.keys(d).length>0;h&&(this.drmManager=new De,this.drmManager.load(t,d,i,!0)),(async()=>{var g,m,v,y;if(!h)return{};const f={},p={};if(d.widevine){const b=d.widevine,S=this.drmManager?await this.drmManager.loadCertificate(b):null;p["com.widevine.alpha"]=b.licenseUrl||"",f["com.widevine.alpha"]={videoCapabilities:[{contentType:'video/mp4; codecs="avc1.640028"'}],audioCapabilities:[{contentType:'audio/mp4; codecs="mp4a.40.2"'}],...S?{serverCertificate:S}:{},...(g=d.robustness)!=null&&g.video?{videoRobustness:d.robustness.video}:{},...(m=d.robustness)!=null&&m.audio?{audioRobustness:d.robustness.audio}:{},persistentState:d.persistentState||"optional",distinctiveIdentifier:d.distinctiveIdentifier||"optional",sessionTypes:["temporary"]}}if(d.playready){const b=d.playready,S=this.drmManager?await this.drmManager.loadCertificate(b):null;p["com.microsoft.playready"]=b.licenseUrl||"",f["com.microsoft.playready"]={videoCapabilities:[{contentType:'video/mp4; codecs="avc1.640028"'}],audioCapabilities:[{contentType:'audio/mp4; codecs="mp4a.40.2"'}],...S?{serverCertificate:S}:{},...(v=d.robustness)!=null&&v.video?{videoRobustness:d.robustness.video}:{},...(y=d.robustness)!=null&&y.audio?{audioRobustness:d.robustness.audio}:{},persistentState:d.persistentState||"optional",distinctiveIdentifier:d.distinctiveIdentifier||"optional",sessionTypes:["temporary"]}}if(d.clearkey){const b=d.clearkey;p["org.w3.clearkey"]=b.licenseUrl||"",f["org.w3.clearkey"]={sessionTypes:["temporary"]}}return{emeEnabled:!0,licenseServers:p,emeConfigurations:f,licenseXhrSetup:(b,S,T,E)=>{var $,M;let A=null,P="";if(T&&T.keySystem&&(T.keySystem.includes("widevine")?(A=d.widevine,P="widevine"):T.keySystem.includes("playready")?(A=d.playready,P="playready"):T.keySystem.includes("clearkey")&&(A=d.clearkey,P="clearkey")),($=this.controller)==null||$.dispatchEvent("drmlicenserequest",{url:S,challengeSize:E&&E.byteLength||0,system:P||"hls"}),(M=this.drmManager)==null||M.noteLicenseRequest(P||"hls",S),A&&(A.headers&&Object.entries(A.headers).forEach(([I,R])=>{b.setRequestHeader(I,R)}),A.withCredentials&&(b.withCredentials=!0)),A&&A.licenseRequestInterceptor){const I=E instanceof Uint8Array?E.buffer:E;return Promise.resolve(A.licenseRequestInterceptor(I,P)).then(R=>{let N=E;return R instanceof ArrayBuffer?N=new Uint8Array(R):R&&typeof R=="object"&&(R.body instanceof ArrayBuffer?N=new Uint8Array(R.body):R.body&&(N=R.body),R.headers&&Object.entries(R.headers).forEach(([U,C])=>{b.setRequestHeader(U,C)})),N})}},licenseResponseCallback:(b,S,T)=>{var M,I;let E=null,A="";T&&T.keySystem&&(T.keySystem.includes("widevine")?(E=d.widevine,A="widevine"):T.keySystem.includes("playready")?(E=d.playready,A="playready"):T.keySystem.includes("clearkey")&&(E=d.clearkey,A="clearkey"));const P=b.response,$=P&&(P.byteLength||P.size)||0;if((M=this.controller)==null||M.dispatchEvent("drmlicenseresponse",{url:S,responseSize:$,system:A||"hls"}),(I=this.drmManager)==null||I.noteLicenseResponse(A||"hls",S),E&&E.licenseResponseInterceptor){const R=P instanceof ArrayBuffer?P:P?P.buffer:new ArrayBuffer(0);return Promise.resolve(E.licenseResponseInterceptor(R,A))}return P}}})().then(f=>{if(this.controller!==i)return;const p=new r({enableWorker:!0,lowLatencyMode:!0,liveSyncDurationCount:3,liveMaxLatencyDurationCount:o?10:void 0,...f});this.hls=p,p.attachMedia(t),p.on(r.Events.MEDIA_ATTACHED,()=>{p.loadSource(e.src)}),p.on(r.Events.LEVEL_LOADED,(g,m)=>{if(this.controller!==i||this.hls!==p)return;this.hlsRetryCount=0,this.mediaRecoveryCount=0;const v=m.details;if(v){const y=v.live,b=v.partTarget!==void 0&&v.partTarget>0,S=v.partHoldBack!==void 0&&v.partHoldBack>0,T=v.fragments&&v.fragments.some(I=>I.parts&&I.parts.length>0),E=y&&(b||S||T),A=y?v.totalduration:0,P=y&&(v.type==="EVENT"||A>30);this._isLive=y,this._isLowLatency=E,this._dvrWindow=A,this._hasDvr=P;const $=i.getState(),M={};$.isLive!==y&&(M.isLive=y,y&&(M.isAtLiveEdge=!0)),$.isLowLatency!==E&&(M.isLowLatency=E),Object.keys(M).length>0&&i.updateStatePublic(M),i.dispatchEvent("live-status-change",{isLive:y,isLowLatency:E}),y?(i.updateLiveState(),this.startLivePolling()):this.stopLivePolling()}}),p.on(r.Events.MANIFEST_PARSED,()=>{i.dispatchEvent("manifestloaded",{system:"hls",levels:p.levels.length}),this.hlsRetryCount=0,this.mediaRecoveryCount=0;const g=p.levels.length>1,m=[];if(g){m.push("Auto");const y={};p.levels.forEach(b=>{const S=b.height?`${b.height}p`:"Unknown";y[S]=(y[S]||0)+1}),p.levels.forEach(b=>{const S=b.height?`${b.height}p`:"Unknown";y[S]>1&&b.bitrate?m.push(`${S} (${Math.round(b.bitrate/1e3)}k)`):m.push(S)})}const v=p.subtitleTracks.map(y=>({label:y.name||y.lang||"Unknown",language:y.lang||"",default:!!y.default,forced:!!y.forced,kind:y.type==="CLOSED-CAPTIONS"?"captions":"subtitles"}));i.setManagedSubtitleTracks("hls",v,p.subtitleTrack),i.updateStatePublic({qualities:m,activeQuality:g?"Auto":"",error:null}),this.syncAndDeduplicateTracks(),g&&this.syncQualityState()}),p.on(r.Events.SUBTITLE_TRACK_SWITCH,(g,m)=>{const v=p.subtitleTracks.map(y=>({label:y.name||y.lang||"Unknown",language:y.lang||"",default:!!y.default,forced:!!y.forced,kind:y.type==="CLOSED-CAPTIONS"?"captions":"subtitles"}));i.setManagedSubtitleTracks("hls",v,m.id)}),p.on(r.Events.SUBTITLE_TRACKS_UPDATED,()=>{const g=p.subtitleTracks.map(m=>({label:m.name||m.lang||"Unknown",language:m.lang||"",default:!!m.default,forced:!!m.forced,kind:m.type==="CLOSED-CAPTIONS"?"captions":"subtitles"}));i.setManagedSubtitleTracks("hls",g,p.subtitleTrack)}),p.on(r.Events.LEVEL_SWITCHED,(g,m)=>{this.lastLevelIndex=m.level,this.syncQualityState()}),p.on(r.Events.AUDIO_TRACKS_UPDATED,()=>{this.syncAndDeduplicateTracks()}),p.on(r.Events.AUDIO_TRACK_SWITCHED,(g,m)=>{const v=typeof m.id=="number"&&m.id>=0&&m.id<p.audioTracks.length?m.id:p.audioTrack;let y=-1;for(let b=0;b<this.uniqueAudioTracks.length;b++)if(this.uniqueAudioTracks[b].rawIndices.includes(v)){y=b;break}y!==-1&&i.updateStatePublic({activeAudioTrack:y})}),p.on(r.Events.FRAG_PARSING_METADATA,(g,m)=>{if(!this.controller)return;const v=m.samples||[];for(const y of v){const b=y.pts,S=y.type||"ID3";this.controller.emit("metadata",{timestamp:b,type:S,sourceProtocol:"hls",rawData:y.data,parsedData:y.info||{}})}}),p.on(r.Events.ERROR,(g,m)=>{var v,y,b;if(m.fatal){const S=(v=m.response)==null?void 0:v.code;switch(m.type){case r.ErrorTypes.KEY_SYSTEM_ERROR:console.error("Fatal HLS DRM key system error:",m),i.updateStatePublic({error:`DRM: Key system decryption error: ${m.details||"unknown"}`}),(y=this.drmManager)==null||y.triggerDrmError(m.details||"Key system decryption error","key-system",m),this.destroy();break;case r.ErrorTypes.NETWORK_ERROR:if(m.details==="keyLoadError"&&(S===401||S===403)){console.error(`[HlsHandler] Non-recoverable DRM key load error (HTTP ${S})`);const T="Media license acquisition request was denied.";i.updateStatePublic({error:T}),(b=this.drmManager)==null||b.triggerDrmError(T,"license",m),this.destroy();return}if(this.hlsRetryCount<3){this.hlsRetryCount++;const T=Math.pow(2,this.hlsRetryCount)*1e3;console.warn(`HLS Network error encountered (detail: ${m.details}, HTTP: ${S??"N/A"}). Retrying in ${T}ms (${this.hlsRetryCount}/3)...`),setTimeout(()=>{!this.hls||this.hls!==p||(m.details==="manifestLoadError"||m.details==="manifestLoadTimeOut"||m.details==="manifestParsingError"?p.loadSource(e.src):p.startLoad())},T)}else{console.error(`Fatal HLS Network error. Retries exhausted. Detail: ${m.details}, HTTP: ${S??"N/A"}`);let T;m.details==="manifestLoadError"?S===404?T="Stream not found (404). The URL may be expired, moved, or invalid.":S===403?T="Access denied (403). The stream may be geo-restricted or require authentication.":S!==void 0&&S>=500?T=`Stream server error (${S}). The server is temporarily unavailable.`:T=`Failed to load stream manifest${S?` (HTTP ${S})`:""}. Check the URL and try again.`:m.details==="manifestLoadTimeOut"?T="Stream connection timed out. The server may be slow or unreachable.":m.details==="manifestParsingError"?T="Invalid stream format. The URL does not point to a valid HLS stream.":T="Fatal streaming connection failure. Check the URL and try again.",i.updateStatePublic({error:T}),this.destroy()}break;case r.ErrorTypes.MEDIA_ERROR:this.mediaRecoveryCount++,this.mediaRecoveryCount===1?(console.warn(`HLS Media error. Stage 1 Recovery: recoverMediaError() (${this.mediaRecoveryCount}/3)`),p.recoverMediaError()):this.mediaRecoveryCount===2?(console.warn(`HLS Media error. Stage 2 Recovery: swapAudioCodec() + recoverMediaError() (${this.mediaRecoveryCount}/3)`),p.swapAudioCodec(),p.recoverMediaError()):this.mediaRecoveryCount===3?(console.warn(`HLS Media error. Stage 3 Recovery: detachMedia() + attachMedia() (${this.mediaRecoveryCount}/3)`),p.detachMedia(),p.attachMedia(this.video)):(console.error("Fatal HLS Media decode error. Stage 3 Recovery exhausted."),i.updateStatePublic({error:"Fatal media decoding failure."}),this.destroy());break;default:console.error("Fatal HLS error, destroying streaming instance:",m),i.updateStatePublic({error:"Fatal video stream initialization crash."}),this.destroy();break}}})}).catch(f=>{console.error("[HlsHandler] DRM setup failed:",f),i.updateStatePublic({error:"Fatal DRM initialization failure."})})}else if(t.canPlayType("application/vnd.apple.mpegurl")){const l={...((n=i.config)==null?void 0:n.drm)||{},...e.drm||{}};Object.keys(l).length>0&&(this.drmManager=new De,this.drmManager.load(t,l,i,!1)),t.src=e.src,t.load()}else i.updateStatePublic({error:"HLS streaming is not supported by your browser."})}).catch(s=>{console.error("Failed to load hls.js:",s),i.updateStatePublic({error:"Failed to load HLS library."})}))}syncAndDeduplicateTracks(){if(!this.hls||!this.controller)return;const e=this.hls.audioTracks||[],t={},i=[];for(let n=0;n<e.length;n++){const l=e[n],o=js(l.name,l.lang);t[o]||(t[o]={label:o,rawIndices:[]},i.push(o)),t[o].rawIndices.push(n)}this.uniqueAudioTracks=i.map(n=>({label:n,rawIndices:t[n].rawIndices}));const s=this.uniqueAudioTracks.map(n=>n.label),r=this.hls.audioTrack;let a=-1;for(let n=0;n<this.uniqueAudioTracks.length;n++)if(this.uniqueAudioTracks[n].rawIndices.includes(r)){a=n;break}this.controller.updateStatePublic({audioTracks:s,activeAudioTrack:a>=0?a:0})}syncQualityState(){if(!this.hls||!this.controller)return;const e=this.controller.getState().qualities;if(e.length===0)return;const t=this.isAutoMode;let i="Auto",s=-1;this.lastLevelIndex>=0&&this.lastLevelIndex<this.hls.levels.length?s=this.lastLevelIndex:this.hls.currentLevel>=0&&this.hls.currentLevel<this.hls.levels.length&&(s=this.hls.currentLevel),s>=0&&s<this.hls.levels.length&&(i=e[s+1]||"Unknown");const r=t?i!=="Auto"?`Auto (${i})`:"Auto":i;this.controller.updateStatePublic({activeQuality:r})}destroy(){this.stopLivePolling(),this.hls&&(this.hls.destroy(),this.hls=null),this.drmManager&&(this.drmManager.destroy(),this.drmManager=null),this.controller=null,this.video=null,this.lastLevelIndex=-1,this.isAutoMode=!0,this.uniqueAudioTracks=[]}setQuality(e){if(this.hls){this.isAutoMode=e===0;const t=e-1;this.hls.nextLevel=t,t===-1?this.lastLevelIndex=-1:this.lastLevelIndex=t,this.syncQualityState()}}setAudioTrack(e){if(this.hls&&this.uniqueAudioTracks&&e>=0&&e<this.uniqueAudioTracks.length){const i=this.uniqueAudioTracks[e].rawIndices[0];this.hls.audioTrack=i}}setSubtitleTrack(e){this.hls&&(this.hls.subtitleTrack=e)}getStats(){if(!this.hls)return{};const e={};this.hls.bandwidthEstimate!==void 0&&(e.bandwidthEstimate=this.hls.bandwidthEstimate);const t=this.hls.currentLevel;return t>=0&&this.hls.levels&&this.hls.levels[t]&&(e.bitrate=this.hls.levels[t].bitrate),e}}class Xs{constructor(){this.player=null,this.controller=null,this.video=null,this.lastQualityIndex=-1,this.isAutoMode=!0,this.videoRepresentations=[],this.uniqueAudioTracks=[],this.managesSubtitles=!0,this.dashRetryCount=0,this.eventNames={},this.drmManager=null,this.followingLive=!0,this.catchupEnabled=null,this.syncLiveCatchup=()=>{if(!(!this.player||!this.controller))try{if(!this.player.isDynamic())return;const e=this.controller.getState().liveMode==="live-only"||this.followingLive&&Vt(this.player);if(e===this.catchupEnabled)return;this.catchupEnabled=e,this.player.updateSettings({streaming:{liveCatchup:{enabled:e}}})}catch{}},this.handleResume=()=>{this.video&&this.recordViewerPosition(this.video.currentTime)},this.handleLiveEdgeSync=()=>{this.followingLive=!0,this.syncLiveCatchup()},this.handleTrackChangeRendered=e=>{if(!(!this.player||!this.controller)&&e.mediaType==="audio"){const t=this.player.getCurrentTrackFor("audio");if(t){let i=-1;for(let s=0;s<this.uniqueAudioTracks.length;s++)if(this.uniqueAudioTracks[s].rawTracks.some(a=>a===t||a.id===t.id||a.lang===t.lang&&a.index===t.index)){i=s;break}i!==-1&&this.controller.updateStatePublic({activeAudioTrack:i})}}},this.handleStreamInitialized=()=>{if(!this.player||!this.controller)return;this.dashRetryCount=0;const e=this.player.getRepresentationsByType?this.player.getRepresentationsByType("video"):[];this.videoRepresentations=e;const t=e.length>1,i=[];if(t){i.push("Auto");const o={};e.forEach(d=>{const h=d.bandwidth||d.bitrate||0,u=d.height?`${d.height}p`:`${Math.round(h/1e3)}kbps`;o[u]=(o[u]||0)+1}),e.forEach(d=>{const h=d.bandwidth||d.bitrate||0,u=d.height?`${d.height}p`:`${Math.round(h/1e3)}kbps`;o[u]>1&&h?i.push(`${u} (${Math.round(h/1e3)}k)`):i.push(u)})}const r=this.player.getTracksFor("text").map(o=>{const d=o,h=d.roles?d.roles.map(u=>typeof u=="string"?u:u.value||"").filter(Boolean):[];return{label:d.label||d.lang||"Unknown",language:d.lang||"",default:!!d.isDefault||!!d.default,forced:!1,kind:h.includes("caption")?"captions":"subtitles"}}),a=this.player.getCurrentTrackFor("text");this.controller.setManagedSubtitleTracks("dash",r,a&&a.index!==null?a.index:-1);const n=this.player.isDynamic(),l=n&&Vt(this.player);this.controller.updateStatePublic({qualities:i,activeQuality:t?"Auto":"",error:null,isLive:n,isLowLatency:l,...n?{isAtLiveEdge:!0}:{}}),this.controller.dispatchEvent("live-status-change",{isLive:n,isLowLatency:l}),n&&this.controller.updateLiveState(),this.syncAndDeduplicateTracks(),t&&this.syncQualityState()},this.handleQualityChangeRendered=e=>{if(this.player&&e.mediaType==="video"){if(this.isAutoMode)this.lastQualityIndex=-1;else{const t=this.resolveCurrentRepresentationIndex();if(t>=0)this.lastQualityIndex=t;else{const i=this.normalizeQualityIndex(e==null?void 0:e.newQuality);i>=0&&(this.lastQualityIndex=i)}}this.syncQualityState()}},this.handleTextTrackChanged=()=>{if(!this.player||!this.controller)return;const t=this.player.getTracksFor("text").map(s=>{const r=s,a=r.roles?r.roles.map(n=>typeof n=="string"?n:n.value||"").filter(Boolean):[];return{label:r.label||r.lang||"Unknown",language:r.lang||"",default:!!r.isDefault||!!r.default,forced:!1,kind:a.includes("caption")?"captions":"subtitles"}}),i=this.player.getCurrentTrackFor("text");this.controller.setManagedSubtitleTracks("dash",t,i&&i.index!==null?i.index:-1)},this.handleKeySystemSelected=e=>{},this.handleKeySessionCreated=e=>{const t=e.session;t&&this.drmManager&&this.drmManager.registerSession(t)},this.handleKeySessionClosed=e=>{const t=e.session;t&&this.drmManager&&this.drmManager.unregisterSession(t),this.controller&&t&&this.controller.dispatchEvent("drmsessionclosed",{session:t,system:"unknown"})},this.handleKeySessionRemoved=e=>{const t=e.session;t&&this.drmManager&&this.drmManager.unregisterSession(t),this.controller&&t&&this.controller.dispatchEvent("drmsessionclosed",{session:t,system:"unknown"})},this.handleKeyStatusesChanged=e=>{const t=e.session;this.controller&&t&&t.keyStatuses.forEach((i,s)=>{var r,a;i==="output-restricted"?(r=this.drmManager)==null||r.triggerDrmError("Playback restricted by HDCP output requirements.","certificate"):i==="expired"&&((a=this.drmManager)==null||a.triggerDrmError("Playback key has expired.","certificate"))})},this.handleKeyMessage=e=>{},this.handleProtectionError=e=>{console.error("[DashHandler] Protection Error:",e);const t=e.error,i=(typeof t=="object"?t==null?void 0:t.message:void 0)||(typeof t=="string"?t:void 0)||"Unknown protection error";let s="session";i.toLowerCase().includes("key system")||i.toLowerCase().includes("keysystem")?s="key-system":i.toLowerCase().includes("license")||i.toLowerCase().includes("request")?s="license":i.toLowerCase().includes("certificate")&&(s="certificate"),this.drmManager?this.drmManager.triggerDrmError(i,s,e):this.controller&&(this.controller.updateStatePublic({error:`DRM: ${i}`}),this.controller.dispatchEvent("error",{message:`DRM: ${i}`}),this.controller.dispatchEvent("drmerror",{message:`DRM: ${i}`,errorType:s,originalError:e}))},this.handleError=e=>{var l,o,d;if(!this.player||!this.controller||!this.video)return;console.error("Dash.js error:",e);const t=e.error,i=typeof t=="object"?t:void 0,s=(i==null?void 0:i.message)||(typeof t=="string"?t:"")||"",r=((o=(l=i==null?void 0:i.data)==null?void 0:l.response)==null?void 0:o.status)??((d=i==null?void 0:i.data)==null?void 0:d.status)??(i==null?void 0:i.status)??void 0,a=r===401||r===403,n=s.toLowerCase().includes("key system")||s.toLowerCase().includes("keysystem");if(a||n){console.error(`[DashHandler] Non-recoverable DASH DRM error: ${s} (HTTP: ${r??"N/A"})`);const h=a?"Media license acquisition request was denied.":"DRM key system is not supported by your browser.";this.controller.updateStatePublic({error:h}),this.controller.dispatchEvent("error",{message:h});return}if(this.dashRetryCount<3){this.dashRetryCount++;const h=this.video.currentTime,u=!this.video.paused,f=this.player.getSource(),p=Math.pow(2,this.dashRetryCount)*1e3;console.warn(`DASH error encountered. Retrying in ${p}ms (${this.dashRetryCount}/3) by re-attaching source...`),setTimeout(()=>{if(!(!this.player||!this.video))try{this.player.attachSource(f);const g=()=>{this.player&&(this.player.off(this.eventNames.streamInitialized||"streamInitialized",g),this.video&&(this.video.currentTime=h,u&&this.video.play().catch(m=>console.warn("Restore play failed:",m))))};this.player.on(this.eventNames.streamInitialized||"streamInitialized",g)}catch(g){console.error("Failed to attach source for recovery:",g)}},p)}else this.controller.updateStatePublic({error:`DASH streaming error: ${(i==null?void 0:i.message)||t||"unknown"}`})}}getDrmManager(){return this.drmManager}getRawLiveInfo(){var n,l,o,d,h,u,f;if(!this.player||!this.player.isDynamic())return null;const e=this.player.getSettings(),t=Vt(this.player),i=((l=(n=e==null?void 0:e.streaming)==null?void 0:n.delay)==null?void 0:l.liveDelay)||3;let s=null,r=0;if(this.video&&this.video.seekable.length>0){const p=this.video.seekable.start(0),g=this.video.seekable.end(this.video.seekable.length-1);s=Math.max(0,g-i),r=g-p}let a=!0;try{r<=15&&(a=!1);const p=(d=(o=this.player).getDashAdapter)==null?void 0:d.call(o),g=((h=p==null?void 0:p.getMpd)==null?void 0:h.call(p))||((f=(u=this.player).getMpd)==null?void 0:f.call(u));g&&g.timeShiftBufferDepth!==void 0&&(a=g.timeShiftBufferDepth>10)}catch{a=r>10}return{isLive:!0,isLowLatency:t,hasDvr:a,dvrWindow:r,liveEdgeTarget:s}}seekToLiveEdge(){var e,t;if(this.player&&typeof this.player.seekToOriginalLive=="function")this.player.seekToOriginalLive();else if(this.player&&this.player.isDynamic())if(this.video&&this.video.seekable.length>0){const i=this.video.seekable.end(this.video.seekable.length-1),s=this.player.getSettings(),r=((t=(e=s==null?void 0:s.streaming)==null?void 0:e.delay)==null?void 0:t.liveDelay)||3;this.player.seek(Math.max(0,i-r))}else Number.isFinite(this.player.duration())&&this.player.seek(this.player.duration())}recordViewerPosition(e){var t;if(this.player)try{if(!this.player.isDynamic())return;const i=(t=this.getRawLiveInfo())==null?void 0:t.liveEdgeTarget;if(i==null||e<=0)return;this.followingLive=i-e<=Ws,this.syncLiveCatchup()}catch{}}normalizeQualityIndex(e){return typeof e=="number"&&Number.isInteger(e)&&e>=0?e:-1}resolveCurrentRepresentationIndex(){if(!this.player||this.videoRepresentations.length===0)return-1;const e=this.player.getCurrentRepresentationForType("video");return e?this.videoRepresentations.findIndex(t=>t.id===e.id):-1}bufferToHex(e){const t=new DataView(e);let i="";for(let s=0;s<t.byteLength;s++){const r=t.getUint8(s);i+=r.toString(16).padStart(2,"0")}return i}load(e,t,i){e.src&&(this.destroy(),this.controller=i,this.video=t,this.lastQualityIndex=-1,this.isAutoMode=!0,this.videoRepresentations=[],this.uniqueAudioTracks=[],this.dashRetryCount=0,this.followingLive=!0,this.catchupEnabled=null,t.addEventListener("play",this.handleResume),t.addEventListener("timeupdate",this.syncLiveCatchup),i.addEventListener("live-edge-sync",this.handleLiveEdgeSync),$i().then(s=>{var p;if(this.controller!==i)return;const r=s,a=r.MediaPlayer().create();this.player=a,a.on(r.MediaPlayer.events.MANIFEST_LOADED,g=>{const m=g.data;i.dispatchEvent("manifestloaded",{system:"dash",data:m!=null&&m.url?{url:m.url}:{}})});const l=i.getState().liveMode==="live-only",o={...((p=i.config)==null?void 0:p.drm)||{},...e.drm||{}},d=Object.keys(o).length>0;d&&(this.drmManager=new De,this.drmManager.load(t,o,i,!0));const h={},u={};o.persistentState&&(u.persistentState=o.persistentState),o.distinctiveIdentifier&&(u.distinctiveIdentifier=o.distinctiveIdentifier),a.updateSettings({streaming:{buffer:{fastSwitchEnabled:!0},liveCatchup:{enabled:l},...Object.keys(u).length>0?{protection:u}:{}}}),(async()=>{var g,m,v,y;if(d){if(o.widevine){const b=o.widevine,S=this.drmManager?await this.drmManager.loadCertificate(b):null;h["com.widevine.alpha"]={serverURL:b.licenseUrl,httpRequestHeaders:b.headers,withCredentials:!!b.withCredentials,...S?{serverCertificate:S}:{},...(g=o.robustness)!=null&&g.video?{videoRobustness:o.robustness.video}:{},...(m=o.robustness)!=null&&m.audio?{audioRobustness:o.robustness.audio}:{}}}if(o.playready){const b=o.playready,S=this.drmManager?await this.drmManager.loadCertificate(b):null;h["com.microsoft.playready"]={serverURL:b.licenseUrl,httpRequestHeaders:b.headers,withCredentials:!!b.withCredentials,...S?{serverCertificate:S}:{},...(v=o.robustness)!=null&&v.video?{videoRobustness:o.robustness.video}:{},...(y=o.robustness)!=null&&y.audio?{audioRobustness:o.robustness.audio}:{}}}if(o.clearkey){const b=o.clearkey,S=Ot(b.clearkeys);h["org.w3.clearkey"]={serverURL:b.licenseUrl,httpRequestHeaders:b.headers,withCredentials:!!b.withCredentials,...Object.keys(S).length>0?{clearkeys:S}:{}}}}})().then(()=>{if(this.controller!==i||!this.player)return;if(Object.keys(h).length>0&&this.player.setProtectionData(h),d){const N=C=>{var q,de;let x=null,H="";const te=C.url||"",V=te.toLowerCase();o.widevine&&o.widevine.licenseUrl&&V.includes(o.widevine.licenseUrl.toLowerCase())?(x=o.widevine,H="widevine"):o.playready&&o.playready.licenseUrl&&V.includes(o.playready.licenseUrl.toLowerCase())?(x=o.playready,H="playready"):o.clearkey&&o.clearkey.licenseUrl&&V.includes(o.clearkey.licenseUrl.toLowerCase())&&(x=o.clearkey,H="clearkey");const F=C.data&&(C.data.byteLength||C.data.length)||0;if((q=this.controller)==null||q.dispatchEvent("drmlicenserequest",{url:te,challengeSize:F,system:H||"dash"}),(de=this.drmManager)==null||de.noteLicenseRequest(H||"dash",te),!x||!x.licenseRequestInterceptor)return Promise.resolve();const L=C.data,D=L instanceof Uint8Array?L.buffer:L;return Promise.resolve(x.licenseRequestInterceptor(D,H)).then(le=>{le instanceof ArrayBuffer?C.data=le:le&&typeof le=="object"&&(le.body&&(C.data=le.body),le.headers&&(C.headers={...C.headers,...le.headers}))})},U=C=>{var q,de;let x=null,H="";const te=C.url||"",V=te.toLowerCase();o.widevine&&o.widevine.licenseUrl&&V.includes(o.widevine.licenseUrl.toLowerCase())?(x=o.widevine,H="widevine"):o.playready&&o.playready.licenseUrl&&V.includes(o.playready.licenseUrl.toLowerCase())?(x=o.playready,H="playready"):o.clearkey&&o.clearkey.licenseUrl&&V.includes(o.clearkey.licenseUrl.toLowerCase())&&(x=o.clearkey,H="clearkey");const F=C.data&&(C.data.byteLength||C.data.length)||0;if((q=this.controller)==null||q.dispatchEvent("drmlicenseresponse",{url:te,responseSize:F,system:H||"dash"}),(de=this.drmManager)==null||de.noteLicenseResponse(H||"dash",te),!x||!x.licenseResponseInterceptor)return Promise.resolve();const L=C.data,D=L instanceof Uint8Array?L.buffer:L;return Promise.resolve(x.licenseResponseInterceptor(D,H)).then(le=>{le instanceof ArrayBuffer&&(C.data=le)})};this.player.registerLicenseRequestFilter(N),this.player.registerLicenseResponseFilter(U)}this.player.initialize(t,e.src,t.autoplay);const g=r.MediaPlayer&&r.MediaPlayer.events||{},m=g.STREAM_INITIALIZED||"streamInitialized",v=g.QUALITY_CHANGE_RENDERED||"qualityChangeRendered",y=g.TEXT_TRACK_CHANGED||"textTrackChanged",b=g.ERROR||"error",S=g.TRACK_CHANGE_RENDERED||"trackChangeRendered",T=g.EVENT_MODE_ON_RECEIVE||"eventModeOnReceive",E=g.KEY_SYSTEM_SELECTED||"keySystemSelected",A=g.KEY_SESSION_CREATED||"keySessionCreated",P=g.KEY_SESSION_CLOSED||"keySessionClosed",$=g.KEY_SESSION_REMOVED||"keySessionRemoved",M=g.KEY_STATUSES_CHANGED||"keyStatusesChanged",I=g.KEY_MESSAGE||"keyMessage",R=g.PROTECTION_ERROR||"protectionError";this.eventNames={streamInitialized:m,qualityChangeRendered:v,textTrackChanged:y,error:b,trackChangeRendered:S,eventModeOnReceive:T,keySystemSelected:E,keySessionCreated:A,keySessionClosed:P,keySessionRemoved:$,keyStatusesChanged:M,keyMessage:I,protectionError:R},a.on(S,this.handleTrackChangeRendered),a.on(m,this.handleStreamInitialized),a.on(v,this.handleQualityChangeRendered),a.on(y,this.handleTextTrackChanged),a.on(b,this.handleError),a.on(E,this.handleKeySystemSelected),a.on(A,this.handleKeySessionCreated),a.on(P,this.handleKeySessionClosed),a.on($,this.handleKeySessionRemoved),a.on(M,this.handleKeyStatusesChanged),a.on(I,this.handleKeyMessage),a.on(R,this.handleProtectionError),a.on(T,N=>{if(!i)return;const U=N.event;U&&i.emit("metadata",{timestamp:U.presentationTime||0,type:U.schemeIdUri||"emsg",sourceProtocol:"dash",rawData:U.messageData||new Uint8Array,parsedData:{schemeIdUri:U.schemeIdUri,value:U.value,timescale:U.timescale,presentationTime:U.presentationTime,duration:U.duration,id:U.id}})})}).catch(g=>{console.error("[DashHandler] Dynamic DRM setup failed:",g),this.handleProtectionError(g)})}).catch(s=>{console.error("Failed to load dashjs:",s),i.updateStatePublic({error:"Failed to load DASH library."})}))}syncAndDeduplicateTracks(){var n,l,o;if(!this.player||!this.controller)return;const e=this.player.getTracksFor("audio")||[],t={},i=[];for(let d=0;d<e.length;d++){const h=e[d],u=h.lang||"";let f="";h.labels&&Array.isArray(h.labels)&&h.labels.length>0&&((n=h.labels[0])!=null&&n.text)?f=h.labels[0].text:"label"in h&&typeof h.label=="string"&&(f=h.label);const p=h.roles?h.roles.map(E=>typeof E=="string"?E:E.value||"").filter(Boolean):[],g=p.map(E=>E.trim().toLowerCase()).filter(E=>E!=="main"&&E!=="alternate"&&E!==""),m=((o=(l=h.audioChannelConfiguration)==null?void 0:l[0])==null?void 0:o.value)||h.channels||"",v=u.toLowerCase(),y=f.toLowerCase(),b=g.sort().join(","),S=m?String(m):"",T=`${v}|${y}|${b}|${S}`;t[T]||(t[T]={lang:u,label:f||void 0,roles:p,channels:m||void 0,rawTracks:[]},i.push(T)),t[T].rawTracks.push(h)}this.uniqueAudioTracks=i.map(d=>{const h=t[d],u=mt(h.lang);let f="";h.label&&(/^[a-zA-Z]{2,3}(-[a-zA-Z]{2,4})?$/.test(h.label.trim())||(f=h.label.trim()));const p=[f||u||"Unknown"],g=h.roles.map(v=>v.trim().toLowerCase()).filter(v=>v!=="main"&&v!=="alternate"&&v!=="");if(g.length>0&&p.push(g.map(v=>v.charAt(0).toUpperCase()+v.slice(1)).join(", ")),h.channels){const v=parseInt(String(h.channels),10);v===2?p.push("Stereo"):v===6||v===5.1?p.push("5.1"):v>0&&p.push(`${v}ch`)}return{label:p.join(" "),rawTracks:h.rawTracks}});const s=this.uniqueAudioTracks.map(d=>d.label),r=this.player.getCurrentTrackFor("audio");let a=-1;if(r){for(let d=0;d<this.uniqueAudioTracks.length;d++)if(this.uniqueAudioTracks[d].rawTracks.some(u=>u===r||u.id===r.id||u.lang===r.lang&&u.index===r.index)){a=d;break}}a===-1&&this.uniqueAudioTracks.length>0&&(a=0),this.controller.updateStatePublic({audioTracks:s,activeAudioTrack:a})}syncQualityState(){if(!this.player||!this.controller)return;const e=this.controller.getState().qualities;if(e.length===0)return;const t=this.isAutoMode;let i="Auto",s=this.normalizeQualityIndex(this.lastQualityIndex);s===-1&&(s=this.resolveCurrentRepresentationIndex()),s>=0&&s<e.length-1&&(i=e[s+1]||"Unknown");const r=t?i!=="Auto"?`Auto (${i})`:"Auto":i;this.controller.updateStatePublic({activeQuality:r})}destroy(){var e;if(this.video&&(this.video.removeEventListener("play",this.handleResume),this.video.removeEventListener("timeupdate",this.syncLiveCatchup)),(e=this.controller)==null||e.removeEventListener("live-edge-sync",this.handleLiveEdgeSync),this.player){try{this.eventNames.trackChangeRendered&&this.player.off(this.eventNames.trackChangeRendered,this.handleTrackChangeRendered),this.eventNames.streamInitialized&&this.player.off(this.eventNames.streamInitialized,this.handleStreamInitialized),this.eventNames.qualityChangeRendered&&this.player.off(this.eventNames.qualityChangeRendered,this.handleQualityChangeRendered),this.eventNames.textTrackChanged&&this.player.off(this.eventNames.textTrackChanged,this.handleTextTrackChanged),this.eventNames.error&&this.player.off(this.eventNames.error,this.handleError),this.eventNames.keySystemSelected&&this.player.off(this.eventNames.keySystemSelected,this.handleKeySystemSelected),this.eventNames.keySessionCreated&&this.player.off(this.eventNames.keySessionCreated,this.handleKeySessionCreated),this.eventNames.keySessionClosed&&this.player.off(this.eventNames.keySessionClosed,this.handleKeySessionClosed),this.eventNames.keySessionRemoved&&this.player.off(this.eventNames.keySessionRemoved,this.handleKeySessionRemoved),this.eventNames.keyStatusesChanged&&this.player.off(this.eventNames.keyStatusesChanged,this.handleKeyStatusesChanged),this.eventNames.keyMessage&&this.player.off(this.eventNames.keyMessage,this.handleKeyMessage),this.eventNames.protectionError&&this.player.off(this.eventNames.protectionError,this.handleProtectionError)}catch(t){console.warn("[DashHandler] Error unbinding event listeners:",t)}this.player.destroy(),this.player=null}this.drmManager&&(this.drmManager.destroy(),this.drmManager=null),this.controller=null,this.video=null,this.lastQualityIndex=-1,this.isAutoMode=!0,this.videoRepresentations=[],this.uniqueAudioTracks=[]}seek(e){if(this.recordViewerPosition(e),!this.player)return!1;try{return this.player.isDynamic()?(this.player.seekToPresentationTime(e),!0):!1}catch{return!1}}setQuality(e){if(this.player){this.isAutoMode=e===0;const t=e-1,i=this.player;if(t===-1)i.setAutoSwitchQualityFor?i.setAutoSwitchQualityFor("video",!0):this.player.updateSettings({streaming:{abr:{autoSwitchBitrate:{video:!0}}}}),this.lastQualityIndex=-1;else if(i.setAutoSwitchQualityFor?i.setAutoSwitchQualityFor("video",!1):this.player.updateSettings({streaming:{abr:{autoSwitchBitrate:{video:!1}}}}),t>=0&&t<this.videoRepresentations.length){const s=this.videoRepresentations[t];i.setRepresentationForTypeById?i.setRepresentationForTypeById("video",s.id):i.setQualityFor&&i.setQualityFor("video",t,!1),this.lastQualityIndex=t}this.syncQualityState()}}setAudioTrack(e){if(this.player&&this.uniqueAudioTracks&&e>=0&&e<this.uniqueAudioTracks.length){const t=this.uniqueAudioTracks[e],i=this.player.getCurrentTrackFor("audio"),s=t.rawTracks.find(r=>i&&(r.mimeType===i.mimeType||r.codec===i.codec))||t.rawTracks[0];s&&this.player.setCurrentTrack(s)}}setSubtitleTrack(e){if(this.player){const t=this.player.getTracksFor("text");e===-1?this.player.setTextTrack(-1):e>=0&&e<t.length&&this.player.setTextTrack(e)}}getStats(){var t,i,s;if(!this.player)return{};const e={};try{const r=this.player,a=((t=r.getAverageThroughput)==null?void 0:t.call(r,"video"))??0;a>0&&(e.bandwidthEstimate=a*1e3);const n=(i=r.getQualityFor)==null?void 0:i.call(r,"video"),l=(s=r.getBitrateInfoListFor)==null?void 0:s.call(r,"video");l&&n!==void 0&&l[n]&&(e.bitrate=l[n].bitrate)}catch{}return e}}class Ys{constructor(){this.iframe=null,this.video=null,this.controller=null}load(e,t,i){this.destroy(),this.video=t,this.controller=i;const s=e.src||"";if(!s)return;const r=s;t.style.display="none",t.pause();const a=document.createElement("iframe");a.src=r,a.style.position="absolute",a.style.top="0",a.style.left="0",a.style.width="100%",a.style.height="100%",a.style.border="none",a.style.zIndex="10",a.allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share",a.allowFullscreen=!0,this.iframe=a,t.parentNode&&t.parentNode.appendChild(a),i.updateStatePublic({qualities:[],activeQuality:"",audioTracks:[],activeAudioTrack:-1,error:null,status:"playing",isPlaying:!0})}destroy(){this.iframe&&(this.iframe.parentNode&&this.iframe.parentNode.removeChild(this.iframe),this.iframe=null),this.video&&(this.video.style.display="",this.video=null),this.controller=null}}class Zs{constructor(){this.activeHandler=null}getActiveHandler(){return this.activeHandler}getHandler(e){switch(e){case"hls":return new Qs;case"dash":return new Xs;case"embed":return new Ys;case"mp4":case"mov":case"webm":case"file":case"blob":default:return new Gs}}load(e,t,i){this.destroy();const s=e.type||"unknown";this.activeHandler=this.getHandler(s),this.activeHandler.load(e,t,i)}destroy(){this.activeHandler&&(this.activeHandler.destroy(),this.activeHandler=null)}setQuality(e){this.activeHandler&&this.activeHandler.setQuality&&this.activeHandler.setQuality(e)}setAudioTrack(e){this.activeHandler&&this.activeHandler.setAudioTrack&&this.activeHandler.setAudioTrack(e)}setSubtitleTrack(e){this.activeHandler&&this.activeHandler.setSubtitleTrack&&this.activeHandler.setSubtitleTrack(e)}seekToLiveEdge(){return this.activeHandler&&this.activeHandler.seekToLiveEdge?(this.activeHandler.seekToLiveEdge(),!0):!1}getRawLiveInfo(){return this.activeHandler&&this.activeHandler.getRawLiveInfo?this.activeHandler.getRawLiveInfo():null}}class Ni{constructor(e){var i;this.bindings=[],this.actions=new Map,this.hooks=new Set,this.enabled=!0,this.controller=e,this.registerDefaultActions(),this.registerDefaultBindings();const t=(i=this.controller.config)==null?void 0:i.hotkeys;if(t&&typeof t=="object"&&(t.bindings&&this.setMap(t.bindings),t.overrides))for(const s of t.overrides)this.bind(s)}enable(){this.enabled=!0}disable(){this.enabled=!1}isEnabled(){return this.enabled}registerAction(e,t){this.actions.set(e,t)}unregisterAction(e){this.actions.delete(e)}bind(e){this.unbind(e.key,e.shiftKey,e.ctrlKey,e.altKey),this.bindings.push({...e,key:e.key.toLowerCase()})}unbind(e,t=!1,i=!1,s=!1){const r=e.toLowerCase();this.bindings=this.bindings.filter(a=>!(a.key===r&&!!a.shiftKey===t&&!!a.ctrlKey===i&&!!a.altKey===s))}setMap(e){this.bindings=e.map(t=>({...t,key:t.key.toLowerCase()}))}onAction(e){return this.hooks.add(e),()=>this.hooks.delete(e)}handleKeyDown(e){var l,o;if(!this.enabled)return;const t=(l=this.controller.config)==null?void 0:l.hotkeys;if(t===!1||t&&typeof t=="object"&&t.enabled===!1)return;const i=e.key.toLowerCase(),s=e.shiftKey,r=e.ctrlKey,a=e.altKey,n=this.bindings.find(d=>{if(d.key===i){const h=(d.shiftKey||!1)===s,u=(d.ctrlKey||!1)===r,f=(d.altKey||!1)===a;return h&&u&&f}return!1});if(n){if(this.controller.getState().isAdPlaying&&!["playPause","muteToggle","volumeUp","volumeDown","fullscreenToggle"].includes(n.action))return;const d=(o=this.controller.config)==null?void 0:o.controls;if(d&&(n.action==="playPause"&&(d.play===!1||d.playButton===!1)||(n.action==="volumeUp"||n.action==="volumeDown"||n.action==="muteToggle")&&(d.volume===!1||d.mute===!1)||(n.action==="seekBackward10"||n.action==="seekForward10"||n.action==="seekStart"||n.action==="seekEnd"||n.action==="frameBackward"||n.action==="frameForward"||n.action==="seekPercent")&&d.seekbar===!1||n.action==="fullscreenToggle"&&d.fullscreen===!1||n.action==="pipToggle"&&(d.pip===!1||d.pictureInPicture===!1)||(n.action==="speedIncrease"||n.action==="speedDecrease")&&d.playbackSpeed===!1||(n.action==="nextChapter"||n.action==="prevChapter")&&d.chapters===!1))return;const h=this.actions.get(n.action);h&&(e.preventDefault(),e.stopPropagation(),h(this.controller,e,{key:e.key}))}}dispatchHook(e,t){this.hooks.forEach(i=>i(e,t))}registerDefaultActions(){this.registerAction("playPause",e=>{e.togglePlay()}),this.registerAction("seekBackward10",e=>{const t=e.getState();t.isLive&&!t.canSeekInDvr||(e.seekBy(-10),this.dispatchHook("seek",{seconds:-10}))}),this.registerAction("seekForward10",e=>{const t=e.getState();t.isLive&&!t.canSeekInDvr||(e.seekBy(10),this.dispatchHook("seek",{seconds:10}))}),this.registerAction("volumeUp",e=>{const t=e.getState().volume,i=Math.min(1,t+.1);e.setVolume(i),this.dispatchHook("volume",{volume:i,isMuted:e.getState().isMuted})}),this.registerAction("volumeDown",e=>{const t=e.getState().volume,i=Math.max(0,t-.1);e.setVolume(i),this.dispatchHook("volume",{volume:i,isMuted:e.getState().isMuted})}),this.registerAction("muteToggle",e=>{e.toggleMute(),this.dispatchHook("volume",{volume:e.getState().volume,isMuted:e.getState().isMuted})}),this.registerAction("fullscreenToggle",e=>{this.dispatchHook("fullscreen")}),this.registerAction("pipToggle",e=>{e.togglePictureInPicture()}),this.registerAction("loopToggle",e=>{e.toggleLoop()}),this.registerAction("nextChapter",e=>{e.nextChapter()}),this.registerAction("prevChapter",e=>{e.prevChapter()}),this.registerAction("seekStart",e=>{const t=e.getState();if(t.isLive&&!t.canSeekInDvr)return;const i=t.currentTime;e.seek(0),this.dispatchHook("seek",{seconds:-i})}),this.registerAction("seekEnd",e=>{const t=e.getState();if(t.isLive&&!t.canSeekInDvr)return;const i=t.currentTime,s=t.duration;e.seek(s),this.dispatchHook("seek",{seconds:s-i})}),this.registerAction("seekPercent",(e,t,i)=>{var r,a;const s=i==null?void 0:i.key;if(s&&s>="0"&&s<="9"){const n=parseInt(s,10)/10,l=e.getState();if(l.isLive&&!l.canSeekInDvr)return;let o=0;if(l.isLive){const h=((r=l.seekableRange)==null?void 0:r.start)??0,u=((a=l.seekableRange)==null?void 0:a.end)??0;o=h+(u-h)*n}else o=(l.duration||0)*n;const d=l.currentTime;e.seek(o),this.dispatchHook("seek",{seconds:o-d})}}),this.registerAction("frameBackward",e=>{if(!e.isKeyboardPrecisionEnabled())return;const t=e.getState();if(t.isLive&&!t.canSeekInDvr)return;const i=t.currentTime,s=Math.max(0,i-.04);e.seek(s),this.dispatchHook("seek",{seconds:s-i})}),this.registerAction("frameForward",e=>{if(!e.isKeyboardPrecisionEnabled())return;const t=e.getState();if(t.isLive&&!t.canSeekInDvr)return;const i=t.currentTime,s=t.duration||0,r=Math.min(s,i+.04);e.seek(r),this.dispatchHook("seek",{seconds:r-i})}),this.registerAction("speedIncrease",e=>{const t=[.25,.5,.75,1,1.25,1.5,1.75,2,2.5,3,4],i=e.getState().playbackRate,s=t.indexOf(i);s!==-1&&s<t.length-1&&e.setPlaybackRate(t[s+1])}),this.registerAction("speedDecrease",e=>{const t=[.25,.5,.75,1,1.25,1.5,1.75,2,2.5,3,4],i=e.getState().playbackRate,s=t.indexOf(i);s!==-1&&s>0&&e.setPlaybackRate(t[s-1])})}registerDefaultBindings(){this.bind({key:" ",action:"playPause"}),this.bind({key:"k",action:"playPause"}),this.bind({key:"arrowleft",action:"seekBackward10"}),this.bind({key:"arrowright",action:"seekForward10"}),this.bind({key:"j",action:"seekBackward10"}),this.bind({key:"l",action:"seekForward10"}),this.bind({key:"arrowup",action:"volumeUp"}),this.bind({key:"arrowdown",action:"volumeDown"}),this.bind({key:"m",action:"muteToggle"}),this.bind({key:"f",action:"fullscreenToggle"}),this.bind({key:"p",action:"pipToggle"}),this.bind({key:"r",action:"loopToggle"}),this.bind({key:"arrowright",action:"nextChapter",ctrlKey:!0}),this.bind({key:"arrowleft",action:"prevChapter",ctrlKey:!0}),this.bind({key:"home",action:"seekStart"}),this.bind({key:"end",action:"seekEnd"}),this.bind({key:",",action:"frameBackward"}),this.bind({key:".",action:"frameForward"}),this.bind({key:">",action:"speedIncrease",shiftKey:!0}),this.bind({key:"<",action:"speedDecrease",shiftKey:!0});for(let e=0;e<=9;e++)this.bind({key:e.toString(),action:"seekPercent"})}destroy(){this.bindings=[],this.actions.clear(),this.hooks.clear()}}var zt=(c=>(c[c.HANDSHAKE_TIMEOUT=1001]="HANDSHAKE_TIMEOUT",c[c.CREATIVE_LOAD_FAILURE=1002]="CREATIVE_LOAD_FAILURE",c[c.SECURITY_VIOLATION=1003]="SECURITY_VIOLATION",c[c.INVALID_PAYLOAD=1004]="INVALID_PAYLOAD",c[c.CREATIVE_FATAL_ERROR=1005]="CREATIVE_FATAL_ERROR",c[c.RUNTIME_ERROR=1006]="RUNTIME_ERROR",c))(zt||{});class Vi{constructor(e){this.config=e,this.pendingRequests=new Map,this.messageListeners=new Set,this.globalListener=null,this.targetWindow=null,this.sessionId=null,this.messageCounter=0,this.creativeOrigin=null,this.allowedOrigins=new Set(e.allowedOrigins||["*"]),this.debugLogging=e.debug!==!1}init(e,t,i){this.targetWindow=e,this.sessionId=t,this.creativeOrigin=i||null,this.setupGlobalListener()}updateSessionId(e){this.sessionId=e}postMessage(e,t,i){if(!this.targetWindow||!this.sessionId)throw new Error("SIMID Bridge is not initialized or has been destroyed");const s=String(++this.messageCounter),r={sessionId:this.sessionId,messageId:s,timestamp:Date.now(),type:e,args:t};i!==void 0&&(r.correlationId=i);const a=this.allowedOrigins.has("*")||this.allowedOrigins.has("null")?"*":this.creativeOrigin&&this.allowedOrigins.has(this.creativeOrigin)?this.creativeOrigin:Array.from(this.allowedOrigins)[0];return this.debugLogging&&console.log("[SIMID Protocol] 📤 Player -> Creative:",{timestamp:new Date().toISOString(),type:e,messageId:s,correlationId:i,sessionId:this.sessionId,payload:r}),this.targetWindow.postMessage(JSON.stringify(r),a),s}postResolve(e,t={}){const s={messageId:typeof e=="string"&&parseInt(e,10)||e,value:t||{}};return this.postMessage("resolve",s,String(e))}postReject(e,t={}){const s={messageId:typeof e=="string"&&parseInt(e,10)||e,value:t||{}};return this.postMessage("reject",s,String(e))}async sendRequest(e,t,i=5e3){if(!this.targetWindow||!this.sessionId)throw new Error("SIMID Bridge is not initialized or has been destroyed");return new Promise((s,r)=>{const a=this.postMessage(e,t),n=setTimeout(()=>{this.pendingRequests.delete(a),r(new Error(`SIMID request timeout for messageId ${a} (${e})`))},i);this.pendingRequests.set(a,{resolve:s,reject:r,timeoutId:n})})}addMessageListener(e){this.messageListeners.add(e)}removeMessageListener(e){this.messageListeners.delete(e)}setupGlobalListener(){typeof window>"u"||(this.globalListener=e=>{var o,d;if(this.targetWindow&&e.source)try{if(e.source!==this.targetWindow&&this.targetWindow.self!==e.source)return}catch{}if(!this.allowedOrigins.has("*")&&!this.allowedOrigins.has(e.origin))return;let t=e.data;if(typeof t=="string")try{t=JSON.parse(t)}catch{return}if(!t||typeof t!="object"||!t.type)return;const i=t,s=String(i.type),r=s.replace(/^simid:(creative|player|media):/i,"").replace(/^simid:/i,"").toLowerCase(),a=r==="createsession"||r==="creativeready"||r==="creativeloaded"||r==="startcreative"||r==="handshake",n=i.sessionId||((o=i.args)==null?void 0:o.sessionId)||((d=i.data)==null?void 0:d.sessionId)||this.sessionId;if(!a&&this.sessionId&&n!==this.sessionId)return;const l={sessionId:String(n||this.sessionId||""),messageId:String(i.messageId||Math.random().toString(36).substring(2,11)),correlationId:i.correlationId!==void 0?String(i.correlationId):void 0,type:s,data:i.data||i.args||i};if(this.debugLogging&&console.log("[SIMID Protocol] 📥 Creative -> Player:",{timestamp:new Date().toISOString(),type:s,normalizedType:r,messageId:l.messageId,correlationId:l.correlationId,sessionId:l.sessionId,payload:i}),l.correlationId){const h=this.pendingRequests.get(l.correlationId);h&&(clearTimeout(h.timeoutId),this.pendingRequests.delete(l.correlationId),h.resolve(l))}this.messageListeners.forEach(h=>{try{h(l)}catch(u){console.error("[SIMID Bridge] Error in message listener:",u)}})},window.addEventListener("message",this.globalListener))}destroy(){typeof window<"u"&&this.globalListener&&window.removeEventListener("message",this.globalListener),this.globalListener=null,this.pendingRequests.forEach((e,t)=>{clearTimeout(e.timeoutId),e.reject(new Error(`SIMID Bridge destroyed for pending message ${t}`))}),this.pendingRequests.clear(),this.messageListeners.clear(),this.targetWindow=null,this.sessionId=null}}class vt{constructor(e,t,i){this.creative=e,this.config=t,this.onStateChange=i,this.state="idle",this.handshakeTimer=null,this.creativeTimer=null,this.errors=[],this.initMessageId=null,this.sessionId=Math.random().toString(36).substring(2,15),this.config=vt.resolveEffectiveConfig(e,t),this.bridge=new Vi(this.config)}static resolveEffectiveConfig(e,t){if(t.allowedOrigins)return t;if(Ii(e.interactiveCreativeFile))return{...t,allowedOrigins:["null"]};try{const i=new URL(e.interactiveCreativeFile,window.location.href).origin;return{...t,allowedOrigins:[i]}}catch(i){return console.warn("[SimidSession] Could not resolve creative origin for allowedOrigins default; falling back to wildcard.",i),{...t,allowedOrigins:["*"]}}}getSessionState(){return this.state}getBridge(){return this.bridge}getErrors(){return this.errors}init(e,t){if(this.state!=="idle")throw new Error(`Cannot initialize SIMID session in state: ${this.state}`);this.transitionTo("available"),this.bridge.init(e,this.sessionId,t),this.bridge.addMessageListener(this.handleIncomingMessage.bind(this))}start(){if(this.state!=="available")throw new Error(`Cannot start SIMID session in state: ${this.state}`);this.transitionTo("loading");const e=this.config.handshakeTimeoutMs||8e3;this.handshakeTimer=setTimeout(()=>{this.handleError(zt.HANDSHAKE_TIMEOUT,"Handshake timeout expired",!0)},e)}complete(){this.state==="destroyed"||this.state==="completed"||(this.transitionTo("completed"),this.cleanupTimers())}destroy(){this.state!=="destroyed"&&(this.transitionTo("destroyed"),this.cleanupTimers(),this.bridge.destroy())}transitionTo(e){if(this.state=e,this.onStateChange)try{this.onStateChange(e,this)}catch(t){console.error("[SIMID Session] Error in state change handler:",t)}}setInitMessageId(e){this.initMessageId=e}handleIncomingMessage(e){if(this.state==="destroyed"||this.state==="completed")return;const i=String(e.type||"").replace(/^simid:(creative|player|media):/i,"").replace(/^simid:/i,"").toLowerCase(),s=e.data,r=e.args;if((i==="createsession"||i==="handshake")&&(this.state==="loading"||this.state==="available")){this.clearHandshakeTimer();const o=e.sessionId||(s==null?void 0:s.sessionId)||(r==null?void 0:r.sessionId);o&&o!==this.sessionId&&(this.sessionId=String(o),this.bridge.updateSessionId(String(o)));try{const d=e.messageId;d!=null&&this.bridge.postResolve(d,{})}catch{}this.transitionTo("initialized");return}if(i==="resolve"&&this.state==="initialized"){const o=(r==null?void 0:r.messageId)??e.correlationId;(!o||String(o)===String(this.initMessageId)||this.initMessageId===null)&&this.transitionTo("running");return}(i==="creativeready"||i==="creativeloaded")&&(this.state==="loading"||this.state==="available")&&(this.clearHandshakeTimer(),this.transitionTo("initialized"))}handleError(e,t,i){const s={code:e,message:t,fatal:i};this.errors.push(s),i&&this.destroy()}cleanupTimers(){this.clearHandshakeTimer(),this.creativeTimer&&(clearTimeout(this.creativeTimer),this.creativeTimer=null)}clearHandshakeTimer(){this.handshakeTimer&&(clearTimeout(this.handshakeTimer),this.handshakeTimer=null)}}class zi{constructor(e){this.activeSession=null,this.config=e||{handshakeTimeoutMs:8e3,creativeTimeoutMs:1e4,maxDurationExtensionSec:30,allowClickThru:!0};const t=this.detectCapabilities();this.diagnostics={simidAvailable:t.iframeSupported,creativeDetected:!1,sessionCreatedCount:0,bridgeInitSuccess:!1,messagesRoutedCount:0,capabilities:t,errorLog:[]}}getConfig(){return this.config}detectCapabilities(){const e=typeof window<"u";return{simidVersion:"1.0",iframeSupported:e&&typeof document<"u"&&typeof document.createElement=="function",secureMessagingSupported:e&&typeof window.postMessage=="function",postMessageSupported:e&&typeof window.postMessage=="function",clickThruSupported:!0,durationChangeSupported:!0}}hasSimidCreative(e){const t=!!(e&&e.interactiveCreativeFile);return t&&(this.diagnostics.creativeDetected=!0),t}createSession(e){if(!this.hasSimidCreative(e)||!e.interactiveCreativeFile)return null;const t={interactiveCreativeFile:e.interactiveCreativeFile,creativeType:e.contentType||"text/html",creativeParameters:e.creativeParameters||e.adParameters||"",adId:e.id,clickThruUrl:e.clickThroughUrl||e.clickThruUrl||"",clickTrackingUrls:(e.clickTrackingUrls||[]).map(i=>typeof i=="string"?i:i.url).filter(Boolean)};return this.activeSession&&this.activeSession.destroy(),this.activeSession=new vt(t,this.config,i=>{i==="initialized"&&(this.diagnostics.bridgeInitSuccess=!0)}),this.diagnostics.sessionCreatedCount++,this.activeSession}getActiveSession(){return this.activeSession}getPublicSession(){return this.activeSession?{sessionId:this.activeSession.sessionId,state:this.activeSession.getSessionState(),creative:this.activeSession.creative,errors:this.activeSession.getErrors()}:null}getDiagnostics(){return this.activeSession&&this.activeSession.getErrors().forEach(t=>{this.diagnostics.errorLog.some(i=>i.code===t.code&&i.message===t.message)||this.diagnostics.errorLog.push(t)}),this.diagnostics}destroy(){this.activeSession&&(this.activeSession.destroy(),this.activeSession=null)}}class _i{constructor(e){this.iframe=null,this.adContainer=null,this.controller=null,this.handshakeStartTime=0,this.messagesSent=0,this.messagesReceived=0,this.validationFailures=0,this.processedMessageIds=new Set,this.durationCutoffListener=null,this.config=e,this.simidManager=new zi(e)}hasSimidCreative(e){return this.simidManager.hasSimidCreative(e)}async startRuntime(e,t,i){var n,l,o;if(typeof window>"u"||typeof document>"u"||!this.simidManager.hasSimidCreative(e))return!1;const s=this.simidManager.detectCapabilities();if(!s.iframeSupported||!s.postMessageSupported)return!1;this.adContainer=t,this.controller=i,this.destroyRuntime();const r=this.simidManager.createSession(e);if(!r)return!1;const a=r.creative.interactiveCreativeFile;try{this.iframe=this.createIframe(t,a);const d=this.iframe.contentWindow;if(!d)throw new Error("SIMID iframe contentWindow is null");let h;try{h=new URL(a,window.location.href).origin}catch{}r.init(d,h),r.getBridge().addMessageListener(this.handleRuntimeMessage.bind(this)),this.handshakeStartTime=Date.now(),this.emitEvent("simidavailable",{sessionId:r.sessionId}),this.iframe.src=a,await this.waitForIframeLoad(this.iframe),r.getSessionState()==="available"&&r.start();const u=((n=this.config)==null?void 0:n.handshakeTimeoutMs)||8e3;await this.waitForState(r,"initialized",u);const f=Math.round(((l=this.adContainer)==null?void 0:l.offsetWidth)||640),p=Math.round(((o=this.adContainer)==null?void 0:o.offsetHeight)||480),g=i.getState(),v=!!e.skippable?"playerHandles":"notSkippable",y={environmentData:{videoDimensions:{x:0,y:0,width:f,height:p},creativeDimensions:{x:0,y:0,width:f,height:p},fullscreen:!!g.isFullscreen,fullscreenAllowed:!0,variableDurationAllowed:!0,skippableState:v,version:"1.0",muted:!!g.isMuted,volume:g.volume??1},creativeData:{adParameters:e.creativeParameters||e.adParameters||"",clickThruUrl:e.clickThroughUrl||e.clickThruUrl||""}},b=this.sendToCreative(r,"SIMID:Player:init",y);return r.setInitMessageId(b),await this.waitForState(r,"running",u),this.sendToCreative(r,"SIMID:Player:startCreative",{}),this.emitEvent("simidstart",{sessionId:r.sessionId}),this.emitEvent("simidready",{sessionId:r.sessionId}),!0}catch(d){const h=d instanceof Error?d.message:String(d);return console.warn("[SimidRuntime] Startup failed:",h),this.emitEvent("simiderror",{message:h}),this.destroyRuntime(),!1}}destroyRuntime(){this.clearDurationCutoff();const e=this.simidManager.getActiveSession();if(e&&e.getSessionState()==="running")try{this.sendToCreative(e,"SIMID:Player:adStopped",{})}catch{}this.simidManager.destroy(),this.removeIframe(),this.processedMessageIds.clear(),this.controller&&this.emitEvent("simidcomplete",{})}getSimidManager(){return this.simidManager}getRuntimeDiagnostics(){const e=this.simidManager.getDiagnostics(),t=this.simidManager.getActiveSession();return{...e,iframeLoaded:this.iframe!==null,handshakeDurationMs:this.handshakeStartTime?Date.now()-this.handshakeStartTime:0,messagesSent:this.messagesSent,messagesReceived:this.messagesReceived,validationFailures:this.validationFailures,sessionState:(t==null?void 0:t.getSessionState())||null,sessionLifetimeMs:this.handshakeStartTime?Date.now()-this.handshakeStartTime:0}}createIframe(e,t){const i=document.createElement("iframe"),s=Li("allow-scripts allow-same-origin allow-popups allow-forms",{srcUrl:t||null});return i.setAttribute("sandbox",s),i.setAttribute("allow","autoplay; fullscreen"),i.setAttribute("referrerpolicy","no-referrer"),e&&typeof getComputedStyle=="function"&&getComputedStyle(e).position==="static"&&(e.style.position="relative"),i.style.position="absolute",i.style.top="0",i.style.left="0",i.style.width="100%",i.style.height="100%",i.style.border="none",i.style.zIndex="1001",i.style.pointerEvents="auto",i.style.backgroundColor="transparent",e.appendChild(i),i}waitForIframeLoad(e){var i;const t=((i=this.config)==null?void 0:i.creativeTimeoutMs)??1e4;return new Promise((s,r)=>{const a=setTimeout(()=>{r(new Error("SIMID iframe load timeout"))},t);e.addEventListener("load",()=>{clearTimeout(a),s()},{once:!0}),e.addEventListener("error",()=>{clearTimeout(a),r(new Error("SIMID iframe load failed"))},{once:!0})})}removeIframe(){this.iframe&&(this.iframe.src="about:blank",this.iframe.parentNode&&this.iframe.parentNode.removeChild(this.iframe),this.iframe=null)}sendToCreative(e,t,i){const s=e.getBridge().postMessage(t,i);return this.messagesSent++,s}handleRuntimeMessage(e){if(this.messagesReceived++,this.processedMessageIds.has(e.messageId)){this.validationFailures++;return}if(this.processedMessageIds.add(e.messageId),this.processedMessageIds.size>1e3){const r=this.processedMessageIds.values().next().value;r&&this.processedMessageIds.delete(r)}const t=this.simidManager.getActiveSession();if(!t||t.sessionId!==e.sessionId){this.validationFailures++;return}switch(String(e.type||"").replace(/^simid:(creative|player|media):/i,"").replace(/^simid:/i,"").toLowerCase()){case"createsession":case"handshake":case"creativeready":case"creativeloaded":case"resolve":case"reject":break;case"requestclickthru":case"requestclickthrough":this.handleRequestClickThru(t,e);break;case"requestchangeadduration":case"requestchangeduration":this.handleRequestChangeAdDuration(t,e);break;case"requestunmute":this.handleRequestMute(t,e,!1);break;case"requestfatalerror":this.handleRequestFatalError(t,e);break;case"requestadparameters":this.handleRequestAdParameters(t,e);break;case"getmediastate":case"requestmediastate":this.handleGetMediaState(t,e);break;case"requestpause":this.handleRequestPause(t,e);break;case"requestplay":case"requestresume":this.handleRequestResume(t,e);break;case"requestchangevolume":case"requestvolume":this.handleRequestVolume(t,e);break;case"requestmute":this.handleRequestMute(t,e,!0);break;case"requestresize":this.handleRequestResize(t,e);break;case"requestfullscreen":this.handleRequestFullscreen(t,e);break;case"requestexitfullscreen":this.handleRequestExitFullscreen(t,e);break;case"requestcollapse":this.handleRequestCollapse(t,e);break;case"requestexpand":this.handleRequestExpand(t,e);break;case"requestduration":this.handleRequestDuration(t,e);break;case"requestcurrenttime":this.handleRequestCurrentTime(t,e);break;case"requestremainingtime":this.handleRequestRemainingTime(t,e);break;case"requestplayerstate":this.handleRequestPlayerState(t,e);break;case"requestcreativedata":this.handleRequestCreativeData(t,e);break;case"requestskip":this.handleRequestSkip(t,e);break;case"requeststop":this.handleRequestStop(t,e);break;case"reporttracking":this.handleReportTracking(t,e);break;case"creativeinteraction":this.respond(t,e,{}),this.emitEvent("simidinteraction",e.data||e.args||{});break;case"creativeclosed":this.respond(t,e,{}),t.complete(),this.emitEvent("simidcomplete",{});break;default:this.respond(t,e,{});break}}handleRequestClickThru(e,t){let s=(t.args||t.data||{}).clickUrl||e.creative.clickThruUrl||"";const r=e.creative.clickTrackingUrls||[];if(typeof s!="string"||!s.trim()){this.rejectRequest(e,t,"No valid click-through URL specified");return}s=s.trim();try{const l=new URL(s,typeof window<"u"?window.location.href:void 0);if(l.protocol!=="http:"&&l.protocol!=="https:"){this.rejectRequest(e,t,"Invalid URL scheme. Only HTTP and HTTPS are permitted."),this.emitEvent("simidsecurityerror",{reason:"Blocked unsafe click-through URL",url:s});return}}catch{this.rejectRequest(e,t,"Malformed click-through URL");return}let a=!1;const n=this.simidManager.getConfig().onSimidClickThru;if(typeof n=="function")try{n(s,r)===!1&&(a=!0)}catch(l){console.warn("[SimidRuntime] Error in onSimidClickThru developer callback:",l)}if(r.forEach(l=>{if(typeof l=="string"&&l)try{fetch(l,{method:"GET",mode:"no-cors",keepalive:!0}).catch(()=>{})}catch{}}),!a&&this.simidManager.getConfig().allowClickThru!==!1&&typeof window<"u")try{window.open(s,"_blank","noopener,noreferrer")}catch(l){console.warn("[SimidRuntime] Popup open failed:",l)}this.emitEvent("simidclick",{url:s,trackingUrls:r,playerHandled:!a}),this.respond(e,t,{success:!0,url:s})}handleRequestChangeAdDuration(e,t){var l,o,d;const i=t.args||t.data||{},s=((d=(o=(l=this.controller)==null?void 0:l.getState)==null?void 0:o.call(l))==null?void 0:d.adDuration)||0;let r;if(typeof i.duration=="number"?r=i.duration:typeof i.extensionSec=="number"&&(r=s+i.extensionSec),r===void 0){this.rejectRequest(e,t,"requestChangeAdDuration missing a numeric duration/extensionSec");return}const a=r-s,n=this.simidManager.getConfig().maxDurationExtensionSec??30;if(a>n){this.rejectRequest(e,t,`Requested duration extension (${a}s) exceeds maximum permitted limit (${n}s)`);return}this.emitEvent("simiddurationchange",{duration:r,extensionSec:a,maxAllowed:n}),this.respond(e,t,{success:!0,duration:r}),r<s&&this.scheduleAdDurationCutoff(r)}scheduleAdDurationCutoff(e){var i;if(this.clearDurationCutoff(),!((i=this.controller)!=null&&i.on))return;const t=s=>{var r,a,n;if(s&&s.currentTime>=e){this.clearDurationCutoff();try{(n=(a=(r=this.controller)==null?void 0:r.ads)==null?void 0:a.skip)==null||n.call(a)}catch{}}};this.durationCutoffListener=t,this.controller.on("adtimeupdate",t)}clearDurationCutoff(){var e;this.durationCutoffListener&&((e=this.controller)!=null&&e.off)&&this.controller.off("adtimeupdate",this.durationCutoffListener),this.durationCutoffListener=null}handleRequestFatalError(e,t){const i=t.args||t.data||{},s=i.code||1005,r=i.message||"Creative reported fatal error";this.emitEvent("simidcreativeerror",{code:s,message:r,fatal:!0}),this.emitEvent("simiderror",{code:s,message:r,fatal:!0}),this.respond(e,t,{acknowledged:!0}),this.destroyRuntime()}handleRequestMute(e,t,i){var s;(s=this.controller)!=null&&s.setMuted&&this.controller.setMuted(i),this.respond(e,t,{success:!0,muted:i})}handleRequestAdParameters(e,t){this.respond(e,t,{adParameters:e.creative.creativeParameters||""})}getSafeDuration(){var t,i,s;const e=(s=(i=(t=this.controller)==null?void 0:t.getState)==null?void 0:i.call(t))==null?void 0:s.duration;return e==null||isNaN(e)||e===1/0||e<0?1/0:e}getSafeRemainingTime(){var i,s,r;const e=this.getSafeDuration();if(e===1/0)return 1/0;const t=((r=(s=(i=this.controller)==null?void 0:i.getState)==null?void 0:s.call(i))==null?void 0:r.currentTime)||0;return Math.max(0,e-t)}handleGetMediaState(e,t){var a,n,l,o;const i=(n=(a=this.controller)==null?void 0:a.getVideoElement)==null?void 0:n.call(a),s=(o=(l=this.controller)==null?void 0:l.getState)==null?void 0:o.call(l),r=this.getSafeDuration();this.respond(e,t,{currentSrc:(i==null?void 0:i.currentSrc)||(i==null?void 0:i.src)||"",currentTime:(i==null?void 0:i.currentTime)||(s==null?void 0:s.currentTime)||0,duration:r,isLive:r===1/0,ended:(i==null?void 0:i.ended)||!1,muted:i?i.muted:(s==null?void 0:s.isMuted)??!1,paused:i?i.paused:s!=null&&s.isPlaying?!s.isPlaying:!0,volume:(i==null?void 0:i.volume)??(s==null?void 0:s.volume)??1,fullscreen:!!(s!=null&&s.isFullscreen)})}handleRequestPause(e,t){var i;(i=this.controller)!=null&&i.getVideoElement&&this.controller.getVideoElement().pause(),this.respond(e,t,{success:!0}),this.emitEvent("simidpause",{})}handleRequestResume(e,t){var i;(i=this.controller)!=null&&i.getVideoElement&&this.controller.getVideoElement().play().catch(()=>{}),this.respond(e,t,{success:!0}),this.emitEvent("simidresume",{})}handleRequestResize(e,t){const{width:i,height:s}=t.data||t.args||{};this.iframe&&i&&s&&(this.iframe.style.width=typeof i=="number"?`${i}px`:i,this.iframe.style.height=typeof s=="number"?`${s}px`:s),this.respond(e,t,{success:!0}),this.emitEvent("simidresize",{width:i,height:s})}handleRequestFullscreen(e,t){var i;(i=this.controller)!=null&&i.toggleFullscreen&&this.controller.toggleFullscreen(),this.respond(e,t,{success:!0}),this.emitEvent("simidfullscreen",{})}handleRequestExitFullscreen(e,t){var i;(i=this.controller)!=null&&i.getState().isFullscreen&&this.controller.toggleFullscreen(),this.respond(e,t,{success:!0}),this.emitEvent("simidexitfullscreen",{})}handleRequestCollapse(e,t){this.iframe&&(this.iframe.style.pointerEvents="none",this.iframe.style.opacity="0"),this.respond(e,t,{success:!0}),this.emitEvent("simidcollapse",{})}handleRequestExpand(e,t){this.iframe&&(this.iframe.style.pointerEvents="auto",this.iframe.style.opacity="1"),this.respond(e,t,{success:!0}),this.emitEvent("simidexpand",{})}handleRequestVolume(e,t){var a,n,l,o,d,h,u,f;const i=t.args||t.data||{},s=i.volume,r=i.muted;(a=this.controller)!=null&&a.setVolume&&typeof s=="number"&&this.controller.setVolume(s),(n=this.controller)!=null&&n.setMuted&&typeof r=="boolean"&&this.controller.setMuted(r),this.respond(e,t,{success:!0,volume:(d=(o=(l=this.controller)==null?void 0:l.getState)==null?void 0:o.call(l))==null?void 0:d.volume,muted:(f=(u=(h=this.controller)==null?void 0:h.getState)==null?void 0:u.call(h))==null?void 0:f.isMuted})}handleRequestDuration(e,t){const i=this.getSafeDuration();this.respond(e,t,{duration:i,isLive:i===1/0})}handleRequestCurrentTime(e,t){var s,r,a;const i=((a=(r=(s=this.controller)==null?void 0:s.getState)==null?void 0:r.call(s))==null?void 0:a.currentTime)||0;this.respond(e,t,{currentTime:i})}handleRequestRemainingTime(e,t){const i=this.getSafeRemainingTime();this.respond(e,t,{remainingTime:i,isLive:i===1/0})}handleRequestPlayerState(e,t){var r,a;const i=(a=(r=this.controller)==null?void 0:r.getState)==null?void 0:a.call(r),s=this.getSafeDuration();this.respond(e,t,{currentTime:(i==null?void 0:i.currentTime)||0,duration:s,isLive:s===1/0,volume:(i==null?void 0:i.volume)||1,muted:(i==null?void 0:i.isMuted)||!1,isPlaying:(i==null?void 0:i.isPlaying)||!1,isFullscreen:(i==null?void 0:i.isFullscreen)||!1})}handleRequestCreativeData(e,t){this.respond(e,t,{creative:e.creative})}handleRequestSkip(e,t){var i,s,r;this.respond(e,t,{}),this.emitEvent("simidskip",{}),this.destroyRuntime();try{(r=(s=(i=this.controller)==null?void 0:i.ads)==null?void 0:s.skip)==null||r.call(s)}catch{}}handleRequestStop(e,t){var i,s,r;this.respond(e,t,{}),this.emitEvent("simidstop",{}),this.destroyRuntime();try{(r=(s=(i=this.controller)==null?void 0:i.ads)==null?void 0:s.skip)==null||r.call(s)}catch{}}handleReportTracking(e,t){const i=t.args||{},s=t.data||{},r=i.trackingUrls||s.trackingUrls||[];Array.isArray(r)&&r.forEach(a=>{if(typeof a=="string"&&a)try{fetch(a,{method:"GET",mode:"no-cors",keepalive:!0}).catch(()=>{})}catch{}}),this.respond(e,t,{})}getPublicDiagnostics(){return this.getRuntimeDiagnostics()}getPublicSession(){return this.simidManager.getPublicSession()}isRuntimeActive(){const e=this.simidManager.getActiveSession();return!!e&&e.getSessionState()==="running"}respond(e,t,i={}){try{t.messageId!==void 0&&t.messageId!==null&&e.getBridge().postResolve(t.messageId,i),this.messagesSent++}catch{}}rejectRequest(e,t,i){try{t.messageId!==void 0&&t.messageId!==null&&e.getBridge().postReject(t.messageId,{message:i}),this.messagesSent++}catch{}}emitEvent(e,t){var i;if((i=this.controller)!=null&&i.emit)try{this.controller.emit(e,t)}catch{}}waitForState(e,t,i){return new Promise((s,r)=>{const a={idle:0,available:1,loading:2,initialized:3,running:4,completed:5,destroyed:6},n=a[t]??0;if((a[e.getSessionState()]??0)>=n&&e.getSessionState()!=="destroyed"){s();return}const o=setTimeout(()=>{r(new Error(`SIMID session did not reach state '${t}' within ${i}ms (current state: '${e.getSessionState()}')`))},i),d=setInterval(()=>{const h=e.getSessionState();(a[h]??0)>=n&&h!=="destroyed"?(clearTimeout(o),clearInterval(d),s()):(h==="destroyed"||h==="completed")&&(clearTimeout(o),clearInterval(d),r(new Error(`SIMID session entered terminal state '${h}' before reaching '${t}'`)))},50)})}}async function Hi(c,e,t={}){const i=t.timeout??1e4,s=t.retryCount??3,r=t.withCredentials?"include":"same-origin",a=t.headers||{};let n=0;const l=o=>new Promise(d=>setTimeout(d,o));for(;n<=s;){if(e.aborted)throw new DOMException("Aborted","AbortError");const o=new AbortController,d=o.signal,h=()=>o.abort();e.addEventListener("abort",h);const u=setTimeout(()=>{o.abort()},i);try{const f=await fetch(c,{headers:a,credentials:r,signal:d});if(clearTimeout(u),e.removeEventListener("abort",h),f.ok)return await f.text();if(f.status>=500&&n<s){n++,await l(Math.pow(2,n)*100);continue}throw new Error(`Server returned HTTP status ${f.status}`)}catch(f){if(clearTimeout(u),e.removeEventListener("abort",h),e.aborted)throw new DOMException("Aborted","AbortError");if(n<s){n++,await l(Math.pow(2,n)*100);continue}throw f}}throw new Error("Request failed after maximum retries")}class Js{constructor(){this.cache=new Map,this.maxAgeMs=3e5}get(e){const t=this.cache.get(e);if(t){if(Date.now()-t.timestamp<this.maxAgeMs)return t.xmlText;this.cache.delete(e)}return null}set(e,t){this.cache.set(e,{xmlText:t,timestamp:Date.now()})}clear(){this.cache.clear()}}class _t{constructor(){this.executedUrls=new Set,this.activeControllers=new Set,this.retryTimers=new Set,this.totalLatency=0,this.latencyCount=0,this.diagnostics={requestsCount:0,successesCount:0,failuresCount:0,retriesCount:0,duplicateSuppressions:0,averageLatencyMs:0,lastTransportUsed:null,errorCodesTracked:{}}}replaceMacros(e,t){if(!e)return"";const i=Date.now(),s=Math.floor(Math.random()*1e8);return e.replace(/\[CACHEBUSTING\]/gi,String(s)).replace(/\[CACHEBUSTER\]/gi,String(s)).replace(/\[TIMESTAMP\]/gi,String(i)).replace(/\[ERRORCODE\]/gi,String(t??0))}trackUrl(e,t,i=3){if(!e)return;const s=this.replaceMacros(e,t);if(this.executedUrls.has(s)){this.diagnostics.duplicateSuppressions++;return}this.executedUrls.add(s),this.sendBeacon(s,i)}async sendBeacon(e,t,i=0){this.diagnostics.requestsCount++;const s=me();if(typeof fetch=="function"){const r=new AbortController;this.activeControllers.add(r);try{await fetch(e,{method:"GET",mode:"no-cors",keepalive:!0,signal:r.signal}),this.activeControllers.delete(r),this.recordSuccess(s,"fetch");return}catch(a){if(this.activeControllers.delete(r),a instanceof Error&&a.name==="AbortError")return}}if(typeof Image<"u")try{const r=new Image;r.src=e,this.recordSuccess(s,"image");return}catch{this.handleFailure(e,500,s,t,i);return}this.diagnostics.failuresCount++}recordSuccess(e,t){this.diagnostics.successesCount++,this.diagnostics.lastTransportUsed=t,this.totalLatency+=me()-e,this.latencyCount++,this.diagnostics.averageLatencyMs=this.totalLatency/this.latencyCount}handleFailure(e,t,i,s,r){this.diagnostics.failuresCount++;const a=String(t);if(this.diagnostics.errorCodesTracked[a]=(this.diagnostics.errorCodesTracked[a]||0)+1,!(t===404||t===400)&&r<s){this.diagnostics.retriesCount++;const n=Math.pow(2,r+1)*100,l=setTimeout(()=>{this.retryTimers.delete(l),this.sendBeacon(e,s,r+1)},n);this.retryTimers.add(l)}}getDiagnostics(){return this.diagnostics}clearRegistry(){this.executedUrls.clear()}destroy(){this.activeControllers.forEach(e=>e.abort()),this.activeControllers.clear(),this.retryTimers.forEach(e=>clearTimeout(e)),this.retryTimers.clear(),this.executedUrls.clear()}}const me=()=>typeof performance<"u"?performance.now():Date.now();function yt(c){if(!c)return 0;const e=c.trim().split(":");if(e.length===3){const i=parseInt(e[0],10)||0,s=parseInt(e[1],10)||0,r=parseFloat(e[2])||0;return i*3600+s*60+r}const t=parseFloat(c);return isNaN(t)?0:t}function Ht(c){if(typeof window>"u"||typeof DOMParser>"u")return null;try{const t=new DOMParser().parseFromString(c,"text/xml");return t.getElementsByTagName("parsererror").length>0?null:t}catch{return null}}function ee(c,e){const t=[],i=c.getElementsByTagName("*"),s=e.toLowerCase();for(let r=0;r<i.length;r++){const a=i[r];(a.localName||a.nodeName.split(":").pop()||"").toLowerCase()===s&&t.push(a)}return t}function Q(c,e){const t=ee(c,e);return t.length>0?t[0]:null}function er(c){return typeof XMLSerializer<"u"?new XMLSerializer().serializeToString(c):c.textContent||""}function tr(c){var g,m,v;if(typeof DOMParser>"u")return null;const e=new DOMParser().parseFromString(c,"text/xml");if(e.getElementsByTagName("parsererror").length>0)return null;const t=Q(e,"Ad"),i=t&&Q(t,"InLine")||Q(e,"InLine");if(!i)return null;const s=Q(i,"AdTitle"),r=(g=s==null?void 0:s.textContent)==null?void 0:g.trim(),a=ee(i,"Creative");let n=null;for(let y=0;y<a.length;y++){const b=Q(a[y],"NonLinear");if(b){n=b;break}}if(!n)return null;const l=bt(n);if(!l)return null;const o=parseInt(n.getAttribute("width")||"0",10)||void 0,d=parseInt(n.getAttribute("height")||"0",10)||void 0,h=Q(n,"NonLinearClickThrough"),u=((m=h==null?void 0:h.textContent)==null?void 0:m.trim())||void 0,f=ee(n,"Tracking"),p=[];for(let y=0;y<f.length;y++){const b=f[y],S=b.getAttribute("event")||"",T=(v=b.textContent)==null?void 0:v.trim();T&&S&&p.push({url:T,event:S})}return{title:r,width:o,height:d,clickThroughUrl:u,trackingUrls:p.length>0?p:void 0,...l}}function bt(c){var n,l,o;const e=Q(c,"StaticResource"),t=(n=e==null?void 0:e.textContent)==null?void 0:n.trim();if(t)return{imageUrl:t};const i=Q(c,"IFrameResource"),s=(l=i==null?void 0:i.textContent)==null?void 0:l.trim();if(s)return{htmlUrl:s,useIframe:!0};const r=Q(c,"HTMLResource"),a=(o=r==null?void 0:r.textContent)==null?void 0:o.trim();return a?{htmlContent:a}:null}function ir(c){const{mode:e,configSkipOffset:t,xmlSkippable:i,xmlSkipOffset:s,currentTime:r}=c;if(e===ze.DISABLED)return{canSkip:!1,skipAvailableAt:null};if(e===ze.USER){const n=t??5,l=r>=n;return{canSkip:l,skipAvailableAt:l?null:Math.max(0,n-r)}}if(!i||s===void 0)return{canSkip:!1,skipAvailableAt:null};const a=r>=s;return{canSkip:a,skipAvailableAt:a?null:Math.max(0,s-r)}}function qi(c,e){return!(c==="impression"&&(e==null?void 0:e.trackImpression)===!1||c==="quartile"&&(e==null?void 0:e.trackQuartiles)===!1)}function sr(c){const e=c||"",t=[[/timeout/i,ie.NETWORK,301],[/version|unsupported/i,ie.CONFIGURATION,101],[/loop/i,ie.PARSING,302],[/depth|limit|oversized/i,ie.CONFIGURATION,302],[/xml|malformed|parse/i,ie.PARSING,100],[/media/i,ie.CONFIGURATION,403],[/creative/i,ie.CONFIGURATION,200],[/http|fetch|status|server/i,ie.NETWORK,300]];for(const[i,s,r]of t)if(i.test(e))return{type:s,code:r};return{type:ie.UNKNOWN,code:900}}class qt{constructor(){this.name="VAST",this.capabilities={supportsLinear:!0,supportsNonLinear:!0,supportsCompanion:!0,supportsSkippable:!0,supportsVMAP:!1,supportsVAST:!0,supportsSSAI:!1,supportsIMA:!1},this.context=null,this.manager=null,this.cache=new Js,this.trackingManager=new _t,this.isCacheEnabled=!1,this.renderingStrategy="dedicated",this.originalSource="",this.skipModeConfig=ze.AUTO,this.currentAd=null,this.currentAdBreak=null,this.currentAdIndex=0,this.adVideoElement=null,this.canSkipAd=!1,this.impressionFired=!1,this.milestones={start:!1,firstQuartile:!1,midpoint:!1,thirdQuartile:!1,complete:!1},this.cleanupListeners=null,this.cleanupClick=null,this.bufferingTimeoutId=null,this.simidRuntime=null,this.limits={maxXmlSize:2097152,maxWrapperDepth:5,maxCreatives:20,maxMediaEntries:50,maxTrackingEntries:100,maxExtensions:20},this.diagnostics={fetchDurationMs:0,parseDurationMs:0,validationDurationMs:0,wrapperCount:0,selectedMedia:null,rejectedMedia:[],validationWarnings:[],parserVersion:"Unknown",creativeCount:0,podCount:0,mediaCandidatesCount:0,rejectedCreativesCount:0,namespaceUsageDetected:!1,cacheHits:0,cacheMisses:0}}init(e){var i,s,r,a,n,l;this.context=e,e.controller&&e.controller.ads&&(this.manager=e.controller.ads.manager);const t=(i=e.config)==null?void 0:i.providerOptions;return t&&(this.isCacheEnabled=!!t.enableCache,this.renderingStrategy=t.renderingStrategy==="swapped"?"swapped":"dedicated",typeof t.maxXmlSize=="number"&&(this.limits.maxXmlSize=t.maxXmlSize),typeof t.maxWrapperDepth=="number"&&(this.limits.maxWrapperDepth=t.maxWrapperDepth)),this.skipModeConfig=((r=(s=e.config)==null?void 0:s.playback)==null?void 0:r.skipMode)??ze.AUTO,this.skipOffsetConfig=(n=(a=e.config)==null?void 0:a.playback)==null?void 0:n.skipOffset,this.trackingConfig=(l=e.config)==null?void 0:l.tracking,{success:!0}}async requestAds(e,t){var h,u,f,p,g,m;const i=t==null?void 0:t.context;if((!this.manager||!this.context)&&i&&this.init(i),!this.manager||!this.context)return{success:!1,error:{type:ie.CONFIGURATION,code:100,message:"VastProvider not initialized."}};this.simidRuntime&&(this.simidRuntime.destroyRuntime(),this.simidRuntime=null),this.manager&&this.manager.transitionTo(w.REQUESTING);const s=new Set;let r=e,a=0;const n=[],l=[],o=[],d=new AbortController().signal;try{for(;a<this.limits.maxWrapperDepth;){if(s.has(r))throw new Error("VAST wrapper loop detected");s.add(r),this.diagnostics.wrapperCount=a;let v="";if(this.isCacheEnabled){const M=this.cache.get(r);M&&(this.diagnostics.cacheHits++,v=M)}if(!v){this.diagnostics.cacheMisses++;const M=me();v=await this.fetchVastXml(r,d,this.context.config.request),this.diagnostics.fetchDurationMs+=me()-M,this.isCacheEnabled&&this.cache.set(r,v)}if(v.length>this.limits.maxXmlSize)throw new Error(`Oversized VAST XML payload: ${v.length} bytes exceeds limits`);const y=me(),b=Ht(v);if(this.diagnostics.parseDurationMs+=me()-y,!b)throw new Error("Malformed VAST XML or parsing error");const S=Q(b,"VAST"),T=Q(b,"Playlist");if(!S&&!T)throw new Error("Missing VAST or Playlist root node");if((v.includes(":VAST")||v.includes(":Ad")||v.includes(":VMAP"))&&(this.diagnostics.namespaceUsageDetected=!0),S){const M=S.getAttribute("version");if(M){this.diagnostics.parserVersion=`VAST-${M}`;const I=parseFloat(M);if(isNaN(I)||I<2||I>4.2)throw new Error(`Unsupported VAST version: ${M}`)}}if(T){const M=ee(T,"Ad"),I=[];for(let R=0;R<M.length;R++){const N=(h=M[R].textContent)==null?void 0:h.trim();N&&(N.startsWith("http://")||N.startsWith("https://"))&&I.push(N)}if(I.length>0){const R=[];for(let N=0;N<I.length;N++)try{const U=await this.fetchVastXml(I[N],d,(u=this.context.config)==null?void 0:u.request),C=Ht(U);if(C){const x=Q(C,"Inline"),H=Q(C,"Wrapper");if(x){const te=ee(C,"Ad");for(let V=0;V<te.length;V++){const F=this.normalizeAdNode(te[V],R.length+1,I.length);F&&R.push(F)}}else if(H){const te=Q(C,"VASTAdTagURI");if(te&&te.textContent){const V=await this.fetchVastXml(te.textContent.trim(),d,(f=this.context.config)==null?void 0:f.request),F=Ht(V);if(F){const L=ee(F,"Ad");for(let D=0;D<L.length;D++){const q=this.normalizeAdNode(L[D],R.length+1,I.length);q&&R.push(q)}}}}}}catch(U){console.warn(`[VastProvider] Failed to fetch playlist ad #${N+1}:`,U)}if(R.length>0){R.sort((C,x)=>(C.sequence??Number.MAX_SAFE_INTEGER)-(x.sequence??Number.MAX_SAFE_INTEGER));const N=R[0];this.currentAd=N,this.currentAdIndex=0;const U={id:`vast-break-${Date.now()}`,timeOffset:0,type:"preroll",ads:R,duration:R.reduce((C,x)=>C+(x.duration||0),0)};return this.currentAdBreak=U,this.manager.getAdBreakManager().registerBreak(U),this.manager.setCurrentAd(N),this.manager.transitionTo(w.LOADED),{success:!0}}}}const E=me(),A=this.validateVastStructure(b);if(this.diagnostics.validationDurationMs+=me()-E,A&&!T)throw new Error(`VAST Validation Failure: ${A}`);if(Q(b,"Inline")){const M=me(),I=ee(b,"Ad");this.diagnostics.podCount=I.length;const R=[];for(let x=0;x<I.length;x++){const H=I[x],te=this.normalizeAdNode(H,x+1,I.length)||this.normalizeNonLinearAdNode(H,x+1,I.length)||this.normalizeCompanionOnlyAdNode(H,x+1,I.length);te&&R.push(te)}if(R.length===0)throw new Error("No compatible ad or creative found in inline VAST.");let N=R;(n.length||l.length||o.length)&&(N=N.map(x=>({...x,impressionUrls:[...x.impressionUrls||[],...n],errorUrls:[...x.errorUrls||[],...l],trackingUrls:[...x.trackingUrls||[],...o]}))),N=[...N].sort((x,H)=>(x.sequence??Number.MAX_SAFE_INTEGER)-(H.sequence??Number.MAX_SAFE_INTEGER)),this.diagnostics.parseDurationMs+=me()-M;const U=N[0];this.currentAd=U,this.currentAdIndex=0;const C={id:`vast-break-${Date.now()}`,timeOffset:0,type:"preroll",ads:N,duration:N.reduce((x,H)=>x+(H.duration||0),0)};return this.currentAdBreak=C,this.manager.getAdBreakManager().registerBreak(C),this.manager.setCurrentAd(U),this.manager.transitionTo(w.LOADED),{success:!0}}const $=Q(b,"Wrapper");if($){const M=Q(b,"VASTAdTagURI");if(!M||!M.textContent)throw new Error("VAST wrapper is missing VASTAdTagURI node.");const I=ee($,"Impression");for(let U=0;U<I.length;U++){const C=(p=I[U].textContent)==null?void 0:p.trim();C&&n.push(C)}const R=ee($,"Error");for(let U=0;U<R.length;U++){const C=(g=R[U].textContent)==null?void 0:g.trim();C&&l.push(C)}const N=ee($,"Tracking");for(let U=0;U<N.length;U++){const C=N[U],x=C.getAttribute("event")||"",H=(m=C.textContent)==null?void 0:m.trim();H&&x&&o.push({url:H,event:x})}r=M.textContent.trim(),a++;continue}throw new Error("VAST XML does not contain an Inline or Wrapper node.")}throw new Error(`VAST wrapper depth limit reached (${this.limits.maxWrapperDepth})`)}catch(v){const y=this.mapError(v);return this.fireErrorTracking(y.type===ie.NETWORK?301:100),this.manager.triggerAdError(y),{success:!1,error:y}}}async fetchVastXml(e,t,i={}){return Hi(e,t,i)}validateVastStructure(e){return ee(e,"Ad").length===0?"VAST contains no Ad elements":null}normalizeAdNode(e,t,i){var ae,wt,ot,Tt,ne,oi,li,Et,lt,xe,We,z,se,he,Be,ct,ds,hs,us,ps;const s=Q(e,"Inline");if(!s)return null;const r=Q(s,"AdTitle"),a=((ae=r==null?void 0:r.textContent)==null?void 0:ae.trim())||"VAST Ad",n=Q(s,"AdSystem"),l=((wt=n==null?void 0:n.textContent)==null?void 0:wt.trim())||"Unknown",o=Q(s,"Duration"),d=yt(o==null?void 0:o.textContent),h=ee(s,"Creative");if(this.diagnostics.creativeCount+=h.length,h.length>this.limits.maxCreatives)return this.diagnostics.validationWarnings.push("Too many creatives detected in XML."),null;let u=null,f="";for(let K=0;K<h.length;K++){const Z=h[K],fe=Q(Z,"Linear");if(fe){u=fe,f=Z.getAttribute("id")||"";break}else this.diagnostics.rejectedCreativesCount++}if(!u)return this.diagnostics.validationWarnings.push("No compatible linear creative found."),null;const p=ee(u,"MediaFile");if(this.diagnostics.mediaCandidatesCount+=p.length,p.length>this.limits.maxMediaEntries)return this.diagnostics.validationWarnings.push("Oversized media entries count."),null;const g=[];for(let K=0;K<p.length;K++){const Z=p[K],fe=(ot=Z.textContent)==null?void 0:ot.trim(),be=Z.getAttribute("type")||"",je=parseInt(Z.getAttribute("bitrate")||"0",10),jr=parseInt(Z.getAttribute("width")||"0",10),Gr=parseInt(Z.getAttribute("height")||"0",10),Qr=Z.getAttribute("delivery")||"progressive";fe&&g.push({url:fe,bitrate:je,width:jr,height:Gr,contentType:be,delivery:Qr})}const m=this.selectMediaFile(g);if(!m)return this.diagnostics.validationWarnings.push("No compatible MediaFile found in creative."),null;this.diagnostics.selectedMedia=m;const v=u.getAttribute("skipoffset"),y=v!=null,b=y?yt(v):void 0,S=ee(u,"Tracking");if(S.length>this.limits.maxTrackingEntries)return this.diagnostics.validationWarnings.push("Tracking events limit exceeded."),null;const T=[];for(let K=0;K<S.length;K++){const Z=S[K],fe=Z.getAttribute("event")||"",be=(Tt=Z.textContent)==null?void 0:Tt.trim();be&&fe&&T.push({url:be,event:fe})}const E=Q(u,"ClickThrough"),A=(ne=E==null?void 0:E.textContent)==null?void 0:ne.trim(),P=ee(s,"Impression"),$=[];for(let K=0;K<P.length;K++){const Z=(oi=P[K].textContent)==null?void 0:oi.trim();Z&&$.push(Z)}const M=ee(u,"ClickTracking"),I=[];for(let K=0;K<M.length;K++){const Z=(li=M[K].textContent)==null?void 0:li.trim();Z&&I.push(Z)}const R=ee(e,"Error");if(R.length===0){const K=ee(e.ownerDocument,"Error");for(let Z=0;Z<K.length;Z++)((Et=K[Z].textContent)==null?void 0:Et.trim())&&R.push(K[Z])}const N=[];for(let K=0;K<R.length;K++){const Z=(lt=R[K].textContent)==null?void 0:lt.trim();Z&&N.push(Z)}let U=null;const C=Q(s,"UniversalAdId");C&&(U={idRegistry:C.getAttribute("idRegistry")||"unknown",value:((xe=C.textContent)==null?void 0:xe.trim())||""});const x=[],H=ee(s,"Extension");for(let K=0;K<Math.min(H.length,this.limits.maxExtensions);K++)x.push(er(H[K]));const te=[],V=ee(s,"Verification");for(let K=0;K<V.length;K++){const Z=V[K],fe=Z.getAttribute("vendor")||"",be=((z=(We=Q(Z,"JavaScriptResource"))==null?void 0:We.textContent)==null?void 0:z.trim())||"";be&&te.push({vendor:fe,script:be})}let F=((he=(se=Q(u,"InteractiveCreativeFile"))==null?void 0:se.textContent)==null?void 0:he.trim())||null;if(F||(F=((ct=(Be=Q(s,"InteractiveCreativeFile"))==null?void 0:Be.textContent)==null?void 0:ct.trim())||null),!F)for(let K=0;K<p.length;K++){const Z=p[K],fe=((ds=Z.getAttribute("apiFramework"))==null?void 0:ds.toUpperCase())||"",be=((hs=Z.getAttribute("type"))==null?void 0:hs.toLowerCase())||"";if(fe==="SIMID"||be==="text/html"){const je=(us=Z.textContent)==null?void 0:us.trim();if(je&&(je.startsWith("http://")||je.startsWith("https://"))){F=je;break}}}const L=Q(u,"Mezzanine"),D=((ps=L==null?void 0:L.textContent)==null?void 0:ps.trim())||null,q=e.getAttribute("sequence"),de=q?parseInt(q,10):void 0,le=e.getAttribute("id")||`vast-${Date.now()}`,Fe=ee(s,"Companion"),Ue=[];for(let K=0;K<Fe.length;K++){const Z=this.normalizeCompanionNode(Fe[K],e,K+1,Fe.length);Z&&Ue.push(Z)}const Ke=this.extractConcurrentNonLinearAds(s,e);return{id:le,title:a,duration:d,width:m.width,height:m.height,linear:!0,skippable:y,skipOffset:b,clickThroughUrl:A,trackingUrls:T,impressionUrls:$,clickTrackingUrls:I,errorUrls:N,contentType:m.contentType,mediaUrl:m.url,creativeId:f,adSystem:l,universalAdId:U,extensions:x,adVerifications:te,interactiveCreativeFile:F,mezzanine:D,sequence:de,podPosition:t,podSize:i,companions:Ue.length>0?Ue:void 0,nonLinearAds:Ke.length>0?Ke:void 0}}normalizeNonLinearAdNode(e,t,i){var $,M,I,R,N,U;const s=Q(e,"Inline");if(!s)return null;const r=Q(s,"AdTitle"),a=(($=r==null?void 0:r.textContent)==null?void 0:$.trim())||"VAST Ad",n=Q(s,"AdSystem"),l=((M=n==null?void 0:n.textContent)==null?void 0:M.trim())||"Unknown",o=ee(s,"Creative");let d=null,h="";for(let C=0;C<o.length;C++){const x=o[C],H=Q(x,"NonLinear");if(H){d=H,h=x.getAttribute("id")||"";break}}if(!d)return this.diagnostics.validationWarnings.push("No compatible NonLinear creative found."),null;const u=bt(d);if(!u)return this.diagnostics.validationWarnings.push("NonLinear creative has no usable resource (StaticResource/IFrameResource/HTMLResource)."),null;const f=parseInt(d.getAttribute("width")||"0",10)||void 0,p=parseInt(d.getAttribute("height")||"0",10)||void 0,g=yt(d.getAttribute("minSuggestedDuration")),m=Q(d,"NonLinearClickThrough"),v=(I=m==null?void 0:m.textContent)==null?void 0:I.trim(),y=ee(d,"Tracking"),b=[];for(let C=0;C<y.length;C++){const x=y[C],H=x.getAttribute("event")||"",te=(R=x.textContent)==null?void 0:R.trim();te&&H&&b.push({url:te,event:H})}const S=ee(s,"Impression"),T=[];for(let C=0;C<S.length;C++){const x=(N=S[C].textContent)==null?void 0:N.trim();x&&T.push(x)}const E=ee(e,"Error"),A=[];for(let C=0;C<E.length;C++){const x=(U=E[C].textContent)==null?void 0:U.trim();x&&A.push(x)}return{id:e.getAttribute("id")||`vast-nonlinear-${Date.now()}`,title:a,duration:g,width:f,height:p,linear:!1,skippable:!1,clickThroughUrl:v,trackingUrls:b,impressionUrls:T,errorUrls:A,creativeId:h,adSystem:l,podPosition:t,podSize:i,...u}}normalizeCompanionNode(e,t,i,s){var f,p;const r=bt(e);if(!r)return this.diagnostics.validationWarnings.push("Companion creative has no usable resource (StaticResource/IFrameResource/HTMLResource)."),null;const a=parseInt(e.getAttribute("width")||"0",10)||void 0,n=parseInt(e.getAttribute("height")||"0",10)||void 0,l=Q(e,"CompanionClickThrough"),o=(f=l==null?void 0:l.textContent)==null?void 0:f.trim(),d=ee(e,"Tracking"),h=[];for(let g=0;g<d.length;g++){const m=d[g],v=m.getAttribute("event")||"",y=(p=m.textContent)==null?void 0:p.trim();y&&v&&h.push({url:y,event:v})}return{id:e.getAttribute("id")||`${t.getAttribute("id")||"vast"}-companion-${i}`,title:"VAST Companion Ad",duration:0,width:a,height:n,linear:!1,skippable:!1,clickThroughUrl:o,trackingUrls:h,podPosition:i,podSize:s,...r}}normalizeCompanionOnlyAdNode(e,t,i){var y,b,S,T;const s=Q(e,"Inline");if(!s)return null;const r=ee(s,"Companion");if(r.length===0)return null;const a=[];for(let E=0;E<r.length;E++){const A=this.normalizeCompanionNode(r[E],e,E+1,r.length);A&&a.push(A)}if(a.length===0)return null;const n=Q(s,"AdTitle"),l=((y=n==null?void 0:n.textContent)==null?void 0:y.trim())||"VAST Ad",o=Q(s,"AdSystem"),d=((b=o==null?void 0:o.textContent)==null?void 0:b.trim())||"Unknown",h=ee(s,"Impression"),u=[];for(let E=0;E<h.length;E++){const A=(S=h[E].textContent)==null?void 0:S.trim();A&&u.push(A)}const f=ee(e,"Error"),p=[];for(let E=0;E<f.length;E++){const A=(T=f[E].textContent)==null?void 0:T.trim();A&&p.push(A)}const g=e.getAttribute("sequence"),m=g?parseInt(g,10):void 0;return{id:e.getAttribute("id")||`vast-companion-only-${Date.now()}`,title:l,duration:0,linear:!1,skippable:!1,impressionUrls:u,errorUrls:p,adSystem:d,sequence:m,podPosition:t,podSize:i,companions:a}}extractConcurrentNonLinearAds(e,t){var a,n;const i=ee(e,"Creative"),s=[];let r=0;for(let l=0;l<i.length;l++){const o=Q(i[l],"NonLinearAds");if(!o)continue;const d=ee(o,"NonLinear");for(let h=0;h<d.length;h++){const u=d[h],f=bt(u);if(!f)continue;r++;const p=parseInt(u.getAttribute("width")||"0",10)||void 0,g=parseInt(u.getAttribute("height")||"0",10)||void 0,m=yt(u.getAttribute("minSuggestedDuration")),v=Q(u,"NonLinearClickThrough"),y=(a=v==null?void 0:v.textContent)==null?void 0:a.trim(),b=ee(u,"Tracking"),S=[];for(let E=0;E<b.length;E++){const A=b[E],P=A.getAttribute("event")||"",$=(n=A.textContent)==null?void 0:n.trim();$&&P&&S.push({url:$,event:P})}const T=u.getAttribute("id")||`${t.getAttribute("id")||"vast"}-nonlinear-${r}`;s.push({id:T,title:"VAST NonLinear Overlay",duration:m,width:p,height:g,linear:!1,skippable:!1,clickThroughUrl:y,trackingUrls:S,...f})}}return s}selectMediaFile(e){if(e.length===0)return null;const t=e.filter(i=>{const s=(i.contentType||"").toLowerCase(),r=(i.url||"").toLowerCase(),a=s.includes("mp4")||s.includes("webm")||s.includes("mpegurl")||s.includes("apple")||s.includes("dash")||s.includes("video/")||r.endsWith(".mp4")||r.endsWith(".webm")||r.endsWith(".m3u8")||r.endsWith(".mpd")||r.includes("mp4");return a||this.diagnostics.rejectedMedia.push(i),a});return t.length===0?e[0]||null:(t.sort((i,s)=>{const r=(i.width||0)*(i.height||0),a=(s.width||0)*(s.height||0);return r!==a?a-r:(s.bitrate||0)-(i.bitrate||0)}),t[0])}mapError(e){const t=e instanceof Error?e.message:String(e??""),{type:i,code:s}=sr(t);return{type:i,code:s,message:t||"VAST request or parsing failed",originalError:e}}getInternalAdBreak(){return this.currentAdBreak}setInternalAdBreak(e){this.currentAdBreak=e,this.currentAd=e.ads[0]??null,this.currentAdIndex=0}getVastDiagnostics(){return{...this.diagnostics,tracking:this.trackingManager.getDiagnostics()}}async playAdBreak(){if(!this.context||!this.manager||!this.currentAd)return;if(this.context.controller.getState().sourceType==="embed"){this.manager.triggerAdError({type:ie.CONFIGURATION,code:900,message:"VAST ads are not supported for embed (YouTube/Vimeo) sources."});return}const e=this.currentAdBreak||this.manager.getAdBreakManager().getActiveBreak()||{id:`vast-break-${Date.now()}`,timeOffset:0,type:"preroll",ads:[this.currentAd],duration:this.currentAd.duration};this.currentAdBreak=e,this.currentAdBreak.ads&&this.currentAdBreak.ads.length>0&&(this.currentAdIndex>=this.currentAdBreak.ads.length&&(this.currentAdIndex=0),this.currentAd=this.currentAdBreak.ads[this.currentAdIndex]),this.manager.startAdBreak(e),this.currentAd.linear&&await this.playCurrentAdInPod()}async playCurrentAdInPod(){var t,i,s,r,a,n;if(!this.context||!this.manager||!this.currentAd)return;if(!this.currentAd.linear){this.manager.isHtmlOverlayCreative(this.currentAd)&&this.manager.playHtmlOverlay(this.currentAd);return}this.canSkipAd=!1,this.impressionFired=!1,this.milestones={start:!1,firstQuartile:!1,midpoint:!1,thirdQuartile:!1,complete:!1},this.trackingManager.clearRegistry();const e=this.currentAd.mediaUrl;if(!e){this.handlePlaybackError("Missing mediaUrl for current linear ad");return}this.manager.setCurrentAd(this.currentAd),this.manager.clearAuxiliaryOverlays();try{if(this.renderingStrategy==="dedicated"){if(!this.adVideoElement){const l=document.createElement("video");l.setAttribute("playsinline","true"),l.setAttribute("webkit-playsinline","true"),l.style.position="absolute",l.style.top="0",l.style.left="0",l.style.width="100%",l.style.height="100%",l.style.zIndex="1000",l.style.backgroundColor="black",l.style.pointerEvents="auto",this.context.adContainer.appendChild(l),this.adVideoElement=l,this.setupAdVideoListeners(l),this.setupClickThrough(this.context.adContainer)}this.adVideoElement.src=e,this.adVideoElement.load(),this.manager.transitionTo(w.PLAYING);try{await this.adVideoElement.play()}catch(l){if(!this.adVideoElement)return;console.warn("[VastProvider] Unmuted ad play blocked by browser policy, falling back to muted play:",l),this.adVideoElement.muted=!0,await this.adVideoElement.play()}}else{const l=this.context.videoElement;this.originalSource||(this.originalSource=l.src||""),this.adVideoElement=l,this.setupAdVideoListeners(l),this.setupClickThrough(this.context.adContainer),l.src=e,l.load(),this.manager.transitionTo(w.PLAYING);try{await l.play()}catch(o){console.warn("[VastProvider] Unmuted ad play blocked by browser policy, falling back to muted play:",o),l.muted=!0,await l.play()}}if((t=this.currentAd)!=null&&t.companions&&this.currentAd.companions.length>0&&this.manager.showCompanions(this.currentAd.companions),(i=this.currentAd)!=null&&i.nonLinearAds&&this.currentAd.nonLinearAds.length>0&&this.manager.showConcurrentOverlays(this.currentAd.nonLinearAds),(s=this.currentAd)!=null&&s.interactiveCreativeFile&&this.context){this.simidRuntime&&(this.simidRuntime.destroyRuntime(),this.simidRuntime=null);const l=((r=this.context.config)==null?void 0:r.simid)||((n=(a=this.context.config)==null?void 0:a.providerOptions)==null?void 0:n.simid);this.simidRuntime=new _i(l);const o=this.context.adContainer,d=this.context.controller;this.simidRuntime.startRuntime(this.currentAd,o,d).catch(h=>{console.warn("[VastProvider] SIMID runtime initialization warning:",h)})}}catch(l){const o=l instanceof Error?l.message:"Ad playback failed to initialize";this.handlePlaybackError(o)}}pauseAd(){this.adVideoElement&&(this.adVideoElement.pause(),this.fireTrackingEvent("pause"))}resumeAd(){this.adVideoElement&&(this.adVideoElement.play().catch(e=>{console.error("[VastProvider] Failed to resume ad play:",e)}),this.fireTrackingEvent("resume"))}setVolume(e){this.adVideoElement&&(this.adVideoElement.volume=e)}setMuted(e){this.adVideoElement&&(this.adVideoElement.muted=e,this.fireTrackingEvent(e?"mute":"unmute"))}fireTrackingEvent(e){if(!this.currentAd||!this.currentAd.trackingUrls)return;const i=["start","firstQuartile","midpoint","thirdQuartile","complete"].includes(e)?"quartile":"other";this.currentAd.trackingUrls.filter(r=>r.event&&r.event.toLowerCase()===e.toLowerCase()).forEach(r=>{var a,n;(n=(a=this.trackingConfig)==null?void 0:a.customTracker)==null||n.call(a,e,r.url),qi(i,this.trackingConfig)&&this.trackingManager.trackUrl(r.url)})}fireErrorTracking(e){!this.currentAd||!this.currentAd.errorUrls||this.currentAd.errorUrls.forEach(t=>{const i=t.replace(/\[ERRORCODE\]/g,String(e));this.trackingManager.trackUrl(i)})}setupAdVideoListeners(e){const t=this.manager;if(!t)return;const i=()=>{t.transitionTo(w.PLAYING)},s=()=>{t.transitionTo(w.PAUSED)},r=()=>{t.transitionTo(w.BUFFERING),this.bufferingTimeoutId=setTimeout(()=>{this.handlePlaybackError("Stalled ad buffering timeout")},1e4)},a=()=>{var d,h,u,f;t.transitionTo(w.PLAYING),this.bufferingTimeoutId&&(clearTimeout(this.bufferingTimeoutId),this.bufferingTimeoutId=null),this.impressionFired||(this.impressionFired=!0,(h=(d=this.currentAd)==null?void 0:d.impressionUrls)==null||h.forEach(p=>{var g,m;(m=(g=this.trackingConfig)==null?void 0:g.customTracker)==null||m.call(g,"impression",p),qi("impression",this.trackingConfig)&&this.trackingManager.trackUrl(p)}),this.fireTrackingEvent("creativeView"),(u=this.currentAd)!=null&&u.adVerifications&&this.currentAd.adVerifications.length>0&&((f=this.context)==null||f.controller.emit("adverificationready",{ad:this.currentAd,verifications:this.currentAd.adVerifications})))},n=()=>{var m,v,y,b,S,T;const d=e.currentTime,h=e.duration||((m=this.currentAd)==null?void 0:m.duration)||0,u=Math.max(0,h-d),f=this.canSkipAd,{canSkip:p,skipAvailableAt:g}=ir({mode:this.skipModeConfig,configSkipOffset:this.skipOffsetConfig,xmlSkippable:(v=this.currentAd)==null?void 0:v.skippable,xmlSkipOffset:(y=this.currentAd)==null?void 0:y.skipOffset,currentTime:d});this.canSkipAd=p,p&&!f&&this.currentAd&&((b=this.context)==null||b.controller.emit("skipavailable",{ad:this.currentAd})),(S=this.context)==null||S.controller.updateStatePublic({canSkipAd:p,skipAvailableAt:g,adCurrentTime:d,adRemainingTime:u,adDuration:h}),this.checkMilestones(d,h),(T=this.context)==null||T.controller.emit("adtimeupdate",{currentTime:d,duration:h,remainingTime:u})},l=()=>{this.handleAdComplete()},o=()=>{this.handlePlaybackError("Native video element playback error")};e.addEventListener("play",i),e.addEventListener("pause",s),e.addEventListener("waiting",r),e.addEventListener("playing",a),e.addEventListener("timeupdate",n),e.addEventListener("ended",l),e.addEventListener("error",o),this.cleanupListeners=()=>{e.removeEventListener("play",i),e.removeEventListener("pause",s),e.removeEventListener("waiting",r),e.removeEventListener("playing",a),e.removeEventListener("timeupdate",n),e.removeEventListener("ended",l),e.removeEventListener("error",o),this.bufferingTimeoutId&&(clearTimeout(this.bufferingTimeoutId),this.bufferingTimeoutId=null)}}checkMilestones(e,t){var s,r,a,n,l,o,d,h;if(t<=0)return;const i=e/t;i>=0&&!this.milestones.start&&(this.milestones.start=!0,this.fireTrackingEvent("start"),(s=this.context)==null||s.controller.emit("admilestone",{milestone:"start"})),i>=.25&&!this.milestones.firstQuartile&&(this.milestones.firstQuartile=!0,this.fireTrackingEvent("firstQuartile"),(r=this.context)==null||r.controller.emit("admilestone",{milestone:"firstQuartile"}),this.currentAd&&((a=this.context)==null||a.controller.emit("adfirstquartile",{ad:this.currentAd}))),i>=.5&&!this.milestones.midpoint&&(this.milestones.midpoint=!0,this.fireTrackingEvent("midpoint"),(n=this.context)==null||n.controller.emit("admilestone",{milestone:"midpoint"}),this.currentAd&&((l=this.context)==null||l.controller.emit("admidpoint",{ad:this.currentAd}))),i>=.75&&!this.milestones.thirdQuartile&&(this.milestones.thirdQuartile=!0,this.fireTrackingEvent("thirdQuartile"),(o=this.context)==null||o.controller.emit("admilestone",{milestone:"thirdQuartile"}),this.currentAd&&((d=this.context)==null||d.controller.emit("adthirdquartile",{ad:this.currentAd}))),i>=.98&&!this.milestones.complete&&(this.milestones.complete=!0,this.fireTrackingEvent("complete"),(h=this.context)==null||h.controller.emit("admilestone",{milestone:"complete"}))}setupClickThrough(e){const t=()=>{var i,s,r;(i=this.currentAd)!=null&&i.clickThroughUrl&&((s=this.currentAd.clickTrackingUrls)==null||s.forEach(a=>this.trackingManager.trackUrl(a)),(r=this.context)==null||r.controller.emit("adclick",{clickUrl:this.currentAd.clickThroughUrl}))};e.addEventListener("click",t),this.cleanupClick=()=>{e.removeEventListener("click",t)}}handleAdComplete(){var e,t,i;this.fireTrackingEvent("complete"),this.currentAdBreak&&this.currentAdBreak.ads&&this.currentAdIndex<this.currentAdBreak.ads.length-1?(this.currentAdIndex++,this.currentAd=this.currentAdBreak.ads[this.currentAdIndex],(e=this.manager)==null||e.transitionTo(w.ENDED),this.currentAd.linear?this.playCurrentAdInPod():this.manager&&this.manager.isHtmlOverlayCreative(this.currentAd)&&this.manager.playHtmlOverlay(this.currentAd)):(this.cleanupPlaybackResources(),(t=this.manager)==null||t.transitionTo(w.ENDED),(i=this.manager)==null||i.endAdBreak())}handlePlaybackError(e){var i;console.error(`[VastProvider] Playback error: ${e}`),this.fireErrorTracking(400),this.cleanupPlaybackResources();const t={type:ie.UNKNOWN,code:400,message:e};(i=this.manager)==null||i.triggerAdError(t)}cleanupPlaybackResources(){if(this.simidRuntime){try{this.simidRuntime.destroyRuntime()}catch{}this.simidRuntime=null}this.cleanupListeners&&(this.cleanupListeners(),this.cleanupListeners=null),this.cleanupClick&&(this.cleanupClick(),this.cleanupClick=null),this.adVideoElement&&(this.renderingStrategy==="dedicated"?this.adVideoElement.parentNode&&this.adVideoElement.parentNode.removeChild(this.adVideoElement):(this.adVideoElement.src=this.originalSource,this.adVideoElement.load()),this.adVideoElement=null)}skipAd(){var e,t,i;this.fireTrackingEvent("skip"),this.cleanupPlaybackResources(),this.currentAdBreak&&this.currentAdBreak.ads&&this.currentAdIndex<this.currentAdBreak.ads.length-1?(this.currentAdIndex++,this.currentAd=this.currentAdBreak.ads[this.currentAdIndex],(e=this.manager)==null||e.transitionTo(w.SKIPPING),this.currentAd.linear?this.playCurrentAdInPod():this.manager&&this.manager.isHtmlOverlayCreative(this.currentAd)&&this.manager.playHtmlOverlay(this.currentAd)):((t=this.manager)==null||t.transitionTo(w.SKIPPING),(i=this.manager)==null||i.endAdBreak())}onSourceLoaded(e){this.reset()}reset(){this.cleanupPlaybackResources(),this.trackingManager.destroy(),this.cache.clear(),this.currentAd=null,this.currentAdBreak=null,this.currentAdIndex=0,this.canSkipAd=!1,this.impressionFired=!1,this.milestones={start:!1,firstQuartile:!1,midpoint:!1,thirdQuartile:!1,complete:!1}}destroy(){this.reset(),this.context=null,this.manager=null}}class st{constructor(e,t,i,s=!1){this.controller=e,this.adContainer=t,this.isExternalSlot=s,this.state="idle",this.containerElement=null,this.contentWrapper=null,this.iframeElement=null,this.currentAd=null,this.destroyController=new AbortController,this.resizeObserver=null,this.firedEvents=new Set,this.durationTimer=null,this.closeDelayTimer=null,this.intrinsicWidth=480,this.intrinsicHeight=70,this.renderStartTime=0,this.renderDuration=0,this.creationTime=0,this.clickCount=0,this.interactionCount=0,this.errors=[],this.trackingManager=i||new _t,this.creationTime=Date.now()}getLifecycleState(){return this.state}getDiagnostics(){return{overlayActive:this.state!=="idle"&&this.state!=="destroyed",overlayVisible:this.state==="visible",renderMode:this.getRenderMode(),renderDurationMs:this.renderDuration,overlayLifetimeMs:this.state!=="destroyed"?Date.now()-this.creationTime:0,clickCount:this.clickCount,interactionCount:this.interactionCount,trackingStatus:this.trackingManager.getDiagnostics(),errors:[...this.errors]}}getRenderMode(){return this.currentAd?this.currentAd.imageUrl?"image":this.currentAd.useIframe||this.currentAd.htmlUrl?"iframe":this.currentAd.htmlTemplateId?"template":this.currentAd.htmlContent?"string":"dom":"unknown"}async loadAd(e){if(typeof window>"u"||typeof document>"u")return!1;this.state="loading",this.currentAd={...e},this.renderStartTime=Date.now(),this.controller.emit("htmloverlayavailable",{adId:e.id});try{await this.resolveVastTagIfNecessary(this.currentAd),this.intrinsicWidth=this.currentAd.width||480,this.intrinsicHeight=this.currentAd.height||70,this.containerElement=document.createElement("div"),this.containerElement.className="html-overlay-container",this.contentWrapper=document.createElement("div"),this.contentWrapper.className="html-overlay-content",this.contentWrapper.style.width="100%",this.contentWrapper.style.height="100%",this.contentWrapper.style.position="relative",this.contentWrapper.style.overflow="hidden",this.contentWrapper.style.borderRadius="4px",this.contentWrapper.style.boxShadow="0 4px 12px rgba(0, 0, 0, 0.4)",this.containerElement.appendChild(this.contentWrapper);let t=null;if(this.currentAd.externalSlot){if(t=this.resolveTargetSlot(this.currentAd),!t)throw new Error(`Target external slot "${this.currentAd.externalSlot}" not found in DOM.`)}else t=this.adContainer;if(t.appendChild(this.containerElement),this.currentAd.imageUrl)await this.renderImage(this.currentAd,this.contentWrapper);else if(this.currentAd.useIframe||this.currentAd.htmlUrl)await this.renderIframe(this.currentAd,this.contentWrapper);else if(this.currentAd.htmlTemplateId)this.renderTemplate(this.currentAd,this.contentWrapper);else if(this.currentAd.htmlContent)this.renderHtmlString(this.currentAd,this.contentWrapper);else throw new Error("Unsupported HTML overlay content type: missing content, template, url, or image");return this.applyStylesAndPositioning(this.currentAd,this.containerElement),this.recalculateLayout(),this.setupCloseButton(),this.setupInteractionHandlers(),this.setupKeyboardAccessibility(),typeof ResizeObserver<"u"&&(this.resizeObserver=new ResizeObserver(()=>{this.recalculateLayout()}),this.resizeObserver.observe(t)),this.renderDuration=Date.now()-this.renderStartTime,this.state="rendered",this.controller.emit("htmloverlayloaded",{adId:e.id}),!0}catch(t){const i=t instanceof Error?t.message:"Rendering overlay failed";return this.handleError(i),!1}}resolveTargetSlot(e){var t;return e.externalSlot?typeof e.externalSlot!="string"?e.externalSlot:typeof document>"u"?null:document.querySelector(e.externalSlot)||((t=this.adContainer.shadowRoot)==null?void 0:t.querySelector(e.externalSlot)):null}async resolveVastTagIfNecessary(e){if(!e.htmlUrl)return;const t=e.htmlUrl.trim(),i=t.startsWith("<"),s=!i&&(t.includes("output=vast")||t.includes("gampad/ads")||t.endsWith(".xml"));if(!(!i&&!s))try{let r;if(i)r=t;else{const l=await fetch(t,{credentials:"same-origin"});if(!l.ok)return;r=await l.text()}if(!r||!r.includes("<VAST"))return;const a=tr(r);if(!a)return;const n=e;a.imageUrl?(n.imageUrl=a.imageUrl,n.htmlUrl=void 0,n.useIframe=!1):a.htmlUrl?(n.htmlUrl=a.htmlUrl,n.useIframe=!0):a.htmlContent&&(n.htmlContent=a.htmlContent,n.htmlUrl=void 0,n.useIframe=!1),a.width&&(n.width=a.width),a.height&&(n.height=a.height),a.clickThroughUrl&&!n.clickThroughUrl&&(n.clickThroughUrl=a.clickThroughUrl),a.trackingUrls&&a.trackingUrls.length>0&&(n.trackingUrls=[...n.trackingUrls||[],...a.trackingUrls])}catch{}}recalculateLayout(){var m,v,y,b,S;if(!this.containerElement||!this.adContainer||this.isExternalSlot)return;const e=this.adContainer.clientWidth||640,t=this.adContainer.clientHeight||360,i=(m=this.currentAd)!=null&&m.maxWidth?Math.min(e,this.currentAd.maxWidth):e*.8,s=(v=this.currentAd)!=null&&v.maxHeight?Math.min(t,this.currentAd.maxHeight):t*.18,r=this.getRenderMode(),a=!!((y=this.currentAd)!=null&&y.width)&&!!((b=this.currentAd)!=null&&b.height),n=()=>{this.containerElement.style.maxWidth="",this.containerElement.style.maxHeight="",this.containerElement.style.width=`${Math.round(i)}px`,this.containerElement.style.height=`${Math.round(s)}px`};if(r==="iframe"&&!a){n();return}if((r==="string"||r==="template")&&!a){this.containerElement.style.width="auto",this.containerElement.style.height="auto",this.containerElement.style.maxWidth=`${Math.round(i)}px`,this.containerElement.style.maxHeight=`${Math.round(s)}px`;const T=this.containerElement.getBoundingClientRect();(T.width<4||T.height<4)&&n();return}this.containerElement.style.maxWidth="",this.containerElement.style.maxHeight="";const l=this.intrinsicWidth||480,o=this.intrinsicHeight||70,d=Math.min(i,l),h=Math.min(s,o),f=((S=this.currentAd)==null?void 0:S.responsive)!==!1?Math.min(1,d/l,h/o):1,p=Math.round(l*f),g=Math.round(o*f);this.containerElement.style.width=`${p}px`,this.containerElement.style.height=`${g}px`}show(){var e;this.state!=="destroyed"&&(this.containerElement&&(this.containerElement.style.display="block",this.recalculateLayout()),this.state="visible",this.controller.emit("htmloverlayshown",{adId:(e=this.currentAd)==null?void 0:e.id}),this.currentAd&&(this.fireTrackingEvents("impression"),this.fireTrackingEvents("creativeView"),this.scheduleDurationTimer()))}hide(){var e;this.state!=="destroyed"&&(this.clearDurationTimer(),this.containerElement&&(this.containerElement.style.display="none"),this.state="hidden",this.controller.emit("htmloverlayhidden",{adId:(e=this.currentAd)==null?void 0:e.id}))}close(){var t;if(this.state==="destroyed")return;const e=(t=this.currentAd)==null?void 0:t.id;this.fireTrackingEvents("close"),this.destroy(),this.controller.emit("htmloverlayclosed",{adId:e})}updateOverlay(e){!this.currentAd||this.state==="destroyed"||(this.currentAd={...this.currentAd,...e},e.width!==void 0&&(this.intrinsicWidth=e.width),e.height!==void 0&&(this.intrinsicHeight=e.height),this.containerElement&&(this.applyStylesAndPositioning(this.currentAd,this.containerElement),this.recalculateLayout()),this.controller.emit("htmloverlayupdated",{adId:this.currentAd.id}))}destroy(){this.state!=="destroyed"&&(this.state="destroyed",this.clearDurationTimer(),this.clearCloseDelayTimer(),this.destroyController.abort(),this.resizeObserver&&(this.resizeObserver.disconnect(),this.resizeObserver=null),this.iframeElement&&(this.iframeElement.src="about:blank",this.iframeElement=null),this.containerElement&&(this.containerElement.parentNode&&this.containerElement.parentNode.removeChild(this.containerElement),this.containerElement=null),this.contentWrapper=null,this.currentAd=null,this.firedEvents.clear())}scheduleDurationTimer(){this.clearDurationTimer(),this.currentAd&&this.currentAd.duration>0&&(this.durationTimer=setTimeout(()=>{this.handleDurationComplete()},this.currentAd.duration*1e3))}handleDurationComplete(){var e;this.state!=="destroyed"&&(this.fireTrackingEvents("complete"),this.controller.emit("htmloverlaycompleted",{adId:(e=this.currentAd)==null?void 0:e.id}),this.close())}clearDurationTimer(){this.durationTimer&&(clearTimeout(this.durationTimer),this.durationTimer=null)}clearCloseDelayTimer(){this.closeDelayTimer&&(clearTimeout(this.closeDelayTimer),this.closeDelayTimer=null)}renderImage(e,t){return new Promise((i,s)=>{if(!e.imageUrl){s(new Error("Missing image URL for image rendering"));return}const r=document.createElement("img");r.alt=e.title||"Advertisement",r.style.width="100%",r.style.height="100%",r.style.objectFit="contain",r.style.display="block";const a=setTimeout(()=>{s(new Error("HTML overlay image creative load timeout"))},5e3);r.onload=()=>{clearTimeout(a);const n=e;!n.width&&r.naturalWidth&&(n.width=r.naturalWidth),!n.height&&r.naturalHeight&&(n.height=r.naturalHeight),this.intrinsicWidth=e.width||r.naturalWidth||480,this.intrinsicHeight=e.height||r.naturalHeight||70,i()},r.onerror=()=>{clearTimeout(a),s(new Error("HTML overlay image creative failed to load"))},r.src=e.imageUrl,t.appendChild(r)})}renderIframe(e,t){return new Promise((i,s)=>{this.iframeElement=document.createElement("iframe");const a=e.iframeSandbox||"allow-scripts allow-popups allow-same-origin allow-forms",n=Li(a,{srcUrl:e.htmlUrl||null,isSrcDoc:!e.htmlUrl&&!!e.htmlContent});if(this.iframeElement.setAttribute("sandbox",n),this.iframeElement.setAttribute("referrerpolicy","no-referrer"),this.iframeElement.setAttribute("scrolling","no"),this.iframeElement.style.width="100%",this.iframeElement.style.height="100%",this.iframeElement.style.border="none",this.iframeElement.style.overflow="hidden",this.iframeElement.style.backgroundColor="transparent",e.htmlUrl&&e.trustedOrigins&&e.trustedOrigins.length>0)try{const o=new URL(e.htmlUrl,window.location.href).origin,d=new URL(o).hostname;if(!e.trustedOrigins.some(u=>u==="*"||u===o||u===d)){s(new Error(`HTML overlay URL origin "${o}" is not in trusted origins.`));return}}catch{}const l=setTimeout(()=>{s(new Error("HTML overlay iframe load timeout"))},8e3);if(this.iframeElement.addEventListener("load",()=>{clearTimeout(l),i()},{once:!0}),this.iframeElement.addEventListener("error",()=>{clearTimeout(l),s(new Error("HTML overlay iframe load failed"))},{once:!0}),e.htmlUrl)this.iframeElement.src=e.htmlUrl;else if(e.htmlContent)this.iframeElement.srcdoc=e.htmlContent;else{clearTimeout(l),s(new Error("HTML url or content is required for iframe rendering"));return}t.appendChild(this.iframeElement)})}renderTemplate(e,t){if(!e.htmlTemplateId)return;const i=document.getElementById(e.htmlTemplateId);if(!i)throw new Error(`Template element not found with ID: ${e.htmlTemplateId}`);const s=document.importNode(i.content,!0);t.appendChild(s)}renderHtmlString(e,t){if(!e.htmlContent)return;const i=document.createElement("div");i.style.width="100%",i.style.height="100%",e.sanitizeHtml?i.innerHTML=e.sanitizeHtml(e.htmlContent):i.innerHTML=e.htmlContent,t.appendChild(i)}setupCloseButton(){if(!this.containerElement||!this.currentAd)return;const e=this.currentAd.closeButton;if(e===!1)return;const t=document.createElement("button");t.className=typeof e=="object"&&e.className?`html-overlay-close-btn ${e.className}`:"html-overlay-close-btn";const i=typeof e=="object"&&e.label?e.label:"Close Advertisement";t.setAttribute("aria-label",i),t.innerText=typeof e=="object"&&e.label?e.label:"×",t.style.position="absolute",t.style.top="-10px",t.style.right="-10px",t.style.zIndex="1006",t.style.cursor="pointer",t.style.background="rgba(0, 0, 0, 0.85)",t.style.color="#ffffff",t.style.border="2px solid rgba(255, 255, 255, 0.8)",t.style.borderRadius="50%",t.style.width="24px",t.style.height="24px",t.style.fontSize="14px",t.style.lineHeight="20px",t.style.textAlign="center",t.style.padding="0",t.style.boxShadow="0 2px 6px rgba(0,0,0,0.5)",t.style.pointerEvents="auto",typeof e=="object"&&e.styleOverrides&&Object.entries(e.styleOverrides).forEach(([r,a])=>{t.style[r]=String(a)});const s=this.currentAd.closeDelay??(typeof e=="object"?e.delaySeconds:0)??0;s>0&&(t.style.display="none",this.closeDelayTimer=setTimeout(()=>{t&&this.state!=="destroyed"&&(t.style.display="block")},s*1e3)),t.addEventListener("click",r=>{r.stopPropagation(),this.close()},{signal:this.destroyController.signal}),this.containerElement.appendChild(t)}setupKeyboardAccessibility(){window.addEventListener("keydown",e=>{e.key==="Escape"&&this.state==="visible"&&this.close()},{signal:this.destroyController.signal})}setupInteractionHandlers(){this.contentWrapper&&(this.contentWrapper.addEventListener("mouseenter",()=>{this.interactionCount++,this.fireTrackingEvents("creativeView")},{signal:this.destroyController.signal}),this.contentWrapper.addEventListener("focusin",()=>{this.interactionCount++},{signal:this.destroyController.signal}),this.contentWrapper.addEventListener("click",()=>{var e,t;if(this.clickCount++,this.controller.emit("htmloverlayclick",{adId:(e=this.currentAd)==null?void 0:e.id}),this.fireTrackingEvents("click"),(t=this.currentAd)!=null&&t.clickThroughUrl)try{window.open(this.currentAd.clickThroughUrl,"_blank","noopener,noreferrer")}catch(i){const s=i instanceof Error?i.message:String(i);this.errors.push(`Click-through navigation failed: ${s}`)}},{signal:this.destroyController.signal}))}applyStylesAndPositioning(e,t){var r;if(this.isExternalSlot||!!e.externalSlot){t.style.position="relative",t.style.margin="0 auto",t.style.display||(t.style.display="none"),t.style.pointerEvents=e.pointerEvents||"auto";return}switch(t.style.top="",t.style.bottom="",t.style.left="",t.style.right="",t.style.transform="",t.style.position="absolute",t.style.zIndex=String(((r=e.overlayStyle)==null?void 0:r.zIndex)||e.zIndex||"1002"),t.style.overflow="visible",t.style.opacity=String(e.opacity!==void 0?e.opacity:1),t.style.pointerEvents=e.pointerEvents||"auto",t.style.display||(t.style.display="none"),e.margin&&(t.style.margin=e.margin),e.padding&&(t.style.padding=e.padding),e.position||"bottom"){case"top":t.style.top="10px",t.style.left="50%",t.style.transform="translateX(-50%)";break;case"left":t.style.left="10px",t.style.top="50%",t.style.transform="translateY(-50%)";break;case"right":t.style.right="10px",t.style.top="50%",t.style.transform="translateY(-50%)";break;case"center":t.style.top="50%",t.style.left="50%",t.style.transform="translate(-50%, -50%)";break;case"bottom":default:t.style.bottom="var(--player-overlay-safe-bottom, calc(20px + 64px + 12px))",t.style.left="50%",t.style.transform="translateX(-50%)";break}e.overlayStyle&&Object.entries(e.overlayStyle).forEach(([a,n])=>{t.style[a]=String(n)})}fireTrackingEvents(e){const t=e.toLowerCase();if(["impression","creativeview","close","complete"].includes(t)){if(this.firedEvents.has(t))return;this.firedEvents.add(t)}if(!this.currentAd||!this.currentAd.trackingUrls)return;this.currentAd.trackingUrls.filter(r=>r.event&&r.event.toLowerCase()===t).forEach(r=>this.trackingManager.trackUrl(r.url))}handleError(e){this.errors.push(e),this.controller.emit("htmloverlayerror",{message:e}),this.destroy()}}function rr(c,e){const t=new Set,i=[];for(const s of e){const r=s.width*s.height;let a=-1,n=1/0;c.forEach((l,o)=>{if(t.has(o))return;const d=l.width??0,h=l.height??0,u=Math.abs(d*h-r);u<n&&(n=u,a=o)}),a>=0&&(t.add(a),i.push({slot:s,companion:c[a]}))}return i}const ar={[w.IDLE]:[w.REQUESTING,w.LOADED,w.PLAYING,w.ERROR,w.CONTENT_RESUMING],[w.REQUESTING]:[w.LOADED,w.PLAYING,w.ERROR,w.CONTENT_RESUMING,w.IDLE],[w.LOADED]:[w.REQUESTING,w.PLAYING,w.PAUSED,w.BUFFERING,w.ERROR,w.CONTENT_RESUMING,w.IDLE],[w.PLAYING]:[w.REQUESTING,w.PAUSED,w.BUFFERING,w.SKIPPING,w.ENDED,w.ERROR,w.CONTENT_RESUMING,w.IDLE],[w.PAUSED]:[w.REQUESTING,w.PLAYING,w.BUFFERING,w.SKIPPING,w.ENDED,w.ERROR,w.CONTENT_RESUMING,w.IDLE],[w.BUFFERING]:[w.REQUESTING,w.PLAYING,w.PAUSED,w.ENDED,w.ERROR,w.CONTENT_RESUMING,w.IDLE],[w.SKIPPING]:[w.REQUESTING,w.PLAYING,w.LOADED,w.CONTENT_RESUMING,w.ERROR,w.IDLE],[w.ENDED]:[w.REQUESTING,w.PLAYING,w.LOADED,w.CONTENT_RESUMING,w.ERROR,w.IDLE],[w.ERROR]:[w.REQUESTING,w.CONTENT_RESUMING,w.IDLE],[w.CONTENT_RESUMING]:[w.REQUESTING,w.IDLE]};class nr{constructor(){this.providers=new Map,this.activeProviderName=null}registerProvider(e,t){this.providers.set(e,t)}getProvider(e){return this.providers.get(e)}unregisterProvider(e){this.activeProviderName===e&&(this.activeProviderName=null),this.providers.delete(e)}selectProvider(e){this.activeProviderName=e}getActiveProvider(){return this.activeProviderName?this.providers.get(this.activeProviderName):void 0}getActiveProviderName(){return this.activeProviderName}getCapabilities(e){const t=this.providers.get(e);return t?t.capabilities:null}onSourceLoaded(e){this.providers.forEach(t=>{try{typeof t.onSourceLoaded=="function"&&t.onSourceLoaded(e)}catch(i){console.error("[ProviderManager] Error running onSourceLoaded for provider:",t.name,i)}})}destroy(){this.providers.forEach(e=>{try{e.destroy()}catch(t){console.error("[ProviderManager] Error destroying provider:",t)}}),this.providers.clear(),this.activeProviderName=null}}class or{constructor(){this.snapshot=null}capture(e){const t=e.getState();this.snapshot={currentTime:t.currentTime,paused:!t.isPlaying,playbackRate:t.playbackRate,muted:t.isMuted,volume:t.volume,activeAudioTrack:t.activeAudioTrack,activeSubtitleTrackId:t.activeSubtitleTrackId,activeQuality:t.qualities.indexOf(t.activeQuality),isFullscreen:t.isFullscreen,pictureInPicture:t.pictureInPicture,isAtLiveEdge:t.isAtLiveEdge,liveLatency:t.liveLatency}}restore(e){if(!this.snapshot)return;const t=this.snapshot;try{e.setVolume(t.volume),e.setMuted(t.muted),e.setPlaybackRate(t.playbackRate),t.activeSubtitleTrackId!==null&&e.setSubtitleTrack(t.activeSubtitleTrackId),t.activeAudioTrack!==-1&&e.setAudioTrack(t.activeAudioTrack);const i=e.getState(),s=i.qualities.indexOf(i.activeQuality);t.activeQuality!==-1&&t.activeQuality!==s&&e.setQuality(t.activeQuality),!i.isLive&&Math.abs(i.currentTime-t.currentTime)>.35&&e.seek(t.currentTime),t.isFullscreen&&!e.getState().isFullscreen&&e.toggleFullscreen(),t.pictureInPicture&&!e.getState().pictureInPicture&&e.enterPictureInPicture().catch(()=>{});try{const r=e.play();r&&typeof r.catch=="function"&&r.catch(a=>{console.warn("[ContentSnapshot] Failed to resume content playback:",a)})}catch(r){console.warn("[ContentSnapshot] Failed to trigger content playback:",r)}}catch(i){console.error("[ContentSnapshot] Error restoring content state:",i)}finally{this.snapshot=null}}clear(){this.snapshot=null}exists(){return this.snapshot!==null}}class Ki{constructor(){this.activeBreak=null,this.pendingBreaks=[],this.completedBreaks=[],this.cancelledBreaks=[]}registerBreak(e){this.pendingBreaks.push(e),this.pendingBreaks.sort((t,i)=>t.timeOffset-i.timeOffset)}activateBreak(e){this.activeBreak=e,this.pendingBreaks=this.pendingBreaks.filter(t=>t.id!==e.id)}completeBreak(){this.activeBreak&&(this.completedBreaks.push(this.activeBreak),this.activeBreak=null)}cancelBreak(e){var t;if(((t=this.activeBreak)==null?void 0:t.id)===e)this.cancelledBreaks.push(this.activeBreak),this.activeBreak=null;else{const i=this.pendingBreaks.findIndex(s=>s.id===e);i!==-1&&(this.cancelledBreaks.push(this.pendingBreaks[i]),this.pendingBreaks.splice(i,1))}}clearBreaks(){this.activeBreak=null,this.pendingBreaks=[],this.completedBreaks=[],this.cancelledBreaks=[]}getActiveBreak(){return this.activeBreak}getPendingBreaks(){return this.pendingBreaks}getCompletedBreaks(){return this.completedBreaks}getCancelledBreaks(){return this.cancelledBreaks}}class lr{constructor(){this.activeToken=0}generateToken(){return this.activeToken++,this.activeToken}isValid(e){return e===this.activeToken}invalidateAll(){this.activeToken++}}class cr{constructor(){this.timers=new Map}set(e,t,i){this.clear(e);const s=setTimeout(()=>{this.timers.delete(e),t()},i);this.timers.set(e,s)}clear(e){const t=this.timers.get(e);t&&(clearTimeout(t),this.timers.delete(e))}clearAll(){this.timers.forEach(e=>clearTimeout(e)),this.timers.clear()}}class Wi{constructor(){this.name="ads-manager",this.state=w.IDLE,this.providerManager=new nr,this.contentSnapshot=new or,this.adBreakManager=new Ki,this.asyncGuard=new lr,this.timeoutManager=new cr,this.htmlOverlayRenderer=null,this.companionRenderers=[],this.concurrentOverlayRenderers=[],this.adContainer=null,this.isInterceptionActive=!1,this.currentAd=null,this.requestedCount=0,this.playedCount=0,this.completedCount=0,this.skippedCount=0,this.errorCount=0,this.recoveryCount=0,this.timeoutCount=0,this.cancelledCount=0,this.providerFailuresCount=0,this.activeOperations=0}install(e){this.controller=e,this.controller.registerPlaybackInterceptor(this),this.controller.on("htmloverlayclosed",()=>{this.currentAd&&this.isHtmlOverlayCreative(this.currentAd)&&this.endAdBreak()}),this.updatePlayerState(),this.triggerLifecycleHook("onProviderLoaded")}destroy(){if(this.triggerLifecycleHook("onDestroy"),this.timeoutManager.clearAll(),this.asyncGuard.invalidateAll(),this.clearCompanions(),this.clearConcurrentOverlays(),this.htmlOverlayRenderer){try{this.htmlOverlayRenderer.destroy()}catch{}this.htmlOverlayRenderer=null}this.controller&&this.controller.unregisterPlaybackInterceptor(this),this.providerManager.destroy(),this.adBreakManager.clearBreaks(),this.contentSnapshot.clear(),this.currentAd=null,this.state=w.IDLE,this.isInterceptionActive=!1}getProviderManager(){return this.providerManager}getAdBreakManager(){return this.adBreakManager}getAdState(){return this.state}getSavedContentSnapshot(){return this.contentSnapshot}transitionTo(e){if(this.state===e)return!0;if(e===w.IDLE){const i=this.state;return this.state=e,this.isInterceptionActive=!1,this.updatePlayerState(),this.triggerLifecycleHook("onStateChanged",i,e),!0}const t=ar[this.state];if(t&&t.includes(e)){const i=this.state;return this.state=e,this.updateDiagnosticsMetrics(i,e),this.updatePlayerState(),this.dispatchStateEvents(i,e),this.triggerLifecycleHook("onStateChanged",i,e),!0}else return console.warn(`[AdsManager] Rejected state transition: ${this.state} -> ${e}`),!1}updateDiagnosticsMetrics(e,t){t===w.REQUESTING?this.requestedCount++:t===w.PLAYING&&e!==w.PAUSED&&e!==w.BUFFERING?this.playedCount++:t===w.ENDED?this.completedCount++:t===w.SKIPPING?this.skippedCount++:t===w.ERROR&&this.errorCount++}dispatchStateEvents(e,t){var i,s;if(this.controller)switch(t){case w.REQUESTING:this.controller.emit("adloadstart",{adTagUrl:((s=(i=this.controller.config)==null?void 0:i.ads)==null?void 0:s.tagUrl)??""});break;case w.LOADED:this.currentAd&&this.controller.emit("adloaded",{ad:this.currentAd});break;case w.PLAYING:e===w.PAUSED?this.currentAd&&this.controller.emit("adresume",{ad:this.currentAd}):this.currentAd&&this.controller.emit("adstart",{ad:this.currentAd});break;case w.PAUSED:this.currentAd&&this.controller.emit("adpause",{ad:this.currentAd});break;case w.SKIPPING:this.currentAd&&this.controller.emit("adskip",{ad:this.currentAd});break;case w.ENDED:this.currentAd&&this.controller.emit("adcomplete",{ad:this.currentAd});break;case w.ERROR:break}}startAdBreak(e,t){if(this.controller.getState().sourceType==="embed"){this.triggerAdError({type:ie.CONFIGURATION,code:900,message:"VAST ads are not supported for embed (YouTube/Vimeo) sources."});return}this.activeOperations++,this.triggerLifecycleHook("onBreakStarted",e),this.adBreakManager.activateBreak(e);const i=e.ads[0],s=i&&this.isHtmlOverlayCreative(i);if(!!i&&!i.linear&&!s&&!!i.companions&&i.companions.length>0)this.isInterceptionActive=!1,this.currentAd=i,this.controller.emit("adbreakstart",{adId:e.id,duration:e.duration}),this.transitionTo(w.REQUESTING),this.transitionTo(w.LOADED),this.showCompanions(i.companions),this.adBreakManager.completeBreak(),this.controller.emit("adbreakend"),this.transitionTo(w.IDLE),this.activeOperations=Math.max(0,this.activeOperations-1);else if(s)this.isInterceptionActive=!1,this.currentAd=i,this.controller.emit("adbreakstart",{adId:e.id,duration:e.duration}),this.transitionTo(w.REQUESTING),this.playHtmlOverlay(i);else{if(this.isInterceptionActive=!0,this.contentSnapshot.capture(this.controller),this.triggerLifecycleHook("onContentPaused"),!(t!=null&&t.skipVideoOwnership)){this.isInterceptionActive=!1;try{this.controller.getVideoElement().pause()}catch(a){console.error("[AdsManager] Pause main content error:",a)}this.isInterceptionActive=!0}this.controller.emit("adbreakstart",{adId:e.id,duration:e.duration}),this.transitionTo(w.REQUESTING)}}skipAd(){const e=this.providerManager.getActiveProvider();if(e)try{typeof e.skipAd=="function"?e.skipAd():typeof e.destroy=="function"&&e.destroy()}catch(t){console.error("[AdsManager] Error skipping provider ad:",t)}this.transitionTo(w.SKIPPING),this.controller.emit("adskip"),this.endAdBreak()}endAdBreak(){this.transitionTo(w.CONTENT_RESUMING),this.triggerLifecycleHook("onBreakCompleted"),this.clearCompanions(),this.clearConcurrentOverlays(),this.adBreakManager.completeBreak(),this.contentSnapshot.exists()&&(this.isInterceptionActive=!1,this.contentSnapshot.restore(this.controller),this.triggerLifecycleHook("onContentResumed")),this.isInterceptionActive=!1,this.controller.emit("adbreakend"),this.transitionTo(w.IDLE),this.activeOperations=Math.max(0,this.activeOperations-1)}recover(e){if(this.recoveryCount++,console.warn(`[AdsManager] Entering recovery path due to: ${e}`),this.triggerLifecycleHook("onRecovery",e),this.timeoutManager.clearAll(),this.asyncGuard.invalidateAll(),this.htmlOverlayRenderer){try{this.htmlOverlayRenderer.destroy()}catch{}this.htmlOverlayRenderer=null}this.currentAd=null,this.endAdBreak()}triggerAdError(e){this.errorCount++,this.providerFailuresCount++,this.controller.emit("aderror",{error:e}),this.recover(`aderror: ${e.message}`)}scheduleTimeout(e,t,i){const s=this.asyncGuard.generateToken();this.timeoutManager.set(e,()=>{this.asyncGuard.isValid(s)&&(this.timeoutCount++,console.warn(`[TimeoutManager] Expired operation timeout: "${e}"`),this.recover(i))},t)}cancelTimeout(e){this.timeoutManager.clear(e)}setAdContainer(e){this.adContainer=e}getAdContainer(){var e,t;return this.adContainer||((t=(e=this.controller)==null?void 0:e.getVideoElement())==null?void 0:t.parentElement)||null}createProviderContext(e){var i;const t=e||this.getAdContainer()||(typeof document<"u"?document.body:null);return t&&t instanceof HTMLElement&&(this.adContainer=t),{videoElement:this.controller.getVideoElement(),adContainer:this.adContainer||t,controller:this.controller,config:((i=this.controller.config)==null?void 0:i.ads)||{}}}setCurrentAd(e){const t=this.currentAd!==e;this.currentAd=e,t&&e&&this.controller.updateStatePublic({adCurrentTime:0,adRemainingTime:e.duration,adDuration:e.duration}),this.updatePlayerState()}updatePlayerState(){var n,l,o;if(!this.controller)return;const e=this.currentAd?this.currentAd.linear!==!1:!0,t=(this.state===w.REQUESTING||this.state===w.LOADED||this.state===w.PLAYING||this.state===w.PAUSED||this.state===w.BUFFERING||this.state===w.SKIPPING||this.state===w.ENDED)&&e,i=this.state===w.REQUESTING||this.state===w.LOADED,s=this.adBreakManager.getActiveBreak(),r=this.providerManager.getActiveProviderName(),a=this.controller.getState();this.controller.updateStatePublic({isAdPlaying:t,isAdLoading:i,currentAd:this.currentAd,currentAdBreak:s,adProvider:r,adCurrentTime:t&&this.currentAd?a.adCurrentTime??0:null,adRemainingTime:t&&this.currentAd?a.adRemainingTime??this.currentAd.duration:null,adDuration:t&&this.currentAd?this.currentAd.duration||a.adDuration||0:null,canSkipAd:a.canSkipAd??((n=this.currentAd)==null?void 0:n.skippable)??!1,skipAvailableAt:a.skipAvailableAt??((l=this.currentAd)==null?void 0:l.skipOffset)??null,adPosition:this.currentAd?(s==null?void 0:s.ads.indexOf(this.currentAd))??null:null,adLinear:((o=this.currentAd)==null?void 0:o.linear)??null,adMuted:this.controller.getState().isMuted})}play(){if(!this.isInterceptionActive)return!1;const e=this.providerManager.getActiveProvider();if(e){try{e.resumeAd(),this.transitionTo(w.PLAYING)}catch(t){console.error("[AdsManager] Play ad execution failed:",t)}return!0}return!0}pause(){if(!this.isInterceptionActive)return!1;const e=this.providerManager.getActiveProvider();if(e){try{e.pauseAd(),this.transitionTo(w.PAUSED)}catch(t){console.error("[AdsManager] Pause ad execution failed:",t)}return!0}return!0}seek(e){return!!this.isInterceptionActive}setVolume(e){if(!this.isInterceptionActive)return!1;const t=this.providerManager.getActiveProvider();if(t)try{t.setVolume(e)}catch{}return!1}setMuted(e){if(!this.isInterceptionActive)return!1;const t=this.providerManager.getActiveProvider();if(t)try{t.setMuted(e)}catch{}return this.controller.updateStatePublic({adMuted:e}),!1}triggerLifecycleHook(e,...t){}liveEdgeSyncHook(){}dvrPositionHook(){}catchUpPlaybackHook(){}liveSourceSwitchHook(){}playlistItemStartHook(){}playlistItemEndHook(){}autoplayNextItemHook(){}playlistRepeatHook(){}playlistNavigationHook(){}getHtmlOverlayRenderer(){return this.htmlOverlayRenderer}applyDefaultSanitizer(e){var i,s,r;if(e.sanitizeHtml||!e.htmlContent)return e;const t=((r=(s=(i=this.controller.config)==null?void 0:i.ads)==null?void 0:s.ui)==null?void 0:r.sanitizeHtml)||Vs;return{...e,sanitizeHtml:t}}isHtmlOverlayCreative(e){return e&&!e.linear&&(!!e.htmlContent||!!e.htmlUrl||!!e.htmlTemplateId||!!e.imageUrl)}showCompanions(e){var o,d;if(!e||e.length===0)return;this.clearCompanions();const t=(d=(o=this.controller.config)==null?void 0:o.ads)==null?void 0:d.ui,i=t==null?void 0:t.companionSlots;if(i&&i.length>0){rr(e,i).forEach(({slot:u,companion:f})=>{const p=document.getElementById(u.elementId);if(!p){this.controller.emit("companionerror",{adId:f.id,slotId:u.id,reason:`elementId "${u.elementId}" not found`});return}const g=new st(this.controller,p,void 0,!0);this.companionRenderers.push(g),f=this.applyDefaultSanitizer(f),g.loadAd(f).then(m=>{m?(g.show(),this.controller.emit("companionshown",{adId:f.id,slotId:u.id})):(this.fireOverlayErrorPixels(f),this.controller.emit("companionerror",{adId:f.id,slotId:u.id,reason:"load failed"}))})});return}const s=this.applyDefaultSanitizer(e[0]),r=t==null?void 0:t.adOverlaySlot,a=r?document.querySelector(r):null;if(!r){console.warn('[AdsManager] VAST response included a Companion ad, but no "ads.ui.companionSlots" or "ads.ui.adOverlaySlot" is configured, so it cannot be displayed. Configure one to show companion ads.'),this.controller.emit("companionerror",{adId:s.id,reason:"no companionSlots or adOverlaySlot configured"});return}if(!a){console.warn(`[AdsManager] "ads.ui.adOverlaySlot" ("${r}") did not match any element in the DOM.`),this.controller.emit("companionerror",{adId:s.id,reason:`adOverlaySlot "${r}" not found in DOM`});return}const n=a,l=new st(this.controller,n,void 0,!0);this.companionRenderers.push(l),l.loadAd(s).then(h=>{h?l.show():this.fireOverlayErrorPixels(s)})}clearCompanions(){this.companionRenderers.forEach(e=>{try{e.destroy()}catch{}}),this.companionRenderers=[]}showConcurrentOverlays(e){var i;if(!e||e.length===0)return;this.clearConcurrentOverlays();const t=this.adContainer||((i=this.controller.getVideoElement())==null?void 0:i.parentElement);t&&e.forEach(s=>{const r=this.applyDefaultSanitizer(s),a=new st(this.controller,t,void 0,!1);this.concurrentOverlayRenderers.push(a),a.loadAd(r).then(n=>{n?a.show():this.fireOverlayErrorPixels(r)})})}clearAuxiliaryOverlays(){this.clearCompanions(),this.clearConcurrentOverlays()}clearConcurrentOverlays(){this.concurrentOverlayRenderers.forEach(e=>{try{e.destroy()}catch{}}),this.concurrentOverlayRenderers=[]}fireOverlayErrorPixels(e){const t=e==null?void 0:e.errorUrls;!t||t.length===0||t.forEach(i=>{const s=i.replace(/\[ERRORCODE\]/g,"900");try{typeof navigator<"u"&&navigator.sendBeacon?navigator.sendBeacon(s):typeof fetch<"u"&&fetch(s,{method:"GET",mode:"no-cors",keepalive:!0}).catch(()=>{})}catch{}})}async showOverlay(e){var i;const t={id:e.id||`overlay-${Date.now()}`,title:e.title||"HTML Overlay Ad",duration:e.duration||0,linear:!1,skippable:!1,...e};return await this.playHtmlOverlay(t),((i=this.htmlOverlayRenderer)==null?void 0:i.getLifecycleState())==="visible"}hideOverlay(){this.htmlOverlayRenderer&&this.htmlOverlayRenderer.hide()}closeOverlay(){this.htmlOverlayRenderer&&(this.htmlOverlayRenderer.close(),this.htmlOverlayRenderer=null)}updateOverlay(e){this.htmlOverlayRenderer&&this.htmlOverlayRenderer.updateOverlay(e)}async playHtmlOverlay(e){var s;const t=this.adContainer||((s=this.controller.getVideoElement())==null?void 0:s.parentNode);if(!t){this.triggerAdError({type:ie.PLAYBACK,code:400,message:"Ad container not found for HTML overlay rendering"});return}if(this.htmlOverlayRenderer)try{this.htmlOverlayRenderer.destroy()}catch{}if(this.htmlOverlayRenderer=new st(this.controller,t),e=this.applyDefaultSanitizer(e),this.setCurrentAd(e),this.transitionTo(w.LOADED),!await this.htmlOverlayRenderer.loadAd(e)){this.fireOverlayErrorPixels(e);return}this.transitionTo(w.PLAYING),this.htmlOverlayRenderer.show()}onSourceLoaded(e){this.triggerLifecycleHook("onSourceChanged",e),this.handleSourceSwitch()}handleSourceSwitch(){if(this.timeoutManager.clearAll(),this.asyncGuard.invalidateAll(),this.adBreakManager.clearBreaks(),this.contentSnapshot.clear(),this.clearCompanions(),this.clearConcurrentOverlays(),this.htmlOverlayRenderer){try{this.htmlOverlayRenderer.destroy()}catch{}this.htmlOverlayRenderer=null}this.providerManager.onSourceLoaded(),this.currentAd=null,this.state=w.IDLE,this.isInterceptionActive=!1,this.activeOperations=0,this.updatePlayerState()}getDiagnosticsStats(){return{totalAdsRequested:this.requestedCount,totalAdsPlayed:this.playedCount,totalAdsCompleted:this.completedCount,totalAdsSkipped:this.skippedCount,totalAdErrors:this.errorCount,recoveryCount:this.recoveryCount,timeoutCount:this.timeoutCount,cancelledAdsCount:this.cancelledCount,providerFailures:this.providerFailuresCount,averageLoadTimeMs:0,averageResumeTimeMs:0,activeOperationsCount:this.activeOperations}}}function dr(c,e){if(c===void 0)return null;if(typeof c=="number")return c;const t=c.trim();if(!t.endsWith("%")){const s=Number(t);return isNaN(s)?null:s}const i=parseFloat(t);return isNaN(i)||!isFinite(e)||e<=0?null:i/100*e}function hr(c,e,t,i){const s=[];for(const r of c){if(r.isPlayed)continue;let a=!1;if(r.type==="preroll")a=e<=3;else if(r.type==="postroll")a=i||t>0&&e>=t-.5;else{const n=r.timeOffset??0;a=e>=n&&e-n<=2.5}a&&s.push(r.id)}return s}class ur{constructor(e,t,i){this.controller=e,this.getProviderByName=t,this.showOverlay=i,this.breaks=[],this.timeUpdateListener=null,this.endedListener=null,this.nextId=0,this.attach()}schedule(e){const t=`sched-${++this.nextId}`;return this.breaks.push({...e,id:t,isPlayed:!1}),t}hasActiveBreaks(){return this.breaks.some(e=>!e.isPlayed)}unschedule(e){this.breaks=this.breaks.filter(t=>t.id!==e)}clear(){this.breaks=[]}destroy(){const e=this.controller.getVideoElement();this.timeUpdateListener&&e.removeEventListener("timeupdate",this.timeUpdateListener),this.endedListener&&e.removeEventListener("ended",this.endedListener),this.breaks=[]}attach(){const e=this.controller.getVideoElement(),t=()=>this.evaluate(e.currentTime,e.duration||0,!1),i=()=>this.evaluate(e.duration||0,e.duration||0,!0);e.addEventListener("timeupdate",t),e.addEventListener("ended",i),this.timeUpdateListener=t,this.endedListener=i}evaluate(e,t,i){if(this.breaks.length===0)return;const s=[];for(const a of this.breaks){if(a.isPlayed){s.push({id:a.id,type:a.type,timeOffset:a.resolvedTimeOffset,isPlayed:!0});continue}if(a.type==="midroll"){if(a.resolvedTimeOffset===void 0){const n=dr(a.timeOffset,t);if(n===null)continue;a.resolvedTimeOffset=n}s.push({id:a.id,type:a.type,timeOffset:a.resolvedTimeOffset,isPlayed:!1})}else s.push({id:a.id,type:a.type,timeOffset:void 0,isPlayed:!1})}const r=hr(s,e,t,i);if(r.length!==0)for(const a of r){const n=this.breaks.find(l=>l.id===a);n&&(n.isPlayed=!0,this.trigger(n))}}async trigger(e){if(this.controller.getState().sourceType==="embed"){this.controller.emit("aderror",{error:{type:ie.CONFIGURATION,code:900,message:"VAST ads are not supported for embed (YouTube/Vimeo) sources."}});return}if(e.provider==="HTML_OVERLAY"){if(!e.overlay)return;await this.showOverlay(e.overlay);return}if(!e.tagUrl)return;const t=this.getProviderByName(e.provider??"VAST");if(!t)return;(await t.requestAds(e.tagUrl)).success&&await t.playAdBreak(e.type)}}function Kt(c){if(!c)return 0;const e=c.trim().split(":");if(e.length===3){const i=parseInt(e[0],10)||0,s=parseInt(e[1],10)||0,r=parseFloat(e[2])||0;return i*3600+s*60+r}const t=parseFloat(c);return isNaN(t)?0:t}function ji(c){return!c||c==="start"?0:c==="end"||c.endsWith("%")?-1:Kt(c)}function pr(c){if(typeof window>"u"||typeof DOMParser>"u")return null;try{const t=new DOMParser().parseFromString(c,"text/xml");return t.getElementsByTagName("parsererror").length>0?null:t}catch{return null}}function Wt(c,e){const t=[],i=c.getElementsByTagName("*");for(let s=0;s<i.length;s++){const r=i[s],n=r.nodeName.split(":");n[n.length-1]===e&&t.push(r)}return t}function kt(c,e){const t=Wt(c,e);return t.length>0?t[0]:null}const fr=["breakStart","breakEnd","error"];function gr(c){var s;const e=kt(c,"TrackingEvents");if(!e)return[];const t=Wt(e,"Tracking"),i=[];for(let r=0;r<t.length;r++){const a=t[r],n=a.getAttribute("event")||"",l=((s=a.textContent)==null?void 0:s.trim())||"";fr.includes(n)&&l&&i.push({event:n,url:l})}return i}class jt{constructor(){this.name="VMAP",this.capabilities={supportsLinear:!0,supportsNonLinear:!0,supportsCompanion:!0,supportsSkippable:!0,supportsVMAP:!0,supportsVAST:!0,supportsSSAI:!1,supportsIMA:!1},this.context=null,this.manager=null,this.vmapTagUrl="",this.scheduledBreaks=[],this.hasDurationResolved=!1,this.lastBreakTime=-1,this.sessionAdCount=0,this.hourlyAdTimestamps=[],this.frequencyCap={},this.limits={maxXmlSize:2097152},this.trackingManager=new _t,this.timeUpdateListener=null,this.durationChangeListener=null,this.loadedMetadataListener=null,this.endedListener=null,this.seekedListener=null,this.diagnostics={parsedBreaksCount:0,registeredBreaksCount:0,playedBreaksCount:0,cancelledBreaksCount:0,dynamicInsertions:0,repeatSchedulingCount:0,playlistResets:0,liveScheduleUpdates:0,frequencyCapSuppressions:0}}init(e){var i;this.context=e,e.controller&&e.controller.ads&&(this.manager=e.controller.ads.manager);const t=(i=e.config)==null?void 0:i.providerOptions;return t&&(this.frequencyCap=t.frequencyCap||{},typeof t.maxXmlSize=="number"&&(this.limits.maxXmlSize=t.maxXmlSize)),this.setupTimelineListeners(),{success:!0}}async requestAds(e,t){var r,a,n,l;const i=t==null?void 0:t.context;if((!this.manager||!this.context)&&i&&this.init(i),!this.manager||!this.context)return{success:!1,error:{type:ie.CONFIGURATION,code:100,message:"VmapProvider not initialized."}};if(this.context.controller.getState().sourceType==="embed"){const o={type:ie.CONFIGURATION,code:900,message:"VMAP ads are not supported for embed (YouTube/Vimeo) sources."};return this.manager.triggerAdError(o),{success:!1,error:o}}this.vmapTagUrl=e,this.resetSchedule();const s=new AbortController().signal;try{const o=await this.fetchVmapXml(e,s,(r=this.context.config)==null?void 0:r.request);if(o.length>this.limits.maxXmlSize)throw new Error(`Oversized VMAP XML: ${o.length} bytes exceeds limits`);const d=pr(o);if(!d)throw new Error("Malformed VMAP XML or parsing error");if(!kt(d,"VMAP"))throw new Error("Missing VMAP root node");const u=this.parseVmapAdBreaks(d);this.diagnostics.parsedBreaksCount=u.length,this.scheduledBreaks=u.map(p=>({...p,resolvedTime:ji(p.timeOffset),isPlayed:!1})),(n=(a=this.context.controller.ads)==null?void 0:a.hasActiveManualSchedule)!=null&&n.call(a)&&(console.warn("[VmapProvider] requestAds() called while an AdScheduler manual schedule has active breaks - AdScheduler and VmapProvider independently watch the same video timeline and are not supported together on one player instance; this can result in duplicate/overlapping ad breaks."),this.context.controller.emit("adschedulerconflict",{source:"vmap",reason:"VmapProvider.requestAds() called while AdScheduler has active breaks"}));const f=this.context.controller.getState().duration;return f&&f>0&&this.resolveCuePoints(f),{success:!0}}catch(o){const d=o instanceof Error?o.message:"VMAP parsing failed",h={type:d.includes("Malformed")?ie.PARSING:ie.UNKNOWN,code:300,message:d,originalError:o};return(l=this.context)==null||l.controller.emit("vmapparseerror",{message:h.message}),{success:!1,error:h}}}async fetchVmapXml(e,t,i){return Hi(e,t,i)}parseVmapAdBreaks(e){var s;const t=[],i=Wt(e,"AdBreak");for(let r=0;r<i.length;r++){const a=i[r],n=a.getAttribute("timeOffset")||"",l=a.getAttribute("breakId")||`vmap-break-${Date.now()}-${r}`,o=a.getAttribute("breakType")||"linear",d=a.getAttribute("repeatAfter")||void 0,h=kt(a,"AdSource"),u=h?kt(h,"AdTagURI"):null,f=((s=u==null?void 0:u.textContent)==null?void 0:s.trim())||"",p=gr(a);t.push({id:l,timeOffset:n,breakType:o,repeatAfter:d,adTagUrl:f,trackingUrls:p})}return t}resolveCuePoints(e){if(!isFinite(e)||e<=0)return;this.hasDurationResolved=!0;const t=[...this.scheduledBreaks];this.scheduledBreaks=[],t.forEach(i=>{let s=i.resolvedTime;if(i.timeOffset==="start")s=0;else if(i.timeOffset==="end")s=e;else if(i.timeOffset.endsWith("%")){const a=parseFloat(i.timeOffset.slice(0,-1))/100;s=isNaN(a)?0:a*e}else s<0&&(s=Kt(i.timeOffset));const r={...i,resolvedTime:s,isPlayed:i.isPlayed};this.scheduledBreaks.push(r),this.diagnostics.registeredBreaksCount++,i.repeatAfter&&!i.isRepeat&&this.generateRepeatSchedules(r,e)}),this.scheduledBreaks.sort((i,s)=>i.resolvedTime-s.resolvedTime)}generateRepeatSchedules(e,t){const i=Kt(e.repeatAfter);if(i<=0)return;let s=e.resolvedTime+i;for(;s<t;)this.scheduledBreaks.push({...e,id:`${e.id}-repeat-${s}`,timeOffset:String(s),resolvedTime:s,isPlayed:!1,isRepeat:!0}),this.diagnostics.repeatSchedulingCount++,this.diagnostics.registeredBreaksCount++,s+=i}setupTimelineListeners(){if(!this.context)return;const e=this.context.videoElement,t=()=>{if(!this.context||!this.manager)return;const n=e.duration||0;isFinite(n)&&n>0&&(this.hasDurationResolved=!1,this.resolveCuePoints(n))},i=()=>{if(!this.context||!this.manager)return;const n=e.currentTime,l=e.duration||0;if(this.context.controller.getState().isLive){this.diagnostics.liveScheduleUpdates++,this.evaluateCueHits(n);return}isFinite(l)&&l>0&&(!this.hasDurationResolved||this.scheduledBreaks.some(o=>o.timeOffset.endsWith("%")||o.timeOffset==="end"))&&this.resolveCuePoints(l),this.evaluateCueHits(n)},s=()=>{const n=e.duration||0;isFinite(n)&&n>0&&(this.hasDurationResolved=!1,this.resolveCuePoints(n))},r=()=>{if(!this.context||!this.manager)return;const n=e.duration||0;this.evaluateCueHits(n,!0)},a=()=>{if(!this.context||!this.manager)return;const n=e.currentTime;this.evaluateCueHits(n,!1,!0)};e.addEventListener("timeupdate",i),e.addEventListener("durationchange",s),e.addEventListener("loadedmetadata",t),e.addEventListener("ended",r),e.addEventListener("seeked",a),this.timeUpdateListener=i,this.durationChangeListener=s,this.loadedMetadataListener=t,this.endedListener=r,this.seekedListener=a}evaluateCueHits(e,t=!1,i=!1){var a;const s=((a=this.context)==null?void 0:a.videoElement.duration)||0,r=[];for(let n=0;n<this.scheduledBreaks.length;n++){const l=this.scheduledBreaks[n];if(!l.isPlayed){if(l.resolvedTime<0)continue;const o=l.timeOffset==="start"||l.resolvedTime===0,d=l.timeOffset==="end";let h=!1;o?h=e<=3:d?h=t||s>0&&e>=s-.5:i?h=l.resolvedTime<=e:h=e>=l.resolvedTime&&e-l.resolvedTime<=2.5,h&&r.push(l)}}if(r.length>0){let n=r;if(i&&r.length>1){r.sort((d,h)=>d.resolvedTime-h.resolvedTime);const o=r[r.length-1];r.forEach(d=>{d.isPlayed=!0}),n=[o]}else r.forEach(o=>{o.isPlayed=!0});const l=n.filter(o=>this.checkFrequencyCappingRules(e));l.length>0?this.executeAdBreaksSequence(l):this.diagnostics.frequencyCapSuppressions+=n.length}}checkFrequencyCappingRules(e){if(this.frequencyCap.minContentWatched!==void 0&&e<this.frequencyCap.minContentWatched||this.frequencyCap.minTimeBetweenBreaks!==void 0&&this.lastBreakTime!==-1&&e-this.lastBreakTime<this.frequencyCap.minTimeBetweenBreaks||this.frequencyCap.maxAdsSession!==void 0&&this.sessionAdCount>=this.frequencyCap.maxAdsSession)return!1;if(this.frequencyCap.maxAdsPerHour!==void 0){const t=Date.now()-36e5;if(this.hourlyAdTimestamps=this.hourlyAdTimestamps.filter(i=>i>t),this.hourlyAdTimestamps.length>=this.frequencyCap.maxAdsPerHour)return!1}return!0}fireBreakTracking(e,t){e.trackingUrls&&e.trackingUrls.filter(i=>i.event===t).forEach(i=>this.trackingManager.trackUrl(i.url))}async executeAdBreaksSequence(e){var r;if(!this.context||!this.manager||e.length===0)return;const t=this.context.controller.ads.getProvider("VAST");if(!t){console.warn("[VmapProvider] Failed to locate VAST provider for executing breaks"),this.manager.recover("VAST provider missing");return}if(e.some(a=>a.timeOffset!=="start"&&a.resolvedTime>0)&&this.context.videoElement){const a=e[0].resolvedTime;try{this.context.videoElement.pause(),a>0&&a<(this.context.videoElement.duration||1/0)&&(this.context.videoElement.currentTime=a)}catch{}this.manager.getSavedContentSnapshot().capture(this.context.controller)}const s=[];for(const a of e){this.lastBreakTime=a.resolvedTime,this.sessionAdCount++,this.hourlyAdTimestamps.push(Date.now()),this.diagnostics.playedBreaksCount++,this.fireBreakTracking(a,"breakStart");const n=await t.requestAds(a.adTagUrl);if(n.success){const l=t.getInternalAdBreak()||this.manager.getAdBreakManager().getActiveBreak();l&&l.ads&&l.ads.length>0&&s.push(...l.ads)}else console.warn("[VmapProvider] VAST request failed for break:",a.id,n.error),this.fireBreakTracking(a,"error"),this.context.controller.emit("vmapbreakerror",{breakId:a.id,tagUrl:a.adTagUrl,message:((r=n.error)==null?void 0:r.message)||"VAST request failed for VMAP break"})}if(s.length>0){const a={id:`vmap-unified-break-${Date.now()}`,timeOffset:e[0].resolvedTime,type:e[0].timeOffset==="start"?"preroll":e[0].timeOffset==="end"?"postroll":"midroll",ads:s,duration:s.reduce((n,l)=>n+(l.duration||0),0)};t.setInternalAdBreak(a),this.manager.getAdBreakManager().registerBreak(a),await t.playAdBreak(),e.forEach(n=>this.fireBreakTracking(n,"breakEnd"))}else this.manager.recover("No playable VAST ads returned for VMAP breaks")}registerBreak(e){var a;const t=String(e.timeOffset||""),i=((a=this.context)==null?void 0:a.videoElement.duration)||0;let s=typeof e.timeOffset=="number"?e.timeOffset:ji(t);if(s<0&&i>0){if(t==="end")s=i;else if(t.endsWith("%")){const n=parseFloat(t.slice(0,-1))/100;s=isNaN(n)?0:n*i}}const r={id:e.id,timeOffset:t,breakType:e.breakType||"linear",adTagUrl:e.adTagUrl,resolvedTime:s,isPlayed:!1};this.scheduledBreaks.push(r),this.diagnostics.dynamicInsertions++,this.diagnostics.registeredBreaksCount++,this.scheduledBreaks.sort((n,l)=>n.resolvedTime-l.resolvedTime)}hasScheduledBreaks(){return this.scheduledBreaks.some(e=>!e.isPlayed)}removeBreak(e){const t=this.scheduledBreaks.findIndex(i=>i.id===e);t!==-1&&(this.scheduledBreaks.splice(t,1),this.diagnostics.cancelledBreaksCount++)}replaceBreak(e,t){this.removeBreak(e),this.registerBreak(t)}clearBreaks(){this.scheduledBreaks=[],this.hasDurationResolved=!1}onSourceLoaded(e){this.diagnostics.playlistResets++,this.resetSchedule(),this.vmapTagUrl=""}getCuePoints(){return this.scheduledBreaks.map(e=>e.resolvedTime).filter(e=>e>=0)}getVmapDiagnostics(){return this.diagnostics}resetSchedule(){this.scheduledBreaks=[],this.hasDurationResolved=!1,this.lastBreakTime=-1,this.sessionAdCount=0,this.hourlyAdTimestamps=[]}cleanupListeners(){if(!this.context)return;const e=this.context.videoElement;this.timeUpdateListener&&(e.removeEventListener("timeupdate",this.timeUpdateListener),this.timeUpdateListener=null),this.durationChangeListener&&(e.removeEventListener("durationchange",this.durationChangeListener),this.durationChangeListener=null),this.loadedMetadataListener&&(e.removeEventListener("loadedmetadata",this.loadedMetadataListener),this.loadedMetadataListener=null),this.endedListener&&(e.removeEventListener("ended",this.endedListener),this.endedListener=null),this.seekedListener&&(e.removeEventListener("seeked",this.seekedListener),this.seekedListener=null)}playAdBreak(){return Promise.resolve()}pauseAd(){}resumeAd(){}setVolume(e){}setMuted(e){}skipAd(){var t;const e=(t=this.manager)==null?void 0:t.getProviderManager().getActiveProvider();e&&e!==this&&typeof e.skipAd=="function"&&e.skipAd()}destroy(){this.cleanupListeners(),this.resetSchedule(),this.context=null,this.manager=null,this.vmapTagUrl=""}}const mr=()=>typeof performance<"u"?performance.now():Date.now(),Gi=8e3;let rt=null,Qi=0;function Xi(){var e;if(typeof window>"u"||typeof document>"u")return Promise.reject(new Error("IMA SDK can only be loaded in a browser environment"));if((e=window.google)!=null&&e.ima)return Promise.resolve();if(rt)return rt;const c=Date.now();return rt=new Promise((t,i)=>{let s=!1;const r=document.createElement("script");r.src="https://imasdk.googleapis.com/js/sdkloader/ima3.js",r.async=!0;const a=setTimeout(()=>{if(s)return;s=!0;const n=new Error(`Google IMA SDK did not load within ${Gi}ms. This commonly means the request to imasdk.googleapis.com was blocked by a browser-level or extension ad blocker (e.g. Opera's built-in blocker, uBlock Origin, AdGuard) rather than a real network failure - check the Network tab for a canceled/blocked request to that domain.`);n.likelyBlocked=!0,i(n)},Gi);r.onload=()=>{var n;s||(s=!0,clearTimeout(a),(n=window.google)!=null&&n.ima?(Qi=Date.now()-c,t()):i(new Error("IMA SDK script loaded but google.ima is not available")))},r.onerror=()=>{if(s)return;s=!0,clearTimeout(a);const n=new Error("Failed to load Google IMA SDK script from imasdk.googleapis.com. This commonly indicates the request was blocked by a browser-level or extension ad blocker rather than an actual network outage.");n.likelyBlocked=!0,i(n)},document.head.appendChild(r)}).catch(t=>{throw rt=null,t}),rt}function vr(c){return[1005,1009,1010,1011,1012,1020].includes(c)?ie.PARSING:[100,101,102,1006,1007].includes(c)?ie.CONFIGURATION:[301,303,1021,1022,1023].includes(c)?ie.NETWORK:[400,401,402,403,405].includes(c)?ie.PLAYBACK:ie.UNKNOWN}const Oe=class Oe{constructor(){this.name="IMA",this.capabilities={supportsLinear:!0,supportsNonLinear:!0,supportsCompanion:!0,supportsSkippable:!0,supportsVMAP:!0,supportsVAST:!0,supportsSSAI:!1,supportsIMA:!0},this.context=null,this.manager=null,this.adDisplayContainer=null,this.adsLoader=null,this.adsManager=null,this.loaderState="idle",this.managerState="idle",this.currentTag="",this.startWatchdogTimer=null,this.containerWatchTimer=null,this.diagnostics={sdkLoaded:!1,sdkVersion:"Unknown",sdkLoadDurationMs:0,adsLoaderState:"idle",adsManagerState:"idle",lastErrorMsg:"",lastErrorCode:0,eventsLogged:[],sdkBlockedLikely:!1},this.resizeListener=null}init(e){return this.context=e,e.controller&&e.controller.ads&&(this.manager=e.controller.ads.manager),typeof window<"u"&&Xi().catch(()=>{}),{success:!0}}async requestAds(e,t){var s,r,a,n;const i=t==null?void 0:t.context;if((!this.context||!this.manager)&&i&&this.init(i),!this.context||!this.manager)return{success:!1,error:{type:ie.CONFIGURATION,code:100,message:"ImaProvider not initialized."}};this.currentTag=e,(s=window.google)!=null&&s.ima&&this.initializeImaLoader();try{this.loaderState="requesting",this.diagnostics.adsLoaderState="requesting",await Xi();const l=window.google.ima;this.diagnostics.sdkLoaded=!0,this.diagnostics.sdkLoadDurationMs=Qi,this.diagnostics.sdkBlockedLikely=!1,l.settings&&(this.diagnostics.sdkVersion=String(((a=(r=l.settings).getLocale)==null?void 0:a.call(r))||"3.x")),this.initializeImaLoader();const o=new l.AdsRequest;o.adTagUrl=e;const d=this.context.videoElement.clientWidth||640,h=this.context.videoElement.clientHeight||360;o.linearAdSlotWidth=d,o.linearAdSlotHeight=h,o.nonLinearAdSlotWidth=d,o.nonLinearAdSlotHeight=Math.round(h/3),typeof o.setAdWillAutoPlay=="function"&&o.setAdWillAutoPlay(!0),typeof o.setAdWillPlayMuted=="function"&&o.setAdWillPlayMuted(!0);const u=(n=this.context.config.providerOptions)==null?void 0:n.ima;if(u&&(u.publisherProvidedId&&(o.publisherProvidedId=u.publisherProvidedId),u.sessionId&&(o.sessionId=u.sessionId),u.language&&l.settings.setLanguage(u.language),u.locale&&l.settings.setLocale(u.locale),u.customTargeting)){const g=[];for(const m in u.customTargeting)g.push(`${encodeURIComponent(m)}=${encodeURIComponent(u.customTargeting[m])}`);o.customParameters=g.join("&")}const f=this.adsLoader;return await new Promise((g,m)=>{const v=()=>{f.removeEventListener(l.AdsManagerLoadedEvent.Type.ADS_MANAGER_LOADED,v),f.removeEventListener(l.AdErrorEvent.Type.AD_ERROR,y),g()},y=b=>{var S;f.removeEventListener(l.AdsManagerLoadedEvent.Type.ADS_MANAGER_LOADED,v),f.removeEventListener(l.AdErrorEvent.Type.AD_ERROR,y),m(((S=b==null?void 0:b.getError)==null?void 0:S.call(b))||new Error("IMA Ad Error"))};f.addEventListener(l.AdsManagerLoadedEvent.Type.ADS_MANAGER_LOADED,v),f.addEventListener(l.AdErrorEvent.Type.AD_ERROR,y),f.requestAds(o)}),this.loaderState="ready",this.diagnostics.adsLoaderState="ready",{success:!0}}catch(l){this.loaderState="error",this.diagnostics.adsLoaderState="error";const o=l instanceof Error?l.message:"IMA Loader failed";this.diagnostics.lastErrorMsg=o;const d=!!(l!=null&&l.likelyBlocked);this.diagnostics.sdkBlockedLikely=d;const h={type:d?ie.BLOCKED:ie.NETWORK,code:d?901:301,message:o||"Google IMA loader request failed",originalError:l};return this.manager.triggerAdError(h),{success:!1,error:h}}}initializeImaLoader(){if(this.adsLoader)return;const e=window.google.ima;this.adDisplayContainer=new e.AdDisplayContainer(this.context.adContainer,this.context.videoElement),this.adDisplayContainer.initialize(),this.adsLoader=new e.AdsLoader(this.adDisplayContainer),this.adsLoader.addEventListener(e.AdsManagerLoadedEvent.Type.ADS_MANAGER_LOADED,t=>this.onAdsManagerLoaded(t),!1),this.adsLoader.addEventListener(e.AdErrorEvent.Type.AD_ERROR,t=>this.onAdError(t),!1),this.setupResizeListener()}setupResizeListener(){typeof window>"u"||(this.resizeListener=()=>this.resize(),window.addEventListener("resize",this.resizeListener))}resize(e,t){var l,o,d,h;if(!this.adsManager||!this.context)return;const i=(l=window.google)==null?void 0:l.ima;if(!i)return;const s=e||this.context.videoElement.clientWidth||640,r=t||this.context.videoElement.clientHeight||360,n=!!((h=(d=(o=this.context.controller)==null?void 0:o.getState)==null?void 0:d.call(o))!=null&&h.isFullscreen)?i.ViewMode.FULLSCREEN:i.ViewMode.NORMAL;try{this.adsManager.resize(s,r,n)}catch(u){console.warn("[ImaProvider] Failed to resize IMA AdsManager:",u)}}onAdsManagerLoaded(e){const t=window.google.ima,i=new t.AdsRenderingSettings;i.restorePlayerStateOnAdComplete=!1,this.adsManager=e.getAdsManager(this.context.videoElement,i),this.managerState="ready",this.diagnostics.adsManagerState="ready",this.setupAdsManagerListeners()}setupAdsManagerListeners(){const e=window.google.ima,t=this.adsManager;if(!t)return;const i=s=>{this.diagnostics.eventsLogged.push(`${s} at ${mr()}`)};t.addEventListener(e.AdErrorEvent.Type.AD_ERROR,s=>{i("AD_ERROR"),this.onAdError(s)}),t.addEventListener(e.AdEvent.Type.CONTENT_PAUSE_REQUESTED,()=>{var s;if(i("CONTENT_PAUSE_REQUESTED"),this.manager&&this.manager.getAdState()===w.IDLE)this.manager.startAdBreak({id:`ima-break-${Date.now()}`,timeOffset:this.context.videoElement.currentTime,type:"midroll",ads:[],duration:0});else try{(s=this.context)!=null&&s.videoElement&&!this.context.videoElement.paused&&this.context.videoElement.pause()}catch{}}),t.addEventListener(e.AdEvent.Type.CONTENT_RESUME_REQUESTED,()=>{var s;i("CONTENT_RESUME_REQUESTED"),(s=this.manager)==null||s.endAdBreak()}),e.AdEvent.Type.ALL_ADS_COMPLETED&&t.addEventListener(e.AdEvent.Type.ALL_ADS_COMPLETED,()=>{var s;i("ALL_ADS_COMPLETED"),(s=this.manager)==null||s.endAdBreak()}),t.addEventListener(e.AdEvent.Type.LOADED,s=>{var p,g,m,v;i("LOADED");const r=(p=s.getAd)==null?void 0:p.call(s);if(!r)return;const a=typeof r.isSkippable=="function"?r.isSkippable():typeof r.getSkippable=="function"?r.getSkippable():!1,n=typeof r.getClickThroughUrl=="function"?r.getClickThroughUrl():"",l=typeof r.getAdPodInfo=="function"?r.getAdPodInfo():null,o=l&&typeof l.getAdPosition=="function"?l.getAdPosition():void 0,d=l&&typeof l.getTotalAds=="function"?l.getTotalAds():void 0,h=l&&typeof l.isBumper=="function"?l.isBumper():void 0,u={id:r.getAdId()||`ima-${Date.now()}`,title:r.getTitle()||"IMA Ad",duration:r.getDuration()||0,width:r.getWidth()||0,height:r.getHeight()||0,linear:r.isLinear(),skippable:a,skipOffset:r.getSkipTimeOffset&&r.getSkipTimeOffset()||0,contentType:r.getContentType()||"video/mp4",clickThroughUrl:n,podPosition:o,podSize:d,isBumper:h},f=typeof r.getCompanionAds=="function"?r.getCompanionAds():[];if(f&&f.length>0){const y=f.map((b,S)=>({id:`ima-companion-${S}`,title:"IMA Companion Ad",duration:0,width:typeof b.getWidth=="function"?b.getWidth():void 0,height:typeof b.getHeight=="function"?b.getHeight():void 0,linear:!1,skippable:!1,htmlContent:typeof b.getContent=="function"?b.getContent():void 0,clickThroughUrl:typeof b.getClickThroughUrl=="function"?b.getClickThroughUrl():""}));(g=this.manager)==null||g.showCompanions(y)}(m=this.manager)==null||m.setCurrentAd(u),(v=this.context)==null||v.controller.emit("adloaded",{ad:u})}),t.addEventListener(e.AdEvent.Type.AD_PROGRESS,s=>{var a,n,l;const r=s.getAdData?s.getAdData():null;if(r){const o=r.currentTime||0,d=r.duration||((a=this.context)==null?void 0:a.controller.getState().adDuration)||0,h=Math.max(0,d-o),u=!!r.skippable&&o>=(r.skipTimeOffset||0),f=r.skippable?Math.max(0,(r.skipTimeOffset||0)-o):null;(n=this.context)==null||n.controller.updateStatePublic({adCurrentTime:o,adRemainingTime:h,adDuration:d,canSkipAd:u,skipAvailableAt:f}),(l=this.context)==null||l.controller.emit("adtimeupdate",{currentTime:o,duration:d,remainingTime:h})}}),t.addEventListener(e.AdEvent.Type.STARTED,()=>{var s,r;i("STARTED"),this.clearStartWatchdog(),this.managerState="playing",this.diagnostics.adsManagerState="playing",(s=this.manager)==null||s.transitionTo(w.PLAYING),(r=this.context)==null||r.controller.emit("adstart"),this.startContainerWatch()}),t.addEventListener(e.AdEvent.Type.PAUSED,()=>{var s,r;i("PAUSED"),this.managerState="paused",this.diagnostics.adsManagerState="paused",(s=this.manager)==null||s.transitionTo(w.PAUSED),(r=this.context)==null||r.controller.emit("adpaused")}),t.addEventListener(e.AdEvent.Type.RESUMED,()=>{var s,r;i("RESUMED"),this.managerState="playing",this.diagnostics.adsManagerState="playing",(s=this.manager)==null||s.transitionTo(w.PLAYING),(r=this.context)==null||r.controller.emit("adresumed")}),t.addEventListener(e.AdEvent.Type.COMPLETE,()=>{var s,r;i("COMPLETE"),this.clearContainerWatch(),(s=this.manager)==null||s.transitionTo(w.ENDED),(r=this.context)==null||r.controller.emit("adcomplete")}),t.addEventListener(e.AdEvent.Type.SKIPPED,()=>{var s,r;i("SKIPPED"),this.clearContainerWatch(),(s=this.context)==null||s.controller.emit("adskip"),(r=this.manager)==null||r.endAdBreak()}),t.addEventListener(e.AdEvent.Type.CLICK,s=>{var l;i("CLICK");const r=s!=null&&s.getAdData?s.getAdData():null,a=s!=null&&s.getAd?s.getAd():null,n=(r==null?void 0:r.clickThroughUrl)||(typeof(a==null?void 0:a.getClickThroughUrl)=="function"?a.getClickThroughUrl():"");(l=this.context)==null||l.controller.emit("adclick",{clickUrl:n})})}onAdError(e){var a,n,l;const t=e.getError(),i=((a=t.getErrorCode)==null?void 0:a.call(t))||300,s=((n=t.getMessage)==null?void 0:n.call(t))||"Unknown Google IMA SDK error";this.diagnostics.lastErrorCode=i,this.diagnostics.lastErrorMsg=s;const r={type:vr(i),code:i,message:s,originalError:t};(l=this.manager)==null||l.triggerAdError(r)}async playAdBreak(e="preroll"){var t,i,s,r,a,n;if(this.adsManager){if(((t=this.context)==null?void 0:t.controller.getState().sourceType)==="embed"){this.onAdError({getError:()=>({getErrorCode:()=>900,getMessage:()=>"Google IMA ads are not supported for embed (YouTube/Vimeo) sources."})});return}try{const l=this.context.videoElement.clientWidth||640,o=this.context.videoElement.clientHeight||360,h=!!((r=(s=(i=this.context.controller)==null?void 0:i.getState)==null?void 0:s.call(i))!=null&&r.isFullscreen)?window.google.ima.ViewMode.FULLSCREEN:window.google.ima.ViewMode.NORMAL;this.adsManager.init(l,o,h);try{this.adsManager.setVolume(0)}catch{}try{(a=this.context)!=null&&a.videoElement&&(this.context.videoElement.muted=!0)}catch{}if((n=this.manager)==null||n.startAdBreak({id:`ima-break-${Date.now()}`,timeOffset:0,type:e,ads:[],duration:0}),e==="preroll")this.adsManager.start(),this.startStartWatchdog();else{const u=window.google.ima,f=this.adsManager,p=()=>{f.removeEventListener(u.AdEvent.Type.AD_BREAK_READY,p),f.start(),this.startStartWatchdog()};f.addEventListener(u.AdEvent.Type.AD_BREAK_READY,p)}}catch(l){const o=l instanceof Error?l.message:"IMA playAdBreak failed";this.onAdError({getError:()=>({getErrorCode:()=>400,getMessage:()=>o})})}}}startStartWatchdog(){this.clearStartWatchdog(),this.startWatchdogTimer=setTimeout(()=>{this.startWatchdogTimer=null,this.managerState!=="playing"&&this.onAdError({getError:()=>({getErrorCode:()=>402,getMessage:()=>`Google IMA: adsManager.start() was called ${Oe.START_WATCHDOG_MS}ms ago but the STARTED event never fired - the ad video never actually began playing, even though IMA's own UI chrome (ad badge / skip countdown, driven by AD_PROGRESS) may still be visible. This usually means the underlying ad media failed to decode/attach - check the ad tag's returned media file (codec/format support), or the ad server response itself, rather than autoplay/mute policy (already handled).`})})},Oe.START_WATCHDOG_MS)}clearStartWatchdog(){this.startWatchdogTimer&&(clearTimeout(this.startWatchdogTimer),this.startWatchdogTimer=null)}startContainerWatch(){var t;this.clearContainerWatch();const e=(t=this.context)==null?void 0:t.adContainer;!e||typeof document>"u"||(this.containerWatchTimer=setInterval(()=>{this.managerState==="playing"&&(document.contains(e)||(this.clearContainerWatch(),this.onAdError({getError:()=>({getErrorCode:()=>403,getMessage:()=>"Google IMA: the ad container element was detached from the page while the ad was still playing (IMA reported STARTED but its container is no longer in the live DOM). This means something in the host app re-rendered/removed the element IMA attached its iframe to - the ad kept running internally (progress/complete events) but nothing was visible. Check for conditional rendering or re-creation of the ads-overlay container while an ad is active."})})))},Oe.CONTAINER_WATCH_INTERVAL_MS))}clearContainerWatch(){this.containerWatchTimer&&(clearInterval(this.containerWatchTimer),this.containerWatchTimer=null)}pauseAd(){this.adsManager&&this.managerState==="playing"&&this.adsManager.pause()}resumeAd(){this.adsManager&&this.managerState==="paused"&&this.adsManager.resume()}setVolume(e){this.adsManager&&this.adsManager.setVolume(e)}setMuted(e){this.adsManager&&this.adsManager.setVolume(e?0:1)}getImaDiagnostics(){return this.diagnostics}skipAd(){if(this.adsManager)try{this.adsManager.skip()}catch{this.destroy()}}destroy(){if(this.clearStartWatchdog(),this.clearContainerWatch(),this.resizeListener&&typeof window<"u"&&(window.removeEventListener("resize",this.resizeListener),this.resizeListener=null),this.adsManager){try{this.adsManager.destroy()}catch{}this.adsManager=null}if(this.adsLoader){try{this.adsLoader.destroy()}catch{}this.adsLoader=null}if(this.adDisplayContainer){try{this.adDisplayContainer.destroy()}catch{}this.adDisplayContainer=null}this.managerState="destroyed",this.diagnostics.adsManagerState="destroyed",this.context=null,this.manager=null}};Oe.START_WATCHDOG_MS=6e3,Oe.CONTAINER_WATCH_INTERVAL_MS=1e3;let at=Oe;class Yi{constructor(e){this.providers=new Map,this.activeProviderName=null,this.adContainerElement=null,this.scheduler=null,this.controller=e,this.manager=new Wi,this.controller.use(this.manager),this.registerProvider("VAST",new qt),this.registerProvider("VMAP",new jt),this.registerProvider("IMA",new at)}setAdContainer(e){this.adContainerElement=e,this.manager.setAdContainer(e),this.providers.forEach((t,i)=>{this.initializeProvider(i,e)})}getAdContainer(){return this.adContainerElement||this.manager.getAdContainer()}state(){const e=this.controller.getState();return{isAdPlaying:e.isAdPlaying,isAdLoading:e.isAdLoading,currentAd:e.currentAd,currentAdBreak:e.currentAdBreak,adRemainingTime:e.adRemainingTime,adDuration:e.adDuration,canSkipAd:e.canSkipAd,skipAvailableAt:e.skipAvailableAt,adPosition:e.adPosition,adProvider:e.adProvider,adLinear:e.adLinear,adMuted:e.adMuted}}provider(){return this.activeProviderName}capabilities(){if(this.activeProviderName){const e=this.providers.get(this.activeProviderName);if(e)return e.capabilities}return null}currentAd(){return this.controller.getState().currentAd}currentBreak(){return this.controller.getState().currentAdBreak}skip(){this.manager.skipAd()}pause(){this.manager.pause()}resume(){this.manager.play()}enable(){this.controller.setAdsEnabled(!0)}disable(){this.controller.setAdsEnabled(!1)}getScheduler(){return this.scheduler||(this.scheduler=new ur(this.controller,e=>this.getProvider(e),e=>this.manager.showOverlay(e))),this.scheduler}schedule(e){var i;const t=this.providers.get("VMAP");return(i=t==null?void 0:t.hasScheduledBreaks)!=null&&i.call(t)&&(console.warn("[AdsController] schedule() called while a VMAP playlist has active breaks - AdScheduler and VmapProvider independently watch the same video timeline and are not supported together on one player instance; this can result in duplicate/overlapping ad breaks."),this.controller.emit("adschedulerconflict",{source:"scheduler",reason:"AdScheduler.schedule() called while VmapProvider has active breaks"})),this.getScheduler().schedule(e)}hasActiveManualSchedule(){return!!this.scheduler&&this.scheduler.hasActiveBreaks()}unschedule(e){var t;(t=this.scheduler)==null||t.unschedule(e)}clearSchedule(){var e;(e=this.scheduler)==null||e.clear()}async play(e){const t=this.getProvider("VAST");if(!t)return;(await t.requestAds(e)).success&&await t.playAdBreak()}registerProvider(e,t,i){var s,r;this.providers.set(e,t),this.manager.getProviderManager().registerProvider(e,t),(!this.activeProviderName||((r=(s=this.controller.config)==null?void 0:s.ads)==null?void 0:r.provider)===e)&&(this.activeProviderName=e,this.manager.getProviderManager().selectProvider(e)),this.initializeProvider(e,i)}initializeProvider(e,t){const i=this.providers.get(e);if(!i)return!1;const s=t||this.adContainerElement||this.manager.getAdContainer()||void 0,r=this.manager.createProviderContext(s);try{return i.init(r),!0}catch(a){return console.error(`[AdsController] Failed to initialize provider "${e}":`,a),!1}}getProvider(e){let t=this.providers.get(e);return t||(e==="VAST"?(t=new qt,this.registerProvider("VAST",t)):e==="VMAP"?(t=new jt,this.registerProvider("VMAP",t)):e==="IMA"&&(t=new at,this.registerProvider("IMA",t))),t&&this.initializeProvider(e),t}unregisterProvider(e){const t=this.providers.get(e);if(t)try{t.destroy()}catch{}this.providers.delete(e),this.manager.getProviderManager().unregisterProvider(e),this.activeProviderName===e&&(this.activeProviderName=null)}destroy(){var e;(e=this.scheduler)==null||e.destroy(),this.scheduler=null}async showOverlay(e){return this.manager.showOverlay(e)}hideOverlay(){this.manager.hideOverlay()}closeOverlay(){this.manager.closeOverlay()}updateOverlay(e){this.manager.updateOverlay(e)}getOverlayDiagnostics(){const e=this.manager.getHtmlOverlayRenderer();return e?e.getDiagnostics():null}diagnostics(){var i;const e=this.manager.getDiagnosticsStats(),t=this.manager.getHtmlOverlayRenderer();return{providerName:this.activeProviderName,state:this.manager.getAdState(),configuration:((i=this.controller.config)==null?void 0:i.ads)||null,lastError:null,statistics:{totalAdsRequested:e.totalAdsRequested,totalAdsPlayed:e.totalAdsPlayed,totalAdsCompleted:e.totalAdsCompleted,totalAdsSkipped:e.totalAdsSkipped,totalAdErrors:e.totalAdErrors},htmlOverlay:t?t.getDiagnostics():null}}validate(){return Mi.validate(this.controller)}}function Gt(c){if(c instanceof DOMException)return c.name==="SecurityError"||c.code===18;if(c&&typeof c=="object"){const e=c;return e.name==="SecurityError"||e.code===18}return!1}class Zi{constructor(e){this.type="frame-capture",this.video=null,this.canvas=null,this.ctx=null,this.cache=new Map,this.currentSrc="",this.pendingSrc="",this.isSeeking=!1,this.seekQueue=[],this.isMetadataLoaded=!1,this.hasError=!1,this.consecutiveFailures=0,this.metadataPromise=null,this.resolveMetadata=null,this.hlsInstance=null,this.dashInstance=null,this.isDestroyed=!1,this.lastSeekTime=0,this.lastHighPriorityTime=0,this.throttleMs=150,this.seekTimeoutId=null,this.MAX_CACHE_SIZE=250,this.isPreciseSeeking=!1,this.activeSeekCleanup=null,this.pendingRequests=new Map,this.handleLoadedMetadata=()=>{(this.currentSrc||"").split("?")[0].toLowerCase().endsWith(".mpd")||(this.isMetadataLoaded=!0,this.resolveMetadata&&this.resolveMetadata())},this.handleVideoError=t=>{var s;const i=(s=this.video)==null?void 0:s.error;if(console.debug("[VideoFrameThumbnailProvider] Global error event fired on hidden video:",i?`Code: ${i.code}, Message: ${i.message}`:t),this.hasError=!0,this.destroyStreamingInstances(),this.video){try{this.video.pause()}catch{}this.video.removeAttribute("src");try{this.video.load()}catch{}}this.resolveMetadata&&this.resolveMetadata()},this.config=e,this.initVideoAndCanvas()}updateConfig(e){this.config=e}initVideoAndCanvas(){this.video||(this.video=document.createElement("video"),this.video.muted=!0,this.video.playsInline=!0,this.video.crossOrigin="anonymous",this.video.preload="auto",this.video.style.cssText="position:fixed;width:320px;height:180px;pointer-events:none;opacity:0.001;z-index:-1000;top:0;left:0;",document.body.appendChild(this.video),this.video.addEventListener("loadedmetadata",this.handleLoadedMetadata),this.video.addEventListener("error",this.handleVideoError),this.canvas=document.createElement("canvas"),this.canvas.width=320,this.canvas.height=180,this.ctx=this.canvas.getContext("2d",{willReadFrequently:!0}))}setSource(e){if(!e||e.includes("Embed")||e.includes("youtube.com")||e.includes("youtu.be")||e.includes("vimeo.com")){this.currentSrc="",this.pendingSrc="",this.cache.clear(),this.pendingRequests.clear();for(const t of this.seekQueue)t.resolve(null);this.seekQueue=[],this.isSeeking=!1,this.isMetadataLoaded=!1,this.hasError=!1,this.consecutiveFailures=0,this.metadataPromise=null,this.resolveMetadata=null,this.destroyStreamingInstances();return}if(this.pendingSrc!==e){this.pendingSrc=e,this.cache.clear(),this.pendingRequests.clear();for(const t of this.seekQueue)t.resolve(null);this.seekQueue=[],this.isSeeking=!1,this.isMetadataLoaded=!1,this.hasError=!1,this.consecutiveFailures=0,this.metadataPromise=null,this.resolveMetadata=null,this.destroyStreamingInstances()}}loadPendingSource(){const e=this.pendingSrc;if(e&&(this.currentSrc=e,this.isMetadataLoaded=!1,this.hasError=!1,this.metadataPromise=new Promise(t=>{this.resolveMetadata=t}),this.initVideoAndCanvas(),this.video)){let t="mp4";const i=e.split("?")[0].toLowerCase();i.endsWith(".m3u8")?t="hls":i.endsWith(".mpd")?t="dash":i.endsWith(".webm")&&(t="webm"),t==="hls"?Ri().then(s=>{if(this.currentSrc!==e||!this.video)return;const r=s;if(r.isSupported()){const a=new r({enableWorker:!0,lowLatencyMode:!0});this.hlsInstance=a,a.attachMedia(this.video),a.on(r.Events.MEDIA_ATTACHED,()=>{this.currentSrc!==e||this.hlsInstance!==a||a.loadSource(e)}),a.on(r.Events.ERROR,(n,l)=>{console.error("[VideoFrameThumbnailProvider HLS Error]:",l.type,l.details,"fatal:",l.fatal)}),a.on(r.Events.MANIFEST_PARSED,()=>{this.currentSrc!==e||this.hlsInstance!==a||(a.currentLevel=0,a.loadLevel=0)})}else this.video.canPlayType("application/vnd.apple.mpegurl")&&(this.video.src=e,this.video.load())}).catch(s=>{console.debug("[VideoFrameThumbnailProvider] Failed to load hls.js:",s),this.hasError=!0,this.resolveMetadata&&this.resolveMetadata()}):t==="dash"?$i().then(s=>{if(this.currentSrc!==e||!this.video)return;const a=s.MediaPlayer().create();this.dashInstance=a,a.updateSettings({streaming:{abr:{autoSwitchBitrate:{video:!1}}}}),a.initialize(this.video,e,!1),a.on("streamInitialized",()=>{if(!(this.currentSrc!==e||this.dashInstance!==a)){try{const n=a.getRepresentationsByType?a.getRepresentationsByType("video"):[];n.length>0&&(typeof a.setRepresentationForTypeById=="function"?a.setRepresentationForTypeById("video",n[0].id):typeof a.setQualityFor=="function"&&a.setQualityFor("video",0,!0))}catch(n){console.debug("[VideoFrameThumbnailProvider] Failed to set quality on DASH instance:",n)}this.isMetadataLoaded=!0,this.resolveMetadata&&this.resolveMetadata()}}),a.on("error",n=>{this.currentSrc!==e||this.dashInstance!==a||(console.debug("[VideoFrameThumbnailProvider] DASH player error:",n),this.hasError=!0,this.resolveMetadata&&this.resolveMetadata())})}).catch(s=>{console.debug("[VideoFrameThumbnailProvider] Failed to load dashjs:",s),this.hasError=!0,this.resolveMetadata&&this.resolveMetadata()}):(this.video.src=e,this.video.load())}}destroyStreamingInstances(){if(this.activeSeekCleanup&&this.activeSeekCleanup(),this.isSeeking=!1,this.seekTimeoutId!==null&&(clearTimeout(this.seekTimeoutId),this.seekTimeoutId=null),this.hlsInstance){try{this.hlsInstance.destroy()}catch{}this.hlsInstance=null}if(this.dashInstance){try{this.dashInstance.destroy()}catch{}this.dashInstance=null}}isUnavailable(){const e=document.getElementById("test-player");if(e&&e.playerState){const t=e.playerState;if(t.isLive&&!t.canSeekInDvr)return!0}return!this.pendingSrc||this.hasError}getNearestCachedThumbnail(e){var s;if(((s=this.config)==null?void 0:s.cache)===!1||this.cache.size===0)return null;let t=null,i=1/0;for(const[r,a]of this.cache.entries()){const n=Math.abs(r-e);n<i&&(i=n,t=a)}return t}getThumbnail(e,t="high"){var o;if(!this.pendingSrc)return null;const i=document.getElementById("test-player"),s=!!(i&&i.playerState&&i.playerState.isLive);if(s&&this.video)try{const d=this.video.seekable;if(d&&d.length>0){const h=d.start(0);for(const u of this.cache.keys())u<h-10&&this.cache.delete(u);for(const u of this.pendingRequests.keys())u<h-10&&this.pendingRequests.delete(u)}}catch{}if(s){const h=Date.now()-this.lastSeekTime;let u=!1;if(h>3e4)u=!0;else if(this.video){const f=this.video.seekable;if(f&&f.length>0){const p=f.end(f.length-1);e>p+10&&(u=!0)}else u=!0}u&&(this.cache.clear(),this.pendingRequests.clear(),this.destroyStreamingInstances(),this.currentSrc="")}if(this.currentSrc!==this.pendingSrc&&this.loadPendingSource(),!this.video)return null;const r=Math.round(e*10)/10,a=this.pendingRequests.get(r);if(a)return a;if(((o=this.config)==null?void 0:o.cache)!==!1){const d=this.cache.get(r);if(d)return d}const n=this.getNearestCachedThumbnail(e);if(n&&n.time!==void 0&&Math.abs(n.time-e)<=.2)return n;t==="high"&&(this.lastHighPriorityTime=Date.now());const l=new Promise((d,h)=>{if(t==="high"){const u=this.seekQueue.findIndex(f=>f.priority==="high");if(u!==-1){const f=this.seekQueue.splice(u,1)[0];f.resolve(null);const p=Math.round(f.time*10)/10;this.pendingRequests.delete(p)}}if(this.seekQueue.push({time:e,priority:t,resolve:u=>{this.pendingRequests.delete(r),d(u)},reject:u=>{this.pendingRequests.delete(r),h(u)}}),t==="low"){const u=[];if(this.seekQueue.forEach((f,p)=>{f.priority==="low"&&u.push(p)}),u.length>9){const f=u.length-9,p=new Set(u.slice(0,f)),g=[];this.seekQueue.forEach((m,v)=>{if(p.has(v)){m.resolve(null);const y=Math.round(m.time*10)/10;this.pendingRequests.delete(y)}else g.push(m)}),this.seekQueue=g}}this.processQueue()});return this.pendingRequests.set(r,l),l}async processQueue(){var g,m;if(this.isSeeking||this.seekQueue.length===0||!this.video)return;const e=Date.now(),t=e-this.lastSeekTime;if(t<this.throttleMs){this.seekTimeoutId!==null&&clearTimeout(this.seekTimeoutId),this.seekTimeoutId=setTimeout(()=>{this.seekTimeoutId=null,this.processQueue()},this.throttleMs-t);return}this.seekTimeoutId!==null&&(clearTimeout(this.seekTimeoutId),this.seekTimeoutId=null);const i=e-this.lastHighPriorityTime<2e3,s=this.seekQueue.some(v=>v.priority==="high");if(i&&!s&&!this.isPreciseSeeking){const v=2e3-(e-this.lastHighPriorityTime);this.seekTimeoutId!==null&&clearTimeout(this.seekTimeoutId),this.seekTimeoutId=setTimeout(()=>{this.seekTimeoutId=null,this.processQueue()},v);return}let r=this.seekQueue.findIndex(v=>v.priority==="high");r===-1&&(r=0),this.lastSeekTime=e,this.isSeeking=!0;const a=this.seekQueue.splice(r,1)[0];let n=a.time;if(this.video&&this.video.seekable&&this.video.seekable.length>0){const v=this.video.seekable.start(0),y=this.video.seekable.end(this.video.seekable.length-1);n=Math.max(v,Math.min(n,y))}const l=Math.round(n*10)/10,o=((g=this.config)==null?void 0:g.cache)!==!1?this.cache.get(l):null;if(o){this.isSeeking=!1,a.resolve(o),this.processQueue();return}if(!this.isMetadataLoaded&&!this.hasError&&this.metadataPromise&&await this.metadataPromise,this.hasError){a.resolve(null),this.isSeeking=!1,this.processQueue();return}if(Math.abs(this.video.currentTime-n)<.01&&this.video.readyState>=2){try{let v=null,y=0;const b=3;for(;y<=b&&(v=this.captureFrame(l),!(v&&!this.isCanvasBlank()));)if(y<b)y++,await new Promise(S=>setTimeout(S,40));else break;if(v){if(((m=this.config)==null?void 0:m.cache)!==!1){if(this.cache.size>=this.MAX_CACHE_SIZE){const S=this.cache.keys().next().value;S!==void 0&&this.cache.delete(S)}this.cache.set(l,v)}this.consecutiveFailures=0,a.resolve(v)}else this.handleFailure(a)}catch(v){Gt(v)?(console.debug("[VideoFrameThumbnailProvider] CORS security error. Disabling seeks for this source immediately."),this.hasError=!0,a.resolve(null)):this.handleFailure(a)}this.isSeeking=!1,this.processQueue();return}let h=null;const u=async()=>{var v;if(!(this.video&&this.video.readyState<2)){p();try{if(this.video&&this.video.readyState>=2){let y=null,b=0;const S=3;for(;b<=S&&(y=this.captureFrame(l),!(y&&!this.isCanvasBlank()));)if(b<S)b++,await new Promise(T=>setTimeout(T,40));else break;if(y){if(((v=this.config)==null?void 0:v.cache)!==!1){if(this.cache.size>=this.MAX_CACHE_SIZE){const T=this.cache.keys().next().value;T!==void 0&&this.cache.delete(T)}this.cache.set(l,y)}this.consecutiveFailures=0,a.resolve(y)}else this.handleFailure(a)}else console.warn("[VideoFrameThumbnailProvider] seeked fired but video readyState < 2."),this.handleFailure(a)}catch(y){console.debug("[VideoFrameThumbnailProvider] Canvas snapshot capture failed (CORS/tainted canvas or exception):",y),Gt(y)?(console.debug("[VideoFrameThumbnailProvider] CORS security error. Disabling seeks for this source immediately."),this.hasError=!0,a.resolve(null)):this.handleFailure(a)}this.isSeeking=!1,this.processQueue()}},f=v=>{p(),console.debug("[VideoFrameThumbnailProvider] Error event fired during video seek:",v),this.handleFailure(a),this.isSeeking=!1,this.processQueue()},p=()=>{this.video&&(this.video.removeEventListener("seeked",u),this.video.removeEventListener("loadeddata",u),this.video.removeEventListener("canplay",u),this.video.removeEventListener("error",f)),h!==null&&(clearTimeout(h),h=null),this.activeSeekCleanup=null};this.activeSeekCleanup=p,this.video.addEventListener("seeked",u),this.video.addEventListener("loadeddata",u),this.video.addEventListener("canplay",u),this.video.addEventListener("error",f),h=setTimeout(async()=>{console.warn(`[VideoFrameThumbnailProvider] Seek timeout reached for time ${n}s. Recovering...`),p();try{if(this.video&&this.video.readyState>=2){let v=null,y=0;const b=3;for(;y<=b&&(v=this.captureFrame(l),!(v&&!this.isCanvasBlank()));)if(y<b)y++,await new Promise(S=>setTimeout(S,40));else break;if(v){if(this.cache.size>=this.MAX_CACHE_SIZE){const S=this.cache.keys().next().value;S!==void 0&&this.cache.delete(S)}this.cache.set(l,v),this.consecutiveFailures=0,a.resolve(v)}else this.handleFailure(a)}else this.handleFailure(a)}catch(v){Gt(v)?(console.debug("[VideoFrameThumbnailProvider] CORS security error on seek timeout. Disabling seeks for this source immediately."),this.hasError=!0,a.resolve(null)):this.handleFailure(a)}this.isSeeking=!1,this.processQueue()},2e3),this.hlsInstance&&this.hlsInstance.startLoad(),this.video.currentTime=n}handleFailure(e){this.consecutiveFailures++,console.debug(`[VideoFrameThumbnailProvider] Seek failed. Consecutive failures: ${this.consecutiveFailures}`),e.resolve(null)}captureFrame(e){if(!this.video||!this.canvas||!this.ctx)return null;const t=this.video.videoWidth||160,i=this.video.videoHeight||90,s=t/i,r=320,a=320;let n=r,l=Math.round(n/s);return l>a&&(l=a,n=Math.round(l*s)),(this.canvas.width!==n||this.canvas.height!==l)&&(this.canvas.width=n,this.canvas.height=l),this.ctx.drawImage(this.video,0,0,this.canvas.width,this.canvas.height),{url:this.canvas.toDataURL("image/jpeg",.8),width:this.canvas.width,height:this.canvas.height,time:e}}isCanvasBlank(){if(!this.canvas||!this.ctx)return!0;const e=this.canvas.width,t=this.canvas.height;try{const s=this.ctx.getImageData(0,0,e,t).data;let r=0;for(let n=0;n<s.length;n+=16){const l=s[n],o=s[n+1],d=s[n+2];s[n+3]>10&&(l>8||o>8||d>8)&&r++}const a=s.length/16;return r/a<.01}catch{return!1}}destroy(){if(!this.isDestroyed){this.isDestroyed=!0,this.cache.clear(),this.pendingRequests.clear();for(const e of this.seekQueue)e.resolve(null);if(this.seekQueue=[],this.isSeeking=!1,this.activeSeekCleanup&&this.activeSeekCleanup(),this.destroyStreamingInstances(),this.video){this.video.removeEventListener("loadedmetadata",this.handleLoadedMetadata),this.video.removeEventListener("error",this.handleVideoError);try{this.video.pause()}catch{}this.video.removeAttribute("src");try{this.video.load()}catch{}this.video.parentNode&&this.video.parentNode.removeChild(this.video),this.video=null}this.canvas=null,this.ctx=null}}}class Ji{constructor(e,t){this.type="vtt",this.cues=[],this.isLoaded=!1,this.loadPromise=null,this.cache=new Map,this.vttUrl=e,this.config=t,this.loadPromise=this.loadVTT()}updateConfig(e){this.config=e}async loadVTT(){try{const e=await fetch(this.vttUrl);if(!e.ok)throw new Error(`Failed to fetch VTT: ${e.status} ${e.statusText}`);const t=await e.text();this.parseVTT(t),this.isLoaded=!0}catch(e){console.debug("[VTTThumbnailProvider] Error loading VTT:",e)}}parseVTT(e){const t=e.split(/\r?\n/);let i=null;const s=new URL(this.vttUrl,window.location.href),r=/([\d:.]+)\s*-->\s*([\d:.]+)/;for(let a=0;a<t.length;a++){const n=t[a].trim();if(!n)continue;const l=n.match(r);if(l){const o=this.parseTimestamp(l[1]),d=this.parseTimestamp(l[2]);i={start:o,end:d}}else if(i&&n.indexOf("-->")===-1&&n!=="WEBVTT"){const o=n,d=o.indexOf("#");let h=o,u,f,p,g;if(d!==-1){h=o.substring(0,d);const m=o.substring(d+1);if(m.startsWith("xywh=")){const v=m.substring(5).split(",").map(Number);v.length===4&&(u=v[0],f=v[1],p=v[2],g=v[3])}}i.url=new URL(h,s).href,u!==void 0&&(i.x=u),f!==void 0&&(i.y=f),p!==void 0&&(i.width=p),g!==void 0&&(i.height=g),this.cues.push(i),i=null}}}parseTimestamp(e){const t=e.trim().replace(",",".").split(":");let i=0;return t.length===3?(i+=parseFloat(t[0])*3600,i+=parseFloat(t[1])*60,i+=parseFloat(t[2])):t.length===2&&(i+=parseFloat(t[0])*60,i+=parseFloat(t[1])),i}getNearestCachedThumbnail(e){var s;if(((s=this.config)==null?void 0:s.cache)===!1)return null;let t=this.cues.find(r=>e>=r.start&&e<=r.end);if(!t&&this.cues.length>0){let r=1/0;for(const a of this.cues){const n=(a.start+a.end)/2,l=Math.abs(n-e);l<r&&(r=l,t=a)}}if(!t)return null;const i=this.cache.get(t.url);return i&&i.complete?{url:t.url,x:t.x,y:t.y,width:t.width,height:t.height,time:e}:null}async getThumbnail(e,t="high"){var r;this.loadPromise&&await this.loadPromise;let i=this.cues.find(a=>e>=a.start&&e<=a.end);if(!i&&this.cues.length>0){let a=1/0;for(const n of this.cues){const l=(n.start+n.end)/2,o=Math.abs(l-e);o<a&&(a=o,i=n)}}if(!i)return null;if(((r=this.config)==null?void 0:r.cache)!==!1)if(this.cache.has(i.url)){const a=this.cache.get(i.url);a.complete||await new Promise(n=>{a.onload=n,a.onerror=n})}else{const a=new Image;a.src=i.url,this.cache.set(i.url,a),a.complete||await new Promise(n=>{a.onload=n,a.onerror=n})}else{const a=new Image;a.src=i.url,a.complete||await new Promise(n=>{a.onload=n,a.onerror=n})}return{url:i.url,x:i.x,y:i.y,width:i.width,height:i.height,time:e}}destroy(){this.cache.clear(),this.cues=[]}isUnavailable(){return!this.vttUrl}}class es{constructor(e,t,i){this.type="sprite",this.cache=null,this.loadPromise=null,this.spriteUrl=e,this.spriteInfo=t,this.config=i}updateConfig(e){this.config=e}preloadImage(){return this.loadPromise?this.loadPromise:(this.loadPromise=new Promise(e=>{const t=new Image;t.onload=()=>{this.cache=t,e()},t.onerror=()=>{e()},t.src=this.spriteUrl}),this.loadPromise)}getNearestCachedThumbnail(e){var t;return((t=this.config)==null?void 0:t.cache)===!1?null:this.cache&&this.cache.complete?{...this.calculateThumbnail(e),time:e}:null}async getThumbnail(e,t="high"){return await this.preloadImage(),{...this.calculateThumbnail(e),time:e}}calculateThumbnail(e){const{tileWidth:t,tileHeight:i,totalColumns:s,interval:r}=this.spriteInfo,a=Math.floor((Math.max(0,e)+1e-4)/r),n=a%s,l=Math.floor(a/s);return{url:this.spriteUrl,x:n*t,y:l*i,width:t,height:i,time:a*r+r/2}}destroy(){this.cache=null,this.loadPromise=null}isUnavailable(){return!this.spriteUrl||!this.spriteInfo}}class _e{constructor(e){this.type="auto",this.currentProvider=null,this.currentSrc="",this.config=e}static resolveSmartSeek(e){if(e)return e.smartSeek&&typeof e.smartSeek=="object"?e.smartSeek:e}updateConfig(e){this.config=e;const t=_e.resolveSmartSeek(e);if(this.currentProvider){const i=this.currentProvider;typeof i.updateConfig=="function"?i.updateConfig(t):i.config=t}}setSource(e,t){var l;if(this.currentSrc===e)return;if(this.currentSrc=e,this.currentProvider&&typeof this.currentProvider.destroy=="function")try{this.currentProvider.destroy()}catch(o){console.debug("[AutoThumbnailProvider] Error destroying provider:",o)}this.currentProvider=null;const i=(t==null?void 0:t.smartSeek)||_e.resolveSmartSeek(this.config),s=(i==null?void 0:i.type)||"auto";if((i==null?void 0:i.enabled)===!1||s==="none")return;if(s==="vtt"||s==="auto"&&(i!=null&&i.vttUrl)){const o=(i==null?void 0:i.vttUrl)||(t==null?void 0:t.vttUrl);o&&(this.currentProvider=new Ji(o,i))}else if(s==="sprite"||s==="auto"&&(i!=null&&i.spriteUrl)&&i.spriteInfo){const o=i==null?void 0:i.spriteUrl,d=i==null?void 0:i.spriteInfo;o&&d&&(this.currentProvider=new es(o,d,i))}const r=(t==null?void 0:t.preciseSeek)||((l=this.config)==null?void 0:l.preciseSeek),a=typeof r=="object"&&r?r:void 0,n=r!==!1&&(a==null?void 0:a.enabled)!==!1&&(a==null?void 0:a.frameAccurate)!==!1;!this.currentProvider&&n&&(this.currentProvider=new Zi(i)),this.currentProvider&&typeof this.currentProvider.setSource=="function"&&this.currentProvider.setSource(e,t)}getNearestCachedThumbnail(e){return this.currentProvider&&typeof this.currentProvider.getNearestCachedThumbnail=="function"?this.currentProvider.getNearestCachedThumbnail(e):null}getThumbnail(e,t="high"){return this.currentProvider?this.currentProvider.getThumbnail(e,t):null}isUnavailable(){return this.currentProvider&&typeof this.currentProvider.isUnavailable=="function"?this.currentProvider.isUnavailable():!this.currentProvider}destroy(){this.currentProvider&&typeof this.currentProvider.destroy=="function"&&this.currentProvider.destroy(),this.currentProvider=null}}class pe{static timeToPercent(e,t,i){const s=i-t;return s<=0?0:Math.max(0,Math.min((e-t)/s*100,100))}static percentToTime(e,t,i){const s=i-t;return t+e/100*s}static clampToSeekable(e,t,i){return Math.max(t,Math.min(e,i))}static isMarkerVisible(e,t,i){return e>=t&&e<=i}static isWithinSeekable(e,t,i){return e>=t&&e<=i}static shouldPruneMarker(e,t){return e<t}static findNearestMarker(e,t,i,s){if(!t||t.length===0)return null;let r=null,a=1/0;for(const n of t){if(i&&!i.includes(n.type))continue;const l=Math.abs(n.time-e);l<a&&l<=s&&(a=l,r=n)}return r}static findNearestChapter(e,t,i){return!t||t.length===0?-1:t.findIndex((s,r)=>{const a=s.startTime,n=s.endTime!==void 0?s.endTime:t[r+1]?t[r+1].startTime:i||1/0;return e>=a&&e<n})}static findNearestChapterBoundary(e,t,i){if(!t||t.length===0)return null;let s=null,r=1/0;for(const a of t){const n=Math.abs(a.startTime-e);n<r&&n<=i&&(r=n,s=a)}return s}}class yr{constructor(e){var i;this.originalPlaylist=null,this.historyStack=[],this.nearEndThreshold=1,this.hasDispatchedNearEndForCurrentBoundary=!1,this.host=e;const t=(i=e.config)==null?void 0:i.nearEndThreshold;this.nearEndThreshold=t!==void 0?Math.max(1,t):1}get state(){return this.host.getState()}updateState(e){this.host.updateStatePublic(e)}dispatchEvent(e,t){this.host.dispatchEvent(e,t)}loadPlaylist(e,t=0){if(e.length===0){this.clearPlaylist();return}this.originalPlaylist=null;const i=Math.max(0,Math.min(t,e.length-1));this.historyStack=[],this.hasDispatchedNearEndForCurrentBoundary=!1,this.updateState({playlist:e,activePlaylistIndex:i}),this.dispatchEvent("playlist-loaded",{playlist:e,startIndex:i}),this.dispatchEvent("playlist-change",{playlist:e}),e.length>0&&this.loadPlaylistItem(i,!0)}setPlaylist(e,t=0){this.loadPlaylist(e,t)}setNearEndThreshold(e){this.nearEndThreshold=Math.max(1,e),this.hasDispatchedNearEndForCurrentBoundary=!1,this.checkPlaylistNearEnd()}getNearEndThreshold(){return this.nearEndThreshold}getPlaylist(){return this.state.playlist}getCurrentPlaylistIndex(){return this.state.activePlaylistIndex}getHistoryStack(){return[...this.historyStack]}getCurrentPlaylistItem(){if(!this.hasPlaylist())return null;const e=this.state.activePlaylistIndex;return e<0||e>=this.state.playlist.length?null:this.state.playlist[e]}getPlaylistLength(){return this.state.playlist.length}hasPlaylist(){return this.state.playlist.length>0}isFirstPlaylistItem(){return this.hasPlaylist()?this.state.activePlaylistIndex===0:!1}isLastPlaylistItem(){return this.hasPlaylist()?this.state.activePlaylistIndex===this.state.playlist.length-1:!1}next(){if(this.state.playlist.length<=1)return;const e=(this.state.activePlaylistIndex+1)%this.state.playlist.length,t=this.state.playlist[e];this.dispatchEvent("playlist-next",{index:e,source:t}),this.loadPlaylistItem(e,!1)}previous(){if(this.state.playlist.length<=1)return;let e;this.historyStack.length>0?e=this.historyStack.pop():e=(this.state.activePlaylistIndex-1+this.state.playlist.length)%this.state.playlist.length;const t=this.state.playlist[e];this.dispatchEvent("playlist-previous",{index:e,source:t}),this.loadPlaylistItem(e,!0)}appendPlaylistItem(e){const t=[...this.state.playlist,e];this.hasDispatchedNearEndForCurrentBoundary=!1,this.updateState({playlist:t}),this.dispatchEvent("playlist-change",{playlist:t}),this.dispatchEvent("playlist-item-added",{index:t.length-1,source:e}),t.length===1?this.loadPlaylistItem(0):this.checkPlaylistNearEnd()}insertPlaylistItem(e,t){if(e<0||e>this.state.playlist.length)return;this.hasDispatchedNearEndForCurrentBoundary=!1;const i=e,s=[...this.state.playlist];s.splice(i,0,t);let r=this.state.activePlaylistIndex;s.length>1&&i<=this.state.activePlaylistIndex&&(r=this.state.activePlaylistIndex+1);const a=r!==this.state.activePlaylistIndex;this.historyStack=this.historyStack.map(n=>n>=i?n+1:n),this.updateState({playlist:s,activePlaylistIndex:r}),this.dispatchEvent("playlist-change",{playlist:s}),this.dispatchEvent("playlist-item-added",{index:i,source:t}),s.length===1?this.loadPlaylistItem(0,!0):(a&&this.dispatchEvent("playlist-index-change",{index:r,source:s[r]}),this.checkPlaylistNearEnd())}removePlaylistItem(e){if(e<0||e>=this.state.playlist.length)return;this.hasDispatchedNearEndForCurrentBoundary=!1;const t=this.state.playlist[e],i=e===this.state.activePlaylistIndex,s=this.state.isPlaying,r=[...this.state.playlist];if(r.splice(e,1),this.historyStack=this.historyStack.filter(l=>l!==e).map(l=>l>e?l-1:l),r.length===0){this.updateState({playlist:[],activePlaylistIndex:0}),this.historyStack=[],this.dispatchEvent("playlist-change",{playlist:[]}),this.dispatchEvent("playlist-item-removed",{index:e,source:t}),this.dispatchEvent("playlist-cleared"),this.host.loadSource({src:""}),this.checkPlaylistNearEnd();return}let a=this.state.activePlaylistIndex;i?a=e>=r.length?0:e:e<this.state.activePlaylistIndex&&(a=this.state.activePlaylistIndex-1),a=Math.max(0,Math.min(a,r.length-1));const n=a!==this.state.activePlaylistIndex;this.updateState({playlist:r,activePlaylistIndex:a}),this.dispatchEvent("playlist-change",{playlist:r}),this.dispatchEvent("playlist-item-removed",{index:e,source:t}),i?(this.loadPlaylistItem(a,!0),s&&this.host.play()):(n&&this.dispatchEvent("playlist-index-change",{index:a,source:r[a]}),this.checkPlaylistNearEnd())}clearPlaylist(){this.state.playlist.length!==0&&(this.originalPlaylist=null,this.hasDispatchedNearEndForCurrentBoundary=!1,this.historyStack=[],this.updateState({playlist:[],activePlaylistIndex:0}),this.dispatchEvent("playlist-change",{playlist:[]}),this.dispatchEvent("playlist-cleared"),this.host.loadSource({src:""}),this.checkPlaylistNearEnd())}replacePlaylistItem(e,t){if(e<0||e>=this.state.playlist.length)return;this.hasDispatchedNearEndForCurrentBoundary=!1;const i=[...this.state.playlist];i[e]=t;const s=e===this.state.activePlaylistIndex,r=this.state.isPlaying;this.updateState({playlist:i}),this.dispatchEvent("playlist-change",{playlist:i}),this.dispatchEvent("playlist-item-replaced",{index:e,source:t}),s?(this.loadPlaylistItem(e,!0),r&&this.host.play()):this.checkPlaylistNearEnd()}movePlaylistItem(e,t){if(e<0||e>=this.state.playlist.length||t<0||t>=this.state.playlist.length||e===t)return;this.hasDispatchedNearEndForCurrentBoundary=!1;const i=[...this.state.playlist],[s]=i.splice(e,1);i.splice(t,0,s);const r=this.state.activePlaylistIndex;let a=r;r===e?a=t:e<r&&r<=t?a=r-1:t<=r&&r<e&&(a=r+1);const n=a!==r;if(this.historyStack=this.historyStack.map(l=>l===e?t:e<l&&l<=t?l-1:t<=l&&l<e?l+1:l),this.updateState({playlist:i,activePlaylistIndex:a}),this.dispatchEvent("playlist-change",{playlist:i}),this.dispatchEvent("playlist-item-moved",{fromIndex:e,toIndex:t,source:s}),n){const l=i[a];this.dispatchEvent("playlist-index-change",{index:a,source:l})}this.checkPlaylistNearEnd()}loadPlaylistItem(e,t=!1){if(e<0||e>=this.state.playlist.length)return;const i=this.state.activePlaylistIndex;this.updateState({activePlaylistIndex:e});const s=this.state.playlist[e];this.dispatchEvent("playlist-index-change",{index:e,source:s}),!t&&i!==e&&this.historyStack.push(i),this.host.loadSource(s,!1),this.checkPlaylistNearEnd()}setPlaylistRepeatMode(e){(e==="off"||e==="repeat-all")&&(this.updateState({playlistRepeatMode:e}),this.dispatchEvent("playlist-repeat-change",{repeatMode:e}))}getPlaylistRepeatMode(){return this.state.playlistRepeatMode}getAutoAdvanceIndexOnEnded(){var t,i;if(this.state.loop&&this.state.displayMode!=="vertical"||this.state.playlist.length<=1)return null;if(!this.isLastPlaylistItem())return(this.state.activePlaylistIndex+1)%this.state.playlist.length;if(this.state.playlistRepeatMode==="repeat-all"||this.state.displayMode==="vertical"){const s=((i=(t=this.host.config)==null?void 0:t.vertical)==null?void 0:i.loopPlaylist)!==!1;return this.state.displayMode==="vertical"&&!s?null:0}return null}checkPlaylistNearEnd(){if(!this.hasPlaylist()){this.hasDispatchedNearEndForCurrentBoundary=!1;return}const e=this.getPlaylistLength(),t=this.getCurrentPlaylistIndex(),i=Math.max(1,e),s=Math.max(1,Math.min(this.nearEndThreshold,i)),r=e-1-t;r<=s?this.hasDispatchedNearEndForCurrentBoundary||(this.hasDispatchedNearEndForCurrentBoundary=!0,this.dispatchEvent("playlist-near-end",{index:t,length:e,remainingItems:r,threshold:s})):this.hasDispatchedNearEndForCurrentBoundary=!1}clearForExternalSourceLoad(){this.originalPlaylist=null,this.updateState({playlist:[],activePlaylistIndex:0}),this.historyStack=[],this.dispatchEvent("playlist-change",{playlist:[]}),this.dispatchEvent("playlist-cleared")}destroy(){this.originalPlaylist=null,this.historyStack=[],this.hasDispatchedNearEndForCurrentBoundary=!1}}const oe={getItem(c){try{if(typeof localStorage<"u")return localStorage.getItem(c)}catch{}return null},setItem(c,e){try{typeof localStorage<"u"&&localStorage.setItem(c,e)}catch{}}},br={fontFamily:"default",fontSize:75,fontColor:"white",backgroundColor:"black",backgroundOpacity:75,windowColor:"black",windowOpacity:0,characterEdgeStyle:"none",fontOpacity:100};class kr{constructor(e,t){this.defaultAppearance={...br},this.managedTracks=[],this.managedActiveTrackId=null,this.managedActiveTrackIndex=-1,this.subtitleBlobUrls=[],this.handleTrackChange=()=>{this.refreshSubtitleTracks()},this.host=e,this.sourceManager=t}get video(){return this.host.getVideoElement()}get state(){return this.host.getState()}updateState(e){this.host.updateStatePublic(e)}dispatchEvent(e,t){this.host.dispatchEvent(e,t)}getDefaultAppearance(){return this.defaultAppearance}readPersistedSettings(){let e=!1,t={...this.defaultAppearance};try{const i=oe.getItem("player_subtitles_enabled");i!==null&&(e=i==="true");const s=oe.getItem("player_subtitle_appearance");if(s!==null){const r=JSON.parse(s);t={...this.defaultAppearance,...r}}}catch(i){console.warn("Failed to load persisted subtitles settings:",i)}return{captionsEnabled:e,appearance:t}}attach(){const e=this.video;e.textTracks&&typeof e.textTracks.addEventListener=="function"&&(e.textTracks.addEventListener("addtrack",this.handleTrackChange),e.textTracks.addEventListener("removetrack",this.handleTrackChange),e.textTracks.addEventListener("change",this.handleTrackChange)),this.syncSubtitleAppearance()}detach(){const e=this.video;e.textTracks&&typeof e.textTracks.removeEventListener=="function"&&(e.textTracks.removeEventListener("addtrack",this.handleTrackChange),e.textTracks.removeEventListener("removetrack",this.handleTrackChange),e.textTracks.removeEventListener("change",this.handleTrackChange))}setManagedSubtitleTracks(e,t,i){if(this.managedTracks=t.map((s,r)=>({id:`${e}-${s.language||"unknown"}-${r}`,language:s.language||"",label:s.label||s.language||`Track ${r+1}`,default:!!s.default,forced:!!s.forced,kind:s.kind||"subtitles",source:e,index:r})),this.managedActiveTrackIndex=i,i>=0&&i<this.managedTracks.length?this.managedActiveTrackId=this.managedTracks[i].id:this.managedActiveTrackId=null,this.refreshSubtitleTracks(),this.state.captionsEnabled&&this.state.activeSubtitleTrackId===null){const s=oe.getItem("player_subtitle_language");let r=s?this.state.subtitleTracks.find(a=>a.language===s||a.id===s):null;r||(r=this.state.subtitleTracks.find(a=>a.default)||this.state.subtitleTracks[0]),r&&this.setSubtitleTrack(r.id)}}refreshSubtitleTracks(){const e=this.sourceManager.getActiveHandler();let t=[],i=null,s=-1,r=!1;if(e&&e.managesSubtitles){t=[...this.managedTracks],i=this.managedActiveTrackId,s=this.managedActiveTrackIndex;const o=this.video.textTracks;if(o&&o.length>0){let d=t.length;for(let h=0;h<o.length;h++){const u=o[h];if(u.kind==="subtitles"||u.kind==="captions"){if(u._zombie)continue;if(this.managedTracks.some(m=>m.label===u.label&&m.language===u.language||u.language&&m.language===u.language)){if(u.mode==="showing"){const m=this.managedTracks.find(v=>v.label===u.label&&v.language===u.language||u.language&&v.language===u.language);m&&(i=m.id,s=m.index??-1)}continue}const p=u.id||`native-embedded-${u.language||"unknown"}-${d}`,g=u.default||!1;t.push({id:p,language:u.language||"",label:u.label||u.language||`Embedded Track ${d+1}`,default:g,forced:!1,kind:u.kind,source:"native",index:h}),u.mode==="showing"&&(i=p,s=d),d++}}}r=t.length>0}else{const o=this.video.textTracks;if(o&&o.length>0){let d=0;for(let h=0;h<o.length;h++){const u=o[h];if(u.kind==="subtitles"||u.kind==="captions"){if(u._zombie)continue;const f=u.id||`native-${u.language||"unknown"}-${d}`,p=u.default||!1;t.push({id:f,language:u.language||"",label:u.label||u.language||`Track ${d+1}`,default:p,forced:!1,kind:u.kind,source:"native",index:h}),u.mode==="showing"&&(i=f,s=d),d++}}}r=t.length>0}const a=i!==null;if(!a){const o=this.video.textTracks;if(o)for(let d=0;d<o.length;d++)o[d].mode==="showing"&&(o[d].mode="disabled")}const n=JSON.stringify(this.state.subtitleTracks)!==JSON.stringify(t),l=this.state.activeSubtitleTrackId!==i||this.state.activeSubtitleTrack!==s||this.state.captionsEnabled!==a;if(this.updateState({subtitleTracks:t,activeSubtitleTrack:s,activeSubtitleTrackId:i,captionsEnabled:a,hasCaptions:r}),n&&this.dispatchEvent("subtitletrackschanged",{tracks:t}),l){const o=t.find(d=>d.id===i)||null;this.dispatchEvent("subtitletrackchange",{activeTrack:o}),a?this.dispatchEvent("subtitleenabled",{activeTrack:o}):this.dispatchEvent("subtitledisabled");try{oe.setItem("player_subtitles_enabled",a.toString()),o&&oe.setItem("player_subtitle_language",o.language||o.id)}catch{}}this.dispatchEvent("subtitlechange",{activeSubtitleTrack:s})}loadCaptions(e){this.video.querySelectorAll("track").forEach(a=>a.remove());const i=document.createElement("track");i.kind="subtitles",i.label=e.label,i.srclang=e.srclang,i.src=e.src,e.default&&(i.default=!0),this.video.appendChild(i);const s=oe.getItem("player_subtitles_enabled");(s!==null?s==="true":!!e.default)&&setTimeout(()=>this.toggleCaptions(!0),100),this.refreshSubtitleTracks()}toggleCaptions(e){if(e!==void 0?e:!this.state.captionsEnabled){const i=this.state.subtitleTracks;if(i.length>0){const s=oe.getItem("player_subtitle_language"),r=i.find(a=>a.language===s||a.id===s||a.default)||i[0];this.setSubtitleTrack(r.id)}else{const s=this.video.textTracks;s&&s.length>0?(s[0].mode="showing",this.refreshSubtitleTracks()):this.updateState({captionsEnabled:!0})}}else this.disableSubtitles()}setSubtitleTrack(e){const t=this.state.subtitleTracks;let i;if(typeof e=="number"?i=t[e]:i=t.find(r=>r.id===e),!i){this.disableSubtitles();return}const s=this.sourceManager.getActiveHandler();if(s&&s.managesSubtitles&&i.source!=="native")s.setSubtitleTrack&&i.index!==void 0&&(s.setSubtitleTrack(i.index),this.managedActiveTrackId=i.id,this.managedActiveTrackIndex=i.index);else{const r=this.video.textTracks;if(r&&i.index!==void 0)for(let a=0;a<r.length;a++)(r[a].kind==="subtitles"||r[a].kind==="captions")&&(r[a].mode=a===i.index?"showing":"disabled")}this.refreshSubtitleTracks()}disableSubtitles(){const e=this.sourceManager.getActiveHandler();if(e&&e.managesSubtitles)e.setSubtitleTrack&&(e.setSubtitleTrack(-1),this.managedActiveTrackId=null,this.managedActiveTrackIndex=-1);else{const t=this.video.textTracks;if(t)for(let i=0;i<t.length;i++)(t[i].kind==="subtitles"||t[i].kind==="captions")&&(t[i].mode="disabled")}this.refreshSubtitleTracks()}hasSubtitles(){return this.state.hasCaptions}getSubtitleTracks(){return this.state.subtitleTracks}getActiveSubtitleTrack(){const e=this.state.subtitleTracks,t=this.state.activeSubtitleTrackId;return e.find(i=>i.id===t)||null}getSubtitleAppearance(){return this.state.subtitleAppearance}setSubtitleAppearance(e){const t={...this.state.subtitleAppearance,...e};this.updateState({subtitleAppearance:t});try{oe.setItem("player_subtitle_appearance",JSON.stringify(t))}catch{}this.syncSubtitleAppearance(),this.dispatchEvent("subtitleappearancechange",{appearance:t})}resetSubtitleAppearance(){this.setSubtitleAppearance(this.defaultAppearance)}syncSubtitleAppearance(){const e=this.state.subtitleAppearance,t=this.video;if(!t)return;const i={white:"255, 255, 255",black:"0, 0, 0",red:"255, 0, 0",green:"0, 255, 0",blue:"0, 0, 255",yellow:"255, 255, 0",magenta:"255, 0, 255",cyan:"0, 255, 255"},s={default:"inherit","proportional-sans-serif":"'Outfit', 'Inter', system-ui, -apple-system, sans-serif","monospace-sans-serif":"'Courier New', 'Andale Mono', monospace","proportional-serif":"'Georgia', 'Times New Roman', serif","monospace-serif":"'Courier New', 'Courier', serif",casual:"'Comic Sans MS', 'Chalkboard SE', sans-serif",cursive:"'Comic Sans MS', 'Lucida Handwriting', cursive","small-capitals":"'Outfit', 'Inter', system-ui, sans-serif"},r={default:"none",none:"none",raised:"1px 1px 0px #000, 2px 2px 0px #000, -1px -1px 0px #fff",depressed:"1px 1px 0px #fff, -1px -1px 0px #000",uniform:"-1px -1px 0 #000, 1px -1px 0 #000, -1px 1px 0 #000, 1px 1px 0 #000","drop-shadow":"2px 2px 4px rgba(0, 0, 0, 0.8)"},a=i[e.fontColor.toLowerCase()]||"255, 255, 255",n=(e.fontOpacity/100).toFixed(2),l=`rgba(${a}, ${n})`,o=i[e.backgroundColor.toLowerCase()]||"0, 0, 0",d=(e.backgroundOpacity/100).toFixed(2),h=`rgba(${o}, ${d})`,u=i[e.windowColor.toLowerCase()]||"0, 0, 0",f=(e.windowOpacity/100).toFixed(2),p=`rgba(${u}, ${f})`,g=s[e.fontFamily]||"inherit",m=`${e.fontSize}%`,v=r[e.characterEdgeStyle]||"none",y=e.fontFamily==="small-capitals"?"small-caps":"normal";t.style.setProperty("--player-cue-font-family",g),t.style.setProperty("--player-cue-font-size",m),t.style.setProperty("--player-cue-font-color",l),t.style.setProperty("--player-cue-background-color",h),t.style.setProperty("--player-cue-text-shadow",v),t.style.setProperty("--player-cue-window-color",p),t.style.setProperty("--player-cue-font-variant",y)}revokeBlobUrls(){this.subtitleBlobUrls&&(this.subtitleBlobUrls.forEach(e=>{try{typeof URL<"u"&&typeof URL.revokeObjectURL=="function"&&URL.revokeObjectURL(e)}catch{}}),this.subtitleBlobUrls=[])}resetManagedTracks(){this.managedTracks=[],this.managedActiveTrackId=null,this.managedActiveTrackIndex=-1}attachSourceSubtitles(e){if(!e||e.length===0)return;e.forEach(r=>{const a=document.createElement("track");a.kind="subtitles",a.label=r.label,a.srclang=r.srclang,r.default&&(a.default=!0),r.src&&(r.src.startsWith("http")||r.src.startsWith("//"))?fetch(r.src).then(n=>{if(!n.ok)throw new Error(`HTTP error ${n.status}`);return n.text()}).then(n=>{const l=new Blob([n],{type:"text/vtt"});if(typeof URL<"u"&&typeof URL.createObjectURL=="function"){const o=URL.createObjectURL(l);a.src=o,this.subtitleBlobUrls.push(o),this.refreshSubtitleTracks()}else a.src=r.src}).catch(n=>{console.error(`Failed to load external subtitle track from ${r.src}:`,n),a.src=r.src}):a.src=r.src,this.video.appendChild(a)});const t=e.find(r=>r.default)||e[0],i=oe.getItem("player_subtitles_enabled");(i!==null?i==="true":!!t.default)&&setTimeout(()=>this.toggleCaptions(!0),100)}}class Sr{constructor(e){this.handleEnterPiP=()=>{this.host.updateStatePublic({pictureInPicture:!0}),this.host.dispatchEvent("pipchange",{isPictureInPicture:!0})},this.handleLeavePiP=()=>{this.host.updateStatePublic({pictureInPicture:!1}),this.host.dispatchEvent("pipchange",{isPictureInPicture:!1})},this.handleWebkitPresentationModeChanged=()=>{const t=this.video.webkitPresentationMode==="picture-in-picture";this.host.updateStatePublic({pictureInPicture:t}),this.host.dispatchEvent("pipchange",{isPictureInPicture:t})},this.host=e}get video(){return this.host.getVideoElement()}get state(){return this.host.getState()}detectSupport(){const e=this.video,t=!!(typeof document<"u"&&document.pictureInPictureEnabled&&typeof e.requestPictureInPicture=="function"),i=!!(typeof e.webkitSupportsPresentationMode=="function"&&e.webkitSupportsPresentationMode("picture-in-picture"));return t||i}attach(){const e=this.video;e.addEventListener("enterpictureinpicture",this.handleEnterPiP),e.addEventListener("leavepictureinpicture",this.handleLeavePiP),e.addEventListener("webkitpresentationmodechanged",this.handleWebkitPresentationModeChanged)}detach(){const e=this.video;e.removeEventListener("enterpictureinpicture",this.handleEnterPiP),e.removeEventListener("leavepictureinpicture",this.handleLeavePiP),e.removeEventListener("webkitpresentationmodechanged",this.handleWebkitPresentationModeChanged)}isPictureInPictureSupported(){return this.state.pictureInPictureSupported}async enterPictureInPicture(){if(!this.state.pictureInPictureSupported){console.warn("[PlayerController] Picture-in-Picture is not supported in this environment.");return}try{if(typeof this.video.requestPictureInPicture=="function")return await this.video.requestPictureInPicture();{const e=this.video;typeof e.webkitSetPresentationMode=="function"&&e.webkitSetPresentationMode("picture-in-picture")}}catch(e){console.warn("[PlayerController] Failed to enter Picture-in-Picture mode:",e)}}async exitPictureInPicture(){if(!this.state.pictureInPictureSupported){console.warn("[PlayerController] Picture-in-Picture is not supported in this environment.");return}try{if(typeof document.exitPictureInPicture=="function"){const e=document.pictureInPictureElement,t=this.video.getRootNode().pictureInPictureElement;(!e||e===this.video||t===this.video)&&await document.exitPictureInPicture()}else{const e=this.video;typeof e.webkitSetPresentationMode=="function"&&e.webkitSetPresentationMode("inline")}}catch(e){console.warn("[PlayerController] Failed to exit Picture-in-Picture mode:",e)}}isInPictureInPicture(){return this.state.pictureInPicture}}function ts(c,e,t){if(e===t)return!0;if(e==null||t==null)return e===t;if(c==="seekableRange"){const i=e,s=t;return i.start===s.start&&i.end===s.end}if(c==="bufferedRanges"){const i=e,s=t;if(i.length!==s.length)return!1;for(let r=0;r<i.length;r++)if(i[r].start!==s[r].start||i[r].end!==s[r].end)return!1;return!0}if(c==="subtitleAppearance"){const i=e,s=t;return i.fontFamily===s.fontFamily&&i.fontSize===s.fontSize&&i.fontColor===s.fontColor&&i.backgroundColor===s.backgroundColor&&i.backgroundOpacity===s.backgroundOpacity&&i.windowColor===s.windowColor&&i.windowOpacity===s.windowOpacity&&i.characterEdgeStyle===s.characterEdgeStyle&&i.fontOpacity===s.fontOpacity}if(c==="qualities"||c==="audioTracks"){const i=e,s=t;if(i.length!==s.length)return!1;for(let r=0;r<i.length;r++)if(i[r]!==s[r])return!1;return!0}if(c==="subtitleTracks"){const i=e,s=t;if(i.length!==s.length)return!1;for(let r=0;r<i.length;r++){const a=i[r],n=s[r];if(a.id!==n.id||a.language!==n.language||a.label!==n.label||a.default!==n.default||a.forced!==n.forced||a.kind!==n.kind||a.source!==n.source||a.index!==n.index)return!1}return!0}if(c==="chapters"){const i=e,s=t;if(i.length!==s.length)return!1;for(let r=0;r<i.length;r++){const a=i[r],n=s[r];if(a.id!==n.id||a.title!==n.title||a.startTime!==n.startTime||a.endTime!==n.endTime||a.description!==n.description)return!1}return!0}if(c==="markers"){const i=e,s=t;if(i.length!==s.length)return!1;for(let r=0;r<i.length;r++){const a=i[r],n=s[r];if(a.id!==n.id||a.time!==n.time||a.label!==n.label||a.type!==n.type||a.color!==n.color)return!1}return!0}if(c==="playlist"){const i=e,s=t;if(i.length!==s.length)return!1;for(let r=0;r<i.length;r++){const a=i[r],n=s[r];if(a.src!==n.src||a.type!==n.type)return!1}return!0}return typeof e=="object"&&typeof t=="object"?JSON.stringify(e)===JSON.stringify(t):!1}function wr(c){if(Array.isArray(c))return c;if(c&&typeof c=="object"){const e=c.list;if(Array.isArray(e))return e}}class is{constructor(e,t={}){var l;if(this.sourceManager=new Zs,this.stateCallbacks=new Set,this.analyticsHandlers=new Set,this.playbackInterceptors=new Set,this.pendingOverlays=new Map,this.plugins=new Map,this.eventListeners=new Map,this.isDestroyed=!1,this.preSeekVolume=null,this.lastFpsTimestamp=0,this.lastDecodedFrames=0,this.lastCalculatedFps=0,this.handleVisibilityChange=()=>{typeof document<"u"&&document.visibilityState==="visible"&&this.sleepTimerEndTimeMs&&!this.state.sleepTimerExpired&&this.tickSleepTimer()},this.state={status:"idle",isPlaying:!1,currentTime:0,duration:0,volume:1,isMuted:!1,isFullscreen:!1,bufferedRanges:[],playbackRate:1,captionsEnabled:!1,currentSource:null,sourceType:"unknown",isBuffering:!1,isSeeking:!1,hasCaptions:!1,error:null,qualities:[],activeQuality:"Auto",audioTracks:[],activeAudioTrack:-1,subtitleTracks:[],activeSubtitleTrack:-1,activeSubtitleTrackId:null,subtitleAppearance:{fontFamily:"default",fontSize:100,fontColor:"white",backgroundColor:"black",backgroundOpacity:75,windowColor:"black",windowOpacity:0,characterEdgeStyle:"none",fontOpacity:100},isLive:null,isLowLatency:!1,isAtLiveEdge:!1,liveLatency:null,hasDvr:!1,dvrWindow:0,canSeekInDvr:!1,seekableRange:{start:0,end:0},liveMode:"live-dvr",thumbnailProvider:void 0,pictureInPicture:!1,pictureInPictureSupported:!1,loop:!1,sleepTimerSetting:"off",sleepTimerSecondsRemaining:null,sleepTimerExpired:!1,chapters:[],activeChapterIndex:-1,markers:[],visibleMarkerTypes:null,displayMode:"standard",playlist:[],activePlaylistIndex:0,playlistRepeatMode:"off",autoScroll:!1,isAdPlaying:!1,isAdLoading:!1,currentAd:null,currentAdBreak:null,adCurrentTime:null,adRemainingTime:null,adDuration:null,canSkipAd:!1,skipAvailableAt:null,adPosition:null,adProvider:null,adLinear:null,adMuted:null},this.hlsRetryCount=0,this.lastNonZeroVolume=1,this.handlePlay=()=>{const o=this.state.status,d=o==="loading"||o==="buffering"?o:"playing";this.updateState({isPlaying:!0,status:d}),this.startStallCheck(),this.dispatchEvent("play"),this.updateMediaSessionPlaybackState(!0),this.updateMediaSessionPosition()},this.handlePause=()=>{const o=this.state.status,d=o==="playing"||o==="buffering"||o==="ready"?"paused":o;this.updateState({isPlaying:!1,status:d}),this.stopStallCheck(),this.dispatchEvent("pause"),this.updateMediaSessionPlaybackState(!1),this.updateMediaSessionPosition()},this.handleWaiting=()=>{this.clearBufferingTimeout();const o=this.state.status,d=o==="playing"||o==="ready"||o==="paused"?"buffering":o;this.bufferingTimeout=window.setTimeout(()=>{this.bufferingTimeout=void 0,this.updateState({isBuffering:!0,status:d})},250),this.dispatchEvent("waiting")},this.handlePlaying=()=>{this.clearBufferingTimeout(),this.updateState({isBuffering:!1,isPlaying:!0,error:null,status:"playing"}),this.dispatchEvent("playing")},this.handleSeeking=()=>{this.clearBufferingTimeout();let o=this.state.status;o==="ended"&&(o=this.video.paused?"paused":"playing");const d=o==="playing"||o==="ready"||o==="paused"?"buffering":o;this.updateState({isSeeking:!0,status:d}),this.dispatchEvent("seekstart"),this.bufferingTimeout=window.setTimeout(()=>{this.bufferingTimeout=void 0,this.updateState({isBuffering:!0})},250)},this.handleSeeked=()=>{this.clearBufferingTimeout();let o=this.state.status;o==="ended"&&(o=this.video.paused?"paused":"playing");let d=o;o==="buffering"&&(d=this.video.paused?"paused":"playing"),this.updateState({isBuffering:!1,status:d,isSeeking:!1}),this.handleTimeUpdate(),this.dispatchEvent("seekend")},this.handleCanPlay=()=>{if(this.clearBufferingTimeout(),this.state.isBuffering){const o=this.state.status;let d=o;o==="buffering"&&(d=this.video.paused?"paused":"playing"),this.updateState({isBuffering:!1,status:d})}},this.handleNativeError=o=>{if(o&&o.target&&o.target!==this.video)return;this.clearBufferingTimeout();const d=this.video.error?this.video.error.code:0;let h="An unknown video error occurred.";switch(d){case 1:h="Video loading aborted by user.";break;case 2:h="Network error occurred while fetching video content.";break;case 3:h="Video decoding failed. File may be corrupted.";break;case 4:h="Video format or codec is not supported by your browser.";break}this.updateState({error:h,isBuffering:!1,status:"error"}),this.dispatchEvent("error",{message:h})},this.handleTimeUpdate=()=>{if(this.state.isSeeking)return;const o=this.video.currentTime;if(o!==this.state.currentTime&&(this.state.isBuffering||this.bufferingTimeout)){this.clearBufferingTimeout();const f=this.state.status;let p=f;f==="buffering"&&(p=this.video.paused?"paused":"playing"),this.updateState({isBuffering:!1,status:p})}const d=this.getSeekableStateBatch(),h=pe.findNearestChapter(o,this.state.chapters||[],this.video.duration||1/0),u=h!==this.state.activeChapterIndex;this.updateState({currentTime:o,activeChapterIndex:h}),this.dispatchEvent("timeupdate",{currentTime:o,duration:this.state.duration||this.video.duration||0}),this.state.isLive?this.updateLiveState():this.updateState({isLive:d.isLive,hasDvr:d.hasDvr,seekableRange:d.seekableRange,dvrWindow:d.dvrWindow,canSeekInDvr:d.canSeekInDvr}),u&&this.dispatchEvent("chapterchange",{activeChapterIndex:h,chapter:h!==-1?this.state.chapters[h]:null}),this.updateMediaSessionPosition()},this.handleDurationChange=()=>{if(this.state.isLive)this.updateLiveState();else{const o=this.getSeekableStateBatch();this.updateState({duration:this.video.duration,isLive:o.isLive,hasDvr:o.hasDvr,seekableRange:o.seekableRange,dvrWindow:o.dvrWindow,canSeekInDvr:o.canSeekInDvr})}this.updateMediaSessionPosition()},this.handleVolumeChange=()=>{if(this.preSeekVolume!==null){this.video.volume===this.preSeekVolume&&(this.preSeekVolume=null);return}this.video.volume>0&&(this.lastNonZeroVolume=this.video.volume),this.updateState({volume:this.video.volume,isMuted:this.video.muted});try{oe.setItem("player_volume",this.video.volume.toString()),oe.setItem("player_muted",this.video.muted.toString())}catch{}this.dispatchEvent("volumechange",{volume:this.video.volume}),this.dispatchEvent("mutechange",{isMuted:this.video.muted})},this.handleProgress=()=>{const o=this.video.buffered,d=[];for(let h=0;h<o.length;h++)d.push({start:o.start(h),end:o.end(h)});if(this.updateState({bufferedRanges:d}),this.state.isLive)this.updateLiveState();else{const h=this.getSeekableStateBatch();this.updateState({isLive:h.isLive,hasDvr:h.hasDvr,seekableRange:h.seekableRange,dvrWindow:h.dvrWindow,canSeekInDvr:h.canSeekInDvr})}},this.handleLoadedMetadata=()=>{this.video.playbackRate=this.state.playbackRate;const o=this.state.status,d=o==="loading"||o==="idle"?"ready":o;if(this.updateState({status:d}),this.state.isLive){if(this.updateLiveState(),this.video.paused&&this.video.currentTime===0){const h=()=>{this.video.seekable.length>0&&(this.seekToLiveEdge(),this.video.removeEventListener("canplay",h),this.video.removeEventListener("timeupdate",h))};this.video.seekable.length>0?this.seekToLiveEdge():(this.video.addEventListener("canplay",h),this.video.addEventListener("timeupdate",h))}}else{const h=this.getSeekableStateBatch();this.updateState({isLive:h.isLive,hasDvr:h.hasDvr,seekableRange:h.seekableRange,dvrWindow:h.dvrWindow,canSeekInDvr:h.canSeekInDvr})}},this.handleEnded=()=>{this.state.loop&&this.state.displayMode!=="vertical"?(this.seek(0),this.play()):(this.updateState({isPlaying:!1,status:"ended"}),this.stopStallCheck(),this.state.sleepTimerSetting==="end"&&(this.clearSleepTimer(),this.triggerSleepTimerExpiration()),this.dispatchEvent("ended"))},this.handleFullscreenChange=()=>{const o=document,d=!!(document.fullscreenElement||o.webkitFullscreenElement||o.mozFullScreenElement||o.msFullscreenElement);this.updateState({isFullscreen:d}),this.dispatchEvent("fullscreenchange",{isFullscreen:d})},this.handleWebkitBeginFullscreen=()=>{this.updateState({isFullscreen:!0}),this.dispatchEvent("fullscreenchange",{isFullscreen:!0})},this.handleWebkitEndFullscreen=()=>{this.updateState({isFullscreen:!1}),this.dispatchEvent("fullscreenchange",{isFullscreen:!1})},this.video=e,this.validateConfig(t),this.config=this.createUnifiedConfig(t),this.shortcuts=new Ni(this),this.ads=new Yi(this),this.playlistManager=new yr(this),this.subtitleManager=new kr(this,this.sourceManager),this.pictureInPictureManager=new Sr(this),t.shortcuts&&t.shortcuts.enabled===!1&&this.shortcuts.disable(),this.isPluginsEnabled()&&t.plugins){const o=wr(t.plugins);if(o)for(const d of o)this.use(d)}if(this.isAnalyticsEnabled()&&t.analytics&&Array.isArray(t.analytics.handlers))for(const o of t.analytics.handlers)this.registerAnalyticsHandler(o);const i=t.smartSeek;i!==!1&&(typeof i!="object"||i.enabled!==!1)&&(t.thumbnailProvider?this.thumbnailProvider=t.thumbnailProvider:this.thumbnailProvider=new _e(t)),this.state.thumbnailProvider=this.thumbnailProvider,this.state.pictureInPictureSupported=this.pictureInPictureManager.detectSupport(),this.config.live&&this.config.live.mode&&(this.state.liveMode=this.config.live.mode),this.config.autoplay&&(this.video.autoplay=!0),this.config.playsinline!==!1&&this.video.setAttribute("playsinline","true"),this.config.preload&&(this.video.preload=this.config.preload),this.config.poster&&this.video.setAttribute("poster",this.config.poster);const r=this.config.crossorigin;r&&this.video.setAttribute("crossorigin",r);try{const o=oe.getItem("player_volume");if(o!==null){const h=parseFloat(o);!isNaN(h)&&h>=0&&h<=1&&(this.video.volume=h,this.state.volume=h)}else t.volume!==void 0&&(this.video.volume=t.volume,this.state.volume=t.volume);const d=oe.getItem("player_muted");if(d!==null){const h=d==="true";this.video.muted=h,this.state.isMuted=h}else t.muted!==void 0&&(this.video.muted=t.muted,this.state.isMuted=t.muted)}catch{t.volume!==void 0&&(this.video.volume=t.volume),t.muted!==void 0&&(this.video.muted=t.muted)}try{const o=oe.getItem("player_loop");if(o!==null){const d=o==="true";this.video.loop=d,this.state.loop=d}else t.loop&&(this.video.loop=!0,this.state.loop=!0)}catch{t.loop&&(this.video.loop=!0)}try{const o=oe.getItem("player_auto_scroll");o!==null?this.state.autoScroll=o==="true":t.autoScroll!==void 0&&(this.state.autoScroll=t.autoScroll)}catch{t.autoScroll!==void 0&&(this.state.autoScroll=t.autoScroll)}this.state.volume=this.video.volume,this.state.isMuted=this.video.muted,this.lastNonZeroVolume=this.video.volume>0?this.video.volume:.5;try{const o=oe.getItem("player_playback_rate");if(o){const d=parseFloat(o);!isNaN(d)&&d>0&&d<=4&&(this.state.playbackRate=d,this.video.playbackRate=d)}}catch{}const a=this.subtitleManager.readPersistedSettings();this.state.captionsEnabled=a.captionsEnabled,this.state.subtitleAppearance=a.appearance;const n=t.displayMode!==void 0?t.displayMode:(l=t.layout)==null?void 0:l.mode;n!==void 0&&["standard","vertical","audio-only","custom","mini","floating"].includes(n)&&(this.state.displayMode=n,this.config.displayMode=n,this.config.layout||(this.config.layout={}),this.config.layout.mode=n),t.playlistRepeatMode!==void 0&&(this.state.playlistRepeatMode=t.playlistRepeatMode),this.setupEventListeners(),this.on("metadata",o=>{var p,g;if(this.state.isLive&&!this.state.hasDvr)return;const d=typeof((p=o.parsedData)==null?void 0:p.title)=="string"?o.parsedData.title:void 0,h=typeof((g=o.parsedData)==null?void 0:g.description)=="string"?o.parsedData.description:void 0,u=d||h||o.type,f=`meta-${o.timestamp}-${o.type}-${Math.random().toString(36).substr(2,9)}`;this.addMarker({id:f,time:o.timestamp,label:u,type:"metadata",color:"#a855f7",metadata:o})})}createUnifiedConfig(e){e||(e={}),e.controls||(e.controls={}),e.settings||(e.settings={});let t=e.settings.order;const i=l=>{const o=l;return o==="enabled"?"settings":o==="speed"?"playbackSpeed":o==="audio"||o==="audioTracks"?"audioTracks":o==="captions"||o==="subtitles"?"subtitles":o==="pip"||o==="pictureInPicture"?"pictureInPicture":o},s={};Object.keys(e.controls).forEach(l=>{s[i(l)]=e.controls[l]}),Object.keys(e.settings).forEach(l=>{s[i(l)]=e.settings[l]});const r={get:(l,o)=>{if(o==="toJSON")return()=>{const h={...s};return t!==void 0&&(h.order=t),h};if(o==="order")return t;const d=i(o);return s[d]},set:(l,o,d)=>{if(o==="order")return t=d,!0;const h=i(o);return s[h]=d,n&&this.dispatchEvent("config-change",n),!0},has:(l,o)=>o==="order"?t!==void 0:i(o)in s,ownKeys:()=>{const l=new Set(Object.keys(s));return t!==void 0&&l.add("order"),Array.from(l)},getOwnPropertyDescriptor:(l,o)=>{const d=i(o);if(o==="order")return t===void 0?void 0:{enumerable:!0,configurable:!0,writable:!0,value:t};if(d in s)return{enumerable:!0,configurable:!0,writable:!0,value:s[d]}}};e.controls=new Proxy(e.controls,r),e.settings=new Proxy(e.settings,r);const a={get:(l,o)=>{if(o==="toJSON")return()=>{const h={};return Object.keys(l).forEach(u=>{const f=l[u];f&&typeof f.toJSON=="function"?h[u]=f.toJSON():h[u]=f}),h};const d=o;return d==="crossOrigin"?l.crossorigin:d==="playsInline"?l.playsinline:l[o]},set:(l,o,d)=>{const h=o;return h==="crossOrigin"?l.crossorigin=d:h==="playsInline"?l.playsinline=d:l[o]=d,n&&this.dispatchEvent("config-change",n),!0},has:(l,o)=>{const d=o;return d==="crossOrigin"?l.crossorigin!==void 0:d==="playsInline"?l.playsinline!==void 0:o in l}},n=new Proxy(e,a);return n}validateConfig(e){if(!e||typeof e!="object")return;const t=i=>{console.warn(`[Player SDK Configuration Warning] ${i}`)};if("crossOrigin"in e&&t("Property 'crossOrigin' is deprecated. Use 'crossorigin' instead."),"playsInline"in e&&t("Property 'playsInline' is deprecated. Use 'playsinline' instead."),e.autoplay!==void 0&&typeof e.autoplay!="boolean"&&t(`'autoplay' must be a boolean, got ${typeof e.autoplay}.`),e.muted!==void 0&&typeof e.muted!="boolean"&&t(`'muted' must be a boolean, got ${typeof e.muted}.`),e.volume!==void 0&&(typeof e.volume!="number"||e.volume<0||e.volume>1)&&t(`'volume' must be a number between 0 and 1, got ${e.volume}.`),e.displayMode!==void 0){const i=["standard","vertical","audio-only","custom","mini","floating"];i.includes(e.displayMode)||t(`Invalid displayMode '${e.displayMode}'. Must be one of: ${i.join(", ")}.`)}if(e.controls&&typeof e.controls=="object"){const i=["play","playButton","pause","seekbar","timeline","currentTime","duration","volume","mute","settings","subtitles","captions","audioTracks","quality","playbackSpeed","sleepTimer","pictureInPicture","pip","fullscreen","liveBadge","markers","chapters","timelinePreview","replayButton","loadingSpinner","feedbackOverlay","volumeOverlay","contextMenu","actionRail","liveDVR","liveEdgeButton","emptyState","controlsBar","verticalControls","plugins","loop","autoScroll","order","groups","layout"];Object.keys(e.controls).forEach(s=>{i.includes(s)||t(`Unknown control config option '${s}'.`)})}if(e.settings&&typeof e.settings=="object"){const i=["order","playbackSpeed","quality","audioTracks","subtitles","loop","sleepTimer","chapters","markers","autoScroll","pictureInPicture","pip","fullscreen","enabled","customItems","groups","labels","icons"];Object.keys(e.settings).forEach(s=>{i.includes(s)||t(`Unknown settings config option '${s}'.`)})}}onStateChange(e){return this.stateCallbacks.add(e),e({...this.state}),()=>this.stateCallbacks.delete(e)}updateState(e){this.isAudioTracksEnabled()||(e.audioTracks&&(e.audioTracks=[]),e.activeAudioTrack!==void 0&&(e.activeAudioTrack=-1)),this.isQualityEnabled()||(e.qualities&&(e.qualities=[]),e.activeQuality!==void 0&&(e.activeQuality="Auto")),this.isChaptersEnabled()||(e.chapters&&(e.chapters=[]),e.activeChapterIndex!==void 0&&(e.activeChapterIndex=-1)),this.isMarkersEnabled()||e.markers&&(e.markers=[]);const t=this.state.audioTracks,i=this.state.activeAudioTrack;let s=!1;for(const a of Object.keys(e)){const n=this.state[a],l=e[a];if(l!==void 0){if(typeof l=="object"&&l!==null){if(!ts(a,n,l)){s=!0;break}}else if(n!==l){s=!0;break}}}if(!s&&e.error===void 0)return;if(e.audioTracks!==void 0&&e.audioTracks.length>0&&(this.state.audioTracks.length===0||!ts("audioTracks",t,e.audioTracks)))try{const a=oe.getItem("player_audio_language");if(a){const n=e.audioTracks.findIndex(o=>o===a),l=e.activeAudioTrack!==void 0?e.activeAudioTrack:this.state.activeAudioTrack;n!==-1&&n!==l&&(e.activeAudioTrack=n,this.sourceManager.setAudioTrack(n))}}catch{}if(e.markers&&e.markers.length>1e3&&(e.markers=e.markers.slice(-1e3)),(this.state.isLive||e.isLive)&&e.seekableRange){const a=e.seekableRange.start,n=e.markers||this.state.markers;if(n&&n.length>0){const l=n.filter(o=>!pe.shouldPruneMarker(o.time,a));l.length!==n.length&&(e.markers=l)}}const r={...this.state,...e};e.error!==void 0&&e.error!==null&&(r.status="error"),this.state=r,e.audioTracks!==void 0&&JSON.stringify(t)!==JSON.stringify(e.audioTracks)&&this.dispatchEvent("audioTracksChanged",{audioTracks:e.audioTracks}),e.activeAudioTrack!==void 0&&i!==e.activeAudioTrack&&this.dispatchEvent("audioTrackChanged",{activeAudioTrack:e.activeAudioTrack}),this.stateCallbacks.forEach(a=>a({...this.state}))}getState(){return this.state}updateStatePublic(e){this.updateState(e)}getThumbnailProvider(){return this.thumbnailProvider}setThumbnailProvider(e){this.thumbnailProvider=e,this.updateState({thumbnailProvider:e})}setDisplayMode(e){if(["standard","vertical","audio-only","custom","mini","floating"].includes(e)){this.updateState({displayMode:e}),this.video.loop=e==="vertical"?!1:this.state.loop,this.config.layout||(this.config.layout={});const i=this.config.displayMode!==e,s=this.config.layout.mode!==e;this.config.displayMode=e,this.config.layout.mode=e,(i||s)&&this.dispatchEvent("config-change",this.config)}}setLiveMode(e){this.state.liveMode!==e&&(this.updateState({liveMode:e}),this.state.isLive&&this.updateLiveState())}loadPlaylist(e,t=0){this.playlistManager.loadPlaylist(e,t)}setPlaylist(e,t=0){this.playlistManager.setPlaylist(e,t)}setNearEndThreshold(e){this.playlistManager.setNearEndThreshold(e)}getNearEndThreshold(){return this.playlistManager.getNearEndThreshold()}getPlaylist(){return this.playlistManager.getPlaylist()}getCurrentPlaylistIndex(){return this.playlistManager.getCurrentPlaylistIndex()}getHistoryStack(){return this.playlistManager.getHistoryStack()}getCurrentPlaylistItem(){return this.playlistManager.getCurrentPlaylistItem()}getPlaylistLength(){return this.playlistManager.getPlaylistLength()}hasPlaylist(){return this.playlistManager.hasPlaylist()}isFirstPlaylistItem(){return this.playlistManager.isFirstPlaylistItem()}isLastPlaylistItem(){return this.playlistManager.isLastPlaylistItem()}next(){this.playlistManager.next()}previous(){this.playlistManager.previous()}appendPlaylistItem(e){this.playlistManager.appendPlaylistItem(e)}insertPlaylistItem(e,t){this.playlistManager.insertPlaylistItem(e,t)}removePlaylistItem(e){this.playlistManager.removePlaylistItem(e)}clearPlaylist(){this.playlistManager.clearPlaylist()}replacePlaylistItem(e,t){this.playlistManager.replacePlaylistItem(e,t)}movePlaylistItem(e,t){this.playlistManager.movePlaylistItem(e,t)}setPlaylistRepeatMode(e){this.playlistManager.setPlaylistRepeatMode(e)}getPlaylistRepeatMode(){return this.playlistManager.getPlaylistRepeatMode()}getAutoAdvanceIndexOnEnded(){return this.playlistManager.getAutoAdvanceIndexOnEnded()}setupEventListeners(){this.video.addEventListener("play",this.handlePlay),this.video.addEventListener("pause",this.handlePause),this.video.addEventListener("timeupdate",this.handleTimeUpdate),this.video.addEventListener("durationchange",this.handleDurationChange),this.video.addEventListener("volumechange",this.handleVolumeChange),this.video.addEventListener("progress",this.handleProgress),this.video.addEventListener("waiting",this.handleWaiting),this.video.addEventListener("playing",this.handlePlaying),this.video.addEventListener("seeking",this.handleSeeking),this.video.addEventListener("seeked",this.handleSeeked),this.video.addEventListener("canplay",this.handleCanPlay),this.video.addEventListener("canplaythrough",this.handleCanPlay),this.video.addEventListener("error",this.handleNativeError),this.video.addEventListener("loadedmetadata",this.handleLoadedMetadata),this.video.addEventListener("ended",this.handleEnded),this.subtitleManager.attach(),typeof document<"u"&&(document.addEventListener("fullscreenchange",this.handleFullscreenChange),document.addEventListener("webkitfullscreenchange",this.handleFullscreenChange),document.addEventListener("visibilitychange",this.handleVisibilityChange)),this.video.addEventListener("webkitbeginfullscreen",this.handleWebkitBeginFullscreen),this.video.addEventListener("webkitendfullscreen",this.handleWebkitEndFullscreen),this.pictureInPictureManager.attach()}destroy(){if(!this.isDestroyed){if(this.isDestroyed=!0,this.playlistManager.destroy(),this.stopStallCheck(),this.clearSleepTimer(),this.clearBufferingTimeout(),this.shortcuts.destroy(),this.analyticsHandlers.clear(),this.playbackInterceptors.clear(),this.pendingOverlays.clear(),this.thumbnailProvider&&typeof this.thumbnailProvider.destroy=="function")try{this.thumbnailProvider.destroy()}catch(e){console.error("[PlayerController] Error destroying thumbnail provider:",e)}this.sourceManager.destroy();try{this.ads.destroy()}catch(e){console.error("[PlayerController] Error destroying ads controller:",e)}this.subtitleManager.revokeBlobUrls(),this.plugins.forEach(e=>{var t;try{(t=e.destroy)==null||t.call(e)}catch(i){console.error(`[PlayerController] Error destroying plugin "${e.name}":`,i)}}),this.plugins.clear(),this.eventListeners.clear(),this.video.removeEventListener("play",this.handlePlay),this.video.removeEventListener("pause",this.handlePause),this.video.removeEventListener("timeupdate",this.handleTimeUpdate),this.video.removeEventListener("durationchange",this.handleDurationChange),this.video.removeEventListener("volumechange",this.handleVolumeChange),this.video.removeEventListener("progress",this.handleProgress),this.video.removeEventListener("waiting",this.handleWaiting),this.video.removeEventListener("playing",this.handlePlaying),this.video.removeEventListener("seeking",this.handleSeeking),this.video.removeEventListener("seeked",this.handleSeeked),this.video.removeEventListener("canplay",this.handleCanPlay),this.video.removeEventListener("canplaythrough",this.handleCanPlay),this.video.removeEventListener("error",this.handleNativeError),this.video.removeEventListener("loadedmetadata",this.handleLoadedMetadata),this.video.removeEventListener("ended",this.handleEnded),this.subtitleManager.detach(),typeof document<"u"&&(document.removeEventListener("fullscreenchange",this.handleFullscreenChange),document.removeEventListener("webkitfullscreenchange",this.handleFullscreenChange),document.removeEventListener("visibilitychange",this.handleVisibilityChange)),this.video.removeEventListener("webkitbeginfullscreen",this.handleWebkitBeginFullscreen),this.video.removeEventListener("webkitendfullscreen",this.handleWebkitEndFullscreen),this.pictureInPictureManager.detach(),this.stateCallbacks.clear()}}clearBufferingTimeout(){this.bufferingTimeout&&(clearTimeout(this.bufferingTimeout),this.bufferingTimeout=void 0)}getSeekableStateBatch(){const e=this.video.seekable;let t=this.state.isLive;this.state.sourceType==="hls"||this.state.sourceType==="dash"||(this.video.duration===1/0?t=!0:t===null&&this.video.duration>0&&(t=!1));let s=0,r=this.video.duration||0;e&&e.length>0?(s=e.start(0),t===!0&&(s+=2),r=e.end(e.length-1),s>r&&(s=r)):t===!0&&(r=0);const a={start:s,end:r},n=t===!0?r-s:0,l=this.state.hasDvr||t===!0&&n>30,o=l&&this.state.liveMode==="live-dvr";return{isLive:t,seekableRange:a,dvrWindow:n,hasDvr:l,canSeekInDvr:o}}updateActiveChapter(){if(!this.state.chapters||this.state.chapters.length===0){this.state.activeChapterIndex!==-1&&this.updateState({activeChapterIndex:-1});return}const e=this.video.currentTime,t=this.state.chapters,i=t.findIndex((s,r)=>{const a=s.startTime,n=s.endTime!==void 0?s.endTime:t[r+1]?t[r+1].startTime:this.video.duration||1/0;return e>=a&&e<n});i!==this.state.activeChapterIndex&&(this.updateState({activeChapterIndex:i}),this.dispatchEvent("chapterchange",{activeChapterIndex:i,chapter:i!==-1?this.state.chapters[i]:null}))}setManagedSubtitleTracks(e,t,i){this.subtitleManager.setManagedSubtitleTracks(e,t,i)}play(){var t,i;const e=this.getPlugins();for(const s of e)try{(t=s.onBeforePlay)==null||t.call(s)}catch(r){console.error(`[PlayerController] Error running onBeforePlay for plugin ${s.name}:`,r)}for(const s of this.playbackInterceptors)if(s.play)try{if(s.play()){for(const a of e)(i=a.onAfterPlay)==null||i.call(a);return}}catch(r){console.error("[PlayerController] Playback interceptor error:",r)}this.video.play().then(()=>{var s;for(const r of e)try{(s=r.onAfterPlay)==null||s.call(r)}catch(a){console.error(`[PlayerController] Error running onAfterPlay for plugin ${r.name}:`,a)}}).catch(s=>{console.warn("Playback failed or was prevented by browser autoplay restrictions:",s)})}pause(){for(const e of this.playbackInterceptors)if(e.pause)try{if(e.pause())return}catch(t){console.error("[PlayerController] Pause interceptor error:",t)}this.video.pause()}togglePlay(){this.state.isPlaying?this.pause():this.play()}seek(e){var a,n,l;if(this.state.isLive&&!this.state.canSeekInDvr)return;let t=e;if(this.state.isLive){const o=((a=this.state.seekableRange)==null?void 0:a.start)??0,d=((n=this.state.seekableRange)==null?void 0:n.end)??0;t=Math.max(o,Math.min(e,d))}else t=Math.max(0,Math.min(e,this.state.duration||0));for(const o of this.playbackInterceptors)if(o.seek)try{if(o.seek(t))return}catch(d){console.error("[PlayerController] Seek interceptor error:",d)}const i=this.sourceManager.getActiveHandler();let s=!1;if(i&&typeof i.seek=="function"&&(s=i.seek(t)),!s){const o=(l=this.config)==null?void 0:l.preciseSeek,d=typeof o=="object"?o:void 0,h=o!==!1&&(d==null?void 0:d.enabled)!==!1&&(d==null?void 0:d.seekSmoothing)!==!1,u=this.video.volume,f=this.video.muted;if(h&&!f&&u>0){this.preSeekVolume===null&&(this.preSeekVolume=u),this.video.volume=this.preSeekVolume*.1;const p=()=>{this.preSeekVolume!==null&&(this.video.volume=this.preSeekVolume,this.preSeekVolume=null),this.video.removeEventListener("seeked",p)};this.video.addEventListener("seeked",p),setTimeout(()=>{this.video.removeEventListener("seeked",p),this.preSeekVolume!==null&&(this.video.volume=this.preSeekVolume,this.preSeekVolume=null)},250)}this.video.currentTime=t}const r={currentTime:t,isSeeking:!0};if(this.state.isLive){const o=this.getLiveEdgeTarget(),d=Math.max(0,o-t),h=this.state.isLowLatency?6:18;r.liveLatency=d,r.isAtLiveEdge=d<=h}this.updateState(r)}seekBy(e){this.seek(this.state.currentTime+e)}setVolume(e){const t=Math.max(0,Math.min(e,1));for(const i of this.playbackInterceptors)if(i.setVolume)try{if(i.setVolume(t))return}catch(s){console.error("[PlayerController] setVolume interceptor error:",s)}this.video.volume=t,t>0&&(this.lastNonZeroVolume=t,this.video.muted&&this.setMuted(!1))}setMuted(e){for(const t of this.playbackInterceptors)if(t.setMuted)try{if(t.setMuted(e))return}catch(i){console.error("[PlayerController] setMuted interceptor error:",i)}this.video.muted=e}toggleMute(){const t=!(this.video.muted||this.video.volume===0);this.setMuted(t),t||this.video.volume===0&&this.setVolume(this.lastNonZeroVolume>0?this.lastNonZeroVolume:.5)}setPlaybackRate(e){this.isPlaybackSpeedEnabled()||(e=1),this.video.playbackRate=e,this.updateState({playbackRate:e});try{oe.setItem("player_playback_rate",e.toString())}catch{}}toggleFullscreen(e){const t=e||this.video,i=t,s=this.video,r=document;this.state.isFullscreen?document.exitFullscreen?document.exitFullscreen():r.webkitExitFullscreen?r.webkitExitFullscreen():this.video&&s.webkitExitFullscreen&&s.webkitExitFullscreen():t.requestFullscreen?t.requestFullscreen():i.webkitRequestFullscreen?i.webkitRequestFullscreen():this.video&&s.webkitEnterFullscreen&&s.webkitEnterFullscreen()}isPictureInPictureSupported(){return this.pictureInPictureManager.isPictureInPictureSupported()}async enterPictureInPicture(){return this.pictureInPictureManager.enterPictureInPicture()}async exitPictureInPicture(){return this.pictureInPictureManager.exitPictureInPicture()}async togglePictureInPicture(){this.pictureInPictureManager.isInPictureInPicture()?await this.exitPictureInPicture():await this.enterPictureInPicture()}loadCaptions(e){this.subtitleManager.loadCaptions(e)}toggleCaptions(e){this.subtitleManager.toggleCaptions(e)}replay(){this.seek(0),this.play(),this.dispatchEvent("replay")}validateSource(e){if(!e||!e.src)return!1;const t=e.src.trim();return t.length===0?!1:t.startsWith("http://")||t.startsWith("https://")||t.startsWith("/")||t.startsWith("blob:")||t.startsWith("data:")}parseAndSanitizeEmbedSource(e){if(!e||!e.src)return!1;const t=zs(e.src);return t?(e.src=t,!0):!1}loadSource(e,t=!0){var n,l,o,d,h,u,f,p,g,m;if((n=e.live)!=null&&n.mode&&this.setLiveMode(e.live.mode),t&&this.state.playlist.length>0&&this.playlistManager.clearForExternalSourceLoad(),this.setSleepTimer("off"),this.subtitleManager.revokeBlobUrls(),this.state.pictureInPicture&&this.exitPictureInPicture().catch(()=>{}),!e||!e.src&&!e.srcObject||typeof e.src=="string"&&e.src.trim()===""){this.sourceManager.destroy(),this.stopStallCheck(),this.video.src="",this.video.srcObject=null,this.video.removeAttribute("src");try{this.video.load()}catch{}this.video.querySelectorAll("track").forEach(y=>y.remove()),this.subtitleManager.resetManagedTracks(),this.updateState({status:"idle",currentSource:null,sourceType:"unknown",error:null,isPlaying:!1,isBuffering:!1,isSeeking:!1,currentTime:0,duration:0,bufferedRanges:[],qualities:[],activeQuality:"Auto",audioTracks:[],activeAudioTrack:-1,subtitleTracks:[],activeSubtitleTrack:-1,activeSubtitleTrackId:null,chapters:[],activeChapterIndex:-1,markers:[]}),this.dispatchEvent("sourcechange",{source:null}),(o=(l=this.thumbnailProvider)==null?void 0:l.setSource)==null||o.call(l,"");return}this.sourceManager.destroy(),this.stopStallCheck();let i=e.type||"unknown";if(i==="unknown"&&e.src){const v=e.src.split("?")[0].toLowerCase();v.endsWith(".m3u8")?i="hls":v.endsWith(".mpd")?i="dash":v.endsWith(".webm")?i="webm":v.endsWith(".mov")?i="mov":v.includes("youtube.com")||v.includes("youtu.be")||v.includes("vimeo.com")||e.src.trim().toLowerCase().startsWith("<iframe")?i="embed":i="mp4"}if(i==="embed"&&!this.parseAndSanitizeEmbedSource(e)){this.updateState({status:"error",currentSource:null,sourceType:"unknown",error:"Invalid embed source or host not approved.",isPlaying:!1,currentTime:0,duration:0,bufferedRanges:[],isLive:!1,seekableRange:{start:0,end:0},chapters:[],activeChapterIndex:-1}),this.dispatchEvent("sourcechange",{source:e}),(h=(d=this.thumbnailProvider)==null?void 0:d.setSource)==null||h.call(d,"");return}if(!this.validateSource(e)){this.updateState({status:"error",currentSource:null,sourceType:"unknown",error:"Invalid video source layout or stream. Please verify input.",isPlaying:!1,currentTime:0,duration:0,bufferedRanges:[],isLive:!1,seekableRange:{start:0,end:0},chapters:[],activeChapterIndex:-1}),this.dispatchEvent("sourcechange",{source:e}),(f=(u=this.thumbnailProvider)==null?void 0:u.setSource)==null||f.call(u,"");return}if(this.subtitleManager.revokeBlobUrls(),this.video.textTracks)for(let v=0;v<this.video.textTracks.length;v++)this.video.textTracks[v]._zombie=!0;this.video.querySelectorAll("track").forEach(v=>v.remove()),this.subtitleManager.resetManagedTracks(),e.type=i;const r=e.src||"";this.video.loop=this.state.displayMode==="vertical"?!1:this.state.loop,this.updateState({status:"loading",currentSource:r,sourceType:i,isBuffering:!1,isSeeking:!1,isPlaying:!1,currentTime:0,duration:0,bufferedRanges:[],error:null,qualities:[],activeQuality:"Auto",audioTracks:[],activeAudioTrack:-1,subtitleTracks:[],activeSubtitleTrack:-1,activeSubtitleTrackId:null,isLive:null,isAtLiveEdge:!0,liveLatency:null,dvrWindow:0,canSeekInDvr:!1,seekableRange:{start:0,end:0},chapters:e.chapters||[],activeChapterIndex:-1,markers:[],visibleMarkerTypes:null}),this.subtitleManager.attachSourceSubtitles(e.subtitles),this.subtitleManager.refreshSubtitleTracks(),this.video.srcObject=null,this.video.src="",this.video.removeAttribute("src"),this.sourceManager.load(e,this.video,this),(g=(p=this.thumbnailProvider)==null?void 0:p.setSource)==null||g.call(p,r,e),this.dispatchEvent("sourcechange",{source:e}),this.updateMediaSession();const a=this.getPlugins();for(const v of a)try{(m=v.onSourceLoaded)==null||m.call(v,e)}catch(y){console.error(`[PlayerController] Error running onSourceLoaded for plugin ${v.name}:`,y)}}setQuality(e){this.isQualityEnabled()&&(this.sourceManager.setQuality(e),this.dispatchEvent("qualitychange",{qualityIndex:e}))}getAudioTracks(){return this.state.audioTracks}getCurrentAudioTrack(){return this.state.activeAudioTrack}setAudioTrack(e){if(this.isAudioTracksEnabled()){this.sourceManager.setAudioTrack(e);try{const t=this.state.audioTracks;e>=0&&e<t.length&&oe.setItem("player_audio_language",t[e])}catch{}this.dispatchEvent("audiochange",{trackIndex:e})}}setSubtitleTrack(e){this.subtitleManager.setSubtitleTrack(e)}disableSubtitles(){this.subtitleManager.disableSubtitles()}hasSubtitles(){return this.subtitleManager.hasSubtitles()}getSubtitleTracks(){return this.subtitleManager.getSubtitleTracks()}getActiveSubtitleTrack(){return this.subtitleManager.getActiveSubtitleTrack()}getSubtitleAppearance(){return this.subtitleManager.getSubtitleAppearance()}setSubtitleAppearance(e){this.subtitleManager.setSubtitleAppearance(e)}resetSubtitleAppearance(){this.subtitleManager.resetSubtitleAppearance()}startStallCheck(){this.stopStallCheck();let e=this.video.currentTime,t=0;this.stallTimer=window.setInterval(()=>{this.state.isPlaying&&!this.state.isBuffering&&(this.video.currentTime===e?(t++,t>=5&&(console.warn("Playback stall detected. Attempting stall recovery seek offset..."),this.video.currentTime=Math.min(this.video.currentTime+.1,this.state.duration||0),t=0)):(t=0,e=this.video.currentTime))},1e3)}stopStallCheck(){this.stallTimer&&(clearInterval(this.stallTimer),this.stallTimer=void 0)}getVideoElement(){return this.video}getDrmManager(){var e,t;return((t=(e=this.sourceManager.getActiveHandler())==null?void 0:e.getDrmManager)==null?void 0:t.call(e))??null}setChapters(e){if(!this.isChaptersEnabled()){this.updateState({chapters:[],activeChapterIndex:-1});return}this.updateState({chapters:e}),this.updateActiveChapter()}nextChapter(){const e=this.state.chapters;if(!e||e.length===0)return;const t=this.video.currentTime,i=e.find(s=>s.startTime>t+.5);i&&this.seek(i.startTime)}prevChapter(){const e=this.state.chapters;if(!e||e.length===0)return;const t=this.video.currentTime,i=this.state.activeChapterIndex;if(i>0&&t-e[i].startTime<2)this.seek(e[i-1].startTime);else if(i>=0)this.seek(e[i].startTime);else{const s=[...e].reverse().find(r=>r.startTime<t-.5);s&&this.seek(s.startTime)}}getChapters(){return this.state.chapters||[]}getActiveChapter(){const e=this.state.activeChapterIndex,t=this.state.chapters;return e>=0&&t&&t[e]?t[e]:null}seekToChapter(e){const t=this.state.chapters;if(!t||t.length===0)return;let i;typeof e=="number"?i=t[e]:i=t.find(s=>s.id===e),i&&this.seek(i.startTime)}setMarkers(e){if(!this.isMarkersEnabled()){this.updateState({markers:[]});return}this.updateState({markers:e})}addMarker(e){if(!this.isMarkersEnabled())return;const t=[...this.state.markers,e];this.updateState({markers:t})}clearMarkers(){this.updateState({markers:[]})}setLoop(e){this.video.loop=this.state.displayMode==="vertical"?!1:e,this.updateState({loop:e});try{oe.setItem("player_loop",e.toString())}catch{}}toggleLoop(){this.setLoop(!this.state.loop)}setAutoScroll(e){this.updateState({autoScroll:e});try{oe.setItem("player_auto_scroll",e.toString())}catch{}this.dispatchEvent("autoscroll-change",{autoScroll:e})}toggleAutoScroll(){this.setAutoScroll(!this.state.autoScroll)}tickSleepTimer(){if(!this.sleepTimerEndTimeMs||this.state.sleepTimerExpired)return;const e=Math.max(0,Math.ceil((this.sleepTimerEndTimeMs-Date.now())/1e3));e<=0?(this.clearSleepTimer(),this.triggerSleepTimerExpiration()):(this.updateState({sleepTimerSecondsRemaining:e}),this.dispatchEvent("sleeptimerupdate",{secondsRemaining:e,endTimeMs:this.sleepTimerEndTimeMs}))}setSleepTimer(e){var s,r;if(((r=(s=this.config)==null?void 0:s.controls)==null?void 0:r.sleepTimer)===!1)return;if(e==="end"&&this.state.isLive){console.warn('[PlayerController] Cannot set "end" sleep timer on a live stream');return}this.clearSleepTimer();const t=this.state.sleepTimerExpired;if(this.updateState({sleepTimerSetting:e,sleepTimerExpired:!1}),e==="off"){this.sleepTimerEndTimeMs=void 0,this.updateState({sleepTimerSecondsRemaining:null}),this.dispatchEvent("sleeptimercancelled");return}if(e==="end"){this.sleepTimerEndTimeMs=void 0,this.updateState({sleepTimerSecondsRemaining:null}),this.dispatchEvent("sleeptimerstart",{setting:"end",secondsRemaining:null,endTimeMs:null}),t&&this.play();return}const i=e*60;this.sleepTimerEndTimeMs=Date.now()+i*1e3,this.updateState({sleepTimerSecondsRemaining:i}),this.dispatchEvent("sleeptimerstart",{setting:e,secondsRemaining:i,endTimeMs:this.sleepTimerEndTimeMs}),this.startSleepTimerCountdown(),t&&this.play()}startSleepTimerCountdown(){this.sleepTimerId&&clearInterval(this.sleepTimerId),this.sleepTimerId=window.setInterval(()=>{this.tickSleepTimer()},1e3)}clearSleepTimer(){this.sleepTimerId&&(clearInterval(this.sleepTimerId),this.sleepTimerId=void 0),this.sleepTimerEndTimeMs=void 0}clearSleepTimerExpired(){this.updateState({sleepTimerExpired:!1})}triggerSleepTimerExpiration(){this.pause(),this.updateState({sleepTimerExpired:!0,sleepTimerSetting:"off",sleepTimerSecondsRemaining:null}),this.dispatchEvent("sleeptimerexpired")}getSleepTimerState(){return{setting:this.state.sleepTimerSetting,secondsRemaining:this.state.sleepTimerSecondsRemaining,endTimeMs:this.sleepTimerEndTimeMs||null,isExpired:this.state.sleepTimerExpired,isRunning:this.isSleepTimerRunning()}}getSleepTimerRemaining(){return!this.sleepTimerEndTimeMs||this.state.sleepTimerExpired?null:Math.max(0,Math.ceil((this.sleepTimerEndTimeMs-Date.now())/1e3))}getSleepTimerPreset(){return this.state.sleepTimerSetting}isSleepTimerRunning(){return!!(this.sleepTimerEndTimeMs&&!this.state.sleepTimerExpired&&(this.state.sleepTimerSecondsRemaining??0)>0)}isPluginsEnabled(){var t,i;const e=(t=this.config)==null?void 0:t.plugins;return e===!1?!1:e&&typeof e=="object"&&"enabled"in e?e.enabled!==!1:!((i=this.config)!=null&&i.controls&&this.config.controls.plugins===!1)}isAnalyticsEnabled(){var t,i;const e=(t=this.config)==null?void 0:t.analytics;return!(e===!1||e&&typeof e=="object"&&e.enabled===!1||(i=this.config)!=null&&i.controls&&this.config.controls.analytics===!1)}isSubtitlesEnabled(){var e,t,i,s;return!(((t=(e=this.config)==null?void 0:e.controls)==null?void 0:t.subtitles)===!1&&((s=(i=this.config)==null?void 0:i.controls)==null?void 0:s.captions)===!1)}isAudioTracksEnabled(){var e,t;return((t=(e=this.config)==null?void 0:e.controls)==null?void 0:t.audioTracks)!==!1}isQualityEnabled(){var e,t;return((t=(e=this.config)==null?void 0:e.controls)==null?void 0:t.quality)!==!1}isPlaybackSpeedEnabled(){var e,t;return((t=(e=this.config)==null?void 0:e.controls)==null?void 0:t.playbackSpeed)!==!1}isSmartSeekEnabled(){var t;const e=(t=this.config)==null?void 0:t.smartSeek;return!(e===!1||typeof e=="object"&&e.enabled===!1)}isChaptersEnabled(){var t,i,s;if(!this.isSmartSeekEnabled())return!1;const e=(t=this.config)==null?void 0:t.smartSeek;return!(e&&typeof e=="object"&&e.chapters===!1||((s=(i=this.config)==null?void 0:i.controls)==null?void 0:s.chapters)===!1)}isMarkersEnabled(){var t,i,s;if(!this.isSmartSeekEnabled())return!1;const e=(t=this.config)==null?void 0:t.smartSeek;return!(e&&typeof e=="object"&&e.markers===!1||((s=(i=this.config)==null?void 0:i.controls)==null?void 0:s.markers)===!1)}isPreciseSeekEnabled(){var t;const e=(t=this.config)==null?void 0:t.preciseSeek;return!(e===!1||typeof e=="object"&&e.enabled===!1)}shouldSnapToChapters(){var i,s;if(!this.isPreciseSeekEnabled()||!this.isChaptersEnabled())return!1;const e=(i=this.config)==null?void 0:i.preciseSeek,t=(s=this.config)==null?void 0:s.smartSeek;return e&&typeof e=="object"&&e.snapToChapters!==void 0?e.snapToChapters:t&&typeof t=="object"&&t.snapToChapters!==void 0?t.snapToChapters:!0}shouldSnapToMarkers(){var i,s;if(!this.isPreciseSeekEnabled()||!this.isMarkersEnabled())return!1;const e=(i=this.config)==null?void 0:i.preciseSeek,t=(s=this.config)==null?void 0:s.smartSeek;return e&&typeof e=="object"&&e.snapToMarkers!==void 0?e.snapToMarkers:t&&typeof t=="object"&&t.snapToMarkers!==void 0?t.snapToMarkers:!0}isKeyboardPrecisionEnabled(){var t;if(!this.isPreciseSeekEnabled())return!1;const e=(t=this.config)==null?void 0:t.preciseSeek;return!(e&&typeof e=="object"&&e.keyboardPrecision===!1)}isFrameAccurateSeekingEnabled(){var t;if(!this.isPreciseSeekEnabled())return!1;const e=(t=this.config)==null?void 0:t.preciseSeek;return!(e&&typeof e=="object"&&e.frameAccurate===!1)}isLiveDraggingEnabled(){var t;if(!this.isPreciseSeekEnabled())return!1;const e=(t=this.config)==null?void 0:t.preciseSeek;return e&&typeof e=="object"&&e.liveDragging!==void 0?e.liveDragging:!0}isSmoothDraggingEnabled(){var t;if(!this.isPreciseSeekEnabled())return!1;const e=(t=this.config)==null?void 0:t.preciseSeek;return!(e&&typeof e=="object"&&(e.smoothDragging===!1||e.dragInterpolation===!1))}isContinuousUpdatesEnabled(){var t;if(!this.isPreciseSeekEnabled())return!1;const e=(t=this.config)==null?void 0:t.preciseSeek;return!(e&&typeof e=="object"&&e.continuousUpdates===!1)}exportConfig(){return JSON.parse(JSON.stringify(this.config))}updateConfig(e){var r,a,n;this.validateConfig(e);const t={...this.config,...e,theme:{...this.config.theme||{},...e.theme||{}},controls:{...this.config.controls||{},...e.controls||{}},settings:{...this.config.settings||{},...e.settings||{}},layout:{...this.config.layout||{},...e.layout||{}},playback:{...this.config.playback||{},...e.playback||{}},sleepTimer:{...this.config.sleepTimer||{},...e.sleepTimer||{}},shortcuts:{...this.config.shortcuts||{},...e.shortcuts||{}},preciseSeek:e.preciseSeek!==void 0?typeof e.preciseSeek=="object"?{...typeof this.config.preciseSeek=="object"?this.config.preciseSeek:{},...e.preciseSeek}:e.preciseSeek:this.config.preciseSeek,smartSeek:e.smartSeek!==void 0?typeof e.smartSeek=="object"?{...typeof this.config.smartSeek=="object"?this.config.smartSeek:{},...e.smartSeek}:e.smartSeek:this.config.smartSeek};this.config=this.createUnifiedConfig(t);const i=this.config.smartSeek;if(i!==!1&&(typeof i!="object"||i.enabled!==!1))if(!this.thumbnailProvider)this.config.thumbnailProvider?this.thumbnailProvider=this.config.thumbnailProvider:this.thumbnailProvider=new _e(this.config),this.updateState({thumbnailProvider:this.thumbnailProvider});else{const l=this.thumbnailProvider;typeof l.updateConfig=="function"?l.updateConfig(this.config):l.config=this.config}else{if(this.thumbnailProvider&&typeof this.thumbnailProvider.destroy=="function")try{this.thumbnailProvider.destroy()}catch(l){console.error("[PlayerController] Error destroying thumbnail provider:",l)}this.thumbnailProvider=void 0,this.updateState({thumbnailProvider:void 0})}this.isAnalyticsEnabled()||this.analyticsHandlers.clear(),!this.isPluginsEnabled()&&this.plugins.size>0&&(this.plugins.forEach(l=>{var o;try{(o=l.destroy)==null||o.call(l)}catch(d){console.error(`[PlayerController] Error destroying plugin "${l.name}":`,d)}}),this.plugins.clear()),((r=this.config.controls)==null?void 0:r.sleepTimer)===!1&&(this.clearSleepTimer(),this.updateState({sleepTimerSetting:"off",sleepTimerSecondsRemaining:null,sleepTimerExpired:!1})),!this.isChaptersEnabled()&&this.state.chapters&&this.state.chapters.length>0&&this.updateState({chapters:[],activeChapterIndex:-1}),!this.isMarkersEnabled()&&this.state.markers&&this.state.markers.length>0&&this.updateState({markers:[]}),this.config.controls&&this.config.controls.liveDVR!==void 0&&(this.config.controls.liveDVR===!1?this.updateState({liveMode:"live-only",canSeekInDvr:!1}):this.updateState({liveMode:((a=this.config.live)==null?void 0:a.mode)||"live-dvr",canSeekInDvr:this.state.hasDvr})),!this.isSubtitlesEnabled()&&this.state.subtitleTracks&&this.state.subtitleTracks.length>0&&(this.updateState({subtitleTracks:[],activeSubtitleTrack:-1,activeSubtitleTrackId:null,captionsEnabled:!1}),this.disableSubtitles()),!this.isAudioTracksEnabled()&&this.state.audioTracks&&this.state.audioTracks.length>0&&this.updateState({audioTracks:[],activeAudioTrack:-1}),!this.isQualityEnabled()&&this.state.qualities&&this.state.qualities.length>0&&this.updateState({qualities:[],activeQuality:"Auto"}),!this.isPlaybackSpeedEnabled()&&this.state.playbackRate!==1&&this.setPlaybackRate(1),e.playback&&e.playback.autoplay!==void 0&&(this.video.autoplay=e.playback.autoplay),e.playback&&e.playback.loop!==void 0&&(this.video.loop=e.playback.loop,this.updateStatePublic({loop:e.playback.loop})),e.playback&&e.playback.volume!==void 0&&this.setVolume(e.playback.volume),e.playback&&e.playback.muted!==void 0&&e.playback.muted!==this.video.muted&&this.toggleMute(),e.shortcuts&&e.shortcuts.enabled!==void 0&&(e.shortcuts.enabled?this.shortcuts.enable():this.shortcuts.disable()),e.displayMode!==void 0?this.setDisplayMode(e.displayMode):((n=e.layout)==null?void 0:n.mode)!==void 0&&this.setDisplayMode(e.layout.mode),this.dispatchEvent("config-change",this.config)}getPlugins(){return this.isPluginsEnabled()?Array.from(this.plugins.values()):[]}use(e){var t,i;if(this.isPluginsEnabled()){if(this.plugins.has(e.name)){console.warn(`[PlayerController] Plugin "${e.name}" is already registered. Reinstalling.`);try{(i=(t=this.plugins.get(e.name))==null?void 0:t.destroy)==null||i.call(t)}catch{}}this.plugins.set(e.name,e),e.install(this)}}getPlugin(e){if(this.isPluginsEnabled())return this.plugins.get(e)}addEventListener(e,t){this.eventListeners.has(e)||this.eventListeners.set(e,new Set),this.eventListeners.get(e).add(t)}removeEventListener(e,t){this.eventListeners.has(e)&&this.eventListeners.get(e).delete(t)}dispatchEvent(e,t){this.isAnalyticsEnabled()&&this.analyticsHandlers.forEach(i=>{try{i(e,t)}catch(s){console.error(`[PlayerController] Error running analytics handler for "${e}":`,s)}}),this.eventListeners.has(e)&&this.eventListeners.get(e).forEach(i=>{try{i(t)}catch(s){console.error(`[PlayerController] Error executing event listener callback for event "${e}":`,s)}})}on(e,t){this.addEventListener(e,t)}off(e,t){this.removeEventListener(e,t)}emit(e,t){this.dispatchEvent(e,t)}registerAnalyticsHandler(e){this.isAnalyticsEnabled()&&this.analyticsHandlers.add(e)}unregisterAnalyticsHandler(e){this.analyticsHandlers.delete(e)}registerPlaybackInterceptor(e){this.playbackInterceptors.add(e)}unregisterPlaybackInterceptor(e){this.playbackInterceptors.delete(e)}getAdsState(){return this.ads.state()}getCurrentAd(){return this.ads.currentAd()}getCurrentAdBreak(){return this.ads.currentBreak()}isPlayingAd(){return!!this.ads.state().isAdPlaying}getAdProvider(){return this.ads.provider()}setAdsEnabled(e){this.config||(this.config={}),this.config.ads||(this.config.ads={}),this.config.ads.enabled=e,this.dispatchEvent("config-change",this.config)}skipAd(){this.ads.skip()}scheduleAd(e){return this.ads.schedule(e)}unscheduleAd(e){this.ads.unschedule(e)}async playAd(e){await this.ads.play(e)}registerOverlay(e,t){this.player&&typeof this.player.registerOverlay=="function"?this.player.registerOverlay(e,t):this.pendingOverlays.set(e,t)}load(e){const t=typeof e=="string"?{src:e}:e;this.loadSource(t)}addPlaylistItem(e){this.appendPlaylistItem(e)}getCurrentItem(){return this.hasPlaylist()?this.getCurrentPlaylistItem():this.state.currentSource?{src:this.state.currentSource,type:this.state.sourceType}:null}repeat(e){e===!0||e==="one"?(this.setLoop(!0),this.setPlaylistRepeatMode("off")):e==="all"?(this.setLoop(!1),this.setPlaylistRepeatMode("repeat-all")):(this.setLoop(!1),this.setPlaylistRepeatMode("off"))}getLiveEdgeTarget(){var s,r;const e=this.sourceManager.getRawLiveInfo();if(e&&e.liveEdgeTarget!==null&&e.liveEdgeTarget>0)return e.liveEdgeTarget;const t=((s=this.state.seekableRange)==null?void 0:s.end)??0,i=((r=this.state.seekableRange)==null?void 0:r.start)??0;if(t>0){const a=this.state.isLowLatency?5:15;return Math.max(i,t-a)}return this.state.duration||0}buildLiveCapabilities(){const e=this.sourceManager.getRawLiveInfo();if(!e||!e.isLive)return null;let t=0,i=this.video.duration||0;this.video.seekable&&this.video.seekable.length>0&&(t=this.video.seekable.start(0),i=this.video.seekable.end(this.video.seekable.length-1),t>i&&(t=i));const s=e.dvrWindow!==void 0?e.dvrWindow:i-t;if(s>0){const h=i-s;h>t&&(t=h)}const r={start:t,end:i},a=e.hasDvr!==void 0?e.hasDvr:s>10,n=e.liveEdgeTarget!==null?e.liveEdgeTarget:i,l=Math.max(0,n-this.video.currentTime),o=e.isLowLatency?6:18,d=l<=o;return{isLive:!0,isLowLatency:e.isLowLatency,hasDvr:a,dvrWindow:s,seekableRange:r,liveLatency:l,isAtLiveEdge:d}}updateLiveState(){if(!this.state.isLive)return;let e=this.buildLiveCapabilities();if(!e){const t=this.getSeekableStateBatch();t.isLive&&(e={isLive:!0,isLowLatency:!1,hasDvr:t.hasDvr,dvrWindow:t.dvrWindow,seekableRange:t.seekableRange,liveLatency:Math.max(0,t.seekableRange.end-this.video.currentTime),isAtLiveEdge:!0})}if(e){let t=e.hasDvr;this.state.liveMode==="live-only"&&(t=!1),this.updateState({isLive:e.isLive,isLowLatency:e.isLowLatency,hasDvr:e.hasDvr,seekableRange:e.seekableRange,dvrWindow:e.dvrWindow,canSeekInDvr:t,liveLatency:e.liveLatency,isAtLiveEdge:e.isAtLiveEdge})}}seekToLiveEdge(){if(this.updateState({isAtLiveEdge:!0}),this.state.seekableRange)this.video.currentTime=this.state.seekableRange.end;else if(!this.sourceManager.seekToLiveEdge()){const e=this.getLiveEdgeTarget();this.video.currentTime=e}this.play(),this.dispatchEvent("live-edge-sync",{latency:this.state.liveLatency||0})}getLiveLatency(){return this.state.liveLatency}isAtLiveEdge(){return this.state.isAtLiveEdge}showMarkerTypes(e){if(!this.state.visibleMarkerTypes)this.updateState({visibleMarkerTypes:[...e]});else{const t=new Set([...this.state.visibleMarkerTypes,...e]);this.updateState({visibleMarkerTypes:Array.from(t)})}}hideMarkerTypes(e){if(this.state.visibleMarkerTypes){const t=this.state.visibleMarkerTypes.filter(i=>!e.includes(i));this.updateState({visibleMarkerTypes:t})}else{const i=Array.from(new Set(this.state.markers.map(s=>s.type))).filter(s=>!e.includes(s));this.updateState({visibleMarkerTypes:i})}}setMarkerVisibility(e){this.updateState({visibleMarkerTypes:e})}getStatistics(){const e=this.video;let t=0;const i=e.buffered,s=e.currentTime;for(let h=0;h<i.length;h++){const u=i.start(h),f=i.end(h);if(s>=u&&s<=f){t=f-s;break}}let r,a;if(typeof e.getVideoPlaybackQuality=="function"){const h=e.getVideoPlaybackQuality();r=h.totalVideoFrames,a=h.droppedVideoFrames}else if(e.webkitDecodedFrameCount!==void 0){const h=e;r=h.webkitDecodedFrameCount,a=h.webkitDroppedFrameCount}let n;const l=performance.now();if(r!==void 0)if(this.lastFpsTimestamp>0){const h=(l-this.lastFpsTimestamp)/1e3;if(h>=.25){const u=r-this.lastDecodedFrames;this.lastCalculatedFps=Math.max(0,Math.round(u/h)),this.lastDecodedFrames=r,this.lastFpsTimestamp=l}n=this.lastCalculatedFps}else this.lastDecodedFrames=r,this.lastFpsTimestamp=l,n=0;const o={currentTime:s,duration:e.duration||0,playbackRate:e.playbackRate,paused:e.paused,ended:e.ended,muted:e.muted,volume:e.volume,width:e.videoWidth||void 0,height:e.videoHeight||void 0,fps:n,droppedFrames:a,decodedFrames:r,bufferedLength:t,bufferHealth:t,isLive:this.state.isLive===!0,liveLatency:this.state.liveLatency!==null?this.state.liveLatency:void 0,isLowLatency:this.state.isLowLatency},d=this.sourceManager.getActiveHandler();if(d&&typeof d.getStats=="function"){const h=d.getStats();h.bitrate!==void 0&&(o.bitrate=h.bitrate),h.bandwidthEstimate!==void 0&&(o.bandwidthEstimate=h.bandwidthEstimate)}return o}updateMediaSession(){if(typeof window>"u"||!("mediaSession"in navigator))return;const e=this.state.currentSource,t=this.state.playlist,i=this.state.activePlaylistIndex,r={...t&&t[i],...e?{src:e}:{}},a=r.title||(typeof e=="string"?e.split("/").pop():"")||"Video Playback",n=r.artist||"Player SDK",l=r.album||"",o=r.artwork||(r.poster?[{src:r.poster}]:[]);try{navigator.mediaSession.metadata=new MediaMetadata({title:a,artist:n,album:l,artwork:o}),navigator.mediaSession.setActionHandler("play",()=>{this.play()}),navigator.mediaSession.setActionHandler("pause",()=>{this.pause()}),navigator.mediaSession.setActionHandler("seekbackward",d=>{const h=d.seekOffset||10;this.seekBy(-h)}),navigator.mediaSession.setActionHandler("seekforward",d=>{const h=d.seekOffset||10;this.seekBy(h)}),navigator.mediaSession.setActionHandler("seekto",d=>{d.seekTime!==void 0&&this.seek(d.seekTime)}),t&&t.length>1?(navigator.mediaSession.setActionHandler("previoustrack",()=>{this.previous()}),navigator.mediaSession.setActionHandler("nexttrack",()=>{this.next()})):(navigator.mediaSession.setActionHandler("previoustrack",null),navigator.mediaSession.setActionHandler("nexttrack",null))}catch(d){console.warn("[PlayerController] Failed to update Media Session metadata:",d)}}updateMediaSessionPosition(){if(!(typeof window>"u"||!("mediaSession"in navigator)||typeof navigator.mediaSession.setPositionState!="function"))try{const e=this.video.duration,t=this.video.currentTime,i=this.video.playbackRate;Number.isFinite(e)&&Number.isFinite(t)&&Number.isFinite(i)&&e>=0&&t>=0&&t<=e&&navigator.mediaSession.setPositionState({duration:e,playbackRate:i,position:t})}catch{}}updateMediaSessionPlaybackState(e){if(!(typeof window>"u"||!("mediaSession"in navigator)))try{navigator.mediaSession.playbackState=e?"playing":"paused"}catch{}}}class Tr{static async validate(e){const t={emeSupported:typeof navigator<"u"&&typeof navigator.requestMediaKeySystemAccess=="function",keySystems:{},activeSystem:null,hasMediaKeys:!1,activeSessionsCount:0,sessionIds:[],keyStatuses:[],hasUsableKey:!1,errors:[],passed:!1,requestMediaKeySystemAccessChecked:!1,mediaKeysCreatedChecked:!1,mediaKeysAttachedChecked:!1,encryptedEventCount:0,licenseChallengeGeneratedCount:0,licenseRequestSentCount:0,licenseResponseReceivedCount:0,sessionUpdatedCount:0,keyStatusesChangeCount:0,usableKeysCount:0,expiredKeysCount:0,outputRestrictedCount:0,internalErrorsCount:0,closedSessionsCount:0,lastInternalError:null};if(!t.emeSupported)return t.errors.push("EME is not supported on this platform/browser."),t;const i={widevine:"com.widevine.alpha",playready:"com.microsoft.playready",fairplay:"com.apple.fps",clearkey:"org.w3.clearkey"},s=[{contentType:'video/mp4; codecs="avc1.640028"'},{contentType:'video/mp4; codecs="avc1.4d401e"'},{contentType:"video/mp4"},{contentType:'video/webm; codecs="vp9"'}],r=[{contentType:'audio/mp4; codecs="mp4a.40.2"'},{contentType:"audio/mp4"},{contentType:'audio/webm; codecs="opus"'}];for(const[l,o]of Object.entries(i))try{const d=[{initDataTypes:["cenc","keyids","webm","skd","sinf"],videoCapabilities:s,audioCapabilities:r},{initDataTypes:["cenc","keyids","webm","skd","sinf"],videoCapabilities:s},{initDataTypes:["cenc","keyids","webm","skd","sinf"],audioCapabilities:r},{initDataTypes:["cenc","keyids","webm","skd","sinf"],videoCapabilities:s,persistentState:"not-allowed",distinctiveIdentifier:"not-allowed"}];await navigator.requestMediaKeySystemAccess(o,d),t.keySystems[l]=!0}catch{t.keySystems[l]=!1}const a=e.getVideoElement();if(a&&a.mediaKeys){t.hasMediaKeys=!0;const l=e.getDrmManager();if(l){const o=l.getConfig();o&&(t.activeSystem=Object.keys(o).find(u=>u!=="robustness"&&u!=="distinctiveIdentifier"&&u!=="persistentState"&&u!=="retryCount"&&u!=="timeout")||null);const d=l.getActiveSessions();d&&(t.activeSessionsCount=d.size,d.forEach(u=>{u.sessionId&&t.sessionIds.push(u.sessionId),u.keyStatuses&&u.keyStatuses.forEach(f=>{t.keyStatuses.push(String(f)),f==="usable"&&(t.hasUsableKey=!0)})}));const h=l.emeDiagnostics;h&&(t.requestMediaKeySystemAccessChecked=h.requestMediaKeySystemAccess,t.mediaKeysCreatedChecked=h.mediaKeysCreated,t.mediaKeysAttachedChecked=h.mediaKeysAttached,t.encryptedEventCount=h.encryptedEventsCount,t.licenseChallengeGeneratedCount=h.challengesGenerated,t.licenseRequestSentCount=h.licenseRequestsSent,t.licenseResponseReceivedCount=h.licenseResponsesReceived,t.sessionUpdatedCount=h.sessionsUpdated,t.keyStatusesChangeCount=h.keyStatusesChanges,t.usableKeysCount=h.usableKeysCount,t.expiredKeysCount=h.expiredKeysCount,t.outputRestrictedCount=h.outputRestrictedCount,t.internalErrorsCount=h.internalErrorsCount,t.closedSessionsCount=h.closedSessionsCount,t.lastInternalError=h.lastInternalError,h.expiredKeysCount>0&&t.errors.push(`EME has ${h.expiredKeysCount} expired key(s).`),h.outputRestrictedCount>0&&t.errors.push("EME playback restricted by HDCP output constraints."),h.internalErrorsCount>0&&h.lastInternalError&&t.errors.push(`EME Internal Error: ${h.lastInternalError}`))}}const n=e.getState();return n&&n.error&&t.errors.push(n.error),t.passed=t.emeSupported&&t.errors.length===0,t}}const Er=Ae`
2039
+ */function Us(c,e){return(t,i,s)=>{const r=a=>{var n;return((n=a.renderRoot)==null?void 0:n.querySelector(c))??null};return Fs(t,i,{get(){return r(this)}})}}var w=(c=>(c.IDLE="idle",c.REQUESTING="ad-requesting",c.LOADED="ad-loaded",c.PLAYING="ad-playing",c.PAUSED="ad-paused",c.BUFFERING="ad-buffering",c.SKIPPING="ad-skipping",c.ENDED="ad-ended",c.ERROR="ad-error",c.CONTENT_RESUMING="content-resuming",c))(w||{}),xi=(c=>(c.PREROLL="preroll",c.MIDROLL="midroll",c.POSTROLL="postroll",c))(xi||{}),Ai=(c=>(c.IMA="IMA",c.VAST="VAST",c.VMAP="VMAP",c.CUSTOM="CUSTOM",c))(Ai||{}),ze=(c=>(c.AUTO="auto",c.USER="user",c.DISABLED="disabled",c))(ze||{}),Pi=(c=>(c.LINEAR="linear",c.NON_LINEAR="non-linear",c.COMPANION="companion",c.OVERLAY="overlay",c))(Pi||{}),Ci=(c=>(c.IMPRESSION="impression",c.CREATIVE_VIEW="creativeView",c.START="start",c.FIRST_QUARTILE="firstQuartile",c.MIDPOINT="midpoint",c.THIRD_QUARTILE="thirdQuartile",c.COMPLETE="complete",c.PAUSE="pause",c.RESUME="resume",c.MUTE="mute",c.UNMUTE="unmute",c.CLICK="click",c.SKIP="skip",c.CLOSE="close",c.ERROR="error",c))(Ci||{}),ie=(c=>(c.CONFIGURATION="configuration",c.PROVIDER="provider",c.NETWORK="network",c.TIMEOUT="timeout",c.PARSING="parsing",c.PLAYBACK="playback",c.TRACKING="tracking",c.BLOCKED="blocked",c.UNKNOWN="unknown",c))(ie||{});class Mi{static validate(e){var s;const t={passed:!1,providerConfigured:!1,tagUrlValid:!1,errors:[]},i=(s=e.config)==null?void 0:s.ads;if(!i)return t.errors.push("No advertisement configuration provided."),t;if(i.enabled===!1)return t.errors.push("Ads subsystem is disabled in configuration."),t;if(i.provider?t.providerConfigured=!0:t.errors.push("No ad provider specified in config."),i.tagUrl)try{new URL(i.tagUrl),t.tagUrlValid=!0}catch{t.errors.push(`Invalid ad tag URL: "${i.tagUrl}"`)}else i.inlineXml||t.errors.push("Neither tagUrl nor inlineXml is configured.");return t.passed=t.errors.length===0,t}}function ce(c,e=!1){if(isNaN(c)||c===1/0)return e?"00:00:00":"00:00";const t=c<0,i=Math.abs(c),s=Math.floor(i%60),r=Math.floor(i/60%60),a=Math.floor(i/3600),n=o=>o.toString().padStart(2,"0"),l=a>0||e?`${n(a)}:${n(r)}:${n(s)}`:`${n(r)}:${n(s)}`;return t?`-${l}`:l}function Ii(c){if(!c||typeof window>"u")return!1;try{return new URL(c,window.location.href).origin===window.location.origin}catch{return!1}}const Bs=["script","iframe","object","embed","link","meta","base","form"],Ns=/^\s*(javascript:|data:text\/html)/i;function Vs(c){var e;if(!c)return"";if(typeof DOMParser>"u")return console.warn("[utils] DOMParser is not defined in this environment. Cannot sanitize HTML."),"";try{const t=new DOMParser().parseFromString(c,"text/html");for(const r of Bs){const a=t.body.getElementsByTagName(r);for(;a.length>0;)(e=a[0].parentNode)==null||e.removeChild(a[0])}const i=t.createTreeWalker(t.body,NodeFilter.SHOW_ELEMENT);let s=i.currentNode;for(;s;){for(const r of Array.from(s.attributes)){const a=r.name.toLowerCase();if(a.startsWith("on")){s.removeAttribute(r.name);continue}(a==="href"||a==="src"||a==="style")&&Ns.test(r.value)&&s.removeAttribute(r.name)}s=i.nextNode()}return t.body.innerHTML}catch(t){return console.warn("[utils] Failed to sanitize HTML overlay content:",t),""}}function Li(c,e){const t=c.split(/\s+/).filter(Boolean);return!t.includes("allow-same-origin")||!(!!e.isSrcDoc||Ii(e.srcUrl))?c:(console.warn("[utils] Stripping allow-same-origin from iframe sandbox: creative resolves to the host page's own origin, which would otherwise grant it full DOM access to the host document."),t.filter(s=>s!=="allow-same-origin").join(" "))}function zs(c){var l,o,d,h;if(!c)return null;let e=c.trim();if(e.length===0)return null;if(e.toLowerCase().includes("<iframe"))try{if(typeof DOMParser>"u")return console.warn("[utils] DOMParser is not defined in this environment. Cannot parse iframe HTML."),null;const f=new DOMParser().parseFromString(e,"text/html");if(f.getElementsByTagName("script").length>0)return console.warn("[utils] script tag detected inside iframe HTML. Rejecting."),null;const g=f.querySelector("iframe");if(!g)return console.warn("[utils] No iframe element found in input HTML."),null;const m=g.getAttribute("src");if(!m)return console.warn("[utils] iframe element has no src attribute."),null;e=m.trim()}catch(u){return console.error("[utils] Error parsing iframe HTML:",u),null}let t;try{t=new URL(e)}catch{return console.warn("[utils] Invalid URL format for embed: ",e),null}if(t.protocol!=="http:"&&t.protocol!=="https:")return console.warn("[utils] Protocol not allowed for embed: ",t.protocol),null;const i=t.hostname.toLowerCase();if(!["youtube.com","www.youtube.com","m.youtube.com","youtu.be","vimeo.com","www.vimeo.com","player.vimeo.com","dailymotion.com","www.dailymotion.com","geo.dailymotion.com","twitch.tv","player.twitch.tv","wistia.com","wistia.net","fast.wistia.com","fast.wistia.net","streamable.com","facebook.com","www.facebook.com"].some(u=>i===u||i.endsWith("."+u)))return console.warn("[utils] Host not approved for embed: ",i),null;let a=e;const n=e.toLowerCase();if(n.includes("youtube.com")||n.includes("youtu.be")){let u="";n.includes("youtube.com/watch")?u=t.searchParams.get("v")||"":n.includes("youtu.be/")?u=((l=e.split("youtu.be/")[1])==null?void 0:l.split("?")[0])||"":n.includes("youtube.com/embed/")&&(u=((o=e.split("youtube.com/embed/")[1])==null?void 0:o.split("?")[0])||""),u&&(a=`https://www.youtube.com/embed/${u}?autoplay=1&rel=0&modestbranding=1`)}else if(n.includes("vimeo.com")){let u="";n.includes("player.vimeo.com/video/")?u=((d=e.split("player.vimeo.com/video/")[1])==null?void 0:d.split("?")[0])||"":u=((h=e.split("vimeo.com/")[1])==null?void 0:h.split("?")[0])||"",u&&(a=`https://player.vimeo.com/video/${u}?autoplay=1`)}return a}function Ri(){const c=globalThis.Hls;return typeof c=="function"?Promise.resolve(c):import("https://cdn.jsdelivr.net/npm/hls.js@1/+esm").then(e=>e.default??e)}function Di(c){return!!c&&typeof c.MediaPlayer=="function"}function $i(){const c=globalThis.dashjs;return Di(c)?Promise.resolve(c):import("https://cdn.jsdelivr.net/npm/dashjs@5/+esm").then(e=>{const t=e.default;return Di(t)?t:e})}function tt(c){return c instanceof Error?c.message:String(c)}function ft(c){return c instanceof Error?c.name:void 0}let Oi=!1;const gt=new WeakMap,Dt=new WeakMap,Fi=new WeakMap,it=new WeakMap,Ui=new WeakSet;function Bi(){return{requestMediaKeySystemAccess:!1,mediaKeysCreated:!1,mediaKeysAttached:!1,encryptedEventsCount:0,challengesGenerated:0,licenseRequestsSent:0,licenseResponsesReceived:0,sessionsUpdated:0,keyStatusesChanges:0,usableKeysCount:0,expiredKeysCount:0,outputRestrictedCount:0,internalErrorsCount:0,closedSessionsCount:0,lastInternalError:null,certificatesLoaded:0,certificateLoadLatenciesMs:[],licenseRequestLatenciesMs:[],retryCount:0}}function _s(c){let e="";for(let i=0;i<c.byteLength;i++)e+=String.fromCharCode(c[i]);return(typeof window<"u"&&typeof window.btoa=="function"?window.btoa(e):Buffer.from(c).toString("base64")).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function Hs(c){const e=c.replace(/[\s:-]/g,"");return e.length>0&&e.length%2===0&&/^[0-9a-fA-F]+$/.test(e)}function $t(c){const e=c.trim();if(!e)return"";if(Hs(e)){const i=e.replace(/[\s:-]/g,"").match(/.{1,2}/g);if(!i)return"";const s=new Uint8Array(i.map(r=>parseInt(r,16)));return _s(s)}return e.replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function Ot(c){if(!c)return{};const e={};return Object.entries(c).forEach(([t,i])=>{e[$t(t)]=$t(i)}),e}function qs(){if(Oi||typeof window>"u"||typeof MediaKeys>"u"||typeof MediaKeys.prototype.createSession!="function")return;if(Oi=!0,typeof HTMLVideoElement<"u"&&HTMLVideoElement.prototype.setMediaKeys){const e=HTMLVideoElement.prototype.setMediaKeys;HTMLVideoElement.prototype.setMediaKeys=function(t){const i=Dt.get(this);return i&&t&&gt.set(t,i),e.call(this,t)}}if(typeof MediaKeySystemAccess<"u"&&MediaKeySystemAccess.prototype.createMediaKeys){const e=MediaKeySystemAccess.prototype.createMediaKeys;MediaKeySystemAccess.prototype.createMediaKeys=function(){const t=this.keySystem,i=e.call(this);return i.then(s=>{Fi.set(s,t)}).catch(()=>{}),i}}const c=MediaKeys.prototype.createSession;if(MediaKeys.prototype.createSession=function(e){const t=c.call(this,e),i=gt.get(this),s=Fi.get(this)||"unknown";if(i){it.set(t,i),i.registerSession(t),t.addEventListener("keystatuseschange",()=>{const a={};i.recordKeyStatusesChange(t),t.keyStatuses.forEach((l,o)=>{const d=i.bufferToHex(o);a[d]=l,l==="output-restricted"?i.triggerDrmError("Playback restricted by HDCP output requirements.","certificate"):l==="expired"&&i.triggerDrmError("Playback key has expired.","certificate")});const n=i.getController();n&&n.dispatchEvent("drmkeychange",{session:t,keyStatuses:a})}),t.addEventListener("message",a=>{i.recordChallengeGenerated();const n=i.getController();n&&n.dispatchEvent("drmmessage",{session:t,messageType:a.messageType,message:a.message})});const r=i.getController();r&&r.dispatchEvent("drmsessioncreated",{session:t,system:s})}return t},typeof MediaKeySession<"u"&&typeof MediaKeySession.prototype.update=="function"){const e=MediaKeySession.prototype.update;MediaKeySession.prototype.update=async function(t){const i=await e.call(this,t),s=it.get(this);return s&&s.recordSessionUpdated(),i}}if(typeof MediaKeySession<"u"&&typeof MediaKeySession.prototype.close=="function"){const e=MediaKeySession.prototype.close;MediaKeySession.prototype.close=async function(){const t=await e.call(this),i=it.get(this);return i&&!Ui.has(this)&&(Ui.add(this),i.recordClosedSession(this)),t}}}async function Re(c,e='video/mp4; codecs="avc1.640028"'){if(typeof window>"u"||typeof navigator>"u"||typeof navigator.requestMediaKeySystemAccess!="function")return!1;try{const t=[{initDataTypes:["cenc","keyids","webm","skd","sinf"],videoCapabilities:[{contentType:e}]}];return await navigator.requestMediaKeySystemAccess(c,t),!0}catch{return!1}}async function Ft(){return Re("com.widevine.alpha")}async function Ut(){const c=["com.microsoft.playready","com.microsoft.playready.recommendation","com.chromecast.playready"];for(const e of c)if(await Re(e))return!0;return!1}async function Bt(){if(typeof window>"u")return!1;const c=["com.apple.fps","com.apple.fps.1_0","com.apple.fps.2_0","com.apple.fps.3_0"];for(const e of c)if(await Re(e))return!0;if(typeof window.WebKitMediaKeys=="function"&&typeof window.WebKitMediaKeys.isTypeSupported=="function")try{return window.WebKitMediaKeys.isTypeSupported("com.apple.fps","video/mp4")}catch{return!1}return!1}async function Nt(){return Re("org.w3.clearkey")}async function Ks(){const[c,e,t,i]=await Promise.all([Ft(),Ut(),Bt(),Nt()]);return{widevine:c,playready:e,fairplay:t,clearkey:i}}const Ee=class Ee{constructor(){this.emeDiagnostics=Bi(),this.video=null,this.config=null,this.controller=null,this.mediaKeys=null,this.activeSessions=new Set,this.isDestroyed=!1,this.destroyAbortController=new AbortController,this.eventListeners=[],this.sessionToContentId=new WeakMap,this.pendingLicenseRequests=new Map}getConfig(){return this.config}getActiveSessions(){return this.activeSessions}load(e,t,i,s=!1){if(this.destroy(),this.video=e,this.config=t,this.controller=i,this.isDestroyed=!1,this.destroyAbortController=new AbortController,this.emeDiagnostics=Bi(),this.pendingLicenseRequests.clear(),Ee.activeManagers.add(this),Dt.set(e,this),qs(),!s){const r=n=>{this.handleEncryptedEvent(n)},a=n=>{const l=n.initData;if(l){const o=l instanceof Uint8Array?l:new Uint8Array(l);this.initializeLegacyWebKitSession(o)}};this.video.addEventListener("encrypted",r),this.video.addEventListener("webkitneedkey",a),this.eventListeners.push({target:this.video,type:"encrypted",listener:r}),this.eventListeners.push({target:this.video,type:"webkitneedkey",listener:a})}}registerSession(e){this.activeSessions.add(e),it.set(e,this)}unregisterSession(e){this.activeSessions.delete(e),it.delete(e)}triggerDrmError(e,t,i){this.handleDrmError(e,t,i)}async handleEncryptedEvent(e){if(this.isDestroyed||!this.video||!this.config)return;const t=e.initDataType,i=e.initData;i&&(this.emeDiagnostics.encryptedEventsCount+=1,await this.initializeSession(t,new Uint8Array(i)))}async selectSupportedKeySystem(){if(!this.config)return null;if(this.config.widevine&&await Ft())return{keySystem:"com.widevine.alpha",config:this.config.widevine};if(this.config.playready&&await Ut()){const e=["com.microsoft.playready","com.microsoft.playready.recommendation","com.chromecast.playready"];for(const t of e)if(await Re(t))return{keySystem:t,config:this.config.playready}}if(this.config.fairplay&&await Bt()){const e=["com.apple.fps","com.apple.fps.1_0","com.apple.fps.2_0","com.apple.fps.3_0"];for(const t of e)if(await Re(t))return{keySystem:t,config:this.config.fairplay};return{keySystem:"com.apple.fps",config:this.config.fairplay}}return this.config.clearkey&&await Nt()?{keySystem:"org.w3.clearkey",config:this.config.clearkey}:null}async ensureMediaKeys(e,t){var i,s,r,a,n,l,o,d,h,u;if(this.mediaKeys)return this.mediaKeys;if(!this.video)throw new Error("No video element attached.");try{this.emeDiagnostics.requestMediaKeySystemAccess=!0;const f=((s=(i=this.config)==null?void 0:i.robustness)==null?void 0:s.video)||"",p=((a=(r=this.config)==null?void 0:r.robustness)==null?void 0:a.audio)||"",g=[{contentType:'video/mp4; codecs="avc1.640028"',...f?{robustness:f}:{}},{contentType:'video/mp4; codecs="avc1.4d401e"',...f?{robustness:f}:{}},{contentType:"video/mp4",...f?{robustness:f}:{}},{contentType:'video/webm; codecs="vp9"',...f?{robustness:f}:{}}],m=[{contentType:'audio/mp4; codecs="mp4a.40.2"',...p?{robustness:p}:{}},{contentType:"audio/mp4",...p?{robustness:p}:{}},{contentType:'audio/webm; codecs="opus"',...p?{robustness:p}:{}}],v=[{initDataTypes:["cenc","keyids","webm","skd","sinf"],videoCapabilities:g,audioCapabilities:m,sessionTypes:["temporary"],persistentState:((n=this.config)==null?void 0:n.persistentState)||"optional",distinctiveIdentifier:((l=this.config)==null?void 0:l.distinctiveIdentifier)||"optional"},{initDataTypes:["cenc","keyids","webm","skd","sinf"],videoCapabilities:g,sessionTypes:["temporary"],persistentState:((o=this.config)==null?void 0:o.persistentState)||"optional",distinctiveIdentifier:((d=this.config)==null?void 0:d.distinctiveIdentifier)||"optional"},{initDataTypes:["cenc","keyids","webm","skd","sinf"],audioCapabilities:m,sessionTypes:["temporary"],persistentState:((h=this.config)==null?void 0:h.persistentState)||"optional",distinctiveIdentifier:((u=this.config)==null?void 0:u.distinctiveIdentifier)||"optional"},{initDataTypes:["cenc","keyids","webm","skd","sinf"],videoCapabilities:g,sessionTypes:["temporary"],persistentState:"not-allowed",distinctiveIdentifier:"not-allowed"}],y=await navigator.requestMediaKeySystemAccess(e,v);if(this.isDestroyed)throw new DOMException("Aborted","AbortError");const b=await y.createMediaKeys();if(this.emeDiagnostics.mediaKeysCreated=!0,this.isDestroyed)throw new DOMException("Aborted","AbortError");gt.set(b,this);const S=await this.loadCertificate(t);if(this.isDestroyed)throw new DOMException("Aborted","AbortError");if(S&&(await b.setServerCertificate(S),this.isDestroyed))throw new DOMException("Aborted","AbortError");if(!this.video)throw new DOMException("Aborted","AbortError");return await this.video.setMediaKeys(b),this.mediaKeys=b,this.emeDiagnostics.mediaKeysAttached=!0,b}catch(f){throw ft(f)==="AbortError"||this.handleDrmError(`Failed to initialize MediaKeys for ${e}: ${tt(f)}`,"key-system",f),f}}async fetchWithRetryAndTimeout(e,t,i=3,s=1e4){let r=0;const a=n=>new Promise(l=>setTimeout(l,n));for(;r<=i;){if(this.isDestroyed||this.destroyAbortController.signal.aborted)throw new DOMException("Aborted","AbortError");const n=new AbortController,l=n.signal,o=()=>n.abort();this.destroyAbortController.signal.addEventListener("abort",o);const d=setTimeout(()=>{n.abort()},s);try{const h=await fetch(e,{...t,signal:l});if(clearTimeout(d),this.destroyAbortController.signal.removeEventListener("abort",o),h.ok)return h;if(h.status>=500&&r<i){r++,await a(Math.pow(2,r)*100);continue}throw new Error(`Server returned HTTP status ${h.status}`)}catch(h){if(clearTimeout(d),this.destroyAbortController.signal.removeEventListener("abort",o),this.isDestroyed||this.destroyAbortController.signal.aborted)throw new DOMException("Aborted","AbortError");if(r<i){r++,await a(Math.pow(2,r)*100);continue}throw h}}throw new Error("Request failed after maximum retries")}async loadCertificate(e){var n,l;if(!e)return null;if(e.serverCertificate instanceof Uint8Array)return this.recordCertificateLoaded(0),e.serverCertificate;const t=e.serverCertificateUrl||e.certificateUrl;if(!t)return null;const i=Ee.certCache.get(t);if(i)return this.recordCertificateLoaded(0),i;const s=e.retryCount??((n=this.config)==null?void 0:n.retryCount)??3,r=e.timeout??((l=this.config)==null?void 0:l.timeout)??1e4,a=this.now();try{const d=await(await this.fetchWithRetryAndTimeout(t,{method:"GET"},s,r)).arrayBuffer(),h=new Uint8Array(d);return Ee.certCache.set(t,h),this.recordCertificateLoaded(this.now()-a),h}catch(o){throw ft(o)==="AbortError"||this.handleDrmError("Failed to load server certificate.","certificate",o),o}}async fetchLicense(e,t,i,s){var f,p;const r=this.getConfiguredSystemName(),a=this.resolveSystemConfig(r),n=(a==null?void 0:a.retryCount)??((f=this.config)==null?void 0:f.retryCount)??3,l=(a==null?void 0:a.timeout)??((p=this.config)==null?void 0:p.timeout)??1e4,o=this.recordLicenseRequest(r,e),h={method:"POST",headers:{"Content-Type":"application/octet-stream",...i},body:t};s&&(h.credentials="include");let u=!1;try{const g=await this.fetchWithRetryAndTimeout(e,h,n,l);return u=!0,await g.arrayBuffer()}catch(g){throw ft(g)==="AbortError",g}finally{this.recordLicenseResponse(o,u)}}resolveSystemConfig(e){if(this.config)switch(e){case"widevine":return this.config.widevine;case"playready":return this.config.playready;case"fairplay":return this.config.fairplay;case"clearkey":return this.config.clearkey;default:return}}async initializeSession(e,t){const i=await this.selectSupportedKeySystem();if(!i){this.handleDrmError("No supported key system found for DRM configuration.","key-system");return}const{keySystem:s,config:r}=i;let a=t,n="";if(s.includes("fps")||s.includes("apple")){const l=r;n=typeof l.extractContentId=="function"?l.extractContentId(t):this.getContentId(t),a=this.prepareFairPlayInitData(t)}try{const o=(await this.ensureMediaKeys(s,r)).createSession("temporary");this.activeSessions.add(o),n&&this.sessionToContentId.set(o,n);const d=async h=>{var u,f;try{const p=h.message,g=r.licenseUrl||"";if(s==="org.w3.clearkey"&&((f=(u=this.config)==null?void 0:u.clearkey)!=null&&f.clearkeys))await this.handleClearKeyInlineUpdate(o);else{if(!g)throw new Error("No license URL configured.");let m;if(s.includes("fps")||s.includes("apple")){const v=this.sessionToContentId.get(o)||"";m=await this.fetchFairPlayLicense(g,p,v,r.headers,r.withCredentials)}else m=await this.fetchLicense(g,p,r.headers,r.withCredentials);if(this.isDestroyed)return;await o.update(m)}}catch(p){this.handleDrmError(`License acquisition failed: ${tt(p)}`,"license",p)}};o.addEventListener("message",d),this.eventListeners.push({target:o,type:"message",listener:d}),await o.generateRequest(e,a)}catch(l){this.handleDrmError(`Failed to create or run MediaKeySession: ${tt(l)}`,"session",l)}}async initializeLegacyWebKitSession(e){var s;if(!this.video||!((s=this.config)!=null&&s.fairplay))return;const t=this.config.fairplay,i=typeof t.extractContentId=="function"?t.extractContentId(e):this.getContentId(e);try{const r=window.WebKitMediaKeys;if(!r)throw new Error("WebKitMediaKeys is unsupported on this browser.");const a=await this.loadCertificate(t);if(!a)throw new Error("FairPlay certificate is required.");const n=this.concatInitData(i,a),l=new r("com.apple.fps");this.video.webkitSetMediaKeys(l);const o=l.createSession("video/mp4",n);if(!o)throw new Error("Failed to create WebKitMediaKeySession.");const d=o;i&&this.sessionToContentId.set(d,i);const h=async p=>{const g=p,m=g.message,v=g.destinationURL||t.licenseUrl,y=this.sessionToContentId.get(d)||"";this.recordChallengeGenerated();try{if(!v)throw new Error("No FairPlay license URL configured.");const b=await this.fetchFairPlayLicense(v,m,y,t.headers,t.withCredentials);if(this.isDestroyed)return;o.update(new Uint8Array(b)),this.recordSessionUpdated()}catch(b){this.handleDrmError("Legacy FairPlay license request failed.","license",b)}},u=()=>{this.emeDiagnostics.keyStatusesChanges+=1,this.emeDiagnostics.usableKeysCount+=1,this.controller&&this.controller.dispatchEvent("drmkeychange",{session:d,keyStatuses:{all:"usable"}})},f=p=>{const g=p;this.handleDrmError(`Legacy FairPlay session error: ${g.code??"unknown"}`,"session",g)};o.addEventListener("webkitkeymessage",h),o.addEventListener("webkitkeyadded",u),o.addEventListener("webkitkeyerror",f),this.eventListeners.push({target:o,type:"webkitkeymessage",listener:h}),this.eventListeners.push({target:o,type:"webkitkeyadded",listener:u}),this.eventListeners.push({target:o,type:"webkitkeyerror",listener:f}),this.activeSessions.add(d),this.controller&&this.controller.dispatchEvent("drmsessioncreated",{session:d,system:"com.apple.fps (Legacy)"})}catch(r){this.handleDrmError(`Failed to initialize legacy FairPlay session: ${tt(r)}`,"session",r)}}prepareFairPlayInitData(e){return e}async handleClearKeyInlineUpdate(e){var s,r;const t=(r=(s=this.config)==null?void 0:s.clearkey)==null?void 0:r.clearkeys;if(!t)return;const i=this.recordLicenseRequest("clearkey","inline://clearkey");try{const a=Object.entries(Ot(t)).map(([o,d])=>({kty:"oct",kid:o,k:d})),n=JSON.stringify({keys:a,type:"temporary"}),l=new TextEncoder().encode(n);await e.update(l),this.recordLicenseResponse(i,!0)}catch(a){this.recordLicenseResponse(i,!1),this.handleDrmError(`Failed to load ClearKey inline values: ${tt(a)}`,"license",a)}}handleDrmError(e,t,i){if(this.isDestroyed)return;const s=this.config?Object.keys(this.config).find(a=>a!=="robustness"&&a!=="distinctiveIdentifier"&&a!=="persistentState"):void 0,r={message:`DRM: ${e}`,system:s,errorType:t,originalError:i};this.emeDiagnostics.internalErrorsCount+=1,this.emeDiagnostics.lastInternalError=r.message,console.error("[DrmManager] Mapped DRM Error:",r),this.controller&&(this.controller.dispatchEvent("drmerror",r),this.controller.updateStatePublic({error:`DRM: ${e}`}),this.controller.dispatchEvent("error",{message:`DRM: ${e}`}))}bufferToHex(e){let t;e instanceof ArrayBuffer?t=e:t=e.buffer;const i=new DataView(t);let s="";for(let r=0;r<i.byteLength;r++){const a=i.getUint8(r);s+=a.toString(16).padStart(2,"0")}return s}destroy(){if(!this.isDestroyed){this.isDestroyed=!0,this.destroyAbortController.abort(),Ee.activeManagers.delete(this);for(const e of this.eventListeners)try{e.target.removeEventListener(e.type,e.listener)}catch{}this.eventListeners=[];for(const e of this.activeSessions)try{e.close().then(()=>{this.controller&&this.controller.dispatchEvent("drmsessionclosed",{session:e,system:"unknown"})}).catch(t=>{console.warn("[DrmManager] Error closing session:",t)})}catch(t){console.warn("[DrmManager] Failed to close session:",t)}if(this.activeSessions.clear(),this.pendingLicenseRequests.clear(),this.video){Dt.delete(this.video),this.mediaKeys&&gt.delete(this.mediaKeys);try{this.video.setMediaKeys(null).catch(e=>{console.warn("[DrmManager] Failed to setMediaKeys(null):",e)})}catch{if(typeof this.video.webkitSetMediaKeys=="function")try{this.video.webkitSetMediaKeys(null)}catch{}}}this.video=null,this.config=null,this.controller=null,this.mediaKeys=null}}getController(){return this.controller}noteLicenseRequest(e,t){this.recordLicenseRequest(e,t)}noteLicenseResponse(e,t){this.recordLicenseResponse(this.createLicenseRequestKey(e,t),!0)}now(){return typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now()}getConfiguredSystemName(){return this.config&&Object.keys(this.config).find(e=>e!=="robustness"&&e!=="distinctiveIdentifier"&&e!=="persistentState"&&e!=="retryCount"&&e!=="timeout")||"unknown"}createLicenseRequestKey(e,t){return`${e}::${t}`}recordLicenseRequest(e,t){const i=this.createLicenseRequestKey(e,t),s=this.pendingLicenseRequests.get(i)||[];return s.push(this.now()),this.pendingLicenseRequests.set(i,s),this.emeDiagnostics.licenseRequestsSent+=1,i}recordLicenseResponse(e,t){const i=this.pendingLicenseRequests.get(e)||[],s=i.shift();i.length>0?this.pendingLicenseRequests.set(e,i):this.pendingLicenseRequests.delete(e),typeof s=="number"&&this.emeDiagnostics.licenseRequestLatenciesMs.push(this.now()-s),t&&(this.emeDiagnostics.licenseResponsesReceived+=1)}recordCertificateLoaded(e){this.emeDiagnostics.certificatesLoaded+=1,this.emeDiagnostics.certificateLoadLatenciesMs.push(Math.max(0,e))}recordChallengeGenerated(){this.emeDiagnostics.challengesGenerated+=1}recordSessionUpdated(){this.emeDiagnostics.sessionsUpdated+=1}recordClosedSession(e){this.emeDiagnostics.closedSessionsCount+=1}recordKeyStatusesChange(e){this.emeDiagnostics.keyStatusesChanges+=1,e.keyStatuses.forEach(t=>{t==="usable"?this.emeDiagnostics.usableKeysCount+=1:t==="expired"?this.emeDiagnostics.expiredKeysCount+=1:t==="output-restricted"&&(this.emeDiagnostics.outputRestrictedCount+=1)})}getContentId(e){let t="";try{t=new TextDecoder("utf-16").decode(e),t.includes("skd://")||(t=new TextDecoder("utf-8").decode(e))}catch{t=new TextDecoder("utf-8").decode(e)}const i=t.indexOf("skd://");if(i===-1)return"";let s=t.substring(i+6);const r=s.indexOf("?");r!==-1&&(s=s.substring(0,r));const a=s.indexOf("#");return a!==-1&&(s=s.substring(0,a)),s.replace(/\0/g,"").trim()}concatInitData(e,t){const i=new TextEncoder().encode(e),s=4+i.length+4+t.length,r=new Uint8Array(s),a=new DataView(r.buffer);let n=0;return a.setUint32(n,i.length),n+=4,r.set(i,n),n+=i.length,a.setUint32(n,t.length),n+=4,r.set(t,n),r}async fetchFairPlayLicense(e,t,i,s,r){var m,v,y;const a=this.recordLicenseRequest("fairplay",e),n=this.arrayBufferToBase64(t),l=s&&(s["Content-Type"]==="application/octet-stream"||s["content-type"]==="application/octet-stream");let o=JSON.stringify({spc:n,contentId:i,assetId:i}),d={"Content-Type":"application/json",...s};l&&(o=t,d={"Content-Type":"application/octet-stream",...s});const h={method:"POST",headers:d,body:o};r&&(h.credentials="include");const u=(m=this.config)==null?void 0:m.fairplay,f=(u==null?void 0:u.retryCount)??((v=this.config)==null?void 0:v.retryCount)??3,p=(u==null?void 0:u.timeout)??((y=this.config)==null?void 0:y.timeout)??1e4;let g=!1;try{const b=await this.fetchWithRetryAndTimeout(e,h,f,p);if(g=!0,l)return await b.arrayBuffer();const S=await b.text();try{const x=JSON.parse(S);if(x.ckc)return this.base64ToArrayBuffer(x.ckc);if(x.license)return this.base64ToArrayBuffer(x.license)}catch{}const T=S.trim();return/^[A-Za-z0-9+/=]+$/.test(T)?this.base64ToArrayBuffer(T):new TextEncoder().encode(S).buffer}catch(b){throw ft(b)==="AbortError",b}finally{this.recordLicenseResponse(a,g)}}arrayBufferToBase64(e){const t=new Uint8Array(e);let i="";for(let s=0;s<t.byteLength;s++)i+=String.fromCharCode(t[s]);return typeof window<"u"&&typeof window.btoa=="function"?window.btoa(i):Buffer.from(t).toString("base64")}base64ToArrayBuffer(e){const t=typeof window<"u"&&typeof window.atob=="function"?window.atob(e):Buffer.from(e,"base64").toString("binary"),i=new ArrayBuffer(t.length),s=new Uint8Array(i);for(let r=0;r<t.length;r++)s[r]=t.charCodeAt(r);return i}};Ee.activeManagers=new Set,Ee.certCache=new Map;let De=Ee;function Vt(c){try{return c.getLowLatencyModeEnabled()}catch{return!1}}const Ws=6;function mt(c){if(!c)return"";const e=c.trim().toLowerCase();try{const r=new Intl.DisplayNames(["en"],{type:"language"}).of(e);if(r&&r!==e)return r.charAt(0).toUpperCase()+r.slice(1)}catch{}const t={en:"English",eng:"English",hi:"Hindi",hin:"Hindi",fr:"French",fre:"French",fra:"French",nl:"Dutch",dut:"Dutch",nld:"Dutch",es:"Spanish",spa:"Spanish",de:"German",ger:"German",deu:"German",it:"Italian",ita:"Italian",ja:"Japanese",jpn:"Japanese",zh:"Chinese",zho:"Chinese",chi:"Chinese",pt:"Portuguese",por:"Portuguese",ru:"Russian",rus:"Russian",ar:"Arabic",ara:"Arabic",ko:"Korean",kor:"Korean",sv:"Swedish",swe:"Swedish",no:"Norwegian",nor:"Norwegian",fi:"Finnish",fin:"Finnish",da:"Danish",dan:"Danish",pl:"Polish",pol:"Polish",tr:"Turkish",tur:"Turkish",vi:"Vietnamese",vie:"Vietnamese"},i=e.split("-")[0];return t[i]||t[e]||c.toUpperCase()}function js(c,e){if(c&&c.trim().length>0){const t=c.trim();if(!(/^stream(_\d+)?$/i.test(t)||/^audio(_\d+)?$/i.test(t)||/^\d+$/.test(t))){if(!/^[a-zA-Z]{2,3}(-[a-zA-Z]{2,4})?$/.test(t))return t;const r=mt(t);if(r)return r}}return e&&e.trim().length>0?mt(e.trim()):"Unknown"}class Gs{constructor(){this.source=null,this.video=null,this.controller=null,this.syncTracksListener=null,this.uniqueAudioTracks=[],this.qualityRestoreListener=null,this.drmManager=null}getDrmManager(){return this.drmManager}load(e,t,i){var h;this.source=e,this.video=t,this.controller=i,t.srcObject=null;const s={...((h=i.config)==null?void 0:h.drm)||{},...e.drm||{}};Object.keys(s).length>0&&(this.drmManager=new De,this.drmManager.load(t,s,i,!1));const a=!!(e.variants&&e.variants.length>1),n=a?e.variants.map(u=>u.label):[];let l=e.src||"",o="";if(a){const u=e.variants.findIndex(p=>p.src===e.src),f=u!==-1?u:0;l=e.variants[f].src,o=e.variants[f].label}l&&(t.src=l,t.load()),i.updateStatePublic({qualities:n,activeQuality:o,audioTracks:[],activeAudioTrack:-1,error:null}),this.uniqueAudioTracks=[];const d=t;if(d.audioTracks){const u=()=>{this.syncAndDeduplicateTracks()};this.syncTracksListener=u,d.audioTracks.addEventListener("change",u),d.audioTracks.addEventListener("addtrack",u),d.audioTracks.addEventListener("removetrack",u),this.syncAndDeduplicateTracks()}}syncAndDeduplicateTracks(){if(!this.video||!this.controller)return;const e=this.video;if(!e.audioTracks)return;const t=e.audioTracks,i={},s=[];for(let n=0;n<t.length;n++){const l=t[n],o=l.language||"",d=l.label||"",h=l.kind||"",u=o.toLowerCase(),f=d.toLowerCase(),p=h.toLowerCase(),g=`${u}|${f}|${p}`;i[g]||(i[g]={label:"",rawIndices:[]},s.push(g)),i[g].rawIndices.push(n)}this.uniqueAudioTracks=s.map(n=>{const l=i[n],o=t[l.rawIndices[0]],d=mt(o.language);let h="";o.label&&(/^[a-zA-Z]{2,3}(-[a-zA-Z]{2,4})?$/.test(o.label.trim())||(h=o.label.trim())),h||(h=d||"Unknown");const u=[h],f=o.kind||"";return f&&f!=="main"&&f!=="alternative"&&u.push(f.charAt(0).toUpperCase()+f.slice(1)),{label:u.join(" "),rawIndices:l.rawIndices}});const r=this.uniqueAudioTracks.map(n=>n.label);let a=-1;for(let n=0;n<this.uniqueAudioTracks.length;n++)if(this.uniqueAudioTracks[n].rawIndices.some(d=>t[d].enabled)){a=n;break}this.controller.updateStatePublic({audioTracks:r,activeAudioTrack:a})}destroy(){if(this.video){if(this.syncTracksListener){const e=this.video;e.audioTracks&&(e.audioTracks.removeEventListener("change",this.syncTracksListener),e.audioTracks.removeEventListener("addtrack",this.syncTracksListener),e.audioTracks.removeEventListener("removetrack",this.syncTracksListener))}this.qualityRestoreListener&&this.video.removeEventListener("loadedmetadata",this.qualityRestoreListener)}this.drmManager&&(this.drmManager.destroy(),this.drmManager=null),this.syncTracksListener=null,this.qualityRestoreListener=null,this.source=null,this.video=null,this.controller=null,this.uniqueAudioTracks=[]}setQuality(e){if(this.source&&this.source.variants&&this.video&&this.controller&&e>=0&&e<this.source.variants.length){const t=this.source.variants[e],i=!this.video.paused,s=this.video.currentTime;this.qualityRestoreListener&&this.video.removeEventListener("loadedmetadata",this.qualityRestoreListener);const r=()=>{this.qualityRestoreListener=null,this.video&&(this.video.currentTime=s,i&&this.video.play().catch(a=>console.warn("Restore play failed:",a)))};this.qualityRestoreListener=r,this.video.addEventListener("loadedmetadata",r,{once:!0}),this.video.src=t.src,this.video.load(),this.controller.updateStatePublic({activeQuality:t.label})}}setAudioTrack(e){if(this.video&&e>=0&&e<this.uniqueAudioTracks.length){const t=this.video;if(t.audioTracks){const s=this.uniqueAudioTracks[e].rawIndices[0];for(let r=0;r<t.audioTracks.length;r++)t.audioTracks[r].enabled=r===s;this.controller&&this.controller.updateStatePublic({activeAudioTrack:e})}}}}class Qs{constructor(){this.hls=null,this.hlsRetryCount=0,this.mediaRecoveryCount=0,this.controller=null,this.video=null,this.lastLevelIndex=-1,this.isAutoMode=!0,this.uniqueAudioTracks=[],this.livePollInterval=null,this._isLive=!1,this._isLowLatency=!1,this._dvrWindow=0,this._hasDvr=!1,this.managesSubtitles=!0,this.drmManager=null}getDrmManager(){return this.drmManager}startLivePolling(){this.stopLivePolling(),this.livePollInterval=setInterval(()=>{this.pollLiveStats()},500)}stopLivePolling(){this.livePollInterval&&(clearInterval(this.livePollInterval),this.livePollInterval=null)}getLiveSyncPosition(){return this.hls?this.hls.liveSyncPosition:null}pollLiveStats(){if(!this.hls||!this.controller||!this.video||!this.controller.getState().isLive)return;this.controller.updateLiveState();const t=this.controller.getState();this.controller.dispatchEvent("live-sync-update",{latency:t.liveLatency||0,isAtLiveEdge:t.isAtLiveEdge,playbackRate:this.video.playbackRate})}getRawLiveInfo(){var e;return this._isLive?{isLive:this._isLive,isLowLatency:this._isLowLatency,hasDvr:this._hasDvr,dvrWindow:this._dvrWindow,liveEdgeTarget:((e=this.hls)==null?void 0:e.liveSyncPosition)??null}:null}seekToLiveEdge(){this.hls&&this.hls.liveSyncPosition!==null&&this.video&&(this.video.currentTime=this.hls.liveSyncPosition)}load(e,t,i){e.src&&(this.destroy(),this.controller=i,this.video=t,this.lastLevelIndex=-1,this.isAutoMode=!0,this.uniqueAudioTracks=[],this.hlsRetryCount=0,this.mediaRecoveryCount=0,Ri().then(s=>{var a,n;if(this.controller!==i)return;const r=s;if(r.isSupported()){const o=i.getState().liveMode==="live-only",d={...((a=i.config)==null?void 0:a.drm)||{},...e.drm||{}},h=Object.keys(d).length>0;h&&(this.drmManager=new De,this.drmManager.load(t,d,i,!0)),(async()=>{var g,m,v,y;if(!h)return{};const f={},p={};if(d.widevine){const b=d.widevine,S=this.drmManager?await this.drmManager.loadCertificate(b):null;p["com.widevine.alpha"]=b.licenseUrl||"",f["com.widevine.alpha"]={videoCapabilities:[{contentType:'video/mp4; codecs="avc1.640028"'}],audioCapabilities:[{contentType:'audio/mp4; codecs="mp4a.40.2"'}],...S?{serverCertificate:S}:{},...(g=d.robustness)!=null&&g.video?{videoRobustness:d.robustness.video}:{},...(m=d.robustness)!=null&&m.audio?{audioRobustness:d.robustness.audio}:{},persistentState:d.persistentState||"optional",distinctiveIdentifier:d.distinctiveIdentifier||"optional",sessionTypes:["temporary"]}}if(d.playready){const b=d.playready,S=this.drmManager?await this.drmManager.loadCertificate(b):null;p["com.microsoft.playready"]=b.licenseUrl||"",f["com.microsoft.playready"]={videoCapabilities:[{contentType:'video/mp4; codecs="avc1.640028"'}],audioCapabilities:[{contentType:'audio/mp4; codecs="mp4a.40.2"'}],...S?{serverCertificate:S}:{},...(v=d.robustness)!=null&&v.video?{videoRobustness:d.robustness.video}:{},...(y=d.robustness)!=null&&y.audio?{audioRobustness:d.robustness.audio}:{},persistentState:d.persistentState||"optional",distinctiveIdentifier:d.distinctiveIdentifier||"optional",sessionTypes:["temporary"]}}if(d.clearkey){const b=d.clearkey;p["org.w3.clearkey"]=b.licenseUrl||"",f["org.w3.clearkey"]={sessionTypes:["temporary"]}}return{emeEnabled:!0,licenseServers:p,emeConfigurations:f,licenseXhrSetup:(b,S,T,E)=>{var O,M;let x=null,A="";if(T&&T.keySystem&&(T.keySystem.includes("widevine")?(x=d.widevine,A="widevine"):T.keySystem.includes("playready")?(x=d.playready,A="playready"):T.keySystem.includes("clearkey")&&(x=d.clearkey,A="clearkey")),(O=this.controller)==null||O.dispatchEvent("drmlicenserequest",{url:S,challengeSize:E&&E.byteLength||0,system:A||"hls"}),(M=this.drmManager)==null||M.noteLicenseRequest(A||"hls",S),x&&(x.headers&&Object.entries(x.headers).forEach(([I,D])=>{b.setRequestHeader(I,D)}),x.withCredentials&&(b.withCredentials=!0)),x&&x.licenseRequestInterceptor){const I=E instanceof Uint8Array?E.buffer:E;return Promise.resolve(x.licenseRequestInterceptor(I,A)).then(D=>{let N=E;return D instanceof ArrayBuffer?N=new Uint8Array(D):D&&typeof D=="object"&&(D.body instanceof ArrayBuffer?N=new Uint8Array(D.body):D.body&&(N=D.body),D.headers&&Object.entries(D.headers).forEach(([P,C])=>{b.setRequestHeader(P,C)})),N})}},licenseResponseCallback:(b,S,T)=>{var M,I;let E=null,x="";T&&T.keySystem&&(T.keySystem.includes("widevine")?(E=d.widevine,x="widevine"):T.keySystem.includes("playready")?(E=d.playready,x="playready"):T.keySystem.includes("clearkey")&&(E=d.clearkey,x="clearkey"));const A=b.response,O=A&&(A.byteLength||A.size)||0;if((M=this.controller)==null||M.dispatchEvent("drmlicenseresponse",{url:S,responseSize:O,system:x||"hls"}),(I=this.drmManager)==null||I.noteLicenseResponse(x||"hls",S),E&&E.licenseResponseInterceptor){const D=A instanceof ArrayBuffer?A:A?A.buffer:new ArrayBuffer(0);return Promise.resolve(E.licenseResponseInterceptor(D,x))}return A}}})().then(f=>{if(this.controller!==i)return;const p=new r({enableWorker:!0,lowLatencyMode:!0,liveSyncDurationCount:3,liveMaxLatencyDurationCount:o?10:void 0,...f});this.hls=p,p.attachMedia(t),p.on(r.Events.MEDIA_ATTACHED,()=>{p.loadSource(e.src)}),p.on(r.Events.LEVEL_LOADED,(g,m)=>{if(this.controller!==i||this.hls!==p)return;this.hlsRetryCount=0,this.mediaRecoveryCount=0;const v=m.details;if(v){const y=v.live,b=v.partTarget!==void 0&&v.partTarget>0,S=v.partHoldBack!==void 0&&v.partHoldBack>0,T=v.fragments&&v.fragments.some(I=>I.parts&&I.parts.length>0),E=y&&(b||S||T),x=y?v.totalduration:0,A=y&&(v.type==="EVENT"||x>30);this._isLive=y,this._isLowLatency=E,this._dvrWindow=x,this._hasDvr=A;const O=i.getState(),M={};O.isLive!==y&&(M.isLive=y,y&&(M.isAtLiveEdge=!0)),O.isLowLatency!==E&&(M.isLowLatency=E),Object.keys(M).length>0&&i.updateStatePublic(M),i.dispatchEvent("live-status-change",{isLive:y,isLowLatency:E}),y?(i.updateLiveState(),this.startLivePolling()):this.stopLivePolling()}}),p.on(r.Events.MANIFEST_PARSED,()=>{i.dispatchEvent("manifestloaded",{system:"hls",levels:p.levels.length}),this.hlsRetryCount=0,this.mediaRecoveryCount=0;const g=p.levels.length>1,m=[];if(g){m.push("Auto");const y={};p.levels.forEach(b=>{const S=b.height?`${b.height}p`:"Unknown";y[S]=(y[S]||0)+1}),p.levels.forEach(b=>{const S=b.height?`${b.height}p`:"Unknown";y[S]>1&&b.bitrate?m.push(`${S} (${Math.round(b.bitrate/1e3)}k)`):m.push(S)})}const v=p.subtitleTracks.map(y=>({label:y.name||y.lang||"Unknown",language:y.lang||"",default:!!y.default,forced:!!y.forced,kind:y.type==="CLOSED-CAPTIONS"?"captions":"subtitles"}));i.setManagedSubtitleTracks("hls",v,p.subtitleTrack),i.updateStatePublic({qualities:m,activeQuality:g?"Auto":"",error:null}),this.syncAndDeduplicateTracks(),g&&this.syncQualityState()}),p.on(r.Events.SUBTITLE_TRACK_SWITCH,(g,m)=>{const v=p.subtitleTracks.map(y=>({label:y.name||y.lang||"Unknown",language:y.lang||"",default:!!y.default,forced:!!y.forced,kind:y.type==="CLOSED-CAPTIONS"?"captions":"subtitles"}));i.setManagedSubtitleTracks("hls",v,m.id)}),p.on(r.Events.SUBTITLE_TRACKS_UPDATED,()=>{const g=p.subtitleTracks.map(m=>({label:m.name||m.lang||"Unknown",language:m.lang||"",default:!!m.default,forced:!!m.forced,kind:m.type==="CLOSED-CAPTIONS"?"captions":"subtitles"}));i.setManagedSubtitleTracks("hls",g,p.subtitleTrack)}),p.on(r.Events.LEVEL_SWITCHED,(g,m)=>{this.lastLevelIndex=m.level,this.syncQualityState()}),p.on(r.Events.AUDIO_TRACKS_UPDATED,()=>{this.syncAndDeduplicateTracks()}),p.on(r.Events.AUDIO_TRACK_SWITCHED,(g,m)=>{const v=typeof m.id=="number"&&m.id>=0&&m.id<p.audioTracks.length?m.id:p.audioTrack;let y=-1;for(let b=0;b<this.uniqueAudioTracks.length;b++)if(this.uniqueAudioTracks[b].rawIndices.includes(v)){y=b;break}y!==-1&&i.updateStatePublic({activeAudioTrack:y})}),p.on(r.Events.FRAG_PARSING_METADATA,(g,m)=>{if(!this.controller)return;const v=m.samples||[];for(const y of v){const b=y.pts,S=y.type||"ID3";this.controller.emit("metadata",{timestamp:b,type:S,sourceProtocol:"hls",rawData:y.data,parsedData:y.info||{}})}}),p.on(r.Events.ERROR,(g,m)=>{var v,y,b;if(m.fatal){const S=(v=m.response)==null?void 0:v.code;switch(m.type){case r.ErrorTypes.KEY_SYSTEM_ERROR:console.error("Fatal HLS DRM key system error:",m),i.updateStatePublic({error:`DRM: Key system decryption error: ${m.details||"unknown"}`}),(y=this.drmManager)==null||y.triggerDrmError(m.details||"Key system decryption error","key-system",m),this.destroy();break;case r.ErrorTypes.NETWORK_ERROR:if(m.details==="keyLoadError"&&(S===401||S===403)){console.error(`[HlsHandler] Non-recoverable DRM key load error (HTTP ${S})`);const T="Media license acquisition request was denied.";i.updateStatePublic({error:T}),(b=this.drmManager)==null||b.triggerDrmError(T,"license",m),this.destroy();return}if(this.hlsRetryCount<3){this.hlsRetryCount++;const T=Math.pow(2,this.hlsRetryCount)*1e3;console.warn(`HLS Network error encountered (detail: ${m.details}, HTTP: ${S??"N/A"}). Retrying in ${T}ms (${this.hlsRetryCount}/3)...`),setTimeout(()=>{!this.hls||this.hls!==p||(m.details==="manifestLoadError"||m.details==="manifestLoadTimeOut"||m.details==="manifestParsingError"?p.loadSource(e.src):p.startLoad())},T)}else{console.error(`Fatal HLS Network error. Retries exhausted. Detail: ${m.details}, HTTP: ${S??"N/A"}`);let T;m.details==="manifestLoadError"?S===404?T="Stream not found (404). The URL may be expired, moved, or invalid.":S===403?T="Access denied (403). The stream may be geo-restricted or require authentication.":S!==void 0&&S>=500?T=`Stream server error (${S}). The server is temporarily unavailable.`:T=`Failed to load stream manifest${S?` (HTTP ${S})`:""}. Check the URL and try again.`:m.details==="manifestLoadTimeOut"?T="Stream connection timed out. The server may be slow or unreachable.":m.details==="manifestParsingError"?T="Invalid stream format. The URL does not point to a valid HLS stream.":T="Fatal streaming connection failure. Check the URL and try again.",i.updateStatePublic({error:T}),this.destroy()}break;case r.ErrorTypes.MEDIA_ERROR:this.mediaRecoveryCount++,this.mediaRecoveryCount===1?(console.warn(`HLS Media error. Stage 1 Recovery: recoverMediaError() (${this.mediaRecoveryCount}/3)`),p.recoverMediaError()):this.mediaRecoveryCount===2?(console.warn(`HLS Media error. Stage 2 Recovery: swapAudioCodec() + recoverMediaError() (${this.mediaRecoveryCount}/3)`),p.swapAudioCodec(),p.recoverMediaError()):this.mediaRecoveryCount===3?(console.warn(`HLS Media error. Stage 3 Recovery: detachMedia() + attachMedia() (${this.mediaRecoveryCount}/3)`),p.detachMedia(),p.attachMedia(this.video)):(console.error("Fatal HLS Media decode error. Stage 3 Recovery exhausted."),i.updateStatePublic({error:"Fatal media decoding failure."}),this.destroy());break;default:console.error("Fatal HLS error, destroying streaming instance:",m),i.updateStatePublic({error:"Fatal video stream initialization crash."}),this.destroy();break}}})}).catch(f=>{console.error("[HlsHandler] DRM setup failed:",f),i.updateStatePublic({error:"Fatal DRM initialization failure."})})}else if(t.canPlayType("application/vnd.apple.mpegurl")){const l={...((n=i.config)==null?void 0:n.drm)||{},...e.drm||{}};Object.keys(l).length>0&&(this.drmManager=new De,this.drmManager.load(t,l,i,!1)),t.src=e.src,t.load()}else i.updateStatePublic({error:"HLS streaming is not supported by your browser."})}).catch(s=>{console.error("Failed to load hls.js:",s),i.updateStatePublic({error:"Failed to load HLS library."})}))}syncAndDeduplicateTracks(){if(!this.hls||!this.controller)return;const e=this.hls.audioTracks||[],t={},i=[];for(let n=0;n<e.length;n++){const l=e[n],o=js(l.name,l.lang);t[o]||(t[o]={label:o,rawIndices:[]},i.push(o)),t[o].rawIndices.push(n)}this.uniqueAudioTracks=i.map(n=>({label:n,rawIndices:t[n].rawIndices}));const s=this.uniqueAudioTracks.map(n=>n.label),r=this.hls.audioTrack;let a=-1;for(let n=0;n<this.uniqueAudioTracks.length;n++)if(this.uniqueAudioTracks[n].rawIndices.includes(r)){a=n;break}this.controller.updateStatePublic({audioTracks:s,activeAudioTrack:a>=0?a:0})}syncQualityState(){if(!this.hls||!this.controller)return;const e=this.controller.getState().qualities;if(e.length===0)return;const t=this.isAutoMode;let i="Auto",s=-1;this.lastLevelIndex>=0&&this.lastLevelIndex<this.hls.levels.length?s=this.lastLevelIndex:this.hls.currentLevel>=0&&this.hls.currentLevel<this.hls.levels.length&&(s=this.hls.currentLevel),s>=0&&s<this.hls.levels.length&&(i=e[s+1]||"Unknown");const r=t?i!=="Auto"?`Auto (${i})`:"Auto":i;this.controller.updateStatePublic({activeQuality:r})}destroy(){this.stopLivePolling(),this.hls&&(this.hls.destroy(),this.hls=null),this.drmManager&&(this.drmManager.destroy(),this.drmManager=null),this.controller=null,this.video=null,this.lastLevelIndex=-1,this.isAutoMode=!0,this.uniqueAudioTracks=[]}setQuality(e){if(this.hls){this.isAutoMode=e===0;const t=e-1;this.hls.nextLevel=t,t===-1?this.lastLevelIndex=-1:this.lastLevelIndex=t,this.syncQualityState()}}setAudioTrack(e){if(this.hls&&this.uniqueAudioTracks&&e>=0&&e<this.uniqueAudioTracks.length){const i=this.uniqueAudioTracks[e].rawIndices[0];this.hls.audioTrack=i}}setSubtitleTrack(e){this.hls&&(this.hls.subtitleTrack=e)}getStats(){if(!this.hls)return{};const e={};this.hls.bandwidthEstimate!==void 0&&(e.bandwidthEstimate=this.hls.bandwidthEstimate);const t=this.hls.currentLevel;return t>=0&&this.hls.levels&&this.hls.levels[t]&&(e.bitrate=this.hls.levels[t].bitrate),e}}class Xs{constructor(){this.player=null,this.controller=null,this.video=null,this.lastQualityIndex=-1,this.isAutoMode=!0,this.videoRepresentations=[],this.uniqueAudioTracks=[],this.managesSubtitles=!0,this.dashRetryCount=0,this.eventNames={},this.drmManager=null,this.followingLive=!0,this.catchupEnabled=null,this.syncLiveCatchup=()=>{if(!(!this.player||!this.controller))try{if(!this.player.isDynamic())return;const e=this.controller.getState().liveMode==="live-only"||this.followingLive&&Vt(this.player);if(e===this.catchupEnabled)return;this.catchupEnabled=e,this.player.updateSettings({streaming:{liveCatchup:{enabled:e}}})}catch{}},this.handleResume=()=>{this.video&&this.recordViewerPosition(this.video.currentTime)},this.handleLiveEdgeSync=()=>{this.followingLive=!0,this.syncLiveCatchup()},this.handleTrackChangeRendered=e=>{if(!(!this.player||!this.controller)&&e.mediaType==="audio"){const t=this.player.getCurrentTrackFor("audio");if(t){let i=-1;for(let s=0;s<this.uniqueAudioTracks.length;s++)if(this.uniqueAudioTracks[s].rawTracks.some(a=>a===t||a.id===t.id||a.lang===t.lang&&a.index===t.index)){i=s;break}i!==-1&&this.controller.updateStatePublic({activeAudioTrack:i})}}},this.handleStreamInitialized=()=>{if(!this.player||!this.controller)return;this.dashRetryCount=0;const e=this.player.getRepresentationsByType?this.player.getRepresentationsByType("video"):[];this.videoRepresentations=e;const t=e.length>1,i=[];if(t){i.push("Auto");const o={};e.forEach(d=>{const h=d.bandwidth||d.bitrate||0,u=d.height?`${d.height}p`:`${Math.round(h/1e3)}kbps`;o[u]=(o[u]||0)+1}),e.forEach(d=>{const h=d.bandwidth||d.bitrate||0,u=d.height?`${d.height}p`:`${Math.round(h/1e3)}kbps`;o[u]>1&&h?i.push(`${u} (${Math.round(h/1e3)}k)`):i.push(u)})}const r=this.player.getTracksFor("text").map(o=>{const d=o,h=d.roles?d.roles.map(u=>typeof u=="string"?u:u.value||"").filter(Boolean):[];return{label:d.label||d.lang||"Unknown",language:d.lang||"",default:!!d.isDefault||!!d.default,forced:!1,kind:h.includes("caption")?"captions":"subtitles"}}),a=this.player.getCurrentTrackFor("text");this.controller.setManagedSubtitleTracks("dash",r,a&&a.index!==null?a.index:-1);const n=this.player.isDynamic(),l=n&&Vt(this.player);this.controller.updateStatePublic({qualities:i,activeQuality:t?"Auto":"",error:null,isLive:n,isLowLatency:l,...n?{isAtLiveEdge:!0}:{}}),this.controller.dispatchEvent("live-status-change",{isLive:n,isLowLatency:l}),n&&this.controller.updateLiveState(),this.syncAndDeduplicateTracks(),t&&this.syncQualityState()},this.handleQualityChangeRendered=e=>{if(this.player&&e.mediaType==="video"){if(this.isAutoMode)this.lastQualityIndex=-1;else{const t=this.resolveCurrentRepresentationIndex();if(t>=0)this.lastQualityIndex=t;else{const i=this.normalizeQualityIndex(e==null?void 0:e.newQuality);i>=0&&(this.lastQualityIndex=i)}}this.syncQualityState()}},this.handleTextTrackChanged=()=>{if(!this.player||!this.controller)return;const t=this.player.getTracksFor("text").map(s=>{const r=s,a=r.roles?r.roles.map(n=>typeof n=="string"?n:n.value||"").filter(Boolean):[];return{label:r.label||r.lang||"Unknown",language:r.lang||"",default:!!r.isDefault||!!r.default,forced:!1,kind:a.includes("caption")?"captions":"subtitles"}}),i=this.player.getCurrentTrackFor("text");this.controller.setManagedSubtitleTracks("dash",t,i&&i.index!==null?i.index:-1)},this.handleKeySystemSelected=e=>{},this.handleKeySessionCreated=e=>{const t=e.session;t&&this.drmManager&&this.drmManager.registerSession(t)},this.handleKeySessionClosed=e=>{const t=e.session;t&&this.drmManager&&this.drmManager.unregisterSession(t),this.controller&&t&&this.controller.dispatchEvent("drmsessionclosed",{session:t,system:"unknown"})},this.handleKeySessionRemoved=e=>{const t=e.session;t&&this.drmManager&&this.drmManager.unregisterSession(t),this.controller&&t&&this.controller.dispatchEvent("drmsessionclosed",{session:t,system:"unknown"})},this.handleKeyStatusesChanged=e=>{const t=e.session;this.controller&&t&&t.keyStatuses.forEach((i,s)=>{var r,a;i==="output-restricted"?(r=this.drmManager)==null||r.triggerDrmError("Playback restricted by HDCP output requirements.","certificate"):i==="expired"&&((a=this.drmManager)==null||a.triggerDrmError("Playback key has expired.","certificate"))})},this.handleKeyMessage=e=>{},this.handleProtectionError=e=>{console.error("[DashHandler] Protection Error:",e);const t=e.error,i=(typeof t=="object"?t==null?void 0:t.message:void 0)||(typeof t=="string"?t:void 0)||"Unknown protection error";let s="session";i.toLowerCase().includes("key system")||i.toLowerCase().includes("keysystem")?s="key-system":i.toLowerCase().includes("license")||i.toLowerCase().includes("request")?s="license":i.toLowerCase().includes("certificate")&&(s="certificate"),this.drmManager?this.drmManager.triggerDrmError(i,s,e):this.controller&&(this.controller.updateStatePublic({error:`DRM: ${i}`}),this.controller.dispatchEvent("error",{message:`DRM: ${i}`}),this.controller.dispatchEvent("drmerror",{message:`DRM: ${i}`,errorType:s,originalError:e}))},this.handleError=e=>{var l,o,d;if(!this.player||!this.controller||!this.video)return;console.error("Dash.js error:",e);const t=e.error,i=typeof t=="object"?t:void 0,s=(i==null?void 0:i.message)||(typeof t=="string"?t:"")||"",r=((o=(l=i==null?void 0:i.data)==null?void 0:l.response)==null?void 0:o.status)??((d=i==null?void 0:i.data)==null?void 0:d.status)??(i==null?void 0:i.status)??void 0,a=r===401||r===403,n=s.toLowerCase().includes("key system")||s.toLowerCase().includes("keysystem");if(a||n){console.error(`[DashHandler] Non-recoverable DASH DRM error: ${s} (HTTP: ${r??"N/A"})`);const h=a?"Media license acquisition request was denied.":"DRM key system is not supported by your browser.";this.controller.updateStatePublic({error:h}),this.controller.dispatchEvent("error",{message:h});return}if(this.dashRetryCount<3){this.dashRetryCount++;const h=this.video.currentTime,u=!this.video.paused,f=this.player.getSource(),p=Math.pow(2,this.dashRetryCount)*1e3;console.warn(`DASH error encountered. Retrying in ${p}ms (${this.dashRetryCount}/3) by re-attaching source...`),setTimeout(()=>{if(!(!this.player||!this.video))try{this.player.attachSource(f);const g=()=>{this.player&&(this.player.off(this.eventNames.streamInitialized||"streamInitialized",g),this.video&&(this.video.currentTime=h,u&&this.video.play().catch(m=>console.warn("Restore play failed:",m))))};this.player.on(this.eventNames.streamInitialized||"streamInitialized",g)}catch(g){console.error("Failed to attach source for recovery:",g)}},p)}else this.controller.updateStatePublic({error:`DASH streaming error: ${(i==null?void 0:i.message)||t||"unknown"}`})}}getDrmManager(){return this.drmManager}getRawLiveInfo(){var n,l,o,d,h,u,f;if(!this.player||!this.player.isDynamic())return null;const e=this.player.getSettings(),t=Vt(this.player),i=((l=(n=e==null?void 0:e.streaming)==null?void 0:n.delay)==null?void 0:l.liveDelay)||3;let s=null,r=0;if(this.video&&this.video.seekable.length>0){const p=this.video.seekable.start(0),g=this.video.seekable.end(this.video.seekable.length-1);s=Math.max(0,g-i),r=g-p}let a=!0;try{r<=15&&(a=!1);const p=(d=(o=this.player).getDashAdapter)==null?void 0:d.call(o),g=((h=p==null?void 0:p.getMpd)==null?void 0:h.call(p))||((f=(u=this.player).getMpd)==null?void 0:f.call(u));g&&g.timeShiftBufferDepth!==void 0&&(a=g.timeShiftBufferDepth>10)}catch{a=r>10}return{isLive:!0,isLowLatency:t,hasDvr:a,dvrWindow:r,liveEdgeTarget:s}}seekToLiveEdge(){var e,t;if(this.player&&typeof this.player.seekToOriginalLive=="function")this.player.seekToOriginalLive();else if(this.player&&this.player.isDynamic())if(this.video&&this.video.seekable.length>0){const i=this.video.seekable.end(this.video.seekable.length-1),s=this.player.getSettings(),r=((t=(e=s==null?void 0:s.streaming)==null?void 0:e.delay)==null?void 0:t.liveDelay)||3;this.player.seek(Math.max(0,i-r))}else Number.isFinite(this.player.duration())&&this.player.seek(this.player.duration())}recordViewerPosition(e){var t;if(this.player)try{if(!this.player.isDynamic())return;const i=(t=this.getRawLiveInfo())==null?void 0:t.liveEdgeTarget;if(i==null||e<=0)return;this.followingLive=i-e<=Ws,this.syncLiveCatchup()}catch{}}normalizeQualityIndex(e){return typeof e=="number"&&Number.isInteger(e)&&e>=0?e:-1}resolveCurrentRepresentationIndex(){if(!this.player||this.videoRepresentations.length===0)return-1;const e=this.player.getCurrentRepresentationForType("video");return e?this.videoRepresentations.findIndex(t=>t.id===e.id):-1}bufferToHex(e){const t=new DataView(e);let i="";for(let s=0;s<t.byteLength;s++){const r=t.getUint8(s);i+=r.toString(16).padStart(2,"0")}return i}load(e,t,i){e.src&&(this.destroy(),this.controller=i,this.video=t,this.lastQualityIndex=-1,this.isAutoMode=!0,this.videoRepresentations=[],this.uniqueAudioTracks=[],this.dashRetryCount=0,this.followingLive=!0,this.catchupEnabled=null,t.addEventListener("play",this.handleResume),t.addEventListener("timeupdate",this.syncLiveCatchup),i.addEventListener("live-edge-sync",this.handleLiveEdgeSync),$i().then(s=>{var p;if(this.controller!==i)return;const r=s,a=r.MediaPlayer().create();this.player=a,a.on(r.MediaPlayer.events.MANIFEST_LOADED,g=>{const m=g.data;i.dispatchEvent("manifestloaded",{system:"dash",data:m!=null&&m.url?{url:m.url}:{}})});const l=i.getState().liveMode==="live-only",o={...((p=i.config)==null?void 0:p.drm)||{},...e.drm||{}},d=Object.keys(o).length>0;d&&(this.drmManager=new De,this.drmManager.load(t,o,i,!0));const h={},u={};o.persistentState&&(u.persistentState=o.persistentState),o.distinctiveIdentifier&&(u.distinctiveIdentifier=o.distinctiveIdentifier),a.updateSettings({streaming:{buffer:{fastSwitchEnabled:!0},liveCatchup:{enabled:l},...Object.keys(u).length>0?{protection:u}:{}}}),(async()=>{var g,m,v,y;if(d){if(o.widevine){const b=o.widevine,S=this.drmManager?await this.drmManager.loadCertificate(b):null;h["com.widevine.alpha"]={serverURL:b.licenseUrl,httpRequestHeaders:b.headers,withCredentials:!!b.withCredentials,...S?{serverCertificate:S}:{},...(g=o.robustness)!=null&&g.video?{videoRobustness:o.robustness.video}:{},...(m=o.robustness)!=null&&m.audio?{audioRobustness:o.robustness.audio}:{}}}if(o.playready){const b=o.playready,S=this.drmManager?await this.drmManager.loadCertificate(b):null;h["com.microsoft.playready"]={serverURL:b.licenseUrl,httpRequestHeaders:b.headers,withCredentials:!!b.withCredentials,...S?{serverCertificate:S}:{},...(v=o.robustness)!=null&&v.video?{videoRobustness:o.robustness.video}:{},...(y=o.robustness)!=null&&y.audio?{audioRobustness:o.robustness.audio}:{}}}if(o.clearkey){const b=o.clearkey,S=Ot(b.clearkeys);h["org.w3.clearkey"]={serverURL:b.licenseUrl,httpRequestHeaders:b.headers,withCredentials:!!b.withCredentials,...Object.keys(S).length>0?{clearkeys:S}:{}}}}})().then(()=>{if(this.controller!==i||!this.player)return;if(Object.keys(h).length>0&&this.player.setProtectionData(h),d){const N=C=>{var H,de;let R=null,q="";const te=C.url||"",V=te.toLowerCase();o.widevine&&o.widevine.licenseUrl&&V.includes(o.widevine.licenseUrl.toLowerCase())?(R=o.widevine,q="widevine"):o.playready&&o.playready.licenseUrl&&V.includes(o.playready.licenseUrl.toLowerCase())?(R=o.playready,q="playready"):o.clearkey&&o.clearkey.licenseUrl&&V.includes(o.clearkey.licenseUrl.toLowerCase())&&(R=o.clearkey,q="clearkey");const U=C.data&&(C.data.byteLength||C.data.length)||0;if((H=this.controller)==null||H.dispatchEvent("drmlicenserequest",{url:te,challengeSize:U,system:q||"dash"}),(de=this.drmManager)==null||de.noteLicenseRequest(q||"dash",te),!R||!R.licenseRequestInterceptor)return Promise.resolve();const L=C.data,$=L instanceof Uint8Array?L.buffer:L;return Promise.resolve(R.licenseRequestInterceptor($,q)).then(le=>{le instanceof ArrayBuffer?C.data=le:le&&typeof le=="object"&&(le.body&&(C.data=le.body),le.headers&&(C.headers={...C.headers,...le.headers}))})},P=C=>{var H,de;let R=null,q="";const te=C.url||"",V=te.toLowerCase();o.widevine&&o.widevine.licenseUrl&&V.includes(o.widevine.licenseUrl.toLowerCase())?(R=o.widevine,q="widevine"):o.playready&&o.playready.licenseUrl&&V.includes(o.playready.licenseUrl.toLowerCase())?(R=o.playready,q="playready"):o.clearkey&&o.clearkey.licenseUrl&&V.includes(o.clearkey.licenseUrl.toLowerCase())&&(R=o.clearkey,q="clearkey");const U=C.data&&(C.data.byteLength||C.data.length)||0;if((H=this.controller)==null||H.dispatchEvent("drmlicenseresponse",{url:te,responseSize:U,system:q||"dash"}),(de=this.drmManager)==null||de.noteLicenseResponse(q||"dash",te),!R||!R.licenseResponseInterceptor)return Promise.resolve();const L=C.data,$=L instanceof Uint8Array?L.buffer:L;return Promise.resolve(R.licenseResponseInterceptor($,q)).then(le=>{le instanceof ArrayBuffer&&(C.data=le)})};this.player.registerLicenseRequestFilter(N),this.player.registerLicenseResponseFilter(P)}this.player.initialize(t,e.src,t.autoplay);const g=r.MediaPlayer&&r.MediaPlayer.events||{},m=g.STREAM_INITIALIZED||"streamInitialized",v=g.QUALITY_CHANGE_RENDERED||"qualityChangeRendered",y=g.TEXT_TRACK_CHANGED||"textTrackChanged",b=g.ERROR||"error",S=g.TRACK_CHANGE_RENDERED||"trackChangeRendered",T=g.EVENT_MODE_ON_RECEIVE||"eventModeOnReceive",E=g.KEY_SYSTEM_SELECTED||"keySystemSelected",x=g.KEY_SESSION_CREATED||"keySessionCreated",A=g.KEY_SESSION_CLOSED||"keySessionClosed",O=g.KEY_SESSION_REMOVED||"keySessionRemoved",M=g.KEY_STATUSES_CHANGED||"keyStatusesChanged",I=g.KEY_MESSAGE||"keyMessage",D=g.PROTECTION_ERROR||"protectionError";this.eventNames={streamInitialized:m,qualityChangeRendered:v,textTrackChanged:y,error:b,trackChangeRendered:S,eventModeOnReceive:T,keySystemSelected:E,keySessionCreated:x,keySessionClosed:A,keySessionRemoved:O,keyStatusesChanged:M,keyMessage:I,protectionError:D},a.on(S,this.handleTrackChangeRendered),a.on(m,this.handleStreamInitialized),a.on(v,this.handleQualityChangeRendered),a.on(y,this.handleTextTrackChanged),a.on(b,this.handleError),a.on(E,this.handleKeySystemSelected),a.on(x,this.handleKeySessionCreated),a.on(A,this.handleKeySessionClosed),a.on(O,this.handleKeySessionRemoved),a.on(M,this.handleKeyStatusesChanged),a.on(I,this.handleKeyMessage),a.on(D,this.handleProtectionError),a.on(T,N=>{if(!i)return;const P=N.event;P&&i.emit("metadata",{timestamp:P.presentationTime||0,type:P.schemeIdUri||"emsg",sourceProtocol:"dash",rawData:P.messageData||new Uint8Array,parsedData:{schemeIdUri:P.schemeIdUri,value:P.value,timescale:P.timescale,presentationTime:P.presentationTime,duration:P.duration,id:P.id}})})}).catch(g=>{console.error("[DashHandler] Dynamic DRM setup failed:",g),this.handleProtectionError(g)})}).catch(s=>{console.error("Failed to load dashjs:",s),i.updateStatePublic({error:"Failed to load DASH library."})}))}syncAndDeduplicateTracks(){var n,l,o;if(!this.player||!this.controller)return;const e=this.player.getTracksFor("audio")||[],t={},i=[];for(let d=0;d<e.length;d++){const h=e[d],u=h.lang||"";let f="";h.labels&&Array.isArray(h.labels)&&h.labels.length>0&&((n=h.labels[0])!=null&&n.text)?f=h.labels[0].text:"label"in h&&typeof h.label=="string"&&(f=h.label);const p=h.roles?h.roles.map(E=>typeof E=="string"?E:E.value||"").filter(Boolean):[],g=p.map(E=>E.trim().toLowerCase()).filter(E=>E!=="main"&&E!=="alternate"&&E!==""),m=((o=(l=h.audioChannelConfiguration)==null?void 0:l[0])==null?void 0:o.value)||h.channels||"",v=u.toLowerCase(),y=f.toLowerCase(),b=g.sort().join(","),S=m?String(m):"",T=`${v}|${y}|${b}|${S}`;t[T]||(t[T]={lang:u,label:f||void 0,roles:p,channels:m||void 0,rawTracks:[]},i.push(T)),t[T].rawTracks.push(h)}this.uniqueAudioTracks=i.map(d=>{const h=t[d],u=mt(h.lang);let f="";h.label&&(/^[a-zA-Z]{2,3}(-[a-zA-Z]{2,4})?$/.test(h.label.trim())||(f=h.label.trim()));const p=[f||u||"Unknown"],g=h.roles.map(v=>v.trim().toLowerCase()).filter(v=>v!=="main"&&v!=="alternate"&&v!=="");if(g.length>0&&p.push(g.map(v=>v.charAt(0).toUpperCase()+v.slice(1)).join(", ")),h.channels){const v=parseInt(String(h.channels),10);v===2?p.push("Stereo"):v===6||v===5.1?p.push("5.1"):v>0&&p.push(`${v}ch`)}return{label:p.join(" "),rawTracks:h.rawTracks}});const s=this.uniqueAudioTracks.map(d=>d.label),r=this.player.getCurrentTrackFor("audio");let a=-1;if(r){for(let d=0;d<this.uniqueAudioTracks.length;d++)if(this.uniqueAudioTracks[d].rawTracks.some(u=>u===r||u.id===r.id||u.lang===r.lang&&u.index===r.index)){a=d;break}}a===-1&&this.uniqueAudioTracks.length>0&&(a=0),this.controller.updateStatePublic({audioTracks:s,activeAudioTrack:a})}syncQualityState(){if(!this.player||!this.controller)return;const e=this.controller.getState().qualities;if(e.length===0)return;const t=this.isAutoMode;let i="Auto",s=this.normalizeQualityIndex(this.lastQualityIndex);s===-1&&(s=this.resolveCurrentRepresentationIndex()),s>=0&&s<e.length-1&&(i=e[s+1]||"Unknown");const r=t?i!=="Auto"?`Auto (${i})`:"Auto":i;this.controller.updateStatePublic({activeQuality:r})}destroy(){var e;if(this.video&&(this.video.removeEventListener("play",this.handleResume),this.video.removeEventListener("timeupdate",this.syncLiveCatchup)),(e=this.controller)==null||e.removeEventListener("live-edge-sync",this.handleLiveEdgeSync),this.player){try{this.eventNames.trackChangeRendered&&this.player.off(this.eventNames.trackChangeRendered,this.handleTrackChangeRendered),this.eventNames.streamInitialized&&this.player.off(this.eventNames.streamInitialized,this.handleStreamInitialized),this.eventNames.qualityChangeRendered&&this.player.off(this.eventNames.qualityChangeRendered,this.handleQualityChangeRendered),this.eventNames.textTrackChanged&&this.player.off(this.eventNames.textTrackChanged,this.handleTextTrackChanged),this.eventNames.error&&this.player.off(this.eventNames.error,this.handleError),this.eventNames.keySystemSelected&&this.player.off(this.eventNames.keySystemSelected,this.handleKeySystemSelected),this.eventNames.keySessionCreated&&this.player.off(this.eventNames.keySessionCreated,this.handleKeySessionCreated),this.eventNames.keySessionClosed&&this.player.off(this.eventNames.keySessionClosed,this.handleKeySessionClosed),this.eventNames.keySessionRemoved&&this.player.off(this.eventNames.keySessionRemoved,this.handleKeySessionRemoved),this.eventNames.keyStatusesChanged&&this.player.off(this.eventNames.keyStatusesChanged,this.handleKeyStatusesChanged),this.eventNames.keyMessage&&this.player.off(this.eventNames.keyMessage,this.handleKeyMessage),this.eventNames.protectionError&&this.player.off(this.eventNames.protectionError,this.handleProtectionError)}catch(t){console.warn("[DashHandler] Error unbinding event listeners:",t)}this.player.destroy(),this.player=null}this.drmManager&&(this.drmManager.destroy(),this.drmManager=null),this.controller=null,this.video=null,this.lastQualityIndex=-1,this.isAutoMode=!0,this.videoRepresentations=[],this.uniqueAudioTracks=[]}seek(e){if(this.recordViewerPosition(e),!this.player)return!1;try{return this.player.isDynamic()?(this.player.seekToPresentationTime(e),!0):!1}catch{return!1}}setQuality(e){if(this.player){this.isAutoMode=e===0;const t=e-1,i=this.player;if(t===-1)i.setAutoSwitchQualityFor?i.setAutoSwitchQualityFor("video",!0):this.player.updateSettings({streaming:{abr:{autoSwitchBitrate:{video:!0}}}}),this.lastQualityIndex=-1;else if(i.setAutoSwitchQualityFor?i.setAutoSwitchQualityFor("video",!1):this.player.updateSettings({streaming:{abr:{autoSwitchBitrate:{video:!1}}}}),t>=0&&t<this.videoRepresentations.length){const s=this.videoRepresentations[t];i.setRepresentationForTypeById?i.setRepresentationForTypeById("video",s.id):i.setQualityFor&&i.setQualityFor("video",t,!1),this.lastQualityIndex=t}this.syncQualityState()}}setAudioTrack(e){if(this.player&&this.uniqueAudioTracks&&e>=0&&e<this.uniqueAudioTracks.length){const t=this.uniqueAudioTracks[e],i=this.player.getCurrentTrackFor("audio"),s=t.rawTracks.find(r=>i&&(r.mimeType===i.mimeType||r.codec===i.codec))||t.rawTracks[0];s&&this.player.setCurrentTrack(s)}}setSubtitleTrack(e){if(this.player){const t=this.player.getTracksFor("text");e===-1?this.player.setTextTrack(-1):e>=0&&e<t.length&&this.player.setTextTrack(e)}}getStats(){var t,i,s;if(!this.player)return{};const e={};try{const r=this.player,a=((t=r.getAverageThroughput)==null?void 0:t.call(r,"video"))??0;a>0&&(e.bandwidthEstimate=a*1e3);const n=(i=r.getQualityFor)==null?void 0:i.call(r,"video"),l=(s=r.getBitrateInfoListFor)==null?void 0:s.call(r,"video");l&&n!==void 0&&l[n]&&(e.bitrate=l[n].bitrate)}catch{}return e}}class Ys{constructor(){this.iframe=null,this.video=null,this.controller=null}load(e,t,i){this.destroy(),this.video=t,this.controller=i;const s=e.src||"";if(!s)return;const r=s;t.style.display="none",t.pause();const a=document.createElement("iframe");a.src=r,a.style.position="absolute",a.style.top="0",a.style.left="0",a.style.width="100%",a.style.height="100%",a.style.border="none",a.style.zIndex="10",a.allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share",a.allowFullscreen=!0,this.iframe=a,t.parentNode&&t.parentNode.appendChild(a),i.updateStatePublic({qualities:[],activeQuality:"",audioTracks:[],activeAudioTrack:-1,error:null,status:"playing",isPlaying:!0})}destroy(){this.iframe&&(this.iframe.parentNode&&this.iframe.parentNode.removeChild(this.iframe),this.iframe=null),this.video&&(this.video.style.display="",this.video=null),this.controller=null}}class Zs{constructor(){this.activeHandler=null}getActiveHandler(){return this.activeHandler}getHandler(e){switch(e){case"hls":return new Qs;case"dash":return new Xs;case"embed":return new Ys;case"mp4":case"mov":case"webm":case"file":case"blob":default:return new Gs}}load(e,t,i){this.destroy();const s=e.type||"unknown";this.activeHandler=this.getHandler(s),this.activeHandler.load(e,t,i)}destroy(){this.activeHandler&&(this.activeHandler.destroy(),this.activeHandler=null)}setQuality(e){this.activeHandler&&this.activeHandler.setQuality&&this.activeHandler.setQuality(e)}setAudioTrack(e){this.activeHandler&&this.activeHandler.setAudioTrack&&this.activeHandler.setAudioTrack(e)}setSubtitleTrack(e){this.activeHandler&&this.activeHandler.setSubtitleTrack&&this.activeHandler.setSubtitleTrack(e)}seekToLiveEdge(){return this.activeHandler&&this.activeHandler.seekToLiveEdge?(this.activeHandler.seekToLiveEdge(),!0):!1}getRawLiveInfo(){return this.activeHandler&&this.activeHandler.getRawLiveInfo?this.activeHandler.getRawLiveInfo():null}}class Ni{constructor(e){var i;this.bindings=[],this.actions=new Map,this.hooks=new Set,this.enabled=!0,this.controller=e,this.registerDefaultActions(),this.registerDefaultBindings();const t=(i=this.controller.config)==null?void 0:i.hotkeys;if(t&&typeof t=="object"&&(t.bindings&&this.setMap(t.bindings),t.overrides))for(const s of t.overrides)this.bind(s)}enable(){this.enabled=!0}disable(){this.enabled=!1}isEnabled(){return this.enabled}registerAction(e,t){this.actions.set(e,t)}unregisterAction(e){this.actions.delete(e)}bind(e){this.unbind(e.key,e.shiftKey,e.ctrlKey,e.altKey),this.bindings.push({...e,key:e.key.toLowerCase()})}unbind(e,t=!1,i=!1,s=!1){const r=e.toLowerCase();this.bindings=this.bindings.filter(a=>!(a.key===r&&!!a.shiftKey===t&&!!a.ctrlKey===i&&!!a.altKey===s))}setMap(e){this.bindings=e.map(t=>({...t,key:t.key.toLowerCase()}))}onAction(e){return this.hooks.add(e),()=>this.hooks.delete(e)}handleKeyDown(e){var l,o;if(!this.enabled)return;const t=(l=this.controller.config)==null?void 0:l.hotkeys;if(t===!1||t&&typeof t=="object"&&t.enabled===!1)return;const i=e.key.toLowerCase(),s=e.shiftKey,r=e.ctrlKey,a=e.altKey,n=this.bindings.find(d=>{if(d.key===i){const h=(d.shiftKey||!1)===s,u=(d.ctrlKey||!1)===r,f=(d.altKey||!1)===a;return h&&u&&f}return!1});if(n){if(this.controller.getState().isAdPlaying&&!["playPause","muteToggle","volumeUp","volumeDown","fullscreenToggle"].includes(n.action))return;const d=(o=this.controller.config)==null?void 0:o.controls;if(d&&(n.action==="playPause"&&(d.play===!1||d.playButton===!1)||(n.action==="volumeUp"||n.action==="volumeDown"||n.action==="muteToggle")&&(d.volume===!1||d.mute===!1)||(n.action==="seekBackward10"||n.action==="seekForward10"||n.action==="seekStart"||n.action==="seekEnd"||n.action==="frameBackward"||n.action==="frameForward"||n.action==="seekPercent")&&d.seekbar===!1||n.action==="fullscreenToggle"&&d.fullscreen===!1||n.action==="pipToggle"&&(d.pip===!1||d.pictureInPicture===!1)||(n.action==="speedIncrease"||n.action==="speedDecrease")&&d.playbackSpeed===!1||(n.action==="nextChapter"||n.action==="prevChapter")&&d.chapters===!1))return;const h=this.actions.get(n.action);h&&(e.preventDefault(),e.stopPropagation(),h(this.controller,e,{key:e.key}))}}dispatchHook(e,t){this.hooks.forEach(i=>i(e,t))}registerDefaultActions(){this.registerAction("playPause",e=>{e.togglePlay()}),this.registerAction("seekBackward10",e=>{const t=e.getState();t.isLive&&!t.canSeekInDvr||(e.seekBy(-10),this.dispatchHook("seek",{seconds:-10}))}),this.registerAction("seekForward10",e=>{const t=e.getState();t.isLive&&!t.canSeekInDvr||(e.seekBy(10),this.dispatchHook("seek",{seconds:10}))}),this.registerAction("volumeUp",e=>{const t=e.getState().volume,i=Math.min(1,t+.1);e.setVolume(i),this.dispatchHook("volume",{volume:i,isMuted:e.getState().isMuted})}),this.registerAction("volumeDown",e=>{const t=e.getState().volume,i=Math.max(0,t-.1);e.setVolume(i),this.dispatchHook("volume",{volume:i,isMuted:e.getState().isMuted})}),this.registerAction("muteToggle",e=>{e.toggleMute(),this.dispatchHook("volume",{volume:e.getState().volume,isMuted:e.getState().isMuted})}),this.registerAction("fullscreenToggle",e=>{this.dispatchHook("fullscreen")}),this.registerAction("pipToggle",e=>{e.togglePictureInPicture()}),this.registerAction("loopToggle",e=>{e.toggleLoop()}),this.registerAction("nextChapter",e=>{e.nextChapter()}),this.registerAction("prevChapter",e=>{e.prevChapter()}),this.registerAction("seekStart",e=>{const t=e.getState();if(t.isLive&&!t.canSeekInDvr)return;const i=t.currentTime;e.seek(0),this.dispatchHook("seek",{seconds:-i})}),this.registerAction("seekEnd",e=>{const t=e.getState();if(t.isLive&&!t.canSeekInDvr)return;const i=t.currentTime,s=t.duration;e.seek(s),this.dispatchHook("seek",{seconds:s-i})}),this.registerAction("seekPercent",(e,t,i)=>{var r,a;const s=i==null?void 0:i.key;if(s&&s>="0"&&s<="9"){const n=parseInt(s,10)/10,l=e.getState();if(l.isLive&&!l.canSeekInDvr)return;let o=0;if(l.isLive){const h=((r=l.seekableRange)==null?void 0:r.start)??0,u=((a=l.seekableRange)==null?void 0:a.end)??0;o=h+(u-h)*n}else o=(l.duration||0)*n;const d=l.currentTime;e.seek(o),this.dispatchHook("seek",{seconds:o-d})}}),this.registerAction("frameBackward",e=>{if(!e.isKeyboardPrecisionEnabled())return;const t=e.getState();if(t.isLive&&!t.canSeekInDvr)return;const i=t.currentTime,s=Math.max(0,i-.04);e.seek(s),this.dispatchHook("seek",{seconds:s-i})}),this.registerAction("frameForward",e=>{if(!e.isKeyboardPrecisionEnabled())return;const t=e.getState();if(t.isLive&&!t.canSeekInDvr)return;const i=t.currentTime,s=t.duration||0,r=Math.min(s,i+.04);e.seek(r),this.dispatchHook("seek",{seconds:r-i})}),this.registerAction("speedIncrease",e=>{const t=[.25,.5,.75,1,1.25,1.5,1.75,2,2.5,3,4],i=e.getState().playbackRate,s=t.indexOf(i);s!==-1&&s<t.length-1&&e.setPlaybackRate(t[s+1])}),this.registerAction("speedDecrease",e=>{const t=[.25,.5,.75,1,1.25,1.5,1.75,2,2.5,3,4],i=e.getState().playbackRate,s=t.indexOf(i);s!==-1&&s>0&&e.setPlaybackRate(t[s-1])})}registerDefaultBindings(){this.bind({key:" ",action:"playPause"}),this.bind({key:"k",action:"playPause"}),this.bind({key:"arrowleft",action:"seekBackward10"}),this.bind({key:"arrowright",action:"seekForward10"}),this.bind({key:"j",action:"seekBackward10"}),this.bind({key:"l",action:"seekForward10"}),this.bind({key:"arrowup",action:"volumeUp"}),this.bind({key:"arrowdown",action:"volumeDown"}),this.bind({key:"m",action:"muteToggle"}),this.bind({key:"f",action:"fullscreenToggle"}),this.bind({key:"p",action:"pipToggle"}),this.bind({key:"r",action:"loopToggle"}),this.bind({key:"arrowright",action:"nextChapter",ctrlKey:!0}),this.bind({key:"arrowleft",action:"prevChapter",ctrlKey:!0}),this.bind({key:"home",action:"seekStart"}),this.bind({key:"end",action:"seekEnd"}),this.bind({key:",",action:"frameBackward"}),this.bind({key:".",action:"frameForward"}),this.bind({key:">",action:"speedIncrease",shiftKey:!0}),this.bind({key:"<",action:"speedDecrease",shiftKey:!0});for(let e=0;e<=9;e++)this.bind({key:e.toString(),action:"seekPercent"})}destroy(){this.bindings=[],this.actions.clear(),this.hooks.clear()}}var zt=(c=>(c[c.HANDSHAKE_TIMEOUT=1001]="HANDSHAKE_TIMEOUT",c[c.CREATIVE_LOAD_FAILURE=1002]="CREATIVE_LOAD_FAILURE",c[c.SECURITY_VIOLATION=1003]="SECURITY_VIOLATION",c[c.INVALID_PAYLOAD=1004]="INVALID_PAYLOAD",c[c.CREATIVE_FATAL_ERROR=1005]="CREATIVE_FATAL_ERROR",c[c.RUNTIME_ERROR=1006]="RUNTIME_ERROR",c))(zt||{});class Vi{constructor(e){this.config=e,this.pendingRequests=new Map,this.messageListeners=new Set,this.globalListener=null,this.targetWindow=null,this.sessionId=null,this.messageCounter=0,this.creativeOrigin=null,this.allowedOrigins=new Set(e.allowedOrigins||["*"]),this.debugLogging=e.debug!==!1}init(e,t,i){this.targetWindow=e,this.sessionId=t,this.creativeOrigin=i||null,this.setupGlobalListener()}updateSessionId(e){this.sessionId=e}postMessage(e,t,i){if(!this.targetWindow||!this.sessionId)throw new Error("SIMID Bridge is not initialized or has been destroyed");const s=String(++this.messageCounter),r={sessionId:this.sessionId,messageId:s,timestamp:Date.now(),type:e,args:t};i!==void 0&&(r.correlationId=i);const a=this.allowedOrigins.has("*")||this.allowedOrigins.has("null")?"*":this.creativeOrigin&&this.allowedOrigins.has(this.creativeOrigin)?this.creativeOrigin:Array.from(this.allowedOrigins)[0];return this.debugLogging&&console.log("[SIMID Protocol] 📤 Player -> Creative:",{timestamp:new Date().toISOString(),type:e,messageId:s,correlationId:i,sessionId:this.sessionId,payload:r}),this.targetWindow.postMessage(JSON.stringify(r),a),s}postResolve(e,t={}){const s={messageId:typeof e=="string"&&parseInt(e,10)||e,value:t||{}};return this.postMessage("resolve",s,String(e))}postReject(e,t={}){const s={messageId:typeof e=="string"&&parseInt(e,10)||e,value:t||{}};return this.postMessage("reject",s,String(e))}async sendRequest(e,t,i=5e3){if(!this.targetWindow||!this.sessionId)throw new Error("SIMID Bridge is not initialized or has been destroyed");return new Promise((s,r)=>{const a=this.postMessage(e,t),n=setTimeout(()=>{this.pendingRequests.delete(a),r(new Error(`SIMID request timeout for messageId ${a} (${e})`))},i);this.pendingRequests.set(a,{resolve:s,reject:r,timeoutId:n})})}addMessageListener(e){this.messageListeners.add(e)}removeMessageListener(e){this.messageListeners.delete(e)}setupGlobalListener(){typeof window>"u"||(this.globalListener=e=>{var o,d;if(this.targetWindow&&e.source)try{if(e.source!==this.targetWindow&&this.targetWindow.self!==e.source)return}catch{}if(!this.allowedOrigins.has("*")&&!this.allowedOrigins.has(e.origin))return;let t=e.data;if(typeof t=="string")try{t=JSON.parse(t)}catch{return}if(!t||typeof t!="object"||!t.type)return;const i=t,s=String(i.type),r=s.replace(/^simid:(creative|player|media):/i,"").replace(/^simid:/i,"").toLowerCase(),a=r==="createsession"||r==="creativeready"||r==="creativeloaded"||r==="startcreative"||r==="handshake",n=i.sessionId||((o=i.args)==null?void 0:o.sessionId)||((d=i.data)==null?void 0:d.sessionId)||this.sessionId;if(!a&&this.sessionId&&n!==this.sessionId)return;const l={sessionId:String(n||this.sessionId||""),messageId:String(i.messageId||Math.random().toString(36).substring(2,11)),correlationId:i.correlationId!==void 0?String(i.correlationId):void 0,type:s,data:i.data||i.args||i};if(this.debugLogging&&console.log("[SIMID Protocol] 📥 Creative -> Player:",{timestamp:new Date().toISOString(),type:s,normalizedType:r,messageId:l.messageId,correlationId:l.correlationId,sessionId:l.sessionId,payload:i}),l.correlationId){const h=this.pendingRequests.get(l.correlationId);h&&(clearTimeout(h.timeoutId),this.pendingRequests.delete(l.correlationId),h.resolve(l))}this.messageListeners.forEach(h=>{try{h(l)}catch(u){console.error("[SIMID Bridge] Error in message listener:",u)}})},window.addEventListener("message",this.globalListener))}destroy(){typeof window<"u"&&this.globalListener&&window.removeEventListener("message",this.globalListener),this.globalListener=null,this.pendingRequests.forEach((e,t)=>{clearTimeout(e.timeoutId),e.reject(new Error(`SIMID Bridge destroyed for pending message ${t}`))}),this.pendingRequests.clear(),this.messageListeners.clear(),this.targetWindow=null,this.sessionId=null}}class vt{constructor(e,t,i){this.creative=e,this.config=t,this.onStateChange=i,this.state="idle",this.handshakeTimer=null,this.creativeTimer=null,this.errors=[],this.initMessageId=null,this.sessionId=Math.random().toString(36).substring(2,15),this.config=vt.resolveEffectiveConfig(e,t),this.bridge=new Vi(this.config)}static resolveEffectiveConfig(e,t){if(t.allowedOrigins)return t;if(Ii(e.interactiveCreativeFile))return{...t,allowedOrigins:["null"]};try{const i=new URL(e.interactiveCreativeFile,window.location.href).origin;return{...t,allowedOrigins:[i]}}catch(i){return console.warn("[SimidSession] Could not resolve creative origin for allowedOrigins default; falling back to wildcard.",i),{...t,allowedOrigins:["*"]}}}getSessionState(){return this.state}getBridge(){return this.bridge}getErrors(){return this.errors}init(e,t){if(this.state!=="idle")throw new Error(`Cannot initialize SIMID session in state: ${this.state}`);this.transitionTo("available"),this.bridge.init(e,this.sessionId,t),this.bridge.addMessageListener(this.handleIncomingMessage.bind(this))}start(){if(this.state!=="available")throw new Error(`Cannot start SIMID session in state: ${this.state}`);this.transitionTo("loading");const e=this.config.handshakeTimeoutMs||8e3;this.handshakeTimer=setTimeout(()=>{this.handleError(zt.HANDSHAKE_TIMEOUT,"Handshake timeout expired",!0)},e)}complete(){this.state==="destroyed"||this.state==="completed"||(this.transitionTo("completed"),this.cleanupTimers())}destroy(){this.state!=="destroyed"&&(this.transitionTo("destroyed"),this.cleanupTimers(),this.bridge.destroy())}transitionTo(e){if(this.state=e,this.onStateChange)try{this.onStateChange(e,this)}catch(t){console.error("[SIMID Session] Error in state change handler:",t)}}setInitMessageId(e){this.initMessageId=e}handleIncomingMessage(e){if(this.state==="destroyed"||this.state==="completed")return;const i=String(e.type||"").replace(/^simid:(creative|player|media):/i,"").replace(/^simid:/i,"").toLowerCase(),s=e.data,r=e.args;if((i==="createsession"||i==="handshake")&&(this.state==="loading"||this.state==="available")){this.clearHandshakeTimer();const o=e.sessionId||(s==null?void 0:s.sessionId)||(r==null?void 0:r.sessionId);o&&o!==this.sessionId&&(this.sessionId=String(o),this.bridge.updateSessionId(String(o)));try{const d=e.messageId;d!=null&&this.bridge.postResolve(d,{})}catch{}this.transitionTo("initialized");return}if(i==="resolve"&&this.state==="initialized"){const o=(r==null?void 0:r.messageId)??e.correlationId;(!o||String(o)===String(this.initMessageId)||this.initMessageId===null)&&this.transitionTo("running");return}(i==="creativeready"||i==="creativeloaded")&&(this.state==="loading"||this.state==="available")&&(this.clearHandshakeTimer(),this.transitionTo("initialized"))}handleError(e,t,i){const s={code:e,message:t,fatal:i};this.errors.push(s),i&&this.destroy()}cleanupTimers(){this.clearHandshakeTimer(),this.creativeTimer&&(clearTimeout(this.creativeTimer),this.creativeTimer=null)}clearHandshakeTimer(){this.handshakeTimer&&(clearTimeout(this.handshakeTimer),this.handshakeTimer=null)}}class zi{constructor(e){this.activeSession=null,this.config=e||{handshakeTimeoutMs:8e3,creativeTimeoutMs:1e4,maxDurationExtensionSec:30,allowClickThru:!0};const t=this.detectCapabilities();this.diagnostics={simidAvailable:t.iframeSupported,creativeDetected:!1,sessionCreatedCount:0,bridgeInitSuccess:!1,messagesRoutedCount:0,capabilities:t,errorLog:[]}}getConfig(){return this.config}detectCapabilities(){const e=typeof window<"u";return{simidVersion:"1.0",iframeSupported:e&&typeof document<"u"&&typeof document.createElement=="function",secureMessagingSupported:e&&typeof window.postMessage=="function",postMessageSupported:e&&typeof window.postMessage=="function",clickThruSupported:!0,durationChangeSupported:!0}}hasSimidCreative(e){const t=!!(e&&e.interactiveCreativeFile);return t&&(this.diagnostics.creativeDetected=!0),t}createSession(e){if(!this.hasSimidCreative(e)||!e.interactiveCreativeFile)return null;const t={interactiveCreativeFile:e.interactiveCreativeFile,creativeType:e.contentType||"text/html",creativeParameters:e.creativeParameters||e.adParameters||"",adId:e.id,clickThruUrl:e.clickThroughUrl||e.clickThruUrl||"",clickTrackingUrls:(e.clickTrackingUrls||[]).map(i=>typeof i=="string"?i:i.url).filter(Boolean)};return this.activeSession&&this.activeSession.destroy(),this.activeSession=new vt(t,this.config,i=>{i==="initialized"&&(this.diagnostics.bridgeInitSuccess=!0)}),this.diagnostics.sessionCreatedCount++,this.activeSession}getActiveSession(){return this.activeSession}getPublicSession(){return this.activeSession?{sessionId:this.activeSession.sessionId,state:this.activeSession.getSessionState(),creative:this.activeSession.creative,errors:this.activeSession.getErrors()}:null}getDiagnostics(){return this.activeSession&&this.activeSession.getErrors().forEach(t=>{this.diagnostics.errorLog.some(i=>i.code===t.code&&i.message===t.message)||this.diagnostics.errorLog.push(t)}),this.diagnostics}destroy(){this.activeSession&&(this.activeSession.destroy(),this.activeSession=null)}}class _i{constructor(e){this.iframe=null,this.adContainer=null,this.controller=null,this.handshakeStartTime=0,this.messagesSent=0,this.messagesReceived=0,this.validationFailures=0,this.processedMessageIds=new Set,this.durationCutoffListener=null,this.config=e,this.simidManager=new zi(e)}hasSimidCreative(e){return this.simidManager.hasSimidCreative(e)}async startRuntime(e,t,i){var n,l,o;if(typeof window>"u"||typeof document>"u"||!this.simidManager.hasSimidCreative(e))return!1;const s=this.simidManager.detectCapabilities();if(!s.iframeSupported||!s.postMessageSupported)return!1;this.adContainer=t,this.controller=i,this.destroyRuntime();const r=this.simidManager.createSession(e);if(!r)return!1;const a=r.creative.interactiveCreativeFile;try{this.iframe=this.createIframe(t,a);const d=this.iframe.contentWindow;if(!d)throw new Error("SIMID iframe contentWindow is null");let h;try{h=new URL(a,window.location.href).origin}catch{}r.init(d,h),r.getBridge().addMessageListener(this.handleRuntimeMessage.bind(this)),this.handshakeStartTime=Date.now(),this.emitEvent("simidavailable",{sessionId:r.sessionId}),this.iframe.src=a,await this.waitForIframeLoad(this.iframe),r.getSessionState()==="available"&&r.start();const u=((n=this.config)==null?void 0:n.handshakeTimeoutMs)||8e3;await this.waitForState(r,"initialized",u);const f=Math.round(((l=this.adContainer)==null?void 0:l.offsetWidth)||640),p=Math.round(((o=this.adContainer)==null?void 0:o.offsetHeight)||480),g=i.getState(),v=!!e.skippable?"playerHandles":"notSkippable",y={environmentData:{videoDimensions:{x:0,y:0,width:f,height:p},creativeDimensions:{x:0,y:0,width:f,height:p},fullscreen:!!g.isFullscreen,fullscreenAllowed:!0,variableDurationAllowed:!0,skippableState:v,version:"1.0",muted:!!g.isMuted,volume:g.volume??1},creativeData:{adParameters:e.creativeParameters||e.adParameters||"",clickThruUrl:e.clickThroughUrl||e.clickThruUrl||""}},b=this.sendToCreative(r,"SIMID:Player:init",y);return r.setInitMessageId(b),await this.waitForState(r,"running",u),this.sendToCreative(r,"SIMID:Player:startCreative",{}),this.emitEvent("simidstart",{sessionId:r.sessionId}),this.emitEvent("simidready",{sessionId:r.sessionId}),!0}catch(d){const h=d instanceof Error?d.message:String(d);return console.warn("[SimidRuntime] Startup failed:",h),this.emitEvent("simiderror",{message:h}),this.destroyRuntime(),!1}}destroyRuntime(){this.clearDurationCutoff();const e=this.simidManager.getActiveSession();if(e&&e.getSessionState()==="running")try{this.sendToCreative(e,"SIMID:Player:adStopped",{})}catch{}this.simidManager.destroy(),this.removeIframe(),this.processedMessageIds.clear(),this.controller&&this.emitEvent("simidcomplete",{})}getSimidManager(){return this.simidManager}getRuntimeDiagnostics(){const e=this.simidManager.getDiagnostics(),t=this.simidManager.getActiveSession();return{...e,iframeLoaded:this.iframe!==null,handshakeDurationMs:this.handshakeStartTime?Date.now()-this.handshakeStartTime:0,messagesSent:this.messagesSent,messagesReceived:this.messagesReceived,validationFailures:this.validationFailures,sessionState:(t==null?void 0:t.getSessionState())||null,sessionLifetimeMs:this.handshakeStartTime?Date.now()-this.handshakeStartTime:0}}createIframe(e,t){const i=document.createElement("iframe"),s=Li("allow-scripts allow-same-origin allow-popups allow-forms",{srcUrl:t||null});return i.setAttribute("sandbox",s),i.setAttribute("allow","autoplay; fullscreen"),i.setAttribute("referrerpolicy","no-referrer"),e&&typeof getComputedStyle=="function"&&getComputedStyle(e).position==="static"&&(e.style.position="relative"),i.style.position="absolute",i.style.top="0",i.style.left="0",i.style.width="100%",i.style.height="100%",i.style.border="none",i.style.zIndex="1001",i.style.pointerEvents="auto",i.style.backgroundColor="transparent",e.appendChild(i),i}waitForIframeLoad(e){var i;const t=((i=this.config)==null?void 0:i.creativeTimeoutMs)??1e4;return new Promise((s,r)=>{const a=setTimeout(()=>{r(new Error("SIMID iframe load timeout"))},t);e.addEventListener("load",()=>{clearTimeout(a),s()},{once:!0}),e.addEventListener("error",()=>{clearTimeout(a),r(new Error("SIMID iframe load failed"))},{once:!0})})}removeIframe(){this.iframe&&(this.iframe.src="about:blank",this.iframe.parentNode&&this.iframe.parentNode.removeChild(this.iframe),this.iframe=null)}sendToCreative(e,t,i){const s=e.getBridge().postMessage(t,i);return this.messagesSent++,s}handleRuntimeMessage(e){if(this.messagesReceived++,this.processedMessageIds.has(e.messageId)){this.validationFailures++;return}if(this.processedMessageIds.add(e.messageId),this.processedMessageIds.size>1e3){const r=this.processedMessageIds.values().next().value;r&&this.processedMessageIds.delete(r)}const t=this.simidManager.getActiveSession();if(!t||t.sessionId!==e.sessionId){this.validationFailures++;return}switch(String(e.type||"").replace(/^simid:(creative|player|media):/i,"").replace(/^simid:/i,"").toLowerCase()){case"createsession":case"handshake":case"creativeready":case"creativeloaded":case"resolve":case"reject":break;case"requestclickthru":case"requestclickthrough":this.handleRequestClickThru(t,e);break;case"requestchangeadduration":case"requestchangeduration":this.handleRequestChangeAdDuration(t,e);break;case"requestunmute":this.handleRequestMute(t,e,!1);break;case"requestfatalerror":this.handleRequestFatalError(t,e);break;case"requestadparameters":this.handleRequestAdParameters(t,e);break;case"getmediastate":case"requestmediastate":this.handleGetMediaState(t,e);break;case"requestpause":this.handleRequestPause(t,e);break;case"requestplay":case"requestresume":this.handleRequestResume(t,e);break;case"requestchangevolume":case"requestvolume":this.handleRequestVolume(t,e);break;case"requestmute":this.handleRequestMute(t,e,!0);break;case"requestresize":this.handleRequestResize(t,e);break;case"requestfullscreen":this.handleRequestFullscreen(t,e);break;case"requestexitfullscreen":this.handleRequestExitFullscreen(t,e);break;case"requestcollapse":this.handleRequestCollapse(t,e);break;case"requestexpand":this.handleRequestExpand(t,e);break;case"requestduration":this.handleRequestDuration(t,e);break;case"requestcurrenttime":this.handleRequestCurrentTime(t,e);break;case"requestremainingtime":this.handleRequestRemainingTime(t,e);break;case"requestplayerstate":this.handleRequestPlayerState(t,e);break;case"requestcreativedata":this.handleRequestCreativeData(t,e);break;case"requestskip":this.handleRequestSkip(t,e);break;case"requeststop":this.handleRequestStop(t,e);break;case"reporttracking":this.handleReportTracking(t,e);break;case"creativeinteraction":this.respond(t,e,{}),this.emitEvent("simidinteraction",e.data||e.args||{});break;case"creativeclosed":this.respond(t,e,{}),t.complete(),this.emitEvent("simidcomplete",{});break;default:this.respond(t,e,{});break}}handleRequestClickThru(e,t){let s=(t.args||t.data||{}).clickUrl||e.creative.clickThruUrl||"";const r=e.creative.clickTrackingUrls||[];if(typeof s!="string"||!s.trim()){this.rejectRequest(e,t,"No valid click-through URL specified");return}s=s.trim();try{const l=new URL(s,typeof window<"u"?window.location.href:void 0);if(l.protocol!=="http:"&&l.protocol!=="https:"){this.rejectRequest(e,t,"Invalid URL scheme. Only HTTP and HTTPS are permitted."),this.emitEvent("simidsecurityerror",{reason:"Blocked unsafe click-through URL",url:s});return}}catch{this.rejectRequest(e,t,"Malformed click-through URL");return}let a=!1;const n=this.simidManager.getConfig().onSimidClickThru;if(typeof n=="function")try{n(s,r)===!1&&(a=!0)}catch(l){console.warn("[SimidRuntime] Error in onSimidClickThru developer callback:",l)}if(r.forEach(l=>{if(typeof l=="string"&&l)try{fetch(l,{method:"GET",mode:"no-cors",keepalive:!0}).catch(()=>{})}catch{}}),!a&&this.simidManager.getConfig().allowClickThru!==!1&&typeof window<"u")try{window.open(s,"_blank","noopener,noreferrer")}catch(l){console.warn("[SimidRuntime] Popup open failed:",l)}this.emitEvent("simidclick",{url:s,trackingUrls:r,playerHandled:!a}),this.respond(e,t,{success:!0,url:s})}handleRequestChangeAdDuration(e,t){var l,o,d;const i=t.args||t.data||{},s=((d=(o=(l=this.controller)==null?void 0:l.getState)==null?void 0:o.call(l))==null?void 0:d.adDuration)||0;let r;if(typeof i.duration=="number"?r=i.duration:typeof i.extensionSec=="number"&&(r=s+i.extensionSec),r===void 0){this.rejectRequest(e,t,"requestChangeAdDuration missing a numeric duration/extensionSec");return}const a=r-s,n=this.simidManager.getConfig().maxDurationExtensionSec??30;if(a>n){this.rejectRequest(e,t,`Requested duration extension (${a}s) exceeds maximum permitted limit (${n}s)`);return}this.emitEvent("simiddurationchange",{duration:r,extensionSec:a,maxAllowed:n}),this.respond(e,t,{success:!0,duration:r}),r<s&&this.scheduleAdDurationCutoff(r)}scheduleAdDurationCutoff(e){var i;if(this.clearDurationCutoff(),!((i=this.controller)!=null&&i.on))return;const t=s=>{var r,a,n;if(s&&s.currentTime>=e){this.clearDurationCutoff();try{(n=(a=(r=this.controller)==null?void 0:r.ads)==null?void 0:a.skip)==null||n.call(a)}catch{}}};this.durationCutoffListener=t,this.controller.on("adtimeupdate",t)}clearDurationCutoff(){var e;this.durationCutoffListener&&((e=this.controller)!=null&&e.off)&&this.controller.off("adtimeupdate",this.durationCutoffListener),this.durationCutoffListener=null}handleRequestFatalError(e,t){const i=t.args||t.data||{},s=i.code||1005,r=i.message||"Creative reported fatal error";this.emitEvent("simidcreativeerror",{code:s,message:r,fatal:!0}),this.emitEvent("simiderror",{code:s,message:r,fatal:!0}),this.respond(e,t,{acknowledged:!0}),this.destroyRuntime()}handleRequestMute(e,t,i){var s;(s=this.controller)!=null&&s.setMuted&&this.controller.setMuted(i),this.respond(e,t,{success:!0,muted:i})}handleRequestAdParameters(e,t){this.respond(e,t,{adParameters:e.creative.creativeParameters||""})}getSafeDuration(){var t,i,s;const e=(s=(i=(t=this.controller)==null?void 0:t.getState)==null?void 0:i.call(t))==null?void 0:s.duration;return e==null||isNaN(e)||e===1/0||e<0?1/0:e}getSafeRemainingTime(){var i,s,r;const e=this.getSafeDuration();if(e===1/0)return 1/0;const t=((r=(s=(i=this.controller)==null?void 0:i.getState)==null?void 0:s.call(i))==null?void 0:r.currentTime)||0;return Math.max(0,e-t)}handleGetMediaState(e,t){var a,n,l,o;const i=(n=(a=this.controller)==null?void 0:a.getVideoElement)==null?void 0:n.call(a),s=(o=(l=this.controller)==null?void 0:l.getState)==null?void 0:o.call(l),r=this.getSafeDuration();this.respond(e,t,{currentSrc:(i==null?void 0:i.currentSrc)||(i==null?void 0:i.src)||"",currentTime:(i==null?void 0:i.currentTime)||(s==null?void 0:s.currentTime)||0,duration:r,isLive:r===1/0,ended:(i==null?void 0:i.ended)||!1,muted:i?i.muted:(s==null?void 0:s.isMuted)??!1,paused:i?i.paused:s!=null&&s.isPlaying?!s.isPlaying:!0,volume:(i==null?void 0:i.volume)??(s==null?void 0:s.volume)??1,fullscreen:!!(s!=null&&s.isFullscreen)})}handleRequestPause(e,t){var i;(i=this.controller)!=null&&i.getVideoElement&&this.controller.getVideoElement().pause(),this.respond(e,t,{success:!0}),this.emitEvent("simidpause",{})}handleRequestResume(e,t){var i;(i=this.controller)!=null&&i.getVideoElement&&this.controller.getVideoElement().play().catch(()=>{}),this.respond(e,t,{success:!0}),this.emitEvent("simidresume",{})}handleRequestResize(e,t){const{width:i,height:s}=t.data||t.args||{};this.iframe&&i&&s&&(this.iframe.style.width=typeof i=="number"?`${i}px`:i,this.iframe.style.height=typeof s=="number"?`${s}px`:s),this.respond(e,t,{success:!0}),this.emitEvent("simidresize",{width:i,height:s})}handleRequestFullscreen(e,t){var i;(i=this.controller)!=null&&i.toggleFullscreen&&this.controller.toggleFullscreen(),this.respond(e,t,{success:!0}),this.emitEvent("simidfullscreen",{})}handleRequestExitFullscreen(e,t){var i;(i=this.controller)!=null&&i.getState().isFullscreen&&this.controller.toggleFullscreen(),this.respond(e,t,{success:!0}),this.emitEvent("simidexitfullscreen",{})}handleRequestCollapse(e,t){this.iframe&&(this.iframe.style.pointerEvents="none",this.iframe.style.opacity="0"),this.respond(e,t,{success:!0}),this.emitEvent("simidcollapse",{})}handleRequestExpand(e,t){this.iframe&&(this.iframe.style.pointerEvents="auto",this.iframe.style.opacity="1"),this.respond(e,t,{success:!0}),this.emitEvent("simidexpand",{})}handleRequestVolume(e,t){var a,n,l,o,d,h,u,f;const i=t.args||t.data||{},s=i.volume,r=i.muted;(a=this.controller)!=null&&a.setVolume&&typeof s=="number"&&this.controller.setVolume(s),(n=this.controller)!=null&&n.setMuted&&typeof r=="boolean"&&this.controller.setMuted(r),this.respond(e,t,{success:!0,volume:(d=(o=(l=this.controller)==null?void 0:l.getState)==null?void 0:o.call(l))==null?void 0:d.volume,muted:(f=(u=(h=this.controller)==null?void 0:h.getState)==null?void 0:u.call(h))==null?void 0:f.isMuted})}handleRequestDuration(e,t){const i=this.getSafeDuration();this.respond(e,t,{duration:i,isLive:i===1/0})}handleRequestCurrentTime(e,t){var s,r,a;const i=((a=(r=(s=this.controller)==null?void 0:s.getState)==null?void 0:r.call(s))==null?void 0:a.currentTime)||0;this.respond(e,t,{currentTime:i})}handleRequestRemainingTime(e,t){const i=this.getSafeRemainingTime();this.respond(e,t,{remainingTime:i,isLive:i===1/0})}handleRequestPlayerState(e,t){var r,a;const i=(a=(r=this.controller)==null?void 0:r.getState)==null?void 0:a.call(r),s=this.getSafeDuration();this.respond(e,t,{currentTime:(i==null?void 0:i.currentTime)||0,duration:s,isLive:s===1/0,volume:(i==null?void 0:i.volume)||1,muted:(i==null?void 0:i.isMuted)||!1,isPlaying:(i==null?void 0:i.isPlaying)||!1,isFullscreen:(i==null?void 0:i.isFullscreen)||!1})}handleRequestCreativeData(e,t){this.respond(e,t,{creative:e.creative})}handleRequestSkip(e,t){var i,s,r;this.respond(e,t,{}),this.emitEvent("simidskip",{}),this.destroyRuntime();try{(r=(s=(i=this.controller)==null?void 0:i.ads)==null?void 0:s.skip)==null||r.call(s)}catch{}}handleRequestStop(e,t){var i,s,r;this.respond(e,t,{}),this.emitEvent("simidstop",{}),this.destroyRuntime();try{(r=(s=(i=this.controller)==null?void 0:i.ads)==null?void 0:s.skip)==null||r.call(s)}catch{}}handleReportTracking(e,t){const i=t.args||{},s=t.data||{},r=i.trackingUrls||s.trackingUrls||[];Array.isArray(r)&&r.forEach(a=>{if(typeof a=="string"&&a)try{fetch(a,{method:"GET",mode:"no-cors",keepalive:!0}).catch(()=>{})}catch{}}),this.respond(e,t,{})}getPublicDiagnostics(){return this.getRuntimeDiagnostics()}getPublicSession(){return this.simidManager.getPublicSession()}isRuntimeActive(){const e=this.simidManager.getActiveSession();return!!e&&e.getSessionState()==="running"}respond(e,t,i={}){try{t.messageId!==void 0&&t.messageId!==null&&e.getBridge().postResolve(t.messageId,i),this.messagesSent++}catch{}}rejectRequest(e,t,i){try{t.messageId!==void 0&&t.messageId!==null&&e.getBridge().postReject(t.messageId,{message:i}),this.messagesSent++}catch{}}emitEvent(e,t){var i;if((i=this.controller)!=null&&i.emit)try{this.controller.emit(e,t)}catch{}}waitForState(e,t,i){return new Promise((s,r)=>{const a={idle:0,available:1,loading:2,initialized:3,running:4,completed:5,destroyed:6},n=a[t]??0;if((a[e.getSessionState()]??0)>=n&&e.getSessionState()!=="destroyed"){s();return}const o=setTimeout(()=>{r(new Error(`SIMID session did not reach state '${t}' within ${i}ms (current state: '${e.getSessionState()}')`))},i),d=setInterval(()=>{const h=e.getSessionState();(a[h]??0)>=n&&h!=="destroyed"?(clearTimeout(o),clearInterval(d),s()):(h==="destroyed"||h==="completed")&&(clearTimeout(o),clearInterval(d),r(new Error(`SIMID session entered terminal state '${h}' before reaching '${t}'`)))},50)})}}async function Hi(c,e,t={}){const i=t.timeout??1e4,s=t.retryCount??3,r=t.withCredentials?"include":"same-origin",a=t.headers||{};let n=0;const l=o=>new Promise(d=>setTimeout(d,o));for(;n<=s;){if(e.aborted)throw new DOMException("Aborted","AbortError");const o=new AbortController,d=o.signal,h=()=>o.abort();e.addEventListener("abort",h);const u=setTimeout(()=>{o.abort()},i);try{const f=await fetch(c,{headers:a,credentials:r,signal:d});if(clearTimeout(u),e.removeEventListener("abort",h),f.ok)return await f.text();if(f.status>=500&&n<s){n++,await l(Math.pow(2,n)*100);continue}throw new Error(`Server returned HTTP status ${f.status}`)}catch(f){if(clearTimeout(u),e.removeEventListener("abort",h),e.aborted)throw new DOMException("Aborted","AbortError");if(n<s){n++,await l(Math.pow(2,n)*100);continue}throw f}}throw new Error("Request failed after maximum retries")}class Js{constructor(){this.cache=new Map,this.maxAgeMs=3e5}get(e){const t=this.cache.get(e);if(t){if(Date.now()-t.timestamp<this.maxAgeMs)return t.xmlText;this.cache.delete(e)}return null}set(e,t){this.cache.set(e,{xmlText:t,timestamp:Date.now()})}clear(){this.cache.clear()}}class _t{constructor(){this.executedUrls=new Set,this.activeControllers=new Set,this.retryTimers=new Set,this.totalLatency=0,this.latencyCount=0,this.diagnostics={requestsCount:0,successesCount:0,failuresCount:0,retriesCount:0,duplicateSuppressions:0,averageLatencyMs:0,lastTransportUsed:null,errorCodesTracked:{}}}replaceMacros(e,t){if(!e)return"";const i=Date.now(),s=Math.floor(Math.random()*1e8);return e.replace(/\[CACHEBUSTING\]/gi,String(s)).replace(/\[CACHEBUSTER\]/gi,String(s)).replace(/\[TIMESTAMP\]/gi,String(i)).replace(/\[ERRORCODE\]/gi,String(t??0))}trackUrl(e,t,i=3){if(!e)return;const s=this.replaceMacros(e,t);if(this.executedUrls.has(s)){this.diagnostics.duplicateSuppressions++;return}this.executedUrls.add(s),this.sendBeacon(s,i)}async sendBeacon(e,t,i=0){this.diagnostics.requestsCount++;const s=me();if(typeof fetch=="function"){const r=new AbortController;this.activeControllers.add(r);try{await fetch(e,{method:"GET",mode:"no-cors",keepalive:!0,signal:r.signal}),this.activeControllers.delete(r),this.recordSuccess(s,"fetch");return}catch(a){if(this.activeControllers.delete(r),a instanceof Error&&a.name==="AbortError")return}}if(typeof Image<"u")try{const r=new Image;r.src=e,this.recordSuccess(s,"image");return}catch{this.handleFailure(e,500,s,t,i);return}this.diagnostics.failuresCount++}recordSuccess(e,t){this.diagnostics.successesCount++,this.diagnostics.lastTransportUsed=t,this.totalLatency+=me()-e,this.latencyCount++,this.diagnostics.averageLatencyMs=this.totalLatency/this.latencyCount}handleFailure(e,t,i,s,r){this.diagnostics.failuresCount++;const a=String(t);if(this.diagnostics.errorCodesTracked[a]=(this.diagnostics.errorCodesTracked[a]||0)+1,!(t===404||t===400)&&r<s){this.diagnostics.retriesCount++;const n=Math.pow(2,r+1)*100,l=setTimeout(()=>{this.retryTimers.delete(l),this.sendBeacon(e,s,r+1)},n);this.retryTimers.add(l)}}getDiagnostics(){return this.diagnostics}clearRegistry(){this.executedUrls.clear()}destroy(){this.activeControllers.forEach(e=>e.abort()),this.activeControllers.clear(),this.retryTimers.forEach(e=>clearTimeout(e)),this.retryTimers.clear(),this.executedUrls.clear()}}const me=()=>typeof performance<"u"?performance.now():Date.now();function yt(c){if(!c)return 0;const e=c.trim().split(":");if(e.length===3){const i=parseInt(e[0],10)||0,s=parseInt(e[1],10)||0,r=parseFloat(e[2])||0;return i*3600+s*60+r}const t=parseFloat(c);return isNaN(t)?0:t}function Ht(c){if(typeof window>"u"||typeof DOMParser>"u")return null;try{const t=new DOMParser().parseFromString(c,"text/xml");return t.getElementsByTagName("parsererror").length>0?null:t}catch{return null}}function ee(c,e){const t=[],i=c.getElementsByTagName("*"),s=e.toLowerCase();for(let r=0;r<i.length;r++){const a=i[r];(a.localName||a.nodeName.split(":").pop()||"").toLowerCase()===s&&t.push(a)}return t}function Q(c,e){const t=ee(c,e);return t.length>0?t[0]:null}function er(c){return typeof XMLSerializer<"u"?new XMLSerializer().serializeToString(c):c.textContent||""}function tr(c){var g,m,v;if(typeof DOMParser>"u")return null;const e=new DOMParser().parseFromString(c,"text/xml");if(e.getElementsByTagName("parsererror").length>0)return null;const t=Q(e,"Ad"),i=t&&Q(t,"InLine")||Q(e,"InLine");if(!i)return null;const s=Q(i,"AdTitle"),r=(g=s==null?void 0:s.textContent)==null?void 0:g.trim(),a=ee(i,"Creative");let n=null;for(let y=0;y<a.length;y++){const b=Q(a[y],"NonLinear");if(b){n=b;break}}if(!n)return null;const l=bt(n);if(!l)return null;const o=parseInt(n.getAttribute("width")||"0",10)||void 0,d=parseInt(n.getAttribute("height")||"0",10)||void 0,h=Q(n,"NonLinearClickThrough"),u=((m=h==null?void 0:h.textContent)==null?void 0:m.trim())||void 0,f=ee(n,"Tracking"),p=[];for(let y=0;y<f.length;y++){const b=f[y],S=b.getAttribute("event")||"",T=(v=b.textContent)==null?void 0:v.trim();T&&S&&p.push({url:T,event:S})}return{title:r,width:o,height:d,clickThroughUrl:u,trackingUrls:p.length>0?p:void 0,...l}}function bt(c){var n,l,o;const e=Q(c,"StaticResource"),t=(n=e==null?void 0:e.textContent)==null?void 0:n.trim();if(t)return{imageUrl:t};const i=Q(c,"IFrameResource"),s=(l=i==null?void 0:i.textContent)==null?void 0:l.trim();if(s)return{htmlUrl:s,useIframe:!0};const r=Q(c,"HTMLResource"),a=(o=r==null?void 0:r.textContent)==null?void 0:o.trim();return a?{htmlContent:a}:null}function ir(c){const{mode:e,configSkipOffset:t,xmlSkippable:i,xmlSkipOffset:s,currentTime:r}=c;if(e===ze.DISABLED)return{canSkip:!1,skipAvailableAt:null};if(e===ze.USER){const n=t??5,l=r>=n;return{canSkip:l,skipAvailableAt:l?null:Math.max(0,n-r)}}if(!i||s===void 0)return{canSkip:!1,skipAvailableAt:null};const a=r>=s;return{canSkip:a,skipAvailableAt:a?null:Math.max(0,s-r)}}function qi(c,e){return!(c==="impression"&&(e==null?void 0:e.trackImpression)===!1||c==="quartile"&&(e==null?void 0:e.trackQuartiles)===!1)}function sr(c){const e=c||"",t=[[/timeout/i,ie.NETWORK,301],[/version|unsupported/i,ie.CONFIGURATION,101],[/loop/i,ie.PARSING,302],[/depth|limit|oversized/i,ie.CONFIGURATION,302],[/xml|malformed|parse/i,ie.PARSING,100],[/media/i,ie.CONFIGURATION,403],[/creative/i,ie.CONFIGURATION,200],[/http|fetch|status|server/i,ie.NETWORK,300]];for(const[i,s,r]of t)if(i.test(e))return{type:s,code:r};return{type:ie.UNKNOWN,code:900}}class qt{constructor(){this.name="VAST",this.capabilities={supportsLinear:!0,supportsNonLinear:!0,supportsCompanion:!0,supportsSkippable:!0,supportsVMAP:!1,supportsVAST:!0,supportsSSAI:!1,supportsIMA:!1},this.context=null,this.manager=null,this.cache=new Js,this.trackingManager=new _t,this.isCacheEnabled=!1,this.renderingStrategy="dedicated",this.originalSource="",this.skipModeConfig=ze.AUTO,this.currentAd=null,this.currentAdBreak=null,this.currentAdIndex=0,this.adVideoElement=null,this.canSkipAd=!1,this.impressionFired=!1,this.milestones={start:!1,firstQuartile:!1,midpoint:!1,thirdQuartile:!1,complete:!1},this.cleanupListeners=null,this.cleanupClick=null,this.bufferingTimeoutId=null,this.simidRuntime=null,this.limits={maxXmlSize:2097152,maxWrapperDepth:5,maxCreatives:20,maxMediaEntries:50,maxTrackingEntries:100,maxExtensions:20},this.diagnostics={fetchDurationMs:0,parseDurationMs:0,validationDurationMs:0,wrapperCount:0,selectedMedia:null,rejectedMedia:[],validationWarnings:[],parserVersion:"Unknown",creativeCount:0,podCount:0,mediaCandidatesCount:0,rejectedCreativesCount:0,namespaceUsageDetected:!1,cacheHits:0,cacheMisses:0}}init(e){var i,s,r,a,n,l;this.context=e,e.controller&&e.controller.ads&&(this.manager=e.controller.ads.manager);const t=(i=e.config)==null?void 0:i.providerOptions;return t&&(this.isCacheEnabled=!!t.enableCache,this.renderingStrategy=t.renderingStrategy==="swapped"?"swapped":"dedicated",typeof t.maxXmlSize=="number"&&(this.limits.maxXmlSize=t.maxXmlSize),typeof t.maxWrapperDepth=="number"&&(this.limits.maxWrapperDepth=t.maxWrapperDepth)),this.skipModeConfig=((r=(s=e.config)==null?void 0:s.playback)==null?void 0:r.skipMode)??ze.AUTO,this.skipOffsetConfig=(n=(a=e.config)==null?void 0:a.playback)==null?void 0:n.skipOffset,this.trackingConfig=(l=e.config)==null?void 0:l.tracking,{success:!0}}async requestAds(e,t){var h,u,f,p,g,m;const i=t==null?void 0:t.context;if((!this.manager||!this.context)&&i&&this.init(i),!this.manager||!this.context)return{success:!1,error:{type:ie.CONFIGURATION,code:100,message:"VastProvider not initialized."}};this.simidRuntime&&(this.simidRuntime.destroyRuntime(),this.simidRuntime=null),this.manager&&this.manager.transitionTo(w.REQUESTING);const s=new Set;let r=e,a=0;const n=[],l=[],o=[],d=new AbortController().signal;try{for(;a<this.limits.maxWrapperDepth;){if(s.has(r))throw new Error("VAST wrapper loop detected");s.add(r),this.diagnostics.wrapperCount=a;let v="";if(this.isCacheEnabled){const M=this.cache.get(r);M&&(this.diagnostics.cacheHits++,v=M)}if(!v){this.diagnostics.cacheMisses++;const M=me();v=await this.fetchVastXml(r,d,this.context.config.request),this.diagnostics.fetchDurationMs+=me()-M,this.isCacheEnabled&&this.cache.set(r,v)}if(v.length>this.limits.maxXmlSize)throw new Error(`Oversized VAST XML payload: ${v.length} bytes exceeds limits`);const y=me(),b=Ht(v);if(this.diagnostics.parseDurationMs+=me()-y,!b)throw new Error("Malformed VAST XML or parsing error");const S=Q(b,"VAST"),T=Q(b,"Playlist");if(!S&&!T)throw new Error("Missing VAST or Playlist root node");if((v.includes(":VAST")||v.includes(":Ad")||v.includes(":VMAP"))&&(this.diagnostics.namespaceUsageDetected=!0),S){const M=S.getAttribute("version");if(M){this.diagnostics.parserVersion=`VAST-${M}`;const I=parseFloat(M);if(isNaN(I)||I<2||I>4.2)throw new Error(`Unsupported VAST version: ${M}`)}}if(T){const M=ee(T,"Ad"),I=[];for(let D=0;D<M.length;D++){const N=(h=M[D].textContent)==null?void 0:h.trim();N&&(N.startsWith("http://")||N.startsWith("https://"))&&I.push(N)}if(I.length>0){const D=[];for(let N=0;N<I.length;N++)try{const P=await this.fetchVastXml(I[N],d,(u=this.context.config)==null?void 0:u.request),C=Ht(P);if(C){const R=Q(C,"Inline"),q=Q(C,"Wrapper");if(R){const te=ee(C,"Ad");for(let V=0;V<te.length;V++){const U=this.normalizeAdNode(te[V],D.length+1,I.length);U&&D.push(U)}}else if(q){const te=Q(C,"VASTAdTagURI");if(te&&te.textContent){const V=await this.fetchVastXml(te.textContent.trim(),d,(f=this.context.config)==null?void 0:f.request),U=Ht(V);if(U){const L=ee(U,"Ad");for(let $=0;$<L.length;$++){const H=this.normalizeAdNode(L[$],D.length+1,I.length);H&&D.push(H)}}}}}}catch(P){console.warn(`[VastProvider] Failed to fetch playlist ad #${N+1}:`,P)}if(D.length>0){D.sort((C,R)=>(C.sequence??Number.MAX_SAFE_INTEGER)-(R.sequence??Number.MAX_SAFE_INTEGER));const N=D[0];this.currentAd=N,this.currentAdIndex=0;const P={id:`vast-break-${Date.now()}`,timeOffset:0,type:"preroll",ads:D,duration:D.reduce((C,R)=>C+(R.duration||0),0)};return this.currentAdBreak=P,this.manager.getAdBreakManager().registerBreak(P),this.manager.setCurrentAd(N),this.manager.transitionTo(w.LOADED),{success:!0}}}}const E=me(),x=this.validateVastStructure(b);if(this.diagnostics.validationDurationMs+=me()-E,x&&!T)throw new Error(`VAST Validation Failure: ${x}`);if(Q(b,"Inline")){const M=me(),I=ee(b,"Ad");this.diagnostics.podCount=I.length;const D=[];for(let R=0;R<I.length;R++){const q=I[R],te=this.normalizeAdNode(q,R+1,I.length)||this.normalizeNonLinearAdNode(q,R+1,I.length)||this.normalizeCompanionOnlyAdNode(q,R+1,I.length);te&&D.push(te)}if(D.length===0)throw new Error("No compatible ad or creative found in inline VAST.");let N=D;(n.length||l.length||o.length)&&(N=N.map(R=>({...R,impressionUrls:[...R.impressionUrls||[],...n],errorUrls:[...R.errorUrls||[],...l],trackingUrls:[...R.trackingUrls||[],...o]}))),N=[...N].sort((R,q)=>(R.sequence??Number.MAX_SAFE_INTEGER)-(q.sequence??Number.MAX_SAFE_INTEGER)),this.diagnostics.parseDurationMs+=me()-M;const P=N[0];this.currentAd=P,this.currentAdIndex=0;const C={id:`vast-break-${Date.now()}`,timeOffset:0,type:"preroll",ads:N,duration:N.reduce((R,q)=>R+(q.duration||0),0)};return this.currentAdBreak=C,this.manager.getAdBreakManager().registerBreak(C),this.manager.setCurrentAd(P),this.manager.transitionTo(w.LOADED),{success:!0}}const O=Q(b,"Wrapper");if(O){const M=Q(b,"VASTAdTagURI");if(!M||!M.textContent)throw new Error("VAST wrapper is missing VASTAdTagURI node.");const I=ee(O,"Impression");for(let P=0;P<I.length;P++){const C=(p=I[P].textContent)==null?void 0:p.trim();C&&n.push(C)}const D=ee(O,"Error");for(let P=0;P<D.length;P++){const C=(g=D[P].textContent)==null?void 0:g.trim();C&&l.push(C)}const N=ee(O,"Tracking");for(let P=0;P<N.length;P++){const C=N[P],R=C.getAttribute("event")||"",q=(m=C.textContent)==null?void 0:m.trim();q&&R&&o.push({url:q,event:R})}r=M.textContent.trim(),a++;continue}throw new Error("VAST XML does not contain an Inline or Wrapper node.")}throw new Error(`VAST wrapper depth limit reached (${this.limits.maxWrapperDepth})`)}catch(v){const y=this.mapError(v);return this.fireErrorTracking(y.type===ie.NETWORK?301:100),this.manager.triggerAdError(y),{success:!1,error:y}}}async fetchVastXml(e,t,i={}){return Hi(e,t,i)}validateVastStructure(e){return ee(e,"Ad").length===0?"VAST contains no Ad elements":null}normalizeAdNode(e,t,i){var ae,wt,ot,Tt,ne,oi,li,Et,lt,xe,We,z,se,he,Be,ct,ds,hs,us,ps;const s=Q(e,"Inline");if(!s)return null;const r=Q(s,"AdTitle"),a=((ae=r==null?void 0:r.textContent)==null?void 0:ae.trim())||"VAST Ad",n=Q(s,"AdSystem"),l=((wt=n==null?void 0:n.textContent)==null?void 0:wt.trim())||"Unknown",o=Q(s,"Duration"),d=yt(o==null?void 0:o.textContent),h=ee(s,"Creative");if(this.diagnostics.creativeCount+=h.length,h.length>this.limits.maxCreatives)return this.diagnostics.validationWarnings.push("Too many creatives detected in XML."),null;let u=null,f="";for(let K=0;K<h.length;K++){const Z=h[K],fe=Q(Z,"Linear");if(fe){u=fe,f=Z.getAttribute("id")||"";break}else this.diagnostics.rejectedCreativesCount++}if(!u)return this.diagnostics.validationWarnings.push("No compatible linear creative found."),null;const p=ee(u,"MediaFile");if(this.diagnostics.mediaCandidatesCount+=p.length,p.length>this.limits.maxMediaEntries)return this.diagnostics.validationWarnings.push("Oversized media entries count."),null;const g=[];for(let K=0;K<p.length;K++){const Z=p[K],fe=(ot=Z.textContent)==null?void 0:ot.trim(),be=Z.getAttribute("type")||"",je=parseInt(Z.getAttribute("bitrate")||"0",10),Qr=parseInt(Z.getAttribute("width")||"0",10),Xr=parseInt(Z.getAttribute("height")||"0",10),Yr=Z.getAttribute("delivery")||"progressive";fe&&g.push({url:fe,bitrate:je,width:Qr,height:Xr,contentType:be,delivery:Yr})}const m=this.selectMediaFile(g);if(!m)return this.diagnostics.validationWarnings.push("No compatible MediaFile found in creative."),null;this.diagnostics.selectedMedia=m;const v=u.getAttribute("skipoffset"),y=v!=null,b=y?yt(v):void 0,S=ee(u,"Tracking");if(S.length>this.limits.maxTrackingEntries)return this.diagnostics.validationWarnings.push("Tracking events limit exceeded."),null;const T=[];for(let K=0;K<S.length;K++){const Z=S[K],fe=Z.getAttribute("event")||"",be=(Tt=Z.textContent)==null?void 0:Tt.trim();be&&fe&&T.push({url:be,event:fe})}const E=Q(u,"ClickThrough"),x=(ne=E==null?void 0:E.textContent)==null?void 0:ne.trim(),A=ee(s,"Impression"),O=[];for(let K=0;K<A.length;K++){const Z=(oi=A[K].textContent)==null?void 0:oi.trim();Z&&O.push(Z)}const M=ee(u,"ClickTracking"),I=[];for(let K=0;K<M.length;K++){const Z=(li=M[K].textContent)==null?void 0:li.trim();Z&&I.push(Z)}const D=ee(e,"Error");if(D.length===0){const K=ee(e.ownerDocument,"Error");for(let Z=0;Z<K.length;Z++)((Et=K[Z].textContent)==null?void 0:Et.trim())&&D.push(K[Z])}const N=[];for(let K=0;K<D.length;K++){const Z=(lt=D[K].textContent)==null?void 0:lt.trim();Z&&N.push(Z)}let P=null;const C=Q(s,"UniversalAdId");C&&(P={idRegistry:C.getAttribute("idRegistry")||"unknown",value:((xe=C.textContent)==null?void 0:xe.trim())||""});const R=[],q=ee(s,"Extension");for(let K=0;K<Math.min(q.length,this.limits.maxExtensions);K++)R.push(er(q[K]));const te=[],V=ee(s,"Verification");for(let K=0;K<V.length;K++){const Z=V[K],fe=Z.getAttribute("vendor")||"",be=((z=(We=Q(Z,"JavaScriptResource"))==null?void 0:We.textContent)==null?void 0:z.trim())||"";be&&te.push({vendor:fe,script:be})}let U=((he=(se=Q(u,"InteractiveCreativeFile"))==null?void 0:se.textContent)==null?void 0:he.trim())||null;if(U||(U=((ct=(Be=Q(s,"InteractiveCreativeFile"))==null?void 0:Be.textContent)==null?void 0:ct.trim())||null),!U)for(let K=0;K<p.length;K++){const Z=p[K],fe=((ds=Z.getAttribute("apiFramework"))==null?void 0:ds.toUpperCase())||"",be=((hs=Z.getAttribute("type"))==null?void 0:hs.toLowerCase())||"";if(fe==="SIMID"||be==="text/html"){const je=(us=Z.textContent)==null?void 0:us.trim();if(je&&(je.startsWith("http://")||je.startsWith("https://"))){U=je;break}}}const L=Q(u,"Mezzanine"),$=((ps=L==null?void 0:L.textContent)==null?void 0:ps.trim())||null,H=e.getAttribute("sequence"),de=H?parseInt(H,10):void 0,le=e.getAttribute("id")||`vast-${Date.now()}`,Fe=ee(s,"Companion"),Ue=[];for(let K=0;K<Fe.length;K++){const Z=this.normalizeCompanionNode(Fe[K],e,K+1,Fe.length);Z&&Ue.push(Z)}const Ke=this.extractConcurrentNonLinearAds(s,e);return{id:le,title:a,duration:d,width:m.width,height:m.height,linear:!0,skippable:y,skipOffset:b,clickThroughUrl:x,trackingUrls:T,impressionUrls:O,clickTrackingUrls:I,errorUrls:N,contentType:m.contentType,mediaUrl:m.url,creativeId:f,adSystem:l,universalAdId:P,extensions:R,adVerifications:te,interactiveCreativeFile:U,mezzanine:$,sequence:de,podPosition:t,podSize:i,companions:Ue.length>0?Ue:void 0,nonLinearAds:Ke.length>0?Ke:void 0}}normalizeNonLinearAdNode(e,t,i){var O,M,I,D,N,P;const s=Q(e,"Inline");if(!s)return null;const r=Q(s,"AdTitle"),a=((O=r==null?void 0:r.textContent)==null?void 0:O.trim())||"VAST Ad",n=Q(s,"AdSystem"),l=((M=n==null?void 0:n.textContent)==null?void 0:M.trim())||"Unknown",o=ee(s,"Creative");let d=null,h="";for(let C=0;C<o.length;C++){const R=o[C],q=Q(R,"NonLinear");if(q){d=q,h=R.getAttribute("id")||"";break}}if(!d)return this.diagnostics.validationWarnings.push("No compatible NonLinear creative found."),null;const u=bt(d);if(!u)return this.diagnostics.validationWarnings.push("NonLinear creative has no usable resource (StaticResource/IFrameResource/HTMLResource)."),null;const f=parseInt(d.getAttribute("width")||"0",10)||void 0,p=parseInt(d.getAttribute("height")||"0",10)||void 0,g=yt(d.getAttribute("minSuggestedDuration")),m=Q(d,"NonLinearClickThrough"),v=(I=m==null?void 0:m.textContent)==null?void 0:I.trim(),y=ee(d,"Tracking"),b=[];for(let C=0;C<y.length;C++){const R=y[C],q=R.getAttribute("event")||"",te=(D=R.textContent)==null?void 0:D.trim();te&&q&&b.push({url:te,event:q})}const S=ee(s,"Impression"),T=[];for(let C=0;C<S.length;C++){const R=(N=S[C].textContent)==null?void 0:N.trim();R&&T.push(R)}const E=ee(e,"Error"),x=[];for(let C=0;C<E.length;C++){const R=(P=E[C].textContent)==null?void 0:P.trim();R&&x.push(R)}return{id:e.getAttribute("id")||`vast-nonlinear-${Date.now()}`,title:a,duration:g,width:f,height:p,linear:!1,skippable:!1,clickThroughUrl:v,trackingUrls:b,impressionUrls:T,errorUrls:x,creativeId:h,adSystem:l,podPosition:t,podSize:i,...u}}normalizeCompanionNode(e,t,i,s){var f,p;const r=bt(e);if(!r)return this.diagnostics.validationWarnings.push("Companion creative has no usable resource (StaticResource/IFrameResource/HTMLResource)."),null;const a=parseInt(e.getAttribute("width")||"0",10)||void 0,n=parseInt(e.getAttribute("height")||"0",10)||void 0,l=Q(e,"CompanionClickThrough"),o=(f=l==null?void 0:l.textContent)==null?void 0:f.trim(),d=ee(e,"Tracking"),h=[];for(let g=0;g<d.length;g++){const m=d[g],v=m.getAttribute("event")||"",y=(p=m.textContent)==null?void 0:p.trim();y&&v&&h.push({url:y,event:v})}return{id:e.getAttribute("id")||`${t.getAttribute("id")||"vast"}-companion-${i}`,title:"VAST Companion Ad",duration:0,width:a,height:n,linear:!1,skippable:!1,clickThroughUrl:o,trackingUrls:h,podPosition:i,podSize:s,...r}}normalizeCompanionOnlyAdNode(e,t,i){var y,b,S,T;const s=Q(e,"Inline");if(!s)return null;const r=ee(s,"Companion");if(r.length===0)return null;const a=[];for(let E=0;E<r.length;E++){const x=this.normalizeCompanionNode(r[E],e,E+1,r.length);x&&a.push(x)}if(a.length===0)return null;const n=Q(s,"AdTitle"),l=((y=n==null?void 0:n.textContent)==null?void 0:y.trim())||"VAST Ad",o=Q(s,"AdSystem"),d=((b=o==null?void 0:o.textContent)==null?void 0:b.trim())||"Unknown",h=ee(s,"Impression"),u=[];for(let E=0;E<h.length;E++){const x=(S=h[E].textContent)==null?void 0:S.trim();x&&u.push(x)}const f=ee(e,"Error"),p=[];for(let E=0;E<f.length;E++){const x=(T=f[E].textContent)==null?void 0:T.trim();x&&p.push(x)}const g=e.getAttribute("sequence"),m=g?parseInt(g,10):void 0;return{id:e.getAttribute("id")||`vast-companion-only-${Date.now()}`,title:l,duration:0,linear:!1,skippable:!1,impressionUrls:u,errorUrls:p,adSystem:d,sequence:m,podPosition:t,podSize:i,companions:a}}extractConcurrentNonLinearAds(e,t){var a,n;const i=ee(e,"Creative"),s=[];let r=0;for(let l=0;l<i.length;l++){const o=Q(i[l],"NonLinearAds");if(!o)continue;const d=ee(o,"NonLinear");for(let h=0;h<d.length;h++){const u=d[h],f=bt(u);if(!f)continue;r++;const p=parseInt(u.getAttribute("width")||"0",10)||void 0,g=parseInt(u.getAttribute("height")||"0",10)||void 0,m=yt(u.getAttribute("minSuggestedDuration")),v=Q(u,"NonLinearClickThrough"),y=(a=v==null?void 0:v.textContent)==null?void 0:a.trim(),b=ee(u,"Tracking"),S=[];for(let E=0;E<b.length;E++){const x=b[E],A=x.getAttribute("event")||"",O=(n=x.textContent)==null?void 0:n.trim();O&&A&&S.push({url:O,event:A})}const T=u.getAttribute("id")||`${t.getAttribute("id")||"vast"}-nonlinear-${r}`;s.push({id:T,title:"VAST NonLinear Overlay",duration:m,width:p,height:g,linear:!1,skippable:!1,clickThroughUrl:y,trackingUrls:S,...f})}}return s}selectMediaFile(e){if(e.length===0)return null;const t=e.filter(i=>{const s=(i.contentType||"").toLowerCase(),r=(i.url||"").toLowerCase(),a=s.includes("mp4")||s.includes("webm")||s.includes("mpegurl")||s.includes("apple")||s.includes("dash")||s.includes("video/")||r.endsWith(".mp4")||r.endsWith(".webm")||r.endsWith(".m3u8")||r.endsWith(".mpd")||r.includes("mp4");return a||this.diagnostics.rejectedMedia.push(i),a});return t.length===0?e[0]||null:(t.sort((i,s)=>{const r=(i.width||0)*(i.height||0),a=(s.width||0)*(s.height||0);return r!==a?a-r:(s.bitrate||0)-(i.bitrate||0)}),t[0])}mapError(e){const t=e instanceof Error?e.message:String(e??""),{type:i,code:s}=sr(t);return{type:i,code:s,message:t||"VAST request or parsing failed",originalError:e}}getInternalAdBreak(){return this.currentAdBreak}setInternalAdBreak(e){this.currentAdBreak=e,this.currentAd=e.ads[0]??null,this.currentAdIndex=0}getVastDiagnostics(){return{...this.diagnostics,tracking:this.trackingManager.getDiagnostics()}}async playAdBreak(){if(!this.context||!this.manager||!this.currentAd)return;if(this.context.controller.getState().sourceType==="embed"){this.manager.triggerAdError({type:ie.CONFIGURATION,code:900,message:"VAST ads are not supported for embed (YouTube/Vimeo) sources."});return}const e=this.currentAdBreak||this.manager.getAdBreakManager().getActiveBreak()||{id:`vast-break-${Date.now()}`,timeOffset:0,type:"preroll",ads:[this.currentAd],duration:this.currentAd.duration};this.currentAdBreak=e,this.currentAdBreak.ads&&this.currentAdBreak.ads.length>0&&(this.currentAdIndex>=this.currentAdBreak.ads.length&&(this.currentAdIndex=0),this.currentAd=this.currentAdBreak.ads[this.currentAdIndex]),this.manager.startAdBreak(e),this.currentAd.linear&&await this.playCurrentAdInPod()}async playCurrentAdInPod(){var t,i,s,r,a,n;if(!this.context||!this.manager||!this.currentAd)return;if(!this.currentAd.linear){this.manager.isHtmlOverlayCreative(this.currentAd)&&this.manager.playHtmlOverlay(this.currentAd);return}this.canSkipAd=!1,this.impressionFired=!1,this.milestones={start:!1,firstQuartile:!1,midpoint:!1,thirdQuartile:!1,complete:!1},this.trackingManager.clearRegistry();const e=this.currentAd.mediaUrl;if(!e){this.handlePlaybackError("Missing mediaUrl for current linear ad");return}this.manager.setCurrentAd(this.currentAd),this.manager.clearAuxiliaryOverlays();try{if(this.renderingStrategy==="dedicated"){if(!this.adVideoElement){const l=document.createElement("video");l.setAttribute("playsinline","true"),l.setAttribute("webkit-playsinline","true"),l.style.position="absolute",l.style.top="0",l.style.left="0",l.style.width="100%",l.style.height="100%",l.style.zIndex="1000",l.style.backgroundColor="black",l.style.pointerEvents="auto",this.context.adContainer.appendChild(l),this.adVideoElement=l,this.setupAdVideoListeners(l),this.setupClickThrough(this.context.adContainer)}this.adVideoElement.src=e,this.adVideoElement.load(),this.manager.transitionTo(w.PLAYING);try{await this.adVideoElement.play()}catch(l){if(!this.adVideoElement)return;console.warn("[VastProvider] Unmuted ad play blocked by browser policy, falling back to muted play:",l),this.adVideoElement.muted=!0,await this.adVideoElement.play()}}else{const l=this.context.videoElement;this.originalSource||(this.originalSource=l.src||""),this.adVideoElement=l,this.setupAdVideoListeners(l),this.setupClickThrough(this.context.adContainer),l.src=e,l.load(),this.manager.transitionTo(w.PLAYING);try{await l.play()}catch(o){console.warn("[VastProvider] Unmuted ad play blocked by browser policy, falling back to muted play:",o),l.muted=!0,await l.play()}}if((t=this.currentAd)!=null&&t.companions&&this.currentAd.companions.length>0&&this.manager.showCompanions(this.currentAd.companions),(i=this.currentAd)!=null&&i.nonLinearAds&&this.currentAd.nonLinearAds.length>0&&this.manager.showConcurrentOverlays(this.currentAd.nonLinearAds),(s=this.currentAd)!=null&&s.interactiveCreativeFile&&this.context){this.simidRuntime&&(this.simidRuntime.destroyRuntime(),this.simidRuntime=null);const l=((r=this.context.config)==null?void 0:r.simid)||((n=(a=this.context.config)==null?void 0:a.providerOptions)==null?void 0:n.simid);this.simidRuntime=new _i(l);const o=this.context.adContainer,d=this.context.controller;this.simidRuntime.startRuntime(this.currentAd,o,d).catch(h=>{console.warn("[VastProvider] SIMID runtime initialization warning:",h)})}}catch(l){const o=l instanceof Error?l.message:"Ad playback failed to initialize";this.handlePlaybackError(o)}}pauseAd(){this.adVideoElement&&(this.adVideoElement.pause(),this.fireTrackingEvent("pause"))}resumeAd(){this.adVideoElement&&(this.adVideoElement.play().catch(e=>{console.error("[VastProvider] Failed to resume ad play:",e)}),this.fireTrackingEvent("resume"))}setVolume(e){this.adVideoElement&&(this.adVideoElement.volume=e)}setMuted(e){this.adVideoElement&&(this.adVideoElement.muted=e,this.fireTrackingEvent(e?"mute":"unmute"))}fireTrackingEvent(e){if(!this.currentAd||!this.currentAd.trackingUrls)return;const i=["start","firstQuartile","midpoint","thirdQuartile","complete"].includes(e)?"quartile":"other";this.currentAd.trackingUrls.filter(r=>r.event&&r.event.toLowerCase()===e.toLowerCase()).forEach(r=>{var a,n;(n=(a=this.trackingConfig)==null?void 0:a.customTracker)==null||n.call(a,e,r.url),qi(i,this.trackingConfig)&&this.trackingManager.trackUrl(r.url)})}fireErrorTracking(e){!this.currentAd||!this.currentAd.errorUrls||this.currentAd.errorUrls.forEach(t=>{const i=t.replace(/\[ERRORCODE\]/g,String(e));this.trackingManager.trackUrl(i)})}setupAdVideoListeners(e){const t=this.manager;if(!t)return;const i=()=>{t.transitionTo(w.PLAYING)},s=()=>{t.transitionTo(w.PAUSED)},r=()=>{t.transitionTo(w.BUFFERING),this.bufferingTimeoutId=setTimeout(()=>{this.handlePlaybackError("Stalled ad buffering timeout")},1e4)},a=()=>{var d,h,u,f;t.transitionTo(w.PLAYING),this.bufferingTimeoutId&&(clearTimeout(this.bufferingTimeoutId),this.bufferingTimeoutId=null),this.impressionFired||(this.impressionFired=!0,(h=(d=this.currentAd)==null?void 0:d.impressionUrls)==null||h.forEach(p=>{var g,m;(m=(g=this.trackingConfig)==null?void 0:g.customTracker)==null||m.call(g,"impression",p),qi("impression",this.trackingConfig)&&this.trackingManager.trackUrl(p)}),this.fireTrackingEvent("creativeView"),(u=this.currentAd)!=null&&u.adVerifications&&this.currentAd.adVerifications.length>0&&((f=this.context)==null||f.controller.emit("adverificationready",{ad:this.currentAd,verifications:this.currentAd.adVerifications})))},n=()=>{var m,v,y,b,S,T;const d=e.currentTime,h=e.duration||((m=this.currentAd)==null?void 0:m.duration)||0,u=Math.max(0,h-d),f=this.canSkipAd,{canSkip:p,skipAvailableAt:g}=ir({mode:this.skipModeConfig,configSkipOffset:this.skipOffsetConfig,xmlSkippable:(v=this.currentAd)==null?void 0:v.skippable,xmlSkipOffset:(y=this.currentAd)==null?void 0:y.skipOffset,currentTime:d});this.canSkipAd=p,p&&!f&&this.currentAd&&((b=this.context)==null||b.controller.emit("skipavailable",{ad:this.currentAd})),(S=this.context)==null||S.controller.updateStatePublic({canSkipAd:p,skipAvailableAt:g,adCurrentTime:d,adRemainingTime:u,adDuration:h}),this.checkMilestones(d,h),(T=this.context)==null||T.controller.emit("adtimeupdate",{currentTime:d,duration:h,remainingTime:u})},l=()=>{this.handleAdComplete()},o=()=>{this.handlePlaybackError("Native video element playback error")};e.addEventListener("play",i),e.addEventListener("pause",s),e.addEventListener("waiting",r),e.addEventListener("playing",a),e.addEventListener("timeupdate",n),e.addEventListener("ended",l),e.addEventListener("error",o),this.cleanupListeners=()=>{e.removeEventListener("play",i),e.removeEventListener("pause",s),e.removeEventListener("waiting",r),e.removeEventListener("playing",a),e.removeEventListener("timeupdate",n),e.removeEventListener("ended",l),e.removeEventListener("error",o),this.bufferingTimeoutId&&(clearTimeout(this.bufferingTimeoutId),this.bufferingTimeoutId=null)}}checkMilestones(e,t){var s,r,a,n,l,o,d,h;if(t<=0)return;const i=e/t;i>=0&&!this.milestones.start&&(this.milestones.start=!0,this.fireTrackingEvent("start"),(s=this.context)==null||s.controller.emit("admilestone",{milestone:"start"})),i>=.25&&!this.milestones.firstQuartile&&(this.milestones.firstQuartile=!0,this.fireTrackingEvent("firstQuartile"),(r=this.context)==null||r.controller.emit("admilestone",{milestone:"firstQuartile"}),this.currentAd&&((a=this.context)==null||a.controller.emit("adfirstquartile",{ad:this.currentAd}))),i>=.5&&!this.milestones.midpoint&&(this.milestones.midpoint=!0,this.fireTrackingEvent("midpoint"),(n=this.context)==null||n.controller.emit("admilestone",{milestone:"midpoint"}),this.currentAd&&((l=this.context)==null||l.controller.emit("admidpoint",{ad:this.currentAd}))),i>=.75&&!this.milestones.thirdQuartile&&(this.milestones.thirdQuartile=!0,this.fireTrackingEvent("thirdQuartile"),(o=this.context)==null||o.controller.emit("admilestone",{milestone:"thirdQuartile"}),this.currentAd&&((d=this.context)==null||d.controller.emit("adthirdquartile",{ad:this.currentAd}))),i>=.98&&!this.milestones.complete&&(this.milestones.complete=!0,this.fireTrackingEvent("complete"),(h=this.context)==null||h.controller.emit("admilestone",{milestone:"complete"}))}setupClickThrough(e){const t=()=>{var i,s,r;(i=this.currentAd)!=null&&i.clickThroughUrl&&((s=this.currentAd.clickTrackingUrls)==null||s.forEach(a=>this.trackingManager.trackUrl(a)),(r=this.context)==null||r.controller.emit("adclick",{clickUrl:this.currentAd.clickThroughUrl}))};e.addEventListener("click",t),this.cleanupClick=()=>{e.removeEventListener("click",t)}}handleAdComplete(){var e,t,i;this.fireTrackingEvent("complete"),this.currentAdBreak&&this.currentAdBreak.ads&&this.currentAdIndex<this.currentAdBreak.ads.length-1?(this.currentAdIndex++,this.currentAd=this.currentAdBreak.ads[this.currentAdIndex],(e=this.manager)==null||e.transitionTo(w.ENDED),this.currentAd.linear?this.playCurrentAdInPod():this.manager&&this.manager.isHtmlOverlayCreative(this.currentAd)&&this.manager.playHtmlOverlay(this.currentAd)):(this.cleanupPlaybackResources(),(t=this.manager)==null||t.transitionTo(w.ENDED),(i=this.manager)==null||i.endAdBreak())}handlePlaybackError(e){var i;console.error(`[VastProvider] Playback error: ${e}`),this.fireErrorTracking(400),this.cleanupPlaybackResources();const t={type:ie.UNKNOWN,code:400,message:e};(i=this.manager)==null||i.triggerAdError(t)}cleanupPlaybackResources(){if(this.simidRuntime){try{this.simidRuntime.destroyRuntime()}catch{}this.simidRuntime=null}this.cleanupListeners&&(this.cleanupListeners(),this.cleanupListeners=null),this.cleanupClick&&(this.cleanupClick(),this.cleanupClick=null),this.adVideoElement&&(this.renderingStrategy==="dedicated"?this.adVideoElement.parentNode&&this.adVideoElement.parentNode.removeChild(this.adVideoElement):(this.adVideoElement.src=this.originalSource,this.adVideoElement.load()),this.adVideoElement=null)}skipAd(){var e,t,i;this.fireTrackingEvent("skip"),this.cleanupPlaybackResources(),this.currentAdBreak&&this.currentAdBreak.ads&&this.currentAdIndex<this.currentAdBreak.ads.length-1?(this.currentAdIndex++,this.currentAd=this.currentAdBreak.ads[this.currentAdIndex],(e=this.manager)==null||e.transitionTo(w.SKIPPING),this.currentAd.linear?this.playCurrentAdInPod():this.manager&&this.manager.isHtmlOverlayCreative(this.currentAd)&&this.manager.playHtmlOverlay(this.currentAd)):((t=this.manager)==null||t.transitionTo(w.SKIPPING),(i=this.manager)==null||i.endAdBreak())}onSourceLoaded(e){this.reset()}reset(){this.cleanupPlaybackResources(),this.trackingManager.destroy(),this.cache.clear(),this.currentAd=null,this.currentAdBreak=null,this.currentAdIndex=0,this.canSkipAd=!1,this.impressionFired=!1,this.milestones={start:!1,firstQuartile:!1,midpoint:!1,thirdQuartile:!1,complete:!1}}destroy(){this.reset(),this.context=null,this.manager=null}}class st{constructor(e,t,i,s=!1){this.controller=e,this.adContainer=t,this.isExternalSlot=s,this.state="idle",this.containerElement=null,this.contentWrapper=null,this.iframeElement=null,this.currentAd=null,this.destroyController=new AbortController,this.resizeObserver=null,this.firedEvents=new Set,this.durationTimer=null,this.closeDelayTimer=null,this.intrinsicWidth=480,this.intrinsicHeight=70,this.renderStartTime=0,this.renderDuration=0,this.creationTime=0,this.clickCount=0,this.interactionCount=0,this.errors=[],this.trackingManager=i||new _t,this.creationTime=Date.now()}getLifecycleState(){return this.state}getDiagnostics(){return{overlayActive:this.state!=="idle"&&this.state!=="destroyed",overlayVisible:this.state==="visible",renderMode:this.getRenderMode(),renderDurationMs:this.renderDuration,overlayLifetimeMs:this.state!=="destroyed"?Date.now()-this.creationTime:0,clickCount:this.clickCount,interactionCount:this.interactionCount,trackingStatus:this.trackingManager.getDiagnostics(),errors:[...this.errors]}}getRenderMode(){return this.currentAd?this.currentAd.imageUrl?"image":this.currentAd.useIframe||this.currentAd.htmlUrl?"iframe":this.currentAd.htmlTemplateId?"template":this.currentAd.htmlContent?"string":"dom":"unknown"}async loadAd(e){if(typeof window>"u"||typeof document>"u")return!1;this.state="loading",this.currentAd={...e},this.renderStartTime=Date.now(),this.controller.emit("htmloverlayavailable",{adId:e.id});try{await this.resolveVastTagIfNecessary(this.currentAd),this.intrinsicWidth=this.currentAd.width||480,this.intrinsicHeight=this.currentAd.height||70,this.containerElement=document.createElement("div"),this.containerElement.className="html-overlay-container",this.contentWrapper=document.createElement("div"),this.contentWrapper.className="html-overlay-content",this.contentWrapper.style.width="100%",this.contentWrapper.style.height="100%",this.contentWrapper.style.position="relative",this.contentWrapper.style.overflow="hidden",this.contentWrapper.style.borderRadius="4px",this.contentWrapper.style.boxShadow="0 4px 12px rgba(0, 0, 0, 0.4)",this.containerElement.appendChild(this.contentWrapper);let t=null;if(this.currentAd.externalSlot){if(t=this.resolveTargetSlot(this.currentAd),!t)throw new Error(`Target external slot "${this.currentAd.externalSlot}" not found in DOM.`)}else t=this.adContainer;if(t.appendChild(this.containerElement),this.currentAd.imageUrl)await this.renderImage(this.currentAd,this.contentWrapper);else if(this.currentAd.useIframe||this.currentAd.htmlUrl)await this.renderIframe(this.currentAd,this.contentWrapper);else if(this.currentAd.htmlTemplateId)this.renderTemplate(this.currentAd,this.contentWrapper);else if(this.currentAd.htmlContent)this.renderHtmlString(this.currentAd,this.contentWrapper);else throw new Error("Unsupported HTML overlay content type: missing content, template, url, or image");return this.applyStylesAndPositioning(this.currentAd,this.containerElement),this.recalculateLayout(),this.setupCloseButton(),this.setupInteractionHandlers(),this.setupKeyboardAccessibility(),typeof ResizeObserver<"u"&&(this.resizeObserver=new ResizeObserver(()=>{this.recalculateLayout()}),this.resizeObserver.observe(t)),this.renderDuration=Date.now()-this.renderStartTime,this.state="rendered",this.controller.emit("htmloverlayloaded",{adId:e.id}),!0}catch(t){const i=t instanceof Error?t.message:"Rendering overlay failed";return this.handleError(i),!1}}resolveTargetSlot(e){var t;return e.externalSlot?typeof e.externalSlot!="string"?e.externalSlot:typeof document>"u"?null:document.querySelector(e.externalSlot)||((t=this.adContainer.shadowRoot)==null?void 0:t.querySelector(e.externalSlot)):null}async resolveVastTagIfNecessary(e){if(!e.htmlUrl)return;const t=e.htmlUrl.trim(),i=t.startsWith("<"),s=!i&&(t.includes("output=vast")||t.includes("gampad/ads")||t.endsWith(".xml"));if(!(!i&&!s))try{let r;if(i)r=t;else{const l=await fetch(t,{credentials:"same-origin"});if(!l.ok)return;r=await l.text()}if(!r||!r.includes("<VAST"))return;const a=tr(r);if(!a)return;const n=e;a.imageUrl?(n.imageUrl=a.imageUrl,n.htmlUrl=void 0,n.useIframe=!1):a.htmlUrl?(n.htmlUrl=a.htmlUrl,n.useIframe=!0):a.htmlContent&&(n.htmlContent=a.htmlContent,n.htmlUrl=void 0,n.useIframe=!1),a.width&&(n.width=a.width),a.height&&(n.height=a.height),a.clickThroughUrl&&!n.clickThroughUrl&&(n.clickThroughUrl=a.clickThroughUrl),a.trackingUrls&&a.trackingUrls.length>0&&(n.trackingUrls=[...n.trackingUrls||[],...a.trackingUrls])}catch{}}recalculateLayout(){var m,v,y,b,S;if(!this.containerElement||!this.adContainer||this.isExternalSlot)return;const e=this.adContainer.clientWidth||640,t=this.adContainer.clientHeight||360,i=(m=this.currentAd)!=null&&m.maxWidth?Math.min(e,this.currentAd.maxWidth):e*.8,s=(v=this.currentAd)!=null&&v.maxHeight?Math.min(t,this.currentAd.maxHeight):t*.18,r=this.getRenderMode(),a=!!((y=this.currentAd)!=null&&y.width)&&!!((b=this.currentAd)!=null&&b.height),n=()=>{this.containerElement.style.maxWidth="",this.containerElement.style.maxHeight="",this.containerElement.style.width=`${Math.round(i)}px`,this.containerElement.style.height=`${Math.round(s)}px`};if(r==="iframe"&&!a){n();return}if((r==="string"||r==="template")&&!a){this.containerElement.style.width="auto",this.containerElement.style.height="auto",this.containerElement.style.maxWidth=`${Math.round(i)}px`,this.containerElement.style.maxHeight=`${Math.round(s)}px`;const T=this.containerElement.getBoundingClientRect();(T.width<4||T.height<4)&&n();return}this.containerElement.style.maxWidth="",this.containerElement.style.maxHeight="";const l=this.intrinsicWidth||480,o=this.intrinsicHeight||70,d=Math.min(i,l),h=Math.min(s,o),f=((S=this.currentAd)==null?void 0:S.responsive)!==!1?Math.min(1,d/l,h/o):1,p=Math.round(l*f),g=Math.round(o*f);this.containerElement.style.width=`${p}px`,this.containerElement.style.height=`${g}px`}show(){var e;this.state!=="destroyed"&&(this.containerElement&&(this.containerElement.style.display="block",this.recalculateLayout()),this.state="visible",this.controller.emit("htmloverlayshown",{adId:(e=this.currentAd)==null?void 0:e.id}),this.currentAd&&(this.fireTrackingEvents("impression"),this.fireTrackingEvents("creativeView"),this.scheduleDurationTimer()))}hide(){var e;this.state!=="destroyed"&&(this.clearDurationTimer(),this.containerElement&&(this.containerElement.style.display="none"),this.state="hidden",this.controller.emit("htmloverlayhidden",{adId:(e=this.currentAd)==null?void 0:e.id}))}close(){var t;if(this.state==="destroyed")return;const e=(t=this.currentAd)==null?void 0:t.id;this.fireTrackingEvents("close"),this.destroy(),this.controller.emit("htmloverlayclosed",{adId:e})}updateOverlay(e){!this.currentAd||this.state==="destroyed"||(this.currentAd={...this.currentAd,...e},e.width!==void 0&&(this.intrinsicWidth=e.width),e.height!==void 0&&(this.intrinsicHeight=e.height),this.containerElement&&(this.applyStylesAndPositioning(this.currentAd,this.containerElement),this.recalculateLayout()),this.controller.emit("htmloverlayupdated",{adId:this.currentAd.id}))}destroy(){this.state!=="destroyed"&&(this.state="destroyed",this.clearDurationTimer(),this.clearCloseDelayTimer(),this.destroyController.abort(),this.resizeObserver&&(this.resizeObserver.disconnect(),this.resizeObserver=null),this.iframeElement&&(this.iframeElement.src="about:blank",this.iframeElement=null),this.containerElement&&(this.containerElement.parentNode&&this.containerElement.parentNode.removeChild(this.containerElement),this.containerElement=null),this.contentWrapper=null,this.currentAd=null,this.firedEvents.clear())}scheduleDurationTimer(){this.clearDurationTimer(),this.currentAd&&this.currentAd.duration>0&&(this.durationTimer=setTimeout(()=>{this.handleDurationComplete()},this.currentAd.duration*1e3))}handleDurationComplete(){var e;this.state!=="destroyed"&&(this.fireTrackingEvents("complete"),this.controller.emit("htmloverlaycompleted",{adId:(e=this.currentAd)==null?void 0:e.id}),this.close())}clearDurationTimer(){this.durationTimer&&(clearTimeout(this.durationTimer),this.durationTimer=null)}clearCloseDelayTimer(){this.closeDelayTimer&&(clearTimeout(this.closeDelayTimer),this.closeDelayTimer=null)}renderImage(e,t){return new Promise((i,s)=>{if(!e.imageUrl){s(new Error("Missing image URL for image rendering"));return}const r=document.createElement("img");r.alt=e.title||"Advertisement",r.style.width="100%",r.style.height="100%",r.style.objectFit="contain",r.style.display="block";const a=setTimeout(()=>{s(new Error("HTML overlay image creative load timeout"))},5e3);r.onload=()=>{clearTimeout(a);const n=e;!n.width&&r.naturalWidth&&(n.width=r.naturalWidth),!n.height&&r.naturalHeight&&(n.height=r.naturalHeight),this.intrinsicWidth=e.width||r.naturalWidth||480,this.intrinsicHeight=e.height||r.naturalHeight||70,i()},r.onerror=()=>{clearTimeout(a),s(new Error("HTML overlay image creative failed to load"))},r.src=e.imageUrl,t.appendChild(r)})}renderIframe(e,t){return new Promise((i,s)=>{this.iframeElement=document.createElement("iframe");const a=e.iframeSandbox||"allow-scripts allow-popups allow-same-origin allow-forms",n=Li(a,{srcUrl:e.htmlUrl||null,isSrcDoc:!e.htmlUrl&&!!e.htmlContent});if(this.iframeElement.setAttribute("sandbox",n),this.iframeElement.setAttribute("referrerpolicy","no-referrer"),this.iframeElement.setAttribute("scrolling","no"),this.iframeElement.style.width="100%",this.iframeElement.style.height="100%",this.iframeElement.style.border="none",this.iframeElement.style.overflow="hidden",this.iframeElement.style.backgroundColor="transparent",e.htmlUrl&&e.trustedOrigins&&e.trustedOrigins.length>0)try{const o=new URL(e.htmlUrl,window.location.href).origin,d=new URL(o).hostname;if(!e.trustedOrigins.some(u=>u==="*"||u===o||u===d)){s(new Error(`HTML overlay URL origin "${o}" is not in trusted origins.`));return}}catch{}const l=setTimeout(()=>{s(new Error("HTML overlay iframe load timeout"))},8e3);if(this.iframeElement.addEventListener("load",()=>{clearTimeout(l),i()},{once:!0}),this.iframeElement.addEventListener("error",()=>{clearTimeout(l),s(new Error("HTML overlay iframe load failed"))},{once:!0}),e.htmlUrl)this.iframeElement.src=e.htmlUrl;else if(e.htmlContent)this.iframeElement.srcdoc=e.htmlContent;else{clearTimeout(l),s(new Error("HTML url or content is required for iframe rendering"));return}t.appendChild(this.iframeElement)})}renderTemplate(e,t){if(!e.htmlTemplateId)return;const i=document.getElementById(e.htmlTemplateId);if(!i)throw new Error(`Template element not found with ID: ${e.htmlTemplateId}`);const s=document.importNode(i.content,!0);t.appendChild(s)}renderHtmlString(e,t){if(!e.htmlContent)return;const i=document.createElement("div");i.style.width="100%",i.style.height="100%",e.sanitizeHtml?i.innerHTML=e.sanitizeHtml(e.htmlContent):i.innerHTML=e.htmlContent,t.appendChild(i)}setupCloseButton(){if(!this.containerElement||!this.currentAd)return;const e=this.currentAd.closeButton;if(e===!1)return;const t=document.createElement("button");t.className=typeof e=="object"&&e.className?`html-overlay-close-btn ${e.className}`:"html-overlay-close-btn";const i=typeof e=="object"&&e.label?e.label:"Close Advertisement";t.setAttribute("aria-label",i),t.innerText=typeof e=="object"&&e.label?e.label:"×",t.style.position="absolute",t.style.top="-10px",t.style.right="-10px",t.style.zIndex="1006",t.style.cursor="pointer",t.style.background="rgba(0, 0, 0, 0.85)",t.style.color="#ffffff",t.style.border="2px solid rgba(255, 255, 255, 0.8)",t.style.borderRadius="50%",t.style.width="24px",t.style.height="24px",t.style.fontSize="14px",t.style.lineHeight="20px",t.style.textAlign="center",t.style.padding="0",t.style.boxShadow="0 2px 6px rgba(0,0,0,0.5)",t.style.pointerEvents="auto",typeof e=="object"&&e.styleOverrides&&Object.entries(e.styleOverrides).forEach(([r,a])=>{t.style[r]=String(a)});const s=this.currentAd.closeDelay??(typeof e=="object"?e.delaySeconds:0)??0;s>0&&(t.style.display="none",this.closeDelayTimer=setTimeout(()=>{t&&this.state!=="destroyed"&&(t.style.display="block")},s*1e3)),t.addEventListener("click",r=>{r.stopPropagation(),this.close()},{signal:this.destroyController.signal}),this.containerElement.appendChild(t)}setupKeyboardAccessibility(){window.addEventListener("keydown",e=>{e.key==="Escape"&&this.state==="visible"&&this.close()},{signal:this.destroyController.signal})}setupInteractionHandlers(){this.contentWrapper&&(this.contentWrapper.addEventListener("mouseenter",()=>{this.interactionCount++,this.fireTrackingEvents("creativeView")},{signal:this.destroyController.signal}),this.contentWrapper.addEventListener("focusin",()=>{this.interactionCount++},{signal:this.destroyController.signal}),this.contentWrapper.addEventListener("click",()=>{var e,t;if(this.clickCount++,this.controller.emit("htmloverlayclick",{adId:(e=this.currentAd)==null?void 0:e.id}),this.fireTrackingEvents("click"),(t=this.currentAd)!=null&&t.clickThroughUrl)try{window.open(this.currentAd.clickThroughUrl,"_blank","noopener,noreferrer")}catch(i){const s=i instanceof Error?i.message:String(i);this.errors.push(`Click-through navigation failed: ${s}`)}},{signal:this.destroyController.signal}))}applyStylesAndPositioning(e,t){var r;if(this.isExternalSlot||!!e.externalSlot){t.style.position="relative",t.style.margin="0 auto",t.style.display||(t.style.display="none"),t.style.pointerEvents=e.pointerEvents||"auto";return}switch(t.style.top="",t.style.bottom="",t.style.left="",t.style.right="",t.style.transform="",t.style.position="absolute",t.style.zIndex=String(((r=e.overlayStyle)==null?void 0:r.zIndex)||e.zIndex||"1002"),t.style.overflow="visible",t.style.opacity=String(e.opacity!==void 0?e.opacity:1),t.style.pointerEvents=e.pointerEvents||"auto",t.style.display||(t.style.display="none"),e.margin&&(t.style.margin=e.margin),e.padding&&(t.style.padding=e.padding),e.position||"bottom"){case"top":t.style.top="10px",t.style.left="50%",t.style.transform="translateX(-50%)";break;case"left":t.style.left="10px",t.style.top="50%",t.style.transform="translateY(-50%)";break;case"right":t.style.right="10px",t.style.top="50%",t.style.transform="translateY(-50%)";break;case"center":t.style.top="50%",t.style.left="50%",t.style.transform="translate(-50%, -50%)";break;case"bottom":default:t.style.bottom="var(--player-overlay-safe-bottom, calc(20px + 64px + 12px))",t.style.left="50%",t.style.transform="translateX(-50%)";break}e.overlayStyle&&Object.entries(e.overlayStyle).forEach(([a,n])=>{t.style[a]=String(n)})}fireTrackingEvents(e){const t=e.toLowerCase();if(["impression","creativeview","close","complete"].includes(t)){if(this.firedEvents.has(t))return;this.firedEvents.add(t)}if(!this.currentAd||!this.currentAd.trackingUrls)return;this.currentAd.trackingUrls.filter(r=>r.event&&r.event.toLowerCase()===t).forEach(r=>this.trackingManager.trackUrl(r.url))}handleError(e){this.errors.push(e),this.controller.emit("htmloverlayerror",{message:e}),this.destroy()}}function rr(c,e){const t=new Set,i=[];for(const s of e){const r=s.width*s.height;let a=-1,n=1/0;c.forEach((l,o)=>{if(t.has(o))return;const d=l.width??0,h=l.height??0,u=Math.abs(d*h-r);u<n&&(n=u,a=o)}),a>=0&&(t.add(a),i.push({slot:s,companion:c[a]}))}return i}const ar={[w.IDLE]:[w.REQUESTING,w.LOADED,w.PLAYING,w.ERROR,w.CONTENT_RESUMING],[w.REQUESTING]:[w.LOADED,w.PLAYING,w.ERROR,w.CONTENT_RESUMING,w.IDLE],[w.LOADED]:[w.REQUESTING,w.PLAYING,w.PAUSED,w.BUFFERING,w.ERROR,w.CONTENT_RESUMING,w.IDLE],[w.PLAYING]:[w.REQUESTING,w.PAUSED,w.BUFFERING,w.SKIPPING,w.ENDED,w.ERROR,w.CONTENT_RESUMING,w.IDLE],[w.PAUSED]:[w.REQUESTING,w.PLAYING,w.BUFFERING,w.SKIPPING,w.ENDED,w.ERROR,w.CONTENT_RESUMING,w.IDLE],[w.BUFFERING]:[w.REQUESTING,w.PLAYING,w.PAUSED,w.ENDED,w.ERROR,w.CONTENT_RESUMING,w.IDLE],[w.SKIPPING]:[w.REQUESTING,w.PLAYING,w.LOADED,w.CONTENT_RESUMING,w.ERROR,w.IDLE],[w.ENDED]:[w.REQUESTING,w.PLAYING,w.LOADED,w.CONTENT_RESUMING,w.ERROR,w.IDLE],[w.ERROR]:[w.REQUESTING,w.CONTENT_RESUMING,w.IDLE],[w.CONTENT_RESUMING]:[w.REQUESTING,w.IDLE]};class nr{constructor(){this.providers=new Map,this.activeProviderName=null}registerProvider(e,t){this.providers.set(e,t)}getProvider(e){return this.providers.get(e)}unregisterProvider(e){this.activeProviderName===e&&(this.activeProviderName=null),this.providers.delete(e)}selectProvider(e){this.activeProviderName=e}getActiveProvider(){return this.activeProviderName?this.providers.get(this.activeProviderName):void 0}getActiveProviderName(){return this.activeProviderName}getCapabilities(e){const t=this.providers.get(e);return t?t.capabilities:null}onSourceLoaded(e){this.providers.forEach(t=>{try{typeof t.onSourceLoaded=="function"&&t.onSourceLoaded(e)}catch(i){console.error("[ProviderManager] Error running onSourceLoaded for provider:",t.name,i)}})}destroy(){this.providers.forEach(e=>{try{e.destroy()}catch(t){console.error("[ProviderManager] Error destroying provider:",t)}}),this.providers.clear(),this.activeProviderName=null}}class or{constructor(){this.snapshot=null}capture(e){const t=e.getState();this.snapshot={currentTime:t.currentTime,paused:!t.isPlaying,playbackRate:t.playbackRate,muted:t.isMuted,volume:t.volume,activeAudioTrack:t.activeAudioTrack,activeSubtitleTrackId:t.activeSubtitleTrackId,activeQuality:t.qualities.indexOf(t.activeQuality),isFullscreen:t.isFullscreen,pictureInPicture:t.pictureInPicture,isAtLiveEdge:t.isAtLiveEdge,liveLatency:t.liveLatency}}restore(e){if(!this.snapshot)return;const t=this.snapshot;try{e.setVolume(t.volume),e.setMuted(t.muted),e.setPlaybackRate(t.playbackRate),t.activeSubtitleTrackId!==null&&e.setSubtitleTrack(t.activeSubtitleTrackId),t.activeAudioTrack!==-1&&e.setAudioTrack(t.activeAudioTrack);const i=e.getState(),s=i.qualities.indexOf(i.activeQuality);t.activeQuality!==-1&&t.activeQuality!==s&&e.setQuality(t.activeQuality),!i.isLive&&Math.abs(i.currentTime-t.currentTime)>.35&&e.seek(t.currentTime),t.isFullscreen&&!e.getState().isFullscreen&&e.toggleFullscreen(),t.pictureInPicture&&!e.getState().pictureInPicture&&e.enterPictureInPicture().catch(()=>{});try{const r=e.play();r&&typeof r.catch=="function"&&r.catch(a=>{console.warn("[ContentSnapshot] Failed to resume content playback:",a)})}catch(r){console.warn("[ContentSnapshot] Failed to trigger content playback:",r)}}catch(i){console.error("[ContentSnapshot] Error restoring content state:",i)}finally{this.snapshot=null}}clear(){this.snapshot=null}exists(){return this.snapshot!==null}}class Ki{constructor(){this.activeBreak=null,this.pendingBreaks=[],this.completedBreaks=[],this.cancelledBreaks=[]}registerBreak(e){this.pendingBreaks.push(e),this.pendingBreaks.sort((t,i)=>t.timeOffset-i.timeOffset)}activateBreak(e){this.activeBreak=e,this.pendingBreaks=this.pendingBreaks.filter(t=>t.id!==e.id)}completeBreak(){this.activeBreak&&(this.completedBreaks.push(this.activeBreak),this.activeBreak=null)}cancelBreak(e){var t;if(((t=this.activeBreak)==null?void 0:t.id)===e)this.cancelledBreaks.push(this.activeBreak),this.activeBreak=null;else{const i=this.pendingBreaks.findIndex(s=>s.id===e);i!==-1&&(this.cancelledBreaks.push(this.pendingBreaks[i]),this.pendingBreaks.splice(i,1))}}clearBreaks(){this.activeBreak=null,this.pendingBreaks=[],this.completedBreaks=[],this.cancelledBreaks=[]}getActiveBreak(){return this.activeBreak}getPendingBreaks(){return this.pendingBreaks}getCompletedBreaks(){return this.completedBreaks}getCancelledBreaks(){return this.cancelledBreaks}}class lr{constructor(){this.activeToken=0}generateToken(){return this.activeToken++,this.activeToken}isValid(e){return e===this.activeToken}invalidateAll(){this.activeToken++}}class cr{constructor(){this.timers=new Map}set(e,t,i){this.clear(e);const s=setTimeout(()=>{this.timers.delete(e),t()},i);this.timers.set(e,s)}clear(e){const t=this.timers.get(e);t&&(clearTimeout(t),this.timers.delete(e))}clearAll(){this.timers.forEach(e=>clearTimeout(e)),this.timers.clear()}}class Wi{constructor(){this.name="ads-manager",this.state=w.IDLE,this.providerManager=new nr,this.contentSnapshot=new or,this.adBreakManager=new Ki,this.asyncGuard=new lr,this.timeoutManager=new cr,this.htmlOverlayRenderer=null,this.companionRenderers=[],this.concurrentOverlayRenderers=[],this.adContainer=null,this.isInterceptionActive=!1,this.currentAd=null,this.requestedCount=0,this.playedCount=0,this.completedCount=0,this.skippedCount=0,this.errorCount=0,this.recoveryCount=0,this.timeoutCount=0,this.cancelledCount=0,this.providerFailuresCount=0,this.activeOperations=0}install(e){this.controller=e,this.controller.registerPlaybackInterceptor(this),this.controller.on("htmloverlayclosed",()=>{this.currentAd&&this.isHtmlOverlayCreative(this.currentAd)&&this.endAdBreak()}),this.updatePlayerState(),this.triggerLifecycleHook("onProviderLoaded")}destroy(){if(this.triggerLifecycleHook("onDestroy"),this.timeoutManager.clearAll(),this.asyncGuard.invalidateAll(),this.clearCompanions(),this.clearConcurrentOverlays(),this.htmlOverlayRenderer){try{this.htmlOverlayRenderer.destroy()}catch{}this.htmlOverlayRenderer=null}this.controller&&this.controller.unregisterPlaybackInterceptor(this),this.providerManager.destroy(),this.adBreakManager.clearBreaks(),this.contentSnapshot.clear(),this.currentAd=null,this.state=w.IDLE,this.isInterceptionActive=!1}getProviderManager(){return this.providerManager}getAdBreakManager(){return this.adBreakManager}getAdState(){return this.state}getSavedContentSnapshot(){return this.contentSnapshot}transitionTo(e){if(this.state===e)return!0;if(e===w.IDLE){const i=this.state;return this.state=e,this.isInterceptionActive=!1,this.updatePlayerState(),this.triggerLifecycleHook("onStateChanged",i,e),!0}const t=ar[this.state];if(t&&t.includes(e)){const i=this.state;return this.state=e,this.updateDiagnosticsMetrics(i,e),this.updatePlayerState(),this.dispatchStateEvents(i,e),this.triggerLifecycleHook("onStateChanged",i,e),!0}else return console.warn(`[AdsManager] Rejected state transition: ${this.state} -> ${e}`),!1}updateDiagnosticsMetrics(e,t){t===w.REQUESTING?this.requestedCount++:t===w.PLAYING&&e!==w.PAUSED&&e!==w.BUFFERING?this.playedCount++:t===w.ENDED?this.completedCount++:t===w.SKIPPING?this.skippedCount++:t===w.ERROR&&this.errorCount++}dispatchStateEvents(e,t){var i,s;if(this.controller)switch(t){case w.REQUESTING:this.controller.emit("adloadstart",{adTagUrl:((s=(i=this.controller.config)==null?void 0:i.ads)==null?void 0:s.tagUrl)??""});break;case w.LOADED:this.currentAd&&this.controller.emit("adloaded",{ad:this.currentAd});break;case w.PLAYING:e===w.PAUSED?this.currentAd&&this.controller.emit("adresume",{ad:this.currentAd}):this.currentAd&&this.controller.emit("adstart",{ad:this.currentAd});break;case w.PAUSED:this.currentAd&&this.controller.emit("adpause",{ad:this.currentAd});break;case w.SKIPPING:this.currentAd&&this.controller.emit("adskip",{ad:this.currentAd});break;case w.ENDED:this.currentAd&&this.controller.emit("adcomplete",{ad:this.currentAd});break;case w.ERROR:break}}startAdBreak(e,t){if(this.controller.getState().sourceType==="embed"){this.triggerAdError({type:ie.CONFIGURATION,code:900,message:"VAST ads are not supported for embed (YouTube/Vimeo) sources."});return}this.activeOperations++,this.triggerLifecycleHook("onBreakStarted",e),this.adBreakManager.activateBreak(e);const i=e.ads[0],s=i&&this.isHtmlOverlayCreative(i);if(!!i&&!i.linear&&!s&&!!i.companions&&i.companions.length>0)this.isInterceptionActive=!1,this.currentAd=i,this.controller.emit("adbreakstart",{adId:e.id,duration:e.duration}),this.transitionTo(w.REQUESTING),this.transitionTo(w.LOADED),this.showCompanions(i.companions),this.adBreakManager.completeBreak(),this.controller.emit("adbreakend"),this.transitionTo(w.IDLE),this.activeOperations=Math.max(0,this.activeOperations-1);else if(s)this.isInterceptionActive=!1,this.currentAd=i,this.controller.emit("adbreakstart",{adId:e.id,duration:e.duration}),this.transitionTo(w.REQUESTING),this.playHtmlOverlay(i);else{if(this.isInterceptionActive=!0,this.contentSnapshot.capture(this.controller),this.triggerLifecycleHook("onContentPaused"),!(t!=null&&t.skipVideoOwnership)){this.isInterceptionActive=!1;try{this.controller.getVideoElement().pause()}catch(a){console.error("[AdsManager] Pause main content error:",a)}this.isInterceptionActive=!0}this.controller.emit("adbreakstart",{adId:e.id,duration:e.duration}),this.transitionTo(w.REQUESTING)}}skipAd(){const e=this.providerManager.getActiveProvider();if(e)try{typeof e.skipAd=="function"?e.skipAd():typeof e.destroy=="function"&&e.destroy()}catch(t){console.error("[AdsManager] Error skipping provider ad:",t)}this.transitionTo(w.SKIPPING),this.controller.emit("adskip"),this.endAdBreak()}endAdBreak(){this.transitionTo(w.CONTENT_RESUMING),this.triggerLifecycleHook("onBreakCompleted"),this.clearCompanions(),this.clearConcurrentOverlays(),this.adBreakManager.completeBreak(),this.contentSnapshot.exists()&&(this.isInterceptionActive=!1,this.contentSnapshot.restore(this.controller),this.triggerLifecycleHook("onContentResumed")),this.isInterceptionActive=!1,this.controller.emit("adbreakend"),this.transitionTo(w.IDLE),this.activeOperations=Math.max(0,this.activeOperations-1)}recover(e){if(this.recoveryCount++,console.warn(`[AdsManager] Entering recovery path due to: ${e}`),this.triggerLifecycleHook("onRecovery",e),this.timeoutManager.clearAll(),this.asyncGuard.invalidateAll(),this.htmlOverlayRenderer){try{this.htmlOverlayRenderer.destroy()}catch{}this.htmlOverlayRenderer=null}this.currentAd=null,this.endAdBreak()}triggerAdError(e){this.errorCount++,this.providerFailuresCount++,this.controller.emit("aderror",{error:e}),this.recover(`aderror: ${e.message}`)}scheduleTimeout(e,t,i){const s=this.asyncGuard.generateToken();this.timeoutManager.set(e,()=>{this.asyncGuard.isValid(s)&&(this.timeoutCount++,console.warn(`[TimeoutManager] Expired operation timeout: "${e}"`),this.recover(i))},t)}cancelTimeout(e){this.timeoutManager.clear(e)}setAdContainer(e){this.adContainer=e}getAdContainer(){var e,t;return this.adContainer||((t=(e=this.controller)==null?void 0:e.getVideoElement())==null?void 0:t.parentElement)||null}createProviderContext(e){var i;const t=e||this.getAdContainer()||(typeof document<"u"?document.body:null);return t&&t instanceof HTMLElement&&(this.adContainer=t),{videoElement:this.controller.getVideoElement(),adContainer:this.adContainer||t,controller:this.controller,config:((i=this.controller.config)==null?void 0:i.ads)||{}}}setCurrentAd(e){const t=this.currentAd!==e;this.currentAd=e,t&&e&&this.controller.updateStatePublic({adCurrentTime:0,adRemainingTime:e.duration,adDuration:e.duration}),this.updatePlayerState()}updatePlayerState(){var n,l,o;if(!this.controller)return;const e=this.currentAd?this.currentAd.linear!==!1:!0,t=(this.state===w.REQUESTING||this.state===w.LOADED||this.state===w.PLAYING||this.state===w.PAUSED||this.state===w.BUFFERING||this.state===w.SKIPPING||this.state===w.ENDED)&&e,i=this.state===w.REQUESTING||this.state===w.LOADED,s=this.adBreakManager.getActiveBreak(),r=this.providerManager.getActiveProviderName(),a=this.controller.getState();this.controller.updateStatePublic({isAdPlaying:t,isAdLoading:i,currentAd:this.currentAd,currentAdBreak:s,adProvider:r,adCurrentTime:t&&this.currentAd?a.adCurrentTime??0:null,adRemainingTime:t&&this.currentAd?a.adRemainingTime??this.currentAd.duration:null,adDuration:t&&this.currentAd?this.currentAd.duration||a.adDuration||0:null,canSkipAd:a.canSkipAd??((n=this.currentAd)==null?void 0:n.skippable)??!1,skipAvailableAt:a.skipAvailableAt??((l=this.currentAd)==null?void 0:l.skipOffset)??null,adPosition:this.currentAd?(s==null?void 0:s.ads.indexOf(this.currentAd))??null:null,adLinear:((o=this.currentAd)==null?void 0:o.linear)??null,adMuted:this.controller.getState().isMuted})}play(){if(!this.isInterceptionActive)return!1;const e=this.providerManager.getActiveProvider();if(e){try{e.resumeAd(),this.transitionTo(w.PLAYING)}catch(t){console.error("[AdsManager] Play ad execution failed:",t)}return!0}return!0}pause(){if(!this.isInterceptionActive)return!1;const e=this.providerManager.getActiveProvider();if(e){try{e.pauseAd(),this.transitionTo(w.PAUSED)}catch(t){console.error("[AdsManager] Pause ad execution failed:",t)}return!0}return!0}seek(e){return!!this.isInterceptionActive}setVolume(e){if(!this.isInterceptionActive)return!1;const t=this.providerManager.getActiveProvider();if(t)try{t.setVolume(e)}catch{}return!1}setMuted(e){if(!this.isInterceptionActive)return!1;const t=this.providerManager.getActiveProvider();if(t)try{t.setMuted(e)}catch{}return this.controller.updateStatePublic({adMuted:e}),!1}triggerLifecycleHook(e,...t){}liveEdgeSyncHook(){}dvrPositionHook(){}catchUpPlaybackHook(){}liveSourceSwitchHook(){}playlistItemStartHook(){}playlistItemEndHook(){}autoplayNextItemHook(){}playlistRepeatHook(){}playlistNavigationHook(){}getHtmlOverlayRenderer(){return this.htmlOverlayRenderer}applyDefaultSanitizer(e){var i,s,r;if(e.sanitizeHtml||!e.htmlContent)return e;const t=((r=(s=(i=this.controller.config)==null?void 0:i.ads)==null?void 0:s.ui)==null?void 0:r.sanitizeHtml)||Vs;return{...e,sanitizeHtml:t}}isHtmlOverlayCreative(e){return e&&!e.linear&&(!!e.htmlContent||!!e.htmlUrl||!!e.htmlTemplateId||!!e.imageUrl)}showCompanions(e){var o,d;if(!e||e.length===0)return;this.clearCompanions();const t=(d=(o=this.controller.config)==null?void 0:o.ads)==null?void 0:d.ui,i=t==null?void 0:t.companionSlots;if(i&&i.length>0){rr(e,i).forEach(({slot:u,companion:f})=>{const p=document.getElementById(u.elementId);if(!p){this.controller.emit("companionerror",{adId:f.id,slotId:u.id,reason:`elementId "${u.elementId}" not found`});return}const g=new st(this.controller,p,void 0,!0);this.companionRenderers.push(g),f=this.applyDefaultSanitizer(f),g.loadAd(f).then(m=>{m?(g.show(),this.controller.emit("companionshown",{adId:f.id,slotId:u.id})):(this.fireOverlayErrorPixels(f),this.controller.emit("companionerror",{adId:f.id,slotId:u.id,reason:"load failed"}))})});return}const s=this.applyDefaultSanitizer(e[0]),r=t==null?void 0:t.adOverlaySlot,a=r?document.querySelector(r):null;if(!r){console.warn('[AdsManager] VAST response included a Companion ad, but no "ads.ui.companionSlots" or "ads.ui.adOverlaySlot" is configured, so it cannot be displayed. Configure one to show companion ads.'),this.controller.emit("companionerror",{adId:s.id,reason:"no companionSlots or adOverlaySlot configured"});return}if(!a){console.warn(`[AdsManager] "ads.ui.adOverlaySlot" ("${r}") did not match any element in the DOM.`),this.controller.emit("companionerror",{adId:s.id,reason:`adOverlaySlot "${r}" not found in DOM`});return}const n=a,l=new st(this.controller,n,void 0,!0);this.companionRenderers.push(l),l.loadAd(s).then(h=>{h?l.show():this.fireOverlayErrorPixels(s)})}clearCompanions(){this.companionRenderers.forEach(e=>{try{e.destroy()}catch{}}),this.companionRenderers=[]}showConcurrentOverlays(e){var i;if(!e||e.length===0)return;this.clearConcurrentOverlays();const t=this.adContainer||((i=this.controller.getVideoElement())==null?void 0:i.parentElement);t&&e.forEach(s=>{const r=this.applyDefaultSanitizer(s),a=new st(this.controller,t,void 0,!1);this.concurrentOverlayRenderers.push(a),a.loadAd(r).then(n=>{n?a.show():this.fireOverlayErrorPixels(r)})})}clearAuxiliaryOverlays(){this.clearCompanions(),this.clearConcurrentOverlays()}clearConcurrentOverlays(){this.concurrentOverlayRenderers.forEach(e=>{try{e.destroy()}catch{}}),this.concurrentOverlayRenderers=[]}fireOverlayErrorPixels(e){const t=e==null?void 0:e.errorUrls;!t||t.length===0||t.forEach(i=>{const s=i.replace(/\[ERRORCODE\]/g,"900");try{typeof navigator<"u"&&navigator.sendBeacon?navigator.sendBeacon(s):typeof fetch<"u"&&fetch(s,{method:"GET",mode:"no-cors",keepalive:!0}).catch(()=>{})}catch{}})}async showOverlay(e){var i;const t={id:e.id||`overlay-${Date.now()}`,title:e.title||"HTML Overlay Ad",duration:e.duration||0,linear:!1,skippable:!1,...e};return await this.playHtmlOverlay(t),((i=this.htmlOverlayRenderer)==null?void 0:i.getLifecycleState())==="visible"}hideOverlay(){this.htmlOverlayRenderer&&this.htmlOverlayRenderer.hide()}closeOverlay(){this.htmlOverlayRenderer&&(this.htmlOverlayRenderer.close(),this.htmlOverlayRenderer=null)}updateOverlay(e){this.htmlOverlayRenderer&&this.htmlOverlayRenderer.updateOverlay(e)}async playHtmlOverlay(e){var s;const t=this.adContainer||((s=this.controller.getVideoElement())==null?void 0:s.parentNode);if(!t){this.triggerAdError({type:ie.PLAYBACK,code:400,message:"Ad container not found for HTML overlay rendering"});return}if(this.htmlOverlayRenderer)try{this.htmlOverlayRenderer.destroy()}catch{}if(this.htmlOverlayRenderer=new st(this.controller,t),e=this.applyDefaultSanitizer(e),this.setCurrentAd(e),this.transitionTo(w.LOADED),!await this.htmlOverlayRenderer.loadAd(e)){this.fireOverlayErrorPixels(e);return}this.transitionTo(w.PLAYING),this.htmlOverlayRenderer.show()}onSourceLoaded(e){this.triggerLifecycleHook("onSourceChanged",e),this.handleSourceSwitch()}handleSourceSwitch(){if(this.timeoutManager.clearAll(),this.asyncGuard.invalidateAll(),this.adBreakManager.clearBreaks(),this.contentSnapshot.clear(),this.clearCompanions(),this.clearConcurrentOverlays(),this.htmlOverlayRenderer){try{this.htmlOverlayRenderer.destroy()}catch{}this.htmlOverlayRenderer=null}this.providerManager.onSourceLoaded(),this.currentAd=null,this.state=w.IDLE,this.isInterceptionActive=!1,this.activeOperations=0,this.updatePlayerState()}getDiagnosticsStats(){return{totalAdsRequested:this.requestedCount,totalAdsPlayed:this.playedCount,totalAdsCompleted:this.completedCount,totalAdsSkipped:this.skippedCount,totalAdErrors:this.errorCount,recoveryCount:this.recoveryCount,timeoutCount:this.timeoutCount,cancelledAdsCount:this.cancelledCount,providerFailures:this.providerFailuresCount,averageLoadTimeMs:0,averageResumeTimeMs:0,activeOperationsCount:this.activeOperations}}}function dr(c,e){if(c===void 0)return null;if(typeof c=="number")return c;const t=c.trim();if(!t.endsWith("%")){const s=Number(t);return isNaN(s)?null:s}const i=parseFloat(t);return isNaN(i)||!isFinite(e)||e<=0?null:i/100*e}function hr(c,e,t,i){const s=[];for(const r of c){if(r.isPlayed)continue;let a=!1;if(r.type==="preroll")a=e<=3;else if(r.type==="postroll")a=i||t>0&&e>=t-.5;else{const n=r.timeOffset??0;a=e>=n&&e-n<=2.5}a&&s.push(r.id)}return s}class ur{constructor(e,t,i){this.controller=e,this.getProviderByName=t,this.showOverlay=i,this.breaks=[],this.timeUpdateListener=null,this.endedListener=null,this.nextId=0,this.attach()}schedule(e){const t=`sched-${++this.nextId}`;return this.breaks.push({...e,id:t,isPlayed:!1}),t}hasActiveBreaks(){return this.breaks.some(e=>!e.isPlayed)}unschedule(e){this.breaks=this.breaks.filter(t=>t.id!==e)}clear(){this.breaks=[]}destroy(){const e=this.controller.getVideoElement();this.timeUpdateListener&&e.removeEventListener("timeupdate",this.timeUpdateListener),this.endedListener&&e.removeEventListener("ended",this.endedListener),this.breaks=[]}attach(){const e=this.controller.getVideoElement(),t=()=>this.evaluate(e.currentTime,e.duration||0,!1),i=()=>this.evaluate(e.duration||0,e.duration||0,!0);e.addEventListener("timeupdate",t),e.addEventListener("ended",i),this.timeUpdateListener=t,this.endedListener=i}evaluate(e,t,i){if(this.breaks.length===0)return;const s=[];for(const a of this.breaks){if(a.isPlayed){s.push({id:a.id,type:a.type,timeOffset:a.resolvedTimeOffset,isPlayed:!0});continue}if(a.type==="midroll"){if(a.resolvedTimeOffset===void 0){const n=dr(a.timeOffset,t);if(n===null)continue;a.resolvedTimeOffset=n}s.push({id:a.id,type:a.type,timeOffset:a.resolvedTimeOffset,isPlayed:!1})}else s.push({id:a.id,type:a.type,timeOffset:void 0,isPlayed:!1})}const r=hr(s,e,t,i);if(r.length!==0)for(const a of r){const n=this.breaks.find(l=>l.id===a);n&&(n.isPlayed=!0,this.trigger(n))}}async trigger(e){if(this.controller.getState().sourceType==="embed"){this.controller.emit("aderror",{error:{type:ie.CONFIGURATION,code:900,message:"VAST ads are not supported for embed (YouTube/Vimeo) sources."}});return}if(e.provider==="HTML_OVERLAY"){if(!e.overlay)return;await this.showOverlay(e.overlay);return}if(!e.tagUrl)return;const t=this.getProviderByName(e.provider??"VAST");if(!t)return;(await t.requestAds(e.tagUrl)).success&&await t.playAdBreak(e.type)}}function Kt(c){if(!c)return 0;const e=c.trim().split(":");if(e.length===3){const i=parseInt(e[0],10)||0,s=parseInt(e[1],10)||0,r=parseFloat(e[2])||0;return i*3600+s*60+r}const t=parseFloat(c);return isNaN(t)?0:t}function ji(c){return!c||c==="start"?0:c==="end"||c.endsWith("%")?-1:Kt(c)}function pr(c){if(typeof window>"u"||typeof DOMParser>"u")return null;try{const t=new DOMParser().parseFromString(c,"text/xml");return t.getElementsByTagName("parsererror").length>0?null:t}catch{return null}}function Wt(c,e){const t=[],i=c.getElementsByTagName("*");for(let s=0;s<i.length;s++){const r=i[s],n=r.nodeName.split(":");n[n.length-1]===e&&t.push(r)}return t}function kt(c,e){const t=Wt(c,e);return t.length>0?t[0]:null}const fr=["breakStart","breakEnd","error"];function gr(c){var s;const e=kt(c,"TrackingEvents");if(!e)return[];const t=Wt(e,"Tracking"),i=[];for(let r=0;r<t.length;r++){const a=t[r],n=a.getAttribute("event")||"",l=((s=a.textContent)==null?void 0:s.trim())||"";fr.includes(n)&&l&&i.push({event:n,url:l})}return i}class jt{constructor(){this.name="VMAP",this.capabilities={supportsLinear:!0,supportsNonLinear:!0,supportsCompanion:!0,supportsSkippable:!0,supportsVMAP:!0,supportsVAST:!0,supportsSSAI:!1,supportsIMA:!1},this.context=null,this.manager=null,this.vmapTagUrl="",this.scheduledBreaks=[],this.hasDurationResolved=!1,this.lastBreakTime=-1,this.sessionAdCount=0,this.hourlyAdTimestamps=[],this.frequencyCap={},this.limits={maxXmlSize:2097152},this.trackingManager=new _t,this.timeUpdateListener=null,this.durationChangeListener=null,this.loadedMetadataListener=null,this.endedListener=null,this.seekedListener=null,this.diagnostics={parsedBreaksCount:0,registeredBreaksCount:0,playedBreaksCount:0,cancelledBreaksCount:0,dynamicInsertions:0,repeatSchedulingCount:0,playlistResets:0,liveScheduleUpdates:0,frequencyCapSuppressions:0}}init(e){var i;this.context=e,e.controller&&e.controller.ads&&(this.manager=e.controller.ads.manager);const t=(i=e.config)==null?void 0:i.providerOptions;return t&&(this.frequencyCap=t.frequencyCap||{},typeof t.maxXmlSize=="number"&&(this.limits.maxXmlSize=t.maxXmlSize)),this.setupTimelineListeners(),{success:!0}}async requestAds(e,t){var r,a,n,l;const i=t==null?void 0:t.context;if((!this.manager||!this.context)&&i&&this.init(i),!this.manager||!this.context)return{success:!1,error:{type:ie.CONFIGURATION,code:100,message:"VmapProvider not initialized."}};if(this.context.controller.getState().sourceType==="embed"){const o={type:ie.CONFIGURATION,code:900,message:"VMAP ads are not supported for embed (YouTube/Vimeo) sources."};return this.manager.triggerAdError(o),{success:!1,error:o}}this.vmapTagUrl=e,this.resetSchedule();const s=new AbortController().signal;try{const o=await this.fetchVmapXml(e,s,(r=this.context.config)==null?void 0:r.request);if(o.length>this.limits.maxXmlSize)throw new Error(`Oversized VMAP XML: ${o.length} bytes exceeds limits`);const d=pr(o);if(!d)throw new Error("Malformed VMAP XML or parsing error");if(!kt(d,"VMAP"))throw new Error("Missing VMAP root node");const u=this.parseVmapAdBreaks(d);this.diagnostics.parsedBreaksCount=u.length,this.scheduledBreaks=u.map(p=>({...p,resolvedTime:ji(p.timeOffset),isPlayed:!1})),(n=(a=this.context.controller.ads)==null?void 0:a.hasActiveManualSchedule)!=null&&n.call(a)&&(console.warn("[VmapProvider] requestAds() called while an AdScheduler manual schedule has active breaks - AdScheduler and VmapProvider independently watch the same video timeline and are not supported together on one player instance; this can result in duplicate/overlapping ad breaks."),this.context.controller.emit("adschedulerconflict",{source:"vmap",reason:"VmapProvider.requestAds() called while AdScheduler has active breaks"}));const f=this.context.controller.getState().duration;return f&&f>0&&this.resolveCuePoints(f),{success:!0}}catch(o){const d=o instanceof Error?o.message:"VMAP parsing failed",h={type:d.includes("Malformed")?ie.PARSING:ie.UNKNOWN,code:300,message:d,originalError:o};return(l=this.context)==null||l.controller.emit("vmapparseerror",{message:h.message}),{success:!1,error:h}}}async fetchVmapXml(e,t,i){return Hi(e,t,i)}parseVmapAdBreaks(e){var s;const t=[],i=Wt(e,"AdBreak");for(let r=0;r<i.length;r++){const a=i[r],n=a.getAttribute("timeOffset")||"",l=a.getAttribute("breakId")||`vmap-break-${Date.now()}-${r}`,o=a.getAttribute("breakType")||"linear",d=a.getAttribute("repeatAfter")||void 0,h=kt(a,"AdSource"),u=h?kt(h,"AdTagURI"):null,f=((s=u==null?void 0:u.textContent)==null?void 0:s.trim())||"",p=gr(a);t.push({id:l,timeOffset:n,breakType:o,repeatAfter:d,adTagUrl:f,trackingUrls:p})}return t}resolveCuePoints(e){if(!isFinite(e)||e<=0)return;this.hasDurationResolved=!0;const t=[...this.scheduledBreaks];this.scheduledBreaks=[],t.forEach(i=>{let s=i.resolvedTime;if(i.timeOffset==="start")s=0;else if(i.timeOffset==="end")s=e;else if(i.timeOffset.endsWith("%")){const a=parseFloat(i.timeOffset.slice(0,-1))/100;s=isNaN(a)?0:a*e}else s<0&&(s=Kt(i.timeOffset));const r={...i,resolvedTime:s,isPlayed:i.isPlayed};this.scheduledBreaks.push(r),this.diagnostics.registeredBreaksCount++,i.repeatAfter&&!i.isRepeat&&this.generateRepeatSchedules(r,e)}),this.scheduledBreaks.sort((i,s)=>i.resolvedTime-s.resolvedTime)}generateRepeatSchedules(e,t){const i=Kt(e.repeatAfter);if(i<=0)return;let s=e.resolvedTime+i;for(;s<t;)this.scheduledBreaks.push({...e,id:`${e.id}-repeat-${s}`,timeOffset:String(s),resolvedTime:s,isPlayed:!1,isRepeat:!0}),this.diagnostics.repeatSchedulingCount++,this.diagnostics.registeredBreaksCount++,s+=i}setupTimelineListeners(){if(!this.context)return;const e=this.context.videoElement,t=()=>{if(!this.context||!this.manager)return;const n=e.duration||0;isFinite(n)&&n>0&&(this.hasDurationResolved=!1,this.resolveCuePoints(n))},i=()=>{if(!this.context||!this.manager)return;const n=e.currentTime,l=e.duration||0;if(this.context.controller.getState().isLive){this.diagnostics.liveScheduleUpdates++,this.evaluateCueHits(n);return}isFinite(l)&&l>0&&(!this.hasDurationResolved||this.scheduledBreaks.some(o=>o.timeOffset.endsWith("%")||o.timeOffset==="end"))&&this.resolveCuePoints(l),this.evaluateCueHits(n)},s=()=>{const n=e.duration||0;isFinite(n)&&n>0&&(this.hasDurationResolved=!1,this.resolveCuePoints(n))},r=()=>{if(!this.context||!this.manager)return;const n=e.duration||0;this.evaluateCueHits(n,!0)},a=()=>{if(!this.context||!this.manager)return;const n=e.currentTime;this.evaluateCueHits(n,!1,!0)};e.addEventListener("timeupdate",i),e.addEventListener("durationchange",s),e.addEventListener("loadedmetadata",t),e.addEventListener("ended",r),e.addEventListener("seeked",a),this.timeUpdateListener=i,this.durationChangeListener=s,this.loadedMetadataListener=t,this.endedListener=r,this.seekedListener=a}evaluateCueHits(e,t=!1,i=!1){var a;const s=((a=this.context)==null?void 0:a.videoElement.duration)||0,r=[];for(let n=0;n<this.scheduledBreaks.length;n++){const l=this.scheduledBreaks[n];if(!l.isPlayed){if(l.resolvedTime<0)continue;const o=l.timeOffset==="start"||l.resolvedTime===0,d=l.timeOffset==="end";let h=!1;o?h=e<=3:d?h=t||s>0&&e>=s-.5:i?h=l.resolvedTime<=e:h=e>=l.resolvedTime&&e-l.resolvedTime<=2.5,h&&r.push(l)}}if(r.length>0){let n=r;if(i&&r.length>1){r.sort((d,h)=>d.resolvedTime-h.resolvedTime);const o=r[r.length-1];r.forEach(d=>{d.isPlayed=!0}),n=[o]}else r.forEach(o=>{o.isPlayed=!0});const l=n.filter(o=>this.checkFrequencyCappingRules(e));l.length>0?this.executeAdBreaksSequence(l):this.diagnostics.frequencyCapSuppressions+=n.length}}checkFrequencyCappingRules(e){if(this.frequencyCap.minContentWatched!==void 0&&e<this.frequencyCap.minContentWatched||this.frequencyCap.minTimeBetweenBreaks!==void 0&&this.lastBreakTime!==-1&&e-this.lastBreakTime<this.frequencyCap.minTimeBetweenBreaks||this.frequencyCap.maxAdsSession!==void 0&&this.sessionAdCount>=this.frequencyCap.maxAdsSession)return!1;if(this.frequencyCap.maxAdsPerHour!==void 0){const t=Date.now()-36e5;if(this.hourlyAdTimestamps=this.hourlyAdTimestamps.filter(i=>i>t),this.hourlyAdTimestamps.length>=this.frequencyCap.maxAdsPerHour)return!1}return!0}fireBreakTracking(e,t){e.trackingUrls&&e.trackingUrls.filter(i=>i.event===t).forEach(i=>this.trackingManager.trackUrl(i.url))}async executeAdBreaksSequence(e){var r;if(!this.context||!this.manager||e.length===0)return;const t=this.context.controller.ads.getProvider("VAST");if(!t){console.warn("[VmapProvider] Failed to locate VAST provider for executing breaks"),this.manager.recover("VAST provider missing");return}if(e.some(a=>a.timeOffset!=="start"&&a.resolvedTime>0)&&this.context.videoElement){const a=e[0].resolvedTime;try{this.context.videoElement.pause(),a>0&&a<(this.context.videoElement.duration||1/0)&&(this.context.videoElement.currentTime=a)}catch{}this.manager.getSavedContentSnapshot().capture(this.context.controller)}const s=[];for(const a of e){this.lastBreakTime=a.resolvedTime,this.sessionAdCount++,this.hourlyAdTimestamps.push(Date.now()),this.diagnostics.playedBreaksCount++,this.fireBreakTracking(a,"breakStart");const n=await t.requestAds(a.adTagUrl);if(n.success){const l=t.getInternalAdBreak()||this.manager.getAdBreakManager().getActiveBreak();l&&l.ads&&l.ads.length>0&&s.push(...l.ads)}else console.warn("[VmapProvider] VAST request failed for break:",a.id,n.error),this.fireBreakTracking(a,"error"),this.context.controller.emit("vmapbreakerror",{breakId:a.id,tagUrl:a.adTagUrl,message:((r=n.error)==null?void 0:r.message)||"VAST request failed for VMAP break"})}if(s.length>0){const a={id:`vmap-unified-break-${Date.now()}`,timeOffset:e[0].resolvedTime,type:e[0].timeOffset==="start"?"preroll":e[0].timeOffset==="end"?"postroll":"midroll",ads:s,duration:s.reduce((n,l)=>n+(l.duration||0),0)};t.setInternalAdBreak(a),this.manager.getAdBreakManager().registerBreak(a),await t.playAdBreak(),e.forEach(n=>this.fireBreakTracking(n,"breakEnd"))}else this.manager.recover("No playable VAST ads returned for VMAP breaks")}registerBreak(e){var a;const t=String(e.timeOffset||""),i=((a=this.context)==null?void 0:a.videoElement.duration)||0;let s=typeof e.timeOffset=="number"?e.timeOffset:ji(t);if(s<0&&i>0){if(t==="end")s=i;else if(t.endsWith("%")){const n=parseFloat(t.slice(0,-1))/100;s=isNaN(n)?0:n*i}}const r={id:e.id,timeOffset:t,breakType:e.breakType||"linear",adTagUrl:e.adTagUrl,resolvedTime:s,isPlayed:!1};this.scheduledBreaks.push(r),this.diagnostics.dynamicInsertions++,this.diagnostics.registeredBreaksCount++,this.scheduledBreaks.sort((n,l)=>n.resolvedTime-l.resolvedTime)}hasScheduledBreaks(){return this.scheduledBreaks.some(e=>!e.isPlayed)}removeBreak(e){const t=this.scheduledBreaks.findIndex(i=>i.id===e);t!==-1&&(this.scheduledBreaks.splice(t,1),this.diagnostics.cancelledBreaksCount++)}replaceBreak(e,t){this.removeBreak(e),this.registerBreak(t)}clearBreaks(){this.scheduledBreaks=[],this.hasDurationResolved=!1}onSourceLoaded(e){this.diagnostics.playlistResets++,this.resetSchedule(),this.vmapTagUrl=""}getCuePoints(){return this.scheduledBreaks.map(e=>e.resolvedTime).filter(e=>e>=0)}getVmapDiagnostics(){return this.diagnostics}resetSchedule(){this.scheduledBreaks=[],this.hasDurationResolved=!1,this.lastBreakTime=-1,this.sessionAdCount=0,this.hourlyAdTimestamps=[]}cleanupListeners(){if(!this.context)return;const e=this.context.videoElement;this.timeUpdateListener&&(e.removeEventListener("timeupdate",this.timeUpdateListener),this.timeUpdateListener=null),this.durationChangeListener&&(e.removeEventListener("durationchange",this.durationChangeListener),this.durationChangeListener=null),this.loadedMetadataListener&&(e.removeEventListener("loadedmetadata",this.loadedMetadataListener),this.loadedMetadataListener=null),this.endedListener&&(e.removeEventListener("ended",this.endedListener),this.endedListener=null),this.seekedListener&&(e.removeEventListener("seeked",this.seekedListener),this.seekedListener=null)}playAdBreak(){return Promise.resolve()}pauseAd(){}resumeAd(){}setVolume(e){}setMuted(e){}skipAd(){var t;const e=(t=this.manager)==null?void 0:t.getProviderManager().getActiveProvider();e&&e!==this&&typeof e.skipAd=="function"&&e.skipAd()}destroy(){this.cleanupListeners(),this.resetSchedule(),this.context=null,this.manager=null,this.vmapTagUrl=""}}const mr=()=>typeof performance<"u"?performance.now():Date.now(),Gi=8e3;let rt=null,Qi=0;function Xi(){var e;if(typeof window>"u"||typeof document>"u")return Promise.reject(new Error("IMA SDK can only be loaded in a browser environment"));if((e=window.google)!=null&&e.ima)return Promise.resolve();if(rt)return rt;const c=Date.now();return rt=new Promise((t,i)=>{let s=!1;const r=document.createElement("script");r.src="https://imasdk.googleapis.com/js/sdkloader/ima3.js",r.async=!0;const a=setTimeout(()=>{if(s)return;s=!0;const n=new Error(`Google IMA SDK did not load within ${Gi}ms. This commonly means the request to imasdk.googleapis.com was blocked by a browser-level or extension ad blocker (e.g. Opera's built-in blocker, uBlock Origin, AdGuard) rather than a real network failure - check the Network tab for a canceled/blocked request to that domain.`);n.likelyBlocked=!0,i(n)},Gi);r.onload=()=>{var n;s||(s=!0,clearTimeout(a),(n=window.google)!=null&&n.ima?(Qi=Date.now()-c,t()):i(new Error("IMA SDK script loaded but google.ima is not available")))},r.onerror=()=>{if(s)return;s=!0,clearTimeout(a);const n=new Error("Failed to load Google IMA SDK script from imasdk.googleapis.com. This commonly indicates the request was blocked by a browser-level or extension ad blocker rather than an actual network outage.");n.likelyBlocked=!0,i(n)},document.head.appendChild(r)}).catch(t=>{throw rt=null,t}),rt}function vr(c){return[1005,1009,1010,1011,1012,1020].includes(c)?ie.PARSING:[100,101,102,1006,1007].includes(c)?ie.CONFIGURATION:[301,303,1021,1022,1023].includes(c)?ie.NETWORK:[400,401,402,403,405].includes(c)?ie.PLAYBACK:ie.UNKNOWN}const Oe=class Oe{constructor(){this.name="IMA",this.capabilities={supportsLinear:!0,supportsNonLinear:!0,supportsCompanion:!0,supportsSkippable:!0,supportsVMAP:!0,supportsVAST:!0,supportsSSAI:!1,supportsIMA:!0},this.context=null,this.manager=null,this.adDisplayContainer=null,this.adsLoader=null,this.adsManager=null,this.loaderState="idle",this.managerState="idle",this.currentTag="",this.startWatchdogTimer=null,this.containerWatchTimer=null,this.diagnostics={sdkLoaded:!1,sdkVersion:"Unknown",sdkLoadDurationMs:0,adsLoaderState:"idle",adsManagerState:"idle",lastErrorMsg:"",lastErrorCode:0,eventsLogged:[],sdkBlockedLikely:!1},this.resizeListener=null}init(e){return this.context=e,e.controller&&e.controller.ads&&(this.manager=e.controller.ads.manager),typeof window<"u"&&Xi().catch(()=>{}),{success:!0}}async requestAds(e,t){var s,r,a,n;const i=t==null?void 0:t.context;if((!this.context||!this.manager)&&i&&this.init(i),!this.context||!this.manager)return{success:!1,error:{type:ie.CONFIGURATION,code:100,message:"ImaProvider not initialized."}};this.currentTag=e,(s=window.google)!=null&&s.ima&&this.initializeImaLoader();try{this.loaderState="requesting",this.diagnostics.adsLoaderState="requesting",await Xi();const l=window.google.ima;this.diagnostics.sdkLoaded=!0,this.diagnostics.sdkLoadDurationMs=Qi,this.diagnostics.sdkBlockedLikely=!1,l.settings&&(this.diagnostics.sdkVersion=String(((a=(r=l.settings).getLocale)==null?void 0:a.call(r))||"3.x")),this.initializeImaLoader();const o=new l.AdsRequest;o.adTagUrl=e;const d=this.context.videoElement.clientWidth||640,h=this.context.videoElement.clientHeight||360;o.linearAdSlotWidth=d,o.linearAdSlotHeight=h,o.nonLinearAdSlotWidth=d,o.nonLinearAdSlotHeight=Math.round(h/3),typeof o.setAdWillAutoPlay=="function"&&o.setAdWillAutoPlay(!0),typeof o.setAdWillPlayMuted=="function"&&o.setAdWillPlayMuted(!0);const u=(n=this.context.config.providerOptions)==null?void 0:n.ima;if(u&&(u.publisherProvidedId&&(o.publisherProvidedId=u.publisherProvidedId),u.sessionId&&(o.sessionId=u.sessionId),u.language&&l.settings.setLanguage(u.language),u.locale&&l.settings.setLocale(u.locale),u.customTargeting)){const g=[];for(const m in u.customTargeting)g.push(`${encodeURIComponent(m)}=${encodeURIComponent(u.customTargeting[m])}`);o.customParameters=g.join("&")}const f=this.adsLoader;return await new Promise((g,m)=>{const v=()=>{f.removeEventListener(l.AdsManagerLoadedEvent.Type.ADS_MANAGER_LOADED,v),f.removeEventListener(l.AdErrorEvent.Type.AD_ERROR,y),g()},y=b=>{var S;f.removeEventListener(l.AdsManagerLoadedEvent.Type.ADS_MANAGER_LOADED,v),f.removeEventListener(l.AdErrorEvent.Type.AD_ERROR,y),m(((S=b==null?void 0:b.getError)==null?void 0:S.call(b))||new Error("IMA Ad Error"))};f.addEventListener(l.AdsManagerLoadedEvent.Type.ADS_MANAGER_LOADED,v),f.addEventListener(l.AdErrorEvent.Type.AD_ERROR,y),f.requestAds(o)}),this.loaderState="ready",this.diagnostics.adsLoaderState="ready",{success:!0}}catch(l){this.loaderState="error",this.diagnostics.adsLoaderState="error";const o=l instanceof Error?l.message:"IMA Loader failed";this.diagnostics.lastErrorMsg=o;const d=!!(l!=null&&l.likelyBlocked);this.diagnostics.sdkBlockedLikely=d;const h={type:d?ie.BLOCKED:ie.NETWORK,code:d?901:301,message:o||"Google IMA loader request failed",originalError:l};return this.manager.triggerAdError(h),{success:!1,error:h}}}initializeImaLoader(){if(this.adsLoader)return;const e=window.google.ima;this.adDisplayContainer=new e.AdDisplayContainer(this.context.adContainer,this.context.videoElement),this.adDisplayContainer.initialize(),this.adsLoader=new e.AdsLoader(this.adDisplayContainer),this.adsLoader.addEventListener(e.AdsManagerLoadedEvent.Type.ADS_MANAGER_LOADED,t=>this.onAdsManagerLoaded(t),!1),this.adsLoader.addEventListener(e.AdErrorEvent.Type.AD_ERROR,t=>this.onAdError(t),!1),this.setupResizeListener()}setupResizeListener(){typeof window>"u"||(this.resizeListener=()=>this.resize(),window.addEventListener("resize",this.resizeListener))}resize(e,t){var l,o,d,h;if(!this.adsManager||!this.context)return;const i=(l=window.google)==null?void 0:l.ima;if(!i)return;const s=e||this.context.videoElement.clientWidth||640,r=t||this.context.videoElement.clientHeight||360,n=!!((h=(d=(o=this.context.controller)==null?void 0:o.getState)==null?void 0:d.call(o))!=null&&h.isFullscreen)?i.ViewMode.FULLSCREEN:i.ViewMode.NORMAL;try{this.adsManager.resize(s,r,n)}catch(u){console.warn("[ImaProvider] Failed to resize IMA AdsManager:",u)}}onAdsManagerLoaded(e){const t=window.google.ima,i=new t.AdsRenderingSettings;i.restorePlayerStateOnAdComplete=!1,this.adsManager=e.getAdsManager(this.context.videoElement,i),this.managerState="ready",this.diagnostics.adsManagerState="ready",this.setupAdsManagerListeners()}setupAdsManagerListeners(){const e=window.google.ima,t=this.adsManager;if(!t)return;const i=s=>{this.diagnostics.eventsLogged.push(`${s} at ${mr()}`)};t.addEventListener(e.AdErrorEvent.Type.AD_ERROR,s=>{i("AD_ERROR"),this.onAdError(s)}),t.addEventListener(e.AdEvent.Type.CONTENT_PAUSE_REQUESTED,()=>{var s;if(i("CONTENT_PAUSE_REQUESTED"),this.manager&&this.manager.getAdState()===w.IDLE)this.manager.startAdBreak({id:`ima-break-${Date.now()}`,timeOffset:this.context.videoElement.currentTime,type:"midroll",ads:[],duration:0});else try{(s=this.context)!=null&&s.videoElement&&!this.context.videoElement.paused&&this.context.videoElement.pause()}catch{}}),t.addEventListener(e.AdEvent.Type.CONTENT_RESUME_REQUESTED,()=>{var s;i("CONTENT_RESUME_REQUESTED"),(s=this.manager)==null||s.endAdBreak()}),e.AdEvent.Type.ALL_ADS_COMPLETED&&t.addEventListener(e.AdEvent.Type.ALL_ADS_COMPLETED,()=>{var s;i("ALL_ADS_COMPLETED"),(s=this.manager)==null||s.endAdBreak()}),t.addEventListener(e.AdEvent.Type.LOADED,s=>{var p,g,m,v;i("LOADED");const r=(p=s.getAd)==null?void 0:p.call(s);if(!r)return;const a=typeof r.isSkippable=="function"?r.isSkippable():typeof r.getSkippable=="function"?r.getSkippable():!1,n=typeof r.getClickThroughUrl=="function"?r.getClickThroughUrl():"",l=typeof r.getAdPodInfo=="function"?r.getAdPodInfo():null,o=l&&typeof l.getAdPosition=="function"?l.getAdPosition():void 0,d=l&&typeof l.getTotalAds=="function"?l.getTotalAds():void 0,h=l&&typeof l.isBumper=="function"?l.isBumper():void 0,u={id:r.getAdId()||`ima-${Date.now()}`,title:r.getTitle()||"IMA Ad",duration:r.getDuration()||0,width:r.getWidth()||0,height:r.getHeight()||0,linear:r.isLinear(),skippable:a,skipOffset:r.getSkipTimeOffset&&r.getSkipTimeOffset()||0,contentType:r.getContentType()||"video/mp4",clickThroughUrl:n,podPosition:o,podSize:d,isBumper:h},f=typeof r.getCompanionAds=="function"?r.getCompanionAds():[];if(f&&f.length>0){const y=f.map((b,S)=>({id:`ima-companion-${S}`,title:"IMA Companion Ad",duration:0,width:typeof b.getWidth=="function"?b.getWidth():void 0,height:typeof b.getHeight=="function"?b.getHeight():void 0,linear:!1,skippable:!1,htmlContent:typeof b.getContent=="function"?b.getContent():void 0,clickThroughUrl:typeof b.getClickThroughUrl=="function"?b.getClickThroughUrl():""}));(g=this.manager)==null||g.showCompanions(y)}(m=this.manager)==null||m.setCurrentAd(u),(v=this.context)==null||v.controller.emit("adloaded",{ad:u})}),t.addEventListener(e.AdEvent.Type.AD_PROGRESS,s=>{var a,n,l;const r=s.getAdData?s.getAdData():null;if(r){const o=r.currentTime||0,d=r.duration||((a=this.context)==null?void 0:a.controller.getState().adDuration)||0,h=Math.max(0,d-o),u=!!r.skippable&&o>=(r.skipTimeOffset||0),f=r.skippable?Math.max(0,(r.skipTimeOffset||0)-o):null;(n=this.context)==null||n.controller.updateStatePublic({adCurrentTime:o,adRemainingTime:h,adDuration:d,canSkipAd:u,skipAvailableAt:f}),(l=this.context)==null||l.controller.emit("adtimeupdate",{currentTime:o,duration:d,remainingTime:h})}}),t.addEventListener(e.AdEvent.Type.STARTED,()=>{var s,r;i("STARTED"),this.clearStartWatchdog(),this.managerState="playing",this.diagnostics.adsManagerState="playing",(s=this.manager)==null||s.transitionTo(w.PLAYING),(r=this.context)==null||r.controller.emit("adstart"),this.startContainerWatch()}),t.addEventListener(e.AdEvent.Type.PAUSED,()=>{var s,r;i("PAUSED"),this.managerState="paused",this.diagnostics.adsManagerState="paused",(s=this.manager)==null||s.transitionTo(w.PAUSED),(r=this.context)==null||r.controller.emit("adpaused")}),t.addEventListener(e.AdEvent.Type.RESUMED,()=>{var s,r;i("RESUMED"),this.managerState="playing",this.diagnostics.adsManagerState="playing",(s=this.manager)==null||s.transitionTo(w.PLAYING),(r=this.context)==null||r.controller.emit("adresumed")}),t.addEventListener(e.AdEvent.Type.COMPLETE,()=>{var s,r;i("COMPLETE"),this.clearContainerWatch(),(s=this.manager)==null||s.transitionTo(w.ENDED),(r=this.context)==null||r.controller.emit("adcomplete")}),t.addEventListener(e.AdEvent.Type.SKIPPED,()=>{var s,r;i("SKIPPED"),this.clearContainerWatch(),(s=this.context)==null||s.controller.emit("adskip"),(r=this.manager)==null||r.endAdBreak()}),t.addEventListener(e.AdEvent.Type.CLICK,s=>{var l;i("CLICK");const r=s!=null&&s.getAdData?s.getAdData():null,a=s!=null&&s.getAd?s.getAd():null,n=(r==null?void 0:r.clickThroughUrl)||(typeof(a==null?void 0:a.getClickThroughUrl)=="function"?a.getClickThroughUrl():"");(l=this.context)==null||l.controller.emit("adclick",{clickUrl:n})})}onAdError(e){var a,n,l;const t=e.getError(),i=((a=t.getErrorCode)==null?void 0:a.call(t))||300,s=((n=t.getMessage)==null?void 0:n.call(t))||"Unknown Google IMA SDK error";this.diagnostics.lastErrorCode=i,this.diagnostics.lastErrorMsg=s;const r={type:vr(i),code:i,message:s,originalError:t};(l=this.manager)==null||l.triggerAdError(r)}async playAdBreak(e="preroll"){var t,i,s,r,a,n;if(this.adsManager){if(((t=this.context)==null?void 0:t.controller.getState().sourceType)==="embed"){this.onAdError({getError:()=>({getErrorCode:()=>900,getMessage:()=>"Google IMA ads are not supported for embed (YouTube/Vimeo) sources."})});return}try{const l=this.context.videoElement.clientWidth||640,o=this.context.videoElement.clientHeight||360,h=!!((r=(s=(i=this.context.controller)==null?void 0:i.getState)==null?void 0:s.call(i))!=null&&r.isFullscreen)?window.google.ima.ViewMode.FULLSCREEN:window.google.ima.ViewMode.NORMAL;this.adsManager.init(l,o,h);try{this.adsManager.setVolume(0)}catch{}try{(a=this.context)!=null&&a.videoElement&&(this.context.videoElement.muted=!0)}catch{}if((n=this.manager)==null||n.startAdBreak({id:`ima-break-${Date.now()}`,timeOffset:0,type:e,ads:[],duration:0}),e==="preroll")this.adsManager.start(),this.startStartWatchdog();else{const u=window.google.ima,f=this.adsManager,p=()=>{f.removeEventListener(u.AdEvent.Type.AD_BREAK_READY,p),f.start(),this.startStartWatchdog()};f.addEventListener(u.AdEvent.Type.AD_BREAK_READY,p)}}catch(l){const o=l instanceof Error?l.message:"IMA playAdBreak failed";this.onAdError({getError:()=>({getErrorCode:()=>400,getMessage:()=>o})})}}}startStartWatchdog(){this.clearStartWatchdog(),this.startWatchdogTimer=setTimeout(()=>{this.startWatchdogTimer=null,this.managerState!=="playing"&&this.onAdError({getError:()=>({getErrorCode:()=>402,getMessage:()=>`Google IMA: adsManager.start() was called ${Oe.START_WATCHDOG_MS}ms ago but the STARTED event never fired - the ad video never actually began playing, even though IMA's own UI chrome (ad badge / skip countdown, driven by AD_PROGRESS) may still be visible. This usually means the underlying ad media failed to decode/attach - check the ad tag's returned media file (codec/format support), or the ad server response itself, rather than autoplay/mute policy (already handled).`})})},Oe.START_WATCHDOG_MS)}clearStartWatchdog(){this.startWatchdogTimer&&(clearTimeout(this.startWatchdogTimer),this.startWatchdogTimer=null)}startContainerWatch(){var t;this.clearContainerWatch();const e=(t=this.context)==null?void 0:t.adContainer;!e||typeof document>"u"||(this.containerWatchTimer=setInterval(()=>{this.managerState==="playing"&&(document.contains(e)||(this.clearContainerWatch(),this.onAdError({getError:()=>({getErrorCode:()=>403,getMessage:()=>"Google IMA: the ad container element was detached from the page while the ad was still playing (IMA reported STARTED but its container is no longer in the live DOM). This means something in the host app re-rendered/removed the element IMA attached its iframe to - the ad kept running internally (progress/complete events) but nothing was visible. Check for conditional rendering or re-creation of the ads-overlay container while an ad is active."})})))},Oe.CONTAINER_WATCH_INTERVAL_MS))}clearContainerWatch(){this.containerWatchTimer&&(clearInterval(this.containerWatchTimer),this.containerWatchTimer=null)}pauseAd(){this.adsManager&&this.managerState==="playing"&&this.adsManager.pause()}resumeAd(){this.adsManager&&this.managerState==="paused"&&this.adsManager.resume()}setVolume(e){this.adsManager&&this.adsManager.setVolume(e)}setMuted(e){this.adsManager&&this.adsManager.setVolume(e?0:1)}getImaDiagnostics(){return this.diagnostics}skipAd(){if(this.adsManager)try{this.adsManager.skip()}catch{this.destroy()}}destroy(){if(this.clearStartWatchdog(),this.clearContainerWatch(),this.resizeListener&&typeof window<"u"&&(window.removeEventListener("resize",this.resizeListener),this.resizeListener=null),this.adsManager){try{this.adsManager.destroy()}catch{}this.adsManager=null}if(this.adsLoader){try{this.adsLoader.destroy()}catch{}this.adsLoader=null}if(this.adDisplayContainer){try{this.adDisplayContainer.destroy()}catch{}this.adDisplayContainer=null}this.managerState="destroyed",this.diagnostics.adsManagerState="destroyed",this.context=null,this.manager=null}};Oe.START_WATCHDOG_MS=6e3,Oe.CONTAINER_WATCH_INTERVAL_MS=1e3;let at=Oe;class Yi{constructor(e){this.providers=new Map,this.activeProviderName=null,this.adContainerElement=null,this.scheduler=null,this.controller=e,this.manager=new Wi,this.controller.use(this.manager),this.registerProvider("VAST",new qt),this.registerProvider("VMAP",new jt),this.registerProvider("IMA",new at)}setAdContainer(e){this.adContainerElement=e,this.manager.setAdContainer(e),this.providers.forEach((t,i)=>{this.initializeProvider(i,e)})}getAdContainer(){return this.adContainerElement||this.manager.getAdContainer()}state(){const e=this.controller.getState();return{isAdPlaying:e.isAdPlaying,isAdLoading:e.isAdLoading,currentAd:e.currentAd,currentAdBreak:e.currentAdBreak,adRemainingTime:e.adRemainingTime,adDuration:e.adDuration,canSkipAd:e.canSkipAd,skipAvailableAt:e.skipAvailableAt,adPosition:e.adPosition,adProvider:e.adProvider,adLinear:e.adLinear,adMuted:e.adMuted}}provider(){return this.activeProviderName}capabilities(){if(this.activeProviderName){const e=this.providers.get(this.activeProviderName);if(e)return e.capabilities}return null}currentAd(){return this.controller.getState().currentAd}currentBreak(){return this.controller.getState().currentAdBreak}skip(){this.manager.skipAd()}pause(){this.manager.pause()}resume(){this.manager.play()}enable(){this.controller.setAdsEnabled(!0)}disable(){this.controller.setAdsEnabled(!1)}getScheduler(){return this.scheduler||(this.scheduler=new ur(this.controller,e=>this.getProvider(e),e=>this.manager.showOverlay(e))),this.scheduler}schedule(e){var i;const t=this.providers.get("VMAP");return(i=t==null?void 0:t.hasScheduledBreaks)!=null&&i.call(t)&&(console.warn("[AdsController] schedule() called while a VMAP playlist has active breaks - AdScheduler and VmapProvider independently watch the same video timeline and are not supported together on one player instance; this can result in duplicate/overlapping ad breaks."),this.controller.emit("adschedulerconflict",{source:"scheduler",reason:"AdScheduler.schedule() called while VmapProvider has active breaks"})),this.getScheduler().schedule(e)}hasActiveManualSchedule(){return!!this.scheduler&&this.scheduler.hasActiveBreaks()}unschedule(e){var t;(t=this.scheduler)==null||t.unschedule(e)}clearSchedule(){var e;(e=this.scheduler)==null||e.clear()}async play(e){const t=this.getProvider("VAST");if(!t)return;(await t.requestAds(e)).success&&await t.playAdBreak()}registerProvider(e,t,i){var s,r;this.providers.set(e,t),this.manager.getProviderManager().registerProvider(e,t),(!this.activeProviderName||((r=(s=this.controller.config)==null?void 0:s.ads)==null?void 0:r.provider)===e)&&(this.activeProviderName=e,this.manager.getProviderManager().selectProvider(e)),this.initializeProvider(e,i)}initializeProvider(e,t){const i=this.providers.get(e);if(!i)return!1;const s=t||this.adContainerElement||this.manager.getAdContainer()||void 0,r=this.manager.createProviderContext(s);try{return i.init(r),!0}catch(a){return console.error(`[AdsController] Failed to initialize provider "${e}":`,a),!1}}getProvider(e){let t=this.providers.get(e);return t||(e==="VAST"?(t=new qt,this.registerProvider("VAST",t)):e==="VMAP"?(t=new jt,this.registerProvider("VMAP",t)):e==="IMA"&&(t=new at,this.registerProvider("IMA",t))),t&&this.initializeProvider(e),t}unregisterProvider(e){const t=this.providers.get(e);if(t)try{t.destroy()}catch{}this.providers.delete(e),this.manager.getProviderManager().unregisterProvider(e),this.activeProviderName===e&&(this.activeProviderName=null)}destroy(){var e;(e=this.scheduler)==null||e.destroy(),this.scheduler=null}async showOverlay(e){return this.manager.showOverlay(e)}hideOverlay(){this.manager.hideOverlay()}closeOverlay(){this.manager.closeOverlay()}updateOverlay(e){this.manager.updateOverlay(e)}getOverlayDiagnostics(){const e=this.manager.getHtmlOverlayRenderer();return e?e.getDiagnostics():null}diagnostics(){var i;const e=this.manager.getDiagnosticsStats(),t=this.manager.getHtmlOverlayRenderer();return{providerName:this.activeProviderName,state:this.manager.getAdState(),configuration:((i=this.controller.config)==null?void 0:i.ads)||null,lastError:null,statistics:{totalAdsRequested:e.totalAdsRequested,totalAdsPlayed:e.totalAdsPlayed,totalAdsCompleted:e.totalAdsCompleted,totalAdsSkipped:e.totalAdsSkipped,totalAdErrors:e.totalAdErrors},htmlOverlay:t?t.getDiagnostics():null}}validate(){return Mi.validate(this.controller)}}function Gt(c){if(c instanceof DOMException)return c.name==="SecurityError"||c.code===18;if(c&&typeof c=="object"){const e=c;return e.name==="SecurityError"||e.code===18}return!1}class Zi{constructor(e){this.type="frame-capture",this.video=null,this.canvas=null,this.ctx=null,this.cache=new Map,this.currentSrc="",this.pendingSrc="",this.isSeeking=!1,this.seekQueue=[],this.isMetadataLoaded=!1,this.hasError=!1,this.consecutiveFailures=0,this.metadataPromise=null,this.resolveMetadata=null,this.hlsInstance=null,this.dashInstance=null,this.isDestroyed=!1,this.lastSeekTime=0,this.lastHighPriorityTime=0,this.throttleMs=150,this.seekTimeoutId=null,this.MAX_CACHE_SIZE=250,this.isPreciseSeeking=!1,this.activeSeekCleanup=null,this.pendingRequests=new Map,this.handleLoadedMetadata=()=>{(this.currentSrc||"").split("?")[0].toLowerCase().endsWith(".mpd")||(this.isMetadataLoaded=!0,this.resolveMetadata&&this.resolveMetadata())},this.handleVideoError=t=>{var s;const i=(s=this.video)==null?void 0:s.error;if(console.debug("[VideoFrameThumbnailProvider] Global error event fired on hidden video:",i?`Code: ${i.code}, Message: ${i.message}`:t),this.hasError=!0,this.destroyStreamingInstances(),this.video){try{this.video.pause()}catch{}this.video.removeAttribute("src");try{this.video.load()}catch{}}this.resolveMetadata&&this.resolveMetadata()},this.config=e,this.initVideoAndCanvas()}updateConfig(e){this.config=e}initVideoAndCanvas(){this.video||(this.video=document.createElement("video"),this.video.muted=!0,this.video.playsInline=!0,this.video.crossOrigin="anonymous",this.video.preload="auto",this.video.style.cssText="position:fixed;width:320px;height:180px;pointer-events:none;opacity:0.001;z-index:-1000;top:0;left:0;",document.body.appendChild(this.video),this.video.addEventListener("loadedmetadata",this.handleLoadedMetadata),this.video.addEventListener("error",this.handleVideoError),this.canvas=document.createElement("canvas"),this.canvas.width=320,this.canvas.height=180,this.ctx=this.canvas.getContext("2d",{willReadFrequently:!0}))}setSource(e){if(!e||e.includes("Embed")||e.includes("youtube.com")||e.includes("youtu.be")||e.includes("vimeo.com")){this.currentSrc="",this.pendingSrc="",this.cache.clear(),this.pendingRequests.clear();for(const t of this.seekQueue)t.resolve(null);this.seekQueue=[],this.isSeeking=!1,this.isMetadataLoaded=!1,this.hasError=!1,this.consecutiveFailures=0,this.metadataPromise=null,this.resolveMetadata=null,this.destroyStreamingInstances();return}if(this.pendingSrc!==e){this.pendingSrc=e,this.cache.clear(),this.pendingRequests.clear();for(const t of this.seekQueue)t.resolve(null);this.seekQueue=[],this.isSeeking=!1,this.isMetadataLoaded=!1,this.hasError=!1,this.consecutiveFailures=0,this.metadataPromise=null,this.resolveMetadata=null,this.destroyStreamingInstances()}}loadPendingSource(){const e=this.pendingSrc;if(e&&(this.currentSrc=e,this.isMetadataLoaded=!1,this.hasError=!1,this.metadataPromise=new Promise(t=>{this.resolveMetadata=t}),this.initVideoAndCanvas(),this.video)){let t="mp4";const i=e.split("?")[0].toLowerCase();i.endsWith(".m3u8")?t="hls":i.endsWith(".mpd")?t="dash":i.endsWith(".webm")&&(t="webm"),t==="hls"?Ri().then(s=>{if(this.currentSrc!==e||!this.video)return;const r=s;if(r.isSupported()){const a=new r({enableWorker:!0,lowLatencyMode:!0});this.hlsInstance=a,a.attachMedia(this.video),a.on(r.Events.MEDIA_ATTACHED,()=>{this.currentSrc!==e||this.hlsInstance!==a||a.loadSource(e)}),a.on(r.Events.ERROR,(n,l)=>{console.error("[VideoFrameThumbnailProvider HLS Error]:",l.type,l.details,"fatal:",l.fatal)}),a.on(r.Events.MANIFEST_PARSED,()=>{this.currentSrc!==e||this.hlsInstance!==a||(a.currentLevel=0,a.loadLevel=0)})}else this.video.canPlayType("application/vnd.apple.mpegurl")&&(this.video.src=e,this.video.load())}).catch(s=>{console.debug("[VideoFrameThumbnailProvider] Failed to load hls.js:",s),this.hasError=!0,this.resolveMetadata&&this.resolveMetadata()}):t==="dash"?$i().then(s=>{if(this.currentSrc!==e||!this.video)return;const a=s.MediaPlayer().create();this.dashInstance=a,a.updateSettings({streaming:{abr:{autoSwitchBitrate:{video:!1}}}}),a.initialize(this.video,e,!1),a.on("streamInitialized",()=>{if(!(this.currentSrc!==e||this.dashInstance!==a)){try{const n=a.getRepresentationsByType?a.getRepresentationsByType("video"):[];n.length>0&&(typeof a.setRepresentationForTypeById=="function"?a.setRepresentationForTypeById("video",n[0].id):typeof a.setQualityFor=="function"&&a.setQualityFor("video",0,!0))}catch(n){console.debug("[VideoFrameThumbnailProvider] Failed to set quality on DASH instance:",n)}this.isMetadataLoaded=!0,this.resolveMetadata&&this.resolveMetadata()}}),a.on("error",n=>{this.currentSrc!==e||this.dashInstance!==a||(console.debug("[VideoFrameThumbnailProvider] DASH player error:",n),this.hasError=!0,this.resolveMetadata&&this.resolveMetadata())})}).catch(s=>{console.debug("[VideoFrameThumbnailProvider] Failed to load dashjs:",s),this.hasError=!0,this.resolveMetadata&&this.resolveMetadata()}):(this.video.src=e,this.video.load())}}destroyStreamingInstances(){if(this.activeSeekCleanup&&this.activeSeekCleanup(),this.isSeeking=!1,this.seekTimeoutId!==null&&(clearTimeout(this.seekTimeoutId),this.seekTimeoutId=null),this.hlsInstance){try{this.hlsInstance.destroy()}catch{}this.hlsInstance=null}if(this.dashInstance){try{this.dashInstance.destroy()}catch{}this.dashInstance=null}}isUnavailable(){const e=document.getElementById("test-player");if(e&&e.playerState){const t=e.playerState;if(t.isLive&&!t.canSeekInDvr)return!0}return!this.pendingSrc||this.hasError}getNearestCachedThumbnail(e){var s;if(((s=this.config)==null?void 0:s.cache)===!1||this.cache.size===0)return null;let t=null,i=1/0;for(const[r,a]of this.cache.entries()){const n=Math.abs(r-e);n<i&&(i=n,t=a)}return t}getThumbnail(e,t="high"){var o;if(!this.pendingSrc)return null;const i=document.getElementById("test-player"),s=!!(i&&i.playerState&&i.playerState.isLive);if(s&&this.video)try{const d=this.video.seekable;if(d&&d.length>0){const h=d.start(0);for(const u of this.cache.keys())u<h-10&&this.cache.delete(u);for(const u of this.pendingRequests.keys())u<h-10&&this.pendingRequests.delete(u)}}catch{}if(s){const h=Date.now()-this.lastSeekTime;let u=!1;if(h>3e4)u=!0;else if(this.video){const f=this.video.seekable;if(f&&f.length>0){const p=f.end(f.length-1);e>p+10&&(u=!0)}else u=!0}u&&(this.cache.clear(),this.pendingRequests.clear(),this.destroyStreamingInstances(),this.currentSrc="")}if(this.currentSrc!==this.pendingSrc&&this.loadPendingSource(),!this.video)return null;const r=Math.round(e*10)/10,a=this.pendingRequests.get(r);if(a)return a;if(((o=this.config)==null?void 0:o.cache)!==!1){const d=this.cache.get(r);if(d)return d}const n=this.getNearestCachedThumbnail(e);if(n&&n.time!==void 0&&Math.abs(n.time-e)<=.2)return n;t==="high"&&(this.lastHighPriorityTime=Date.now());const l=new Promise((d,h)=>{if(t==="high"){const u=this.seekQueue.findIndex(f=>f.priority==="high");if(u!==-1){const f=this.seekQueue.splice(u,1)[0];f.resolve(null);const p=Math.round(f.time*10)/10;this.pendingRequests.delete(p)}}if(this.seekQueue.push({time:e,priority:t,resolve:u=>{this.pendingRequests.delete(r),d(u)},reject:u=>{this.pendingRequests.delete(r),h(u)}}),t==="low"){const u=[];if(this.seekQueue.forEach((f,p)=>{f.priority==="low"&&u.push(p)}),u.length>9){const f=u.length-9,p=new Set(u.slice(0,f)),g=[];this.seekQueue.forEach((m,v)=>{if(p.has(v)){m.resolve(null);const y=Math.round(m.time*10)/10;this.pendingRequests.delete(y)}else g.push(m)}),this.seekQueue=g}}this.processQueue()});return this.pendingRequests.set(r,l),l}async processQueue(){var g,m;if(this.isSeeking||this.seekQueue.length===0||!this.video)return;const e=Date.now(),t=e-this.lastSeekTime;if(t<this.throttleMs){this.seekTimeoutId!==null&&clearTimeout(this.seekTimeoutId),this.seekTimeoutId=setTimeout(()=>{this.seekTimeoutId=null,this.processQueue()},this.throttleMs-t);return}this.seekTimeoutId!==null&&(clearTimeout(this.seekTimeoutId),this.seekTimeoutId=null);const i=e-this.lastHighPriorityTime<2e3,s=this.seekQueue.some(v=>v.priority==="high");if(i&&!s&&!this.isPreciseSeeking){const v=2e3-(e-this.lastHighPriorityTime);this.seekTimeoutId!==null&&clearTimeout(this.seekTimeoutId),this.seekTimeoutId=setTimeout(()=>{this.seekTimeoutId=null,this.processQueue()},v);return}let r=this.seekQueue.findIndex(v=>v.priority==="high");r===-1&&(r=0),this.lastSeekTime=e,this.isSeeking=!0;const a=this.seekQueue.splice(r,1)[0];let n=a.time;if(this.video&&this.video.seekable&&this.video.seekable.length>0){const v=this.video.seekable.start(0),y=this.video.seekable.end(this.video.seekable.length-1);n=Math.max(v,Math.min(n,y))}const l=Math.round(n*10)/10,o=((g=this.config)==null?void 0:g.cache)!==!1?this.cache.get(l):null;if(o){this.isSeeking=!1,a.resolve(o),this.processQueue();return}if(!this.isMetadataLoaded&&!this.hasError&&this.metadataPromise&&await this.metadataPromise,this.hasError){a.resolve(null),this.isSeeking=!1,this.processQueue();return}if(Math.abs(this.video.currentTime-n)<.01&&this.video.readyState>=2){try{let v=null,y=0;const b=3;for(;y<=b&&(v=this.captureFrame(l),!(v&&!this.isCanvasBlank()));)if(y<b)y++,await new Promise(S=>setTimeout(S,40));else break;if(v){if(((m=this.config)==null?void 0:m.cache)!==!1){if(this.cache.size>=this.MAX_CACHE_SIZE){const S=this.cache.keys().next().value;S!==void 0&&this.cache.delete(S)}this.cache.set(l,v)}this.consecutiveFailures=0,a.resolve(v)}else this.handleFailure(a)}catch(v){Gt(v)?(console.debug("[VideoFrameThumbnailProvider] CORS security error. Disabling seeks for this source immediately."),this.hasError=!0,a.resolve(null)):this.handleFailure(a)}this.isSeeking=!1,this.processQueue();return}let h=null;const u=async()=>{var v;if(!(this.video&&this.video.readyState<2)){p();try{if(this.video&&this.video.readyState>=2){let y=null,b=0;const S=3;for(;b<=S&&(y=this.captureFrame(l),!(y&&!this.isCanvasBlank()));)if(b<S)b++,await new Promise(T=>setTimeout(T,40));else break;if(y){if(((v=this.config)==null?void 0:v.cache)!==!1){if(this.cache.size>=this.MAX_CACHE_SIZE){const T=this.cache.keys().next().value;T!==void 0&&this.cache.delete(T)}this.cache.set(l,y)}this.consecutiveFailures=0,a.resolve(y)}else this.handleFailure(a)}else console.warn("[VideoFrameThumbnailProvider] seeked fired but video readyState < 2."),this.handleFailure(a)}catch(y){console.debug("[VideoFrameThumbnailProvider] Canvas snapshot capture failed (CORS/tainted canvas or exception):",y),Gt(y)?(console.debug("[VideoFrameThumbnailProvider] CORS security error. Disabling seeks for this source immediately."),this.hasError=!0,a.resolve(null)):this.handleFailure(a)}this.isSeeking=!1,this.processQueue()}},f=v=>{p(),console.debug("[VideoFrameThumbnailProvider] Error event fired during video seek:",v),this.handleFailure(a),this.isSeeking=!1,this.processQueue()},p=()=>{this.video&&(this.video.removeEventListener("seeked",u),this.video.removeEventListener("loadeddata",u),this.video.removeEventListener("canplay",u),this.video.removeEventListener("error",f)),h!==null&&(clearTimeout(h),h=null),this.activeSeekCleanup=null};this.activeSeekCleanup=p,this.video.addEventListener("seeked",u),this.video.addEventListener("loadeddata",u),this.video.addEventListener("canplay",u),this.video.addEventListener("error",f),h=setTimeout(async()=>{console.warn(`[VideoFrameThumbnailProvider] Seek timeout reached for time ${n}s. Recovering...`),p();try{if(this.video&&this.video.readyState>=2){let v=null,y=0;const b=3;for(;y<=b&&(v=this.captureFrame(l),!(v&&!this.isCanvasBlank()));)if(y<b)y++,await new Promise(S=>setTimeout(S,40));else break;if(v){if(this.cache.size>=this.MAX_CACHE_SIZE){const S=this.cache.keys().next().value;S!==void 0&&this.cache.delete(S)}this.cache.set(l,v),this.consecutiveFailures=0,a.resolve(v)}else this.handleFailure(a)}else this.handleFailure(a)}catch(v){Gt(v)?(console.debug("[VideoFrameThumbnailProvider] CORS security error on seek timeout. Disabling seeks for this source immediately."),this.hasError=!0,a.resolve(null)):this.handleFailure(a)}this.isSeeking=!1,this.processQueue()},2e3),this.hlsInstance&&this.hlsInstance.startLoad(),this.video.currentTime=n}handleFailure(e){this.consecutiveFailures++,console.debug(`[VideoFrameThumbnailProvider] Seek failed. Consecutive failures: ${this.consecutiveFailures}`),e.resolve(null)}captureFrame(e){if(!this.video||!this.canvas||!this.ctx)return null;const t=this.video.videoWidth||160,i=this.video.videoHeight||90,s=t/i,r=320,a=320;let n=r,l=Math.round(n/s);return l>a&&(l=a,n=Math.round(l*s)),(this.canvas.width!==n||this.canvas.height!==l)&&(this.canvas.width=n,this.canvas.height=l),this.ctx.drawImage(this.video,0,0,this.canvas.width,this.canvas.height),{url:this.canvas.toDataURL("image/jpeg",.8),width:this.canvas.width,height:this.canvas.height,time:e}}isCanvasBlank(){if(!this.canvas||!this.ctx)return!0;const e=this.canvas.width,t=this.canvas.height;try{const s=this.ctx.getImageData(0,0,e,t).data;let r=0;for(let n=0;n<s.length;n+=16){const l=s[n],o=s[n+1],d=s[n+2];s[n+3]>10&&(l>8||o>8||d>8)&&r++}const a=s.length/16;return r/a<.01}catch{return!1}}destroy(){if(!this.isDestroyed){this.isDestroyed=!0,this.cache.clear(),this.pendingRequests.clear();for(const e of this.seekQueue)e.resolve(null);if(this.seekQueue=[],this.isSeeking=!1,this.activeSeekCleanup&&this.activeSeekCleanup(),this.destroyStreamingInstances(),this.video){this.video.removeEventListener("loadedmetadata",this.handleLoadedMetadata),this.video.removeEventListener("error",this.handleVideoError);try{this.video.pause()}catch{}this.video.removeAttribute("src");try{this.video.load()}catch{}this.video.parentNode&&this.video.parentNode.removeChild(this.video),this.video=null}this.canvas=null,this.ctx=null}}}class Ji{constructor(e,t){this.type="vtt",this.cues=[],this.isLoaded=!1,this.loadPromise=null,this.cache=new Map,this.vttUrl=e,this.config=t,this.loadPromise=this.loadVTT()}updateConfig(e){this.config=e}async loadVTT(){try{const e=await fetch(this.vttUrl);if(!e.ok)throw new Error(`Failed to fetch VTT: ${e.status} ${e.statusText}`);const t=await e.text();this.parseVTT(t),this.isLoaded=!0}catch(e){console.debug("[VTTThumbnailProvider] Error loading VTT:",e)}}parseVTT(e){const t=e.split(/\r?\n/);let i=null;const s=new URL(this.vttUrl,window.location.href),r=/([\d:.]+)\s*-->\s*([\d:.]+)/;for(let a=0;a<t.length;a++){const n=t[a].trim();if(!n)continue;const l=n.match(r);if(l){const o=this.parseTimestamp(l[1]),d=this.parseTimestamp(l[2]);i={start:o,end:d}}else if(i&&n.indexOf("-->")===-1&&n!=="WEBVTT"){const o=n,d=o.indexOf("#");let h=o,u,f,p,g;if(d!==-1){h=o.substring(0,d);const m=o.substring(d+1);if(m.startsWith("xywh=")){const v=m.substring(5).split(",").map(Number);v.length===4&&(u=v[0],f=v[1],p=v[2],g=v[3])}}i.url=new URL(h,s).href,u!==void 0&&(i.x=u),f!==void 0&&(i.y=f),p!==void 0&&(i.width=p),g!==void 0&&(i.height=g),this.cues.push(i),i=null}}}parseTimestamp(e){const t=e.trim().replace(",",".").split(":");let i=0;return t.length===3?(i+=parseFloat(t[0])*3600,i+=parseFloat(t[1])*60,i+=parseFloat(t[2])):t.length===2&&(i+=parseFloat(t[0])*60,i+=parseFloat(t[1])),i}getNearestCachedThumbnail(e){var s;if(((s=this.config)==null?void 0:s.cache)===!1)return null;let t=this.cues.find(r=>e>=r.start&&e<=r.end);if(!t&&this.cues.length>0){let r=1/0;for(const a of this.cues){const n=(a.start+a.end)/2,l=Math.abs(n-e);l<r&&(r=l,t=a)}}if(!t)return null;const i=this.cache.get(t.url);return i&&i.complete?{url:t.url,x:t.x,y:t.y,width:t.width,height:t.height,time:e}:null}async getThumbnail(e,t="high"){var r;this.loadPromise&&await this.loadPromise;let i=this.cues.find(a=>e>=a.start&&e<=a.end);if(!i&&this.cues.length>0){let a=1/0;for(const n of this.cues){const l=(n.start+n.end)/2,o=Math.abs(l-e);o<a&&(a=o,i=n)}}if(!i)return null;if(((r=this.config)==null?void 0:r.cache)!==!1)if(this.cache.has(i.url)){const a=this.cache.get(i.url);a.complete||await new Promise(n=>{a.onload=n,a.onerror=n})}else{const a=new Image;a.src=i.url,this.cache.set(i.url,a),a.complete||await new Promise(n=>{a.onload=n,a.onerror=n})}else{const a=new Image;a.src=i.url,a.complete||await new Promise(n=>{a.onload=n,a.onerror=n})}return{url:i.url,x:i.x,y:i.y,width:i.width,height:i.height,time:e}}destroy(){this.cache.clear(),this.cues=[]}isUnavailable(){return!this.vttUrl}}class es{constructor(e,t,i){this.type="sprite",this.cache=null,this.loadPromise=null,this.spriteUrl=e,this.spriteInfo=t,this.config=i}updateConfig(e){this.config=e}preloadImage(){return this.loadPromise?this.loadPromise:(this.loadPromise=new Promise(e=>{const t=new Image;t.onload=()=>{this.cache=t,e()},t.onerror=()=>{e()},t.src=this.spriteUrl}),this.loadPromise)}getNearestCachedThumbnail(e){var t;return((t=this.config)==null?void 0:t.cache)===!1?null:this.cache&&this.cache.complete?{...this.calculateThumbnail(e),time:e}:null}async getThumbnail(e,t="high"){return await this.preloadImage(),{...this.calculateThumbnail(e),time:e}}calculateThumbnail(e){const{tileWidth:t,tileHeight:i,totalColumns:s,interval:r}=this.spriteInfo,a=Math.floor((Math.max(0,e)+1e-4)/r),n=a%s,l=Math.floor(a/s);return{url:this.spriteUrl,x:n*t,y:l*i,width:t,height:i,time:a*r+r/2}}destroy(){this.cache=null,this.loadPromise=null}isUnavailable(){return!this.spriteUrl||!this.spriteInfo}}class _e{constructor(e){this.type="auto",this.currentProvider=null,this.currentSrc="",this.config=e}static resolveSmartSeek(e){if(e)return e.smartSeek&&typeof e.smartSeek=="object"?e.smartSeek:e}updateConfig(e){this.config=e;const t=_e.resolveSmartSeek(e);if(this.currentProvider){const i=this.currentProvider;typeof i.updateConfig=="function"?i.updateConfig(t):i.config=t}}setSource(e,t){var l;if(this.currentSrc===e)return;if(this.currentSrc=e,this.currentProvider&&typeof this.currentProvider.destroy=="function")try{this.currentProvider.destroy()}catch(o){console.debug("[AutoThumbnailProvider] Error destroying provider:",o)}this.currentProvider=null;const i=(t==null?void 0:t.smartSeek)||_e.resolveSmartSeek(this.config),s=(i==null?void 0:i.type)||"auto";if((i==null?void 0:i.enabled)===!1||s==="none")return;if(s==="vtt"||s==="auto"&&(i!=null&&i.vttUrl)){const o=(i==null?void 0:i.vttUrl)||(t==null?void 0:t.vttUrl);o&&(this.currentProvider=new Ji(o,i))}else if(s==="sprite"||s==="auto"&&(i!=null&&i.spriteUrl)&&i.spriteInfo){const o=i==null?void 0:i.spriteUrl,d=i==null?void 0:i.spriteInfo;o&&d&&(this.currentProvider=new es(o,d,i))}const r=(t==null?void 0:t.preciseSeek)||((l=this.config)==null?void 0:l.preciseSeek),a=typeof r=="object"&&r?r:void 0,n=r!==!1&&(a==null?void 0:a.enabled)!==!1&&(a==null?void 0:a.frameAccurate)!==!1;!this.currentProvider&&n&&(this.currentProvider=new Zi(i)),this.currentProvider&&typeof this.currentProvider.setSource=="function"&&this.currentProvider.setSource(e,t)}getNearestCachedThumbnail(e){return this.currentProvider&&typeof this.currentProvider.getNearestCachedThumbnail=="function"?this.currentProvider.getNearestCachedThumbnail(e):null}getThumbnail(e,t="high"){return this.currentProvider?this.currentProvider.getThumbnail(e,t):null}isUnavailable(){return this.currentProvider&&typeof this.currentProvider.isUnavailable=="function"?this.currentProvider.isUnavailable():!this.currentProvider}destroy(){this.currentProvider&&typeof this.currentProvider.destroy=="function"&&this.currentProvider.destroy(),this.currentProvider=null}}class pe{static timeToPercent(e,t,i){const s=i-t;return s<=0?0:Math.max(0,Math.min((e-t)/s*100,100))}static percentToTime(e,t,i){const s=i-t;return t+e/100*s}static clampToSeekable(e,t,i){return Math.max(t,Math.min(e,i))}static isMarkerVisible(e,t,i){return e>=t&&e<=i}static isWithinSeekable(e,t,i){return e>=t&&e<=i}static shouldPruneMarker(e,t){return e<t}static findNearestMarker(e,t,i,s){if(!t||t.length===0)return null;let r=null,a=1/0;for(const n of t){if(i&&!i.includes(n.type))continue;const l=Math.abs(n.time-e);l<a&&l<=s&&(a=l,r=n)}return r}static findNearestChapter(e,t,i){return!t||t.length===0?-1:t.findIndex((s,r)=>{const a=s.startTime,n=s.endTime!==void 0?s.endTime:t[r+1]?t[r+1].startTime:i||1/0;return e>=a&&e<n})}static findNearestChapterBoundary(e,t,i){if(!t||t.length===0)return null;let s=null,r=1/0;for(const a of t){const n=Math.abs(a.startTime-e);n<r&&n<=i&&(r=n,s=a)}return s}}class yr{constructor(e){var i;this.originalPlaylist=null,this.historyStack=[],this.nearEndThreshold=1,this.hasDispatchedNearEndForCurrentBoundary=!1,this.host=e;const t=(i=e.config)==null?void 0:i.nearEndThreshold;this.nearEndThreshold=t!==void 0?Math.max(1,t):1}get state(){return this.host.getState()}updateState(e){this.host.updateStatePublic(e)}dispatchEvent(e,t){this.host.dispatchEvent(e,t)}loadPlaylist(e,t=0){if(e.length===0){this.clearPlaylist();return}this.originalPlaylist=null;const i=Math.max(0,Math.min(t,e.length-1));this.historyStack=[],this.hasDispatchedNearEndForCurrentBoundary=!1,this.updateState({playlist:e,activePlaylistIndex:i}),this.dispatchEvent("playlist-loaded",{playlist:e,startIndex:i}),this.dispatchEvent("playlist-change",{playlist:e}),e.length>0&&this.loadPlaylistItem(i,!0)}setPlaylist(e,t=0){this.loadPlaylist(e,t)}setNearEndThreshold(e){this.nearEndThreshold=Math.max(1,e),this.hasDispatchedNearEndForCurrentBoundary=!1,this.checkPlaylistNearEnd()}getNearEndThreshold(){return this.nearEndThreshold}getPlaylist(){return this.state.playlist}getCurrentPlaylistIndex(){return this.state.activePlaylistIndex}getHistoryStack(){return[...this.historyStack]}getCurrentPlaylistItem(){if(!this.hasPlaylist())return null;const e=this.state.activePlaylistIndex;return e<0||e>=this.state.playlist.length?null:this.state.playlist[e]}getPlaylistLength(){return this.state.playlist.length}hasPlaylist(){return this.state.playlist.length>0}isFirstPlaylistItem(){return this.hasPlaylist()?this.state.activePlaylistIndex===0:!1}isLastPlaylistItem(){return this.hasPlaylist()?this.state.activePlaylistIndex===this.state.playlist.length-1:!1}next(){if(this.state.playlist.length<=1)return;const e=(this.state.activePlaylistIndex+1)%this.state.playlist.length,t=this.state.playlist[e];this.dispatchEvent("playlist-next",{index:e,source:t}),this.loadPlaylistItem(e,!1)}previous(){if(this.state.playlist.length<=1)return;let e;this.historyStack.length>0?e=this.historyStack.pop():e=(this.state.activePlaylistIndex-1+this.state.playlist.length)%this.state.playlist.length;const t=this.state.playlist[e];this.dispatchEvent("playlist-previous",{index:e,source:t}),this.loadPlaylistItem(e,!0)}appendPlaylistItem(e){const t=[...this.state.playlist,e];this.hasDispatchedNearEndForCurrentBoundary=!1,this.updateState({playlist:t}),this.dispatchEvent("playlist-change",{playlist:t}),this.dispatchEvent("playlist-item-added",{index:t.length-1,source:e}),t.length===1?this.loadPlaylistItem(0):this.checkPlaylistNearEnd()}insertPlaylistItem(e,t){if(e<0||e>this.state.playlist.length)return;this.hasDispatchedNearEndForCurrentBoundary=!1;const i=e,s=[...this.state.playlist];s.splice(i,0,t);let r=this.state.activePlaylistIndex;s.length>1&&i<=this.state.activePlaylistIndex&&(r=this.state.activePlaylistIndex+1);const a=r!==this.state.activePlaylistIndex;this.historyStack=this.historyStack.map(n=>n>=i?n+1:n),this.updateState({playlist:s,activePlaylistIndex:r}),this.dispatchEvent("playlist-change",{playlist:s}),this.dispatchEvent("playlist-item-added",{index:i,source:t}),s.length===1?this.loadPlaylistItem(0,!0):(a&&this.dispatchEvent("playlist-index-change",{index:r,source:s[r]}),this.checkPlaylistNearEnd())}removePlaylistItem(e){if(e<0||e>=this.state.playlist.length)return;this.hasDispatchedNearEndForCurrentBoundary=!1;const t=this.state.playlist[e],i=e===this.state.activePlaylistIndex,s=this.state.isPlaying,r=[...this.state.playlist];if(r.splice(e,1),this.historyStack=this.historyStack.filter(l=>l!==e).map(l=>l>e?l-1:l),r.length===0){this.updateState({playlist:[],activePlaylistIndex:0}),this.historyStack=[],this.dispatchEvent("playlist-change",{playlist:[]}),this.dispatchEvent("playlist-item-removed",{index:e,source:t}),this.dispatchEvent("playlist-cleared"),this.host.loadSource({src:""}),this.checkPlaylistNearEnd();return}let a=this.state.activePlaylistIndex;i?a=e>=r.length?0:e:e<this.state.activePlaylistIndex&&(a=this.state.activePlaylistIndex-1),a=Math.max(0,Math.min(a,r.length-1));const n=a!==this.state.activePlaylistIndex;this.updateState({playlist:r,activePlaylistIndex:a}),this.dispatchEvent("playlist-change",{playlist:r}),this.dispatchEvent("playlist-item-removed",{index:e,source:t}),i?(this.loadPlaylistItem(a,!0),s&&this.host.play()):(n&&this.dispatchEvent("playlist-index-change",{index:a,source:r[a]}),this.checkPlaylistNearEnd())}clearPlaylist(){this.state.playlist.length!==0&&(this.originalPlaylist=null,this.hasDispatchedNearEndForCurrentBoundary=!1,this.historyStack=[],this.updateState({playlist:[],activePlaylistIndex:0}),this.dispatchEvent("playlist-change",{playlist:[]}),this.dispatchEvent("playlist-cleared"),this.host.loadSource({src:""}),this.checkPlaylistNearEnd())}replacePlaylistItem(e,t){if(e<0||e>=this.state.playlist.length)return;this.hasDispatchedNearEndForCurrentBoundary=!1;const i=[...this.state.playlist];i[e]=t;const s=e===this.state.activePlaylistIndex,r=this.state.isPlaying;this.updateState({playlist:i}),this.dispatchEvent("playlist-change",{playlist:i}),this.dispatchEvent("playlist-item-replaced",{index:e,source:t}),s?(this.loadPlaylistItem(e,!0),r&&this.host.play()):this.checkPlaylistNearEnd()}movePlaylistItem(e,t){if(e<0||e>=this.state.playlist.length||t<0||t>=this.state.playlist.length||e===t)return;this.hasDispatchedNearEndForCurrentBoundary=!1;const i=[...this.state.playlist],[s]=i.splice(e,1);i.splice(t,0,s);const r=this.state.activePlaylistIndex;let a=r;r===e?a=t:e<r&&r<=t?a=r-1:t<=r&&r<e&&(a=r+1);const n=a!==r;if(this.historyStack=this.historyStack.map(l=>l===e?t:e<l&&l<=t?l-1:t<=l&&l<e?l+1:l),this.updateState({playlist:i,activePlaylistIndex:a}),this.dispatchEvent("playlist-change",{playlist:i}),this.dispatchEvent("playlist-item-moved",{fromIndex:e,toIndex:t,source:s}),n){const l=i[a];this.dispatchEvent("playlist-index-change",{index:a,source:l})}this.checkPlaylistNearEnd()}loadPlaylistItem(e,t=!1){if(e<0||e>=this.state.playlist.length)return;const i=this.state.activePlaylistIndex;this.updateState({activePlaylistIndex:e});const s=this.state.playlist[e];this.dispatchEvent("playlist-index-change",{index:e,source:s}),!t&&i!==e&&this.historyStack.push(i),this.host.loadSource(s,!1),this.checkPlaylistNearEnd()}setPlaylistRepeatMode(e){(e==="off"||e==="repeat-all")&&(this.updateState({playlistRepeatMode:e}),this.dispatchEvent("playlist-repeat-change",{repeatMode:e}))}getPlaylistRepeatMode(){return this.state.playlistRepeatMode}getAutoAdvanceIndexOnEnded(){var t,i;if(this.state.loop&&this.state.displayMode!=="vertical"||this.state.playlist.length<=1)return null;if(!this.isLastPlaylistItem())return(this.state.activePlaylistIndex+1)%this.state.playlist.length;if(this.state.playlistRepeatMode==="repeat-all"||this.state.displayMode==="vertical"){const s=((i=(t=this.host.config)==null?void 0:t.vertical)==null?void 0:i.loopPlaylist)!==!1;return this.state.displayMode==="vertical"&&!s?null:0}return null}checkPlaylistNearEnd(){if(!this.hasPlaylist()){this.hasDispatchedNearEndForCurrentBoundary=!1;return}const e=this.getPlaylistLength(),t=this.getCurrentPlaylistIndex(),i=Math.max(1,e),s=Math.max(1,Math.min(this.nearEndThreshold,i)),r=e-1-t;r<=s?this.hasDispatchedNearEndForCurrentBoundary||(this.hasDispatchedNearEndForCurrentBoundary=!0,this.dispatchEvent("playlist-near-end",{index:t,length:e,remainingItems:r,threshold:s})):this.hasDispatchedNearEndForCurrentBoundary=!1}clearForExternalSourceLoad(){this.originalPlaylist=null,this.updateState({playlist:[],activePlaylistIndex:0}),this.historyStack=[],this.dispatchEvent("playlist-change",{playlist:[]}),this.dispatchEvent("playlist-cleared")}destroy(){this.originalPlaylist=null,this.historyStack=[],this.hasDispatchedNearEndForCurrentBoundary=!1}}const oe={getItem(c){try{if(typeof localStorage<"u")return localStorage.getItem(c)}catch{}return null},setItem(c,e){try{typeof localStorage<"u"&&localStorage.setItem(c,e)}catch{}}},br={fontFamily:"default",fontSize:75,fontColor:"white",backgroundColor:"black",backgroundOpacity:75,windowColor:"black",windowOpacity:0,characterEdgeStyle:"none",fontOpacity:100};class kr{constructor(e,t){this.defaultAppearance={...br},this.managedTracks=[],this.managedActiveTrackId=null,this.managedActiveTrackIndex=-1,this.subtitleBlobUrls=[],this.handleTrackChange=()=>{this.refreshSubtitleTracks()},this.host=e,this.sourceManager=t}get video(){return this.host.getVideoElement()}get state(){return this.host.getState()}updateState(e){this.host.updateStatePublic(e)}dispatchEvent(e,t){this.host.dispatchEvent(e,t)}getDefaultAppearance(){return this.defaultAppearance}readPersistedSettings(){let e=!1,t={...this.defaultAppearance};try{const i=oe.getItem("player_subtitles_enabled");i!==null&&(e=i==="true");const s=oe.getItem("player_subtitle_appearance");if(s!==null){const r=JSON.parse(s);t={...this.defaultAppearance,...r}}}catch(i){console.warn("Failed to load persisted subtitles settings:",i)}return{captionsEnabled:e,appearance:t}}attach(){const e=this.video;e.textTracks&&typeof e.textTracks.addEventListener=="function"&&(e.textTracks.addEventListener("addtrack",this.handleTrackChange),e.textTracks.addEventListener("removetrack",this.handleTrackChange),e.textTracks.addEventListener("change",this.handleTrackChange)),this.syncSubtitleAppearance()}detach(){const e=this.video;e.textTracks&&typeof e.textTracks.removeEventListener=="function"&&(e.textTracks.removeEventListener("addtrack",this.handleTrackChange),e.textTracks.removeEventListener("removetrack",this.handleTrackChange),e.textTracks.removeEventListener("change",this.handleTrackChange))}setManagedSubtitleTracks(e,t,i){if(this.managedTracks=t.map((s,r)=>({id:`${e}-${s.language||"unknown"}-${r}`,language:s.language||"",label:s.label||s.language||`Track ${r+1}`,default:!!s.default,forced:!!s.forced,kind:s.kind||"subtitles",source:e,index:r})),this.managedActiveTrackIndex=i,i>=0&&i<this.managedTracks.length?this.managedActiveTrackId=this.managedTracks[i].id:this.managedActiveTrackId=null,this.refreshSubtitleTracks(),this.state.captionsEnabled&&this.state.activeSubtitleTrackId===null){const s=oe.getItem("player_subtitle_language");let r=s?this.state.subtitleTracks.find(a=>a.language===s||a.id===s):null;r||(r=this.state.subtitleTracks.find(a=>a.default)||this.state.subtitleTracks[0]),r&&this.setSubtitleTrack(r.id)}}refreshSubtitleTracks(){const e=this.sourceManager.getActiveHandler();let t=[],i=null,s=-1,r=!1;if(e&&e.managesSubtitles){t=[...this.managedTracks],i=this.managedActiveTrackId,s=this.managedActiveTrackIndex;const o=this.video.textTracks;if(o&&o.length>0){let d=t.length;for(let h=0;h<o.length;h++){const u=o[h];if(u.kind==="subtitles"||u.kind==="captions"){if(u._zombie)continue;if(this.managedTracks.some(m=>m.label===u.label&&m.language===u.language||u.language&&m.language===u.language)){if(u.mode==="showing"){const m=this.managedTracks.find(v=>v.label===u.label&&v.language===u.language||u.language&&v.language===u.language);m&&(i=m.id,s=m.index??-1)}continue}const p=u.id||`native-embedded-${u.language||"unknown"}-${d}`,g=u.default||!1;t.push({id:p,language:u.language||"",label:u.label||u.language||`Embedded Track ${d+1}`,default:g,forced:!1,kind:u.kind,source:"native",index:h}),u.mode==="showing"&&(i=p,s=d),d++}}}r=t.length>0}else{const o=this.video.textTracks;if(o&&o.length>0){let d=0;for(let h=0;h<o.length;h++){const u=o[h];if(u.kind==="subtitles"||u.kind==="captions"){if(u._zombie)continue;const f=u.id||`native-${u.language||"unknown"}-${d}`,p=u.default||!1;t.push({id:f,language:u.language||"",label:u.label||u.language||`Track ${d+1}`,default:p,forced:!1,kind:u.kind,source:"native",index:h}),u.mode==="showing"&&(i=f,s=d),d++}}}r=t.length>0}const a=i!==null;if(!a){const o=this.video.textTracks;if(o)for(let d=0;d<o.length;d++)o[d].mode==="showing"&&(o[d].mode="disabled")}const n=JSON.stringify(this.state.subtitleTracks)!==JSON.stringify(t),l=this.state.activeSubtitleTrackId!==i||this.state.activeSubtitleTrack!==s||this.state.captionsEnabled!==a;if(this.updateState({subtitleTracks:t,activeSubtitleTrack:s,activeSubtitleTrackId:i,captionsEnabled:a,hasCaptions:r}),n&&this.dispatchEvent("subtitletrackschanged",{tracks:t}),l){const o=t.find(d=>d.id===i)||null;this.dispatchEvent("subtitletrackchange",{activeTrack:o}),a?this.dispatchEvent("subtitleenabled",{activeTrack:o}):this.dispatchEvent("subtitledisabled");try{oe.setItem("player_subtitles_enabled",a.toString()),o&&oe.setItem("player_subtitle_language",o.language||o.id)}catch{}}this.dispatchEvent("subtitlechange",{activeSubtitleTrack:s})}loadCaptions(e){this.video.querySelectorAll("track").forEach(a=>a.remove());const i=document.createElement("track");i.kind="subtitles",i.label=e.label,i.srclang=e.srclang,i.src=e.src,e.default&&(i.default=!0),this.video.appendChild(i);const s=oe.getItem("player_subtitles_enabled");(s!==null?s==="true":!!e.default)&&setTimeout(()=>this.toggleCaptions(!0),100),this.refreshSubtitleTracks()}toggleCaptions(e){if(e!==void 0?e:!this.state.captionsEnabled){const i=this.state.subtitleTracks;if(i.length>0){const s=oe.getItem("player_subtitle_language"),r=i.find(a=>a.language===s||a.id===s||a.default)||i[0];this.setSubtitleTrack(r.id)}else{const s=this.video.textTracks;s&&s.length>0?(s[0].mode="showing",this.refreshSubtitleTracks()):this.updateState({captionsEnabled:!0})}}else this.disableSubtitles()}setSubtitleTrack(e){const t=this.state.subtitleTracks;let i;if(typeof e=="number"?i=t[e]:i=t.find(r=>r.id===e),!i){this.disableSubtitles();return}const s=this.sourceManager.getActiveHandler();if(s&&s.managesSubtitles&&i.source!=="native")s.setSubtitleTrack&&i.index!==void 0&&(s.setSubtitleTrack(i.index),this.managedActiveTrackId=i.id,this.managedActiveTrackIndex=i.index);else{const r=this.video.textTracks;if(r&&i.index!==void 0)for(let a=0;a<r.length;a++)(r[a].kind==="subtitles"||r[a].kind==="captions")&&(r[a].mode=a===i.index?"showing":"disabled")}this.refreshSubtitleTracks()}disableSubtitles(){const e=this.sourceManager.getActiveHandler();if(e&&e.managesSubtitles)e.setSubtitleTrack&&(e.setSubtitleTrack(-1),this.managedActiveTrackId=null,this.managedActiveTrackIndex=-1);else{const t=this.video.textTracks;if(t)for(let i=0;i<t.length;i++)(t[i].kind==="subtitles"||t[i].kind==="captions")&&(t[i].mode="disabled")}this.refreshSubtitleTracks()}hasSubtitles(){return this.state.hasCaptions}getSubtitleTracks(){return this.state.subtitleTracks}getActiveSubtitleTrack(){const e=this.state.subtitleTracks,t=this.state.activeSubtitleTrackId;return e.find(i=>i.id===t)||null}getSubtitleAppearance(){return this.state.subtitleAppearance}setSubtitleAppearance(e){const t={...this.state.subtitleAppearance,...e};this.updateState({subtitleAppearance:t});try{oe.setItem("player_subtitle_appearance",JSON.stringify(t))}catch{}this.syncSubtitleAppearance(),this.dispatchEvent("subtitleappearancechange",{appearance:t})}resetSubtitleAppearance(){this.setSubtitleAppearance(this.defaultAppearance)}syncSubtitleAppearance(){const e=this.state.subtitleAppearance,t=this.video;if(!t)return;const i={white:"255, 255, 255",black:"0, 0, 0",red:"255, 0, 0",green:"0, 255, 0",blue:"0, 0, 255",yellow:"255, 255, 0",magenta:"255, 0, 255",cyan:"0, 255, 255"},s={default:"inherit","proportional-sans-serif":"'Outfit', 'Inter', system-ui, -apple-system, sans-serif","monospace-sans-serif":"'Courier New', 'Andale Mono', monospace","proportional-serif":"'Georgia', 'Times New Roman', serif","monospace-serif":"'Courier New', 'Courier', serif",casual:"'Comic Sans MS', 'Chalkboard SE', sans-serif",cursive:"'Comic Sans MS', 'Lucida Handwriting', cursive","small-capitals":"'Outfit', 'Inter', system-ui, sans-serif"},r={default:"none",none:"none",raised:"1px 1px 0px #000, 2px 2px 0px #000, -1px -1px 0px #fff",depressed:"1px 1px 0px #fff, -1px -1px 0px #000",uniform:"-1px -1px 0 #000, 1px -1px 0 #000, -1px 1px 0 #000, 1px 1px 0 #000","drop-shadow":"2px 2px 4px rgba(0, 0, 0, 0.8)"},a=i[e.fontColor.toLowerCase()]||"255, 255, 255",n=(e.fontOpacity/100).toFixed(2),l=`rgba(${a}, ${n})`,o=i[e.backgroundColor.toLowerCase()]||"0, 0, 0",d=(e.backgroundOpacity/100).toFixed(2),h=`rgba(${o}, ${d})`,u=i[e.windowColor.toLowerCase()]||"0, 0, 0",f=(e.windowOpacity/100).toFixed(2),p=`rgba(${u}, ${f})`,g=s[e.fontFamily]||"inherit",m=`${e.fontSize}%`,v=r[e.characterEdgeStyle]||"none",y=e.fontFamily==="small-capitals"?"small-caps":"normal";t.style.setProperty("--player-cue-font-family",g),t.style.setProperty("--player-cue-font-size",m),t.style.setProperty("--player-cue-font-color",l),t.style.setProperty("--player-cue-background-color",h),t.style.setProperty("--player-cue-text-shadow",v),t.style.setProperty("--player-cue-window-color",p),t.style.setProperty("--player-cue-font-variant",y)}revokeBlobUrls(){this.subtitleBlobUrls&&(this.subtitleBlobUrls.forEach(e=>{try{typeof URL<"u"&&typeof URL.revokeObjectURL=="function"&&URL.revokeObjectURL(e)}catch{}}),this.subtitleBlobUrls=[])}resetManagedTracks(){this.managedTracks=[],this.managedActiveTrackId=null,this.managedActiveTrackIndex=-1}attachSourceSubtitles(e){if(!e||e.length===0)return;e.forEach(r=>{const a=document.createElement("track");a.kind="subtitles",a.label=r.label,a.srclang=r.srclang,r.default&&(a.default=!0),r.src&&(r.src.startsWith("http")||r.src.startsWith("//"))?fetch(r.src).then(n=>{if(!n.ok)throw new Error(`HTTP error ${n.status}`);return n.text()}).then(n=>{const l=new Blob([n],{type:"text/vtt"});if(typeof URL<"u"&&typeof URL.createObjectURL=="function"){const o=URL.createObjectURL(l);a.src=o,this.subtitleBlobUrls.push(o),this.refreshSubtitleTracks()}else a.src=r.src}).catch(n=>{console.error(`Failed to load external subtitle track from ${r.src}:`,n),a.src=r.src}):a.src=r.src,this.video.appendChild(a)});const t=e.find(r=>r.default)||e[0],i=oe.getItem("player_subtitles_enabled");(i!==null?i==="true":!!t.default)&&setTimeout(()=>this.toggleCaptions(!0),100)}}class Sr{constructor(e){this.handleEnterPiP=()=>{this.host.updateStatePublic({pictureInPicture:!0}),this.host.dispatchEvent("pipchange",{isPictureInPicture:!0})},this.handleLeavePiP=()=>{this.host.updateStatePublic({pictureInPicture:!1}),this.host.dispatchEvent("pipchange",{isPictureInPicture:!1})},this.handleWebkitPresentationModeChanged=()=>{const t=this.video.webkitPresentationMode==="picture-in-picture";this.host.updateStatePublic({pictureInPicture:t}),this.host.dispatchEvent("pipchange",{isPictureInPicture:t})},this.host=e}get video(){return this.host.getVideoElement()}get state(){return this.host.getState()}detectSupport(){const e=this.video,t=!!(typeof document<"u"&&document.pictureInPictureEnabled&&typeof e.requestPictureInPicture=="function"),i=!!(typeof e.webkitSupportsPresentationMode=="function"&&e.webkitSupportsPresentationMode("picture-in-picture"));return t||i}attach(){const e=this.video;e.addEventListener("enterpictureinpicture",this.handleEnterPiP),e.addEventListener("leavepictureinpicture",this.handleLeavePiP),e.addEventListener("webkitpresentationmodechanged",this.handleWebkitPresentationModeChanged)}detach(){const e=this.video;e.removeEventListener("enterpictureinpicture",this.handleEnterPiP),e.removeEventListener("leavepictureinpicture",this.handleLeavePiP),e.removeEventListener("webkitpresentationmodechanged",this.handleWebkitPresentationModeChanged)}isPictureInPictureSupported(){return this.state.pictureInPictureSupported}async enterPictureInPicture(){if(!this.state.pictureInPictureSupported){console.warn("[PlayerController] Picture-in-Picture is not supported in this environment.");return}try{if(typeof this.video.requestPictureInPicture=="function")return await this.video.requestPictureInPicture();{const e=this.video;typeof e.webkitSetPresentationMode=="function"&&e.webkitSetPresentationMode("picture-in-picture")}}catch(e){console.warn("[PlayerController] Failed to enter Picture-in-Picture mode:",e)}}async exitPictureInPicture(){if(!this.state.pictureInPictureSupported){console.warn("[PlayerController] Picture-in-Picture is not supported in this environment.");return}try{if(typeof document.exitPictureInPicture=="function"){const e=document.pictureInPictureElement,t=this.video.getRootNode().pictureInPictureElement;(!e||e===this.video||t===this.video)&&await document.exitPictureInPicture()}else{const e=this.video;typeof e.webkitSetPresentationMode=="function"&&e.webkitSetPresentationMode("inline")}}catch(e){console.warn("[PlayerController] Failed to exit Picture-in-Picture mode:",e)}}isInPictureInPicture(){return this.state.pictureInPicture}}function ts(c,e,t){if(e===t)return!0;if(e==null||t==null)return e===t;if(c==="seekableRange"){const i=e,s=t;return i.start===s.start&&i.end===s.end}if(c==="bufferedRanges"){const i=e,s=t;if(i.length!==s.length)return!1;for(let r=0;r<i.length;r++)if(i[r].start!==s[r].start||i[r].end!==s[r].end)return!1;return!0}if(c==="subtitleAppearance"){const i=e,s=t;return i.fontFamily===s.fontFamily&&i.fontSize===s.fontSize&&i.fontColor===s.fontColor&&i.backgroundColor===s.backgroundColor&&i.backgroundOpacity===s.backgroundOpacity&&i.windowColor===s.windowColor&&i.windowOpacity===s.windowOpacity&&i.characterEdgeStyle===s.characterEdgeStyle&&i.fontOpacity===s.fontOpacity}if(c==="qualities"||c==="audioTracks"){const i=e,s=t;if(i.length!==s.length)return!1;for(let r=0;r<i.length;r++)if(i[r]!==s[r])return!1;return!0}if(c==="subtitleTracks"){const i=e,s=t;if(i.length!==s.length)return!1;for(let r=0;r<i.length;r++){const a=i[r],n=s[r];if(a.id!==n.id||a.language!==n.language||a.label!==n.label||a.default!==n.default||a.forced!==n.forced||a.kind!==n.kind||a.source!==n.source||a.index!==n.index)return!1}return!0}if(c==="chapters"){const i=e,s=t;if(i.length!==s.length)return!1;for(let r=0;r<i.length;r++){const a=i[r],n=s[r];if(a.id!==n.id||a.title!==n.title||a.startTime!==n.startTime||a.endTime!==n.endTime||a.description!==n.description)return!1}return!0}if(c==="markers"){const i=e,s=t;if(i.length!==s.length)return!1;for(let r=0;r<i.length;r++){const a=i[r],n=s[r];if(a.id!==n.id||a.time!==n.time||a.label!==n.label||a.type!==n.type||a.color!==n.color)return!1}return!0}if(c==="playlist"){const i=e,s=t;if(i.length!==s.length)return!1;for(let r=0;r<i.length;r++){const a=i[r],n=s[r];if(a.src!==n.src||a.type!==n.type)return!1}return!0}return typeof e=="object"&&typeof t=="object"?JSON.stringify(e)===JSON.stringify(t):!1}function wr(c){if(Array.isArray(c))return c;if(c&&typeof c=="object"){const e=c.list;if(Array.isArray(e))return e}}class is{constructor(e,t={}){var l;if(this.sourceManager=new Zs,this.stateCallbacks=new Set,this.analyticsHandlers=new Set,this.playbackInterceptors=new Set,this.pendingOverlays=new Map,this.plugins=new Map,this.eventListeners=new Map,this.isDestroyed=!1,this.preSeekVolume=null,this.lastFpsTimestamp=0,this.lastDecodedFrames=0,this.lastCalculatedFps=0,this.handleVisibilityChange=()=>{typeof document<"u"&&document.visibilityState==="visible"&&this.sleepTimerEndTimeMs&&!this.state.sleepTimerExpired&&this.tickSleepTimer()},this.state={status:"idle",isPlaying:!1,currentTime:0,duration:0,volume:1,isMuted:!1,isFullscreen:!1,bufferedRanges:[],playbackRate:1,captionsEnabled:!1,currentSource:null,sourceType:"unknown",isBuffering:!1,isSeeking:!1,hasCaptions:!1,error:null,qualities:[],activeQuality:"Auto",audioTracks:[],activeAudioTrack:-1,subtitleTracks:[],activeSubtitleTrack:-1,activeSubtitleTrackId:null,subtitleAppearance:{fontFamily:"default",fontSize:100,fontColor:"white",backgroundColor:"black",backgroundOpacity:75,windowColor:"black",windowOpacity:0,characterEdgeStyle:"none",fontOpacity:100},isLive:null,isLowLatency:!1,isAtLiveEdge:!1,liveLatency:null,hasDvr:!1,dvrWindow:0,canSeekInDvr:!1,seekableRange:{start:0,end:0},liveMode:"live-dvr",thumbnailProvider:void 0,pictureInPicture:!1,pictureInPictureSupported:!1,loop:!1,sleepTimerSetting:"off",sleepTimerSecondsRemaining:null,sleepTimerExpired:!1,chapters:[],activeChapterIndex:-1,markers:[],visibleMarkerTypes:null,displayMode:"standard",playlist:[],activePlaylistIndex:0,playlistRepeatMode:"off",autoScroll:!1,isAdPlaying:!1,isAdLoading:!1,currentAd:null,currentAdBreak:null,adCurrentTime:null,adRemainingTime:null,adDuration:null,canSkipAd:!1,skipAvailableAt:null,adPosition:null,adProvider:null,adLinear:null,adMuted:null},this.hlsRetryCount=0,this.lastNonZeroVolume=1,this.handlePlay=()=>{const o=this.state.status,d=o==="loading"||o==="buffering"?o:"playing";this.updateState({isPlaying:!0,status:d}),this.startStallCheck(),this.dispatchEvent("play"),this.updateMediaSessionPlaybackState(!0),this.updateMediaSessionPosition()},this.handlePause=()=>{const o=this.state.status,d=o==="playing"||o==="buffering"||o==="ready"?"paused":o;this.updateState({isPlaying:!1,status:d}),this.stopStallCheck(),this.dispatchEvent("pause"),this.updateMediaSessionPlaybackState(!1),this.updateMediaSessionPosition()},this.handleWaiting=()=>{this.clearBufferingTimeout();const o=this.state.status,d=o==="playing"||o==="ready"||o==="paused"?"buffering":o;this.bufferingTimeout=window.setTimeout(()=>{this.bufferingTimeout=void 0,this.updateState({isBuffering:!0,status:d})},250),this.dispatchEvent("waiting")},this.handlePlaying=()=>{this.clearBufferingTimeout(),this.updateState({isBuffering:!1,isPlaying:!0,error:null,status:"playing"}),this.dispatchEvent("playing")},this.handleSeeking=()=>{this.clearBufferingTimeout();let o=this.state.status;o==="ended"&&(o=this.video.paused?"paused":"playing");const d=o==="playing"||o==="ready"||o==="paused"?"buffering":o;this.updateState({isSeeking:!0,status:d}),this.dispatchEvent("seekstart"),this.bufferingTimeout=window.setTimeout(()=>{this.bufferingTimeout=void 0,this.updateState({isBuffering:!0})},250)},this.handleSeeked=()=>{this.clearBufferingTimeout();let o=this.state.status;o==="ended"&&(o=this.video.paused?"paused":"playing");let d=o;o==="buffering"&&(d=this.video.paused?"paused":"playing"),this.updateState({isBuffering:!1,status:d,isSeeking:!1}),this.handleTimeUpdate(),this.dispatchEvent("seekend")},this.handleCanPlay=()=>{if(this.clearBufferingTimeout(),this.state.isBuffering){const o=this.state.status;let d=o;o==="buffering"&&(d=this.video.paused?"paused":"playing"),this.updateState({isBuffering:!1,status:d})}},this.handleNativeError=o=>{if(o&&o.target&&o.target!==this.video)return;this.clearBufferingTimeout();const d=this.video.error?this.video.error.code:0;let h="An unknown video error occurred.";switch(d){case 1:h="Video loading aborted by user.";break;case 2:h="Network error occurred while fetching video content.";break;case 3:h="Video decoding failed. File may be corrupted.";break;case 4:h="Video format or codec is not supported by your browser.";break}this.updateState({error:h,isBuffering:!1,status:"error"}),this.dispatchEvent("error",{message:h})},this.handleTimeUpdate=()=>{if(this.state.isSeeking)return;const o=this.video.currentTime;if(o!==this.state.currentTime&&(this.state.isBuffering||this.bufferingTimeout)){this.clearBufferingTimeout();const f=this.state.status;let p=f;f==="buffering"&&(p=this.video.paused?"paused":"playing"),this.updateState({isBuffering:!1,status:p})}const d=this.getSeekableStateBatch(),h=pe.findNearestChapter(o,this.state.chapters||[],this.video.duration||1/0),u=h!==this.state.activeChapterIndex;this.updateState({currentTime:o,activeChapterIndex:h}),this.dispatchEvent("timeupdate",{currentTime:o,duration:this.state.duration||this.video.duration||0}),this.state.isLive?this.updateLiveState():this.updateState({isLive:d.isLive,hasDvr:d.hasDvr,seekableRange:d.seekableRange,dvrWindow:d.dvrWindow,canSeekInDvr:d.canSeekInDvr}),u&&this.dispatchEvent("chapterchange",{activeChapterIndex:h,chapter:h!==-1?this.state.chapters[h]:null}),this.updateMediaSessionPosition()},this.handleDurationChange=()=>{if(this.state.isLive)this.updateLiveState();else{const o=this.getSeekableStateBatch();this.updateState({duration:this.video.duration,isLive:o.isLive,hasDvr:o.hasDvr,seekableRange:o.seekableRange,dvrWindow:o.dvrWindow,canSeekInDvr:o.canSeekInDvr})}this.updateMediaSessionPosition()},this.handleVolumeChange=()=>{if(this.preSeekVolume!==null){this.video.volume===this.preSeekVolume&&(this.preSeekVolume=null);return}this.video.volume>0&&(this.lastNonZeroVolume=this.video.volume),this.updateState({volume:this.video.volume,isMuted:this.video.muted});try{oe.setItem("player_volume",this.video.volume.toString()),oe.setItem("player_muted",this.video.muted.toString())}catch{}this.dispatchEvent("volumechange",{volume:this.video.volume}),this.dispatchEvent("mutechange",{isMuted:this.video.muted})},this.handleProgress=()=>{const o=this.video.buffered,d=[];for(let h=0;h<o.length;h++)d.push({start:o.start(h),end:o.end(h)});if(this.updateState({bufferedRanges:d}),this.state.isLive)this.updateLiveState();else{const h=this.getSeekableStateBatch();this.updateState({isLive:h.isLive,hasDvr:h.hasDvr,seekableRange:h.seekableRange,dvrWindow:h.dvrWindow,canSeekInDvr:h.canSeekInDvr})}},this.handleLoadedMetadata=()=>{this.video.playbackRate=this.state.playbackRate;const o=this.state.status,d=o==="loading"||o==="idle"?"ready":o;if(this.updateState({status:d}),this.state.isLive){if(this.updateLiveState(),this.video.paused&&this.video.currentTime===0){const h=()=>{this.video.seekable.length>0&&(this.seekToLiveEdge(),this.video.removeEventListener("canplay",h),this.video.removeEventListener("timeupdate",h))};this.video.seekable.length>0?this.seekToLiveEdge():(this.video.addEventListener("canplay",h),this.video.addEventListener("timeupdate",h))}}else{const h=this.getSeekableStateBatch();this.updateState({isLive:h.isLive,hasDvr:h.hasDvr,seekableRange:h.seekableRange,dvrWindow:h.dvrWindow,canSeekInDvr:h.canSeekInDvr})}},this.handleEnded=()=>{this.state.loop&&this.state.displayMode!=="vertical"?(this.seek(0),this.play()):(this.updateState({isPlaying:!1,status:"ended"}),this.stopStallCheck(),this.state.sleepTimerSetting==="end"&&(this.clearSleepTimer(),this.triggerSleepTimerExpiration()),this.dispatchEvent("ended"))},this.handleFullscreenChange=()=>{const o=document,d=!!(document.fullscreenElement||o.webkitFullscreenElement||o.mozFullScreenElement||o.msFullscreenElement);this.updateState({isFullscreen:d}),this.dispatchEvent("fullscreenchange",{isFullscreen:d})},this.handleWebkitBeginFullscreen=()=>{this.updateState({isFullscreen:!0}),this.dispatchEvent("fullscreenchange",{isFullscreen:!0})},this.handleWebkitEndFullscreen=()=>{this.updateState({isFullscreen:!1}),this.dispatchEvent("fullscreenchange",{isFullscreen:!1})},this.video=e,this.validateConfig(t),this.config=this.createUnifiedConfig(t),this.shortcuts=new Ni(this),this.ads=new Yi(this),this.playlistManager=new yr(this),this.subtitleManager=new kr(this,this.sourceManager),this.pictureInPictureManager=new Sr(this),t.shortcuts&&t.shortcuts.enabled===!1&&this.shortcuts.disable(),this.isPluginsEnabled()&&t.plugins){const o=wr(t.plugins);if(o)for(const d of o)this.use(d)}if(this.isAnalyticsEnabled()&&t.analytics&&Array.isArray(t.analytics.handlers))for(const o of t.analytics.handlers)this.registerAnalyticsHandler(o);const i=t.smartSeek;i!==!1&&(typeof i!="object"||i.enabled!==!1)&&(t.thumbnailProvider?this.thumbnailProvider=t.thumbnailProvider:this.thumbnailProvider=new _e(t)),this.state.thumbnailProvider=this.thumbnailProvider,this.state.pictureInPictureSupported=this.pictureInPictureManager.detectSupport(),this.config.live&&this.config.live.mode&&(this.state.liveMode=this.config.live.mode),this.config.autoplay&&(this.video.autoplay=!0),this.config.playsinline!==!1&&this.video.setAttribute("playsinline","true"),this.config.preload&&(this.video.preload=this.config.preload),this.config.poster&&this.video.setAttribute("poster",this.config.poster);const r=this.config.crossorigin;r&&this.video.setAttribute("crossorigin",r);try{const o=oe.getItem("player_volume");if(o!==null){const h=parseFloat(o);!isNaN(h)&&h>=0&&h<=1&&(this.video.volume=h,this.state.volume=h)}else t.volume!==void 0&&(this.video.volume=t.volume,this.state.volume=t.volume);const d=oe.getItem("player_muted");if(d!==null){const h=d==="true";this.video.muted=h,this.state.isMuted=h}else t.muted!==void 0&&(this.video.muted=t.muted,this.state.isMuted=t.muted)}catch{t.volume!==void 0&&(this.video.volume=t.volume),t.muted!==void 0&&(this.video.muted=t.muted)}try{const o=oe.getItem("player_loop");if(o!==null){const d=o==="true";this.video.loop=d,this.state.loop=d}else t.loop&&(this.video.loop=!0,this.state.loop=!0)}catch{t.loop&&(this.video.loop=!0)}try{const o=oe.getItem("player_auto_scroll");o!==null?this.state.autoScroll=o==="true":t.autoScroll!==void 0&&(this.state.autoScroll=t.autoScroll)}catch{t.autoScroll!==void 0&&(this.state.autoScroll=t.autoScroll)}this.state.volume=this.video.volume,this.state.isMuted=this.video.muted,this.lastNonZeroVolume=this.video.volume>0?this.video.volume:.5;try{const o=oe.getItem("player_playback_rate");if(o){const d=parseFloat(o);!isNaN(d)&&d>0&&d<=4&&(this.state.playbackRate=d,this.video.playbackRate=d)}}catch{}const a=this.subtitleManager.readPersistedSettings();this.state.captionsEnabled=a.captionsEnabled,this.state.subtitleAppearance=a.appearance;const n=t.displayMode!==void 0?t.displayMode:(l=t.layout)==null?void 0:l.mode;n!==void 0&&["standard","vertical","audio-only","custom","mini","floating"].includes(n)&&(this.state.displayMode=n,this.config.displayMode=n,this.config.layout||(this.config.layout={}),this.config.layout.mode=n),t.playlistRepeatMode!==void 0&&(this.state.playlistRepeatMode=t.playlistRepeatMode),this.setupEventListeners(),this.on("metadata",o=>{var p,g;if(this.state.isLive&&!this.state.hasDvr)return;const d=typeof((p=o.parsedData)==null?void 0:p.title)=="string"?o.parsedData.title:void 0,h=typeof((g=o.parsedData)==null?void 0:g.description)=="string"?o.parsedData.description:void 0,u=d||h||o.type,f=`meta-${o.timestamp}-${o.type}-${Math.random().toString(36).substr(2,9)}`;this.addMarker({id:f,time:o.timestamp,label:u,type:"metadata",color:"#a855f7",metadata:o})})}createUnifiedConfig(e){e||(e={}),e.controls||(e.controls={}),e.settings||(e.settings={});let t=e.settings.order;const i=l=>{const o=l;return o==="enabled"?"settings":o==="speed"?"playbackSpeed":o==="audio"||o==="audioTracks"?"audioTracks":o==="captions"||o==="subtitles"?"subtitles":o==="pip"||o==="pictureInPicture"?"pictureInPicture":o},s={};Object.keys(e.controls).forEach(l=>{s[i(l)]=e.controls[l]}),Object.keys(e.settings).forEach(l=>{s[i(l)]=e.settings[l]});const r={get:(l,o)=>{if(o==="toJSON")return()=>{const h={...s};return t!==void 0&&(h.order=t),h};if(o==="order")return t;const d=i(o);return s[d]},set:(l,o,d)=>{if(o==="order")return t=d,!0;const h=i(o);return s[h]=d,n&&this.dispatchEvent("config-change",n),!0},has:(l,o)=>o==="order"?t!==void 0:i(o)in s,ownKeys:()=>{const l=new Set(Object.keys(s));return t!==void 0&&l.add("order"),Array.from(l)},getOwnPropertyDescriptor:(l,o)=>{const d=i(o);if(o==="order")return t===void 0?void 0:{enumerable:!0,configurable:!0,writable:!0,value:t};if(d in s)return{enumerable:!0,configurable:!0,writable:!0,value:s[d]}}};e.controls=new Proxy(e.controls,r),e.settings=new Proxy(e.settings,r);const a={get:(l,o)=>{if(o==="toJSON")return()=>{const h={};return Object.keys(l).forEach(u=>{const f=l[u];f&&typeof f.toJSON=="function"?h[u]=f.toJSON():h[u]=f}),h};const d=o;return d==="crossOrigin"?l.crossorigin:d==="playsInline"?l.playsinline:l[o]},set:(l,o,d)=>{const h=o;return h==="crossOrigin"?l.crossorigin=d:h==="playsInline"?l.playsinline=d:l[o]=d,n&&this.dispatchEvent("config-change",n),!0},has:(l,o)=>{const d=o;return d==="crossOrigin"?l.crossorigin!==void 0:d==="playsInline"?l.playsinline!==void 0:o in l}},n=new Proxy(e,a);return n}validateConfig(e){if(!e||typeof e!="object")return;const t=i=>{console.warn(`[Player SDK Configuration Warning] ${i}`)};if("crossOrigin"in e&&t("Property 'crossOrigin' is deprecated. Use 'crossorigin' instead."),"playsInline"in e&&t("Property 'playsInline' is deprecated. Use 'playsinline' instead."),e.autoplay!==void 0&&typeof e.autoplay!="boolean"&&t(`'autoplay' must be a boolean, got ${typeof e.autoplay}.`),e.muted!==void 0&&typeof e.muted!="boolean"&&t(`'muted' must be a boolean, got ${typeof e.muted}.`),e.volume!==void 0&&(typeof e.volume!="number"||e.volume<0||e.volume>1)&&t(`'volume' must be a number between 0 and 1, got ${e.volume}.`),e.displayMode!==void 0){const i=["standard","vertical","audio-only","custom","mini","floating"];i.includes(e.displayMode)||t(`Invalid displayMode '${e.displayMode}'. Must be one of: ${i.join(", ")}.`)}if(e.controls&&typeof e.controls=="object"){const i=["play","playButton","pause","seekbar","timeline","currentTime","duration","volume","mute","settings","subtitles","captions","audioTracks","quality","playbackSpeed","sleepTimer","pictureInPicture","pip","fullscreen","liveBadge","markers","chapters","timelinePreview","replayButton","loadingSpinner","feedbackOverlay","volumeOverlay","contextMenu","actionRail","liveDVR","liveEdgeButton","emptyState","controlsBar","verticalControls","plugins","loop","autoScroll","order","groups","layout"];Object.keys(e.controls).forEach(s=>{i.includes(s)||t(`Unknown control config option '${s}'.`)})}if(e.settings&&typeof e.settings=="object"){const i=["order","playbackSpeed","quality","audioTracks","subtitles","loop","sleepTimer","chapters","markers","autoScroll","pictureInPicture","pip","fullscreen","enabled","customItems","groups","labels","icons"];Object.keys(e.settings).forEach(s=>{i.includes(s)||t(`Unknown settings config option '${s}'.`)})}}onStateChange(e){return this.stateCallbacks.add(e),e({...this.state}),()=>this.stateCallbacks.delete(e)}updateState(e){this.isAudioTracksEnabled()||(e.audioTracks&&(e.audioTracks=[]),e.activeAudioTrack!==void 0&&(e.activeAudioTrack=-1)),this.isQualityEnabled()||(e.qualities&&(e.qualities=[]),e.activeQuality!==void 0&&(e.activeQuality="Auto")),this.isChaptersEnabled()||(e.chapters&&(e.chapters=[]),e.activeChapterIndex!==void 0&&(e.activeChapterIndex=-1)),this.isMarkersEnabled()||e.markers&&(e.markers=[]);const t=this.state.audioTracks,i=this.state.activeAudioTrack;let s=!1;for(const a of Object.keys(e)){const n=this.state[a],l=e[a];if(l!==void 0){if(typeof l=="object"&&l!==null){if(!ts(a,n,l)){s=!0;break}}else if(n!==l){s=!0;break}}}if(!s&&e.error===void 0)return;if(e.audioTracks!==void 0&&e.audioTracks.length>0&&(this.state.audioTracks.length===0||!ts("audioTracks",t,e.audioTracks)))try{const a=oe.getItem("player_audio_language");if(a){const n=e.audioTracks.findIndex(o=>o===a),l=e.activeAudioTrack!==void 0?e.activeAudioTrack:this.state.activeAudioTrack;n!==-1&&n!==l&&(e.activeAudioTrack=n,this.sourceManager.setAudioTrack(n))}}catch{}if(e.markers&&e.markers.length>1e3&&(e.markers=e.markers.slice(-1e3)),(this.state.isLive||e.isLive)&&e.seekableRange){const a=e.seekableRange.start,n=e.markers||this.state.markers;if(n&&n.length>0){const l=n.filter(o=>!pe.shouldPruneMarker(o.time,a));l.length!==n.length&&(e.markers=l)}}const r={...this.state,...e};e.error!==void 0&&e.error!==null&&(r.status="error"),this.state=r,e.audioTracks!==void 0&&JSON.stringify(t)!==JSON.stringify(e.audioTracks)&&this.dispatchEvent("audioTracksChanged",{audioTracks:e.audioTracks}),e.activeAudioTrack!==void 0&&i!==e.activeAudioTrack&&this.dispatchEvent("audioTrackChanged",{activeAudioTrack:e.activeAudioTrack}),this.stateCallbacks.forEach(a=>a({...this.state}))}getState(){return this.state}updateStatePublic(e){this.updateState(e)}getThumbnailProvider(){return this.thumbnailProvider}setThumbnailProvider(e){this.thumbnailProvider=e,this.updateState({thumbnailProvider:e})}setDisplayMode(e){if(["standard","vertical","audio-only","custom","mini","floating"].includes(e)){this.updateState({displayMode:e}),this.video.loop=e==="vertical"?!1:this.state.loop,this.config.layout||(this.config.layout={});const i=this.config.displayMode!==e,s=this.config.layout.mode!==e;this.config.displayMode=e,this.config.layout.mode=e,(i||s)&&this.dispatchEvent("config-change",this.config)}}setLiveMode(e){this.state.liveMode!==e&&(this.updateState({liveMode:e}),this.state.isLive&&this.updateLiveState())}loadPlaylist(e,t=0){this.playlistManager.loadPlaylist(e,t)}setPlaylist(e,t=0){this.playlistManager.setPlaylist(e,t)}setNearEndThreshold(e){this.playlistManager.setNearEndThreshold(e)}getNearEndThreshold(){return this.playlistManager.getNearEndThreshold()}getPlaylist(){return this.playlistManager.getPlaylist()}getCurrentPlaylistIndex(){return this.playlistManager.getCurrentPlaylistIndex()}getHistoryStack(){return this.playlistManager.getHistoryStack()}getCurrentPlaylistItem(){return this.playlistManager.getCurrentPlaylistItem()}getPlaylistLength(){return this.playlistManager.getPlaylistLength()}hasPlaylist(){return this.playlistManager.hasPlaylist()}isFirstPlaylistItem(){return this.playlistManager.isFirstPlaylistItem()}isLastPlaylistItem(){return this.playlistManager.isLastPlaylistItem()}next(){this.playlistManager.next()}previous(){this.playlistManager.previous()}appendPlaylistItem(e){this.playlistManager.appendPlaylistItem(e)}insertPlaylistItem(e,t){this.playlistManager.insertPlaylistItem(e,t)}removePlaylistItem(e){this.playlistManager.removePlaylistItem(e)}clearPlaylist(){this.playlistManager.clearPlaylist()}replacePlaylistItem(e,t){this.playlistManager.replacePlaylistItem(e,t)}movePlaylistItem(e,t){this.playlistManager.movePlaylistItem(e,t)}setPlaylistRepeatMode(e){this.playlistManager.setPlaylistRepeatMode(e)}getPlaylistRepeatMode(){return this.playlistManager.getPlaylistRepeatMode()}getAutoAdvanceIndexOnEnded(){return this.playlistManager.getAutoAdvanceIndexOnEnded()}setupEventListeners(){this.video.addEventListener("play",this.handlePlay),this.video.addEventListener("pause",this.handlePause),this.video.addEventListener("timeupdate",this.handleTimeUpdate),this.video.addEventListener("durationchange",this.handleDurationChange),this.video.addEventListener("volumechange",this.handleVolumeChange),this.video.addEventListener("progress",this.handleProgress),this.video.addEventListener("waiting",this.handleWaiting),this.video.addEventListener("playing",this.handlePlaying),this.video.addEventListener("seeking",this.handleSeeking),this.video.addEventListener("seeked",this.handleSeeked),this.video.addEventListener("canplay",this.handleCanPlay),this.video.addEventListener("canplaythrough",this.handleCanPlay),this.video.addEventListener("error",this.handleNativeError),this.video.addEventListener("loadedmetadata",this.handleLoadedMetadata),this.video.addEventListener("ended",this.handleEnded),this.subtitleManager.attach(),typeof document<"u"&&(document.addEventListener("fullscreenchange",this.handleFullscreenChange),document.addEventListener("webkitfullscreenchange",this.handleFullscreenChange),document.addEventListener("visibilitychange",this.handleVisibilityChange)),this.video.addEventListener("webkitbeginfullscreen",this.handleWebkitBeginFullscreen),this.video.addEventListener("webkitendfullscreen",this.handleWebkitEndFullscreen),this.pictureInPictureManager.attach()}destroy(){if(!this.isDestroyed){if(this.isDestroyed=!0,this.playlistManager.destroy(),this.stopStallCheck(),this.clearSleepTimer(),this.clearBufferingTimeout(),this.shortcuts.destroy(),this.analyticsHandlers.clear(),this.playbackInterceptors.clear(),this.pendingOverlays.clear(),this.thumbnailProvider&&typeof this.thumbnailProvider.destroy=="function")try{this.thumbnailProvider.destroy()}catch(e){console.error("[PlayerController] Error destroying thumbnail provider:",e)}this.sourceManager.destroy();try{this.ads.destroy()}catch(e){console.error("[PlayerController] Error destroying ads controller:",e)}this.subtitleManager.revokeBlobUrls(),this.plugins.forEach(e=>{var t;try{(t=e.destroy)==null||t.call(e)}catch(i){console.error(`[PlayerController] Error destroying plugin "${e.name}":`,i)}}),this.plugins.clear(),this.eventListeners.clear(),this.video.removeEventListener("play",this.handlePlay),this.video.removeEventListener("pause",this.handlePause),this.video.removeEventListener("timeupdate",this.handleTimeUpdate),this.video.removeEventListener("durationchange",this.handleDurationChange),this.video.removeEventListener("volumechange",this.handleVolumeChange),this.video.removeEventListener("progress",this.handleProgress),this.video.removeEventListener("waiting",this.handleWaiting),this.video.removeEventListener("playing",this.handlePlaying),this.video.removeEventListener("seeking",this.handleSeeking),this.video.removeEventListener("seeked",this.handleSeeked),this.video.removeEventListener("canplay",this.handleCanPlay),this.video.removeEventListener("canplaythrough",this.handleCanPlay),this.video.removeEventListener("error",this.handleNativeError),this.video.removeEventListener("loadedmetadata",this.handleLoadedMetadata),this.video.removeEventListener("ended",this.handleEnded),this.subtitleManager.detach(),typeof document<"u"&&(document.removeEventListener("fullscreenchange",this.handleFullscreenChange),document.removeEventListener("webkitfullscreenchange",this.handleFullscreenChange),document.removeEventListener("visibilitychange",this.handleVisibilityChange)),this.video.removeEventListener("webkitbeginfullscreen",this.handleWebkitBeginFullscreen),this.video.removeEventListener("webkitendfullscreen",this.handleWebkitEndFullscreen),this.pictureInPictureManager.detach(),this.stateCallbacks.clear()}}clearBufferingTimeout(){this.bufferingTimeout&&(clearTimeout(this.bufferingTimeout),this.bufferingTimeout=void 0)}getSeekableStateBatch(){const e=this.video.seekable;let t=this.state.isLive;this.state.sourceType==="hls"||this.state.sourceType==="dash"||(this.video.duration===1/0?t=!0:t===null&&this.video.duration>0&&(t=!1));let s=0,r=this.video.duration||0;e&&e.length>0?(s=e.start(0),t===!0&&(s+=2),r=e.end(e.length-1),s>r&&(s=r)):t===!0&&(r=0);const a={start:s,end:r},n=t===!0?r-s:0,l=this.state.hasDvr||t===!0&&n>30,o=l&&this.state.liveMode==="live-dvr";return{isLive:t,seekableRange:a,dvrWindow:n,hasDvr:l,canSeekInDvr:o}}updateActiveChapter(){if(!this.state.chapters||this.state.chapters.length===0){this.state.activeChapterIndex!==-1&&this.updateState({activeChapterIndex:-1});return}const e=this.video.currentTime,t=this.state.chapters,i=t.findIndex((s,r)=>{const a=s.startTime,n=s.endTime!==void 0?s.endTime:t[r+1]?t[r+1].startTime:this.video.duration||1/0;return e>=a&&e<n});i!==this.state.activeChapterIndex&&(this.updateState({activeChapterIndex:i}),this.dispatchEvent("chapterchange",{activeChapterIndex:i,chapter:i!==-1?this.state.chapters[i]:null}))}setManagedSubtitleTracks(e,t,i){this.subtitleManager.setManagedSubtitleTracks(e,t,i)}play(){var t,i;const e=this.getPlugins();for(const s of e)try{(t=s.onBeforePlay)==null||t.call(s)}catch(r){console.error(`[PlayerController] Error running onBeforePlay for plugin ${s.name}:`,r)}for(const s of this.playbackInterceptors)if(s.play)try{if(s.play()){for(const a of e)(i=a.onAfterPlay)==null||i.call(a);return}}catch(r){console.error("[PlayerController] Playback interceptor error:",r)}this.video.play().then(()=>{var s;for(const r of e)try{(s=r.onAfterPlay)==null||s.call(r)}catch(a){console.error(`[PlayerController] Error running onAfterPlay for plugin ${r.name}:`,a)}}).catch(s=>{console.warn("Playback failed or was prevented by browser autoplay restrictions:",s)})}pause(){for(const e of this.playbackInterceptors)if(e.pause)try{if(e.pause())return}catch(t){console.error("[PlayerController] Pause interceptor error:",t)}this.video.pause()}togglePlay(){this.state.isPlaying?this.pause():this.play()}seek(e){var a,n,l;if(this.state.isLive&&!this.state.canSeekInDvr)return;let t=e;if(this.state.isLive){const o=((a=this.state.seekableRange)==null?void 0:a.start)??0,d=((n=this.state.seekableRange)==null?void 0:n.end)??0;t=Math.max(o,Math.min(e,d))}else t=Math.max(0,Math.min(e,this.state.duration||0));for(const o of this.playbackInterceptors)if(o.seek)try{if(o.seek(t))return}catch(d){console.error("[PlayerController] Seek interceptor error:",d)}const i=this.sourceManager.getActiveHandler();let s=!1;if(i&&typeof i.seek=="function"&&(s=i.seek(t)),!s){const o=(l=this.config)==null?void 0:l.preciseSeek,d=typeof o=="object"?o:void 0,h=o!==!1&&(d==null?void 0:d.enabled)!==!1&&(d==null?void 0:d.seekSmoothing)!==!1,u=this.video.volume,f=this.video.muted;if(h&&!f&&u>0){this.preSeekVolume===null&&(this.preSeekVolume=u),this.video.volume=this.preSeekVolume*.1;const p=()=>{this.preSeekVolume!==null&&(this.video.volume=this.preSeekVolume,this.preSeekVolume=null),this.video.removeEventListener("seeked",p)};this.video.addEventListener("seeked",p),setTimeout(()=>{this.video.removeEventListener("seeked",p),this.preSeekVolume!==null&&(this.video.volume=this.preSeekVolume,this.preSeekVolume=null)},250)}this.video.currentTime=t}const r={currentTime:t,isSeeking:!0};if(this.state.isLive){const o=this.getLiveEdgeTarget(),d=Math.max(0,o-t),h=this.state.isLowLatency?6:18;r.liveLatency=d,r.isAtLiveEdge=d<=h}this.updateState(r)}seekBy(e){this.seek(this.state.currentTime+e)}setVolume(e){const t=Math.max(0,Math.min(e,1));for(const i of this.playbackInterceptors)if(i.setVolume)try{if(i.setVolume(t))return}catch(s){console.error("[PlayerController] setVolume interceptor error:",s)}this.video.volume=t,t>0&&(this.lastNonZeroVolume=t,this.video.muted&&this.setMuted(!1))}setMuted(e){for(const t of this.playbackInterceptors)if(t.setMuted)try{if(t.setMuted(e))return}catch(i){console.error("[PlayerController] setMuted interceptor error:",i)}this.video.muted=e}toggleMute(){const t=!(this.video.muted||this.video.volume===0);this.setMuted(t),t||this.video.volume===0&&this.setVolume(this.lastNonZeroVolume>0?this.lastNonZeroVolume:.5)}setPlaybackRate(e){this.isPlaybackSpeedEnabled()||(e=1),this.video.playbackRate=e,this.updateState({playbackRate:e});try{oe.setItem("player_playback_rate",e.toString())}catch{}}toggleFullscreen(e){const t=e||this.video,i=t,s=this.video,r=document;this.state.isFullscreen?document.exitFullscreen?document.exitFullscreen():r.webkitExitFullscreen?r.webkitExitFullscreen():this.video&&s.webkitExitFullscreen&&s.webkitExitFullscreen():t.requestFullscreen?t.requestFullscreen():i.webkitRequestFullscreen?i.webkitRequestFullscreen():this.video&&s.webkitEnterFullscreen&&s.webkitEnterFullscreen()}isPictureInPictureSupported(){return this.pictureInPictureManager.isPictureInPictureSupported()}async enterPictureInPicture(){return this.pictureInPictureManager.enterPictureInPicture()}async exitPictureInPicture(){return this.pictureInPictureManager.exitPictureInPicture()}async togglePictureInPicture(){this.pictureInPictureManager.isInPictureInPicture()?await this.exitPictureInPicture():await this.enterPictureInPicture()}loadCaptions(e){this.subtitleManager.loadCaptions(e)}toggleCaptions(e){this.subtitleManager.toggleCaptions(e)}replay(){this.seek(0),this.play(),this.dispatchEvent("replay")}validateSource(e){if(!e||!e.src)return!1;const t=e.src.trim();return t.length===0?!1:t.startsWith("http://")||t.startsWith("https://")||t.startsWith("/")||t.startsWith("blob:")||t.startsWith("data:")}parseAndSanitizeEmbedSource(e){if(!e||!e.src)return!1;const t=zs(e.src);return t?(e.src=t,!0):!1}loadSource(e,t=!0){var n,l,o,d,h,u,f,p,g,m;if((n=e.live)!=null&&n.mode&&this.setLiveMode(e.live.mode),t&&this.state.playlist.length>0&&this.playlistManager.clearForExternalSourceLoad(),this.setSleepTimer("off"),this.subtitleManager.revokeBlobUrls(),this.state.pictureInPicture&&this.exitPictureInPicture().catch(()=>{}),!e||!e.src&&!e.srcObject||typeof e.src=="string"&&e.src.trim()===""){this.sourceManager.destroy(),this.stopStallCheck(),this.video.src="",this.video.srcObject=null,this.video.removeAttribute("src");try{this.video.load()}catch{}this.video.querySelectorAll("track").forEach(y=>y.remove()),this.subtitleManager.resetManagedTracks(),this.updateState({status:"idle",currentSource:null,sourceType:"unknown",error:null,isPlaying:!1,isBuffering:!1,isSeeking:!1,currentTime:0,duration:0,bufferedRanges:[],qualities:[],activeQuality:"Auto",audioTracks:[],activeAudioTrack:-1,subtitleTracks:[],activeSubtitleTrack:-1,activeSubtitleTrackId:null,chapters:[],activeChapterIndex:-1,markers:[]}),this.dispatchEvent("sourcechange",{source:null}),(o=(l=this.thumbnailProvider)==null?void 0:l.setSource)==null||o.call(l,"");return}this.sourceManager.destroy(),this.stopStallCheck();let i=e.type||"unknown";if(i==="unknown"&&e.src){const v=e.src.split("?")[0].toLowerCase();v.endsWith(".m3u8")?i="hls":v.endsWith(".mpd")?i="dash":v.endsWith(".webm")?i="webm":v.endsWith(".mov")?i="mov":v.includes("youtube.com")||v.includes("youtu.be")||v.includes("vimeo.com")||e.src.trim().toLowerCase().startsWith("<iframe")?i="embed":i="mp4"}if(i==="embed"&&!this.parseAndSanitizeEmbedSource(e)){this.updateState({status:"error",currentSource:null,sourceType:"unknown",error:"Invalid embed source or host not approved.",isPlaying:!1,currentTime:0,duration:0,bufferedRanges:[],isLive:!1,seekableRange:{start:0,end:0},chapters:[],activeChapterIndex:-1}),this.dispatchEvent("sourcechange",{source:e}),(h=(d=this.thumbnailProvider)==null?void 0:d.setSource)==null||h.call(d,"");return}if(!this.validateSource(e)){this.updateState({status:"error",currentSource:null,sourceType:"unknown",error:"Invalid video source layout or stream. Please verify input.",isPlaying:!1,currentTime:0,duration:0,bufferedRanges:[],isLive:!1,seekableRange:{start:0,end:0},chapters:[],activeChapterIndex:-1}),this.dispatchEvent("sourcechange",{source:e}),(f=(u=this.thumbnailProvider)==null?void 0:u.setSource)==null||f.call(u,"");return}if(this.subtitleManager.revokeBlobUrls(),this.video.textTracks)for(let v=0;v<this.video.textTracks.length;v++)this.video.textTracks[v]._zombie=!0;this.video.querySelectorAll("track").forEach(v=>v.remove()),this.subtitleManager.resetManagedTracks(),e.type=i;const r=e.src||"";this.video.loop=this.state.displayMode==="vertical"?!1:this.state.loop,this.updateState({status:"loading",currentSource:r,sourceType:i,isBuffering:!1,isSeeking:!1,isPlaying:!1,currentTime:0,duration:0,bufferedRanges:[],error:null,qualities:[],activeQuality:"Auto",audioTracks:[],activeAudioTrack:-1,subtitleTracks:[],activeSubtitleTrack:-1,activeSubtitleTrackId:null,isLive:null,isAtLiveEdge:!0,liveLatency:null,dvrWindow:0,canSeekInDvr:!1,seekableRange:{start:0,end:0},chapters:e.chapters||[],activeChapterIndex:-1,markers:[],visibleMarkerTypes:null}),this.subtitleManager.attachSourceSubtitles(e.subtitles),this.subtitleManager.refreshSubtitleTracks(),this.video.srcObject=null,this.video.src="",this.video.removeAttribute("src"),this.sourceManager.load(e,this.video,this),(g=(p=this.thumbnailProvider)==null?void 0:p.setSource)==null||g.call(p,r,e),this.dispatchEvent("sourcechange",{source:e}),this.updateMediaSession();const a=this.getPlugins();for(const v of a)try{(m=v.onSourceLoaded)==null||m.call(v,e)}catch(y){console.error(`[PlayerController] Error running onSourceLoaded for plugin ${v.name}:`,y)}}setQuality(e){this.isQualityEnabled()&&(this.sourceManager.setQuality(e),this.dispatchEvent("qualitychange",{qualityIndex:e}))}getAudioTracks(){return this.state.audioTracks}getCurrentAudioTrack(){return this.state.activeAudioTrack}setAudioTrack(e){if(this.isAudioTracksEnabled()){this.sourceManager.setAudioTrack(e);try{const t=this.state.audioTracks;e>=0&&e<t.length&&oe.setItem("player_audio_language",t[e])}catch{}this.dispatchEvent("audiochange",{trackIndex:e})}}setSubtitleTrack(e){this.subtitleManager.setSubtitleTrack(e)}disableSubtitles(){this.subtitleManager.disableSubtitles()}hasSubtitles(){return this.subtitleManager.hasSubtitles()}getSubtitleTracks(){return this.subtitleManager.getSubtitleTracks()}getActiveSubtitleTrack(){return this.subtitleManager.getActiveSubtitleTrack()}getSubtitleAppearance(){return this.subtitleManager.getSubtitleAppearance()}setSubtitleAppearance(e){this.subtitleManager.setSubtitleAppearance(e)}resetSubtitleAppearance(){this.subtitleManager.resetSubtitleAppearance()}startStallCheck(){this.stopStallCheck();let e=this.video.currentTime,t=0;this.stallTimer=window.setInterval(()=>{this.state.isPlaying&&!this.state.isBuffering&&(this.video.currentTime===e?(t++,t>=5&&(console.warn("Playback stall detected. Attempting stall recovery seek offset..."),this.video.currentTime=Math.min(this.video.currentTime+.1,this.state.duration||0),t=0)):(t=0,e=this.video.currentTime))},1e3)}stopStallCheck(){this.stallTimer&&(clearInterval(this.stallTimer),this.stallTimer=void 0)}getVideoElement(){return this.video}getDrmManager(){var e,t;return((t=(e=this.sourceManager.getActiveHandler())==null?void 0:e.getDrmManager)==null?void 0:t.call(e))??null}setChapters(e){if(!this.isChaptersEnabled()){this.updateState({chapters:[],activeChapterIndex:-1});return}this.updateState({chapters:e}),this.updateActiveChapter()}nextChapter(){const e=this.state.chapters;if(!e||e.length===0)return;const t=this.video.currentTime,i=e.find(s=>s.startTime>t+.5);i&&this.seek(i.startTime)}prevChapter(){const e=this.state.chapters;if(!e||e.length===0)return;const t=this.video.currentTime,i=this.state.activeChapterIndex;if(i>0&&t-e[i].startTime<2)this.seek(e[i-1].startTime);else if(i>=0)this.seek(e[i].startTime);else{const s=[...e].reverse().find(r=>r.startTime<t-.5);s&&this.seek(s.startTime)}}getChapters(){return this.state.chapters||[]}getActiveChapter(){const e=this.state.activeChapterIndex,t=this.state.chapters;return e>=0&&t&&t[e]?t[e]:null}seekToChapter(e){const t=this.state.chapters;if(!t||t.length===0)return;let i;typeof e=="number"?i=t[e]:i=t.find(s=>s.id===e),i&&this.seek(i.startTime)}setMarkers(e){if(!this.isMarkersEnabled()){this.updateState({markers:[]});return}this.updateState({markers:e})}addMarker(e){if(!this.isMarkersEnabled())return;const t=[...this.state.markers,e];this.updateState({markers:t})}clearMarkers(){this.updateState({markers:[]})}setLoop(e){this.video.loop=this.state.displayMode==="vertical"?!1:e,this.updateState({loop:e});try{oe.setItem("player_loop",e.toString())}catch{}}toggleLoop(){this.setLoop(!this.state.loop)}setAutoScroll(e){this.updateState({autoScroll:e});try{oe.setItem("player_auto_scroll",e.toString())}catch{}this.dispatchEvent("autoscroll-change",{autoScroll:e})}toggleAutoScroll(){this.setAutoScroll(!this.state.autoScroll)}tickSleepTimer(){if(!this.sleepTimerEndTimeMs||this.state.sleepTimerExpired)return;const e=Math.max(0,Math.ceil((this.sleepTimerEndTimeMs-Date.now())/1e3));e<=0?(this.clearSleepTimer(),this.triggerSleepTimerExpiration()):(this.updateState({sleepTimerSecondsRemaining:e}),this.dispatchEvent("sleeptimerupdate",{secondsRemaining:e,endTimeMs:this.sleepTimerEndTimeMs}))}setSleepTimer(e){var s,r;if(((r=(s=this.config)==null?void 0:s.controls)==null?void 0:r.sleepTimer)===!1)return;if(e==="end"&&this.state.isLive){console.warn('[PlayerController] Cannot set "end" sleep timer on a live stream');return}this.clearSleepTimer();const t=this.state.sleepTimerExpired;if(this.updateState({sleepTimerSetting:e,sleepTimerExpired:!1}),e==="off"){this.sleepTimerEndTimeMs=void 0,this.updateState({sleepTimerSecondsRemaining:null}),this.dispatchEvent("sleeptimercancelled");return}if(e==="end"){this.sleepTimerEndTimeMs=void 0,this.updateState({sleepTimerSecondsRemaining:null}),this.dispatchEvent("sleeptimerstart",{setting:"end",secondsRemaining:null,endTimeMs:null}),t&&this.play();return}const i=e*60;this.sleepTimerEndTimeMs=Date.now()+i*1e3,this.updateState({sleepTimerSecondsRemaining:i}),this.dispatchEvent("sleeptimerstart",{setting:e,secondsRemaining:i,endTimeMs:this.sleepTimerEndTimeMs}),this.startSleepTimerCountdown(),t&&this.play()}startSleepTimerCountdown(){this.sleepTimerId&&clearInterval(this.sleepTimerId),this.sleepTimerId=window.setInterval(()=>{this.tickSleepTimer()},1e3)}clearSleepTimer(){this.sleepTimerId&&(clearInterval(this.sleepTimerId),this.sleepTimerId=void 0),this.sleepTimerEndTimeMs=void 0}clearSleepTimerExpired(){this.updateState({sleepTimerExpired:!1})}triggerSleepTimerExpiration(){this.pause(),this.updateState({sleepTimerExpired:!0,sleepTimerSetting:"off",sleepTimerSecondsRemaining:null}),this.dispatchEvent("sleeptimerexpired")}getSleepTimerState(){return{setting:this.state.sleepTimerSetting,secondsRemaining:this.state.sleepTimerSecondsRemaining,endTimeMs:this.sleepTimerEndTimeMs||null,isExpired:this.state.sleepTimerExpired,isRunning:this.isSleepTimerRunning()}}getSleepTimerRemaining(){return!this.sleepTimerEndTimeMs||this.state.sleepTimerExpired?null:Math.max(0,Math.ceil((this.sleepTimerEndTimeMs-Date.now())/1e3))}getSleepTimerPreset(){return this.state.sleepTimerSetting}isSleepTimerRunning(){return!!(this.sleepTimerEndTimeMs&&!this.state.sleepTimerExpired&&(this.state.sleepTimerSecondsRemaining??0)>0)}isPluginsEnabled(){var t,i;const e=(t=this.config)==null?void 0:t.plugins;return e===!1?!1:e&&typeof e=="object"&&"enabled"in e?e.enabled!==!1:!((i=this.config)!=null&&i.controls&&this.config.controls.plugins===!1)}isAnalyticsEnabled(){var t,i;const e=(t=this.config)==null?void 0:t.analytics;return!(e===!1||e&&typeof e=="object"&&e.enabled===!1||(i=this.config)!=null&&i.controls&&this.config.controls.analytics===!1)}isSubtitlesEnabled(){var e,t,i,s;return!(((t=(e=this.config)==null?void 0:e.controls)==null?void 0:t.subtitles)===!1&&((s=(i=this.config)==null?void 0:i.controls)==null?void 0:s.captions)===!1)}isAudioTracksEnabled(){var e,t;return((t=(e=this.config)==null?void 0:e.controls)==null?void 0:t.audioTracks)!==!1}isQualityEnabled(){var e,t;return((t=(e=this.config)==null?void 0:e.controls)==null?void 0:t.quality)!==!1}isPlaybackSpeedEnabled(){var e,t;return((t=(e=this.config)==null?void 0:e.controls)==null?void 0:t.playbackSpeed)!==!1}isSmartSeekEnabled(){var t;const e=(t=this.config)==null?void 0:t.smartSeek;return!(e===!1||typeof e=="object"&&e.enabled===!1)}isChaptersEnabled(){var t,i,s;if(!this.isSmartSeekEnabled())return!1;const e=(t=this.config)==null?void 0:t.smartSeek;return!(e&&typeof e=="object"&&e.chapters===!1||((s=(i=this.config)==null?void 0:i.controls)==null?void 0:s.chapters)===!1)}isMarkersEnabled(){var t,i,s;if(!this.isSmartSeekEnabled())return!1;const e=(t=this.config)==null?void 0:t.smartSeek;return!(e&&typeof e=="object"&&e.markers===!1||((s=(i=this.config)==null?void 0:i.controls)==null?void 0:s.markers)===!1)}isPreciseSeekEnabled(){var t;const e=(t=this.config)==null?void 0:t.preciseSeek;return!(e===!1||typeof e=="object"&&e.enabled===!1)}shouldSnapToChapters(){var i,s;if(!this.isPreciseSeekEnabled()||!this.isChaptersEnabled())return!1;const e=(i=this.config)==null?void 0:i.preciseSeek,t=(s=this.config)==null?void 0:s.smartSeek;return e&&typeof e=="object"&&e.snapToChapters!==void 0?e.snapToChapters:t&&typeof t=="object"&&t.snapToChapters!==void 0?t.snapToChapters:!0}shouldSnapToMarkers(){var i,s;if(!this.isPreciseSeekEnabled()||!this.isMarkersEnabled())return!1;const e=(i=this.config)==null?void 0:i.preciseSeek,t=(s=this.config)==null?void 0:s.smartSeek;return e&&typeof e=="object"&&e.snapToMarkers!==void 0?e.snapToMarkers:t&&typeof t=="object"&&t.snapToMarkers!==void 0?t.snapToMarkers:!0}isKeyboardPrecisionEnabled(){var t;if(!this.isPreciseSeekEnabled())return!1;const e=(t=this.config)==null?void 0:t.preciseSeek;return!(e&&typeof e=="object"&&e.keyboardPrecision===!1)}isFrameAccurateSeekingEnabled(){var t;if(!this.isPreciseSeekEnabled())return!1;const e=(t=this.config)==null?void 0:t.preciseSeek;return!(e&&typeof e=="object"&&e.frameAccurate===!1)}isLiveDraggingEnabled(){var t;if(!this.isPreciseSeekEnabled())return!1;const e=(t=this.config)==null?void 0:t.preciseSeek;return e&&typeof e=="object"&&e.liveDragging!==void 0?e.liveDragging:!0}isSmoothDraggingEnabled(){var t;if(!this.isPreciseSeekEnabled())return!1;const e=(t=this.config)==null?void 0:t.preciseSeek;return!(e&&typeof e=="object"&&(e.smoothDragging===!1||e.dragInterpolation===!1))}isContinuousUpdatesEnabled(){var t;if(!this.isPreciseSeekEnabled())return!1;const e=(t=this.config)==null?void 0:t.preciseSeek;return!(e&&typeof e=="object"&&e.continuousUpdates===!1)}exportConfig(){return JSON.parse(JSON.stringify(this.config))}updateConfig(e){var r,a,n;this.validateConfig(e);const t={...this.config,...e,theme:{...this.config.theme||{},...e.theme||{}},controls:{...this.config.controls||{},...e.controls||{}},settings:{...this.config.settings||{},...e.settings||{}},layout:{...this.config.layout||{},...e.layout||{}},playback:{...this.config.playback||{},...e.playback||{}},sleepTimer:{...this.config.sleepTimer||{},...e.sleepTimer||{}},shortcuts:{...this.config.shortcuts||{},...e.shortcuts||{}},preciseSeek:e.preciseSeek!==void 0?typeof e.preciseSeek=="object"?{...typeof this.config.preciseSeek=="object"?this.config.preciseSeek:{},...e.preciseSeek}:e.preciseSeek:this.config.preciseSeek,smartSeek:e.smartSeek!==void 0?typeof e.smartSeek=="object"?{...typeof this.config.smartSeek=="object"?this.config.smartSeek:{},...e.smartSeek}:e.smartSeek:this.config.smartSeek};this.config=this.createUnifiedConfig(t);const i=this.config.smartSeek;if(i!==!1&&(typeof i!="object"||i.enabled!==!1))if(!this.thumbnailProvider)this.config.thumbnailProvider?this.thumbnailProvider=this.config.thumbnailProvider:this.thumbnailProvider=new _e(this.config),this.updateState({thumbnailProvider:this.thumbnailProvider});else{const l=this.thumbnailProvider;typeof l.updateConfig=="function"?l.updateConfig(this.config):l.config=this.config}else{if(this.thumbnailProvider&&typeof this.thumbnailProvider.destroy=="function")try{this.thumbnailProvider.destroy()}catch(l){console.error("[PlayerController] Error destroying thumbnail provider:",l)}this.thumbnailProvider=void 0,this.updateState({thumbnailProvider:void 0})}this.isAnalyticsEnabled()||this.analyticsHandlers.clear(),!this.isPluginsEnabled()&&this.plugins.size>0&&(this.plugins.forEach(l=>{var o;try{(o=l.destroy)==null||o.call(l)}catch(d){console.error(`[PlayerController] Error destroying plugin "${l.name}":`,d)}}),this.plugins.clear()),((r=this.config.controls)==null?void 0:r.sleepTimer)===!1&&(this.clearSleepTimer(),this.updateState({sleepTimerSetting:"off",sleepTimerSecondsRemaining:null,sleepTimerExpired:!1})),!this.isChaptersEnabled()&&this.state.chapters&&this.state.chapters.length>0&&this.updateState({chapters:[],activeChapterIndex:-1}),!this.isMarkersEnabled()&&this.state.markers&&this.state.markers.length>0&&this.updateState({markers:[]}),this.config.controls&&this.config.controls.liveDVR!==void 0&&(this.config.controls.liveDVR===!1?this.updateState({liveMode:"live-only",canSeekInDvr:!1}):this.updateState({liveMode:((a=this.config.live)==null?void 0:a.mode)||"live-dvr",canSeekInDvr:this.state.hasDvr})),!this.isSubtitlesEnabled()&&this.state.subtitleTracks&&this.state.subtitleTracks.length>0&&(this.updateState({subtitleTracks:[],activeSubtitleTrack:-1,activeSubtitleTrackId:null,captionsEnabled:!1}),this.disableSubtitles()),!this.isAudioTracksEnabled()&&this.state.audioTracks&&this.state.audioTracks.length>0&&this.updateState({audioTracks:[],activeAudioTrack:-1}),!this.isQualityEnabled()&&this.state.qualities&&this.state.qualities.length>0&&this.updateState({qualities:[],activeQuality:"Auto"}),!this.isPlaybackSpeedEnabled()&&this.state.playbackRate!==1&&this.setPlaybackRate(1),e.playback&&e.playback.autoplay!==void 0&&(this.video.autoplay=e.playback.autoplay),e.playback&&e.playback.loop!==void 0&&(this.video.loop=e.playback.loop,this.updateStatePublic({loop:e.playback.loop})),e.playback&&e.playback.volume!==void 0&&this.setVolume(e.playback.volume),e.playback&&e.playback.muted!==void 0&&e.playback.muted!==this.video.muted&&this.toggleMute(),e.shortcuts&&e.shortcuts.enabled!==void 0&&(e.shortcuts.enabled?this.shortcuts.enable():this.shortcuts.disable()),e.displayMode!==void 0?this.setDisplayMode(e.displayMode):((n=e.layout)==null?void 0:n.mode)!==void 0&&this.setDisplayMode(e.layout.mode),this.dispatchEvent("config-change",this.config)}getPlugins(){return this.isPluginsEnabled()?Array.from(this.plugins.values()):[]}use(e){var t,i;if(this.isPluginsEnabled()){if(this.plugins.has(e.name)){console.warn(`[PlayerController] Plugin "${e.name}" is already registered. Reinstalling.`);try{(i=(t=this.plugins.get(e.name))==null?void 0:t.destroy)==null||i.call(t)}catch{}}this.plugins.set(e.name,e),e.install(this)}}getPlugin(e){if(this.isPluginsEnabled())return this.plugins.get(e)}addEventListener(e,t){this.eventListeners.has(e)||this.eventListeners.set(e,new Set),this.eventListeners.get(e).add(t)}removeEventListener(e,t){this.eventListeners.has(e)&&this.eventListeners.get(e).delete(t)}dispatchEvent(e,t){this.isAnalyticsEnabled()&&this.analyticsHandlers.forEach(i=>{try{i(e,t)}catch(s){console.error(`[PlayerController] Error running analytics handler for "${e}":`,s)}}),this.eventListeners.has(e)&&this.eventListeners.get(e).forEach(i=>{try{i(t)}catch(s){console.error(`[PlayerController] Error executing event listener callback for event "${e}":`,s)}})}on(e,t){this.addEventListener(e,t)}off(e,t){this.removeEventListener(e,t)}emit(e,t){this.dispatchEvent(e,t)}registerAnalyticsHandler(e){this.isAnalyticsEnabled()&&this.analyticsHandlers.add(e)}unregisterAnalyticsHandler(e){this.analyticsHandlers.delete(e)}registerPlaybackInterceptor(e){this.playbackInterceptors.add(e)}unregisterPlaybackInterceptor(e){this.playbackInterceptors.delete(e)}getAdsState(){return this.ads.state()}getCurrentAd(){return this.ads.currentAd()}getCurrentAdBreak(){return this.ads.currentBreak()}isPlayingAd(){return!!this.ads.state().isAdPlaying}getAdProvider(){return this.ads.provider()}setAdsEnabled(e){this.config||(this.config={}),this.config.ads||(this.config.ads={}),this.config.ads.enabled=e,this.dispatchEvent("config-change",this.config)}skipAd(){this.ads.skip()}scheduleAd(e){return this.ads.schedule(e)}unscheduleAd(e){this.ads.unschedule(e)}async playAd(e){await this.ads.play(e)}registerOverlay(e,t){this.player&&typeof this.player.registerOverlay=="function"?this.player.registerOverlay(e,t):this.pendingOverlays.set(e,t)}load(e){const t=typeof e=="string"?{src:e}:e;this.loadSource(t)}addPlaylistItem(e){this.appendPlaylistItem(e)}getCurrentItem(){return this.hasPlaylist()?this.getCurrentPlaylistItem():this.state.currentSource?{src:this.state.currentSource,type:this.state.sourceType}:null}repeat(e){e===!0||e==="one"?(this.setLoop(!0),this.setPlaylistRepeatMode("off")):e==="all"?(this.setLoop(!1),this.setPlaylistRepeatMode("repeat-all")):(this.setLoop(!1),this.setPlaylistRepeatMode("off"))}getLiveEdgeTarget(){var s,r;const e=this.sourceManager.getRawLiveInfo();if(e&&e.liveEdgeTarget!==null&&e.liveEdgeTarget>0)return e.liveEdgeTarget;const t=((s=this.state.seekableRange)==null?void 0:s.end)??0,i=((r=this.state.seekableRange)==null?void 0:r.start)??0;if(t>0){const a=this.state.isLowLatency?5:15;return Math.max(i,t-a)}return this.state.duration||0}buildLiveCapabilities(){const e=this.sourceManager.getRawLiveInfo();if(!e||!e.isLive)return null;let t=0,i=this.video.duration||0;this.video.seekable&&this.video.seekable.length>0&&(t=this.video.seekable.start(0),i=this.video.seekable.end(this.video.seekable.length-1),t>i&&(t=i));const s=e.dvrWindow!==void 0?e.dvrWindow:i-t;if(s>0){const h=i-s;h>t&&(t=h)}const r={start:t,end:i},a=e.hasDvr!==void 0?e.hasDvr:s>10,n=e.liveEdgeTarget!==null?e.liveEdgeTarget:i,l=Math.max(0,n-this.video.currentTime),o=e.isLowLatency?6:18,d=l<=o;return{isLive:!0,isLowLatency:e.isLowLatency,hasDvr:a,dvrWindow:s,seekableRange:r,liveLatency:l,isAtLiveEdge:d}}updateLiveState(){if(!this.state.isLive)return;let e=this.buildLiveCapabilities();if(!e){const t=this.getSeekableStateBatch();t.isLive&&(e={isLive:!0,isLowLatency:!1,hasDvr:t.hasDvr,dvrWindow:t.dvrWindow,seekableRange:t.seekableRange,liveLatency:Math.max(0,t.seekableRange.end-this.video.currentTime),isAtLiveEdge:!0})}if(e){let t=e.hasDvr;this.state.liveMode==="live-only"&&(t=!1),this.updateState({isLive:e.isLive,isLowLatency:e.isLowLatency,hasDvr:e.hasDvr,seekableRange:e.seekableRange,dvrWindow:e.dvrWindow,canSeekInDvr:t,liveLatency:e.liveLatency,isAtLiveEdge:e.isAtLiveEdge})}}seekToLiveEdge(){if(this.updateState({isAtLiveEdge:!0}),this.state.seekableRange)this.video.currentTime=this.state.seekableRange.end;else if(!this.sourceManager.seekToLiveEdge()){const e=this.getLiveEdgeTarget();this.video.currentTime=e}this.play(),this.dispatchEvent("live-edge-sync",{latency:this.state.liveLatency||0})}getLiveLatency(){return this.state.liveLatency}isAtLiveEdge(){return this.state.isAtLiveEdge}showMarkerTypes(e){if(!this.state.visibleMarkerTypes)this.updateState({visibleMarkerTypes:[...e]});else{const t=new Set([...this.state.visibleMarkerTypes,...e]);this.updateState({visibleMarkerTypes:Array.from(t)})}}hideMarkerTypes(e){if(this.state.visibleMarkerTypes){const t=this.state.visibleMarkerTypes.filter(i=>!e.includes(i));this.updateState({visibleMarkerTypes:t})}else{const i=Array.from(new Set(this.state.markers.map(s=>s.type))).filter(s=>!e.includes(s));this.updateState({visibleMarkerTypes:i})}}setMarkerVisibility(e){this.updateState({visibleMarkerTypes:e})}getStatistics(){const e=this.video;let t=0;const i=e.buffered,s=e.currentTime;for(let h=0;h<i.length;h++){const u=i.start(h),f=i.end(h);if(s>=u&&s<=f){t=f-s;break}}let r,a;if(typeof e.getVideoPlaybackQuality=="function"){const h=e.getVideoPlaybackQuality();r=h.totalVideoFrames,a=h.droppedVideoFrames}else if(e.webkitDecodedFrameCount!==void 0){const h=e;r=h.webkitDecodedFrameCount,a=h.webkitDroppedFrameCount}let n;const l=performance.now();if(r!==void 0)if(this.lastFpsTimestamp>0){const h=(l-this.lastFpsTimestamp)/1e3;if(h>=.25){const u=r-this.lastDecodedFrames;this.lastCalculatedFps=Math.max(0,Math.round(u/h)),this.lastDecodedFrames=r,this.lastFpsTimestamp=l}n=this.lastCalculatedFps}else this.lastDecodedFrames=r,this.lastFpsTimestamp=l,n=0;const o={currentTime:s,duration:e.duration||0,playbackRate:e.playbackRate,paused:e.paused,ended:e.ended,muted:e.muted,volume:e.volume,width:e.videoWidth||void 0,height:e.videoHeight||void 0,fps:n,droppedFrames:a,decodedFrames:r,bufferedLength:t,bufferHealth:t,isLive:this.state.isLive===!0,liveLatency:this.state.liveLatency!==null?this.state.liveLatency:void 0,isLowLatency:this.state.isLowLatency},d=this.sourceManager.getActiveHandler();if(d&&typeof d.getStats=="function"){const h=d.getStats();h.bitrate!==void 0&&(o.bitrate=h.bitrate),h.bandwidthEstimate!==void 0&&(o.bandwidthEstimate=h.bandwidthEstimate)}return o}updateMediaSession(){if(typeof window>"u"||!("mediaSession"in navigator))return;const e=this.state.currentSource,t=this.state.playlist,i=this.state.activePlaylistIndex,r={...t&&t[i],...e?{src:e}:{}},a=r.title||(typeof e=="string"?e.split("/").pop():"")||"Video Playback",n=r.artist||"Player SDK",l=r.album||"",o=r.artwork||(r.poster?[{src:r.poster}]:[]);try{navigator.mediaSession.metadata=new MediaMetadata({title:a,artist:n,album:l,artwork:o}),navigator.mediaSession.setActionHandler("play",()=>{this.play()}),navigator.mediaSession.setActionHandler("pause",()=>{this.pause()}),navigator.mediaSession.setActionHandler("seekbackward",d=>{const h=d.seekOffset||10;this.seekBy(-h)}),navigator.mediaSession.setActionHandler("seekforward",d=>{const h=d.seekOffset||10;this.seekBy(h)}),navigator.mediaSession.setActionHandler("seekto",d=>{d.seekTime!==void 0&&this.seek(d.seekTime)}),t&&t.length>1?(navigator.mediaSession.setActionHandler("previoustrack",()=>{this.previous()}),navigator.mediaSession.setActionHandler("nexttrack",()=>{this.next()})):(navigator.mediaSession.setActionHandler("previoustrack",null),navigator.mediaSession.setActionHandler("nexttrack",null))}catch(d){console.warn("[PlayerController] Failed to update Media Session metadata:",d)}}updateMediaSessionPosition(){if(!(typeof window>"u"||!("mediaSession"in navigator)||typeof navigator.mediaSession.setPositionState!="function"))try{const e=this.video.duration,t=this.video.currentTime,i=this.video.playbackRate;Number.isFinite(e)&&Number.isFinite(t)&&Number.isFinite(i)&&e>=0&&t>=0&&t<=e&&navigator.mediaSession.setPositionState({duration:e,playbackRate:i,position:t})}catch{}}updateMediaSessionPlaybackState(e){if(!(typeof window>"u"||!("mediaSession"in navigator)))try{navigator.mediaSession.playbackState=e?"playing":"paused"}catch{}}}class Tr{static async validate(e){const t={emeSupported:typeof navigator<"u"&&typeof navigator.requestMediaKeySystemAccess=="function",keySystems:{},activeSystem:null,hasMediaKeys:!1,activeSessionsCount:0,sessionIds:[],keyStatuses:[],hasUsableKey:!1,errors:[],passed:!1,requestMediaKeySystemAccessChecked:!1,mediaKeysCreatedChecked:!1,mediaKeysAttachedChecked:!1,encryptedEventCount:0,licenseChallengeGeneratedCount:0,licenseRequestSentCount:0,licenseResponseReceivedCount:0,sessionUpdatedCount:0,keyStatusesChangeCount:0,usableKeysCount:0,expiredKeysCount:0,outputRestrictedCount:0,internalErrorsCount:0,closedSessionsCount:0,lastInternalError:null};if(!t.emeSupported)return t.errors.push("EME is not supported on this platform/browser."),t;const i={widevine:"com.widevine.alpha",playready:"com.microsoft.playready",fairplay:"com.apple.fps",clearkey:"org.w3.clearkey"},s=[{contentType:'video/mp4; codecs="avc1.640028"'},{contentType:'video/mp4; codecs="avc1.4d401e"'},{contentType:"video/mp4"},{contentType:'video/webm; codecs="vp9"'}],r=[{contentType:'audio/mp4; codecs="mp4a.40.2"'},{contentType:"audio/mp4"},{contentType:'audio/webm; codecs="opus"'}];for(const[l,o]of Object.entries(i))try{const d=[{initDataTypes:["cenc","keyids","webm","skd","sinf"],videoCapabilities:s,audioCapabilities:r},{initDataTypes:["cenc","keyids","webm","skd","sinf"],videoCapabilities:s},{initDataTypes:["cenc","keyids","webm","skd","sinf"],audioCapabilities:r},{initDataTypes:["cenc","keyids","webm","skd","sinf"],videoCapabilities:s,persistentState:"not-allowed",distinctiveIdentifier:"not-allowed"}];await navigator.requestMediaKeySystemAccess(o,d),t.keySystems[l]=!0}catch{t.keySystems[l]=!1}const a=e.getVideoElement();if(a&&a.mediaKeys){t.hasMediaKeys=!0;const l=e.getDrmManager();if(l){const o=l.getConfig();o&&(t.activeSystem=Object.keys(o).find(u=>u!=="robustness"&&u!=="distinctiveIdentifier"&&u!=="persistentState"&&u!=="retryCount"&&u!=="timeout")||null);const d=l.getActiveSessions();d&&(t.activeSessionsCount=d.size,d.forEach(u=>{u.sessionId&&t.sessionIds.push(u.sessionId),u.keyStatuses&&u.keyStatuses.forEach(f=>{t.keyStatuses.push(String(f)),f==="usable"&&(t.hasUsableKey=!0)})}));const h=l.emeDiagnostics;h&&(t.requestMediaKeySystemAccessChecked=h.requestMediaKeySystemAccess,t.mediaKeysCreatedChecked=h.mediaKeysCreated,t.mediaKeysAttachedChecked=h.mediaKeysAttached,t.encryptedEventCount=h.encryptedEventsCount,t.licenseChallengeGeneratedCount=h.challengesGenerated,t.licenseRequestSentCount=h.licenseRequestsSent,t.licenseResponseReceivedCount=h.licenseResponsesReceived,t.sessionUpdatedCount=h.sessionsUpdated,t.keyStatusesChangeCount=h.keyStatusesChanges,t.usableKeysCount=h.usableKeysCount,t.expiredKeysCount=h.expiredKeysCount,t.outputRestrictedCount=h.outputRestrictedCount,t.internalErrorsCount=h.internalErrorsCount,t.closedSessionsCount=h.closedSessionsCount,t.lastInternalError=h.lastInternalError,h.expiredKeysCount>0&&t.errors.push(`EME has ${h.expiredKeysCount} expired key(s).`),h.outputRestrictedCount>0&&t.errors.push("EME playback restricted by HDCP output constraints."),h.internalErrorsCount>0&&h.lastInternalError&&t.errors.push(`EME Internal Error: ${h.lastInternalError}`))}}const n=e.getState();return n&&n.error&&t.errors.push(n.error),t.passed=t.emeSupported&&t.errors.length===0,t}}const Er=Ae`
2040
2040
  :host {
2041
2041
  display: inline-block;
2042
2042
  width: var(--player-button-width, 40px);
@@ -2189,7 +2189,7 @@ var StreamitPlayer=function(B){"use strict";/**
2189
2189
  >
2190
2190
  ${this.playing?G(this.player?this.player.getIcon("pause"):X.getDefaultIcon("pause")):G(this.player?this.player.getIcon("play"):X.getDefaultIcon("play"))}
2191
2191
  </button>
2192
- `}};ei.styles=Er;let $e=ei;if(rs([O({type:Boolean,reflect:!0})],$e.prototype,"playing"),rs([O({attribute:!1})],$e.prototype,"player"),typeof window<"u"&&typeof customElements<"u"&&(customElements.get("streamit-play-button")||customElements.define("streamit-play-button",$e),!customElements.get("player-play-button"))){class c extends $e{}customElements.define("player-play-button",c)}const Ir=Ae`
2192
+ `}};ei.styles=Er;let $e=ei;if(rs([F({type:Boolean,reflect:!0})],$e.prototype,"playing"),rs([F({attribute:!1})],$e.prototype,"player"),typeof window<"u"&&typeof customElements<"u"&&(customElements.get("streamit-play-button")||customElements.define("streamit-play-button",$e),!customElements.get("player-play-button"))){class c extends $e{}customElements.define("player-play-button",c)}const Ir=Ae`
2193
2193
  :host {
2194
2194
  display: inline-block;
2195
2195
  width: var(--player-button-width, 40px);
@@ -2239,7 +2239,7 @@ var StreamitPlayer=function(B){"use strict";/**
2239
2239
  <button part="button" @click=${this.handleClick} aria-label=${s} title=${s}>
2240
2240
  ${G(e?this.player?this.player.getIcon("seek-backward",{amount:this.amount}):typeof r=="function"?r({amount:this.amount}):r:this.player?this.player.getIcon("seek-forward",{amount:this.amount}):typeof a=="function"?a({amount:this.amount}):a)}
2241
2241
  </button>
2242
- `}};ti.styles=Ir;let we=ti;if(Yt([O({type:String})],we.prototype,"direction"),Yt([O({type:Number})],we.prototype,"amount"),Yt([O({attribute:!1})],we.prototype,"player"),typeof window<"u"&&typeof customElements<"u"&&(customElements.get("streamit-seek-button")||customElements.define("streamit-seek-button",we),!customElements.get("player-seek-button"))){class c extends we{}customElements.define("player-seek-button",c)}const Rr=Ae`
2242
+ `}};ti.styles=Ir;let we=ti;if(Yt([F({type:String})],we.prototype,"direction"),Yt([F({type:Number})],we.prototype,"amount"),Yt([F({attribute:!1})],we.prototype,"player"),typeof window<"u"&&typeof customElements<"u"&&(customElements.get("streamit-seek-button")||customElements.define("streamit-seek-button",we),!customElements.get("player-seek-button"))){class c extends we{}customElements.define("player-seek-button",c)}const Rr=Ae`
2243
2243
  :host {
2244
2244
  display: block;
2245
2245
  width: 100%;
@@ -2628,13 +2628,13 @@ var StreamitPlayer=function(B){"use strict";/**
2628
2628
  .seekbar-container.vertical .tooltip-marker-label {
2629
2629
  max-width: var(--player-preview-vertical-width, 90px);
2630
2630
  }
2631
- `;var Dr=Object.defineProperty,J=(c,e,t,i)=>{for(var s=void 0,r=c.length-1,a;r>=0;r--)(a=c[r])&&(s=a(e,t,s)||s);return s&&Dr(e,t,s),s};const ii=class ii extends ge{constructor(){super(...arguments),this.currentTime=0,this.duration=0,this.bufferedRanges=[],this.isSeeking=!1,this.isLive=null,this.currentSource="",this.variant="standard",this.markers=[],this.visibleMarkerTypes=null,this.chapters=[],this.canSeekInDvr=!1,this.isAtLiveEdge=!1,this.paused=!1,this.hideCurrentTime=!1,this.hideDuration=!1,this.isAdPlaying=!1,this.activeFilmstripThumbnail=null,this.frozenPercent=null,this.isDragging=!1,this.dragTime=0,this.isHovered=!1,this.hoverTime=0,this.isPreciseSeeking=!1,this.tooltipLeft=0,this.showRemaining=!1,this.activeThumbnail=null,this.isThumbnailLoading=!1,this.caretOffset=0,this.activeMarker=null,this.activeMarkerLabel="",this.frozenTimelineRange=null,this.latestThumbnailRequestId=0,this.lastSuccessfulThumbnail=null,this.pendingHoverClientX=null,this.isPointerInside=!1,this.dragStartTrackTop=0,this.dragStartX=0,this.dragStartY=0,this.hasMoved=!1,this.cachedHostRect=null,this.cachedTrackRect=null,this.handlePointerMove=e=>{var i,s;if(!this.isDragging)return;this.hasMoved||(Math.abs(e.clientX-this.dragStartX)>5||Math.abs(e.clientY-this.dragStartY)>5)&&(this.hasMoved=!0,this.dispatchSeek(this.dragTime,!1)),this.lastClientX=e.clientX,this.computeTooltipPosition(e.clientX);const t=this.getTimeFromEvent(e);if(this.dragTime=t,this.hoverTime=t,this.computeActiveMarker(t),this.pendingHoverClientX=e.clientX,this.hoverThrottleTimer||(this.hoverThrottleTimer=window.setTimeout(()=>{this.hoverThrottleTimer=void 0,this.pendingHoverClientX!==null&&(this.updateTooltipPosition(this.pendingHoverClientX),this.pendingHoverClientX=null)},60)),((s=(i=this.player)==null?void 0:i.controllerInstance)==null?void 0:s.isPreciseSeekEnabled())!==!1&&this.variant!=="vertical"&&(!this.isLive||this.isLive&&this.canSeekInDvr)){const r=this.dragStartTrackTop-e.clientY,a=r>40;a&&!this.isPreciseSeeking?(this.isPreciseSeeking=!0,this.dispatchEvent(new CustomEvent("player-precise-seek-change",{detail:{isPreciseSeeking:!0},bubbles:!0,composed:!0}))):!a&&this.isPreciseSeeking&&r<20&&(this.isPreciseSeeking=!1,this.dispatchEvent(new CustomEvent("player-precise-seek-change",{detail:{isPreciseSeeking:!1},bubbles:!0,composed:!0})))}this.hasMoved&&this.dispatchSeek(t,!1)},this.handlePointerUp=e=>{if(!this.isDragging)return;this.isDragging=!1,this.frozenTimelineRange=null;try{e.target.releasePointerCapture(e.pointerId)}catch{}let t=this.getTimeFromEvent(e);const{trackRect:i}=this.getInteractiveRects();let s=!1;if(i){const a=(e.clientX-i.left)/i.width;s=a<=.005||a>=.995}const r=a=>{var n,l,o,d,h,u;return((l=(n=this.player)==null?void 0:n.controllerInstance)==null?void 0:l.isPreciseSeekEnabled())===!1?!1:a.type==="chapter"?((d=(o=this.player)==null?void 0:o.controllerInstance)==null?void 0:d.shouldSnapToChapters())!==!1:((u=(h=this.player)==null?void 0:h.controllerInstance)==null?void 0:u.shouldSnapToMarkers())!==!1};!s&&this.activeMarker&&r(this.activeMarker)&&(t=this.activeMarker.time),this.dispatchSeek(t,!0),this.cleanupDrag(),this.hasMoved=!1,this.isPreciseSeeking&&(this.isPreciseSeeking=!1,this.dispatchEvent(new CustomEvent("player-precise-seek-change",{detail:{isPreciseSeeking:!1},bubbles:!0,composed:!0}))),(!this.isPointerInside||e.pointerType==="touch")&&(this.isHovered=!1,this.activeThumbnail=null,this.lastSuccessfulThumbnail=null,this.activeMarkerLabel="",this.isThumbnailLoading=!1,this.hoverThrottleTimer&&(clearTimeout(this.hoverThrottleTimer),this.hoverThrottleTimer=void 0),this.pendingHoverClientX=null,this.isPointerInside=!1)},this.lastClientX=0,this.handleKeyDown=e=>{const{start:t,end:i,isInteractive:s}=this.getTimelineRange();if(!s)return;const r=5,a=30;let n=this.isDragging?this.dragTime:this.currentTime,l=!1;switch(e.key){case"ArrowRight":case"ArrowUp":n=Math.min(i,n+r),l=!0;break;case"ArrowLeft":case"ArrowDown":n=Math.max(t,n-r),l=!0;break;case"PageUp":n=Math.min(i,n+a),l=!0;break;case"PageDown":n=Math.max(t,n-a),l=!0;break;case"Home":n=t,l=!0;break;case"End":n=i,l=!0;break}l&&(e.preventDefault(),e.stopPropagation(),this.isDragging?(this.dragTime=n,this.dispatchSeek(n,!1)):this.dispatchSeek(n,!0))},this.handleWindowResize=()=>{this.cachedHostRect=null,this.cachedTrackRect=null}}getInteractiveRects(){var e;if(!this.cachedHostRect||!this.cachedTrackRect){this.cachedHostRect=this.getBoundingClientRect();const t=(e=this.renderRoot)==null?void 0:e.querySelector(".track");t&&(this.cachedTrackRect=t.getBoundingClientRect())}return{hostRect:this.cachedHostRect,trackRect:this.cachedTrackRect}}getTimelineRange(){if(this.isAdPlaying)return{start:0,end:0,range:0,isInteractive:!1};if(this.isDragging&&this.frozenTimelineRange)return this.frozenTimelineRange;if(this.isLive===null)return{start:0,end:0,range:0,isInteractive:!1};const e=this.isLive===!0;if(e&&!this.canSeekInDvr)return{start:0,end:0,range:0,isInteractive:!1};const t=e&&this.seekableRange?this.seekableRange.start:0,i=e&&this.seekableRange?this.seekableRange.end:this.duration,s=i-t,r=e?Number.isFinite(s)&&s>=5:Number.isFinite(s)&&s>0;return{start:t,end:i,range:Number.isFinite(s)?s:0,isInteractive:r}}getBufferedPercent(){if(this.isLive&&(!this.canSeekInDvr||this.isAtLiveEdge))return 100;const{start:e,end:t,range:i}=this.getTimelineRange();if(i<=0||!this.bufferedRanges.length)return 0;const s=this.isDragging?this.dragTime:this.currentTime;let r=e;for(const n of this.bufferedRanges)if(n.start<=s&&n.end>=s){r=n.end;break}r===e&&this.bufferedRanges.length>0&&(r=this.bufferedRanges[0].end);const a=pe.clampToSeekable(r,e,t);return pe.timeToPercent(a,e,t)}getTimeFromEvent(e){var l,o;const{start:t,end:i}=this.getTimelineRange();if(this.isLive&&((o=(l=this.player)==null?void 0:l.controllerInstance)==null?void 0:o.isLiveDraggingEnabled())===!1)return i;const{trackRect:s}=this.getInteractiveRects();if(!s)return 0;const r=s,a=(e.clientX-r.left)/r.width,n=Math.max(0,Math.min(a,1));return n<=.005?t:n>=.995?i:pe.percentToTime(n*100,t,i)}computeActiveMarker(e){var p,g,m,v;if(this.isLive&&!this.canSeekInDvr){this.activeMarker=null,this.activeMarkerLabel="";return}const{start:t,end:i,range:s}=this.getTimelineRange(),r=Math.max(1.5,s*.015),a=((g=(p=this.player)==null?void 0:p.controllerInstance)==null?void 0:g.shouldSnapToChapters())!==!1,n=((v=(m=this.player)==null?void 0:m.controllerInstance)==null?void 0:v.shouldSnapToMarkers())!==!1,l=n&&this.markers?this.markers.filter(y=>pe.isMarkerVisible(y.time,t,i)):[],o=n?pe.findNearestMarker(e,l,this.visibleMarkerTypes,r):null,d=a?pe.findNearestChapterBoundary(e,this.chapters||[],r):null;let h=null,u=1/0;if(o&&(u=Math.abs(o.time-e),h=o),d){const y=Math.abs(d.startTime-e);y<u&&(u=y,h={id:`chapter-${d.id??d.startTime}`,time:d.startTime,label:d.title||"",type:"chapter"})}const f=this.activeMarker;this.activeMarker=h,this.activeMarkerLabel=h?h.label:"",this.activeMarker!==f&&this.activeMarker&&this.activeMarker.type!=="chapter"&&this.dispatchEvent(new CustomEvent("player-marker-hover",{detail:{marker:this.activeMarker,type:this.activeMarker.type,time:this.activeMarker.time,label:this.activeMarker.label},bubbles:!0,composed:!0}))}handlePointerDown(e){const{isInteractive:t}=this.getTimelineRange();if(!t)return;e.preventDefault();try{e.target.setPointerCapture(e.pointerId)}catch{}this.isDragging=!0,this.frozenTimelineRange=this.getTimelineRange(),this.dragTime=this.getTimeFromEvent(e),this.hoverTime=this.dragTime,this.dragStartX=e.clientX,this.dragStartY=e.clientY,this.hasMoved=!1,this.computeTooltipPosition(e.clientX),this.computeActiveMarker(this.dragTime),this.updateTooltipPosition(e.clientX);const{trackRect:i}=this.getInteractiveRects();i&&(this.dragStartTrackTop=i.top),window.addEventListener("pointermove",this.handlePointerMove),window.addEventListener("pointerup",this.handlePointerUp),window.addEventListener("pointercancel",this.handlePointerUp)}cleanupDrag(){this.cachedHostRect=null,this.cachedTrackRect=null,typeof window<"u"&&(window.removeEventListener("pointermove",this.handlePointerMove),window.removeEventListener("pointerup",this.handlePointerUp),window.removeEventListener("pointercancel",this.handlePointerUp))}dispatchSeek(e,t){this.dispatchEvent(new CustomEvent("player-seek",{detail:{time:e,isFinal:t},bubbles:!0,composed:!0}))}handlePointerEnter(){const{isInteractive:e}=this.getTimelineRange();e&&(this.isHovered=!0,this.isPointerInside=!0)}handlePointerLeave(){this.isPointerInside=!1,this.cachedHostRect=null,this.cachedTrackRect=null,!this.isDragging&&(this.isHovered=!1,this.clearThumbnailHoverState())}clearThumbnailHoverState(){this.activeThumbnail=null,this.lastSuccessfulThumbnail=null,this.activeMarkerLabel="",this.isThumbnailLoading=!1,this.hoverThrottleTimer&&(clearTimeout(this.hoverThrottleTimer),this.hoverThrottleTimer=void 0),this.pendingHoverClientX=null}handleHoverPointerMove(e){if(this.isDragging)return;this.lastClientX=e.clientX,this.computeTooltipPosition(e.clientX);const{isInteractive:t}=this.getTimelineRange();if(t){const i=this.getTimeFromEvent(e);this.hoverTime=i,this.computeActiveMarker(i)}this.pendingHoverClientX=e.clientX,this.hoverThrottleTimer||(this.hoverThrottleTimer=window.setTimeout(()=>{this.hoverThrottleTimer=void 0,this.pendingHoverClientX!==null&&(this.updateTooltipPosition(this.pendingHoverClientX),this.pendingHoverClientX=null)},60))}computeTooltipPosition(e){var A;const{hostRect:t,trackRect:i}=this.getInteractiveRects();if(!i||!t)return;const s=(e-i.left)/i.width,r=Math.max(0,Math.min(s,1)),{isInteractive:a}=this.getTimelineRange();if(!a)return;const n=i.left-t.left+r*i.width,l=(A=this.renderRoot)==null?void 0:A.querySelector(".hover-tooltip");let o=0;if(l)if(l.offsetWidth>0)o=l.offsetWidth;else{const P=l.getBoundingClientRect();P.width>0&&(o=P.width)}const d=!!this.activeThumbnail||this.isThumbnailLoading;if(o===0){const P=d?this.variant==="vertical"?94:204:50;o=window.innerWidth<=480?P*.85:P}const h=o/2;let u=this.player||null;if(!u){const P=this.getRootNode();P instanceof ShadowRoot&&P.host&&(u=P.host)}u||(u=this.parentElement||this.offsetParent);let f=0,p=t.width;if(u){const P=u.getBoundingClientRect();P.width>0&&(f=Math.min(0,P.left-t.left),p=Math.max(t.width,P.right-t.left))}if(typeof window<"u"){const P=-t.left,$=window.innerWidth-t.left;f=Math.max(f,P),p=Math.min(p,$)}const g=3,m=f+h+g,v=p-h-g;this.tooltipLeft=Math.max(m,Math.min(n,v));const y=n-this.tooltipLeft,T=(d?12:4)+Math.ceil(6/2),E=Math.max(0,h-T);this.caretOffset=Math.max(-E,Math.min(y,E))}updated(e){if(super.updated(e),e.has("activeFilmstripThumbnail")&&this.isPreciseSeeking&&this.activeFilmstripThumbnail!==void 0&&(this.activeFilmstripThumbnail?(this.activeThumbnail=this.activeFilmstripThumbnail,this.lastSuccessfulThumbnail=this.activeFilmstripThumbnail,this.isThumbnailLoading=!1):(this.activeThumbnail=this.lastSuccessfulThumbnail||null,this.isThumbnailLoading=!this.lastSuccessfulThumbnail)),(e.has("activeThumbnail")||e.has("isHovered")||e.has("isThumbnailLoading"))&&(this.isHovered||this.isDragging)&&this.computeTooltipPosition(this.lastClientX),(e.has("seekableRange")||e.has("duration"))&&(this.isHovered||this.isDragging)){const{trackRect:a}=this.getInteractiveRects();if(a){const n=(this.lastClientX-a.left)/a.width,l=Math.max(0,Math.min(n,1)),{start:o,end:d,isInteractive:h}=this.getTimelineRange();if(h){const u=pe.percentToTime(l*100,o,d);this.hoverTime=u,this.isDragging&&(this.dragTime=u,this.dispatchSeek(u,!1)),this.computeActiveMarker(u),this.updateTooltipPosition(this.lastClientX)}}}(e.has("thumbnailProvider")||e.has("currentSource"))&&!(this.thumbnailProvider&&!(typeof this.thumbnailProvider.isUnavailable=="function"&&this.thumbnailProvider.isUnavailable()))&&this.isPreciseSeeking&&(this.isPreciseSeeking=!1,this.dispatchEvent(new CustomEvent("player-precise-seek-change",{detail:{isPreciseSeeking:!1},bubbles:!0,composed:!0})));const{start:t,end:i}=this.getTimelineRange(),s=this.isDragging?this.dragTime:this.currentTime,r=this.isLive?i-t>=3600:i>=3600;this.setAttribute("role","slider"),this.setAttribute("aria-valuemin",Math.round(t).toString()),this.setAttribute("aria-valuemax",Math.round(i).toString()),this.setAttribute("aria-valuenow",Math.round(s).toString()),this.setAttribute("aria-valuetext",ce(s,r))}async updateTooltipPosition(e){var v,y,b,S;this.lastClientX=e;const{trackRect:t}=this.getInteractiveRects();if(!t)return;const i=(e-t.left)/t.width,s=Math.max(0,Math.min(i,1)),{start:r,end:a,range:n,isInteractive:l}=this.getTimelineRange();if(!l){this.activeThumbnail=null;return}let o=pe.percentToTime(s*100,r,a);this.hoverTime=o,this.isDragging&&(this.dragTime=o),this.computeTooltipPosition(e),this.computeActiveMarker(o);const d=s<=.005||s>=.995,h=T=>{var E,A,P,$,M,I;return((A=(E=this.player)==null?void 0:E.controllerInstance)==null?void 0:A.isPreciseSeekEnabled())===!1?!1:T.type==="chapter"?(($=(P=this.player)==null?void 0:P.controllerInstance)==null?void 0:$.shouldSnapToChapters())!==!1:((I=(M=this.player)==null?void 0:M.controllerInstance)==null?void 0:I.shouldSnapToMarkers())!==!1};!d&&this.activeMarker&&h(this.activeMarker)&&(o=this.activeMarker.time,this.hoverTime=o);const u=((y=(v=this.player)==null?void 0:v.controllerInstance)==null?void 0:y.isSmartSeekEnabled())===!1,f=(S=(b=this.player)==null?void 0:b.config)==null?void 0:S.smartSeek,p=u||f&&typeof f=="object"&&f.thumbnails===!1,g=u||f&&typeof f=="object"&&f.storyboard===!1,m=p||g||this.thumbnailProvider&&typeof this.thumbnailProvider.isUnavailable=="function"&&this.thumbnailProvider.isUnavailable();if(!(!this.isHovered&&!this.isDragging))if(this.thumbnailProvider&&!m){if(this.isPreciseSeeking){const E=Math.round(o);let A=this.activeFilmstripThumbnail||null;if(!A&&typeof this.thumbnailProvider.getNearestCachedThumbnail=="function"){const P=this.thumbnailProvider.getNearestCachedThumbnail(E);P&&P.time!==void 0&&Math.abs(P.time-E)<=5&&(A=P)}A?(this.activeThumbnail=A,this.lastSuccessfulThumbnail=A,this.isThumbnailLoading=!1):(this.activeThumbnail=null,this.isThumbnailLoading=!0);return}const T=++this.latestThumbnailRequestId;try{const E=this.thumbnailProvider.getThumbnail(o);if(E instanceof Promise){let A=null;if(typeof this.thumbnailProvider.getNearestCachedThumbnail=="function"){const $=this.thumbnailProvider.getNearestCachedThumbnail(o);if($&&$.time!==void 0){const M=Math.abs($.time-o),I=Math.max(15,n*.05);M<=I&&(A=$)}}if(A)this.activeThumbnail=A;else if(this.activeThumbnail&&this.activeThumbnail.time!==void 0){const $=Math.abs(this.activeThumbnail.time-o),M=Math.max(15,n*.05);$>M&&(this.activeThumbnail=null)}else if(this.activeThumbnail=this.lastSuccessfulThumbnail||null,this.activeThumbnail&&this.activeThumbnail.time!==void 0){const $=Math.abs(this.activeThumbnail.time-o),M=Math.max(15,n*.05);$>M&&(this.activeThumbnail=null)}this.isThumbnailLoading=!0;const P=await E.catch($=>(console.debug("[Seekbar] Exception caught during thumbnail fetch (async):",$),null));T===this.latestThumbnailRequestId&&(this.isHovered||this.isDragging)&&(P?(this.activeThumbnail=P,this.lastSuccessfulThumbnail=P):this.activeThumbnail=this.lastSuccessfulThumbnail||null,this.isThumbnailLoading=!1)}else T===this.latestThumbnailRequestId&&(this.activeThumbnail=E,E&&(this.lastSuccessfulThumbnail=E),this.isThumbnailLoading=!1)}catch(E){console.debug("[Seekbar] Exception caught during thumbnail fetch:",E),T===this.latestThumbnailRequestId&&(this.activeThumbnail=null,this.isThumbnailLoading=!1)}}else this.activeThumbnail=null,this.isThumbnailLoading=!1}handleTimeClick(e){e.stopPropagation(),!(this.hideCurrentTime||this.hideDuration)&&(this.showRemaining=!this.showRemaining)}connectedCallback(){super.connectedCallback(),this.setAttribute("tabindex","0"),this.setAttribute("role","slider"),this.setAttribute("aria-label","Seek timeline progress"),this.addEventListener("keydown",this.handleKeyDown),typeof window<"u"&&window.addEventListener("resize",this.handleWindowResize)}disconnectedCallback(){super.disconnectedCallback(),this.removeEventListener("keydown",this.handleKeyDown),typeof window<"u"&&window.removeEventListener("resize",this.handleWindowResize),this.cleanupDrag(),this.hoverThrottleTimer&&(clearTimeout(this.hoverThrottleTimer),this.hoverThrottleTimer=void 0),this.cachedHostRect=null,this.cachedTrackRect=null}willUpdate(e){if(super.willUpdate(e),e.has("paused"))if(this.paused){const{start:a,range:n}=this.getTimelineRange();n>0?this.frozenPercent=(this.currentTime-a)/n*100:this.frozenPercent=this.isLive?100:0}else this.frozenPercent=null;if(this.paused&&(e.has("currentTime")||e.has("seekableRange"))){const{start:a,range:n}=this.getTimelineRange();this.currentTime<a?this.frozenPercent=0:e.has("currentTime")&&n>0&&(this.frozenPercent=(this.currentTime-a)/n*100)}(e.has("thumbnailProvider")||e.has("currentSource"))&&(this.lastSuccessfulThumbnail=null,this.activeThumbnail=null,this.isThumbnailLoading=!1);const{start:t,end:i,isInteractive:s}=this.getTimelineRange();this.setAttribute("aria-valuemin",Math.round(t).toString()),this.setAttribute("aria-valuemax",Math.round(i).toString());const r=this.isDragging?this.dragTime:this.currentTime;this.setAttribute("aria-valuenow",Math.round(r).toString()),this.setAttribute("aria-valuetext",ce(r,i>=3600)),s?this.removeAttribute("aria-disabled"):this.setAttribute("aria-disabled","true")}handleMarkerClick(e,t){this.isLive&&!this.canSeekInDvr||(e.stopPropagation(),e.preventDefault(),this.dispatchSeek(t.time,!0),this.dispatchEvent(new CustomEvent("player-marker-click",{detail:{marker:t,type:t.type,time:t.time,label:t.label,originalEvent:e},bubbles:!0,composed:!0})))}render(){var $,M,I,R,N,U,C,x,H,te,V,F;const{start:e,end:t,range:i,isInteractive:s}=this.getTimelineRange(),r=this.player?this.player.localize("live","LIVE"):"LIVE",a=this.player?this.player.localize("preciseSeeking","Precise seeking"):"Precise seeking",n=this.player?this.player.localize("pullUpForPreciseSeeking","Pull up for precise seeking"):"Pull up for precise seeking",l=((M=($=this.player)==null?void 0:$.controllerInstance)==null?void 0:M.isMarkersEnabled())!==!1,o=(R=(I=this.player)==null?void 0:I.config)==null?void 0:R.smartSeek,d=((U=(N=this.player)==null?void 0:N.controllerInstance)==null?void 0:U.isSmartSeekEnabled())!==!1&&(o===void 0||typeof o!="object"||o.hoverTime!==!1),h=l&&!(this.isLive&&!this.canSeekInDvr)&&this.markers?this.markers.filter(L=>{const D=!this.visibleMarkerTypes||this.visibleMarkerTypes.includes(L.type),q=L.time>=e&&L.time<=t;return D&&q}):[],u=((x=(C=this.player)==null?void 0:C.controllerInstance)==null?void 0:x.isSmoothDraggingEnabled())!==!1,f=u?"transition: width 0.05s ease-out;":"",p=u?"transition: left 0.05s ease-out;":"",g=this.isDragging?this.dragTime:this.currentTime,m=this.isLive&&(!this.canSeekInDvr||this.isAtLiveEdge)?100:this.paused&&this.frozenPercent!==null&&!this.isDragging?this.frozenPercent:i>0?pe.timeToPercent(g,e,t):0,v=this.getBufferedPercent(),y=s&&(this.isDragging||this.isHovered||this.isSeeking),b=this.isLive?i>=3600:t>=3600;let S="";const T=this.isDragging?this.dragTime:this.isHovered?this.hoverTime:this.currentTime;if(this.hideCurrentTime&&this.hideDuration)S="";else if(this.hideCurrentTime)S=ce(t,b);else if(this.hideDuration)S=ce(T,b);else if(this.showRemaining){const L=T-t;S=ce(L,b)}else S=ce(T,b);let E="";if(this.activeThumbnail)if(this.variant==="vertical")if(this.activeThumbnail.x!==void 0){const L=this.activeThumbnail.width||200,D=this.activeThumbnail.height||112,q=Math.min(90/L,160/D);E=`
2631
+ `;var Dr=Object.defineProperty,J=(c,e,t,i)=>{for(var s=void 0,r=c.length-1,a;r>=0;r--)(a=c[r])&&(s=a(e,t,s)||s);return s&&Dr(e,t,s),s};const ii=class ii extends ge{constructor(){super(...arguments),this.currentTime=0,this.duration=0,this.bufferedRanges=[],this.isSeeking=!1,this.isLive=null,this.currentSource="",this.variant="standard",this.markers=[],this.visibleMarkerTypes=null,this.chapters=[],this.canSeekInDvr=!1,this.isAtLiveEdge=!1,this.paused=!1,this.hideCurrentTime=!1,this.hideDuration=!1,this.isAdPlaying=!1,this.activeFilmstripThumbnail=null,this.frozenPercent=null,this.isDragging=!1,this.dragTime=0,this.isHovered=!1,this.hoverTime=0,this.isPreciseSeeking=!1,this.tooltipLeft=0,this.showRemaining=!1,this.activeThumbnail=null,this.isThumbnailLoading=!1,this.caretOffset=0,this.activeMarker=null,this.activeMarkerLabel="",this.frozenTimelineRange=null,this.latestThumbnailRequestId=0,this.lastSuccessfulThumbnail=null,this.pendingHoverClientX=null,this.isPointerInside=!1,this.dragStartTrackTop=0,this.dragStartX=0,this.dragStartY=0,this.hasMoved=!1,this.cachedHostRect=null,this.cachedTrackRect=null,this.handlePointerMove=e=>{var i,s;if(!this.isDragging)return;this.hasMoved||(Math.abs(e.clientX-this.dragStartX)>5||Math.abs(e.clientY-this.dragStartY)>5)&&(this.hasMoved=!0,this.dispatchSeek(this.dragTime,!1)),this.lastClientX=e.clientX,this.computeTooltipPosition(e.clientX);const t=this.getTimeFromEvent(e);if(this.dragTime=t,this.hoverTime=t,this.computeActiveMarker(t),this.pendingHoverClientX=e.clientX,this.hoverThrottleTimer||(this.hoverThrottleTimer=window.setTimeout(()=>{this.hoverThrottleTimer=void 0,this.pendingHoverClientX!==null&&(this.updateTooltipPosition(this.pendingHoverClientX),this.pendingHoverClientX=null)},60)),((s=(i=this.player)==null?void 0:i.controllerInstance)==null?void 0:s.isPreciseSeekEnabled())!==!1&&this.variant!=="vertical"&&(!this.isLive||this.isLive&&this.canSeekInDvr)){const r=this.dragStartTrackTop-e.clientY,a=r>40;a&&!this.isPreciseSeeking?(this.isPreciseSeeking=!0,this.dispatchEvent(new CustomEvent("player-precise-seek-change",{detail:{isPreciseSeeking:!0},bubbles:!0,composed:!0}))):!a&&this.isPreciseSeeking&&r<20&&(this.isPreciseSeeking=!1,this.dispatchEvent(new CustomEvent("player-precise-seek-change",{detail:{isPreciseSeeking:!1},bubbles:!0,composed:!0})))}this.hasMoved&&this.dispatchSeek(t,!1)},this.handlePointerUp=e=>{if(!this.isDragging)return;this.isDragging=!1,this.frozenTimelineRange=null;try{e.target.releasePointerCapture(e.pointerId)}catch{}let t=this.getTimeFromEvent(e);const{trackRect:i}=this.getInteractiveRects();let s=!1;if(i){const a=(e.clientX-i.left)/i.width;s=a<=.005||a>=.995}const r=a=>{var n,l,o,d,h,u;return((l=(n=this.player)==null?void 0:n.controllerInstance)==null?void 0:l.isPreciseSeekEnabled())===!1?!1:a.type==="chapter"?((d=(o=this.player)==null?void 0:o.controllerInstance)==null?void 0:d.shouldSnapToChapters())!==!1:((u=(h=this.player)==null?void 0:h.controllerInstance)==null?void 0:u.shouldSnapToMarkers())!==!1};!s&&this.activeMarker&&r(this.activeMarker)&&(t=this.activeMarker.time),this.dispatchSeek(t,!0),this.cleanupDrag(),this.hasMoved=!1,this.isPreciseSeeking&&(this.isPreciseSeeking=!1,this.dispatchEvent(new CustomEvent("player-precise-seek-change",{detail:{isPreciseSeeking:!1},bubbles:!0,composed:!0}))),(!this.isPointerInside||e.pointerType==="touch")&&(this.isHovered=!1,this.activeThumbnail=null,this.lastSuccessfulThumbnail=null,this.activeMarkerLabel="",this.isThumbnailLoading=!1,this.hoverThrottleTimer&&(clearTimeout(this.hoverThrottleTimer),this.hoverThrottleTimer=void 0),this.pendingHoverClientX=null,this.isPointerInside=!1)},this.lastClientX=0,this.handleKeyDown=e=>{const{start:t,end:i,isInteractive:s}=this.getTimelineRange();if(!s)return;const r=5,a=30;let n=this.isDragging?this.dragTime:this.currentTime,l=!1;switch(e.key){case"ArrowRight":case"ArrowUp":n=Math.min(i,n+r),l=!0;break;case"ArrowLeft":case"ArrowDown":n=Math.max(t,n-r),l=!0;break;case"PageUp":n=Math.min(i,n+a),l=!0;break;case"PageDown":n=Math.max(t,n-a),l=!0;break;case"Home":n=t,l=!0;break;case"End":n=i,l=!0;break}l&&(e.preventDefault(),e.stopPropagation(),this.isDragging?(this.dragTime=n,this.dispatchSeek(n,!1)):this.dispatchSeek(n,!0))},this.handleWindowResize=()=>{this.cachedHostRect=null,this.cachedTrackRect=null}}getInteractiveRects(){var e;if(!this.cachedHostRect||!this.cachedTrackRect){this.cachedHostRect=this.getBoundingClientRect();const t=(e=this.renderRoot)==null?void 0:e.querySelector(".track");t&&(this.cachedTrackRect=t.getBoundingClientRect())}return{hostRect:this.cachedHostRect,trackRect:this.cachedTrackRect}}getTimelineRange(){if(this.isAdPlaying)return{start:0,end:0,range:0,isInteractive:!1};if(this.isDragging&&this.frozenTimelineRange)return this.frozenTimelineRange;if(this.isLive===null)return{start:0,end:0,range:0,isInteractive:!1};const e=this.isLive===!0;if(e&&!this.canSeekInDvr)return{start:0,end:0,range:0,isInteractive:!1};const t=e&&this.seekableRange?this.seekableRange.start:0,i=e&&this.seekableRange?this.seekableRange.end:this.duration,s=i-t,r=e?Number.isFinite(s)&&s>=5:Number.isFinite(s)&&s>0;return{start:t,end:i,range:Number.isFinite(s)?s:0,isInteractive:r}}getBufferedPercent(){if(this.isLive&&(!this.canSeekInDvr||this.isAtLiveEdge))return 100;const{start:e,end:t,range:i}=this.getTimelineRange();if(i<=0||!this.bufferedRanges.length)return 0;const s=this.isDragging?this.dragTime:this.currentTime;let r=e;for(const n of this.bufferedRanges)if(n.start<=s&&n.end>=s){r=n.end;break}r===e&&this.bufferedRanges.length>0&&(r=this.bufferedRanges[0].end);const a=pe.clampToSeekable(r,e,t);return pe.timeToPercent(a,e,t)}getTimeFromEvent(e){var l,o;const{start:t,end:i}=this.getTimelineRange();if(this.isLive&&((o=(l=this.player)==null?void 0:l.controllerInstance)==null?void 0:o.isLiveDraggingEnabled())===!1)return i;const{trackRect:s}=this.getInteractiveRects();if(!s)return 0;const r=s,a=(e.clientX-r.left)/r.width,n=Math.max(0,Math.min(a,1));return n<=.005?t:n>=.995?i:pe.percentToTime(n*100,t,i)}computeActiveMarker(e){var p,g,m,v;if(this.isLive&&!this.canSeekInDvr){this.activeMarker=null,this.activeMarkerLabel="";return}const{start:t,end:i,range:s}=this.getTimelineRange(),r=Math.max(1.5,s*.015),a=((g=(p=this.player)==null?void 0:p.controllerInstance)==null?void 0:g.shouldSnapToChapters())!==!1,n=((v=(m=this.player)==null?void 0:m.controllerInstance)==null?void 0:v.shouldSnapToMarkers())!==!1,l=n&&this.markers?this.markers.filter(y=>pe.isMarkerVisible(y.time,t,i)):[],o=n?pe.findNearestMarker(e,l,this.visibleMarkerTypes,r):null,d=a?pe.findNearestChapterBoundary(e,this.chapters||[],r):null;let h=null,u=1/0;if(o&&(u=Math.abs(o.time-e),h=o),d){const y=Math.abs(d.startTime-e);y<u&&(u=y,h={id:`chapter-${d.id??d.startTime}`,time:d.startTime,label:d.title||"",type:"chapter"})}const f=this.activeMarker;this.activeMarker=h,this.activeMarkerLabel=h?h.label:"",this.activeMarker!==f&&this.activeMarker&&this.activeMarker.type!=="chapter"&&this.dispatchEvent(new CustomEvent("player-marker-hover",{detail:{marker:this.activeMarker,type:this.activeMarker.type,time:this.activeMarker.time,label:this.activeMarker.label},bubbles:!0,composed:!0}))}handlePointerDown(e){const{isInteractive:t}=this.getTimelineRange();if(!t)return;e.preventDefault();try{e.target.setPointerCapture(e.pointerId)}catch{}this.isDragging=!0,this.frozenTimelineRange=this.getTimelineRange(),this.dragTime=this.getTimeFromEvent(e),this.hoverTime=this.dragTime,this.dragStartX=e.clientX,this.dragStartY=e.clientY,this.hasMoved=!1,this.computeTooltipPosition(e.clientX),this.computeActiveMarker(this.dragTime),this.updateTooltipPosition(e.clientX);const{trackRect:i}=this.getInteractiveRects();i&&(this.dragStartTrackTop=i.top),window.addEventListener("pointermove",this.handlePointerMove),window.addEventListener("pointerup",this.handlePointerUp),window.addEventListener("pointercancel",this.handlePointerUp)}cleanupDrag(){this.cachedHostRect=null,this.cachedTrackRect=null,typeof window<"u"&&(window.removeEventListener("pointermove",this.handlePointerMove),window.removeEventListener("pointerup",this.handlePointerUp),window.removeEventListener("pointercancel",this.handlePointerUp))}dispatchSeek(e,t){this.dispatchEvent(new CustomEvent("player-seek",{detail:{time:e,isFinal:t},bubbles:!0,composed:!0}))}handlePointerEnter(){const{isInteractive:e}=this.getTimelineRange();e&&(this.isHovered=!0,this.isPointerInside=!0)}handlePointerLeave(){this.isPointerInside=!1,this.cachedHostRect=null,this.cachedTrackRect=null,!this.isDragging&&(this.isHovered=!1,this.clearThumbnailHoverState())}clearThumbnailHoverState(){this.activeThumbnail=null,this.lastSuccessfulThumbnail=null,this.activeMarkerLabel="",this.isThumbnailLoading=!1,this.hoverThrottleTimer&&(clearTimeout(this.hoverThrottleTimer),this.hoverThrottleTimer=void 0),this.pendingHoverClientX=null}handleHoverPointerMove(e){if(this.isDragging)return;this.lastClientX=e.clientX,this.computeTooltipPosition(e.clientX);const{isInteractive:t}=this.getTimelineRange();if(t){const i=this.getTimeFromEvent(e);this.hoverTime=i,this.computeActiveMarker(i)}this.pendingHoverClientX=e.clientX,this.hoverThrottleTimer||(this.hoverThrottleTimer=window.setTimeout(()=>{this.hoverThrottleTimer=void 0,this.pendingHoverClientX!==null&&(this.updateTooltipPosition(this.pendingHoverClientX),this.pendingHoverClientX=null)},60))}computeTooltipPosition(e){var x;const{hostRect:t,trackRect:i}=this.getInteractiveRects();if(!i||!t)return;const s=(e-i.left)/i.width,r=Math.max(0,Math.min(s,1)),{isInteractive:a}=this.getTimelineRange();if(!a)return;const n=i.left-t.left+r*i.width,l=(x=this.renderRoot)==null?void 0:x.querySelector(".hover-tooltip");let o=0;if(l)if(l.offsetWidth>0)o=l.offsetWidth;else{const A=l.getBoundingClientRect();A.width>0&&(o=A.width)}const d=!!this.activeThumbnail||this.isThumbnailLoading;if(o===0){const A=d?this.variant==="vertical"?94:204:50;o=window.innerWidth<=480?A*.85:A}const h=o/2;let u=this.player||null;if(!u){const A=this.getRootNode();A instanceof ShadowRoot&&A.host&&(u=A.host)}u||(u=this.parentElement||this.offsetParent);let f=0,p=t.width;if(u){const A=u.getBoundingClientRect();A.width>0&&(f=Math.min(0,A.left-t.left),p=Math.max(t.width,A.right-t.left))}if(typeof window<"u"){const A=-t.left,O=window.innerWidth-t.left;f=Math.max(f,A),p=Math.min(p,O)}const g=3,m=f+h+g,v=p-h-g;this.tooltipLeft=Math.max(m,Math.min(n,v));const y=n-this.tooltipLeft,T=(d?12:4)+Math.ceil(6/2),E=Math.max(0,h-T);this.caretOffset=Math.max(-E,Math.min(y,E))}updated(e){if(super.updated(e),e.has("activeFilmstripThumbnail")&&this.isPreciseSeeking&&this.activeFilmstripThumbnail!==void 0&&(this.activeFilmstripThumbnail?(this.activeThumbnail=this.activeFilmstripThumbnail,this.lastSuccessfulThumbnail=this.activeFilmstripThumbnail,this.isThumbnailLoading=!1):(this.activeThumbnail=this.lastSuccessfulThumbnail||null,this.isThumbnailLoading=!this.lastSuccessfulThumbnail)),(e.has("activeThumbnail")||e.has("isHovered")||e.has("isThumbnailLoading"))&&(this.isHovered||this.isDragging)&&this.computeTooltipPosition(this.lastClientX),(e.has("seekableRange")||e.has("duration"))&&(this.isHovered||this.isDragging)){const{trackRect:a}=this.getInteractiveRects();if(a){const n=(this.lastClientX-a.left)/a.width,l=Math.max(0,Math.min(n,1)),{start:o,end:d,isInteractive:h}=this.getTimelineRange();if(h){const u=pe.percentToTime(l*100,o,d);this.hoverTime=u,this.isDragging&&(this.dragTime=u,this.dispatchSeek(u,!1)),this.computeActiveMarker(u),this.updateTooltipPosition(this.lastClientX)}}}(e.has("thumbnailProvider")||e.has("currentSource"))&&!(this.thumbnailProvider&&!(typeof this.thumbnailProvider.isUnavailable=="function"&&this.thumbnailProvider.isUnavailable()))&&this.isPreciseSeeking&&(this.isPreciseSeeking=!1,this.dispatchEvent(new CustomEvent("player-precise-seek-change",{detail:{isPreciseSeeking:!1},bubbles:!0,composed:!0})));const{start:t,end:i}=this.getTimelineRange(),s=this.isDragging?this.dragTime:this.currentTime,r=this.isLive?i-t>=3600:i>=3600;this.setAttribute("role","slider"),this.setAttribute("aria-valuemin",Math.round(t).toString()),this.setAttribute("aria-valuemax",Math.round(i).toString()),this.setAttribute("aria-valuenow",Math.round(s).toString()),this.setAttribute("aria-valuetext",ce(s,r))}async updateTooltipPosition(e){var v,y,b,S;this.lastClientX=e;const{trackRect:t}=this.getInteractiveRects();if(!t)return;const i=(e-t.left)/t.width,s=Math.max(0,Math.min(i,1)),{start:r,end:a,range:n,isInteractive:l}=this.getTimelineRange();if(!l){this.activeThumbnail=null;return}let o=pe.percentToTime(s*100,r,a);this.hoverTime=o,this.isDragging&&(this.dragTime=o),this.computeTooltipPosition(e),this.computeActiveMarker(o);const d=s<=.005||s>=.995,h=T=>{var E,x,A,O,M,I;return((x=(E=this.player)==null?void 0:E.controllerInstance)==null?void 0:x.isPreciseSeekEnabled())===!1?!1:T.type==="chapter"?((O=(A=this.player)==null?void 0:A.controllerInstance)==null?void 0:O.shouldSnapToChapters())!==!1:((I=(M=this.player)==null?void 0:M.controllerInstance)==null?void 0:I.shouldSnapToMarkers())!==!1};!d&&this.activeMarker&&h(this.activeMarker)&&(o=this.activeMarker.time,this.hoverTime=o);const u=((y=(v=this.player)==null?void 0:v.controllerInstance)==null?void 0:y.isSmartSeekEnabled())===!1,f=(S=(b=this.player)==null?void 0:b.config)==null?void 0:S.smartSeek,p=u||f&&typeof f=="object"&&f.thumbnails===!1,g=u||f&&typeof f=="object"&&f.storyboard===!1,m=p||g||this.thumbnailProvider&&typeof this.thumbnailProvider.isUnavailable=="function"&&this.thumbnailProvider.isUnavailable();if(!(!this.isHovered&&!this.isDragging))if(this.thumbnailProvider&&!m){if(this.isPreciseSeeking){const E=Math.round(o);let x=this.activeFilmstripThumbnail||null;if(!x&&typeof this.thumbnailProvider.getNearestCachedThumbnail=="function"){const A=this.thumbnailProvider.getNearestCachedThumbnail(E);A&&A.time!==void 0&&Math.abs(A.time-E)<=5&&(x=A)}x?(this.activeThumbnail=x,this.lastSuccessfulThumbnail=x,this.isThumbnailLoading=!1):(this.activeThumbnail=null,this.isThumbnailLoading=!0);return}const T=++this.latestThumbnailRequestId;try{const E=this.thumbnailProvider.getThumbnail(o);if(E instanceof Promise){let x=null;if(typeof this.thumbnailProvider.getNearestCachedThumbnail=="function"){const O=this.thumbnailProvider.getNearestCachedThumbnail(o);if(O&&O.time!==void 0){const M=Math.abs(O.time-o),I=Math.max(15,n*.05);M<=I&&(x=O)}}if(x)this.activeThumbnail=x;else if(this.activeThumbnail&&this.activeThumbnail.time!==void 0){const O=Math.abs(this.activeThumbnail.time-o),M=Math.max(15,n*.05);O>M&&(this.activeThumbnail=null)}else if(this.activeThumbnail=this.lastSuccessfulThumbnail||null,this.activeThumbnail&&this.activeThumbnail.time!==void 0){const O=Math.abs(this.activeThumbnail.time-o),M=Math.max(15,n*.05);O>M&&(this.activeThumbnail=null)}this.isThumbnailLoading=!0;const A=await E.catch(O=>(console.debug("[Seekbar] Exception caught during thumbnail fetch (async):",O),null));T===this.latestThumbnailRequestId&&(this.isHovered||this.isDragging)&&(A?(this.activeThumbnail=A,this.lastSuccessfulThumbnail=A):this.activeThumbnail=this.lastSuccessfulThumbnail||null,this.isThumbnailLoading=!1)}else T===this.latestThumbnailRequestId&&(this.activeThumbnail=E,E&&(this.lastSuccessfulThumbnail=E),this.isThumbnailLoading=!1)}catch(E){console.debug("[Seekbar] Exception caught during thumbnail fetch:",E),T===this.latestThumbnailRequestId&&(this.activeThumbnail=null,this.isThumbnailLoading=!1)}}else this.activeThumbnail=null,this.isThumbnailLoading=!1}handleTimeClick(e){e.stopPropagation(),!(this.hideCurrentTime||this.hideDuration)&&(this.showRemaining=!this.showRemaining)}connectedCallback(){super.connectedCallback(),this.setAttribute("tabindex","0"),this.setAttribute("role","slider"),this.setAttribute("aria-label","Seek timeline progress"),this.addEventListener("keydown",this.handleKeyDown),typeof window<"u"&&window.addEventListener("resize",this.handleWindowResize)}disconnectedCallback(){super.disconnectedCallback(),this.removeEventListener("keydown",this.handleKeyDown),typeof window<"u"&&window.removeEventListener("resize",this.handleWindowResize),this.cleanupDrag(),this.hoverThrottleTimer&&(clearTimeout(this.hoverThrottleTimer),this.hoverThrottleTimer=void 0),this.cachedHostRect=null,this.cachedTrackRect=null}willUpdate(e){if(super.willUpdate(e),e.has("paused"))if(this.paused){const{start:a,range:n}=this.getTimelineRange();n>0?this.frozenPercent=(this.currentTime-a)/n*100:this.frozenPercent=this.isLive?100:0}else this.frozenPercent=null;if(this.paused&&(e.has("currentTime")||e.has("seekableRange"))){const{start:a,range:n}=this.getTimelineRange();this.currentTime<a?this.frozenPercent=0:e.has("currentTime")&&n>0&&(this.frozenPercent=(this.currentTime-a)/n*100)}(e.has("thumbnailProvider")||e.has("currentSource"))&&(this.lastSuccessfulThumbnail=null,this.activeThumbnail=null,this.isThumbnailLoading=!1);const{start:t,end:i,isInteractive:s}=this.getTimelineRange();this.setAttribute("aria-valuemin",Math.round(t).toString()),this.setAttribute("aria-valuemax",Math.round(i).toString());const r=this.isDragging?this.dragTime:this.currentTime;this.setAttribute("aria-valuenow",Math.round(r).toString()),this.setAttribute("aria-valuetext",ce(r,i>=3600)),s?this.removeAttribute("aria-disabled"):this.setAttribute("aria-disabled","true")}handleMarkerClick(e,t){this.isLive&&!this.canSeekInDvr||(e.stopPropagation(),e.preventDefault(),this.dispatchSeek(t.time,!0),this.dispatchEvent(new CustomEvent("player-marker-click",{detail:{marker:t,type:t.type,time:t.time,label:t.label,originalEvent:e},bubbles:!0,composed:!0})))}render(){var O,M,I,D,N,P,C,R,q,te,V,U;const{start:e,end:t,range:i,isInteractive:s}=this.getTimelineRange(),r=this.player?this.player.localize("live","LIVE"):"LIVE",a=this.player?this.player.localize("preciseSeeking","Precise seeking"):"Precise seeking",n=this.player?this.player.localize("pullUpForPreciseSeeking","Pull up for precise seeking"):"Pull up for precise seeking",l=((M=(O=this.player)==null?void 0:O.controllerInstance)==null?void 0:M.isMarkersEnabled())!==!1,o=(D=(I=this.player)==null?void 0:I.config)==null?void 0:D.smartSeek,d=((P=(N=this.player)==null?void 0:N.controllerInstance)==null?void 0:P.isSmartSeekEnabled())!==!1&&(o===void 0||typeof o!="object"||o.hoverTime!==!1),h=l&&!(this.isLive&&!this.canSeekInDvr)&&this.markers?this.markers.filter(L=>{const $=!this.visibleMarkerTypes||this.visibleMarkerTypes.includes(L.type),H=L.time>=e&&L.time<=t;return $&&H}):[],u=((R=(C=this.player)==null?void 0:C.controllerInstance)==null?void 0:R.isSmoothDraggingEnabled())!==!1,f=u?"transition: width 0.05s ease-out;":"",p=u?"transition: left 0.05s ease-out;":"",g=this.isDragging?this.dragTime:this.currentTime,m=this.isLive&&(!this.canSeekInDvr||this.isAtLiveEdge)?100:this.paused&&this.frozenPercent!==null&&!this.isDragging?this.frozenPercent:i>0?pe.timeToPercent(g,e,t):0,v=this.getBufferedPercent(),y=s&&(this.isDragging||this.isHovered||this.isSeeking),b=this.isLive?i>=3600:t>=3600;let S="";const T=this.isDragging?this.dragTime:this.isHovered?this.hoverTime:this.currentTime;if(this.hideCurrentTime&&this.hideDuration)S="";else if(this.hideCurrentTime)S=ce(t,b);else if(this.hideDuration)S=ce(T,b);else if(this.showRemaining){const L=T-t;S=ce(L,b)}else S=ce(T,b);let E="";if(this.activeThumbnail)if(this.variant==="vertical")if(this.activeThumbnail.x!==void 0){const L=this.activeThumbnail.width||200,$=this.activeThumbnail.height||112,H=Math.min(90/L,160/$);E=`
2632
2632
  background-image: url('${this.activeThumbnail.url}');
2633
2633
  background-position: -${this.activeThumbnail.x||0}px -${this.activeThumbnail.y||0}px;
2634
2634
  width: ${L}px;
2635
- height: ${D}px;
2635
+ height: ${$}px;
2636
2636
  background-size: auto;
2637
- transform: translate(-50%, -50%) scale(${q});
2637
+ transform: translate(-50%, -50%) scale(${H});
2638
2638
  position: absolute;
2639
2639
  left: 50%;
2640
2640
  top: 50%;
@@ -2651,7 +2651,7 @@ var StreamitPlayer=function(B){"use strict";/**
2651
2651
  width: ${this.activeThumbnail.x!==void 0?`${this.activeThumbnail.width||200}px`:"100%"};
2652
2652
  height: ${this.activeThumbnail.y!==void 0?`${this.activeThumbnail.height||112}px`:"100%"};
2653
2653
  background-size: ${this.activeThumbnail.x!==void 0?"auto":"cover"};
2654
- `;const A=((te=(H=this.player)==null?void 0:H.config)==null?void 0:te.controls)||{},P=s&&(this.isHovered||this.isDragging)&&i>0&&A.timelinePreview!==!1&&A.hoverTooltip!==!1&&A.tooltip!==!1&&((F=(V=this.player)==null?void 0:V.controllerInstance)==null?void 0:F.isSmartSeekEnabled())!==!1;return k`
2654
+ `;const x=((te=(q=this.player)==null?void 0:q.config)==null?void 0:te.controls)||{},A=s&&(this.isHovered||this.isDragging)&&i>0&&x.timelinePreview!==!1&&x.hoverTooltip!==!1&&x.tooltip!==!1&&((U=(V=this.player)==null?void 0:V.controllerInstance)==null?void 0:U.isSmartSeekEnabled())!==!1;return k`
2655
2655
  <div
2656
2656
  part="seekbar-container"
2657
2657
  class="seekbar-container ${this.variant} ${y?"interactive":""}"
@@ -2662,7 +2662,7 @@ var StreamitPlayer=function(B){"use strict";/**
2662
2662
  >
2663
2663
  <div
2664
2664
  part="hover-tooltip"
2665
- class="hover-tooltip ${P?"visible":""} ${this.activeThumbnail||this.isThumbnailLoading?"has-thumbnail":""}"
2665
+ class="hover-tooltip ${A?"visible":""} ${this.activeThumbnail||this.isThumbnailLoading?"has-thumbnail":""}"
2666
2666
  style="left: ${this.tooltipLeft}px; --caret-left: calc(50% + ${this.caretOffset}px);"
2667
2667
  >
2668
2668
  ${this.isDragging&&this.variant!=="vertical"&&!this.isLive&&this.thumbnailProvider&&!(typeof this.thumbnailProvider.isUnavailable=="function"&&this.thumbnailProvider.isUnavailable())?k`<div class="precise-seek-label">
@@ -2701,11 +2701,11 @@ var StreamitPlayer=function(B){"use strict";/**
2701
2701
  <div part="track" class="track">
2702
2702
  <div part="buffer-bar" class="buffer-bar" style="width: ${v}%"></div>
2703
2703
  <div part="progress-bar" class="progress-bar" style="width: ${m}%; ${f}"></div>
2704
- ${h.map(L=>{const D=pe.timeToPercent(L.time,e,t),q=L.color?`background-color: ${L.color};`:"";return k`
2704
+ ${h.map(L=>{const $=pe.timeToPercent(L.time,e,t),H=L.color?`background-color: ${L.color};`:"";return k`
2705
2705
  <div
2706
2706
  part="marker marker-${L.type||"default"}"
2707
2707
  class="marker ${L.type||""}"
2708
- style="left: ${D}%; ${q}"
2708
+ style="left: ${$}%; ${H}"
2709
2709
  @click=${de=>this.handleMarkerClick(de,L)}
2710
2710
  @pointerdown=${de=>de.stopPropagation()}
2711
2711
  >
@@ -2735,7 +2735,7 @@ var StreamitPlayer=function(B){"use strict";/**
2735
2735
  </div>
2736
2736
  `}
2737
2737
  </div>
2738
- `}};ii.styles=Rr;let Y=ii;if(J([O({type:Number})],Y.prototype,"currentTime"),J([O({type:Number})],Y.prototype,"duration"),J([O({type:Array})],Y.prototype,"bufferedRanges"),J([O({type:Boolean})],Y.prototype,"isSeeking"),J([O({type:Boolean})],Y.prototype,"isLive"),J([O({type:Object})],Y.prototype,"seekableRange"),J([O({attribute:!1})],Y.prototype,"thumbnailProvider"),J([O({attribute:!1})],Y.prototype,"player"),J([O({type:String})],Y.prototype,"currentSource"),J([O({type:String,reflect:!0})],Y.prototype,"variant"),J([O({type:Array})],Y.prototype,"markers"),J([O({type:Array})],Y.prototype,"visibleMarkerTypes"),J([O({type:Array})],Y.prototype,"chapters"),J([O({type:Boolean})],Y.prototype,"canSeekInDvr"),J([O({type:Boolean})],Y.prototype,"isAtLiveEdge"),J([O({type:Boolean})],Y.prototype,"paused"),J([O({type:Boolean})],Y.prototype,"hideCurrentTime"),J([O({type:Boolean})],Y.prototype,"hideDuration"),J([O({type:Boolean})],Y.prototype,"isAdPlaying"),J([O({type:Object})],Y.prototype,"activeFilmstripThumbnail"),J([j()],Y.prototype,"frozenPercent"),J([j()],Y.prototype,"isDragging"),J([j()],Y.prototype,"dragTime"),J([j()],Y.prototype,"isHovered"),J([j()],Y.prototype,"hoverTime"),J([j()],Y.prototype,"isPreciseSeeking"),J([j()],Y.prototype,"tooltipLeft"),J([j()],Y.prototype,"showRemaining"),J([j()],Y.prototype,"activeThumbnail"),J([j()],Y.prototype,"isThumbnailLoading"),J([j()],Y.prototype,"caretOffset"),J([j()],Y.prototype,"activeMarker"),J([j()],Y.prototype,"activeMarkerLabel"),J([j()],Y.prototype,"frozenTimelineRange"),typeof window<"u"&&typeof customElements<"u"&&(customElements.get("streamit-seekbar")||customElements.define("streamit-seekbar",Y),!customElements.get("player-seekbar"))){class c extends Y{}customElements.define("player-seekbar",c)}const $r=Ae`
2738
+ `}};ii.styles=Rr;let Y=ii;if(J([F({type:Number})],Y.prototype,"currentTime"),J([F({type:Number})],Y.prototype,"duration"),J([F({type:Array})],Y.prototype,"bufferedRanges"),J([F({type:Boolean})],Y.prototype,"isSeeking"),J([F({type:Boolean})],Y.prototype,"isLive"),J([F({type:Object})],Y.prototype,"seekableRange"),J([F({attribute:!1})],Y.prototype,"thumbnailProvider"),J([F({attribute:!1})],Y.prototype,"player"),J([F({type:String})],Y.prototype,"currentSource"),J([F({type:String,reflect:!0})],Y.prototype,"variant"),J([F({type:Array})],Y.prototype,"markers"),J([F({type:Array})],Y.prototype,"visibleMarkerTypes"),J([F({type:Array})],Y.prototype,"chapters"),J([F({type:Boolean})],Y.prototype,"canSeekInDvr"),J([F({type:Boolean})],Y.prototype,"isAtLiveEdge"),J([F({type:Boolean})],Y.prototype,"paused"),J([F({type:Boolean})],Y.prototype,"hideCurrentTime"),J([F({type:Boolean})],Y.prototype,"hideDuration"),J([F({type:Boolean})],Y.prototype,"isAdPlaying"),J([F({type:Object})],Y.prototype,"activeFilmstripThumbnail"),J([j()],Y.prototype,"frozenPercent"),J([j()],Y.prototype,"isDragging"),J([j()],Y.prototype,"dragTime"),J([j()],Y.prototype,"isHovered"),J([j()],Y.prototype,"hoverTime"),J([j()],Y.prototype,"isPreciseSeeking"),J([j()],Y.prototype,"tooltipLeft"),J([j()],Y.prototype,"showRemaining"),J([j()],Y.prototype,"activeThumbnail"),J([j()],Y.prototype,"isThumbnailLoading"),J([j()],Y.prototype,"caretOffset"),J([j()],Y.prototype,"activeMarker"),J([j()],Y.prototype,"activeMarkerLabel"),J([j()],Y.prototype,"frozenTimelineRange"),typeof window<"u"&&typeof customElements<"u"&&(customElements.get("streamit-seekbar")||customElements.define("streamit-seekbar",Y),!customElements.get("player-seekbar"))){class c extends Y{}customElements.define("player-seekbar",c)}const $r=Ae`
2739
2739
  :host {
2740
2740
  display: inline-flex;
2741
2741
  align-items: center;
@@ -2949,7 +2949,7 @@ var StreamitPlayer=function(B){"use strict";/**
2949
2949
  ${s}
2950
2950
  </div>
2951
2951
  </div>
2952
- `}};si.styles=$r;let Te=si;if(Zt([O({type:Number})],Te.prototype,"volume"),Zt([O({type:Boolean})],Te.prototype,"muted"),Zt([O({attribute:!1})],Te.prototype,"player"),typeof window<"u"&&typeof customElements<"u"&&(customElements.get("streamit-volume-control")||customElements.define("streamit-volume-control",Te),!customElements.get("player-volume-control"))){class c extends Te{}customElements.define("player-volume-control",c)}const Fr=Ae`
2952
+ `}};si.styles=$r;let Te=si;if(Zt([F({type:Number})],Te.prototype,"volume"),Zt([F({type:Boolean})],Te.prototype,"muted"),Zt([F({attribute:!1})],Te.prototype,"player"),typeof window<"u"&&typeof customElements<"u"&&(customElements.get("streamit-volume-control")||customElements.define("streamit-volume-control",Te),!customElements.get("player-volume-control"))){class c extends Te{}customElements.define("player-volume-control",c)}const Fr=Ae`
2953
2953
  :host {
2954
2954
  display: inline-block;
2955
2955
  position: relative;
@@ -3153,7 +3153,7 @@ var StreamitPlayer=function(B){"use strict";/**
3153
3153
  `)}
3154
3154
  </div>
3155
3155
  </div>
3156
- `}};ri.styles=Fr;let ve=ri;if(nt([O({type:Array})],ve.prototype,"chapters"),nt([O({type:Number})],ve.prototype,"activeChapterIndex"),nt([O({attribute:!1})],ve.prototype,"player"),nt([j()],ve.prototype,"open"),nt([j()],ve.prototype,"lastFocusedButton"),typeof window<"u"&&typeof customElements<"u"&&(customElements.get("streamit-chapters-button")||customElements.define("streamit-chapters-button",ve),!customElements.get("player-chapters-button"))){class c extends ve{}customElements.define("player-chapters-button",c)}const Br=Ae`
3156
+ `}};ri.styles=Fr;let ve=ri;if(nt([F({type:Array})],ve.prototype,"chapters"),nt([F({type:Number})],ve.prototype,"activeChapterIndex"),nt([F({attribute:!1})],ve.prototype,"player"),nt([j()],ve.prototype,"open"),nt([j()],ve.prototype,"lastFocusedButton"),typeof window<"u"&&typeof customElements<"u"&&(customElements.get("streamit-chapters-button")||customElements.define("streamit-chapters-button",ve),!customElements.get("player-chapters-button"))){class c extends ve{}customElements.define("player-chapters-button",c)}const Br=Ae`
3157
3157
  :host {
3158
3158
  display: block;
3159
3159
  position: absolute;
@@ -3565,7 +3565,7 @@ var StreamitPlayer=function(B){"use strict";/**
3565
3565
  </button>
3566
3566
  `;default:if(this.player&&typeof this.player.renderControlOrPlugin=="function"){const h=this.player.renderControlOrPlugin(e);if(h!=="")return k`<div part="rail-btn rail-btn-custom" class="rail-btn custom-rail-btn">
3567
3567
  ${h}
3568
- </div>`}return""}}render(){var u,f,p,g,m,v,y,b,S,T,E,A,P,$,M,I,R,N,U,C,x,H,te,V,F,L,D;const{currentTime:e,duration:t,isPlaying:i,bufferedRanges:s}=this.playerState,r=((p=(f=(u=this.player)==null?void 0:u.config)==null?void 0:f.vertical)==null?void 0:p.railPosition)||"right",l=(((y=(v=(m=(g=this.player)==null?void 0:g.config)==null?void 0:m.controls)==null?void 0:v.groups)==null?void 0:y.rail)||((E=(T=(S=(b=this.player)==null?void 0:b.config)==null?void 0:S.controls)==null?void 0:T.groups)==null?void 0:E.actionRail)||(($=(P=(A=this.player)==null?void 0:A.config)==null?void 0:P.vertical)==null?void 0:$.railButtons)||["prev-btn","next-btn","volume-btn","caption-btn","fullscreen-btn","settings-btn"]).map(q=>q==="play-button"||q==="play"?"play-btn":q==="playlist-prev"||q==="playlist-previous"?"prev-btn":q==="playlist-next"?"next-btn":q==="volume-control"||q==="volume"?"volume-btn":q==="caption-btn"||q==="captions"||q==="subtitles"?"caption-btn":q==="fullscreen-btn"||q==="fullscreen"?"fullscreen-btn":q==="settings-btn"||q==="settings"?"settings-btn":q),o=((R=(I=(M=this.player)==null?void 0:M.config)==null?void 0:I.vertical)==null?void 0:R.showProgressBar)!==!1&&((C=(U=(N=this.player)==null?void 0:N.config)==null?void 0:U.controls)==null?void 0:C.timeline)!==!1&&((te=(H=(x=this.player)==null?void 0:x.config)==null?void 0:H.controls)==null?void 0:te.seekbar)!==!1,d=((L=(F=(V=this.player)==null?void 0:V.config)==null?void 0:F.controls)==null?void 0:L.actionRail)!==!1,h=this.controlsVisible&&!((D=this.playerState)!=null&&D.isAdPlaying);return k`
3568
+ </div>`}return""}}render(){var u,f,p,g,m,v,y,b,S,T,E,x,A,O,M,I,D,N,P,C,R,q,te,V,U,L,$;const{currentTime:e,duration:t,isPlaying:i,bufferedRanges:s}=this.playerState,r=((p=(f=(u=this.player)==null?void 0:u.config)==null?void 0:f.vertical)==null?void 0:p.railPosition)||"right",l=(((y=(v=(m=(g=this.player)==null?void 0:g.config)==null?void 0:m.controls)==null?void 0:v.groups)==null?void 0:y.rail)||((E=(T=(S=(b=this.player)==null?void 0:b.config)==null?void 0:S.controls)==null?void 0:T.groups)==null?void 0:E.actionRail)||((O=(A=(x=this.player)==null?void 0:x.config)==null?void 0:A.vertical)==null?void 0:O.railButtons)||["prev-btn","next-btn","volume-btn","caption-btn","fullscreen-btn","settings-btn"]).map(H=>H==="play-button"||H==="play"?"play-btn":H==="playlist-prev"||H==="playlist-previous"?"prev-btn":H==="playlist-next"?"next-btn":H==="volume-control"||H==="volume"?"volume-btn":H==="caption-btn"||H==="captions"||H==="subtitles"?"caption-btn":H==="fullscreen-btn"||H==="fullscreen"?"fullscreen-btn":H==="settings-btn"||H==="settings"?"settings-btn":H),o=((D=(I=(M=this.player)==null?void 0:M.config)==null?void 0:I.vertical)==null?void 0:D.showProgressBar)!==!1&&((C=(P=(N=this.player)==null?void 0:N.config)==null?void 0:P.controls)==null?void 0:C.timeline)!==!1&&((te=(q=(R=this.player)==null?void 0:R.config)==null?void 0:q.controls)==null?void 0:te.seekbar)!==!1,d=((L=(U=(V=this.player)==null?void 0:V.config)==null?void 0:U.controls)==null?void 0:L.actionRail)!==!1,h=this.controlsVisible&&!(($=this.playerState)!=null&&$.isAdPlaying);return k`
3569
3569
  <div
3570
3570
  part="vertical-controls-container"
3571
3571
  class="vertical-controls-container ${h?"visible":""}"
@@ -3578,7 +3578,7 @@ var StreamitPlayer=function(B){"use strict";/**
3578
3578
  <!-- Top Section Slot -->
3579
3579
  <slot name="top-actions"></slot>
3580
3580
 
3581
- ${l.map(q=>this.renderRailButton(q))}
3581
+ ${l.map(H=>this.renderRailButton(H))}
3582
3582
 
3583
3583
  <!-- Social Actions Slot -->
3584
3584
  <slot name="social-actions"></slot>
@@ -3617,7 +3617,7 @@ var StreamitPlayer=function(B){"use strict";/**
3617
3617
  </div>
3618
3618
  `:""}
3619
3619
  </div>
3620
- `}};ai.styles=Br;let ue=ai;if(ye([O({type:Object})],ue.prototype,"playerState"),ye([O({type:Boolean})],ue.prototype,"controlsVisible"),ye([O({type:Boolean})],ue.prototype,"settingsMenuOpen"),ye([O({type:String})],ue.prototype,"activeMenuScreen"),ye([O({type:Number})],ue.prototype,"pendingSeekTime"),ye([O({type:Boolean})],ue.prototype,"showNavigation"),ye([O({attribute:!1})],ue.prototype,"player"),ye([O({type:Boolean})],ue.prototype,"hideCurrentTime"),ye([O({type:Boolean})],ue.prototype,"hideDuration"),ye([j()],ue.prototype,"isVolumeSliderActive"),typeof window<"u"&&typeof customElements<"u"&&(customElements.get("streamit-vertical-controls")||customElements.define("streamit-vertical-controls",ue),!customElements.get("player-vertical-controls"))){class c extends ue{}customElements.define("player-vertical-controls",c)}const Jt={light:{"--player-primary-color":"#4f46e5","--player-accent-color":"#818cf8","--player-bg-color":"#ffffff","--player-text-color":"#1f2937","--player-glass-bg":"rgba(255, 255, 255, 0.75)","--player-glass-border":"rgba(0, 0, 0, 0.08)","--player-glass-shadow":"0 8px 32px rgba(31, 38, 135, 0.07)","--player-menu-bg":"rgba(255, 255, 255, 0.95)","--player-seekbar-bg":"rgba(0, 0, 0, 0.1)","--player-seekbar-buffer":"rgba(0, 0, 0, 0.15)","--tooltip-bg":"rgba(255, 255, 255, 0.95)","--player-tooltip-color":"#1f2937","--marker-color-default":"#6b7280","--player-primary-glow":"rgba(79, 70, 229, 0.35)","--player-glass-panel":"rgba(255, 255, 255, 0.95)","--player-button-color":"#4b5563","--player-button-hover-color":"#1f2937","--player-button-hover-bg":"rgba(0, 0, 0, 0.05)","--player-volume-played-bg":"#4f46e5","--player-volume-unplayed-bg":"rgba(0, 0, 0, 0.15)","--player-vertical-max-width":"450px","--player-overlay-bg":"#f8fafc","--player-ad-badge-bg":"rgba(15, 23, 42, 0.85)","--player-ad-badge-color":"#ffffff","--player-ad-skip-bg":"rgba(15, 23, 42, 0.9)","--player-ad-skip-color":"#ffffff","--player-ad-skip-disabled-bg":"rgba(15, 23, 42, 0.9)","--player-ad-progress-bg":"rgba(255, 255, 255, 0.2)","--player-ad-progress-fill":"#f59e0b","--player-live-badge-live-bg":"rgba(239, 68, 68, 0.15)","--player-live-badge-live-border":"rgba(239, 68, 68, 0.3)","--player-live-badge-live-color":"#ef4444","--player-live-badge-behind-bg":"rgba(0, 0, 0, 0.05)","--player-live-badge-behind-border":"rgba(0, 0, 0, 0.1)","--player-live-badge-behind-color":"#4b5563","--player-preview-border-color":"#ffffff","--player-preview-border-width":"2px","--player-preview-border-radius":"12px","--player-preview-shadow":"0 10px 25px rgba(0, 0, 0, 0.5)","--player-preview-bg":"#08080c","--player-preview-time-bg":"linear-gradient(to top, rgba(0, 0, 0, 0.55) 0%, rgba(0, 0, 0, 0) 100%)","--player-preview-time-color":"#ffffff","--player-preview-time-font":"var(--player-font-family, 'Outfit', sans-serif)","--player-preview-time-size":"12px","--player-preview-width":"200px","--player-preview-height":"112px","--player-preview-offset":"16px","--player-preview-animation":"opacity var(--player-transition-duration, 0.15s) var(--player-ease-smooth)","--player-preview-opacity":"1","--player-preview-blur":"none","--player-preview-arrow-color":"#ffffff","--player-preview-arrow-size":"6px","--player-preview-arrow-visible":"block","--player-preview-transition":"opacity var(--player-transition-duration, 0.15s) var(--player-ease-smooth)","--player-preview-z-index":"50","--player-preview-padding":"0","--player-preview-spacing":"0","--player-preview-backdrop-filter":"none","--player-preview-vertical-width":"90px","--player-preview-vertical-height":"160px"},dark:{"--player-primary-color":"#6366f1","--player-accent-color":"#818cf8","--player-bg-color":"#0f172a","--player-text-color":"#f8fafc","--player-glass-bg":"rgba(15, 23, 42, 0.65)","--player-glass-border":"rgba(255, 255, 255, 0.08)","--player-glass-shadow":"0 8px 32px rgba(0, 0, 0, 0.3)","--player-menu-bg":"rgba(15, 23, 42, 0.95)","--player-seekbar-bg":"rgba(255, 255, 255, 0.15)","--player-seekbar-buffer":"rgba(255, 255, 255, 0.25)","--tooltip-bg":"rgba(15, 23, 42, 0.95)","--player-tooltip-color":"#f8fafc","--marker-color-default":"#ffffff","--player-primary-glow":"rgba(99, 102, 241, 0.35)","--player-glass-panel":"rgba(15, 23, 42, 0.95)","--player-button-color":"#cbd5e1","--player-button-hover-color":"#ffffff","--player-button-hover-bg":"rgba(255, 255, 255, 0.08)","--player-volume-played-bg":"#6366f1","--player-volume-unplayed-bg":"rgba(255, 255, 255, 0.2)","--player-vertical-max-width":"450px","--player-overlay-bg":"#08080c","--player-ad-badge-bg":"rgba(15, 23, 42, 0.85)","--player-ad-badge-color":"#ffffff","--player-ad-skip-bg":"rgba(15, 23, 42, 0.9)","--player-ad-skip-color":"#ffffff","--player-ad-skip-disabled-bg":"rgba(15, 23, 42, 0.9)","--player-ad-progress-bg":"rgba(255, 255, 255, 0.2)","--player-ad-progress-fill":"#f59e0b","--player-live-badge-live-bg":"rgba(239, 68, 68, 0.15)","--player-live-badge-live-border":"rgba(239, 68, 68, 0.3)","--player-live-badge-live-color":"#ef4444","--player-live-badge-behind-bg":"rgba(255, 255, 255, 0.08)","--player-live-badge-behind-border":"rgba(255, 255, 255, 0.12)","--player-live-badge-behind-color":"#94a3b8","--player-preview-border-color":"#ffffff","--player-preview-border-width":"2px","--player-preview-border-radius":"12px","--player-preview-shadow":"0 10px 25px rgba(0, 0, 0, 0.5)","--player-preview-bg":"#08080c","--player-preview-time-bg":"linear-gradient(to top, rgba(0, 0, 0, 0.55) 0%, rgba(0, 0, 0, 0) 100%)","--player-preview-time-color":"#ffffff","--player-preview-time-font":"var(--player-font-family, 'Outfit', sans-serif)","--player-preview-time-size":"12px","--player-preview-width":"200px","--player-preview-height":"112px","--player-preview-offset":"16px","--player-preview-animation":"opacity var(--player-transition-duration, 0.15s) var(--player-ease-smooth)","--player-preview-opacity":"1","--player-preview-blur":"none","--player-preview-arrow-color":"#ffffff","--player-preview-arrow-size":"6px","--player-preview-arrow-visible":"block","--player-preview-transition":"opacity var(--player-transition-duration, 0.15s) var(--player-ease-smooth)","--player-preview-z-index":"50","--player-preview-padding":"0","--player-preview-spacing":"0","--player-preview-backdrop-filter":"none","--player-preview-vertical-width":"90px","--player-preview-vertical-height":"160px"},"glass-dark":{"--player-primary-color":"#6366f1","--player-accent-color":"#818cf8","--player-bg-color":"transparent","--player-text-color":"#f8fafc","--player-glass-bg":"rgba(8, 8, 12, 0.45)","--player-glass-border":"rgba(255, 255, 255, 0.06)","--player-glass-shadow":"0 20px 50px rgba(0, 0, 0, 0.45)","--player-menu-bg":"rgba(8, 8, 12, 0.85)","--player-seekbar-bg":"rgba(255, 255, 255, 0.15)","--player-seekbar-buffer":"rgba(255, 255, 255, 0.25)","--marker-color-default":"#ffffff","--tooltip-bg":"rgba(8, 8, 12, 0.9)","--player-tooltip-color":"#f8fafc","--player-primary-glow":"rgba(99, 102, 241, 0.35)","--player-glass-panel":"rgba(10, 10, 15, 0.85)","--player-button-color":"#cbd5e1","--player-button-hover-color":"#ffffff","--player-button-hover-bg":"rgba(255, 255, 255, 0.08)","--player-volume-played-bg":"#6366f1","--player-volume-unplayed-bg":"rgba(255, 255, 255, 0.2)","--player-vertical-max-width":"450px","--player-overlay-bg":"#08080c","--player-ad-badge-bg":"rgba(8, 8, 12, 0.85)","--player-ad-badge-color":"#ffffff","--player-ad-skip-bg":"rgba(8, 8, 12, 0.9)","--player-ad-skip-color":"#ffffff","--player-ad-skip-disabled-bg":"rgba(8, 8, 12, 0.9)","--player-ad-progress-bg":"rgba(255, 255, 255, 0.2)","--player-ad-progress-fill":"#f59e0b","--player-live-badge-live-bg":"rgba(239, 68, 68, 0.15)","--player-live-badge-live-border":"rgba(239, 68, 68, 0.3)","--player-live-badge-live-color":"#ef4444","--player-live-badge-behind-bg":"rgba(255, 255, 255, 0.08)","--player-live-badge-behind-border":"rgba(255, 255, 255, 0.12)","--player-live-badge-behind-color":"#94a3b8","--player-preview-border-color":"#ffffff","--player-preview-border-width":"2px","--player-preview-border-radius":"12px","--player-preview-shadow":"0 10px 25px rgba(0, 0, 0, 0.5)","--player-preview-bg":"#08080c","--player-preview-time-bg":"linear-gradient(to top, rgba(0, 0, 0, 0.55) 0%, rgba(0, 0, 0, 0) 100%)","--player-preview-time-color":"#ffffff","--player-preview-time-font":"var(--player-font-family, 'Outfit', sans-serif)","--player-preview-time-size":"12px","--player-preview-width":"200px","--player-preview-height":"112px","--player-preview-offset":"16px","--player-preview-animation":"opacity var(--player-transition-duration, 0.15s) var(--player-ease-smooth)","--player-preview-opacity":"1","--player-preview-blur":"none","--player-preview-arrow-color":"#ffffff","--player-preview-arrow-size":"6px","--player-preview-arrow-visible":"block","--player-preview-transition":"opacity var(--player-transition-duration, 0.15s) var(--player-ease-smooth)","--player-preview-z-index":"50","--player-preview-padding":"0","--player-preview-spacing":"0","--player-preview-backdrop-filter":"none","--player-preview-vertical-width":"90px","--player-preview-vertical-height":"160px"},"glass-light":{"--player-primary-color":"#db2777","--player-accent-color":"#f472b6","--player-bg-color":"transparent","--player-text-color":"#111827","--player-glass-bg":"rgba(255, 255, 255, 0.45)","--player-glass-border":"rgba(0, 0, 0, 0.05)","--player-glass-shadow":"0 20px 50px rgba(0, 0, 0, 0.1)","--player-menu-bg":"rgba(255, 255, 255, 0.85)","--player-seekbar-bg":"rgba(0, 0, 0, 0.1)","--player-seekbar-buffer":"rgba(0, 0, 0, 0.15)","--marker-color-default":"#db2777","--tooltip-bg":"rgba(255, 255, 255, 0.9)","--player-tooltip-color":"#111827","--player-primary-glow":"rgba(219, 39, 119, 0.35)","--player-glass-panel":"rgba(255, 255, 255, 0.85)","--player-button-color":"#4b5563","--player-button-hover-color":"#111827","--player-button-hover-bg":"rgba(0, 0, 0, 0.05)","--player-volume-played-bg":"#db2777","--player-volume-unplayed-bg":"rgba(0, 0, 0, 0.15)","--player-vertical-max-width":"450px","--player-overlay-bg":"#ffffff","--player-ad-badge-bg":"rgba(15, 23, 42, 0.85)","--player-ad-badge-color":"#ffffff","--player-ad-skip-bg":"rgba(15, 23, 42, 0.9)","--player-ad-skip-color":"#ffffff","--player-ad-skip-disabled-bg":"rgba(15, 23, 42, 0.9)","--player-ad-progress-bg":"rgba(255, 255, 255, 0.2)","--player-ad-progress-fill":"#f59e0b","--player-live-badge-live-bg":"rgba(239, 68, 68, 0.15)","--player-live-badge-live-border":"rgba(239, 68, 68, 0.3)","--player-live-badge-live-color":"#ef4444","--player-live-badge-behind-bg":"rgba(0, 0, 0, 0.05)","--player-live-badge-behind-border":"rgba(0, 0, 0, 0.1)","--player-live-badge-behind-color":"#4b5563","--player-preview-border-color":"#ffffff","--player-preview-border-width":"2px","--player-preview-border-radius":"12px","--player-preview-shadow":"0 10px 25px rgba(0, 0, 0, 0.5)","--player-preview-bg":"#08080c","--player-preview-time-bg":"linear-gradient(to top, rgba(0, 0, 0, 0.55) 0%, rgba(0, 0, 0, 0) 100%)","--player-preview-time-color":"#ffffff","--player-preview-time-font":"var(--player-font-family, 'Outfit', sans-serif)","--player-preview-time-size":"12px","--player-preview-width":"200px","--player-preview-height":"112px","--player-preview-offset":"16px","--player-preview-animation":"opacity var(--player-transition-duration, 0.15s) var(--player-ease-smooth)","--player-preview-opacity":"1","--player-preview-blur":"none","--player-preview-arrow-color":"#ffffff","--player-preview-arrow-size":"6px","--player-preview-arrow-visible":"block","--player-preview-transition":"opacity var(--player-transition-duration, 0.15s) var(--player-ease-smooth)","--player-preview-z-index":"50","--player-preview-padding":"0","--player-preview-spacing":"0","--player-preview-backdrop-filter":"none","--player-preview-vertical-width":"90px","--player-preview-vertical-height":"160px"}};function as(c={}){const e=c.preset||"glass-dark",i={...Jt[e]||Jt["glass-dark"]};if(c.primaryColor&&(i["--player-primary-color"]=c.primaryColor),c.accentColor&&(i["--player-accent-color"]=c.accentColor),c.backgroundColor&&(i["--player-bg-color"]=c.backgroundColor),c.textColor&&(i["--player-text-color"]=c.textColor),c.menuColor&&(i["--player-menu-bg"]=c.menuColor),c.seekbarBg&&(i["--player-seekbar-bg"]=c.seekbarBg),c.seekbarPlayed&&(i["--player-seekbar-played"]=c.seekbarPlayed),c.seekbarBuffered&&(i["--player-seekbar-buffer"]=c.seekbarBuffered),c.borderRadius&&(i["--player-border-radius"]=c.borderRadius),c.fontFamily&&(i["--player-font-family"]=c.fontFamily),c.fontSize&&(i["--player-cue-font-size"]=c.fontSize),c.blur&&(i["--player-glass-blur"]=c.blur,i["--player-glass-blur-webkit"]=c.blur),c.shadows&&(i["--player-shadow"]=c.shadows),c.spacing&&(i["--player-spacing"]=c.spacing),c.transitions&&(i["--player-transition-duration"]=c.transitions),c.primaryGlow&&(i["--player-primary-glow"]=c.primaryGlow),c.glassBg&&(i["--player-glass-bg"]=c.glassBg),c.glassPanel&&(i["--player-glass-panel"]=c.glassPanel),c.glassBorder&&(i["--player-glass-border"]=c.glassBorder),c.glassShadow&&(i["--player-glass-shadow"]=c.glassShadow),c.menuBg&&(i["--player-menu-bg"]=c.menuBg),c.tooltipBg&&(i["--tooltip-bg"]=c.tooltipBg),c.tooltipColor&&(i["--player-tooltip-color"]=c.tooltipColor),c.buttonColor&&(i["--player-button-color"]=c.buttonColor),c.buttonHoverColor&&(i["--player-button-hover-color"]=c.buttonHoverColor),c.buttonHoverBg&&(i["--player-button-hover-bg"]=c.buttonHoverBg),c.buttonIconSize&&(i["--player-button-icon-size"]=c.buttonIconSize),c.volumePlayedBg&&(i["--player-volume-played-bg"]=c.volumePlayedBg),c.volumeUnplayedBg&&(i["--player-volume-unplayed-bg"]=c.volumeUnplayedBg),c.verticalMaxWidth&&(i["--player-vertical-max-width"]=c.verticalMaxWidth),c.overlayBg&&(i["--player-overlay-bg"]=c.overlayBg),c.liveBadgeLiveBg&&(i["--player-live-badge-live-bg"]=c.liveBadgeLiveBg),c.liveBadgeLiveBorder&&(i["--player-live-badge-live-border"]=c.liveBadgeLiveBorder),c.liveBadgeLiveColor&&(i["--player-live-badge-live-color"]=c.liveBadgeLiveColor),c.liveBadgeBehindBg&&(i["--player-live-badge-behind-bg"]=c.liveBadgeBehindBg),c.liveBadgeBehindBorder&&(i["--player-live-badge-behind-border"]=c.liveBadgeBehindBorder),c.liveBadgeBehindColor&&(i["--player-live-badge-behind-color"]=c.liveBadgeBehindColor),c.previewBorderColor&&(i["--player-preview-border-color"]=c.previewBorderColor),c.previewBorderWidth&&(i["--player-preview-border-width"]=c.previewBorderWidth),c.previewBorderRadius&&(i["--player-preview-border-radius"]=c.previewBorderRadius),c.previewShadow&&(i["--player-preview-shadow"]=c.previewShadow),c.previewBg&&(i["--player-preview-bg"]=c.previewBg),c.previewTimeBg&&(i["--player-preview-time-bg"]=c.previewTimeBg),c.previewTimeColor&&(i["--player-preview-time-color"]=c.previewTimeColor),c.previewTimeFont&&(i["--player-preview-time-font"]=c.previewTimeFont),c.previewTimeSize&&(i["--player-preview-time-size"]=c.previewTimeSize),c.previewWidth&&(i["--player-preview-width"]=c.previewWidth),c.previewHeight&&(i["--player-preview-height"]=c.previewHeight),c.previewOffset&&(i["--player-preview-offset"]=c.previewOffset),c.previewAnimation&&(i["--player-preview-animation"]=c.previewAnimation),c.previewOpacity&&(i["--player-preview-opacity"]=c.previewOpacity),c.previewBlur&&(i["--player-preview-blur"]=c.previewBlur),c.previewArrowColor&&(i["--player-preview-arrow-color"]=c.previewArrowColor),c.previewArrowSize&&(i["--player-preview-arrow-size"]=c.previewArrowSize),c.previewArrowVisible&&(i["--player-preview-arrow-visible"]=c.previewArrowVisible),c.previewTransition&&(i["--player-preview-transition"]=c.previewTransition),c.previewZIndex&&(i["--player-preview-z-index"]=c.previewZIndex),c.previewPadding&&(i["--player-preview-padding"]=c.previewPadding),c.previewSpacing&&(i["--player-preview-spacing"]=c.previewSpacing),c.previewBackdropFilter&&(i["--player-preview-backdrop-filter"]=c.previewBackdropFilter),c.previewVerticalWidth&&(i["--player-preview-vertical-width"]=c.previewVerticalWidth),c.previewVerticalHeight&&(i["--player-preview-vertical-height"]=c.previewVerticalHeight),c.customVariables)for(const[s,r]of Object.entries(c.customVariables))typeof r=="string"&&(i[s]=r);return i}class Vr{constructor(e){this.providers=new Map,this.mainProvider=null,this.pendingTasks=[],this.activeIdleCallbackId=null,this.host=e}getProvider(e){return this.providers.get(e)}setProviderForSource(e,t){this.providers.set(e,t)}getMainProvider(){return this.mainProvider}setMainProvider(e){this.mainProvider=e}getCachedPosterForSource(e){if(!e)return null;const t=this.providers.get(e);if(!t)return null;if(typeof t.getNearestCachedThumbnail=="function"){const i=t.getNearestCachedThumbnail(0);if(i&&i.url&&Math.abs((i.time||0)-0)<1)return i.url}if(typeof t.getThumbnail=="function"){const i=t.getThumbnail(0,"low");if(i&&!(i instanceof Promise)&&i.url)return i.url}if(t.video instanceof HTMLVideoElement&&t.video.readyState>=2)try{const i=document.createElement("canvas");i.width=t.video.videoWidth||320,i.height=t.video.videoHeight||180;const s=i.getContext("2d");if(s)return s.drawImage(t.video,0,0,i.width,i.height),i.toDataURL("image/jpeg",.8)}catch(i){console.warn("Failed to draw hidden video frame for fallback poster:",i)}return null}cancelPendingPreloads(){this.activeIdleCallbackId!==null&&(typeof window.cancelIdleCallback=="function"?window.cancelIdleCallback(this.activeIdleCallbackId):window.clearTimeout(this.activeIdleCallbackId),this.activeIdleCallbackId=null),this.pendingTasks=[]}trigger(){this.cancelPendingPreloads();const e=this.host.playerState;if(this.host.isVisualTransitioning||!e||e.status==="idle"||e.status==="loading")return;const t=this.host.controller;if(!t)return;const i=t.getThumbnailProvider();if(!i)return;if(this.mainProvider=i,!e.playlist||e.playlist.length<=1){const f=e.currentSource;for(const[p,g]of this.providers.entries())p!==f&&(this.destroyProvider(g,i,"unused provider"),this.providers.delete(p));return}const s=(e.activePlaylistIndex+1)%e.playlist.length,r=(e.activePlaylistIndex-1+e.playlist.length)%e.playlist.length,a=e.playlist[s],n=e.playlist[r],l=e.currentSource,o=(a==null?void 0:a.src)||"",d=(n==null?void 0:n.src)||"",h=new Set;l&&h.add(l),o&&h.add(o),d&&h.add(d);for(const[f,p]of this.providers.entries())h.has(f)||(this.destroyProvider(p,i,"evicted provider"),this.providers.delete(f));l&&!this.providers.has(l)&&this.providers.set(l,i);const u=[];o&&o!==l&&u.push({source:a,url:o}),d&&d!==l&&d!==o&&u.push({source:n,url:d});for(const f of u){let p=this.providers.get(f.url);if(!p)try{const g=i.constructor;p=new g,typeof p.setSource=="function"&&p.setSource(f.url),this.providers.set(f.url,p)}catch(g){console.debug("[Player] Failed to instantiate thumbnail provider for preload:",g);continue}if(f.source.chapters&&f.source.chapters.length>0)for(const g of f.source.chapters)this.pendingTasks.push({provider:p,time:g.startTime,source:f.source,isInitial:!1});this.pendingTasks.push({provider:p,time:0,source:f.source,isInitial:!0})}this.pendingTasks.length>0&&this.scheduleNextPreloadTask()}destroy(){this.cancelPendingPreloads();for(const e of this.providers.values())this.destroyProvider(e,this.mainProvider,"provider on disconnect");this.providers.clear(),this.mainProvider=null}destroyProvider(e,t,i){if(e!==t&&e&&typeof e.destroy=="function")try{e.destroy()}catch(s){console.debug(`[Player] Error destroying ${i}:`,s)}}scheduleNextPreloadTask(){if(this.activeIdleCallbackId!==null||this.pendingTasks.length===0)return;const e=typeof window.requestIdleCallback=="function"?t=>window.requestIdleCallback(t):t=>window.setTimeout(()=>t(void 0),50);this.activeIdleCallbackId=e(t=>{this.activeIdleCallbackId=null,this.runPreloadTask(t)})}async runPreloadTask(e){const t=()=>typeof(e==null?void 0:e.timeRemaining)=="function"?e.timeRemaining():10;for(;this.pendingTasks.length>0&&(t()>0||e!=null&&e.didTimeout);){const i=this.pendingTasks.shift();if(!i)break;const{provider:s,time:r,source:a,isInitial:n}=i;if(Array.from(this.providers.values()).includes(s))try{const o=s.getThumbnail(r,"low");o instanceof Promise&&await o,n&&this.expandPreloadTasksForProvider(s,a)}catch(o){console.warn("[Player] Error preloading thumbnail:",o)}}this.pendingTasks.length>0&&this.scheduleNextPreloadTask()}expandPreloadTasksForProvider(e,t){if(!t.src||e._preloadedIntervalsAdded)return;e._preloadedIntervalsAdded=!0;const s=new Set,r=e.video;if(r&&r instanceof HTMLVideoElement&&!isNaN(r.duration)&&r.duration>0){const n=r.duration,l=10;for(let o=1;o<l;o++)s.add(Math.round(o/l*n))}else{const n=[10,20,30,45,60,90,120,180,240,300];for(const l of n)s.add(l)}const a=this.pendingTasks.filter(n=>n.provider===e).map(n=>n.time);for(const n of s){const l=typeof e.getNearestCachedThumbnail=="function"?e.getNearestCachedThumbnail(n):null;!(!!l&&Math.abs((l.time||0)-n)<1)&&!a.includes(n)&&this.pendingTasks.push({provider:e,time:n,source:t,isInitial:!1})}}}class zr{constructor(e){this.direction="next",this.abortController=null,this.activeUrl="",this.host=e}setDirection(e){this.direction=e}getDirection(){return this.direction}cancel(e){var t;if(this.abortController){if(e&&this.activeUrl===e)return;const i=(t=this.host.playerState)==null?void 0:t.currentSource;if(i&&this.activeUrl===i){this.abortController=null,this.activeUrl="";return}try{this.abortController.abort()}catch{}this.abortController=null}this.activeUrl=""}trigger(){const e=this.host.playerState;if(!e.playlist||e.playlist.length<=1){this.cancel();return}if(this.host.isVisualTransitioning){const l=this.direction==="next"?(e.activePlaylistIndex+1)%e.playlist.length:(e.activePlaylistIndex-1+e.playlist.length)%e.playlist.length,o=e.playlist[l],d=(o==null?void 0:o.src)||"";this.cancel(d);return}if(!e||e.status==="idle"||e.status==="loading"){this.cancel((e==null?void 0:e.currentSource)||void 0);return}const t=this.direction==="next"?(e.activePlaylistIndex+1)%e.playlist.length:(e.activePlaylistIndex-1+e.playlist.length)%e.playlist.length;if(t===e.activePlaylistIndex){this.cancel();return}const i=e.playlist[t],s=(i==null?void 0:i.src)||"";if(!s){this.cancel();return}if(this.activeUrl===s)return;this.cancel(),this.activeUrl=s,this.abortController=new AbortController;const r=this.abortController.signal;let a=i.type||"unknown";if(a==="unknown"){const l=s.split("?")[0].toLowerCase();l.endsWith(".m3u8")?a="hls":l.endsWith(".mpd")?a="dash":l.endsWith(".webm")?a="webm":l.endsWith(".mov")?a="mov":a="mp4"}(typeof window.requestIdleCallback=="function"?l=>window.requestIdleCallback(l):l=>window.setTimeout(l,50))(()=>{r.aborted||this.execute(s,a,r).catch(l=>{l&&l.name==="AbortError"||console.warn(`[Player] Prefetch uncaught rejection for ${s}:`,l)})})}async execute(e,t,i){try{if(t==="hls"||t==="dash"){const s=await fetch(e,{signal:i,headers:{Accept:"*/*"}}).catch(r=>{if(r&&r.name==="AbortError")return null;throw r});if(!s)return;s.ok||console.warn(`[Player] Manifest prefetch failed for ${t}: "${e}" (status ${s.status})`)}else if(t==="mp4"||t==="webm"||t==="mov"||t==="file")try{const s=await fetch(e,{signal:i}).catch(r=>{if(r&&r.name==="AbortError")return null;throw r});if(!s)return;if(s.ok&&s.body){const r=s.body.getReader();await r.read().catch(a=>{if(a&&a.name==="AbortError")return{done:!0,value:void 0};throw a}),await r.cancel().catch(()=>{})}else s.body?console.warn(`[Player] Cache warming failed for media: "${e}" (status ${s.status})`):console.warn(`[Player] Cache warming skipped for media: "${e}" (readable body not supported)`)}catch(s){if(s instanceof Error&&s.name==="AbortError"||!await fetch(e,{signal:i,mode:"no-cors"}).catch(a=>{if(a&&a.name==="AbortError")return null;throw a}))return}}catch(s){s instanceof Error&&s.name==="AbortError"||console.warn(`[Player] Error during source prefetch for "${e}":`,s)}finally{this.activeUrl===e&&(this.activeUrl="",this.abortController=null)}}}class _r{constructor(e){this.lastFocusedSettingsButton=null,this.open=(t="main")=>{this.host.settingsMenuOpen=!0,this.host.activeMenuScreen=t},this.close=()=>{this.host.settingsMenuOpen=!1},this.goTo=t=>{this.host.activeMenuScreen=t},this.backToMain=()=>{this.host.activeMenuScreen="main"},this.toggle=()=>{this.host.settingsMenuOpen=!this.host.settingsMenuOpen,this.host.activeMenuScreen="main",this.host.handleActivity(),this.host.settingsMenuOpen&&(this.lastFocusedSettingsButton=this.host.getDeepActiveElement(),setTimeout(()=>{var i;const t=(i=this.host.shadowRoot)==null?void 0:i.querySelector(".settings-menu .settings-item");t&&t.focus()},50))},this.handleItemKey=t=>{(t.key==="Enter"||t.key===" ")&&(t.preventDefault(),t.currentTarget.click())},this.host=e}get isOpen(){return this.host.settingsMenuOpen}get activeScreen(){return this.host.activeMenuScreen}getAriaLabel(){switch(this.host.activeMenuScreen){case"speed":return"Playback speed settings";case"quality":return"Video resolution settings";case"audio":return"Audio language settings";case"subtitles":return"Subtitles settings";default:return"Settings options"}}getSettingsButton(){var t,i;let e=(t=this.host.shadowRoot)==null?void 0:t.querySelector(".settings-btn");if(!e){const s=(i=this.host.shadowRoot)==null?void 0:i.querySelector("player-vertical-controls");s&&s.shadowRoot&&(e=s.shadowRoot.querySelector(".settings-btn"))}return e}handleKeyDown(e,t){var i;if(this.host.settingsMenuOpen){if(e.key==="Tab"){this.host.settingsMenuOpen=!1;const r=this.getSettingsButton();return r&&r.focus(),!0}const s=(i=this.host.shadowRoot)==null?void 0:i.querySelector(".settings-menu");if(s){const r=Array.from(s.querySelectorAll(".settings-header, .settings-item"));if(r.length>0){const a=r.findIndex(n=>n===t);if(e.key==="ArrowDown"){e.preventDefault(),e.stopPropagation();const n=a===-1?0:(a+1)%r.length;return r[n].focus(),this.host.handleActivity(),!0}else if(e.key==="ArrowUp"){e.preventDefault(),e.stopPropagation();const n=a===-1?r.length-1:(a-1+r.length)%r.length;return r[n].focus(),this.host.handleActivity(),!0}else if(e.key==="ArrowLeft"&&this.host.activeMenuScreen!=="main"){e.preventDefault(),e.stopPropagation();const n=this.host.activeMenuScreen;return this.backToMain(),setTimeout(()=>{const l=this.host.shadowRoot;if(l){const o=Array.from(l.querySelectorAll(".settings-menu .settings-item")),d=o.find(h=>{var f,p;const u=((p=(f=h.querySelector("span"))==null?void 0:f.textContent)==null?void 0:p.toLowerCase())||"";return n==="speed"?u.includes("speed"):n==="quality"?u.includes("quality"):n==="audio"?u.includes("audio"):n==="subtitles"?u.includes("subtitles"):n==="sleeptimer"?u.includes("sleep"):!1});d?d.focus():o[0]&&o[0].focus()}},50),this.host.handleActivity(),!0}}}}return e.key==="Escape"&&this.host.settingsMenuOpen?(e.preventDefault(),e.stopPropagation(),this.host.settingsMenuOpen=!1,!0):!1}closeIfOutside(e){if(!this.host.settingsMenuOpen)return;e.composedPath().some(s=>s instanceof Element&&(s.classList.contains("settings-menu")||s.classList.contains("settings-btn")))||(this.host.settingsMenuOpen=!1)}onScreenChanged(){this.host.settingsMenuOpen&&setTimeout(()=>{var t;const e=(t=this.host.shadowRoot)==null?void 0:t.querySelector(".settings-menu");if(e){const i=e.querySelector(".settings-header, .settings-item");i&&i.focus()}},50)}onOpenStateChanged(e){e===!0&&!this.host.settingsMenuOpen&&setTimeout(()=>{if(this.lastFocusedSettingsButton&&typeof this.lastFocusedSettingsButton.focus=="function")this.lastFocusedSettingsButton.focus();else{const t=this.getSettingsButton();t&&t.focus()}this.lastFocusedSettingsButton=null},50)}}class Hr{constructor(e){this.gestureState="IDLE",this.gestureStartX=0,this.gestureStartY=0,this.gestureLastTapTime=0,this.gestureSingleTapTimer=null,this.gestureLongPressTimer=null,this.gestureIsRightSide=!1,this.gestureStartVolume=0,this.gestureActiveDrag="NONE",this.gestureStartTimeVal=0,this.gestureLastTouchType=!1,this.isLongPressSpeedActiveInternal=!1,this.preLongPressPlaybackRate=1,this.touchStartY=0,this.touchStartX=0,this.touchDeltaY=0,this.isTouchActive=!1,this.lastFeedTransitionTime=0,this.isTransitionLockedInternal=!1,this.isDragPreviewActive=!1,this.dragPreviewDirection=null,this.dragPreviewCanvasHeight=0,this.dragCanvasEl=null,this.dragPreviewPending=!1,this.isTransitionAnimationFinished=!1,this.handleWheel=t=>{this.host.displayMode!=="vertical"||!this.host.playerState.playlist||this.host.playerState.playlist.length<=1||(t.preventDefault(),!(Math.abs(t.deltaY)<10)&&(t.deltaY>0?this.throttleTransition(()=>this.host.next()):t.deltaY<0&&this.throttleTransition(()=>this.host.previous())))},this.handleVideoTouchStart=t=>{if(t.touches.length>1)return;const i=t.touches[0];this.handleVideoDown(i.clientX,i.clientY,!0,t)},this.handleVideoTouchMove=t=>{if(t.touches.length>1)return;const i=t.touches[0];this.handleVideoMove(i.clientX,i.clientY,!0,t),(this.gestureState==="LONG_PRESS"||this.gestureState==="SWIPE")&&t.cancelable&&t.preventDefault()},this.handleVideoTouchEnd=t=>{const i=t.changedTouches[0];i&&this.handleVideoUp(i.clientX,i.clientY,!0,t),t.cancelable&&t.preventDefault()},this.handleVideoTouchCancel=t=>{this.gestureLongPressTimer&&(clearTimeout(this.gestureLongPressTimer),this.gestureLongPressTimer=null),this.gestureState="IDLE"},this.handleVideoMouseDown=t=>{t.button===0&&this.handleVideoDown(t.clientX,t.clientY,!1,t)},this.handleVideoMouseMove=t=>{this.handleVideoMove(t.clientX,t.clientY,!1,t)},this.handleVideoMouseUp=t=>{t.button===0&&this.handleVideoUp(t.clientX,t.clientY,!1,t)},this.handleVideoMouseLeave=t=>{this.gestureLongPressTimer&&(clearTimeout(this.gestureLongPressTimer),this.gestureLongPressTimer=null),this.gestureState==="LONG_PRESS"&&this.triggerLongPressEnd(t),this.gestureState="IDLE"},this.handleTouchStart=t=>{var a,n,l,o,d;if(this.gestureState==="LONG_PRESS"||this.isLongPressSpeedActiveInternal)return;const i=((l=(n=(a=this.host.config)==null?void 0:a.vertical)==null?void 0:n.gestures)==null?void 0:l.swipeToNavigate)!==!1,s=((d=(o=this.host.config)==null?void 0:o.vertical)==null?void 0:d.snapBehavior)!=="none";if(this.host.displayMode!=="vertical"||!i||!s||!this.host.playerState.playlist||this.host.playerState.playlist.length<=1||this.isTouchOnInteractiveElement(t))return;const r=t.touches[0];this.touchStartY=r.clientY,this.touchStartX=r.clientX,this.touchDeltaY=0,this.isTouchActive=!0,this.host.handleActivity()},this.handleTouchMove=t=>{var o,d,h,u,f;if(this.gestureState==="LONG_PRESS"||this.isLongPressSpeedActiveInternal){t.cancelable&&t.preventDefault();return}const i=((h=(d=(o=this.host.config)==null?void 0:o.vertical)==null?void 0:d.gestures)==null?void 0:h.swipeToNavigate)!==!1,s=((f=(u=this.host.config)==null?void 0:u.vertical)==null?void 0:f.snapBehavior)!=="none";if(this.host.displayMode!=="vertical"||!i||!s||!this.host.playerState.playlist||this.host.playerState.playlist.length<=1||this.isTouchOnInteractiveElement(t))return;const r=t.touches[0],a=r.clientY-this.touchStartY,n=r.clientX-this.touchStartX;this.touchDeltaY=a;const l=Math.abs(a)>Math.abs(n)&&Math.abs(a)>5;l&&t.cancelable&&t.preventDefault(),this.isDragPreviewActive?this.updateDragPreview(a):l&&Math.abs(a)>10&&!this.isTransitionLockedInternal&&this.beginDragPreview(a<0?"next":"prev"),this.host.handleActivity()},this.handleTouchEnd=()=>{var l,o,d,h,u,f,p;if(this.gestureState==="LONG_PRESS"||this.isLongPressSpeedActiveInternal)return;const t=((d=(o=(l=this.host.config)==null?void 0:l.vertical)==null?void 0:o.gestures)==null?void 0:d.swipeToNavigate)!==!1,i=((u=(h=this.host.config)==null?void 0:h.vertical)==null?void 0:u.snapBehavior)!=="none";if(this.host.displayMode!=="vertical"||!t||!i||!this.host.playerState.playlist||this.host.playerState.playlist.length<=1)return;const s=((p=(f=this.host.config)==null?void 0:f.vertical)==null?void 0:p.swipeThreshold)??50,r=this.touchDeltaY,a=r<-s,n=r>s;if(this.isDragPreviewActive){const g=this.dragPreviewDirection;g==="next"&&a?(this.lastFeedTransitionTime=Date.now(),this.completeDragPreview("next")):g==="prev"&&n?(this.lastFeedTransitionTime=Date.now(),this.completeDragPreview("prev")):this.cancelDragPreview()}else a?this.throttleTransition(()=>this.host.next()):n&&this.throttleTransition(()=>this.host.previous());this.touchStartY=0,this.touchStartX=0,this.touchDeltaY=0,this.isTouchActive=!1},this.host=e}get isLongPressSpeedActive(){return this.isLongPressSpeedActiveInternal}get isTransitionLocked(){return this.isTransitionLockedInternal}attach(){const e=this.host;e.addEventListener("wheel",this.handleWheel,{passive:!1});const t=e.videoElement;t&&(t.addEventListener("mousedown",this.handleVideoMouseDown),t.addEventListener("mousemove",this.handleVideoMouseMove),t.addEventListener("mouseup",this.handleVideoMouseUp),t.addEventListener("mouseleave",this.handleVideoMouseLeave),t.addEventListener("touchstart",this.handleVideoTouchStart,{passive:!1}),t.addEventListener("touchmove",this.handleVideoTouchMove,{passive:!1}),t.addEventListener("touchend",this.handleVideoTouchEnd,{passive:!1}),t.addEventListener("touchcancel",this.handleVideoTouchCancel,{passive:!1})),e.addEventListener("touchstart",this.handleTouchStart,{passive:!1}),e.addEventListener("touchmove",this.handleTouchMove,{passive:!1}),e.addEventListener("touchend",this.handleTouchEnd,{passive:!0})}detach(){const e=this.host;e.removeEventListener("wheel",this.handleWheel),e.removeEventListener("touchstart",this.handleTouchStart),e.removeEventListener("touchmove",this.handleTouchMove),e.removeEventListener("touchend",this.handleTouchEnd);const t=e.videoElement;t&&(t.removeEventListener("mousedown",this.handleVideoMouseDown),t.removeEventListener("mousemove",this.handleVideoMouseMove),t.removeEventListener("mouseup",this.handleVideoMouseUp),t.removeEventListener("mouseleave",this.handleVideoMouseLeave),t.removeEventListener("touchstart",this.handleVideoTouchStart),t.removeEventListener("touchmove",this.handleVideoTouchMove),t.removeEventListener("touchend",this.handleVideoTouchEnd),t.removeEventListener("touchcancel",this.handleVideoTouchCancel)),this.gestureSingleTapTimer&&(clearTimeout(this.gestureSingleTapTimer),this.gestureSingleTapTimer=null),this.gestureLongPressTimer&&(clearTimeout(this.gestureLongPressTimer),this.gestureLongPressTimer=null)}drawFrame(e,t,i,s,r){let a=0,n=0;if(t instanceof HTMLVideoElement?(a=t.videoWidth,n=t.videoHeight):t instanceof HTMLImageElement&&(a=t.naturalWidth,n=t.naturalHeight),a===0||n===0){e.fillStyle="#000000",e.fillRect(0,i,s,r);return}const l=a/n,o=s/r;let d=s,h=r,u=0,f=i;l>o?(h=s/l,f=i+(r-h)/2):(d=r*l,u=(s-d)/2),e.fillStyle="#000000",e.fillRect(0,i,s,r),e.drawImage(t,u,f,d,h)}prepareTransitionFrames(e){var p,g,m;const t=this.host.videoElement;if(!t)return null;const i=(p=this.host.shadowRoot)==null?void 0:p.querySelector(".transition-canvas");if(!i)return null;const s=((m=(g=this.host.shadowRoot)==null?void 0:g.querySelector(".video-wrapper"))==null?void 0:m.getBoundingClientRect())||t.getBoundingClientRect(),r=Math.round(s.width)||360,a=Math.round(s.height)||640;(i.width!==r||i.height!==a*2)&&(i.width=r,i.height=a*2);const n=i.getContext("2d"),l=e==="next"?0:a,o=e==="next"?a:0;n&&(t.readyState>=2?this.drawFrame(n,t,l,r,a):(n.fillStyle="#000000",n.fillRect(0,l,r,a)));let d="";if(this.host.playerState.playlist&&this.host.playerState.playlist.length>1){const v=e==="next"?(this.host.playerState.activePlaylistIndex+1)%this.host.playerState.playlist.length:(this.host.playerState.activePlaylistIndex-1+this.host.playerState.playlist.length)%this.host.playerState.playlist.length,y=this.host.playerState.playlist[v];d=(y==null?void 0:y.src)||""}const h=this.host.thumbnailCache.getProvider(d),u=h==null?void 0:h.video,f=this.host.thumbnailCache.getCachedPosterForSource(d);if(f&&this.host.isOverlayEnabled("poster")?t.setAttribute("poster",f):t.removeAttribute("poster"),n){const v=y=>{try{this.drawFrame(n,y,o,r,a)}catch(b){console.warn("Failed to draw incoming frame onto canvas:",b)}};if(u&&u.readyState>=2)v(u);else if(f){const y=new Image;y.onload=()=>{v(y)},y.src=f,y.complete?v(y):(n.fillStyle="#000000",n.fillRect(0,o,r,a))}else n.fillStyle="#000000",n.fillRect(0,o,r,a)}return{domCanvas:i,canvasHeight:a}}initiateVisualTransition(e,t){if(this.host.displayMode!=="vertical"){t();return}if(!this.host.videoElement){t();return}const i=this.prepareTransitionFrames(e);if(!i){t();return}const{domCanvas:s}=i;this.isTransitionLockedInternal=!0;const r=this.host.playerState.isPlaying||this.host.playerState.status==="ended";this.host.shouldAutoplayAfterTransition=r,this.host.suppressPlayPauseFeedback=r,this.host.transitionDirection=e,this.host.isVisualTransitioning=!0,this.host.transitionStage="start",this.isTransitionAnimationFinished=!1,this.host.updateComplete.then(()=>{const a=l=>{l.propertyName==="transform"&&l.target===s&&(s.removeEventListener("transitionend",a),this.onTransitionAnimationEnd())},n=setTimeout(()=>{s.removeEventListener("transitionend",a),this.onTransitionAnimationEnd()},700);s.addEventListener("transitionend",a),this.cleanupTransitionListeners=()=>{clearTimeout(n),s.removeEventListener("transitionend",a)},requestAnimationFrame(()=>{requestAnimationFrame(()=>{this.host.transitionStage="active",t()})})})}onTransitionAnimationEnd(){this.isTransitionAnimationFinished=!0,this.checkTransitionCompletion()}checkTransitionCompletion(){var a,n;if(!this.isTransitionAnimationFinished)return;const e=this.host.videoElement;if(!e){this.endVisualTransition();return}const t=(a=this.host.playerState)==null?void 0:a.status,i=(n=this.host.playerState)==null?void 0:n.sourceType,s=e.error||t==="error";if(e.readyState>=2||s||t==="idle"||i==="embed")this.endVisualTransition();else{const l=()=>{e.removeEventListener("loadeddata",l),e.removeEventListener("playing",l),e.removeEventListener("canplay",l),e.removeEventListener("error",l),e.removeEventListener("emptied",l),this.checkTransitionCompletion()};e.addEventListener("loadeddata",l),e.addEventListener("playing",l),e.addEventListener("canplay",l),e.addEventListener("error",l),e.addEventListener("emptied",l),this.cleanupReadyListener=()=>{e.removeEventListener("loadeddata",l),e.removeEventListener("playing",l),e.removeEventListener("canplay",l),e.removeEventListener("error",l),e.removeEventListener("emptied",l)}}}endVisualTransition(){var t;this.cleanupTransitionListeners&&(this.cleanupTransitionListeners(),this.cleanupTransitionListeners=void 0),this.cleanupReadyListener&&(this.cleanupReadyListener(),this.cleanupReadyListener=void 0),this.isTransitionAnimationFinished=!1,this.host.isVisualTransitioning=!1,this.host.transitionStage="idle",this.isTransitionLockedInternal=!1,this.isDragPreviewActive=!1,this.dragPreviewDirection=null;const e=this.dragCanvasEl||((t=this.host.shadowRoot)==null?void 0:t.querySelector(".transition-canvas"));e&&(e.style.transform="",e.style.transition=""),this.dragCanvasEl=null,this.host.videoElement&&this.host.videoElement.removeAttribute("poster"),this.host.shouldAutoplayAfterTransition&&(this.host.controller&&this.host.controller.play(),setTimeout(()=>{this.host.shouldAutoplayAfterTransition=!1,this.host.requestUpdate()},150)),this.host.thumbnailCache.trigger(),this.host.prefetch.trigger()}throttleTransition(e){const t=Date.now();t-this.lastFeedTransitionTime>=800&&(this.lastFeedTransitionTime=t,e())}beginDragPreview(e){if(this.isTransitionLockedInternal||this.isDragPreviewActive||this.dragPreviewPending||this.host.displayMode!=="vertical"||!this.host.videoElement||!this.host.playerState.playlist||this.host.playerState.playlist.length<=1)return;this.dragPreviewPending=!0;const t=this.host.playerState.isPlaying||this.host.playerState.status==="ended";this.host.shouldAutoplayAfterTransition=t,this.host.suppressPlayPauseFeedback=t,this.host.transitionDirection=e,this.host.isVisualTransitioning=!0,this.host.transitionStage="idle",this.host.updateComplete.then(()=>{if(this.dragPreviewPending=!1,!this.isTouchActive){this.host.isVisualTransitioning=!1;return}const i=this.prepareTransitionFrames(e);if(!i){this.host.isVisualTransitioning=!1;return}this.dragCanvasEl=i.domCanvas,this.dragPreviewCanvasHeight=i.canvasHeight,this.dragPreviewDirection=e,this.isDragPreviewActive=!0,this.dragCanvasEl.style.transition="none",this.updateDragPreview(this.touchDeltaY)})}updateDragPreview(e){if(!this.isDragPreviewActive||!this.dragCanvasEl||!this.dragPreviewDirection)return;const t=this.dragPreviewCanvasHeight,i=this.dragPreviewDirection==="next"?Math.max(-t,Math.min(0,e)):Math.max(-t,Math.min(0,-t+e));this.dragCanvasEl.style.transform=`translateY(${i}px)`}completeDragPreview(e){const t=this.dragCanvasEl,i=this.dragPreviewCanvasHeight;if(this.isDragPreviewActive=!1,this.dragPreviewDirection=null,!t){this.host.isVisualTransitioning=!1;return}this.isTransitionLockedInternal=!0,this.host.prefetch.setDirection(e),this.isTransitionAnimationFinished=!1;const s=e==="next"?-i:0,r="var(--player-vertical-transition-duration, 0.6s)",a="var(--player-vertical-transition-easing, cubic-bezier(0.16, 1, 0.3, 1))";t.style.transition=`transform ${r} ${a}`,t.offsetHeight,requestAnimationFrame(()=>{t.style.transform=`translateY(${s}px)`}),e==="next"?this.host.controller.next():this.host.controller.previous();const n=o=>{o.propertyName==="transform"&&o.target===t&&(t.removeEventListener("transitionend",n),this.onTransitionAnimationEnd())},l=setTimeout(()=>{t.removeEventListener("transitionend",n),this.onTransitionAnimationEnd()},700);t.addEventListener("transitionend",n),this.cleanupTransitionListeners=()=>{clearTimeout(l),t.removeEventListener("transitionend",n)}}cancelDragPreview(){const e=this.dragCanvasEl;if(this.isDragPreviewActive=!1,this.dragPreviewDirection=null,!e){this.host.isVisualTransitioning=!1;return}const t="var(--player-vertical-transition-duration, 0.6s)",i="var(--player-vertical-transition-easing, cubic-bezier(0.16, 1, 0.3, 1))";e.style.transition=`transform ${t} ${i}`,requestAnimationFrame(()=>{e.style.transform="translateY(0px)"});const s=()=>{e.removeEventListener("transitionend",r),clearTimeout(a),this.host.isVisualTransitioning=!1,this.host.transitionStage="idle",e.style.transform="",e.style.transition="",this.dragCanvasEl=null,this.host.videoElement&&this.host.videoElement.removeAttribute("poster")},r=n=>{n.propertyName==="transform"&&n.target===e&&s()},a=setTimeout(s,300);e.addEventListener("transitionend",r)}handleVideoDown(e,t,i,s){var l,o;if(i&&this.isTouchOnInteractiveElement(s))return;if(this.gestureLastTouchType=i,this.gestureLongPressTimer&&(clearTimeout(this.gestureLongPressTimer),this.gestureLongPressTimer=null),this.gestureState="DOWN",this.gestureStartX=e,this.gestureStartY=t,this.host.videoElement){const d=this.host.videoElement.getBoundingClientRect();this.gestureIsRightSide=e-d.left>d.width/2}else this.gestureIsRightSide=!1;this.gestureStartVolume=this.host.playerState.volume||0,this.gestureStartTimeVal=this.host.playerState.currentTime||0,this.gestureActiveDrag="NONE";const r=(o=(l=this.host.config)==null?void 0:l.vertical)==null?void 0:o.gestures,a=this.host.displayMode==="vertical";((r==null?void 0:r.longPressToSpeed)??a)&&!this.host.playerState.isLive&&(this.gestureLongPressTimer=window.setTimeout(()=>{if(this.gestureState="LONG_PRESS",this.isLongPressSpeedActiveInternal=!0,this.host.isSpeedOverlayFadingOut=!1,this.host.speedLockState==="LOCKED")this.host.speedLockState="LOCKED_HOLDING",this.host.activeSpeedFeedback=this.host.playerState.playbackRate||2,this.host.requestUpdate();else{this.preLongPressPlaybackRate=this.host.playerState.playbackRate||1;const d=(r==null?void 0:r.longPressSpeed)||2;this.host.controller.setPlaybackRate(d),this.host.speedLockState="HOLDING",this.host.activeSpeedFeedback=d,this.host.requestUpdate()}},500))}handleVideoMove(e,t,i,s){const r=e-this.gestureStartX,a=t-this.gestureStartY;if(this.gestureState==="DOWN"&&Math.hypot(r,a)>10)if(Math.abs(r)>Math.abs(a))this.gestureState="SWIPE",this.gestureActiveDrag="HORIZONTAL",this.gestureLongPressTimer&&(clearTimeout(this.gestureLongPressTimer),this.gestureLongPressTimer=null);else if(this.host.displayMode==="vertical"){this.gestureState="IDLE",this.gestureActiveDrag="NONE",this.gestureLongPressTimer&&(clearTimeout(this.gestureLongPressTimer),this.gestureLongPressTimer=null);return}else this.gestureState="SWIPE",this.gestureActiveDrag="VERTICAL",this.gestureLongPressTimer&&(clearTimeout(this.gestureLongPressTimer),this.gestureLongPressTimer=null);if(this.gestureState==="SWIPE"){if(this.gestureActiveDrag==="HORIZONTAL"){if(this.host.videoElement&&this.host.playerState.duration>0&&!this.host.playerState.isLive){const n=this.host.videoElement.getBoundingClientRect(),l=r/n.width,o=Math.min(90,this.host.playerState.duration),d=l*o,h=Math.max(0,Math.min(this.host.playerState.duration,this.gestureStartTimeVal+d));this.host.controller.seek(h),this.host.handleActivity()}}else if(this.gestureActiveDrag==="VERTICAL")if(this.gestureIsRightSide){if(this.host.videoElement){const n=this.host.videoElement.getBoundingClientRect(),l=-(a/n.height),o=Math.max(0,Math.min(1,this.gestureStartVolume+l));this.host.controller.setVolume(o),this.host.handleActivity()}}else this.host.handleActivity()}else this.gestureState==="LONG_PRESS"&&(this.host.speedLockState==="HOLDING"?a>40&&(this.host.speedLockState="READY_TO_LOCK",this.host.requestUpdate()):this.host.speedLockState==="READY_TO_LOCK"?a<=40&&(this.host.speedLockState="HOLDING",this.host.requestUpdate()):this.host.speedLockState==="LOCKED_HOLDING"?a>40&&(this.host.speedLockState="READY_TO_UNLOCK",this.host.requestUpdate()):this.host.speedLockState==="READY_TO_UNLOCK"&&a<=40&&(this.host.speedLockState="LOCKED_HOLDING",this.host.requestUpdate()))}handleVideoUp(e,t,i,s){this.gestureLongPressTimer&&(clearTimeout(this.gestureLongPressTimer),this.gestureLongPressTimer=null);const r=this.gestureState;if(this.gestureState="IDLE",r==="LONG_PRESS")this.triggerLongPressEnd(s);else if(r==="SWIPE")this.host.handleActivity();else if(r==="DOWN"){const a=Date.now(),n=a-this.gestureLastTapTime;n<300&&n>0?(this.gestureSingleTapTimer&&(clearTimeout(this.gestureSingleTapTimer),this.gestureSingleTapTimer=null),this.gestureLastTapTime=0,this.triggerDoubleTap(e,s)):(this.gestureLastTapTime=a,this.gestureSingleTapTimer=window.setTimeout(()=>{this.gestureSingleTapTimer=null,this.triggerSingleTap()},250))}}triggerLongPressEnd(e){var t,i;this.isLongPressSpeedActiveInternal&&((i=(t=this.host.config)==null?void 0:t.vertical)==null||i.gestures,this.host.speedLockState==="HOLDING"?(this.host.controller.setPlaybackRate(this.preLongPressPlaybackRate),this.host.isSpeedOverlayFadingOut=!0,this.host.requestUpdate(),this.host.speedFeedbackTimer&&clearTimeout(this.host.speedFeedbackTimer),this.host.speedFeedbackTimer=window.setTimeout(()=>{this.host.activeSpeedFeedback=null,this.host.speedLockState="IDLE",this.host.isSpeedOverlayFadingOut=!1,this.host.requestUpdate()},250)):this.host.speedLockState==="READY_TO_LOCK"?(this.host.speedLockState="LOCKED",this.host.activeSpeedFeedback=this.host.playerState.playbackRate||2,this.host.isSpeedOverlayFadingOut=!1,this.host.requestUpdate(),this.host.speedFeedbackTimer&&clearTimeout(this.host.speedFeedbackTimer),this.host.speedFeedbackTimer=window.setTimeout(()=>{this.host.isSpeedOverlayFadingOut=!0,this.host.requestUpdate(),this.host.speedFeedbackTimer=window.setTimeout(()=>{this.host.activeSpeedFeedback=null,this.host.isSpeedOverlayFadingOut=!1,this.host.requestUpdate()},250)},1e3)):this.host.speedLockState==="LOCKED_HOLDING"?(this.host.speedLockState="LOCKED",this.host.activeSpeedFeedback=this.host.playerState.playbackRate||2,this.host.isSpeedOverlayFadingOut=!1,this.host.requestUpdate(),this.host.speedFeedbackTimer&&clearTimeout(this.host.speedFeedbackTimer),this.host.speedFeedbackTimer=window.setTimeout(()=>{this.host.isSpeedOverlayFadingOut=!0,this.host.requestUpdate(),this.host.speedFeedbackTimer=window.setTimeout(()=>{this.host.activeSpeedFeedback=null,this.host.isSpeedOverlayFadingOut=!1,this.host.requestUpdate()},250)},1e3)):this.host.speedLockState==="READY_TO_UNLOCK"&&(this.host.controller.setPlaybackRate(this.preLongPressPlaybackRate),this.host.isSpeedOverlayFadingOut=!0,this.host.requestUpdate(),this.host.speedFeedbackTimer&&clearTimeout(this.host.speedFeedbackTimer),this.host.speedFeedbackTimer=window.setTimeout(()=>{this.host.activeSpeedFeedback=null,this.host.speedLockState="IDLE",this.host.isSpeedOverlayFadingOut=!1,this.host.requestUpdate()},250)),setTimeout(()=>{this.isLongPressSpeedActiveInternal=!1,this.host.requestUpdate()},50))}triggerSingleTap(){var e,t,i,s;if(!this.isLongPressSpeedActiveInternal){if(this.host.settingsMenu.isOpen){this.host.settingsMenu.close();return}if(!(((t=(e=this.host.config)==null?void 0:e.controls)==null?void 0:t.play)===!1||((s=(i=this.host.config)==null?void 0:i.controls)==null?void 0:s.playButton)===!1)){if(this.host.playerState.status==="ended"&&!this.host.playerState.isLive&&this.host.displayMode!=="vertical"){this.host.handleReplay();return}this.host.controller.togglePlay(),this.host.handleActivity()}}}triggerDoubleTap(e,t){var l,o,d,h,u,f,p;if(((o=(l=this.host.config)==null?void 0:l.controls)==null?void 0:o.seekbar)===!1||this.host.playerState.isLive&&!this.host.playerState.canSeekInDvr||!(this.host.displayMode==="vertical"?((u=(h=(d=this.host.config)==null?void 0:d.vertical)==null?void 0:h.gestures)==null?void 0:u.doubleTapToSeek)!==!1:!0))return;const r=this.host.videoElement.getBoundingClientRect(),a=e-r.left,n=((p=(f=this.host.config)==null?void 0:f.playback)==null?void 0:p.doubleTapInterval)||10;a<r.width/2?(this.host.controller.seekBy(-n),this.host.showFeedbackOverlay("rewind")):(this.host.controller.seekBy(n),this.host.showFeedbackOverlay("fastforward")),this.host.handleActivity()}isTouchOnInteractiveElement(e){return(typeof e.composedPath=="function"?e.composedPath():[]).some(i=>{if(!(i instanceof Element))return!1;const s=i.tagName.toLowerCase(),r=i.getAttribute?i.getAttribute("role"):null,a=i.classList;return s==="button"||s==="player-seekbar"||s==="player-vertical-controls"||r==="button"||r==="menuitem"||r==="menuitemradio"||a&&(a.contains("controls-bar")||a.contains("settings-menu")||a.contains("settings-menu-wrapper")||a.contains("sleep-timer-dialog-card"))})}}var qr=Object.defineProperty,W=(c,e,t,i)=>{for(var s=void 0,r=c.length-1,a;r>=0;r--)(a=c[r])&&(s=a(e,t,s)||s);return s&&qr(e,t,s),s};const ns=[{value:"default",label:"Default"},{value:"proportional-sans-serif",label:"Proportional Sans-Serif"},{value:"monospace-sans-serif",label:"Monospace Sans-Serif"},{value:"proportional-serif",label:"Proportional Serif"},{value:"monospace-serif",label:"Monospace Serif"},{value:"casual",label:"Casual"},{value:"cursive",label:"Cursive"},{value:"small-capitals",label:"Small Capitals"}],He=[{value:"white",label:"White"},{value:"black",label:"Black"},{value:"red",label:"Red"},{value:"green",label:"Green"},{value:"blue",label:"Blue"},{value:"yellow",label:"Yellow"},{value:"magenta",label:"Magenta"},{value:"cyan",label:"Cyan"}],os=[{value:50,label:"50%"},{value:75,label:"75%"},{value:100,label:"100%"},{value:125,label:"125%"},{value:150,label:"150%"},{value:175,label:"175%"},{value:200,label:"200%"},{value:300,label:"300%"},{value:400,label:"400%"}],qe=[{value:0,label:"0%"},{value:25,label:"25%"},{value:50,label:"50%"},{value:75,label:"75%"},{value:100,label:"100%"}],ls=[{value:"none",label:"None"},{value:"raised",label:"Raised"},{value:"depressed",label:"Depressed"},{value:"uniform",label:"Uniform"},{value:"drop-shadow",label:"Drop Shadow"}],Kr=[.25,.5,.75,1,1.25,1.5,1.75,2,2.5,3,4],Wr=[.5,1,2],ni=class ni extends ge{constructor(){super(...arguments),this.src="",this.captions="",this.autoplay=!1,this.muted=!1,this.volume=1,this.displayMode="standard",this.nearEndThreshold=1,this.autoScroll=!1,this.liveMode="live-dvr",this.preload="metadata",this.loop=!1,this.playsinline=!0,this.poster="",this.isFeedTransitioning=!1,this.iconRegistry=new ss,this.customControls=new Map,this.customOverlays=new Map,this.isVisualTransitioning=!1,this.transitionDirection="next",this.transitionStage="idle",this.shouldAutoplayAfterTransition=!1,this.suppressPlayPauseFeedback=!1,this.contextMenuOpen=!1,this.contextMenuX=0,this.contextMenuY=0,this.isContextMenuDisabled=!1,this.customContextMenuItems=[],this.customSettingsItems=[],this.customSettingsScreens=new Map,this.playerState={status:"idle",isPlaying:!1,currentTime:0,duration:0,volume:1,isMuted:!1,isFullscreen:!1,bufferedRanges:[],playbackRate:1,captionsEnabled:!1,currentSource:null,sourceType:"unknown",isBuffering:!1,isSeeking:!1,hasCaptions:!1,error:null,qualities:[],activeQuality:"Auto",audioTracks:[],activeAudioTrack:-1,subtitleTracks:[],activeSubtitleTrack:-1,activeSubtitleTrackId:null,subtitleAppearance:{fontFamily:"default",fontSize:75,fontColor:"white",backgroundColor:"black",backgroundOpacity:75,windowColor:"black",windowOpacity:0,characterEdgeStyle:"none",fontOpacity:100},isLive:null,isLowLatency:!1,isAtLiveEdge:!1,liveLatency:null,hasDvr:!1,dvrWindow:0,canSeekInDvr:!1,seekableRange:{start:0,end:0},liveMode:"live-dvr",thumbnailProvider:void 0,pictureInPicture:!1,pictureInPictureSupported:!1,loop:!1,sleepTimerSetting:"off",sleepTimerSecondsRemaining:null,sleepTimerExpired:!1,chapters:[],activeChapterIndex:-1,markers:[],visibleMarkerTypes:null,displayMode:"standard",playlist:[],activePlaylistIndex:0,playlistRepeatMode:"off",autoScroll:!1,isAdPlaying:!1,isAdLoading:!1,currentAd:null,currentAdBreak:null,adCurrentTime:null,adRemainingTime:null,adDuration:null,canSkipAd:!1,skipAvailableAt:null,adPosition:null,adProvider:null,adLinear:null,adMuted:null},this.controlsVisible=!0,this.settingsMenuOpen=!1,this.activeMenuScreen="main",this.toastMessage="",this.toastType="info",this.toastVisible=!1,this.lastFocusedElement=null,this.tapFeedback=null,this.feedbackTaps=0,this.playPauseFeedback=null,this.activeVolumeFeedback=null,this.isSeekingInteraction=!1,this.activeSpeedFeedback=null,this.activeQualityFeedback=null,this.shouldShowQualityFeedback=!1,this.pendingSeekTime=null,this.lastTap=0,this.isDraggingSeekbar=!1,this.wasPlayingBeforeDrag=!1,this.isPreciseSeeking=!1,this.filmstripCenterTime=-1,this.speedLockState="IDLE",this.isSpeedOverlayFadingOut=!1,this.isVolumeFeedbackFadingOut=!1,this.filmstripThumbs=new Map,this.preciseSeekContainerWidth=1056,this.thumbnailCache=new Vr(this),this.prefetch=new zr(this),this.settingsMenu=new _r(this),this.gestures=new Hr(this),this.pendingListeners=[],this.handleResize=()=>{var e;if(this.isPreciseSeeking){const t=(e=this.shadowRoot)==null?void 0:e.querySelector(".precise-seek-container");t&&t.clientWidth>0&&this.preciseSeekContainerWidth!==t.clientWidth&&(this.preciseSeekContainerWidth=t.clientWidth,this.requestUpdate())}},this.handleKeyDown=e=>{var i,s;const t=this.getDeepActiveElement();if(this.displayMode==="vertical"&&this.playerState.playlist&&this.playerState.playlist.length>1&&t&&(this===t||((i=this.shadowRoot)==null?void 0:i.contains(t))||this.contains(t))){if(e.key==="ArrowDown"){e.preventDefault(),e.stopPropagation(),this.gestures.throttleTransition(()=>this.next());return}else if(e.key==="ArrowUp"){e.preventDefault(),e.stopPropagation(),this.gestures.throttleTransition(()=>this.previous());return}}if(this.playerState.sleepTimerExpired){const r=(s=this.shadowRoot)==null?void 0:s.querySelector(".sleep-timer-dialog-overlay");if(r){const a=Array.from(r.querySelectorAll(".sleep-timer-btn"));if(a.length>0){const n=a.findIndex(d=>d===t),l=e.key==="ArrowRight"||e.key==="ArrowDown"||e.key==="Tab"&&!e.shiftKey,o=e.key==="ArrowLeft"||e.key==="ArrowUp"||e.key==="Tab"&&e.shiftKey;if(l){e.preventDefault(),e.stopPropagation();const d=n===-1?0:(n+1)%a.length;a[d].focus();return}else if(o){e.preventDefault(),e.stopPropagation();const d=n===-1?a.length-1:(n-1+a.length)%a.length;a[d].focus();return}}}e.key==="Escape"&&(e.preventDefault(),e.stopPropagation(),this.handleSleepTimerClose());return}t&&(t.tagName==="INPUT"||t.tagName==="TEXTAREA"||t.tagName==="SELECT"||t.hasAttribute("contenteditable"))||this.settingsMenu.handleKeyDown(e,t)||e.key===" "&&t&&(t.tagName==="BUTTON"||t.getAttribute("role")==="button")||(this.controller.shortcuts.handleKeyDown(e),this.handleActivity())},this.handleActivity=()=>{var t,i,s;if((t=this.playerState)!=null&&t.isAdPlaying){this.cleanupControlsTimer(),this.controlsVisible=!1,this.classList.add("controls-hidden");return}if(!(((s=(i=this.config)==null?void 0:i.controls)==null?void 0:s.controlsBar)!==!1&&this.controlsSectionEnabled)){this.controlsVisible&&(this.controlsVisible=!1,this.classList.add("controls-hidden")),this.cleanupControlsTimer();return}this.controlsVisible||(this.controlsVisible=!0,this.classList.remove("controls-hidden")),this.cleanupControlsTimer(),this.playerState&&this.playerState.isPlaying&&!this.settingsMenuOpen&&!this.isDraggingSeekbar&&(this.hideControlsTimer=window.setTimeout(()=>{this.controlsVisible=!1,this.classList.add("controls-hidden")},2500))},this.handleMouseLeave=()=>{var e;if((e=this.playerState)!=null&&e.isAdPlaying){this.cleanupControlsTimer(),this.controlsVisible=!1,this.classList.add("controls-hidden");return}this.playerState&&this.playerState.isPlaying&&!this.settingsMenuOpen&&!this.isDraggingSeekbar&&(this.controlsVisible=!1,this.classList.add("controls-hidden"))},this.handleContextMenu=e=>{var i,s;if(this.isContextMenuDisabled||((s=(i=this.config)==null?void 0:i.controls)==null?void 0:s.contextMenu)===!1){e.preventDefault();return}const t=this.getBoundingClientRect();this.contextMenuX=e.clientX-t.left,this.contextMenuY=e.clientY-t.top,this.contextMenuOpen=!0},this.handleDocumentClick=e=>{this.contextMenuOpen&&(this.contextMenuOpen=!1),this.settingsMenu.closeIfOutside(e)},this.handleFocusIn=e=>{this.settingsMenu.closeIfOutside(e)}}get activePreload(){var e;return((e=this.config)==null?void 0:e.preload)||this.preload||"metadata"}get activeLoop(){var e,t,i;return((t=(e=this.config)==null?void 0:e.playback)==null?void 0:t.loop)!==void 0?this.config.playback.loop:((i=this.config)==null?void 0:i.loop)!==void 0?this.config.loop:this.loop}get activePlaysinline(){var e;return((e=this.config)==null?void 0:e.playsinline)!==void 0?this.config.playsinline:this.playsinline}get activePoster(){var e;return((e=this.config)==null?void 0:e.poster)||this.poster||""}get activeCrossorigin(){var t;const e=((t=this.config)==null?void 0:t.crossorigin)||this.crossorigin;if(e==="anonymous"||e==="use-credentials")return e}get controlsSectionEnabled(){var t;const e=(t=this.config)==null?void 0:t.controls;return!(e===!1||e&&typeof e=="object"&&e.enabled===!1)}get emptyStateSectionEnabled(){var t;const e=(t=this.config)==null?void 0:t.emptyState;return!(e===!1||e&&typeof e=="object"&&e.enabled===!1)}localize(e,t){var r,a,n;const i=((r=this.config)==null?void 0:r.locale)||{};return(((n=(a=this.config)==null?void 0:a.settings)==null?void 0:n.labels)||{})[e]||i[e]||t}get controllerInstance(){return this.controller}loadSource(e){this.prefetch.setDirection("next"),this.controller?this.controller.loadSource(e):this.updateComplete.then(()=>{var t;return(t=this.controller)==null?void 0:t.loadSource(e)})}loadPlaylist(e,t=0){this.prefetch.setDirection("next"),this.controller?this.controller.loadPlaylist(e,t):this.updateComplete.then(()=>{var i;return(i=this.controller)==null?void 0:i.loadPlaylist(e,t)})}play(){this.controller?this.controller.play():this.updateComplete.then(()=>{var e;return(e=this.controller)==null?void 0:e.play()})}pause(){this.controller?this.controller.pause():this.updateComplete.then(()=>{var e;return(e=this.controller)==null?void 0:e.pause()})}load(e){const t=typeof e=="string"?{src:e}:e;this.controller?this.controller.load(t):this.updateComplete.then(()=>{var i;return(i=this.controller)==null?void 0:i.load(t)})}destroy(){this.controller&&this.controller.destroy(),this.remove()}addPlaylistItem(e){this.controller?this.controller.addPlaylistItem(e):this.updateComplete.then(()=>{var t;return(t=this.controller)==null?void 0:t.addPlaylistItem(e)})}getCurrentItem(){return this.controller?this.controller.getCurrentItem():null}repeat(e){this.controller?this.controller.repeat(e):this.updateComplete.then(()=>{var t;return(t=this.controller)==null?void 0:t.repeat(e)})}on(e,t){this.controller?this.controller.on(e,t):this.pendingListeners.push({action:"on",event:e,callback:t})}off(e,t){this.controller?this.controller.off(e,t):this.pendingListeners.push({action:"off",event:e,callback:t})}emit(e,t){this.controller&&this.controller.emit(e,t)}setNearEndThreshold(e){this.nearEndThreshold=e,this.controller&&this.controller.setNearEndThreshold(e)}getNearEndThreshold(){return this.controller?this.controller.getNearEndThreshold():this.nearEndThreshold}getPlaylist(){return this.controller?this.controller.getPlaylist():[]}getCurrentPlaylistIndex(){return this.controller?this.controller.getCurrentPlaylistIndex():0}getHistoryStack(){return this.controller?this.controller.getHistoryStack():[]}getCurrentPlaylistItem(){return this.controller?this.controller.getCurrentPlaylistItem():null}getPlaylistLength(){return this.controller?this.controller.getPlaylistLength():0}hasPlaylist(){return this.controller?this.controller.hasPlaylist():!1}isFirstPlaylistItem(){return this.controller?this.controller.isFirstPlaylistItem():!1}isLastPlaylistItem(){return this.controller?this.controller.isLastPlaylistItem():!1}setPlaylistRepeatMode(e){this.controller&&this.controller.setPlaylistRepeatMode(e)}getPlaylistRepeatMode(){return this.controller?this.controller.getPlaylistRepeatMode():"off"}next(){if(!this.controller){this.updateComplete.then(()=>this.next());return}this.getPlaylistLength()<=1||this.gestures.isTransitionLocked||(this.prefetch.setDirection("next"),this.gestures.initiateVisualTransition("next",()=>{this.controller.next()}))}previous(){if(!this.controller){this.updateComplete.then(()=>this.previous());return}this.getPlaylistLength()<=1||this.gestures.isTransitionLocked||(this.prefetch.setDirection("prev"),this.gestures.initiateVisualTransition("prev",()=>{this.controller.previous()}))}appendPlaylistItem(e){this.controller?this.controller.appendPlaylistItem(e):this.updateComplete.then(()=>{var t;return(t=this.controller)==null?void 0:t.appendPlaylistItem(e)})}insertPlaylistItem(e,t){this.controller?this.controller.insertPlaylistItem(e,t):this.updateComplete.then(()=>{var i;return(i=this.controller)==null?void 0:i.insertPlaylistItem(e,t)})}removePlaylistItem(e){if(!this.controller){this.updateComplete.then(()=>this.removePlaylistItem(e));return}if(this.gestures.isTransitionLocked)return;e===this.getCurrentPlaylistIndex()&&this.displayMode==="vertical"?(this.prefetch.setDirection("next"),this.gestures.initiateVisualTransition("next",()=>{this.controller.removePlaylistItem(e)})):this.controller.removePlaylistItem(e)}clearPlaylist(){this.controller?this.controller.clearPlaylist():this.updateComplete.then(()=>{var e;return(e=this.controller)==null?void 0:e.clearPlaylist()})}replacePlaylistItem(e,t){this.controller?this.controller.replacePlaylistItem(e,t):this.updateComplete.then(()=>{var i;return(i=this.controller)==null?void 0:i.replacePlaylistItem(e,t)})}movePlaylistItem(e,t){this.controller?this.controller.movePlaylistItem(e,t):this.updateComplete.then(()=>{var i;return(i=this.controller)==null?void 0:i.movePlaylistItem(e,t)})}goToNextPlaylistItem(){this.next()}goToPreviousPlaylistItem(){this.previous()}setIcon(e,t){this.iconRegistry.setIcon(e,t),this.requestUpdate()}registerIconPack(e,t){X.registerIconPack(e,t),this.requestUpdate()}useIconPack(e){this.iconRegistry.useIconPack(e),this.requestUpdate()}registerControl(e,t){this.customControls.set(e,t),this.requestUpdate()}registerOverlay(e,t){this.customOverlays.set(e,t),this.requestUpdate()}disableOverlay(e){const t=this.customOverlays.get(e)||{};this.customOverlays.set(e,{...t,enabled:!1}),this.requestUpdate()}enableOverlay(e){const t=this.customOverlays.get(e)||{};this.customOverlays.set(e,{...t,enabled:!0}),this.requestUpdate()}setOverlayTemplate(e,t){const i=this.customOverlays.get(e)||{};this.customOverlays.set(e,{...i,template:t}),this.requestUpdate()}setOverlayTiming(e,t){const i=this.customOverlays.get(e)||{};this.customOverlays.set(e,{...i,timing:t}),this.requestUpdate()}getIcon(e,t){var a,n,l;const i=((a=this.config)==null?void 0:a.icons)||{},r=(((l=(n=this.config)==null?void 0:n.settings)==null?void 0:l.icons)||{})[e]||i[e];return r||this.iconRegistry.getIcon(e,t)}setThumbnailProvider(e){var i;this.thumbnailCache.setMainProvider(e),this.controller&&this.controller.setThumbnailProvider(e);const t=(i=this.playerState)==null?void 0:i.currentSource;t&&e&&this.thumbnailCache.setProviderForSource(t,e),this.thumbnailCache.trigger()}seekToChapter(e){this.controller&&this.controller.seekToChapter(e)}willUpdate(e){e.has("liveMode")&&this.controller&&this.controller.setLiveMode(this.liveMode)}firstUpdated(){var r,a,n,l,o,d,h,u,f;const e=((r=this.config)==null?void 0:r.displayMode)||((n=(a=this.config)==null?void 0:a.layout)==null?void 0:n.mode)||this.displayMode,t={autoplay:this.autoplay,muted:this.muted,volume:this.volume,displayMode:e,autoScroll:this.autoScroll,nearEndThreshold:this.nearEndThreshold,preload:this.activePreload,loop:this.activeLoop,playsinline:this.activePlaysinline,poster:this.activePoster,crossorigin:this.activeCrossorigin,...this.config||{},playback:{autoplay:this.autoplay,muted:this.muted,volume:this.volume,...((l=this.config)==null?void 0:l.playback)||{}},layout:{mode:e,...((o=this.config)==null?void 0:o.layout)||{}},sleepTimer:{...((d=this.config)==null?void 0:d.sleepTimer)||{}},live:{mode:this.liveMode,...((h=this.config)==null?void 0:h.live)||{}}};if(t.displayMode=e,t.layout||(t.layout={}),t.layout.mode=e,this.preciseSeekEnabled!==void 0&&(t.preciseSeek={...typeof t.preciseSeek=="object"?t.preciseSeek:{},enabled:this.preciseSeekEnabled}),this.smartSeekEnabled!==void 0&&(t.smartSeek={...typeof t.smartSeek=="object"?t.smartSeek:{},enabled:this.smartSeekEnabled}),t.iconPack&&this.iconRegistry.useIconPack(t.iconPack),t.icons)for(const[p,g]of Object.entries(t.icons))this.iconRegistry.setIcon(p,g);this.controller=new is(this.videoElement,t),t.theme&&this.applyTheme(t.theme);const i=(u=this.shadowRoot)==null?void 0:u.querySelector(".player-ads-overlay");i&&this.controller.ads&&this.controller.ads.setAdContainer(i);for(const p of this.pendingListeners)p.action==="on"?this.controller.on(p.event,p.callback):p.action==="off"&&this.controller.off(p.event,p.callback);if(this.pendingListeners=[],this.unsubscribe=this.controller.onStateChange(p=>{var A;if(this.isVisualTransitioning&&this.gestures.checkTransitionCompletion(),this.videoElement&&(p.isPlaying||p.status==="playing"||this.videoElement.readyState>=2)&&this.videoElement.removeAttribute("poster"),this.playerState&&this.playerState.currentSource!==p.currentSource&&(this.isFeedTransitioning=!0,p.currentSource)){const P=this.thumbnailCache.getProvider(p.currentSource);if(P&&P!==this.thumbnailCache.getMainProvider()){if(this.thumbnailCache.setMainProvider(P),this.controller){const $=this.controller;$.thumbnailProvider=P,$.state.thumbnailProvider=P}p.thumbnailProvider=P}}if(this.playerState&&this.playerState.isAdPlaying!==p.isAdPlaying&&(p.isAdPlaying?(this.cleanupControlsTimer(),this.controlsVisible=!1,this.classList.add("controls-hidden")):(this.controlsVisible=!0,this.classList.remove("controls-hidden"))),this.playerState&&this.playerState.isPlaying!==p.isPlaying&&p.status!=="idle"&&p.status!=="error"&&!(p.status==="ended"&&this.displayMode==="vertical")){const P=this.displayMode==="vertical"&&((A=this.videoElement)==null?void 0:A.ended);!this.isFeedTransitioning&&!this.suppressPlayPauseFeedback&&!P&&this.triggerPlayPauseFeedback(p.isPlaying?"play":"pause")}this.isFeedTransitioning&&(p.status==="playing"||p.status==="paused"||p.status==="error"||p.status==="ended")&&(this.isFeedTransitioning=!1),(p.isPlaying||p.status==="playing")&&(this.suppressPlayPauseFeedback=!1,this.shouldAutoplayAfterTransition=!1),this.playerState&&(this.playerState.volume!==p.volume||this.playerState.isMuted!==p.isMuted)&&p.status!=="idle"&&p.status!=="error"&&this.triggerVolumeFeedback(p.volume,p.isMuted),this.playerState&&this.playerState.playbackRate!==p.playbackRate&&p.status!=="idle"&&p.status!=="error"&&this.triggerSpeedFeedback(p.playbackRate),this.shouldShowQualityFeedback&&this.playerState&&this.playerState.activeQuality!==p.activeQuality&&p.activeQuality&&p.status!=="idle"&&p.status!=="loading"&&p.status!=="error"&&(this.triggerQualityFeedback(p.activeQuality),this.shouldShowQualityFeedback=!1);const m=this.playerState;this.playerState=p,this.muted=p.isMuted,this.volume=p.volume,this.displayMode=p.displayMode,this.autoScroll=p.autoScroll,this.liveMode=p.liveMode;const v=!m||m.status!==p.status,y=!m||m.currentSource!==p.currentSource;(v||y)&&(this.thumbnailCache.trigger(),this.prefetch.trigger()),m&&m.currentSource!==p.currentSource&&(this.filmstripThumbs.clear(),this.filmstripCenterTime=-1,this.isPreciseSeeking=!1,this.speedLockState="IDLE",this.isSpeedOverlayFadingOut=!1),!p.isSeeking&&!this.isDraggingSeekbar&&(this.pendingSeekTime=null);const S=!m||["status","isPlaying","volume","isMuted","isFullscreen","playbackRate","captionsEnabled","currentSource","sourceType","isBuffering","isSeeking","hasCaptions","error","activeQuality","activeAudioTrack","activeSubtitleTrackId","activeChapterIndex","loop","isLive","isLowLatency","isAtLiveEdge","liveLatency","dvrWindow","canSeekInDvr"].some(P=>m[P]!==p[P]),E=(m?Math.abs(m.currentTime-p.currentTime):0)>=.2||p.isSeeking||m&&m.isSeeking!==p.isSeeking;(S||E)&&this.dispatchEvent(new CustomEvent("player-state-change",{detail:p,bubbles:!0,composed:!0}))}),["play","ended","pause","seek","seekstart","seekend","volumechange","mutechange","playbackratechange","qualitychange","subtitlechange","audiochange","fullscreenchange","pipchange","sourcechange","chapterchange","markerclick","markerhover","metadata","error","replay","playlist-loaded","playlist-cleared","playlist-change","playlist-index-change","playlist-next","playlist-previous","playlist-item-added","playlist-item-removed","playlist-item-replaced","playlist-item-moved","playlist-near-end","playlist-repeat-change","autoscroll-change","metadata","timeupdate","waiting","playing","config-change","drmsessioncreated","drmsessionclosed","drmmessage","drmkeychange","drmerror","drmlicenserequest","drmlicenseresponse","manifestloaded","adbreakstart","adbreakend","adclick","adloadstart","adloaded","adstart","adpause","adresume","adskip","adcomplete","adquartile","admute","adunmute","adtimeupdate","adproviderchange","aderror","adverificationready","skipavailable","admilestone","companionshown","companionerror","vmapparseerror","vmapbreakerror","htmloverlayavailable","htmloverlayloaded","htmloverlayshown","htmloverlayhidden","htmloverlayclosed","htmloverlayclick","htmloverlaycompleted","htmloverlayerror","htmloverlayupdated","simidavailable","simidstart","simidready","simiderror","simidcomplete","simidinteraction","simidsecurityerror","simidclick","simiddurationchange","simidcreativeerror","simidpause","simidresume","simidresize","simidfullscreen","simidexitfullscreen","simidcollapse","simidexpand","simidskip","simidstop"].forEach(p=>{this.controller.addEventListener(p,g=>{var m,v,y,b;if(p==="config-change"){const S=g;this.config=S,S.theme&&this.applyTheme(S.theme),this.requestUpdate()}if(p==="ended")if(this.controller.getAutoAdvanceIndexOnEnded()!==null){const T=((v=(m=this.config)==null?void 0:m.vertical)==null?void 0:v.loopSingleVideo)!==void 0?this.config.vertical.loopSingleVideo:this.displayMode==="vertical"&&!this.playerState.autoScroll;this.displayMode!=="vertical"||this.playerState.autoScroll&&!T?(this.next(),this.displayMode!=="vertical"&&this.controller.play()):this.displayMode==="vertical"&&(this.suppressPlayPauseFeedback=!0,this.controller.seek(0),this.controller.play())}else this.displayMode==="vertical"&&((b=(y=this.config)==null?void 0:y.vertical)==null?void 0:b.loopSingleVideo)!==!1&&(this.suppressPlayPauseFeedback=!0,this.controller.seek(0),this.controller.play());if(p==="playlist-next"){const S=g;this.dispatchEvent(new CustomEvent("player-feed-next",{detail:{index:S.index,source:S.source},bubbles:!0,composed:!0}))}if(p==="playlist-previous"){const S=g;this.dispatchEvent(new CustomEvent("player-feed-previous",{detail:{index:S.index,source:S.source},bubbles:!0,composed:!0}))}this.dispatchEvent(new CustomEvent(`player-${p}`,{detail:g,bubbles:!0,composed:!0}))})}),this.src&&this.controller.loadSource({src:this.src}),this.captions&&this.controller.loadCaptions({src:this.captions,label:"English Subtitles",srclang:"en",default:!0}),this.setupInteractionListeners(),this.gestures.attach(),this.addEventListener("contextmenu",this.handleContextMenu),document.addEventListener("click",this.handleDocumentClick),document.addEventListener("focusin",this.handleFocusIn),this.controller){this.controller.player=this,this.controller.pendingOverlays.forEach((g,m)=>{this.registerOverlay(m,g)}),this.controller.pendingOverlays.clear();const p=this.controller.getPlugins();for(const g of p)try{(f=g.onPlayerAttached)==null||f.call(g,this)}catch(m){console.error(`[Player] Error running onPlayerAttached for plugin ${g.name}:`,m)}}this.shortcutsUnsubscribe=this.controller.shortcuts.onAction((p,g)=>{if(p==="seek"&&(g==null?void 0:g.seconds)!==void 0){const m=g.seconds;this.showFeedbackOverlay(m<0?"rewind":"fastforward"),this.triggerSeekInteraction()}else if(p==="volume"&&(g==null?void 0:g.volume)!==void 0&&g.isMuted!==void 0){const{volume:m,isMuted:v}=g;this.triggerVolumeFeedback(m,v)}else p==="fullscreen"&&this.handleFullscreenToggle()})}updated(e){var t,i,s,r,a,n,l;if(super.updated(e),e.has("config")&&this.controller&&this.config&&this.config!==this.controller.config&&this.controller.updateConfig(this.config),e.has("preciseSeekEnabled")&&this.controller&&this.preciseSeekEnabled!==void 0&&this.controller.updateConfig({preciseSeek:{...typeof((t=this.config)==null?void 0:t.preciseSeek)=="object"?this.config.preciseSeek:{},enabled:this.preciseSeekEnabled}}),e.has("smartSeekEnabled")&&this.controller&&this.smartSeekEnabled!==void 0&&this.controller.updateConfig({smartSeek:{...typeof((i=this.config)==null?void 0:i.smartSeek)=="object"?this.config.smartSeek:{},enabled:this.smartSeekEnabled}}),e.has("config")){const o=(r=(s=this.config)==null?void 0:s.vertical)==null?void 0:r.animationTiming;o!==void 0?this.style.setProperty("--player-vertical-transition-duration",`${o}ms`):this.style.removeProperty("--player-vertical-transition-duration"),((n=(a=this.config)==null?void 0:a.vertical)==null?void 0:n.autoScroll)!==void 0&&(this.autoScroll=this.config.vertical.autoScroll,this.controller&&this.controller.setAutoScroll(this.autoScroll))}if(e.has("displayMode")&&this.controller){const o=e.get("displayMode");if(o!==void 0&&o!==this.displayMode){this.controller.setDisplayMode(this.displayMode);const d=this.getAvailableSpeeds(this.displayMode),h=this.playerState.playbackRate;if(!d.includes(h)){const u=d.reduce((f,p)=>Math.abs(p-h)<Math.abs(f-h)?p:f);this.controller.setPlaybackRate(u)}if(this.displayMode==="vertical"){this.isPreciseSeeking=!1;const u=this.playerState.thumbnailProvider;u&&(u.isPreciseSeeking=!1)}}}if(e.has("nearEndThreshold")&&this.controller){const o=e.get("nearEndThreshold");o!==void 0&&o!==this.nearEndThreshold&&this.controller.setNearEndThreshold(this.nearEndThreshold)}if(e.has("autoScroll")&&this.controller){const o=e.get("autoScroll");o!==void 0&&o!==this.autoScroll&&this.controller.setAutoScroll(this.autoScroll)}if(e.has("src")&&this.controller){const o=e.get("src");o!==void 0&&o!==this.src&&(this.settingsMenu.close(),this.filmstripThumbs.clear(),this.filmstripCenterTime=-1,this.isPreciseSeeking=!1,this.speedLockState="IDLE",this.isSpeedOverlayFadingOut=!1,this.controller.loadSource({src:this.src}))}if(e.has("captions")&&this.controller&&this.captions){const o=e.get("captions");o!==void 0&&o!==this.captions&&this.controller.loadCaptions({src:this.captions,label:"English Subtitles",srclang:"en",default:!0})}if(e.has("activeMenuScreen")&&this.settingsMenu.onScreenChanged(),e.has("settingsMenuOpen")&&this.settingsMenu.onOpenStateChanged(e.get("settingsMenuOpen")),e.has("contextMenuOpen")){const o=e.get("contextMenuOpen");this.contextMenuOpen&&!o&&setTimeout(()=>{var h;const d=(h=this.shadowRoot)==null?void 0:h.querySelector(".custom-context-menu");if(d){const u=d.querySelector(".context-menu-item:not(.disabled)");u?u.focus():d.focus()}},50)}if(e.has("playerState")){const o=e.get("playerState");this.playerState.status==="ended"&&!this.playerState.isLive&&this.displayMode!=="vertical"&&(!o||o.status!=="ended")&&setTimeout(()=>{var h;const d=(h=this.shadowRoot)==null?void 0:h.querySelector(".replay-icon-circle");d&&d.focus()},50),this.playerState.sleepTimerExpired&&(!o||!o.sleepTimerExpired)&&(this.lastFocusedElement=this.getDeepActiveElement(),setTimeout(()=>{var h;const d=(h=this.shadowRoot)==null?void 0:h.querySelector(".sleep-timer-btn-close");d&&d.focus()},50)),o&&o.sleepTimerExpired&&!this.playerState.sleepTimerExpired&&setTimeout(()=>{this.lastFocusedElement&&typeof this.lastFocusedElement.focus=="function"?this.lastFocusedElement.focus():this.focus(),this.lastFocusedElement=null},50)}if(this.isPreciseSeeking){const o=(l=this.shadowRoot)==null?void 0:l.querySelector(".precise-seek-container");o&&o.clientWidth>0&&this.preciseSeekContainerWidth!==o.clientWidth&&(this.preciseSeekContainerWidth=o.clientWidth,this.requestUpdate())}}disconnectedCallback(){var e;if(super.disconnectedCallback(),this.speedLockState="IDLE",this.isSpeedOverlayFadingOut=!1,this.activeSpeedFeedback=null,this.gestures.detach(),typeof window<"u"&&window.removeEventListener("resize",this.handleResize),this.removeEventListener("mousemove",this.handleActivity),this.removeEventListener("mouseleave",this.handleMouseLeave),this.removeEventListener("focusin",this.handleActivity),this.removeEventListener("keydown",this.handleKeyDown),this.removeEventListener("contextmenu",this.handleContextMenu),document.removeEventListener("click",this.handleDocumentClick),document.removeEventListener("focusin",this.handleFocusIn),this.settingsMenu.close(),this.controller){const t=this.controller.getPlugins();for(const i of t)try{(e=i.onPlayerDetached)==null||e.call(i,this)}catch(s){console.error(`[Player] Error running onPlayerDetached for plugin ${i.name}:`,s)}}this.unsubscribe&&this.unsubscribe(),this.shortcutsUnsubscribe&&this.shortcutsUnsubscribe(),this.thumbnailCache.destroy(),this.prefetch.cancel(),this.controller&&this.controller.destroy(),this.cleanupControlsTimer(),this.feedbackTimer&&(clearTimeout(this.feedbackTimer),this.feedbackTimer=void 0),this.tapFeedback=null,this.feedbackTaps=0,this.playPauseFeedbackTimer&&clearTimeout(this.playPauseFeedbackTimer),this.seekInteractionTimer&&clearTimeout(this.seekInteractionTimer),this.speedFeedbackTimer&&clearTimeout(this.speedFeedbackTimer),this.qualityFeedbackTimer&&clearTimeout(this.qualityFeedbackTimer),this.volumeFeedbackTimer&&clearTimeout(this.volumeFeedbackTimer),this.throttledSeekTimer&&clearTimeout(this.throttledSeekTimer),this.toastTimer&&clearTimeout(this.toastTimer),this.isDraggingSeekbar=!1,this.filmstripThumbs.clear(),this.gestures.endVisualTransition()}getDeepActiveElement(){let e=document.activeElement;for(;e&&e.shadowRoot&&e.shadowRoot.activeElement;)e=e.shadowRoot.activeElement;return e}setupInteractionListeners(){this.addEventListener("mousemove",this.handleActivity),this.addEventListener("mouseleave",this.handleMouseLeave),this.addEventListener("focusin",this.handleActivity),typeof window<"u"&&window.addEventListener("resize",this.handleResize),this.setAttribute("tabindex","0"),this.addEventListener("keydown",this.handleKeyDown)}cleanupControlsTimer(){this.hideControlsTimer&&(clearTimeout(this.hideControlsTimer),this.hideControlsTimer=void 0)}showFeedbackOverlay(e){this.tapFeedback&&this.tapFeedback!==e&&(this.feedbackTaps=0),this.tapFeedback=null,this.requestUpdate(),this.feedbackTaps++,this.feedbackTimer&&(clearTimeout(this.feedbackTimer),this.feedbackTimer=void 0),requestAnimationFrame(()=>{requestAnimationFrame(()=>{this.tapFeedback=e,this.feedbackTimer=window.setTimeout(()=>{this.tapFeedback=null,this.feedbackTaps=0,this.feedbackTimer=void 0},this.getOverlayTiming("seek",800))})})}triggerPlayPauseFeedback(e){this.playPauseFeedback=null,this.requestUpdate(),this.playPauseFeedbackTimer&&clearTimeout(this.playPauseFeedbackTimer),requestAnimationFrame(()=>{requestAnimationFrame(()=>{this.playPauseFeedback=e,this.playPauseFeedbackTimer=window.setTimeout(()=>{this.playPauseFeedback=null},this.getOverlayTiming("play-pause",800))})})}handleVideoClick(){var e,t,i,s;if(!this.gestures.isLongPressSpeedActive){if(this.settingsMenuOpen){this.settingsMenu.close();return}if(!(((t=(e=this.config)==null?void 0:e.controls)==null?void 0:t.play)===!1||((s=(i=this.config)==null?void 0:i.controls)==null?void 0:s.playButton)===!1)){if(this.playerState.status==="ended"&&!this.playerState.isLive&&this.displayMode!=="vertical"){this.handleReplay();return}this.controller.togglePlay(),this.handleActivity()}}}handleReplay(){this.controller&&(this.controller.replay(),this.handleActivity())}handleReplayKeyDown(e){(e.key==="Enter"||e.key===" ")&&(e.preventDefault(),e.stopPropagation(),this.handleReplay())}handleVideoDoubleClick(e){var n,l,o,d,h;if(((l=(n=this.config)==null?void 0:n.controls)==null?void 0:l.seekbar)===!1||this.playerState.isLive&&!this.playerState.canSeekInDvr||!(this.displayMode==="vertical"?((h=(d=(o=this.config)==null?void 0:o.vertical)==null?void 0:d.gestures)==null?void 0:h.doubleTapToSeek)!==!1:!0))return;const s=this.videoElement.getBoundingClientRect(),a=(e.clientX-s.left)/s.width;a<.4?(this.controller.seekBy(-10),this.showFeedbackOverlay("rewind")):a>.6?(this.controller.seekBy(10),this.showFeedbackOverlay("fastforward")):this.controller.toggleFullscreen(this)}handleSeekBy(e){if(this.playerState.isLive&&!this.playerState.canSeekInDvr)return;const t=e.detail.seconds;this.controller.seekBy(t),this.showFeedbackOverlay(t<0?"rewind":"fastforward"),this.triggerSeekInteraction()}handleSelectSpeed(e){this.controller.setPlaybackRate(e),this.settingsMenu.close()}getAvailableSpeeds(e){var t,i;return((i=(t=this.config)==null?void 0:t.playback)==null?void 0:i.playbackRates)||(e==="vertical"?Wr:Kr)}handleSelectQuality(e){this.shouldShowQualityFeedback=!0,this.controller.setQuality(e),this.settingsMenu.close()}handleSelectAudio(e){this.controller.setAudioTrack(e),this.settingsMenu.close()}handleSelectSubtitle(e){e===-1?this.controller.disableSubtitles():this.controller.setSubtitleTrack(e),this.settingsMenu.close()}handleSelectSleepTimer(e){this.controller.setSleepTimer(e),this.settingsMenu.close()}getSleepTimerLabel(){const e=this.playerState.sleepTimerSetting;if(e==="off")return"Off";if(e==="end")return"End of video";const t=this.playerState.sleepTimerSecondsRemaining;return t!=null?`${Math.ceil(t/60)} min`:`${e} min`}getRemainingVideoTimeText(){const e=this.playerState.duration,t=this.playerState.currentTime,i=Math.max(0,e-t);return isNaN(i)||i===1/0||i===0?"":`${Math.ceil(i/60)} min`}handleSleepTimerAddTime(){this.controller.clearSleepTimerExpired(),this.controlsVisible=!0,this.classList.remove("controls-hidden"),this.settingsMenu.open("sleeptimer"),this.requestUpdate()}handleSleepTimerClose(){this.controller.clearSleepTimerExpired(),this.settingsMenu.close(),this.controlsVisible=!0,this.classList.remove("controls-hidden"),this.requestUpdate()}handleIconSlotChange(e,t){const s=t.target.assignedElements();s.length>0&&(this.iconRegistry.setIcon(e,s[0]),this.requestUpdate())}renderHiddenSlots(){return k`
3620
+ `}};ai.styles=Br;let ue=ai;if(ye([F({type:Object})],ue.prototype,"playerState"),ye([F({type:Boolean})],ue.prototype,"controlsVisible"),ye([F({type:Boolean})],ue.prototype,"settingsMenuOpen"),ye([F({type:String})],ue.prototype,"activeMenuScreen"),ye([F({type:Number})],ue.prototype,"pendingSeekTime"),ye([F({type:Boolean})],ue.prototype,"showNavigation"),ye([F({attribute:!1})],ue.prototype,"player"),ye([F({type:Boolean})],ue.prototype,"hideCurrentTime"),ye([F({type:Boolean})],ue.prototype,"hideDuration"),ye([j()],ue.prototype,"isVolumeSliderActive"),typeof window<"u"&&typeof customElements<"u"&&(customElements.get("streamit-vertical-controls")||customElements.define("streamit-vertical-controls",ue),!customElements.get("player-vertical-controls"))){class c extends ue{}customElements.define("player-vertical-controls",c)}const Jt={light:{"--player-primary-color":"#4f46e5","--player-accent-color":"#818cf8","--player-bg-color":"#ffffff","--player-text-color":"#1f2937","--player-glass-bg":"rgba(255, 255, 255, 0.75)","--player-glass-border":"rgba(0, 0, 0, 0.08)","--player-glass-shadow":"0 8px 32px rgba(31, 38, 135, 0.07)","--player-menu-bg":"rgba(255, 255, 255, 0.95)","--player-seekbar-bg":"rgba(0, 0, 0, 0.1)","--player-seekbar-buffer":"rgba(0, 0, 0, 0.15)","--tooltip-bg":"rgba(255, 255, 255, 0.95)","--player-tooltip-color":"#1f2937","--marker-color-default":"#6b7280","--player-primary-glow":"rgba(79, 70, 229, 0.35)","--player-glass-panel":"rgba(255, 255, 255, 0.95)","--player-button-color":"#4b5563","--player-button-hover-color":"#1f2937","--player-button-hover-bg":"rgba(0, 0, 0, 0.05)","--player-volume-played-bg":"#4f46e5","--player-volume-unplayed-bg":"rgba(0, 0, 0, 0.15)","--player-vertical-max-width":"450px","--player-overlay-bg":"#f8fafc","--player-ad-badge-bg":"rgba(15, 23, 42, 0.85)","--player-ad-badge-color":"#ffffff","--player-ad-skip-bg":"rgba(15, 23, 42, 0.9)","--player-ad-skip-color":"#ffffff","--player-ad-skip-disabled-bg":"rgba(15, 23, 42, 0.9)","--player-ad-progress-bg":"rgba(255, 255, 255, 0.2)","--player-ad-progress-fill":"#f59e0b","--player-live-badge-live-bg":"rgba(239, 68, 68, 0.15)","--player-live-badge-live-border":"rgba(239, 68, 68, 0.3)","--player-live-badge-live-color":"#ef4444","--player-live-badge-behind-bg":"rgba(0, 0, 0, 0.05)","--player-live-badge-behind-border":"rgba(0, 0, 0, 0.1)","--player-live-badge-behind-color":"#4b5563","--player-preview-border-color":"#ffffff","--player-preview-border-width":"2px","--player-preview-border-radius":"12px","--player-preview-shadow":"0 10px 25px rgba(0, 0, 0, 0.5)","--player-preview-bg":"#08080c","--player-preview-time-bg":"linear-gradient(to top, rgba(0, 0, 0, 0.55) 0%, rgba(0, 0, 0, 0) 100%)","--player-preview-time-color":"#ffffff","--player-preview-time-font":"var(--player-font-family, 'Outfit', sans-serif)","--player-preview-time-size":"12px","--player-preview-width":"200px","--player-preview-height":"112px","--player-preview-offset":"16px","--player-preview-animation":"opacity var(--player-transition-duration, 0.15s) var(--player-ease-smooth)","--player-preview-opacity":"1","--player-preview-blur":"none","--player-preview-arrow-color":"#ffffff","--player-preview-arrow-size":"6px","--player-preview-arrow-visible":"block","--player-preview-transition":"opacity var(--player-transition-duration, 0.15s) var(--player-ease-smooth)","--player-preview-z-index":"50","--player-preview-padding":"0","--player-preview-spacing":"0","--player-preview-backdrop-filter":"none","--player-preview-vertical-width":"90px","--player-preview-vertical-height":"160px"},dark:{"--player-primary-color":"#6366f1","--player-accent-color":"#818cf8","--player-bg-color":"#0f172a","--player-text-color":"#f8fafc","--player-glass-bg":"rgba(15, 23, 42, 0.65)","--player-glass-border":"rgba(255, 255, 255, 0.08)","--player-glass-shadow":"0 8px 32px rgba(0, 0, 0, 0.3)","--player-menu-bg":"rgba(15, 23, 42, 0.95)","--player-seekbar-bg":"rgba(255, 255, 255, 0.15)","--player-seekbar-buffer":"rgba(255, 255, 255, 0.25)","--tooltip-bg":"rgba(15, 23, 42, 0.95)","--player-tooltip-color":"#f8fafc","--marker-color-default":"#ffffff","--player-primary-glow":"rgba(99, 102, 241, 0.35)","--player-glass-panel":"rgba(15, 23, 42, 0.95)","--player-button-color":"#cbd5e1","--player-button-hover-color":"#ffffff","--player-button-hover-bg":"rgba(255, 255, 255, 0.08)","--player-volume-played-bg":"#6366f1","--player-volume-unplayed-bg":"rgba(255, 255, 255, 0.2)","--player-vertical-max-width":"450px","--player-overlay-bg":"#08080c","--player-ad-badge-bg":"rgba(15, 23, 42, 0.85)","--player-ad-badge-color":"#ffffff","--player-ad-skip-bg":"rgba(15, 23, 42, 0.9)","--player-ad-skip-color":"#ffffff","--player-ad-skip-disabled-bg":"rgba(15, 23, 42, 0.9)","--player-ad-progress-bg":"rgba(255, 255, 255, 0.2)","--player-ad-progress-fill":"#f59e0b","--player-live-badge-live-bg":"rgba(239, 68, 68, 0.15)","--player-live-badge-live-border":"rgba(239, 68, 68, 0.3)","--player-live-badge-live-color":"#ef4444","--player-live-badge-behind-bg":"rgba(255, 255, 255, 0.08)","--player-live-badge-behind-border":"rgba(255, 255, 255, 0.12)","--player-live-badge-behind-color":"#94a3b8","--player-preview-border-color":"#ffffff","--player-preview-border-width":"2px","--player-preview-border-radius":"12px","--player-preview-shadow":"0 10px 25px rgba(0, 0, 0, 0.5)","--player-preview-bg":"#08080c","--player-preview-time-bg":"linear-gradient(to top, rgba(0, 0, 0, 0.55) 0%, rgba(0, 0, 0, 0) 100%)","--player-preview-time-color":"#ffffff","--player-preview-time-font":"var(--player-font-family, 'Outfit', sans-serif)","--player-preview-time-size":"12px","--player-preview-width":"200px","--player-preview-height":"112px","--player-preview-offset":"16px","--player-preview-animation":"opacity var(--player-transition-duration, 0.15s) var(--player-ease-smooth)","--player-preview-opacity":"1","--player-preview-blur":"none","--player-preview-arrow-color":"#ffffff","--player-preview-arrow-size":"6px","--player-preview-arrow-visible":"block","--player-preview-transition":"opacity var(--player-transition-duration, 0.15s) var(--player-ease-smooth)","--player-preview-z-index":"50","--player-preview-padding":"0","--player-preview-spacing":"0","--player-preview-backdrop-filter":"none","--player-preview-vertical-width":"90px","--player-preview-vertical-height":"160px"},"glass-dark":{"--player-primary-color":"#6366f1","--player-accent-color":"#818cf8","--player-bg-color":"transparent","--player-text-color":"#f8fafc","--player-glass-bg":"rgba(8, 8, 12, 0.45)","--player-glass-border":"rgba(255, 255, 255, 0.06)","--player-glass-shadow":"0 20px 50px rgba(0, 0, 0, 0.45)","--player-menu-bg":"rgba(8, 8, 12, 0.85)","--player-seekbar-bg":"rgba(255, 255, 255, 0.15)","--player-seekbar-buffer":"rgba(255, 255, 255, 0.25)","--marker-color-default":"#ffffff","--tooltip-bg":"rgba(8, 8, 12, 0.9)","--player-tooltip-color":"#f8fafc","--player-primary-glow":"rgba(99, 102, 241, 0.35)","--player-glass-panel":"rgba(10, 10, 15, 0.85)","--player-button-color":"#cbd5e1","--player-button-hover-color":"#ffffff","--player-button-hover-bg":"rgba(255, 255, 255, 0.08)","--player-volume-played-bg":"#6366f1","--player-volume-unplayed-bg":"rgba(255, 255, 255, 0.2)","--player-vertical-max-width":"450px","--player-overlay-bg":"#08080c","--player-ad-badge-bg":"rgba(8, 8, 12, 0.85)","--player-ad-badge-color":"#ffffff","--player-ad-skip-bg":"rgba(8, 8, 12, 0.9)","--player-ad-skip-color":"#ffffff","--player-ad-skip-disabled-bg":"rgba(8, 8, 12, 0.9)","--player-ad-progress-bg":"rgba(255, 255, 255, 0.2)","--player-ad-progress-fill":"#f59e0b","--player-live-badge-live-bg":"rgba(239, 68, 68, 0.15)","--player-live-badge-live-border":"rgba(239, 68, 68, 0.3)","--player-live-badge-live-color":"#ef4444","--player-live-badge-behind-bg":"rgba(255, 255, 255, 0.08)","--player-live-badge-behind-border":"rgba(255, 255, 255, 0.12)","--player-live-badge-behind-color":"#94a3b8","--player-preview-border-color":"#ffffff","--player-preview-border-width":"2px","--player-preview-border-radius":"12px","--player-preview-shadow":"0 10px 25px rgba(0, 0, 0, 0.5)","--player-preview-bg":"#08080c","--player-preview-time-bg":"linear-gradient(to top, rgba(0, 0, 0, 0.55) 0%, rgba(0, 0, 0, 0) 100%)","--player-preview-time-color":"#ffffff","--player-preview-time-font":"var(--player-font-family, 'Outfit', sans-serif)","--player-preview-time-size":"12px","--player-preview-width":"200px","--player-preview-height":"112px","--player-preview-offset":"16px","--player-preview-animation":"opacity var(--player-transition-duration, 0.15s) var(--player-ease-smooth)","--player-preview-opacity":"1","--player-preview-blur":"none","--player-preview-arrow-color":"#ffffff","--player-preview-arrow-size":"6px","--player-preview-arrow-visible":"block","--player-preview-transition":"opacity var(--player-transition-duration, 0.15s) var(--player-ease-smooth)","--player-preview-z-index":"50","--player-preview-padding":"0","--player-preview-spacing":"0","--player-preview-backdrop-filter":"none","--player-preview-vertical-width":"90px","--player-preview-vertical-height":"160px"},"glass-light":{"--player-primary-color":"#db2777","--player-accent-color":"#f472b6","--player-bg-color":"transparent","--player-text-color":"#111827","--player-glass-bg":"rgba(255, 255, 255, 0.45)","--player-glass-border":"rgba(0, 0, 0, 0.05)","--player-glass-shadow":"0 20px 50px rgba(0, 0, 0, 0.1)","--player-menu-bg":"rgba(255, 255, 255, 0.85)","--player-seekbar-bg":"rgba(0, 0, 0, 0.1)","--player-seekbar-buffer":"rgba(0, 0, 0, 0.15)","--marker-color-default":"#db2777","--tooltip-bg":"rgba(255, 255, 255, 0.9)","--player-tooltip-color":"#111827","--player-primary-glow":"rgba(219, 39, 119, 0.35)","--player-glass-panel":"rgba(255, 255, 255, 0.85)","--player-button-color":"#4b5563","--player-button-hover-color":"#111827","--player-button-hover-bg":"rgba(0, 0, 0, 0.05)","--player-volume-played-bg":"#db2777","--player-volume-unplayed-bg":"rgba(0, 0, 0, 0.15)","--player-vertical-max-width":"450px","--player-overlay-bg":"#ffffff","--player-ad-badge-bg":"rgba(15, 23, 42, 0.85)","--player-ad-badge-color":"#ffffff","--player-ad-skip-bg":"rgba(15, 23, 42, 0.9)","--player-ad-skip-color":"#ffffff","--player-ad-skip-disabled-bg":"rgba(15, 23, 42, 0.9)","--player-ad-progress-bg":"rgba(255, 255, 255, 0.2)","--player-ad-progress-fill":"#f59e0b","--player-live-badge-live-bg":"rgba(239, 68, 68, 0.15)","--player-live-badge-live-border":"rgba(239, 68, 68, 0.3)","--player-live-badge-live-color":"#ef4444","--player-live-badge-behind-bg":"rgba(0, 0, 0, 0.05)","--player-live-badge-behind-border":"rgba(0, 0, 0, 0.1)","--player-live-badge-behind-color":"#4b5563","--player-preview-border-color":"#ffffff","--player-preview-border-width":"2px","--player-preview-border-radius":"12px","--player-preview-shadow":"0 10px 25px rgba(0, 0, 0, 0.5)","--player-preview-bg":"#08080c","--player-preview-time-bg":"linear-gradient(to top, rgba(0, 0, 0, 0.55) 0%, rgba(0, 0, 0, 0) 100%)","--player-preview-time-color":"#ffffff","--player-preview-time-font":"var(--player-font-family, 'Outfit', sans-serif)","--player-preview-time-size":"12px","--player-preview-width":"200px","--player-preview-height":"112px","--player-preview-offset":"16px","--player-preview-animation":"opacity var(--player-transition-duration, 0.15s) var(--player-ease-smooth)","--player-preview-opacity":"1","--player-preview-blur":"none","--player-preview-arrow-color":"#ffffff","--player-preview-arrow-size":"6px","--player-preview-arrow-visible":"block","--player-preview-transition":"opacity var(--player-transition-duration, 0.15s) var(--player-ease-smooth)","--player-preview-z-index":"50","--player-preview-padding":"0","--player-preview-spacing":"0","--player-preview-backdrop-filter":"none","--player-preview-vertical-width":"90px","--player-preview-vertical-height":"160px"}};function as(c={}){const e=c.preset||"glass-dark",i={...Jt[e]||Jt["glass-dark"]};if(c.primaryColor&&(i["--player-primary-color"]=c.primaryColor),c.accentColor&&(i["--player-accent-color"]=c.accentColor),c.backgroundColor&&(i["--player-bg-color"]=c.backgroundColor),c.textColor&&(i["--player-text-color"]=c.textColor),c.menuColor&&(i["--player-menu-bg"]=c.menuColor),c.seekbarBg&&(i["--player-seekbar-bg"]=c.seekbarBg),c.seekbarPlayed&&(i["--player-seekbar-played"]=c.seekbarPlayed),c.seekbarBuffered&&(i["--player-seekbar-buffer"]=c.seekbarBuffered),c.borderRadius&&(i["--player-border-radius"]=c.borderRadius),c.fontFamily&&(i["--player-font-family"]=c.fontFamily),c.fontSize&&(i["--player-cue-font-size"]=c.fontSize),c.blur&&(i["--player-glass-blur"]=c.blur,i["--player-glass-blur-webkit"]=c.blur),c.shadows&&(i["--player-shadow"]=c.shadows),c.spacing&&(i["--player-spacing"]=c.spacing),c.transitions&&(i["--player-transition-duration"]=c.transitions),c.primaryGlow&&(i["--player-primary-glow"]=c.primaryGlow),c.glassBg&&(i["--player-glass-bg"]=c.glassBg),c.glassPanel&&(i["--player-glass-panel"]=c.glassPanel),c.glassBorder&&(i["--player-glass-border"]=c.glassBorder),c.glassShadow&&(i["--player-glass-shadow"]=c.glassShadow),c.menuBg&&(i["--player-menu-bg"]=c.menuBg),c.tooltipBg&&(i["--tooltip-bg"]=c.tooltipBg),c.tooltipColor&&(i["--player-tooltip-color"]=c.tooltipColor),c.buttonColor&&(i["--player-button-color"]=c.buttonColor),c.buttonHoverColor&&(i["--player-button-hover-color"]=c.buttonHoverColor),c.buttonHoverBg&&(i["--player-button-hover-bg"]=c.buttonHoverBg),c.buttonIconSize&&(i["--player-button-icon-size"]=c.buttonIconSize),c.volumePlayedBg&&(i["--player-volume-played-bg"]=c.volumePlayedBg),c.volumeUnplayedBg&&(i["--player-volume-unplayed-bg"]=c.volumeUnplayedBg),c.verticalMaxWidth&&(i["--player-vertical-max-width"]=c.verticalMaxWidth),c.overlayBg&&(i["--player-overlay-bg"]=c.overlayBg),c.liveBadgeLiveBg&&(i["--player-live-badge-live-bg"]=c.liveBadgeLiveBg),c.liveBadgeLiveBorder&&(i["--player-live-badge-live-border"]=c.liveBadgeLiveBorder),c.liveBadgeLiveColor&&(i["--player-live-badge-live-color"]=c.liveBadgeLiveColor),c.liveBadgeBehindBg&&(i["--player-live-badge-behind-bg"]=c.liveBadgeBehindBg),c.liveBadgeBehindBorder&&(i["--player-live-badge-behind-border"]=c.liveBadgeBehindBorder),c.liveBadgeBehindColor&&(i["--player-live-badge-behind-color"]=c.liveBadgeBehindColor),c.previewBorderColor&&(i["--player-preview-border-color"]=c.previewBorderColor),c.previewBorderWidth&&(i["--player-preview-border-width"]=c.previewBorderWidth),c.previewBorderRadius&&(i["--player-preview-border-radius"]=c.previewBorderRadius),c.previewShadow&&(i["--player-preview-shadow"]=c.previewShadow),c.previewBg&&(i["--player-preview-bg"]=c.previewBg),c.previewTimeBg&&(i["--player-preview-time-bg"]=c.previewTimeBg),c.previewTimeColor&&(i["--player-preview-time-color"]=c.previewTimeColor),c.previewTimeFont&&(i["--player-preview-time-font"]=c.previewTimeFont),c.previewTimeSize&&(i["--player-preview-time-size"]=c.previewTimeSize),c.previewWidth&&(i["--player-preview-width"]=c.previewWidth),c.previewHeight&&(i["--player-preview-height"]=c.previewHeight),c.previewOffset&&(i["--player-preview-offset"]=c.previewOffset),c.previewAnimation&&(i["--player-preview-animation"]=c.previewAnimation),c.previewOpacity&&(i["--player-preview-opacity"]=c.previewOpacity),c.previewBlur&&(i["--player-preview-blur"]=c.previewBlur),c.previewArrowColor&&(i["--player-preview-arrow-color"]=c.previewArrowColor),c.previewArrowSize&&(i["--player-preview-arrow-size"]=c.previewArrowSize),c.previewArrowVisible&&(i["--player-preview-arrow-visible"]=c.previewArrowVisible),c.previewTransition&&(i["--player-preview-transition"]=c.previewTransition),c.previewZIndex&&(i["--player-preview-z-index"]=c.previewZIndex),c.previewPadding&&(i["--player-preview-padding"]=c.previewPadding),c.previewSpacing&&(i["--player-preview-spacing"]=c.previewSpacing),c.previewBackdropFilter&&(i["--player-preview-backdrop-filter"]=c.previewBackdropFilter),c.previewVerticalWidth&&(i["--player-preview-vertical-width"]=c.previewVerticalWidth),c.previewVerticalHeight&&(i["--player-preview-vertical-height"]=c.previewVerticalHeight),c.customVariables)for(const[s,r]of Object.entries(c.customVariables))typeof r=="string"&&(i[s]=r);return i}class Vr{constructor(e){this.providers=new Map,this.mainProvider=null,this.pendingTasks=[],this.activeIdleCallbackId=null,this.host=e}getProvider(e){return this.providers.get(e)}setProviderForSource(e,t){this.providers.set(e,t)}getMainProvider(){return this.mainProvider}setMainProvider(e){this.mainProvider=e}getCachedPosterForSource(e){if(!e)return null;const t=this.providers.get(e);if(!t)return null;if(typeof t.getNearestCachedThumbnail=="function"){const i=t.getNearestCachedThumbnail(0);if(i&&i.url&&Math.abs((i.time||0)-0)<1)return i.url}if(typeof t.getThumbnail=="function"){const i=t.getThumbnail(0,"low");if(i&&!(i instanceof Promise)&&i.url)return i.url}if(t.video instanceof HTMLVideoElement&&t.video.readyState>=2)try{const i=document.createElement("canvas");i.width=t.video.videoWidth||320,i.height=t.video.videoHeight||180;const s=i.getContext("2d");if(s)return s.drawImage(t.video,0,0,i.width,i.height),i.toDataURL("image/jpeg",.8)}catch(i){console.warn("Failed to draw hidden video frame for fallback poster:",i)}return null}cancelPendingPreloads(){this.activeIdleCallbackId!==null&&(typeof window.cancelIdleCallback=="function"?window.cancelIdleCallback(this.activeIdleCallbackId):window.clearTimeout(this.activeIdleCallbackId),this.activeIdleCallbackId=null),this.pendingTasks=[]}trigger(){this.cancelPendingPreloads();const e=this.host.playerState;if(this.host.isVisualTransitioning||!e||e.status==="idle"||e.status==="loading")return;const t=this.host.controller;if(!t)return;const i=t.getThumbnailProvider();if(!i)return;if(this.mainProvider=i,!e.playlist||e.playlist.length<=1){const f=e.currentSource;for(const[p,g]of this.providers.entries())p!==f&&(this.destroyProvider(g,i,"unused provider"),this.providers.delete(p));return}const s=(e.activePlaylistIndex+1)%e.playlist.length,r=(e.activePlaylistIndex-1+e.playlist.length)%e.playlist.length,a=e.playlist[s],n=e.playlist[r],l=e.currentSource,o=(a==null?void 0:a.src)||"",d=(n==null?void 0:n.src)||"",h=new Set;l&&h.add(l),o&&h.add(o),d&&h.add(d);for(const[f,p]of this.providers.entries())h.has(f)||(this.destroyProvider(p,i,"evicted provider"),this.providers.delete(f));l&&!this.providers.has(l)&&this.providers.set(l,i);const u=[];o&&o!==l&&u.push({source:a,url:o}),d&&d!==l&&d!==o&&u.push({source:n,url:d});for(const f of u){let p=this.providers.get(f.url);if(!p)try{const g=i.constructor;p=new g,typeof p.setSource=="function"&&p.setSource(f.url),this.providers.set(f.url,p)}catch(g){console.debug("[Player] Failed to instantiate thumbnail provider for preload:",g);continue}if(f.source.chapters&&f.source.chapters.length>0)for(const g of f.source.chapters)this.pendingTasks.push({provider:p,time:g.startTime,source:f.source,isInitial:!1});this.pendingTasks.push({provider:p,time:0,source:f.source,isInitial:!0})}this.pendingTasks.length>0&&this.scheduleNextPreloadTask()}destroy(){this.cancelPendingPreloads();for(const e of this.providers.values())this.destroyProvider(e,this.mainProvider,"provider on disconnect");this.providers.clear(),this.mainProvider=null}destroyProvider(e,t,i){if(e!==t&&e&&typeof e.destroy=="function")try{e.destroy()}catch(s){console.debug(`[Player] Error destroying ${i}:`,s)}}scheduleNextPreloadTask(){if(this.activeIdleCallbackId!==null||this.pendingTasks.length===0)return;const e=typeof window.requestIdleCallback=="function"?t=>window.requestIdleCallback(t):t=>window.setTimeout(()=>t(void 0),50);this.activeIdleCallbackId=e(t=>{this.activeIdleCallbackId=null,this.runPreloadTask(t)})}async runPreloadTask(e){const t=()=>typeof(e==null?void 0:e.timeRemaining)=="function"?e.timeRemaining():10;for(;this.pendingTasks.length>0&&(t()>0||e!=null&&e.didTimeout);){const i=this.pendingTasks.shift();if(!i)break;const{provider:s,time:r,source:a,isInitial:n}=i;if(Array.from(this.providers.values()).includes(s))try{const o=s.getThumbnail(r,"low");o instanceof Promise&&await o,n&&this.expandPreloadTasksForProvider(s,a)}catch(o){console.warn("[Player] Error preloading thumbnail:",o)}}this.pendingTasks.length>0&&this.scheduleNextPreloadTask()}expandPreloadTasksForProvider(e,t){if(!t.src||e._preloadedIntervalsAdded)return;e._preloadedIntervalsAdded=!0;const s=new Set,r=e.video;if(r&&r instanceof HTMLVideoElement&&!isNaN(r.duration)&&r.duration>0){const n=r.duration,l=10;for(let o=1;o<l;o++)s.add(Math.round(o/l*n))}else{const n=[10,20,30,45,60,90,120,180,240,300];for(const l of n)s.add(l)}const a=this.pendingTasks.filter(n=>n.provider===e).map(n=>n.time);for(const n of s){const l=typeof e.getNearestCachedThumbnail=="function"?e.getNearestCachedThumbnail(n):null;!(!!l&&Math.abs((l.time||0)-n)<1)&&!a.includes(n)&&this.pendingTasks.push({provider:e,time:n,source:t,isInitial:!1})}}}class zr{constructor(e){this.direction="next",this.abortController=null,this.activeUrl="",this.host=e}setDirection(e){this.direction=e}getDirection(){return this.direction}cancel(e){var t;if(this.abortController){if(e&&this.activeUrl===e)return;const i=(t=this.host.playerState)==null?void 0:t.currentSource;if(i&&this.activeUrl===i){this.abortController=null,this.activeUrl="";return}try{this.abortController.abort()}catch{}this.abortController=null}this.activeUrl=""}trigger(){const e=this.host.playerState;if(!e.playlist||e.playlist.length<=1){this.cancel();return}if(this.host.isVisualTransitioning){const l=this.direction==="next"?(e.activePlaylistIndex+1)%e.playlist.length:(e.activePlaylistIndex-1+e.playlist.length)%e.playlist.length,o=e.playlist[l],d=(o==null?void 0:o.src)||"";this.cancel(d);return}if(!e||e.status==="idle"||e.status==="loading"){this.cancel((e==null?void 0:e.currentSource)||void 0);return}const t=this.direction==="next"?(e.activePlaylistIndex+1)%e.playlist.length:(e.activePlaylistIndex-1+e.playlist.length)%e.playlist.length;if(t===e.activePlaylistIndex){this.cancel();return}const i=e.playlist[t],s=(i==null?void 0:i.src)||"";if(!s){this.cancel();return}if(this.activeUrl===s)return;this.cancel(),this.activeUrl=s,this.abortController=new AbortController;const r=this.abortController.signal;let a=i.type||"unknown";if(a==="unknown"){const l=s.split("?")[0].toLowerCase();l.endsWith(".m3u8")?a="hls":l.endsWith(".mpd")?a="dash":l.endsWith(".webm")?a="webm":l.endsWith(".mov")?a="mov":a="mp4"}(typeof window.requestIdleCallback=="function"?l=>window.requestIdleCallback(l):l=>window.setTimeout(l,50))(()=>{r.aborted||this.execute(s,a,r).catch(l=>{l&&l.name==="AbortError"||console.warn(`[Player] Prefetch uncaught rejection for ${s}:`,l)})})}async execute(e,t,i){try{if(t==="hls"||t==="dash"){const s=await fetch(e,{signal:i,headers:{Accept:"*/*"}}).catch(r=>{if(r&&r.name==="AbortError")return null;throw r});if(!s)return;s.ok||console.warn(`[Player] Manifest prefetch failed for ${t}: "${e}" (status ${s.status})`)}else if(t==="mp4"||t==="webm"||t==="mov"||t==="file")try{const s=await fetch(e,{signal:i}).catch(r=>{if(r&&r.name==="AbortError")return null;throw r});if(!s)return;if(s.ok&&s.body){const r=s.body.getReader();await r.read().catch(a=>{if(a&&a.name==="AbortError")return{done:!0,value:void 0};throw a}),await r.cancel().catch(()=>{})}else s.body?console.warn(`[Player] Cache warming failed for media: "${e}" (status ${s.status})`):console.warn(`[Player] Cache warming skipped for media: "${e}" (readable body not supported)`)}catch(s){if(s instanceof Error&&s.name==="AbortError"||!await fetch(e,{signal:i,mode:"no-cors"}).catch(a=>{if(a&&a.name==="AbortError")return null;throw a}))return}}catch(s){s instanceof Error&&s.name==="AbortError"||console.warn(`[Player] Error during source prefetch for "${e}":`,s)}finally{this.activeUrl===e&&(this.activeUrl="",this.abortController=null)}}}class _r{constructor(e){this.lastFocusedSettingsButton=null,this.open=(t="main")=>{this.host.settingsMenuOpen=!0,this.host.activeMenuScreen=t},this.close=()=>{this.host.settingsMenuOpen=!1},this.goTo=t=>{this.host.activeMenuScreen=t},this.backToMain=()=>{this.host.activeMenuScreen="main"},this.toggle=()=>{this.host.settingsMenuOpen=!this.host.settingsMenuOpen,this.host.activeMenuScreen="main",this.host.handleActivity(),this.host.settingsMenuOpen&&(this.lastFocusedSettingsButton=this.host.getDeepActiveElement(),setTimeout(()=>{var i;const t=(i=this.host.shadowRoot)==null?void 0:i.querySelector(".settings-menu .settings-item");t&&t.focus()},50))},this.handleItemKey=t=>{(t.key==="Enter"||t.key===" ")&&(t.preventDefault(),t.currentTarget.click())},this.host=e}get isOpen(){return this.host.settingsMenuOpen}get activeScreen(){return this.host.activeMenuScreen}getAriaLabel(){switch(this.host.activeMenuScreen){case"speed":return"Playback speed settings";case"quality":return"Video resolution settings";case"audio":return"Audio language settings";case"subtitles":return"Subtitles settings";default:return"Settings options"}}getSettingsButton(){var t,i;let e=(t=this.host.shadowRoot)==null?void 0:t.querySelector(".settings-btn");if(!e){const s=(i=this.host.shadowRoot)==null?void 0:i.querySelector("player-vertical-controls");s&&s.shadowRoot&&(e=s.shadowRoot.querySelector(".settings-btn"))}return e}handleKeyDown(e,t){var i;if(this.host.settingsMenuOpen){if(e.key==="Tab"){this.host.settingsMenuOpen=!1;const r=this.getSettingsButton();return r&&r.focus(),!0}const s=(i=this.host.shadowRoot)==null?void 0:i.querySelector(".settings-menu");if(s){const r=Array.from(s.querySelectorAll(".settings-header, .settings-item"));if(r.length>0){const a=r.findIndex(n=>n===t);if(e.key==="ArrowDown"){e.preventDefault(),e.stopPropagation();const n=a===-1?0:(a+1)%r.length;return r[n].focus(),this.host.handleActivity(),!0}else if(e.key==="ArrowUp"){e.preventDefault(),e.stopPropagation();const n=a===-1?r.length-1:(a-1+r.length)%r.length;return r[n].focus(),this.host.handleActivity(),!0}else if(e.key==="ArrowLeft"&&this.host.activeMenuScreen!=="main"){e.preventDefault(),e.stopPropagation();const n=this.host.activeMenuScreen;return this.backToMain(),setTimeout(()=>{const l=this.host.shadowRoot;if(l){const o=Array.from(l.querySelectorAll(".settings-menu .settings-item")),d=o.find(h=>{var f,p;const u=((p=(f=h.querySelector("span"))==null?void 0:f.textContent)==null?void 0:p.toLowerCase())||"";return n==="speed"?u.includes("speed"):n==="quality"?u.includes("quality"):n==="audio"?u.includes("audio"):n==="subtitles"?u.includes("subtitles"):n==="sleeptimer"?u.includes("sleep"):!1});d?d.focus():o[0]&&o[0].focus()}},50),this.host.handleActivity(),!0}}}}return e.key==="Escape"&&this.host.settingsMenuOpen?(e.preventDefault(),e.stopPropagation(),this.host.settingsMenuOpen=!1,!0):!1}closeIfOutside(e){if(!this.host.settingsMenuOpen)return;e.composedPath().some(s=>s instanceof Element&&(s.classList.contains("settings-menu")||s.classList.contains("settings-btn")))||(this.host.settingsMenuOpen=!1)}onScreenChanged(){this.host.settingsMenuOpen&&setTimeout(()=>{var t;const e=(t=this.host.shadowRoot)==null?void 0:t.querySelector(".settings-menu");if(e){const i=e.querySelector(".settings-header, .settings-item");i&&i.focus()}},50)}onOpenStateChanged(e){e===!0&&!this.host.settingsMenuOpen&&setTimeout(()=>{if(this.lastFocusedSettingsButton&&typeof this.lastFocusedSettingsButton.focus=="function")this.lastFocusedSettingsButton.focus();else{const t=this.getSettingsButton();t&&t.focus()}this.lastFocusedSettingsButton=null},50)}}class Hr{constructor(e){this.gestureState="IDLE",this.gestureStartX=0,this.gestureStartY=0,this.gestureLastTapTime=0,this.gestureSingleTapTimer=null,this.gestureLongPressTimer=null,this.gestureIsRightSide=!1,this.gestureStartVolume=0,this.gestureActiveDrag="NONE",this.gestureStartTimeVal=0,this.gestureLastTouchType=!1,this.isLongPressSpeedActiveInternal=!1,this.preLongPressPlaybackRate=1,this.touchStartY=0,this.touchStartX=0,this.touchDeltaY=0,this.isTouchActive=!1,this.lastFeedTransitionTime=0,this.isTransitionLockedInternal=!1,this.isDragPreviewActive=!1,this.dragPreviewDirection=null,this.dragPreviewCanvasHeight=0,this.dragCanvasEl=null,this.dragPreviewPending=!1,this.isTransitionAnimationFinished=!1,this.handleWheel=t=>{this.host.displayMode!=="vertical"||!this.host.playerState.playlist||this.host.playerState.playlist.length<=1||(t.preventDefault(),!(Math.abs(t.deltaY)<10)&&(t.deltaY>0?this.throttleTransition(()=>this.host.next()):t.deltaY<0&&this.throttleTransition(()=>this.host.previous())))},this.handleVideoTouchStart=t=>{if(t.touches.length>1)return;const i=t.touches[0];this.handleVideoDown(i.clientX,i.clientY,!0,t)},this.handleVideoTouchMove=t=>{if(t.touches.length>1)return;const i=t.touches[0];this.handleVideoMove(i.clientX,i.clientY,!0,t),(this.gestureState==="LONG_PRESS"||this.gestureState==="SWIPE")&&t.cancelable&&t.preventDefault()},this.handleVideoTouchEnd=t=>{const i=t.changedTouches[0];i&&this.handleVideoUp(i.clientX,i.clientY,!0,t),t.cancelable&&t.preventDefault()},this.handleVideoTouchCancel=t=>{this.gestureLongPressTimer&&(clearTimeout(this.gestureLongPressTimer),this.gestureLongPressTimer=null),this.gestureState="IDLE"},this.handleVideoMouseDown=t=>{t.button===0&&this.handleVideoDown(t.clientX,t.clientY,!1,t)},this.handleVideoMouseMove=t=>{this.handleVideoMove(t.clientX,t.clientY,!1,t)},this.handleVideoMouseUp=t=>{t.button===0&&this.handleVideoUp(t.clientX,t.clientY,!1,t)},this.handleVideoMouseLeave=t=>{this.gestureLongPressTimer&&(clearTimeout(this.gestureLongPressTimer),this.gestureLongPressTimer=null),this.gestureState==="LONG_PRESS"&&this.triggerLongPressEnd(t),this.gestureState="IDLE"},this.handleTouchStart=t=>{var a,n,l,o,d;if(this.gestureState==="LONG_PRESS"||this.isLongPressSpeedActiveInternal)return;const i=((l=(n=(a=this.host.config)==null?void 0:a.vertical)==null?void 0:n.gestures)==null?void 0:l.swipeToNavigate)!==!1,s=((d=(o=this.host.config)==null?void 0:o.vertical)==null?void 0:d.snapBehavior)!=="none";if(this.host.displayMode!=="vertical"||!i||!s||!this.host.playerState.playlist||this.host.playerState.playlist.length<=1||this.isTouchOnInteractiveElement(t))return;const r=t.touches[0];this.touchStartY=r.clientY,this.touchStartX=r.clientX,this.touchDeltaY=0,this.isTouchActive=!0,this.host.handleActivity()},this.handleTouchMove=t=>{var o,d,h,u,f;if(this.gestureState==="LONG_PRESS"||this.isLongPressSpeedActiveInternal){t.cancelable&&t.preventDefault();return}const i=((h=(d=(o=this.host.config)==null?void 0:o.vertical)==null?void 0:d.gestures)==null?void 0:h.swipeToNavigate)!==!1,s=((f=(u=this.host.config)==null?void 0:u.vertical)==null?void 0:f.snapBehavior)!=="none";if(this.host.displayMode!=="vertical"||!i||!s||!this.host.playerState.playlist||this.host.playerState.playlist.length<=1||this.isTouchOnInteractiveElement(t))return;const r=t.touches[0],a=r.clientY-this.touchStartY,n=r.clientX-this.touchStartX;this.touchDeltaY=a;const l=Math.abs(a)>Math.abs(n)&&Math.abs(a)>5;l&&t.cancelable&&t.preventDefault(),this.isDragPreviewActive?this.updateDragPreview(a):l&&Math.abs(a)>10&&!this.isTransitionLockedInternal&&this.beginDragPreview(a<0?"next":"prev"),this.host.handleActivity()},this.handleTouchEnd=()=>{var l,o,d,h,u,f,p;if(this.gestureState==="LONG_PRESS"||this.isLongPressSpeedActiveInternal)return;const t=((d=(o=(l=this.host.config)==null?void 0:l.vertical)==null?void 0:o.gestures)==null?void 0:d.swipeToNavigate)!==!1,i=((u=(h=this.host.config)==null?void 0:h.vertical)==null?void 0:u.snapBehavior)!=="none";if(this.host.displayMode!=="vertical"||!t||!i||!this.host.playerState.playlist||this.host.playerState.playlist.length<=1)return;const s=((p=(f=this.host.config)==null?void 0:f.vertical)==null?void 0:p.swipeThreshold)??50,r=this.touchDeltaY,a=r<-s,n=r>s;if(this.isDragPreviewActive){const g=this.dragPreviewDirection;g==="next"&&a?(this.lastFeedTransitionTime=Date.now(),this.completeDragPreview("next")):g==="prev"&&n?(this.lastFeedTransitionTime=Date.now(),this.completeDragPreview("prev")):this.cancelDragPreview()}else a?this.throttleTransition(()=>this.host.next()):n&&this.throttleTransition(()=>this.host.previous());this.touchStartY=0,this.touchStartX=0,this.touchDeltaY=0,this.isTouchActive=!1},this.host=e}get isLongPressSpeedActive(){return this.isLongPressSpeedActiveInternal}get isTransitionLocked(){return this.isTransitionLockedInternal}attach(){const e=this.host;e.addEventListener("wheel",this.handleWheel,{passive:!1});const t=e.videoElement;t&&(t.addEventListener("mousedown",this.handleVideoMouseDown),t.addEventListener("mousemove",this.handleVideoMouseMove),t.addEventListener("mouseup",this.handleVideoMouseUp),t.addEventListener("mouseleave",this.handleVideoMouseLeave),t.addEventListener("touchstart",this.handleVideoTouchStart,{passive:!1}),t.addEventListener("touchmove",this.handleVideoTouchMove,{passive:!1}),t.addEventListener("touchend",this.handleVideoTouchEnd,{passive:!1}),t.addEventListener("touchcancel",this.handleVideoTouchCancel,{passive:!1})),e.addEventListener("touchstart",this.handleTouchStart,{passive:!1}),e.addEventListener("touchmove",this.handleTouchMove,{passive:!1}),e.addEventListener("touchend",this.handleTouchEnd,{passive:!0})}detach(){const e=this.host;e.removeEventListener("wheel",this.handleWheel),e.removeEventListener("touchstart",this.handleTouchStart),e.removeEventListener("touchmove",this.handleTouchMove),e.removeEventListener("touchend",this.handleTouchEnd);const t=e.videoElement;t&&(t.removeEventListener("mousedown",this.handleVideoMouseDown),t.removeEventListener("mousemove",this.handleVideoMouseMove),t.removeEventListener("mouseup",this.handleVideoMouseUp),t.removeEventListener("mouseleave",this.handleVideoMouseLeave),t.removeEventListener("touchstart",this.handleVideoTouchStart),t.removeEventListener("touchmove",this.handleVideoTouchMove),t.removeEventListener("touchend",this.handleVideoTouchEnd),t.removeEventListener("touchcancel",this.handleVideoTouchCancel)),this.gestureSingleTapTimer&&(clearTimeout(this.gestureSingleTapTimer),this.gestureSingleTapTimer=null),this.gestureLongPressTimer&&(clearTimeout(this.gestureLongPressTimer),this.gestureLongPressTimer=null)}drawFrame(e,t,i,s,r){let a=0,n=0;if(t instanceof HTMLVideoElement?(a=t.videoWidth,n=t.videoHeight):t instanceof HTMLImageElement&&(a=t.naturalWidth,n=t.naturalHeight),a===0||n===0){e.fillStyle="#000000",e.fillRect(0,i,s,r);return}const l=a/n,o=s/r;let d=s,h=r,u=0,f=i;l>o?(h=s/l,f=i+(r-h)/2):(d=r*l,u=(s-d)/2),e.fillStyle="#000000",e.fillRect(0,i,s,r),e.drawImage(t,u,f,d,h)}prepareTransitionFrames(e){var p,g,m;const t=this.host.videoElement;if(!t)return null;const i=(p=this.host.shadowRoot)==null?void 0:p.querySelector(".transition-canvas");if(!i)return null;const s=((m=(g=this.host.shadowRoot)==null?void 0:g.querySelector(".video-wrapper"))==null?void 0:m.getBoundingClientRect())||t.getBoundingClientRect(),r=Math.round(s.width)||360,a=Math.round(s.height)||640;(i.width!==r||i.height!==a*2)&&(i.width=r,i.height=a*2);const n=i.getContext("2d"),l=e==="next"?0:a,o=e==="next"?a:0;n&&(t.readyState>=2?this.drawFrame(n,t,l,r,a):(n.fillStyle="#000000",n.fillRect(0,l,r,a)));let d="";if(this.host.playerState.playlist&&this.host.playerState.playlist.length>1){const v=e==="next"?(this.host.playerState.activePlaylistIndex+1)%this.host.playerState.playlist.length:(this.host.playerState.activePlaylistIndex-1+this.host.playerState.playlist.length)%this.host.playerState.playlist.length,y=this.host.playerState.playlist[v];d=(y==null?void 0:y.src)||""}const h=this.host.thumbnailCache.getProvider(d),u=h==null?void 0:h.video,f=this.host.thumbnailCache.getCachedPosterForSource(d);if(f&&this.host.isOverlayEnabled("poster")?t.setAttribute("poster",f):t.removeAttribute("poster"),n){const v=y=>{try{this.drawFrame(n,y,o,r,a)}catch(b){console.warn("Failed to draw incoming frame onto canvas:",b)}};if(u&&u.readyState>=2)v(u);else if(f){const y=new Image;y.onload=()=>{v(y)},y.src=f,y.complete?v(y):(n.fillStyle="#000000",n.fillRect(0,o,r,a))}else n.fillStyle="#000000",n.fillRect(0,o,r,a)}return{domCanvas:i,canvasHeight:a}}initiateVisualTransition(e,t){if(this.host.displayMode!=="vertical"){t();return}if(!this.host.videoElement){t();return}const i=this.prepareTransitionFrames(e);if(!i){t();return}const{domCanvas:s}=i;this.isTransitionLockedInternal=!0;const r=this.host.playerState.isPlaying||this.host.playerState.status==="ended";this.host.shouldAutoplayAfterTransition=r,this.host.suppressPlayPauseFeedback=r,this.host.transitionDirection=e,this.host.isVisualTransitioning=!0,this.host.transitionStage="start",this.isTransitionAnimationFinished=!1,this.host.updateComplete.then(()=>{const a=l=>{l.propertyName==="transform"&&l.target===s&&(s.removeEventListener("transitionend",a),this.onTransitionAnimationEnd())},n=setTimeout(()=>{s.removeEventListener("transitionend",a),this.onTransitionAnimationEnd()},700);s.addEventListener("transitionend",a),this.cleanupTransitionListeners=()=>{clearTimeout(n),s.removeEventListener("transitionend",a)},requestAnimationFrame(()=>{requestAnimationFrame(()=>{this.host.transitionStage="active",t()})})})}onTransitionAnimationEnd(){this.isTransitionAnimationFinished=!0,this.checkTransitionCompletion()}checkTransitionCompletion(){var a,n;if(!this.isTransitionAnimationFinished)return;const e=this.host.videoElement;if(!e){this.endVisualTransition();return}const t=(a=this.host.playerState)==null?void 0:a.status,i=(n=this.host.playerState)==null?void 0:n.sourceType,s=e.error||t==="error";if(e.readyState>=2||s||t==="idle"||i==="embed")this.endVisualTransition();else{const l=()=>{e.removeEventListener("loadeddata",l),e.removeEventListener("playing",l),e.removeEventListener("canplay",l),e.removeEventListener("error",l),e.removeEventListener("emptied",l),this.checkTransitionCompletion()};e.addEventListener("loadeddata",l),e.addEventListener("playing",l),e.addEventListener("canplay",l),e.addEventListener("error",l),e.addEventListener("emptied",l),this.cleanupReadyListener=()=>{e.removeEventListener("loadeddata",l),e.removeEventListener("playing",l),e.removeEventListener("canplay",l),e.removeEventListener("error",l),e.removeEventListener("emptied",l)}}}endVisualTransition(){var t;this.cleanupTransitionListeners&&(this.cleanupTransitionListeners(),this.cleanupTransitionListeners=void 0),this.cleanupReadyListener&&(this.cleanupReadyListener(),this.cleanupReadyListener=void 0),this.isTransitionAnimationFinished=!1,this.host.isVisualTransitioning=!1,this.host.transitionStage="idle",this.isTransitionLockedInternal=!1,this.isDragPreviewActive=!1,this.dragPreviewDirection=null;const e=this.dragCanvasEl||((t=this.host.shadowRoot)==null?void 0:t.querySelector(".transition-canvas"));e&&(e.style.transform="",e.style.transition=""),this.dragCanvasEl=null,this.host.videoElement&&this.host.videoElement.removeAttribute("poster"),this.host.shouldAutoplayAfterTransition&&(this.host.controller&&this.host.controller.play(),setTimeout(()=>{this.host.shouldAutoplayAfterTransition=!1,this.host.requestUpdate()},150)),this.host.thumbnailCache.trigger(),this.host.prefetch.trigger()}throttleTransition(e){const t=Date.now();t-this.lastFeedTransitionTime>=800&&(this.lastFeedTransitionTime=t,e())}beginDragPreview(e){if(this.isTransitionLockedInternal||this.isDragPreviewActive||this.dragPreviewPending||this.host.displayMode!=="vertical"||!this.host.videoElement||!this.host.playerState.playlist||this.host.playerState.playlist.length<=1)return;this.dragPreviewPending=!0;const t=this.host.playerState.isPlaying||this.host.playerState.status==="ended";this.host.shouldAutoplayAfterTransition=t,this.host.suppressPlayPauseFeedback=t,this.host.transitionDirection=e,this.host.isVisualTransitioning=!0,this.host.transitionStage="idle",this.host.updateComplete.then(()=>{if(this.dragPreviewPending=!1,!this.isTouchActive){this.host.isVisualTransitioning=!1;return}const i=this.prepareTransitionFrames(e);if(!i){this.host.isVisualTransitioning=!1;return}this.dragCanvasEl=i.domCanvas,this.dragPreviewCanvasHeight=i.canvasHeight,this.dragPreviewDirection=e,this.isDragPreviewActive=!0,this.dragCanvasEl.style.transition="none",this.updateDragPreview(this.touchDeltaY)})}updateDragPreview(e){if(!this.isDragPreviewActive||!this.dragCanvasEl||!this.dragPreviewDirection)return;const t=this.dragPreviewCanvasHeight,i=this.dragPreviewDirection==="next"?Math.max(-t,Math.min(0,e)):Math.max(-t,Math.min(0,-t+e));this.dragCanvasEl.style.transform=`translateY(${i}px)`}completeDragPreview(e){const t=this.dragCanvasEl,i=this.dragPreviewCanvasHeight;if(this.isDragPreviewActive=!1,this.dragPreviewDirection=null,!t){this.host.isVisualTransitioning=!1;return}this.isTransitionLockedInternal=!0,this.host.prefetch.setDirection(e),this.isTransitionAnimationFinished=!1;const s=e==="next"?-i:0,r="var(--player-vertical-transition-duration, 0.6s)",a="var(--player-vertical-transition-easing, cubic-bezier(0.16, 1, 0.3, 1))";t.style.transition=`transform ${r} ${a}`,t.offsetHeight,requestAnimationFrame(()=>{t.style.transform=`translateY(${s}px)`}),e==="next"?this.host.controller.next():this.host.controller.previous();const n=o=>{o.propertyName==="transform"&&o.target===t&&(t.removeEventListener("transitionend",n),this.onTransitionAnimationEnd())},l=setTimeout(()=>{t.removeEventListener("transitionend",n),this.onTransitionAnimationEnd()},700);t.addEventListener("transitionend",n),this.cleanupTransitionListeners=()=>{clearTimeout(l),t.removeEventListener("transitionend",n)}}cancelDragPreview(){const e=this.dragCanvasEl;if(this.isDragPreviewActive=!1,this.dragPreviewDirection=null,!e){this.host.isVisualTransitioning=!1;return}const t="var(--player-vertical-transition-duration, 0.6s)",i="var(--player-vertical-transition-easing, cubic-bezier(0.16, 1, 0.3, 1))";e.style.transition=`transform ${t} ${i}`,requestAnimationFrame(()=>{e.style.transform="translateY(0px)"});const s=()=>{e.removeEventListener("transitionend",r),clearTimeout(a),this.host.isVisualTransitioning=!1,this.host.transitionStage="idle",e.style.transform="",e.style.transition="",this.dragCanvasEl=null,this.host.videoElement&&this.host.videoElement.removeAttribute("poster")},r=n=>{n.propertyName==="transform"&&n.target===e&&s()},a=setTimeout(s,300);e.addEventListener("transitionend",r)}handleVideoDown(e,t,i,s){var l,o;if(i&&this.isTouchOnInteractiveElement(s))return;if(this.gestureLastTouchType=i,this.gestureLongPressTimer&&(clearTimeout(this.gestureLongPressTimer),this.gestureLongPressTimer=null),this.gestureState="DOWN",this.gestureStartX=e,this.gestureStartY=t,this.host.videoElement){const d=this.host.videoElement.getBoundingClientRect();this.gestureIsRightSide=e-d.left>d.width/2}else this.gestureIsRightSide=!1;this.gestureStartVolume=this.host.playerState.volume||0,this.gestureStartTimeVal=this.host.playerState.currentTime||0,this.gestureActiveDrag="NONE";const r=(o=(l=this.host.config)==null?void 0:l.vertical)==null?void 0:o.gestures,a=this.host.displayMode==="vertical";((r==null?void 0:r.longPressToSpeed)??a)&&!this.host.playerState.isLive&&(this.gestureLongPressTimer=window.setTimeout(()=>{if(this.gestureState="LONG_PRESS",this.isLongPressSpeedActiveInternal=!0,this.host.isSpeedOverlayFadingOut=!1,this.host.speedLockState==="LOCKED")this.host.speedLockState="LOCKED_HOLDING",this.host.activeSpeedFeedback=this.host.playerState.playbackRate||2,this.host.requestUpdate();else{this.preLongPressPlaybackRate=this.host.playerState.playbackRate||1;const d=(r==null?void 0:r.longPressSpeed)||2;this.host.controller.setPlaybackRate(d),this.host.speedLockState="HOLDING",this.host.activeSpeedFeedback=d,this.host.requestUpdate()}},500))}handleVideoMove(e,t,i,s){const r=e-this.gestureStartX,a=t-this.gestureStartY;if(this.gestureState==="DOWN"&&Math.hypot(r,a)>10)if(Math.abs(r)>Math.abs(a))this.gestureState="SWIPE",this.gestureActiveDrag="HORIZONTAL",this.gestureLongPressTimer&&(clearTimeout(this.gestureLongPressTimer),this.gestureLongPressTimer=null);else if(this.host.displayMode==="vertical"){this.gestureState="IDLE",this.gestureActiveDrag="NONE",this.gestureLongPressTimer&&(clearTimeout(this.gestureLongPressTimer),this.gestureLongPressTimer=null);return}else this.gestureState="SWIPE",this.gestureActiveDrag="VERTICAL",this.gestureLongPressTimer&&(clearTimeout(this.gestureLongPressTimer),this.gestureLongPressTimer=null);if(this.gestureState==="SWIPE"){if(this.gestureActiveDrag==="HORIZONTAL"){if(this.host.videoElement&&this.host.playerState.duration>0&&!this.host.playerState.isLive){const n=this.host.videoElement.getBoundingClientRect(),l=r/n.width,o=Math.min(90,this.host.playerState.duration),d=l*o,h=Math.max(0,Math.min(this.host.playerState.duration,this.gestureStartTimeVal+d));this.host.controller.seek(h),this.host.handleActivity()}}else if(this.gestureActiveDrag==="VERTICAL")if(this.gestureIsRightSide){if(this.host.videoElement){const n=this.host.videoElement.getBoundingClientRect(),l=-(a/n.height),o=Math.max(0,Math.min(1,this.gestureStartVolume+l));this.host.controller.setVolume(o),this.host.handleActivity()}}else this.host.handleActivity()}else this.gestureState==="LONG_PRESS"&&(this.host.speedLockState==="HOLDING"?a>40&&(this.host.speedLockState="READY_TO_LOCK",this.host.requestUpdate()):this.host.speedLockState==="READY_TO_LOCK"?a<=40&&(this.host.speedLockState="HOLDING",this.host.requestUpdate()):this.host.speedLockState==="LOCKED_HOLDING"?a>40&&(this.host.speedLockState="READY_TO_UNLOCK",this.host.requestUpdate()):this.host.speedLockState==="READY_TO_UNLOCK"&&a<=40&&(this.host.speedLockState="LOCKED_HOLDING",this.host.requestUpdate()))}handleVideoUp(e,t,i,s){this.gestureLongPressTimer&&(clearTimeout(this.gestureLongPressTimer),this.gestureLongPressTimer=null);const r=this.gestureState;if(this.gestureState="IDLE",r==="LONG_PRESS")this.triggerLongPressEnd(s);else if(r==="SWIPE")this.host.handleActivity();else if(r==="DOWN"){const a=Date.now(),n=a-this.gestureLastTapTime;n<300&&n>0?(this.gestureSingleTapTimer&&(clearTimeout(this.gestureSingleTapTimer),this.gestureSingleTapTimer=null),this.gestureLastTapTime=0,this.triggerDoubleTap(e,s)):(this.gestureLastTapTime=a,this.gestureSingleTapTimer=window.setTimeout(()=>{this.gestureSingleTapTimer=null,this.triggerSingleTap()},250))}}triggerLongPressEnd(e){var t,i;this.isLongPressSpeedActiveInternal&&((i=(t=this.host.config)==null?void 0:t.vertical)==null||i.gestures,this.host.speedLockState==="HOLDING"?(this.host.controller.setPlaybackRate(this.preLongPressPlaybackRate),this.host.isSpeedOverlayFadingOut=!0,this.host.requestUpdate(),this.host.speedFeedbackTimer&&clearTimeout(this.host.speedFeedbackTimer),this.host.speedFeedbackTimer=window.setTimeout(()=>{this.host.activeSpeedFeedback=null,this.host.speedLockState="IDLE",this.host.isSpeedOverlayFadingOut=!1,this.host.requestUpdate()},250)):this.host.speedLockState==="READY_TO_LOCK"?(this.host.speedLockState="LOCKED",this.host.activeSpeedFeedback=this.host.playerState.playbackRate||2,this.host.isSpeedOverlayFadingOut=!1,this.host.requestUpdate(),this.host.speedFeedbackTimer&&clearTimeout(this.host.speedFeedbackTimer),this.host.speedFeedbackTimer=window.setTimeout(()=>{this.host.isSpeedOverlayFadingOut=!0,this.host.requestUpdate(),this.host.speedFeedbackTimer=window.setTimeout(()=>{this.host.activeSpeedFeedback=null,this.host.isSpeedOverlayFadingOut=!1,this.host.requestUpdate()},250)},1e3)):this.host.speedLockState==="LOCKED_HOLDING"?(this.host.speedLockState="LOCKED",this.host.activeSpeedFeedback=this.host.playerState.playbackRate||2,this.host.isSpeedOverlayFadingOut=!1,this.host.requestUpdate(),this.host.speedFeedbackTimer&&clearTimeout(this.host.speedFeedbackTimer),this.host.speedFeedbackTimer=window.setTimeout(()=>{this.host.isSpeedOverlayFadingOut=!0,this.host.requestUpdate(),this.host.speedFeedbackTimer=window.setTimeout(()=>{this.host.activeSpeedFeedback=null,this.host.isSpeedOverlayFadingOut=!1,this.host.requestUpdate()},250)},1e3)):this.host.speedLockState==="READY_TO_UNLOCK"&&(this.host.controller.setPlaybackRate(this.preLongPressPlaybackRate),this.host.isSpeedOverlayFadingOut=!0,this.host.requestUpdate(),this.host.speedFeedbackTimer&&clearTimeout(this.host.speedFeedbackTimer),this.host.speedFeedbackTimer=window.setTimeout(()=>{this.host.activeSpeedFeedback=null,this.host.speedLockState="IDLE",this.host.isSpeedOverlayFadingOut=!1,this.host.requestUpdate()},250)),setTimeout(()=>{this.isLongPressSpeedActiveInternal=!1,this.host.requestUpdate()},50))}triggerSingleTap(){var e,t,i,s;if(!this.isLongPressSpeedActiveInternal){if(this.host.settingsMenu.isOpen){this.host.settingsMenu.close();return}if(!(((t=(e=this.host.config)==null?void 0:e.controls)==null?void 0:t.play)===!1||((s=(i=this.host.config)==null?void 0:i.controls)==null?void 0:s.playButton)===!1)){if(this.host.playerState.status==="ended"&&!this.host.playerState.isLive&&this.host.displayMode!=="vertical"){this.host.handleReplay();return}this.host.controller.togglePlay(),this.host.handleActivity()}}}triggerDoubleTap(e,t){var l,o,d,h,u,f,p;if(((o=(l=this.host.config)==null?void 0:l.controls)==null?void 0:o.seekbar)===!1||this.host.playerState.isLive&&!this.host.playerState.canSeekInDvr||!(this.host.displayMode==="vertical"?((u=(h=(d=this.host.config)==null?void 0:d.vertical)==null?void 0:h.gestures)==null?void 0:u.doubleTapToSeek)!==!1:!0))return;const r=this.host.videoElement.getBoundingClientRect(),a=e-r.left,n=((p=(f=this.host.config)==null?void 0:f.playback)==null?void 0:p.doubleTapInterval)||10;a<r.width/2?(this.host.controller.seekBy(-n),this.host.showFeedbackOverlay("rewind")):(this.host.controller.seekBy(n),this.host.showFeedbackOverlay("fastforward")),this.host.handleActivity()}isTouchOnInteractiveElement(e){return(typeof e.composedPath=="function"?e.composedPath():[]).some(i=>{if(!(i instanceof Element))return!1;const s=i.tagName.toLowerCase(),r=i.getAttribute?i.getAttribute("role"):null,a=i.classList;return s==="button"||s==="player-seekbar"||s==="player-vertical-controls"||r==="button"||r==="menuitem"||r==="menuitemradio"||a&&(a.contains("controls-bar")||a.contains("settings-menu")||a.contains("settings-menu-wrapper")||a.contains("sleep-timer-dialog-card"))})}}var qr=Object.defineProperty,W=(c,e,t,i)=>{for(var s=void 0,r=c.length-1,a;r>=0;r--)(a=c[r])&&(s=a(e,t,s)||s);return s&&qr(e,t,s),s};const ns=[{value:"default",label:"Default"},{value:"proportional-sans-serif",label:"Proportional Sans-Serif"},{value:"monospace-sans-serif",label:"Monospace Sans-Serif"},{value:"proportional-serif",label:"Proportional Serif"},{value:"monospace-serif",label:"Monospace Serif"},{value:"casual",label:"Casual"},{value:"cursive",label:"Cursive"},{value:"small-capitals",label:"Small Capitals"}],He=[{value:"white",label:"White"},{value:"black",label:"Black"},{value:"red",label:"Red"},{value:"green",label:"Green"},{value:"blue",label:"Blue"},{value:"yellow",label:"Yellow"},{value:"magenta",label:"Magenta"},{value:"cyan",label:"Cyan"}],os=[{value:50,label:"50%"},{value:75,label:"75%"},{value:100,label:"100%"},{value:125,label:"125%"},{value:150,label:"150%"},{value:175,label:"175%"},{value:200,label:"200%"},{value:300,label:"300%"},{value:400,label:"400%"}],qe=[{value:0,label:"0%"},{value:25,label:"25%"},{value:50,label:"50%"},{value:75,label:"75%"},{value:100,label:"100%"}],ls=[{value:"none",label:"None"},{value:"raised",label:"Raised"},{value:"depressed",label:"Depressed"},{value:"uniform",label:"Uniform"},{value:"drop-shadow",label:"Drop Shadow"}],Kr=[.25,.5,.75,1,1.25,1.5,1.75,2,2.5,3,4],Wr=[.5,1,2];function jr(c){const e=new Map;for(const t of c)if(t.includes("-"))for(const i of[t.replace(/-/g,""),t.replace(/-/g,"_")])i!==t&&!c.includes(i)&&e.set(i,t);return e}function Gr(c){if(c===null)return;const e=c.trim();if(e!==""){if(e.startsWith("[object ")){console.warn(`[streamit-player] The "config" attribute received a stringified object ("${e}") and has been ignored. Pass config as a DOM property (element.config = {...}, or .config=\${...} / :config="..." in a framework template) rather than as an attribute.`);return}try{return JSON.parse(e)}catch{console.warn('[streamit-player] The "config" attribute is not valid JSON and has been ignored. Pass config as a DOM property instead.');return}}}const ni=class ni extends ge{constructor(){super(...arguments),this.src="",this.captions="",this.autoplay=!1,this.muted=!1,this.volume=1,this.displayMode="standard",this.nearEndThreshold=1,this.autoScroll=!1,this.liveMode="live-dvr",this.preload="metadata",this.loop=!1,this.playsinline=!0,this.poster="",this.isFeedTransitioning=!1,this.iconRegistry=new ss,this.customControls=new Map,this.customOverlays=new Map,this.isVisualTransitioning=!1,this.transitionDirection="next",this.transitionStage="idle",this.shouldAutoplayAfterTransition=!1,this.suppressPlayPauseFeedback=!1,this.contextMenuOpen=!1,this.contextMenuX=0,this.contextMenuY=0,this.isContextMenuDisabled=!1,this.customContextMenuItems=[],this.customSettingsItems=[],this.customSettingsScreens=new Map,this.playerState={status:"idle",isPlaying:!1,currentTime:0,duration:0,volume:1,isMuted:!1,isFullscreen:!1,bufferedRanges:[],playbackRate:1,captionsEnabled:!1,currentSource:null,sourceType:"unknown",isBuffering:!1,isSeeking:!1,hasCaptions:!1,error:null,qualities:[],activeQuality:"Auto",audioTracks:[],activeAudioTrack:-1,subtitleTracks:[],activeSubtitleTrack:-1,activeSubtitleTrackId:null,subtitleAppearance:{fontFamily:"default",fontSize:75,fontColor:"white",backgroundColor:"black",backgroundOpacity:75,windowColor:"black",windowOpacity:0,characterEdgeStyle:"none",fontOpacity:100},isLive:null,isLowLatency:!1,isAtLiveEdge:!1,liveLatency:null,hasDvr:!1,dvrWindow:0,canSeekInDvr:!1,seekableRange:{start:0,end:0},liveMode:"live-dvr",thumbnailProvider:void 0,pictureInPicture:!1,pictureInPictureSupported:!1,loop:!1,sleepTimerSetting:"off",sleepTimerSecondsRemaining:null,sleepTimerExpired:!1,chapters:[],activeChapterIndex:-1,markers:[],visibleMarkerTypes:null,displayMode:"standard",playlist:[],activePlaylistIndex:0,playlistRepeatMode:"off",autoScroll:!1,isAdPlaying:!1,isAdLoading:!1,currentAd:null,currentAdBreak:null,adCurrentTime:null,adRemainingTime:null,adDuration:null,canSkipAd:!1,skipAvailableAt:null,adPosition:null,adProvider:null,adLinear:null,adMuted:null},this.controlsVisible=!0,this.settingsMenuOpen=!1,this.activeMenuScreen="main",this.toastMessage="",this.toastType="info",this.toastVisible=!1,this.lastFocusedElement=null,this.tapFeedback=null,this.feedbackTaps=0,this.playPauseFeedback=null,this.activeVolumeFeedback=null,this.isSeekingInteraction=!1,this.activeSpeedFeedback=null,this.activeQualityFeedback=null,this.shouldShowQualityFeedback=!1,this.pendingSeekTime=null,this.lastTap=0,this.isDraggingSeekbar=!1,this.wasPlayingBeforeDrag=!1,this.isPreciseSeeking=!1,this.filmstripCenterTime=-1,this.speedLockState="IDLE",this.isSpeedOverlayFadingOut=!1,this.isVolumeFeedbackFadingOut=!1,this.filmstripThumbs=new Map,this.preciseSeekContainerWidth=1056,this.thumbnailCache=new Vr(this),this.prefetch=new zr(this),this.settingsMenu=new _r(this),this.gestures=new Hr(this),this.pendingListeners=[],this.handleResize=()=>{var e;if(this.isPreciseSeeking){const t=(e=this.shadowRoot)==null?void 0:e.querySelector(".precise-seek-container");t&&t.clientWidth>0&&this.preciseSeekContainerWidth!==t.clientWidth&&(this.preciseSeekContainerWidth=t.clientWidth,this.requestUpdate())}},this.handleKeyDown=e=>{var i,s;const t=this.getDeepActiveElement();if(this.displayMode==="vertical"&&this.playerState.playlist&&this.playerState.playlist.length>1&&t&&(this===t||((i=this.shadowRoot)==null?void 0:i.contains(t))||this.contains(t))){if(e.key==="ArrowDown"){e.preventDefault(),e.stopPropagation(),this.gestures.throttleTransition(()=>this.next());return}else if(e.key==="ArrowUp"){e.preventDefault(),e.stopPropagation(),this.gestures.throttleTransition(()=>this.previous());return}}if(this.playerState.sleepTimerExpired){const r=(s=this.shadowRoot)==null?void 0:s.querySelector(".sleep-timer-dialog-overlay");if(r){const a=Array.from(r.querySelectorAll(".sleep-timer-btn"));if(a.length>0){const n=a.findIndex(d=>d===t),l=e.key==="ArrowRight"||e.key==="ArrowDown"||e.key==="Tab"&&!e.shiftKey,o=e.key==="ArrowLeft"||e.key==="ArrowUp"||e.key==="Tab"&&e.shiftKey;if(l){e.preventDefault(),e.stopPropagation();const d=n===-1?0:(n+1)%a.length;a[d].focus();return}else if(o){e.preventDefault(),e.stopPropagation();const d=n===-1?a.length-1:(n-1+a.length)%a.length;a[d].focus();return}}}e.key==="Escape"&&(e.preventDefault(),e.stopPropagation(),this.handleSleepTimerClose());return}t&&(t.tagName==="INPUT"||t.tagName==="TEXTAREA"||t.tagName==="SELECT"||t.hasAttribute("contenteditable"))||this.settingsMenu.handleKeyDown(e,t)||e.key===" "&&t&&(t.tagName==="BUTTON"||t.getAttribute("role")==="button")||(this.controller.shortcuts.handleKeyDown(e),this.handleActivity())},this.handleActivity=()=>{var t,i,s;if((t=this.playerState)!=null&&t.isAdPlaying){this.cleanupControlsTimer(),this.controlsVisible=!1,this.classList.add("controls-hidden");return}if(!(((s=(i=this.config)==null?void 0:i.controls)==null?void 0:s.controlsBar)!==!1&&this.controlsSectionEnabled)){this.controlsVisible&&(this.controlsVisible=!1,this.classList.add("controls-hidden")),this.cleanupControlsTimer();return}this.controlsVisible||(this.controlsVisible=!0,this.classList.remove("controls-hidden")),this.cleanupControlsTimer(),this.playerState&&this.playerState.isPlaying&&!this.settingsMenuOpen&&!this.isDraggingSeekbar&&(this.hideControlsTimer=window.setTimeout(()=>{this.controlsVisible=!1,this.classList.add("controls-hidden")},2500))},this.handleMouseLeave=()=>{var e;if((e=this.playerState)!=null&&e.isAdPlaying){this.cleanupControlsTimer(),this.controlsVisible=!1,this.classList.add("controls-hidden");return}this.playerState&&this.playerState.isPlaying&&!this.settingsMenuOpen&&!this.isDraggingSeekbar&&(this.controlsVisible=!1,this.classList.add("controls-hidden"))},this.handleContextMenu=e=>{var i,s;if(this.isContextMenuDisabled||((s=(i=this.config)==null?void 0:i.controls)==null?void 0:s.contextMenu)===!1){e.preventDefault();return}const t=this.getBoundingClientRect();this.contextMenuX=e.clientX-t.left,this.contextMenuY=e.clientY-t.top,this.contextMenuOpen=!0},this.handleDocumentClick=e=>{this.contextMenuOpen&&(this.contextMenuOpen=!1),this.settingsMenu.closeIfOutside(e)},this.handleFocusIn=e=>{this.settingsMenu.closeIfOutside(e)}}get activePreload(){var e;return((e=this.config)==null?void 0:e.preload)||this.preload||"metadata"}get activeLoop(){var e,t,i;return((t=(e=this.config)==null?void 0:e.playback)==null?void 0:t.loop)!==void 0?this.config.playback.loop:((i=this.config)==null?void 0:i.loop)!==void 0?this.config.loop:this.loop}get activePlaysinline(){var e;return((e=this.config)==null?void 0:e.playsinline)!==void 0?this.config.playsinline:this.playsinline}get activePoster(){var e;return((e=this.config)==null?void 0:e.poster)||this.poster||""}get activeCrossorigin(){var t;const e=((t=this.config)==null?void 0:t.crossorigin)||this.crossorigin;if(e==="anonymous"||e==="use-credentials")return e}get controlsSectionEnabled(){var t;const e=(t=this.config)==null?void 0:t.controls;return!(e===!1||e&&typeof e=="object"&&e.enabled===!1)}get emptyStateSectionEnabled(){var t;const e=(t=this.config)==null?void 0:t.emptyState;return!(e===!1||e&&typeof e=="object"&&e.enabled===!1)}localize(e,t){var r,a,n;const i=((r=this.config)==null?void 0:r.locale)||{};return(((n=(a=this.config)==null?void 0:a.settings)==null?void 0:n.labels)||{})[e]||i[e]||t}static get observedAttributes(){const e=super.observedAttributes;return Object.prototype.hasOwnProperty.call(this,"attributeAliases")||(this.attributeAliases=jr(e)),[...e,...this.attributeAliases.keys()]}attributeChangedCallback(e,t,i){var r;const s=(r=this.constructor.attributeAliases)==null?void 0:r.get(e);if(s){i===null?this.removeAttribute(s):this.getAttribute(s)!==i&&this.setAttribute(s,i);return}super.attributeChangedCallback(e,t,i)}get controllerInstance(){return this.controller}loadSource(e){this.prefetch.setDirection("next"),this.controller?this.controller.loadSource(e):this.updateComplete.then(()=>{var t;return(t=this.controller)==null?void 0:t.loadSource(e)})}loadPlaylist(e,t=0){this.prefetch.setDirection("next"),this.controller?this.controller.loadPlaylist(e,t):this.updateComplete.then(()=>{var i;return(i=this.controller)==null?void 0:i.loadPlaylist(e,t)})}play(){this.controller?this.controller.play():this.updateComplete.then(()=>{var e;return(e=this.controller)==null?void 0:e.play()})}pause(){this.controller?this.controller.pause():this.updateComplete.then(()=>{var e;return(e=this.controller)==null?void 0:e.pause()})}load(e){const t=typeof e=="string"?{src:e}:e;this.controller?this.controller.load(t):this.updateComplete.then(()=>{var i;return(i=this.controller)==null?void 0:i.load(t)})}destroy(){this.controller&&this.controller.destroy(),this.remove()}addPlaylistItem(e){this.controller?this.controller.addPlaylistItem(e):this.updateComplete.then(()=>{var t;return(t=this.controller)==null?void 0:t.addPlaylistItem(e)})}getCurrentItem(){return this.controller?this.controller.getCurrentItem():null}repeat(e){this.controller?this.controller.repeat(e):this.updateComplete.then(()=>{var t;return(t=this.controller)==null?void 0:t.repeat(e)})}on(e,t){this.controller?this.controller.on(e,t):this.pendingListeners.push({action:"on",event:e,callback:t})}off(e,t){this.controller?this.controller.off(e,t):this.pendingListeners.push({action:"off",event:e,callback:t})}emit(e,t){this.controller&&this.controller.emit(e,t)}setNearEndThreshold(e){this.nearEndThreshold=e,this.controller&&this.controller.setNearEndThreshold(e)}getNearEndThreshold(){return this.controller?this.controller.getNearEndThreshold():this.nearEndThreshold}getPlaylist(){return this.controller?this.controller.getPlaylist():[]}getCurrentPlaylistIndex(){return this.controller?this.controller.getCurrentPlaylistIndex():0}getHistoryStack(){return this.controller?this.controller.getHistoryStack():[]}getCurrentPlaylistItem(){return this.controller?this.controller.getCurrentPlaylistItem():null}getPlaylistLength(){return this.controller?this.controller.getPlaylistLength():0}hasPlaylist(){return this.controller?this.controller.hasPlaylist():!1}isFirstPlaylistItem(){return this.controller?this.controller.isFirstPlaylistItem():!1}isLastPlaylistItem(){return this.controller?this.controller.isLastPlaylistItem():!1}setPlaylistRepeatMode(e){this.controller&&this.controller.setPlaylistRepeatMode(e)}getPlaylistRepeatMode(){return this.controller?this.controller.getPlaylistRepeatMode():"off"}next(){if(!this.controller){this.updateComplete.then(()=>this.next());return}this.getPlaylistLength()<=1||this.gestures.isTransitionLocked||(this.prefetch.setDirection("next"),this.gestures.initiateVisualTransition("next",()=>{this.controller.next()}))}previous(){if(!this.controller){this.updateComplete.then(()=>this.previous());return}this.getPlaylistLength()<=1||this.gestures.isTransitionLocked||(this.prefetch.setDirection("prev"),this.gestures.initiateVisualTransition("prev",()=>{this.controller.previous()}))}appendPlaylistItem(e){this.controller?this.controller.appendPlaylistItem(e):this.updateComplete.then(()=>{var t;return(t=this.controller)==null?void 0:t.appendPlaylistItem(e)})}insertPlaylistItem(e,t){this.controller?this.controller.insertPlaylistItem(e,t):this.updateComplete.then(()=>{var i;return(i=this.controller)==null?void 0:i.insertPlaylistItem(e,t)})}removePlaylistItem(e){if(!this.controller){this.updateComplete.then(()=>this.removePlaylistItem(e));return}if(this.gestures.isTransitionLocked)return;e===this.getCurrentPlaylistIndex()&&this.displayMode==="vertical"?(this.prefetch.setDirection("next"),this.gestures.initiateVisualTransition("next",()=>{this.controller.removePlaylistItem(e)})):this.controller.removePlaylistItem(e)}clearPlaylist(){this.controller?this.controller.clearPlaylist():this.updateComplete.then(()=>{var e;return(e=this.controller)==null?void 0:e.clearPlaylist()})}replacePlaylistItem(e,t){this.controller?this.controller.replacePlaylistItem(e,t):this.updateComplete.then(()=>{var i;return(i=this.controller)==null?void 0:i.replacePlaylistItem(e,t)})}movePlaylistItem(e,t){this.controller?this.controller.movePlaylistItem(e,t):this.updateComplete.then(()=>{var i;return(i=this.controller)==null?void 0:i.movePlaylistItem(e,t)})}goToNextPlaylistItem(){this.next()}goToPreviousPlaylistItem(){this.previous()}setIcon(e,t){this.iconRegistry.setIcon(e,t),this.requestUpdate()}registerIconPack(e,t){X.registerIconPack(e,t),this.requestUpdate()}useIconPack(e){this.iconRegistry.useIconPack(e),this.requestUpdate()}registerControl(e,t){this.customControls.set(e,t),this.requestUpdate()}registerOverlay(e,t){this.customOverlays.set(e,t),this.requestUpdate()}disableOverlay(e){const t=this.customOverlays.get(e)||{};this.customOverlays.set(e,{...t,enabled:!1}),this.requestUpdate()}enableOverlay(e){const t=this.customOverlays.get(e)||{};this.customOverlays.set(e,{...t,enabled:!0}),this.requestUpdate()}setOverlayTemplate(e,t){const i=this.customOverlays.get(e)||{};this.customOverlays.set(e,{...i,template:t}),this.requestUpdate()}setOverlayTiming(e,t){const i=this.customOverlays.get(e)||{};this.customOverlays.set(e,{...i,timing:t}),this.requestUpdate()}getIcon(e,t){var a,n,l;const i=((a=this.config)==null?void 0:a.icons)||{},r=(((l=(n=this.config)==null?void 0:n.settings)==null?void 0:l.icons)||{})[e]||i[e];return r||this.iconRegistry.getIcon(e,t)}setThumbnailProvider(e){var i;this.thumbnailCache.setMainProvider(e),this.controller&&this.controller.setThumbnailProvider(e);const t=(i=this.playerState)==null?void 0:i.currentSource;t&&e&&this.thumbnailCache.setProviderForSource(t,e),this.thumbnailCache.trigger()}seekToChapter(e){this.controller&&this.controller.seekToChapter(e)}willUpdate(e){e.has("liveMode")&&this.controller&&this.controller.setLiveMode(this.liveMode),this.adoptDisplayModeFromConfig(e)}adoptDisplayModeFromConfig(e){var i,s,r;if(!e.has("config"))return;const t=((i=this.config)==null?void 0:i.displayMode)||((r=(s=this.config)==null?void 0:s.layout)==null?void 0:r.mode);!t||t===this.configRequestedMode||(this.configRequestedMode=t,this.displayMode!==t&&(this.displayMode=t))}firstUpdated(){var r,a,n,l,o,d,h,u,f;const e=((r=this.config)==null?void 0:r.displayMode)||((n=(a=this.config)==null?void 0:a.layout)==null?void 0:n.mode)||this.displayMode,t={autoplay:this.autoplay,muted:this.muted,volume:this.volume,displayMode:e,autoScroll:this.autoScroll,nearEndThreshold:this.nearEndThreshold,preload:this.activePreload,loop:this.activeLoop,playsinline:this.activePlaysinline,poster:this.activePoster,crossorigin:this.activeCrossorigin,...this.config||{},playback:{autoplay:this.autoplay,muted:this.muted,volume:this.volume,...((l=this.config)==null?void 0:l.playback)||{}},layout:{mode:e,...((o=this.config)==null?void 0:o.layout)||{}},sleepTimer:{...((d=this.config)==null?void 0:d.sleepTimer)||{}},live:{mode:this.liveMode,...((h=this.config)==null?void 0:h.live)||{}}};if(t.displayMode=e,t.layout||(t.layout={}),t.layout.mode=e,this.preciseSeekEnabled!==void 0&&(t.preciseSeek={...typeof t.preciseSeek=="object"?t.preciseSeek:{},enabled:this.preciseSeekEnabled}),this.smartSeekEnabled!==void 0&&(t.smartSeek={...typeof t.smartSeek=="object"?t.smartSeek:{},enabled:this.smartSeekEnabled}),t.iconPack&&this.iconRegistry.useIconPack(t.iconPack),t.icons)for(const[p,g]of Object.entries(t.icons))this.iconRegistry.setIcon(p,g);this.controller=new is(this.videoElement,t),t.theme&&this.applyTheme(t.theme);const i=(u=this.shadowRoot)==null?void 0:u.querySelector(".player-ads-overlay");i&&this.controller.ads&&this.controller.ads.setAdContainer(i);for(const p of this.pendingListeners)p.action==="on"?this.controller.on(p.event,p.callback):p.action==="off"&&this.controller.off(p.event,p.callback);if(this.pendingListeners=[],this.unsubscribe=this.controller.onStateChange(p=>{var x;if(this.isVisualTransitioning&&this.gestures.checkTransitionCompletion(),this.videoElement&&(p.isPlaying||p.status==="playing"||this.videoElement.readyState>=2)&&this.videoElement.removeAttribute("poster"),this.playerState&&this.playerState.currentSource!==p.currentSource&&(this.isFeedTransitioning=!0,p.currentSource)){const A=this.thumbnailCache.getProvider(p.currentSource);if(A&&A!==this.thumbnailCache.getMainProvider()){if(this.thumbnailCache.setMainProvider(A),this.controller){const O=this.controller;O.thumbnailProvider=A,O.state.thumbnailProvider=A}p.thumbnailProvider=A}}if(this.playerState&&this.playerState.isAdPlaying!==p.isAdPlaying&&(p.isAdPlaying?(this.cleanupControlsTimer(),this.controlsVisible=!1,this.classList.add("controls-hidden")):(this.controlsVisible=!0,this.classList.remove("controls-hidden"))),this.playerState&&this.playerState.isPlaying!==p.isPlaying&&p.status!=="idle"&&p.status!=="error"&&!(p.status==="ended"&&this.displayMode==="vertical")){const A=this.displayMode==="vertical"&&((x=this.videoElement)==null?void 0:x.ended);!this.isFeedTransitioning&&!this.suppressPlayPauseFeedback&&!A&&this.triggerPlayPauseFeedback(p.isPlaying?"play":"pause")}this.isFeedTransitioning&&(p.status==="playing"||p.status==="paused"||p.status==="error"||p.status==="ended")&&(this.isFeedTransitioning=!1),(p.isPlaying||p.status==="playing")&&(this.suppressPlayPauseFeedback=!1,this.shouldAutoplayAfterTransition=!1),this.playerState&&(this.playerState.volume!==p.volume||this.playerState.isMuted!==p.isMuted)&&p.status!=="idle"&&p.status!=="error"&&this.triggerVolumeFeedback(p.volume,p.isMuted),this.playerState&&this.playerState.playbackRate!==p.playbackRate&&p.status!=="idle"&&p.status!=="error"&&this.triggerSpeedFeedback(p.playbackRate),this.shouldShowQualityFeedback&&this.playerState&&this.playerState.activeQuality!==p.activeQuality&&p.activeQuality&&p.status!=="idle"&&p.status!=="loading"&&p.status!=="error"&&(this.triggerQualityFeedback(p.activeQuality),this.shouldShowQualityFeedback=!1);const m=this.playerState;this.playerState=p,this.muted=p.isMuted,this.volume=p.volume,this.displayMode=p.displayMode,this.autoScroll=p.autoScroll,this.liveMode=p.liveMode;const v=!m||m.status!==p.status,y=!m||m.currentSource!==p.currentSource;(v||y)&&(this.thumbnailCache.trigger(),this.prefetch.trigger()),m&&m.currentSource!==p.currentSource&&(this.filmstripThumbs.clear(),this.filmstripCenterTime=-1,this.isPreciseSeeking=!1,this.speedLockState="IDLE",this.isSpeedOverlayFadingOut=!1),!p.isSeeking&&!this.isDraggingSeekbar&&(this.pendingSeekTime=null);const S=!m||["status","isPlaying","volume","isMuted","isFullscreen","playbackRate","captionsEnabled","currentSource","sourceType","isBuffering","isSeeking","hasCaptions","error","activeQuality","activeAudioTrack","activeSubtitleTrackId","activeChapterIndex","loop","isLive","isLowLatency","isAtLiveEdge","liveLatency","dvrWindow","canSeekInDvr"].some(A=>m[A]!==p[A]),E=(m?Math.abs(m.currentTime-p.currentTime):0)>=.2||p.isSeeking||m&&m.isSeeking!==p.isSeeking;(S||E)&&this.dispatchEvent(new CustomEvent("player-state-change",{detail:p,bubbles:!0,composed:!0}))}),["play","ended","pause","seek","seekstart","seekend","volumechange","mutechange","playbackratechange","qualitychange","subtitlechange","audiochange","fullscreenchange","pipchange","sourcechange","chapterchange","markerclick","markerhover","metadata","error","replay","playlist-loaded","playlist-cleared","playlist-change","playlist-index-change","playlist-next","playlist-previous","playlist-item-added","playlist-item-removed","playlist-item-replaced","playlist-item-moved","playlist-near-end","playlist-repeat-change","autoscroll-change","metadata","timeupdate","waiting","playing","config-change","drmsessioncreated","drmsessionclosed","drmmessage","drmkeychange","drmerror","drmlicenserequest","drmlicenseresponse","manifestloaded","adbreakstart","adbreakend","adclick","adloadstart","adloaded","adstart","adpause","adresume","adskip","adcomplete","adquartile","admute","adunmute","adtimeupdate","adproviderchange","aderror","adverificationready","skipavailable","admilestone","companionshown","companionerror","vmapparseerror","vmapbreakerror","htmloverlayavailable","htmloverlayloaded","htmloverlayshown","htmloverlayhidden","htmloverlayclosed","htmloverlayclick","htmloverlaycompleted","htmloverlayerror","htmloverlayupdated","simidavailable","simidstart","simidready","simiderror","simidcomplete","simidinteraction","simidsecurityerror","simidclick","simiddurationchange","simidcreativeerror","simidpause","simidresume","simidresize","simidfullscreen","simidexitfullscreen","simidcollapse","simidexpand","simidskip","simidstop"].forEach(p=>{this.controller.addEventListener(p,g=>{var m,v,y,b;if(p==="config-change"){const S=g;this.config=S,S.theme&&this.applyTheme(S.theme),this.requestUpdate()}if(p==="ended")if(this.controller.getAutoAdvanceIndexOnEnded()!==null){const T=((v=(m=this.config)==null?void 0:m.vertical)==null?void 0:v.loopSingleVideo)!==void 0?this.config.vertical.loopSingleVideo:this.displayMode==="vertical"&&!this.playerState.autoScroll;this.displayMode!=="vertical"||this.playerState.autoScroll&&!T?(this.next(),this.displayMode!=="vertical"&&this.controller.play()):this.displayMode==="vertical"&&(this.suppressPlayPauseFeedback=!0,this.controller.seek(0),this.controller.play())}else this.displayMode==="vertical"&&((b=(y=this.config)==null?void 0:y.vertical)==null?void 0:b.loopSingleVideo)!==!1&&(this.suppressPlayPauseFeedback=!0,this.controller.seek(0),this.controller.play());if(p==="playlist-next"){const S=g;this.dispatchEvent(new CustomEvent("player-feed-next",{detail:{index:S.index,source:S.source},bubbles:!0,composed:!0}))}if(p==="playlist-previous"){const S=g;this.dispatchEvent(new CustomEvent("player-feed-previous",{detail:{index:S.index,source:S.source},bubbles:!0,composed:!0}))}this.dispatchEvent(new CustomEvent(`player-${p}`,{detail:g,bubbles:!0,composed:!0}))})}),this.src&&this.controller.loadSource({src:this.src}),this.captions&&this.controller.loadCaptions({src:this.captions,label:"English Subtitles",srclang:"en",default:!0}),this.setupInteractionListeners(),this.gestures.attach(),this.addEventListener("contextmenu",this.handleContextMenu),document.addEventListener("click",this.handleDocumentClick),document.addEventListener("focusin",this.handleFocusIn),this.controller){this.controller.player=this,this.controller.pendingOverlays.forEach((g,m)=>{this.registerOverlay(m,g)}),this.controller.pendingOverlays.clear();const p=this.controller.getPlugins();for(const g of p)try{(f=g.onPlayerAttached)==null||f.call(g,this)}catch(m){console.error(`[Player] Error running onPlayerAttached for plugin ${g.name}:`,m)}}this.shortcutsUnsubscribe=this.controller.shortcuts.onAction((p,g)=>{if(p==="seek"&&(g==null?void 0:g.seconds)!==void 0){const m=g.seconds;this.showFeedbackOverlay(m<0?"rewind":"fastforward"),this.triggerSeekInteraction()}else if(p==="volume"&&(g==null?void 0:g.volume)!==void 0&&g.isMuted!==void 0){const{volume:m,isMuted:v}=g;this.triggerVolumeFeedback(m,v)}else p==="fullscreen"&&this.handleFullscreenToggle()})}updated(e){var t,i,s,r,a,n,l;if(super.updated(e),e.has("config")&&this.controller&&this.config&&this.config!==this.controller.config&&this.controller.updateConfig(this.config),e.has("preciseSeekEnabled")&&this.controller&&this.preciseSeekEnabled!==void 0&&this.controller.updateConfig({preciseSeek:{...typeof((t=this.config)==null?void 0:t.preciseSeek)=="object"?this.config.preciseSeek:{},enabled:this.preciseSeekEnabled}}),e.has("smartSeekEnabled")&&this.controller&&this.smartSeekEnabled!==void 0&&this.controller.updateConfig({smartSeek:{...typeof((i=this.config)==null?void 0:i.smartSeek)=="object"?this.config.smartSeek:{},enabled:this.smartSeekEnabled}}),e.has("config")){const o=(r=(s=this.config)==null?void 0:s.vertical)==null?void 0:r.animationTiming;o!==void 0?this.style.setProperty("--player-vertical-transition-duration",`${o}ms`):this.style.removeProperty("--player-vertical-transition-duration"),((n=(a=this.config)==null?void 0:a.vertical)==null?void 0:n.autoScroll)!==void 0&&(this.autoScroll=this.config.vertical.autoScroll,this.controller&&this.controller.setAutoScroll(this.autoScroll))}if(e.has("displayMode")&&this.controller){const o=e.get("displayMode");if(o!==void 0&&o!==this.displayMode){this.controller.setDisplayMode(this.displayMode);const d=this.getAvailableSpeeds(this.displayMode),h=this.playerState.playbackRate;if(!d.includes(h)){const u=d.reduce((f,p)=>Math.abs(p-h)<Math.abs(f-h)?p:f);this.controller.setPlaybackRate(u)}if(this.displayMode==="vertical"){this.isPreciseSeeking=!1;const u=this.playerState.thumbnailProvider;u&&(u.isPreciseSeeking=!1)}}}if(e.has("nearEndThreshold")&&this.controller){const o=e.get("nearEndThreshold");o!==void 0&&o!==this.nearEndThreshold&&this.controller.setNearEndThreshold(this.nearEndThreshold)}if(e.has("autoScroll")&&this.controller){const o=e.get("autoScroll");o!==void 0&&o!==this.autoScroll&&this.controller.setAutoScroll(this.autoScroll)}if(e.has("src")&&this.controller){const o=e.get("src");o!==void 0&&o!==this.src&&(this.settingsMenu.close(),this.filmstripThumbs.clear(),this.filmstripCenterTime=-1,this.isPreciseSeeking=!1,this.speedLockState="IDLE",this.isSpeedOverlayFadingOut=!1,this.controller.loadSource({src:this.src}))}if(e.has("captions")&&this.controller&&this.captions){const o=e.get("captions");o!==void 0&&o!==this.captions&&this.controller.loadCaptions({src:this.captions,label:"English Subtitles",srclang:"en",default:!0})}if(e.has("activeMenuScreen")&&this.settingsMenu.onScreenChanged(),e.has("settingsMenuOpen")&&this.settingsMenu.onOpenStateChanged(e.get("settingsMenuOpen")),e.has("contextMenuOpen")){const o=e.get("contextMenuOpen");this.contextMenuOpen&&!o&&setTimeout(()=>{var h;const d=(h=this.shadowRoot)==null?void 0:h.querySelector(".custom-context-menu");if(d){const u=d.querySelector(".context-menu-item:not(.disabled)");u?u.focus():d.focus()}},50)}if(e.has("playerState")){const o=e.get("playerState");this.playerState.status==="ended"&&!this.playerState.isLive&&this.displayMode!=="vertical"&&(!o||o.status!=="ended")&&setTimeout(()=>{var h;const d=(h=this.shadowRoot)==null?void 0:h.querySelector(".replay-icon-circle");d&&d.focus()},50),this.playerState.sleepTimerExpired&&(!o||!o.sleepTimerExpired)&&(this.lastFocusedElement=this.getDeepActiveElement(),setTimeout(()=>{var h;const d=(h=this.shadowRoot)==null?void 0:h.querySelector(".sleep-timer-btn-close");d&&d.focus()},50)),o&&o.sleepTimerExpired&&!this.playerState.sleepTimerExpired&&setTimeout(()=>{this.lastFocusedElement&&typeof this.lastFocusedElement.focus=="function"?this.lastFocusedElement.focus():this.focus(),this.lastFocusedElement=null},50)}if(this.isPreciseSeeking){const o=(l=this.shadowRoot)==null?void 0:l.querySelector(".precise-seek-container");o&&o.clientWidth>0&&this.preciseSeekContainerWidth!==o.clientWidth&&(this.preciseSeekContainerWidth=o.clientWidth,this.requestUpdate())}}disconnectedCallback(){var e;if(super.disconnectedCallback(),this.speedLockState="IDLE",this.isSpeedOverlayFadingOut=!1,this.activeSpeedFeedback=null,this.gestures.detach(),typeof window<"u"&&window.removeEventListener("resize",this.handleResize),this.removeEventListener("mousemove",this.handleActivity),this.removeEventListener("mouseleave",this.handleMouseLeave),this.removeEventListener("focusin",this.handleActivity),this.removeEventListener("keydown",this.handleKeyDown),this.removeEventListener("contextmenu",this.handleContextMenu),document.removeEventListener("click",this.handleDocumentClick),document.removeEventListener("focusin",this.handleFocusIn),this.settingsMenu.close(),this.controller){const t=this.controller.getPlugins();for(const i of t)try{(e=i.onPlayerDetached)==null||e.call(i,this)}catch(s){console.error(`[Player] Error running onPlayerDetached for plugin ${i.name}:`,s)}}this.unsubscribe&&this.unsubscribe(),this.shortcutsUnsubscribe&&this.shortcutsUnsubscribe(),this.thumbnailCache.destroy(),this.prefetch.cancel(),this.controller&&this.controller.destroy(),this.cleanupControlsTimer(),this.feedbackTimer&&(clearTimeout(this.feedbackTimer),this.feedbackTimer=void 0),this.tapFeedback=null,this.feedbackTaps=0,this.playPauseFeedbackTimer&&clearTimeout(this.playPauseFeedbackTimer),this.seekInteractionTimer&&clearTimeout(this.seekInteractionTimer),this.speedFeedbackTimer&&clearTimeout(this.speedFeedbackTimer),this.qualityFeedbackTimer&&clearTimeout(this.qualityFeedbackTimer),this.volumeFeedbackTimer&&clearTimeout(this.volumeFeedbackTimer),this.throttledSeekTimer&&clearTimeout(this.throttledSeekTimer),this.toastTimer&&clearTimeout(this.toastTimer),this.isDraggingSeekbar=!1,this.filmstripThumbs.clear(),this.gestures.endVisualTransition()}getDeepActiveElement(){let e=document.activeElement;for(;e&&e.shadowRoot&&e.shadowRoot.activeElement;)e=e.shadowRoot.activeElement;return e}setupInteractionListeners(){this.addEventListener("mousemove",this.handleActivity),this.addEventListener("mouseleave",this.handleMouseLeave),this.addEventListener("focusin",this.handleActivity),typeof window<"u"&&window.addEventListener("resize",this.handleResize),this.setAttribute("tabindex","0"),this.addEventListener("keydown",this.handleKeyDown)}cleanupControlsTimer(){this.hideControlsTimer&&(clearTimeout(this.hideControlsTimer),this.hideControlsTimer=void 0)}showFeedbackOverlay(e){this.tapFeedback&&this.tapFeedback!==e&&(this.feedbackTaps=0),this.tapFeedback=null,this.requestUpdate(),this.feedbackTaps++,this.feedbackTimer&&(clearTimeout(this.feedbackTimer),this.feedbackTimer=void 0),requestAnimationFrame(()=>{requestAnimationFrame(()=>{this.tapFeedback=e,this.feedbackTimer=window.setTimeout(()=>{this.tapFeedback=null,this.feedbackTaps=0,this.feedbackTimer=void 0},this.getOverlayTiming("seek",800))})})}triggerPlayPauseFeedback(e){this.playPauseFeedback=null,this.requestUpdate(),this.playPauseFeedbackTimer&&clearTimeout(this.playPauseFeedbackTimer),requestAnimationFrame(()=>{requestAnimationFrame(()=>{this.playPauseFeedback=e,this.playPauseFeedbackTimer=window.setTimeout(()=>{this.playPauseFeedback=null},this.getOverlayTiming("play-pause",800))})})}handleVideoClick(){var e,t,i,s;if(!this.gestures.isLongPressSpeedActive){if(this.settingsMenuOpen){this.settingsMenu.close();return}if(!(((t=(e=this.config)==null?void 0:e.controls)==null?void 0:t.play)===!1||((s=(i=this.config)==null?void 0:i.controls)==null?void 0:s.playButton)===!1)){if(this.playerState.status==="ended"&&!this.playerState.isLive&&this.displayMode!=="vertical"){this.handleReplay();return}this.controller.togglePlay(),this.handleActivity()}}}handleReplay(){this.controller&&(this.controller.replay(),this.handleActivity())}handleReplayKeyDown(e){(e.key==="Enter"||e.key===" ")&&(e.preventDefault(),e.stopPropagation(),this.handleReplay())}handleVideoDoubleClick(e){var n,l,o,d,h;if(((l=(n=this.config)==null?void 0:n.controls)==null?void 0:l.seekbar)===!1||this.playerState.isLive&&!this.playerState.canSeekInDvr||!(this.displayMode==="vertical"?((h=(d=(o=this.config)==null?void 0:o.vertical)==null?void 0:d.gestures)==null?void 0:h.doubleTapToSeek)!==!1:!0))return;const s=this.videoElement.getBoundingClientRect(),a=(e.clientX-s.left)/s.width;a<.4?(this.controller.seekBy(-10),this.showFeedbackOverlay("rewind")):a>.6?(this.controller.seekBy(10),this.showFeedbackOverlay("fastforward")):this.controller.toggleFullscreen(this)}handleSeekBy(e){if(this.playerState.isLive&&!this.playerState.canSeekInDvr)return;const t=e.detail.seconds;this.controller.seekBy(t),this.showFeedbackOverlay(t<0?"rewind":"fastforward"),this.triggerSeekInteraction()}handleSelectSpeed(e){this.controller.setPlaybackRate(e),this.settingsMenu.close()}getAvailableSpeeds(e){var t,i;return((i=(t=this.config)==null?void 0:t.playback)==null?void 0:i.playbackRates)||(e==="vertical"?Wr:Kr)}handleSelectQuality(e){this.shouldShowQualityFeedback=!0,this.controller.setQuality(e),this.settingsMenu.close()}handleSelectAudio(e){this.controller.setAudioTrack(e),this.settingsMenu.close()}handleSelectSubtitle(e){e===-1?this.controller.disableSubtitles():this.controller.setSubtitleTrack(e),this.settingsMenu.close()}handleSelectSleepTimer(e){this.controller.setSleepTimer(e),this.settingsMenu.close()}getSleepTimerLabel(){const e=this.playerState.sleepTimerSetting;if(e==="off")return"Off";if(e==="end")return"End of video";const t=this.playerState.sleepTimerSecondsRemaining;return t!=null?`${Math.ceil(t/60)} min`:`${e} min`}getRemainingVideoTimeText(){const e=this.playerState.duration,t=this.playerState.currentTime,i=Math.max(0,e-t);return isNaN(i)||i===1/0||i===0?"":`${Math.ceil(i/60)} min`}handleSleepTimerAddTime(){this.controller.clearSleepTimerExpired(),this.controlsVisible=!0,this.classList.remove("controls-hidden"),this.settingsMenu.open("sleeptimer"),this.requestUpdate()}handleSleepTimerClose(){this.controller.clearSleepTimerExpired(),this.settingsMenu.close(),this.controlsVisible=!0,this.classList.remove("controls-hidden"),this.requestUpdate()}handleIconSlotChange(e,t){const s=t.target.assignedElements();s.length>0&&(this.iconRegistry.setIcon(e,s[0]),this.requestUpdate())}renderHiddenSlots(){return k`
3621
3621
  <div class="hidden-slots" style="display: none;" aria-hidden="true">
3622
3622
  ${["play","pause","replay","loading","volume","volume-mute","volume-low","volume-medium","settings","settings-vertical","fullscreen","fullscreen-exit","pip","captions","seek-backward","seek-forward","live","playlist-prev","playlist-next","chapters","markers","arrow-back","arrow-forward","check","audio-only","speed-feedback"].map(t=>k`
3623
3623
  <slot
@@ -3684,7 +3684,7 @@ var StreamitPlayer=function(B){"use strict";/**
3684
3684
  class="precise-seek-filmstrip"
3685
3685
  style="--cell-width: ${f}px; transform: translateX(${g}px);"
3686
3686
  >
3687
- ${l.map((m,v)=>{const y=m,b=Math.round(y);let S=this.filmstripThumbs.get(b)||null;if(!S&&typeof e.getNearestCachedThumbnail=="function"){const I=e.getNearestCachedThumbnail(b);I&&I.time!==void 0&&Math.abs(I.time-b)<=5&&(S=I)}const T=v===d,E=!S,A=S&&S.width||200,P=S&&S.height||112,$=f/A,M=S?S.x!==void 0?`background-image: url('${S.url}'); background-position: -${S.x||0}px -${S.y||0}px; width: ${A}px; height: ${P}px; background-size: auto; transform: translate(-50%, -50%) scale(${$}); position: absolute; left: 50%; top: 50%; transform-origin: center;`:`background-image: url('${S.url}'); width: 100%; height: 100%; background-size: cover;`:"";return k`
3687
+ ${l.map((m,v)=>{const y=m,b=Math.round(y);let S=this.filmstripThumbs.get(b)||null;if(!S&&typeof e.getNearestCachedThumbnail=="function"){const I=e.getNearestCachedThumbnail(b);I&&I.time!==void 0&&Math.abs(I.time-b)<=5&&(S=I)}const T=v===d,E=!S,x=S&&S.width||200,A=S&&S.height||112,O=f/x,M=S?S.x!==void 0?`background-image: url('${S.url}'); background-position: -${S.x||0}px -${S.y||0}px; width: ${x}px; height: ${A}px; background-size: auto; transform: translate(-50%, -50%) scale(${O}); position: absolute; left: 50%; top: 50%; transform-origin: center;`:`background-image: url('${S.url}'); width: 100%; height: 100%; background-size: cover;`:"";return k`
3688
3688
  <div
3689
3689
  class="filmstrip-thumbnail-cell ${T?"active":""} ${E?"loading":""}"
3690
3690
  @click=${()=>this.handleFilmstripClick(y)}
@@ -3701,7 +3701,7 @@ var StreamitPlayer=function(B){"use strict";/**
3701
3701
  `})}
3702
3702
  </div>
3703
3703
  </div>
3704
- `}handleFilmstripClick(e){this.isDraggingSeekbar?(this.pendingSeekTime=e,this.controller.seek(e),this.requestUpdate()):(this.controller.seek(e),this.handleActivity())}handleToggleMute(){this.controller.toggleMute()}handleVolumeChange(e){this.controller.setVolume(e.detail.volume)}handleFullscreenToggle(){this.controller.toggleFullscreen(this)}handlePictureInPictureToggle(){this.controller.togglePictureInPicture()}handleCaptionsToggle(){this.controller.toggleCaptions()}renderSettingsMenuContent(){var s,r,a,n,l,o,d,h,u,f,p,g,m,v,y,b,S,T,E,A,P,$,M,I,R,N,U,C,x,H,te;const e=k`<slot name="icon-arrow-back"
3704
+ `}handleFilmstripClick(e){this.isDraggingSeekbar?(this.pendingSeekTime=e,this.controller.seek(e),this.requestUpdate()):(this.controller.seek(e),this.handleActivity())}handleToggleMute(){this.controller.toggleMute()}handleVolumeChange(e){this.controller.setVolume(e.detail.volume)}handleFullscreenToggle(){this.controller.toggleFullscreen(this)}handlePictureInPictureToggle(){this.controller.togglePictureInPicture()}handleCaptionsToggle(){this.controller.toggleCaptions()}renderSettingsMenuContent(){var s,r,a,n,l,o,d,h,u,f,p,g,m,v,y,b,S,T,E,x,A,O,M,I,D,N,P,C,R,q,te;const e=k`<slot name="icon-arrow-back"
3705
3705
  >${G(this.getIcon("arrow-back"))}</slot
3706
3706
  >`,t=k`<slot name="icon-check">${G(this.getIcon("check"))}</slot>`,i=k`<slot name="icon-arrow-forward"
3707
3707
  >${G(this.getIcon("arrow-forward"))}</slot
@@ -3717,17 +3717,17 @@ var StreamitPlayer=function(B){"use strict";/**
3717
3717
  ${e} Speed
3718
3718
  </div>
3719
3719
  <div class="settings-list-scroll" role="menu">
3720
- ${V.map(F=>k`
3720
+ ${V.map(U=>k`
3721
3721
  <div
3722
3722
  class="settings-item"
3723
- @click=${()=>this.handleSelectSpeed(F)}
3723
+ @click=${()=>this.handleSelectSpeed(U)}
3724
3724
  role="menuitemradio"
3725
- aria-checked=${this.playerState.playbackRate===F}
3725
+ aria-checked=${this.playerState.playbackRate===U}
3726
3726
  tabindex="0"
3727
3727
  @keydown=${this.settingsMenu.handleItemKey}
3728
3728
  >
3729
- <span>${F===1?this.localize("normal","Normal"):`${F}x`}</span>
3730
- ${this.playerState.playbackRate===F?t:""}
3729
+ <span>${U===1?this.localize("normal","Normal"):`${U}x`}</span>
3730
+ ${this.playerState.playbackRate===U?t:""}
3731
3731
  </div>
3732
3732
  `)}
3733
3733
  </div>
@@ -3743,17 +3743,17 @@ var StreamitPlayer=function(B){"use strict";/**
3743
3743
  ${e} ${this.localize("quality","Quality")}
3744
3744
  </div>
3745
3745
  <div class="settings-list-scroll" role="menu">
3746
- ${this.playerState.qualities.map((V,F)=>{const L=V==="Auto"&&this.playerState.activeQuality.startsWith("Auto")||this.playerState.activeQuality===V,D=(()=>{const q=V.match(/^(\d+)p$/);return q?parseInt(q[1],10)>=720:!1})();return k`
3746
+ ${this.playerState.qualities.map((V,U)=>{const L=V==="Auto"&&this.playerState.activeQuality.startsWith("Auto")||this.playerState.activeQuality===V,$=(()=>{const H=V.match(/^(\d+)p$/);return H?parseInt(H[1],10)>=720:!1})();return k`
3747
3747
  <div
3748
3748
  class="settings-item"
3749
- @click=${()=>this.handleSelectQuality(F)}
3749
+ @click=${()=>this.handleSelectQuality(U)}
3750
3750
  role="menuitemradio"
3751
3751
  aria-checked=${L?"true":"false"}
3752
3752
  tabindex="0"
3753
3753
  @keydown=${this.settingsMenu.handleItemKey}
3754
3754
  >
3755
3755
  <span style="display: flex; align-items: center; gap: 6px;">
3756
- ${V} ${D?k`<span class="hd-badge">HD</span>`:""}
3756
+ ${V} ${$?k`<span class="hd-badge">HD</span>`:""}
3757
3757
  </span>
3758
3758
  ${L?t:""}
3759
3759
  </div>
@@ -3771,17 +3771,17 @@ var StreamitPlayer=function(B){"use strict";/**
3771
3771
  ${e} ${this.localize("audioDubs","Audio Dubs")}
3772
3772
  </div>
3773
3773
  <div class="settings-list-scroll" role="menu">
3774
- ${this.playerState.audioTracks.map((V,F)=>k`
3774
+ ${this.playerState.audioTracks.map((V,U)=>k`
3775
3775
  <div
3776
3776
  class="settings-item"
3777
- @click=${()=>this.handleSelectAudio(F)}
3777
+ @click=${()=>this.handleSelectAudio(U)}
3778
3778
  role="menuitemradio"
3779
- aria-checked=${this.playerState.activeAudioTrack===F}
3779
+ aria-checked=${this.playerState.activeAudioTrack===U}
3780
3780
  tabindex="0"
3781
3781
  @keydown=${this.settingsMenu.handleItemKey}
3782
3782
  >
3783
3783
  <span>${V}</span>
3784
- ${this.playerState.activeAudioTrack===F?t:""}
3784
+ ${this.playerState.activeAudioTrack===U?t:""}
3785
3785
  </div>
3786
3786
  `)}
3787
3787
  </div>
@@ -3800,7 +3800,7 @@ var StreamitPlayer=function(B){"use strict";/**
3800
3800
  >${e} ${this.localize("subtitles","Subtitles")}</span
3801
3801
  >
3802
3802
  <span
3803
- @click=${F=>{F.stopPropagation(),this.settingsMenu.goTo("subtitle-options")}}
3803
+ @click=${U=>{U.stopPropagation(),this.settingsMenu.goTo("subtitle-options")}}
3804
3804
  style="font-size: 11px; text-decoration: underline; color: var(--player-primary-color, #6366f1); cursor: pointer;"
3805
3805
  role="button"
3806
3806
  >${this.localize("options","Options")}</span
@@ -3818,21 +3818,21 @@ var StreamitPlayer=function(B){"use strict";/**
3818
3818
  <span>${this.localize("off","Off")}</span>
3819
3819
  ${V?t:""}
3820
3820
  </div>
3821
- ${this.playerState.subtitleTracks.map(F=>{const L=!V&&this.playerState.activeSubtitleTrackId===F.id;return k`
3821
+ ${this.playerState.subtitleTracks.map(U=>{const L=!V&&this.playerState.activeSubtitleTrackId===U.id;return k`
3822
3822
  <div
3823
3823
  class="settings-item"
3824
- @click=${()=>this.handleSelectSubtitle(F.id)}
3824
+ @click=${()=>this.handleSelectSubtitle(U.id)}
3825
3825
  role="menuitemradio"
3826
3826
  aria-checked=${L?"true":"false"}
3827
3827
  tabindex="0"
3828
3828
  @keydown=${this.settingsMenu.handleItemKey}
3829
3829
  >
3830
- <span>${F.label||F.language||"Unknown"}</span>
3830
+ <span>${U.label||U.language||"Unknown"}</span>
3831
3831
  ${L?t:""}
3832
3832
  </div>
3833
3833
  `})}
3834
3834
  </div>
3835
- `}case"subtitle-options":{const V=this.playerState.subtitleAppearance,F=((s=ns.find(ae=>ae.value===V.fontFamily))==null?void 0:s.label)||"Default",L=((r=He.find(ae=>ae.value===V.fontColor))==null?void 0:r.label)||"White",D=((a=os.find(ae=>ae.value===V.fontSize))==null?void 0:a.label)||"100%",q=((n=He.find(ae=>ae.value===V.backgroundColor))==null?void 0:n.label)||"Black",de=((l=qe.find(ae=>ae.value===V.backgroundOpacity))==null?void 0:l.label)||"75%",le=((o=He.find(ae=>ae.value===V.windowColor))==null?void 0:o.label)||"Black",Fe=((d=qe.find(ae=>ae.value===V.windowOpacity))==null?void 0:d.label)||"0%",Ue=((h=ls.find(ae=>ae.value===V.characterEdgeStyle))==null?void 0:h.label)||"None",Ke=((u=qe.find(ae=>ae.value===V.fontOpacity))==null?void 0:u.label)||"100%";return k`
3835
+ `}case"subtitle-options":{const V=this.playerState.subtitleAppearance,U=((s=ns.find(ae=>ae.value===V.fontFamily))==null?void 0:s.label)||"Default",L=((r=He.find(ae=>ae.value===V.fontColor))==null?void 0:r.label)||"White",$=((a=os.find(ae=>ae.value===V.fontSize))==null?void 0:a.label)||"100%",H=((n=He.find(ae=>ae.value===V.backgroundColor))==null?void 0:n.label)||"Black",de=((l=qe.find(ae=>ae.value===V.backgroundOpacity))==null?void 0:l.label)||"75%",le=((o=He.find(ae=>ae.value===V.windowColor))==null?void 0:o.label)||"Black",Fe=((d=qe.find(ae=>ae.value===V.windowOpacity))==null?void 0:d.label)||"0%",Ue=((h=ls.find(ae=>ae.value===V.characterEdgeStyle))==null?void 0:h.label)||"None",Ke=((u=qe.find(ae=>ae.value===V.fontOpacity))==null?void 0:u.label)||"100%";return k`
3836
3836
  <div
3837
3837
  class="settings-header"
3838
3838
  @click=${()=>this.settingsMenu.goTo("subtitles")}
@@ -3853,7 +3853,7 @@ var StreamitPlayer=function(B){"use strict";/**
3853
3853
  >
3854
3854
  <span>${this.localize("fontFamily","Font family")}</span>
3855
3855
  <span style="color: #9ca3af; display: flex; align-items: center; gap: 4px;"
3856
- >${F} ${i}</span
3856
+ >${U} ${i}</span
3857
3857
  >
3858
3858
  </div>
3859
3859
  <div
@@ -3877,7 +3877,7 @@ var StreamitPlayer=function(B){"use strict";/**
3877
3877
  >
3878
3878
  <span>${this.localize("fontSize","Font size")}</span>
3879
3879
  <span style="color: #9ca3af; display: flex; align-items: center; gap: 4px;"
3880
- >${D} ${i}</span
3880
+ >${$} ${i}</span
3881
3881
  >
3882
3882
  </div>
3883
3883
  <div
@@ -3889,7 +3889,7 @@ var StreamitPlayer=function(B){"use strict";/**
3889
3889
  >
3890
3890
  <span>${this.localize("backgroundColour","Background colour")}</span>
3891
3891
  <span style="color: #9ca3af; display: flex; align-items: center; gap: 4px;"
3892
- >${q} ${i}</span
3892
+ >${H} ${i}</span
3893
3893
  >
3894
3894
  </div>
3895
3895
  <div
@@ -3963,7 +3963,7 @@ var StreamitPlayer=function(B){"use strict";/**
3963
3963
  <span>${this.localize("reset","Reset")}</span>
3964
3964
  </div>
3965
3965
  </div>
3966
- `}case"opt-font-family":return this.renderAppearanceSelectionScreen("Font family",ns,"fontFamily");case"opt-font-color":return this.renderAppearanceSelectionScreen("Font colour",He,"fontColor");case"opt-font-size":return this.renderAppearanceSelectionScreen("Font size",os,"fontSize");case"opt-background-color":return this.renderAppearanceSelectionScreen("Background colour",He,"backgroundColor");case"opt-background-opacity":return this.renderAppearanceSelectionScreen("Background opacity",qe,"backgroundOpacity");case"opt-window-color":return this.renderAppearanceSelectionScreen("Window colour",He,"windowColor");case"opt-window-opacity":return this.renderAppearanceSelectionScreen("Window opacity",qe,"windowOpacity");case"opt-character-edge":return this.renderAppearanceSelectionScreen("Character edge style",ls,"characterEdgeStyle");case"opt-font-opacity":return this.renderAppearanceSelectionScreen("Font opacity",qe,"fontOpacity");case"sleeptimer":{const V=!!((f=this.playerState)!=null&&f.isLive),F=((g=(p=this.config)==null?void 0:p.sleepTimer)==null?void 0:g.presets)||[10,15,20,30,45,60],L=[{value:"off",label:this.localize("off","Off")},...F.map(D=>({value:D,label:`${D} ${this.localize("minutes","minutes")}`})),...V?[]:[{value:"end",label:this.localize("endOfVideo","End of video")}]];return k`
3966
+ `}case"opt-font-family":return this.renderAppearanceSelectionScreen("Font family",ns,"fontFamily");case"opt-font-color":return this.renderAppearanceSelectionScreen("Font colour",He,"fontColor");case"opt-font-size":return this.renderAppearanceSelectionScreen("Font size",os,"fontSize");case"opt-background-color":return this.renderAppearanceSelectionScreen("Background colour",He,"backgroundColor");case"opt-background-opacity":return this.renderAppearanceSelectionScreen("Background opacity",qe,"backgroundOpacity");case"opt-window-color":return this.renderAppearanceSelectionScreen("Window colour",He,"windowColor");case"opt-window-opacity":return this.renderAppearanceSelectionScreen("Window opacity",qe,"windowOpacity");case"opt-character-edge":return this.renderAppearanceSelectionScreen("Character edge style",ls,"characterEdgeStyle");case"opt-font-opacity":return this.renderAppearanceSelectionScreen("Font opacity",qe,"fontOpacity");case"sleeptimer":{const V=!!((f=this.playerState)!=null&&f.isLive),U=((g=(p=this.config)==null?void 0:p.sleepTimer)==null?void 0:g.presets)||[10,15,20,30,45,60],L=[{value:"off",label:this.localize("off","Off")},...U.map($=>({value:$,label:`${$} ${this.localize("minutes","minutes")}`})),...V?[]:[{value:"end",label:this.localize("endOfVideo","End of video")}]];return k`
3967
3967
  <div
3968
3968
  class="settings-header"
3969
3969
  @click=${this.settingsMenu.backToMain}
@@ -3975,26 +3975,26 @@ var StreamitPlayer=function(B){"use strict";/**
3975
3975
  ${e} ${this.localize("sleepTimer","Sleep Timer")}
3976
3976
  </div>
3977
3977
  <div class="settings-list-scroll" role="menu">
3978
- ${L.map(D=>{const q=this.playerState.sleepTimerSetting===D.value;return k`
3978
+ ${L.map($=>{const H=this.playerState.sleepTimerSetting===$.value;return k`
3979
3979
  <div
3980
3980
  class="settings-item"
3981
- @click=${()=>this.handleSelectSleepTimer(D.value)}
3981
+ @click=${()=>this.handleSelectSleepTimer($.value)}
3982
3982
  role="menuitemradio"
3983
- aria-checked=${q?"true":"false"}
3983
+ aria-checked=${H?"true":"false"}
3984
3984
  tabindex="0"
3985
3985
  @keydown=${this.settingsMenu.handleItemKey}
3986
3986
  >
3987
- ${D.value==="end"?k`
3987
+ ${$.value==="end"?k`
3988
3988
  <span
3989
3989
  style="display: flex; flex-direction: column; align-items: flex-start;"
3990
3990
  >
3991
- <span>${D.label}</span>
3991
+ <span>${$.label}</span>
3992
3992
  ${this.getRemainingVideoTimeText()?k`<span style="font-size: 11px; color: #9ca3af; margin-top: 2px;">
3993
3993
  ${this.getRemainingVideoTimeText()}
3994
3994
  </span>`:""}
3995
3995
  </span>
3996
- `:k`<span>${D.label}</span>`}
3997
- ${q?t:""}
3996
+ `:k`<span>${$.label}</span>`}
3997
+ ${H?t:""}
3998
3998
  </div>
3999
3999
  `})}
4000
4000
  </div>
@@ -4010,12 +4010,12 @@ var StreamitPlayer=function(B){"use strict";/**
4010
4010
  ${e} ${this.localize("chapters","Chapters")}
4011
4011
  </div>
4012
4012
  <div class="settings-list-scroll" role="menu">
4013
- ${this.playerState.chapters.map((V,F)=>k`
4013
+ ${this.playerState.chapters.map((V,U)=>k`
4014
4014
  <div
4015
4015
  class="settings-item"
4016
- @click=${()=>{this.handleSelectChapter(F),this.settingsMenu.close()}}
4016
+ @click=${()=>{this.handleSelectChapter(U),this.settingsMenu.close()}}
4017
4017
  role="menuitemradio"
4018
- aria-checked=${this.playerState.activeChapterIndex===F}
4018
+ aria-checked=${this.playerState.activeChapterIndex===U}
4019
4019
  tabindex="0"
4020
4020
  @keydown=${this.settingsMenu.handleItemKey}
4021
4021
  >
@@ -4025,11 +4025,11 @@ var StreamitPlayer=function(B){"use strict";/**
4025
4025
  ${ce(V.startTime)}
4026
4026
  </span>
4027
4027
  </span>
4028
- ${this.playerState.activeChapterIndex===F?t:""}
4028
+ ${this.playerState.activeChapterIndex===U?t:""}
4029
4029
  </div>
4030
4030
  `)}
4031
4031
  </div>
4032
- `;default:{if(this.customSettingsScreens.has(this.activeMenuScreen))try{const z=this.customSettingsScreens.get(this.activeMenuScreen);if(z){const se=z(this,()=>this.settingsMenu.backToMain());if(se)return se}}catch(z){console.error(`[Player] Error rendering custom settings screen ${this.activeMenuScreen}:`,z)}if(this.controller){const z=this.controller.getPlugins();for(const se of z)if(se.renderSettingsScreen){const he=se.renderSettingsScreen(this.activeMenuScreen,this.controller,()=>this.settingsMenu.backToMain());if(he)return he}}const V=this.playerState.playbackRate===1?this.localize("normal","Normal"):`${this.playerState.playbackRate}x`,F=((m=this.config)==null?void 0:m.controls)||{},L=this.displayMode==="vertical",D=(y=(v=this.config)==null?void 0:v.vertical)==null?void 0:y.menus,q=L&&(D==null?void 0:D.playbackSpeed)!==void 0?D.playbackSpeed:F.playbackSpeed!==!1,de=L&&(D==null?void 0:D.quality)!==void 0?D.quality:F.quality!==!1,le=L&&(D==null?void 0:D.audioTracks)!==void 0?D.audioTracks:F.audioTracks!==!1,Fe=L&&(D==null?void 0:D.subtitles)!==void 0?D.subtitles:F.subtitles!==!1,Ue=L&&(D==null?void 0:D.sleepTimer)!==void 0?D.sleepTimer:F.sleepTimer!==!1,Ke=F.loop!==!1&&((S=(b=this.config)==null?void 0:b.playback)==null?void 0:S.loop)!==!1,ae=L&&(D==null?void 0:D.autoScroll)!==void 0?D.autoScroll:F.autoScroll!==!1,wt=L&&(D==null?void 0:D.chapters)!==void 0?D.chapters:F.chapters===!0,ot=[];if(this.controller){const z=this.controller.getPlugins();for(const se of z)if(se.getSettingsItems){const he=se.getSettingsItems(this.controller);he&&ot.push(...he)}}const Tt=(((E=(T=this.config)==null?void 0:T.settings)==null?void 0:E.order)||["speed","quality","audioTracks","subtitles","autoScroll","sleepTimer","loop"]).map(z=>z==="captions"?"subtitles":z==="playbackSpeed"?"speed":z==="audio"?"audioTracks":z),ne=new Map;if(q&&ne.set("speed",k`
4032
+ `;default:{if(this.customSettingsScreens.has(this.activeMenuScreen))try{const z=this.customSettingsScreens.get(this.activeMenuScreen);if(z){const se=z(this,()=>this.settingsMenu.backToMain());if(se)return se}}catch(z){console.error(`[Player] Error rendering custom settings screen ${this.activeMenuScreen}:`,z)}if(this.controller){const z=this.controller.getPlugins();for(const se of z)if(se.renderSettingsScreen){const he=se.renderSettingsScreen(this.activeMenuScreen,this.controller,()=>this.settingsMenu.backToMain());if(he)return he}}const V=this.playerState.playbackRate===1?this.localize("normal","Normal"):`${this.playerState.playbackRate}x`,U=((m=this.config)==null?void 0:m.controls)||{},L=this.displayMode==="vertical",$=(y=(v=this.config)==null?void 0:v.vertical)==null?void 0:y.menus,H=L&&($==null?void 0:$.playbackSpeed)!==void 0?$.playbackSpeed:U.playbackSpeed!==!1,de=L&&($==null?void 0:$.quality)!==void 0?$.quality:U.quality!==!1,le=L&&($==null?void 0:$.audioTracks)!==void 0?$.audioTracks:U.audioTracks!==!1,Fe=L&&($==null?void 0:$.subtitles)!==void 0?$.subtitles:U.subtitles!==!1,Ue=L&&($==null?void 0:$.sleepTimer)!==void 0?$.sleepTimer:U.sleepTimer!==!1,Ke=U.loop!==!1&&((S=(b=this.config)==null?void 0:b.playback)==null?void 0:S.loop)!==!1,ae=L&&($==null?void 0:$.autoScroll)!==void 0?$.autoScroll:U.autoScroll!==!1,wt=L&&($==null?void 0:$.chapters)!==void 0?$.chapters:U.chapters===!0,ot=[];if(this.controller){const z=this.controller.getPlugins();for(const se of z)if(se.getSettingsItems){const he=se.getSettingsItems(this.controller);he&&ot.push(...he)}}const Tt=(((E=(T=this.config)==null?void 0:T.settings)==null?void 0:E.order)||["speed","quality","audioTracks","subtitles","autoScroll","sleepTimer","loop"]).map(z=>z==="captions"?"subtitles":z==="playbackSpeed"?"speed":z==="audio"?"audioTracks":z),ne=new Map;if(H&&ne.set("speed",k`
4033
4033
  <div
4034
4034
  class="settings-item"
4035
4035
  @click=${()=>this.settingsMenu.goTo("speed")}
@@ -4080,7 +4080,7 @@ var StreamitPlayer=function(B){"use strict";/**
4080
4080
  <span>${this.localize("subtitles","Subtitles")}</span>
4081
4081
  <span class="settings-item-value">
4082
4082
  <span>
4083
- ${this.playerState.activeSubtitleTrackId===null||!this.playerState.captionsEnabled?this.localize("off","Off"):((A=this.playerState.subtitleTracks.find(z=>z.id===this.playerState.activeSubtitleTrackId))==null?void 0:A.label)||this.localize("on","On")}
4083
+ ${this.playerState.activeSubtitleTrackId===null||!this.playerState.captionsEnabled?this.localize("off","Off"):((x=this.playerState.subtitleTracks.find(z=>z.id===this.playerState.activeSubtitleTrackId))==null?void 0:x.label)||this.localize("on","On")}
4084
4084
  </span>
4085
4085
  ${i}
4086
4086
  </span>
@@ -4098,7 +4098,7 @@ var StreamitPlayer=function(B){"use strict";/**
4098
4098
  ${se} ${i}
4099
4099
  </span>
4100
4100
  </div>
4101
- `)}((($=(P=this.config)==null?void 0:P.settings)==null?void 0:$.pictureInPicture)===!0||((I=(M=this.config)==null?void 0:M.settings)==null?void 0:I.pip)===!0)&&ne.set("pictureInPicture",k`
4101
+ `)}(((O=(A=this.config)==null?void 0:A.settings)==null?void 0:O.pictureInPicture)===!0||((I=(M=this.config)==null?void 0:M.settings)==null?void 0:I.pip)===!0)&&ne.set("pictureInPicture",k`
4102
4102
  <div
4103
4103
  class="settings-item"
4104
4104
  @click=${()=>{this.handlePictureInPictureToggle(),this.settingsMenu.close()}}
@@ -4110,7 +4110,7 @@ var StreamitPlayer=function(B){"use strict";/**
4110
4110
  <span>${this.localize("pictureInPicture","Picture in Picture")}</span>
4111
4111
  <span class="settings-toggle ${this.playerState.pictureInPicture?"active":""}"></span>
4112
4112
  </div>
4113
- `),((N=(R=this.config)==null?void 0:R.settings)==null?void 0:N.fullscreen)===!0&&ne.set("fullscreen",k`
4113
+ `),((N=(D=this.config)==null?void 0:D.settings)==null?void 0:N.fullscreen)===!0&&ne.set("fullscreen",k`
4114
4114
  <div
4115
4115
  class="settings-item"
4116
4116
  @click=${()=>{this.handleFullscreenToggle(),this.settingsMenu.close()}}
@@ -4189,7 +4189,7 @@ var StreamitPlayer=function(B){"use strict";/**
4189
4189
  ${z.valueLabel||""} ${i}
4190
4190
  </span>
4191
4191
  </div>
4192
- `;ne.set(z.id||`custom-${se}`,he)});const Et=(U=this.config)==null?void 0:U.customItems,lt=((x=(C=this.config)==null?void 0:C.settings)==null?void 0:x.customItems)||Et||[];Array.isArray(lt)&&lt.forEach((z,se)=>{const he=k`
4192
+ `;ne.set(z.id||`custom-${se}`,he)});const Et=(P=this.config)==null?void 0:P.customItems,lt=((R=(C=this.config)==null?void 0:C.settings)==null?void 0:R.customItems)||Et||[];Array.isArray(lt)&&lt.forEach((z,se)=>{const he=k`
4193
4193
  <div
4194
4194
  class="settings-item"
4195
4195
  @click=${()=>{typeof z.onClick=="function"&&z.onClick(this)}}
@@ -4202,7 +4202,7 @@ var StreamitPlayer=function(B){"use strict";/**
4202
4202
  ${z.valueLabel||""} ${i}
4203
4203
  </span>
4204
4204
  </div>
4205
- `;ne.set(z.id||`static-custom-${se}`,he)});const xe=[],We=(te=(H=this.config)==null?void 0:H.settings)==null?void 0:te.groups;if(We&&typeof We=="object"){Object.entries(We).forEach(([z,se])=>{if(!Array.isArray(se))return;const he=[];if(se.forEach(Be=>{const ct=ne.get(Be);ct&&(he.push(ct),ne.delete(Be))}),he.length>0){const Be=k`
4205
+ `;ne.set(z.id||`static-custom-${se}`,he)});const xe=[],We=(te=(q=this.config)==null?void 0:q.settings)==null?void 0:te.groups;if(We&&typeof We=="object"){Object.entries(We).forEach(([z,se])=>{if(!Array.isArray(se))return;const he=[];if(se.forEach(Be=>{const ct=ne.get(Be);ct&&(he.push(ct),ne.delete(Be))}),he.length>0){const Be=k`
4206
4206
  <div class="settings-group-header" part="settings-group-header">
4207
4207
  ${this.localize(z,z)}
4208
4208
  </div>
@@ -4313,11 +4313,11 @@ var StreamitPlayer=function(B){"use strict";/**
4313
4313
  <div class="error-message">${t}</div>
4314
4314
  <button class="retry-btn" @click=${e.handleRetryLoad}>${e.localize("retryPlayback","Retry Playback")}</button>
4315
4315
  </div>
4316
- `:""}renderDefaultLiveOverlay(e){var i,s;return(((s=(i=e.config)==null?void 0:i.layout)==null?void 0:s.mode)||e.displayMode)!=="vertical"||!e.playerState.isLive?"":k`
4316
+ `:""}renderDefaultLiveOverlay(e){return e.displayMode!=="vertical"||!e.playerState.isLive?"":k`
4317
4317
  <div
4318
4318
  class="vertical-persistent-live-badge ${e.playerState.isAtLiveEdge?"live":"behind"}"
4319
4319
  @click=${e.handleLiveBadgeClick}
4320
- @keydown=${r=>{(r.key==="Enter"||r.key===" ")&&(r.preventDefault(),e.handleLiveBadgeClick(r))}}
4320
+ @keydown=${i=>{(i.key==="Enter"||i.key===" ")&&(i.preventDefault(),e.handleLiveBadgeClick(i))}}
4321
4321
  role="button"
4322
4322
  tabindex="0"
4323
4323
  aria-label="${e.playerState.isAtLiveEdge?"Playing at live edge":"Seek to live edge"}"
@@ -4473,7 +4473,7 @@ var StreamitPlayer=function(B){"use strict";/**
4473
4473
  >${G(this.getIcon("fullscreen"))}</slot
4474
4474
  >`}
4475
4475
  </button>
4476
- `;default:return""}}handleSkipAd(){this.controller&&this.controller.ads&&this.controller.ads.skip()}handleAdClickThrough(){var t,i;const e=(t=this.playerState)==null?void 0:t.currentAd;if(e!=null&&e.clickThroughUrl)try{window.open(e.clickThroughUrl,"_blank"),(i=this.controller)==null||i.emit("adclick",{adId:e.id,clickUrl:e.clickThroughUrl})}catch(s){console.error("Ad clickthrough failed:",s)}}renderAdUIOverlay(){var m,v,y,b,S,T,E,A,P,$,M,I,R;if(!((m=this.playerState)!=null&&m.isAdPlaying))return"";const e=this.playerState.currentAd;if(e&&e.linear===!1||this.playerState.adLinear===!1)return"";const t=this.playerState.currentAdBreak,i=this.playerState.adPosition,s=((v=t==null?void 0:t.ads)==null?void 0:v.length)||1,r=(e==null?void 0:e.title)||"",a=!!this.playerState.canSkipAd,n=this.playerState.skipAvailableAt,l=a||n!=null,o=this.playerState.adDuration||(e==null?void 0:e.duration)||0,d=this.playerState.adCurrentTime??Math.max(0,o-(this.playerState.adRemainingTime??o)),h=Math.ceil(this.playerState.adRemainingTime??Math.max(0,o-d)),u=o>0?Math.min(100,d/o*100):0,f=!!((S=(b=(y=this.controller)==null?void 0:y.config)==null?void 0:b.ads)!=null&&S.showAdTitle),p=((P=(A=(E=(T=this.controller)==null?void 0:T.config)==null?void 0:E.ads)==null?void 0:A.ui)==null?void 0:P.showSkipButton)??!0,g=((R=(I=(M=($=this.controller)==null?void 0:$.config)==null?void 0:M.ads)==null?void 0:I.ui)==null?void 0:R.showCountdown)??!0;return k`
4476
+ `;default:return""}}handleSkipAd(){this.controller&&this.controller.ads&&this.controller.ads.skip()}handleAdClickThrough(){var t,i;const e=(t=this.playerState)==null?void 0:t.currentAd;if(e!=null&&e.clickThroughUrl)try{window.open(e.clickThroughUrl,"_blank"),(i=this.controller)==null||i.emit("adclick",{adId:e.id,clickUrl:e.clickThroughUrl})}catch(s){console.error("Ad clickthrough failed:",s)}}renderAdUIOverlay(){var m,v,y,b,S,T,E,x,A,O,M,I,D;if(!((m=this.playerState)!=null&&m.isAdPlaying))return"";const e=this.playerState.currentAd;if(e&&e.linear===!1||this.playerState.adLinear===!1)return"";const t=this.playerState.currentAdBreak,i=this.playerState.adPosition,s=((v=t==null?void 0:t.ads)==null?void 0:v.length)||1,r=(e==null?void 0:e.title)||"",a=!!this.playerState.canSkipAd,n=this.playerState.skipAvailableAt,l=a||n!=null,o=this.playerState.adDuration||(e==null?void 0:e.duration)||0,d=this.playerState.adCurrentTime??Math.max(0,o-(this.playerState.adRemainingTime??o)),h=Math.ceil(this.playerState.adRemainingTime??Math.max(0,o-d)),u=o>0?Math.min(100,d/o*100):0,f=!!((S=(b=(y=this.controller)==null?void 0:y.config)==null?void 0:b.ads)!=null&&S.showAdTitle),p=((A=(x=(E=(T=this.controller)==null?void 0:T.config)==null?void 0:E.ads)==null?void 0:x.ui)==null?void 0:A.showSkipButton)??!0,g=((D=(I=(M=(O=this.controller)==null?void 0:O.config)==null?void 0:M.ads)==null?void 0:I.ui)==null?void 0:D.showCountdown)??!0;return k`
4477
4477
  <div class="player-ad-ui-overlay" part="ad-ui-overlay">
4478
4478
  <!-- Top Left Ad Info Badge (Compact by default) -->
4479
4479
  <div class="ad-badge-top" @click=${this.handleAdClickThrough}>
@@ -4510,7 +4510,7 @@ var StreamitPlayer=function(B){"use strict";/**
4510
4510
  <div class="ad-progress-bar-fill" part="ad-progress-fill" style="width: ${u}%"></div>
4511
4511
  </div>
4512
4512
  </div>
4513
- `}render(){var u,f,p,g,m,v,y,b,S,T,E,A,P,$,M,I,R,N,U,C;const{isPlaying:e,status:t,currentTime:i,duration:s,bufferedRanges:r,isBuffering:a,error:n,currentSource:l,loop:o}=this.playerState,d=this.controlsVisible||!e,h=((f=(u=this.config)==null?void 0:u.layout)==null?void 0:f.mode)||this.displayMode;return k`
4513
+ `}render(){var u,f,p,g,m,v,y,b,S,T,E,x,A,O,M,I,D,N;const{isPlaying:e,status:t,currentTime:i,duration:s,bufferedRanges:r,isBuffering:a,error:n,currentSource:l,loop:o}=this.playerState,d=this.controlsVisible||!e,h=this.displayMode;return k`
4514
4514
  <div
4515
4515
  part="player-container"
4516
4516
  class="player-container layout-${h} ${d?"controls-visible":""} source-type-${this.playerState.sourceType} ${this.isVisualTransitioning?"feed-transitioning":""} transition-stage-${this.transitionStage} transition-direction-${this.transitionDirection}"
@@ -4530,12 +4530,12 @@ var StreamitPlayer=function(B){"use strict";/**
4530
4530
  <canvas part="transition-canvas" class="transition-canvas"></canvas>
4531
4531
  </div>
4532
4532
 
4533
- ${!l&&this.emptyStateSectionEnabled&&((g=(p=this.config)==null?void 0:p.controls)==null?void 0:g.emptyState)!==!1?this.renderEmptyState():k`
4533
+ ${!l&&this.emptyStateSectionEnabled&&((f=(u=this.config)==null?void 0:u.controls)==null?void 0:f.emptyState)!==!1?this.renderEmptyState():k`
4534
4534
  <!-- Custom overlay slot -->
4535
4535
  <slot name="top-overlay"></slot>
4536
4536
 
4537
4537
  <!-- Center Play Button Overlay -->
4538
- ${(m=this.playerState)!=null&&m.isAdPlaying?"":this.renderOverlay("center-play",x=>this.renderDefaultCenterPlayOverlay(x))}
4538
+ ${(p=this.playerState)!=null&&p.isAdPlaying?"":this.renderOverlay("center-play",P=>this.renderDefaultCenterPlayOverlay(P))}
4539
4539
 
4540
4540
  <!-- Audio only cover -->
4541
4541
  ${h==="audio-only"?k`
@@ -4566,7 +4566,7 @@ var StreamitPlayer=function(B){"use strict";/**
4566
4566
  aria-modal="true"
4567
4567
  aria-labelledby="sleep-title"
4568
4568
  aria-describedby="sleep-desc"
4569
- @click=${x=>x.stopPropagation()}
4569
+ @click=${P=>P.stopPropagation()}
4570
4570
  >
4571
4571
  <div part="sleep-timer-dialog-content" class="sleep-timer-dialog-card">
4572
4572
  <div part="sleep-timer-title" class="sleep-timer-dialog-title" id="sleep-title">
@@ -4579,14 +4579,14 @@ var StreamitPlayer=function(B){"use strict";/**
4579
4579
  <button
4580
4580
  part="sleep-timer-btn sleep-timer-btn-add"
4581
4581
  class="sleep-timer-btn sleep-timer-btn-add secondary"
4582
- @click=${x=>{x.stopPropagation(),this.handleSleepTimerAddTime()}}
4582
+ @click=${P=>{P.stopPropagation(),this.handleSleepTimerAddTime()}}
4583
4583
  >
4584
4584
  ${this.localize("addTime","Add time")}
4585
4585
  </button>
4586
4586
  <button
4587
4587
  part="sleep-timer-btn sleep-timer-btn-close"
4588
4588
  class="sleep-timer-btn sleep-timer-btn-close primary"
4589
- @click=${x=>{x.stopPropagation(),this.handleSleepTimerClose()}}
4589
+ @click=${P=>{P.stopPropagation(),this.handleSleepTimerClose()}}
4590
4590
  >
4591
4591
  ${this.localize("close","Close")}
4592
4592
  </button>
@@ -4596,24 +4596,24 @@ var StreamitPlayer=function(B){"use strict";/**
4596
4596
  `:""}
4597
4597
 
4598
4598
  <!-- Error State Overlay -->
4599
- ${n?this.renderOverlay("error",x=>this.renderDefaultErrorOverlay(x)):""}
4599
+ ${n?this.renderOverlay("error",P=>this.renderDefaultErrorOverlay(P)):""}
4600
4600
 
4601
4601
  <!-- Buffering Loading Spinner Overlay -->
4602
- ${a&&!n?this.renderOverlay("buffering",x=>this.renderDefaultBufferingOverlay(x)):""}
4602
+ ${a&&!n?this.renderOverlay("buffering",P=>this.renderDefaultBufferingOverlay(P)):""}
4603
4603
 
4604
4604
  <!-- Centered Replay Overlay (not shown in vertical mode) -->
4605
- ${t==="ended"&&!this.playerState.isLive&&this.displayMode!=="vertical"&&!o&&!((v=this.playerState)!=null&&v.isAdPlaying)?this.renderOverlay("replay",x=>this.renderDefaultReplayOverlay(x)):""}
4605
+ ${t==="ended"&&!this.playerState.isLive&&this.displayMode!=="vertical"&&!o&&!((g=this.playerState)!=null&&g.isAdPlaying)?this.renderOverlay("replay",P=>this.renderDefaultReplayOverlay(P)):""}
4606
4606
 
4607
4607
  <!-- Ambient Tap Skip / Volume / Playback Speed gesture feedback ripples -->
4608
- ${this.tapFeedback&&!((y=this.playerState)!=null&&y.isAdPlaying)?this.renderOverlay("seek",(x,H)=>this.renderDefaultSeekOverlay(x,H),this.tapFeedback):""}
4609
- ${this.playPauseFeedback&&!((b=this.playerState)!=null&&b.isAdPlaying)?this.renderOverlay("play-pause",x=>this.renderDefaultPlayPauseOverlay(x)):""}
4610
- ${this.activeVolumeFeedback&&!((S=this.playerState)!=null&&S.isAdPlaying)?this.renderOverlay("volume",x=>this.renderDefaultVolumeOverlay(x)):""}
4611
- ${this.activeSpeedFeedback&&!((T=this.playerState)!=null&&T.isAdPlaying)?this.renderOverlay("speed",x=>this.renderDefaultSpeedOverlay(x)):""}
4608
+ ${this.tapFeedback&&!((m=this.playerState)!=null&&m.isAdPlaying)?this.renderOverlay("seek",(P,C)=>this.renderDefaultSeekOverlay(P,C),this.tapFeedback):""}
4609
+ ${this.playPauseFeedback&&!((v=this.playerState)!=null&&v.isAdPlaying)?this.renderOverlay("play-pause",P=>this.renderDefaultPlayPauseOverlay(P)):""}
4610
+ ${this.activeVolumeFeedback&&!((y=this.playerState)!=null&&y.isAdPlaying)?this.renderOverlay("volume",P=>this.renderDefaultVolumeOverlay(P)):""}
4611
+ ${this.activeSpeedFeedback&&!((b=this.playerState)!=null&&b.isAdPlaying)?this.renderOverlay("speed",P=>this.renderDefaultSpeedOverlay(P)):""}
4612
4612
 
4613
4613
  <!-- Persistent Live Badge for Vertical Player -->
4614
- ${h==="vertical"&&this.playerState.isLive&&!((E=this.playerState)!=null&&E.isAdPlaying)?this.renderOverlay("live",x=>this.renderDefaultLiveOverlay(x)):""}
4614
+ ${h==="vertical"&&this.playerState.isLive&&!((S=this.playerState)!=null&&S.isAdPlaying)?this.renderOverlay("live",P=>this.renderDefaultLiveOverlay(P)):""}
4615
4615
 
4616
- ${(A=this.playerState)!=null&&A.isAdPlaying?"":k`
4616
+ ${(T=this.playerState)!=null&&T.isAdPlaying?"":k`
4617
4617
  <!-- Ambient top/bottom vignette scrim -->
4618
4618
  <div part="scrim" class="scrim ${d?"visible":""}"></div>
4619
4619
 
@@ -4632,12 +4632,12 @@ var StreamitPlayer=function(B){"use strict";/**
4632
4632
 
4633
4633
  <!-- Control overlays wrapper -->
4634
4634
  <div part="controls-overlay" class="controls-overlay">
4635
- ${h==="custom"?k`<slot></slot>`:h==="vertical"?(($=(P=this.config)==null?void 0:P.controls)==null?void 0:$.verticalControls)!==!1&&this.controlsSectionEnabled?k`
4635
+ ${h==="custom"?k`<slot></slot>`:h==="vertical"?((x=(E=this.config)==null?void 0:E.controls)==null?void 0:x.verticalControls)!==!1&&this.controlsSectionEnabled?k`
4636
4636
  <player-vertical-controls
4637
4637
  part="vertical-controls"
4638
4638
  exportparts="vertical-controls-container, action-rail, rail-btn, seekbar, seekbar-container, hover-tooltip, tooltip-marker-label, thumbnail-container, thumbnail-preview, tooltip-time-text, track, buffer-bar, progress-bar, handle, marker, time-display"
4639
- ?hideCurrentTime=${((I=(M=this.config)==null?void 0:M.controls)==null?void 0:I.currentTime)===!1}
4640
- ?hideDuration=${((N=(R=this.config)==null?void 0:R.controls)==null?void 0:N.duration)===!1}
4639
+ ?hideCurrentTime=${((O=(A=this.config)==null?void 0:A.controls)==null?void 0:O.currentTime)===!1}
4640
+ ?hideDuration=${((I=(M=this.config)==null?void 0:M.controls)==null?void 0:I.duration)===!1}
4641
4641
  .currentTime=${i}
4642
4642
  .duration=${s}
4643
4643
  .bufferedRanges=${r}
@@ -4664,7 +4664,7 @@ var StreamitPlayer=function(B){"use strict";/**
4664
4664
  <slot name="social-actions" slot="social-actions"></slot>
4665
4665
  <slot name="bottom-actions" slot="bottom-actions"></slot>
4666
4666
  </player-vertical-controls>
4667
- `:"":((C=(U=this.config)==null?void 0:U.controls)==null?void 0:C.controlsBar)!==!1&&this.controlsSectionEnabled?this.renderStandardControls():""}
4667
+ `:"":((N=(D=this.config)==null?void 0:D.controls)==null?void 0:N.controlsBar)!==!1&&this.controlsSectionEnabled?this.renderStandardControls():""}
4668
4668
  </div>
4669
4669
  `}
4670
4670
 
@@ -4687,14 +4687,14 @@ var StreamitPlayer=function(B){"use strict";/**
4687
4687
  aria-label="Context menu"
4688
4688
  @keydown=${this.handleContextMenuKeyDown}
4689
4689
  >
4690
- ${this.getContextMenuItems().map(x=>k`
4690
+ ${this.getContextMenuItems().map(P=>k`
4691
4691
  <div
4692
- class="context-menu-item ${x.disabled?"disabled":""}"
4693
- @click=${()=>this.handleContextMenuItemClick(x)}
4692
+ class="context-menu-item ${P.disabled?"disabled":""}"
4693
+ @click=${()=>this.handleContextMenuItemClick(P)}
4694
4694
  role="menuitem"
4695
- tabindex="${x.disabled?"-1":"0"}"
4695
+ tabindex="${P.disabled?"-1":"0"}"
4696
4696
  >
4697
- ${x.label}
4697
+ ${P.label}
4698
4698
  </div>
4699
4699
  `)}
4700
4700
  </div>
@@ -4747,4 +4747,4 @@ var StreamitPlayer=function(B){"use strict";/**
4747
4747
  </div>
4748
4748
  `}
4749
4749
  </div>
4750
- `}getStatistics(){return this.controller?this.controller.getStatistics():null}};ni.styles=Ds;let _=ni;if(W([O({type:String,reflect:!0})],_.prototype,"src"),W([O({type:String,reflect:!0})],_.prototype,"captions"),W([O({type:Boolean,reflect:!0})],_.prototype,"autoplay"),W([O({type:Boolean,reflect:!0})],_.prototype,"muted"),W([O({type:Number,reflect:!0})],_.prototype,"volume"),W([O({type:String,attribute:"display-mode",reflect:!0})],_.prototype,"displayMode"),W([O({type:Number})],_.prototype,"nearEndThreshold"),W([O({type:Boolean,attribute:"auto-scroll",reflect:!0})],_.prototype,"autoScroll"),W([O({type:String,attribute:"live-mode",reflect:!0})],_.prototype,"liveMode"),W([O({type:Object})],_.prototype,"config"),W([O({type:Boolean,attribute:"precise-seek",reflect:!0})],_.prototype,"preciseSeekEnabled"),W([O({type:Boolean,attribute:"smart-seek",reflect:!0})],_.prototype,"smartSeekEnabled"),W([O({type:String,reflect:!0})],_.prototype,"preload"),W([O({type:Boolean,reflect:!0})],_.prototype,"loop"),W([O({type:Boolean,reflect:!0})],_.prototype,"playsinline"),W([O({type:String,reflect:!0})],_.prototype,"poster"),W([O({type:String,reflect:!0})],_.prototype,"crossorigin"),W([j()],_.prototype,"isVisualTransitioning"),W([j()],_.prototype,"transitionDirection"),W([j()],_.prototype,"transitionStage"),W([j()],_.prototype,"contextMenuOpen"),W([j()],_.prototype,"contextMenuX"),W([j()],_.prototype,"contextMenuY"),W([j({hasChanged(c,e){return e?["status","isPlaying","currentTime","duration","volume","isMuted","isFullscreen","bufferedRanges","playbackRate","captionsEnabled","currentSource","sourceType","isBuffering","isSeeking","hasCaptions","error","qualities","activeQuality","audioTracks","activeAudioTrack","subtitleTracks","activeSubtitleTrackId","chapters","activeChapterIndex","isLive","isLowLatency","isAtLiveEdge","hasDvr","displayMode","liveMode","loop","playlist","activePlaylistIndex","playlistRepeatMode","autoScroll","seekableRange","isAdPlaying","isAdLoading","currentAd","currentAdBreak","adCurrentTime","adRemainingTime","adDuration","canSkipAd","skipAvailableAt","adPosition","adProvider","adLinear","adMuted"].some(i=>{const s=c[i],r=e[i];if(i==="seekableRange"){const a=s,n=r;return!a||!n||a.start!==n.start||a.end!==n.end}if(i==="bufferedRanges"){const a=s,n=r;if(!a||!n||a.length!==n.length)return!0;for(let l=0;l<a.length;l++)if(a[l].start!==n[l].start||a[l].end!==n[l].end)return!0;return!1}return s!==r}):!0}})],_.prototype,"playerState"),W([j()],_.prototype,"controlsVisible"),W([j()],_.prototype,"settingsMenuOpen"),W([j()],_.prototype,"activeMenuScreen"),W([j()],_.prototype,"toastMessage"),W([j()],_.prototype,"toastType"),W([j()],_.prototype,"toastVisible"),W([j()],_.prototype,"tapFeedback"),W([j()],_.prototype,"feedbackTaps"),W([j()],_.prototype,"playPauseFeedback"),W([j()],_.prototype,"activeVolumeFeedback"),W([j()],_.prototype,"isSeekingInteraction"),W([j()],_.prototype,"activeSpeedFeedback"),W([j()],_.prototype,"activeQualityFeedback"),W([Us("video")],_.prototype,"videoElement"),W([j()],_.prototype,"isPreciseSeeking"),W([j()],_.prototype,"speedLockState"),W([j()],_.prototype,"isSpeedOverlayFadingOut"),W([j()],_.prototype,"isVolumeFeedbackFadingOut"),typeof window<"u"&&typeof customElements<"u"&&(customElements.get("streamit-player")||customElements.define("streamit-player",_),!customElements.get("player-player"))){class c extends _{}customElements.define("player-player",c)}return B.AdBreakManager=Ki,B.AdBreakType=xi,B.AdErrorType=ie,B.AdPlacementType=Pi,B.AdProviderType=Ai,B.AdSkipMode=ze,B.AdState=w,B.AdsController=Yi,B.AdsManager=Wi,B.AdsValidator=Mi,B.AutoThumbnailProvider=_e,B.DrmManager=De,B.DrmValidator=Tr,B.HtmlOverlayRenderer=st,B.IconRegistry=X,B.ImaProvider=at,B.KeyboardManager=Ni,B.PlayerChaptersButton=ve,B.PlayerController=is,B.PlayerIconRegistry=ss,B.PlayerPlayButton=$e,B.PlayerPlayer=_,B.PlayerSeekButton=we,B.PlayerSeekbar=Y,B.PlayerVerticalControls=ue,B.PlayerVolumeControl=Te,B.SimidBridge=Vi,B.SimidErrorCode=zt,B.SimidManager=zi,B.SimidRuntime=_i,B.SimidSession=vt,B.SpriteThumbnailProvider=es,B.THEME_PRESETS=Jt,B.TimelineMath=pe,B.TrackingEventName=Ci,B.VTTThumbnailProvider=Ji,B.VastProvider=qt,B.VideoFrameThumbnailProvider=Zi,B.VmapProvider=jt,B.compileTheme=as,B.detectSupportedKeySystems=Ks,B.formatTime=ce,B.isClearKeySupported=Nt,B.isFairPlaySupported=Bt,B.isKeySystemSupported=Re,B.isPlayReadySupported=Ut,B.isWidevineSupported=Ft,B.normalizeClearKeyValue=$t,B.normalizeClearKeys=Ot,B.renderIcon=G,Object.defineProperty(B,Symbol.toStringTag,{value:"Module"}),B}({});
4750
+ `}getStatistics(){return this.controller?this.controller.getStatistics():null}};ni.styles=Ds;let _=ni;if(W([F({type:String,reflect:!0})],_.prototype,"src"),W([F({type:String,reflect:!0})],_.prototype,"captions"),W([F({type:Boolean,reflect:!0})],_.prototype,"autoplay"),W([F({type:Boolean,reflect:!0})],_.prototype,"muted"),W([F({type:Number,reflect:!0})],_.prototype,"volume"),W([F({type:String,attribute:"display-mode",reflect:!0})],_.prototype,"displayMode"),W([F({type:Number})],_.prototype,"nearEndThreshold"),W([F({type:Boolean,attribute:"auto-scroll",reflect:!0})],_.prototype,"autoScroll"),W([F({type:String,attribute:"live-mode",reflect:!0})],_.prototype,"liveMode"),W([F({type:Object,converter:{fromAttribute:Gr}})],_.prototype,"config"),W([F({type:Boolean,attribute:"precise-seek",reflect:!0})],_.prototype,"preciseSeekEnabled"),W([F({type:Boolean,attribute:"smart-seek",reflect:!0})],_.prototype,"smartSeekEnabled"),W([F({type:String,reflect:!0})],_.prototype,"preload"),W([F({type:Boolean,reflect:!0})],_.prototype,"loop"),W([F({type:Boolean,reflect:!0})],_.prototype,"playsinline"),W([F({type:String,reflect:!0})],_.prototype,"poster"),W([F({type:String,reflect:!0})],_.prototype,"crossorigin"),W([j()],_.prototype,"isVisualTransitioning"),W([j()],_.prototype,"transitionDirection"),W([j()],_.prototype,"transitionStage"),W([j()],_.prototype,"contextMenuOpen"),W([j()],_.prototype,"contextMenuX"),W([j()],_.prototype,"contextMenuY"),W([j({hasChanged(c,e){return e?["status","isPlaying","currentTime","duration","volume","isMuted","isFullscreen","bufferedRanges","playbackRate","captionsEnabled","currentSource","sourceType","isBuffering","isSeeking","hasCaptions","error","qualities","activeQuality","audioTracks","activeAudioTrack","subtitleTracks","activeSubtitleTrackId","chapters","activeChapterIndex","isLive","isLowLatency","isAtLiveEdge","hasDvr","displayMode","liveMode","loop","playlist","activePlaylistIndex","playlistRepeatMode","autoScroll","seekableRange","isAdPlaying","isAdLoading","currentAd","currentAdBreak","adCurrentTime","adRemainingTime","adDuration","canSkipAd","skipAvailableAt","adPosition","adProvider","adLinear","adMuted"].some(i=>{const s=c[i],r=e[i];if(i==="seekableRange"){const a=s,n=r;return!a||!n||a.start!==n.start||a.end!==n.end}if(i==="bufferedRanges"){const a=s,n=r;if(!a||!n||a.length!==n.length)return!0;for(let l=0;l<a.length;l++)if(a[l].start!==n[l].start||a[l].end!==n[l].end)return!0;return!1}return s!==r}):!0}})],_.prototype,"playerState"),W([j()],_.prototype,"controlsVisible"),W([j()],_.prototype,"settingsMenuOpen"),W([j()],_.prototype,"activeMenuScreen"),W([j()],_.prototype,"toastMessage"),W([j()],_.prototype,"toastType"),W([j()],_.prototype,"toastVisible"),W([j()],_.prototype,"tapFeedback"),W([j()],_.prototype,"feedbackTaps"),W([j()],_.prototype,"playPauseFeedback"),W([j()],_.prototype,"activeVolumeFeedback"),W([j()],_.prototype,"isSeekingInteraction"),W([j()],_.prototype,"activeSpeedFeedback"),W([j()],_.prototype,"activeQualityFeedback"),W([Us("video")],_.prototype,"videoElement"),W([j()],_.prototype,"isPreciseSeeking"),W([j()],_.prototype,"speedLockState"),W([j()],_.prototype,"isSpeedOverlayFadingOut"),W([j()],_.prototype,"isVolumeFeedbackFadingOut"),typeof window<"u"&&typeof customElements<"u"&&(customElements.get("streamit-player")||customElements.define("streamit-player",_),!customElements.get("player-player"))){class c extends _{}customElements.define("player-player",c)}return B.AdBreakManager=Ki,B.AdBreakType=xi,B.AdErrorType=ie,B.AdPlacementType=Pi,B.AdProviderType=Ai,B.AdSkipMode=ze,B.AdState=w,B.AdsController=Yi,B.AdsManager=Wi,B.AdsValidator=Mi,B.AutoThumbnailProvider=_e,B.DrmManager=De,B.DrmValidator=Tr,B.HtmlOverlayRenderer=st,B.IconRegistry=X,B.ImaProvider=at,B.KeyboardManager=Ni,B.PlayerChaptersButton=ve,B.PlayerController=is,B.PlayerIconRegistry=ss,B.PlayerPlayButton=$e,B.PlayerPlayer=_,B.PlayerSeekButton=we,B.PlayerSeekbar=Y,B.PlayerVerticalControls=ue,B.PlayerVolumeControl=Te,B.SimidBridge=Vi,B.SimidErrorCode=zt,B.SimidManager=zi,B.SimidRuntime=_i,B.SimidSession=vt,B.SpriteThumbnailProvider=es,B.THEME_PRESETS=Jt,B.TimelineMath=pe,B.TrackingEventName=Ci,B.VTTThumbnailProvider=Ji,B.VastProvider=qt,B.VideoFrameThumbnailProvider=Zi,B.VmapProvider=jt,B.compileTheme=as,B.detectSupportedKeySystems=Ks,B.formatTime=ce,B.isClearKeySupported=Nt,B.isFairPlaySupported=Bt,B.isKeySystemSupported=Re,B.isPlayReadySupported=Ut,B.isWidevineSupported=Ft,B.normalizeClearKeyValue=$t,B.normalizeClearKeys=Ot,B.renderIcon=G,Object.defineProperty(B,Symbol.toStringTag,{value:"Module"}),B}({});