streamit-player 1.0.0 → 1.0.2

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.
@@ -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.currentLevel=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.handleLivePositionChange=()=>{var e;if(!(!this.player||!this.video))try{if(!this.player.isDynamic())return;const t=(e=this.getRawLiveInfo())==null?void 0:e.liveEdgeTarget;if(t==null||this.video.currentTime<=0)return;this.followingLive=t-this.video.currentTime<=Ws,this.syncLiveCatchup()}catch{}},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())}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("seeking",this.handleLivePositionChange),t.addEventListener("play",this.handleLivePositionChange),t.addEventListener("timeupdate",this.syncLiveCatchup),$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(){if(this.video&&(this.video.removeEventListener("seeking",this.handleLivePositionChange),this.video.removeEventListener("play",this.handleLivePositionChange),this.video.removeEventListener("timeupdate",this.syncLiveCatchup)),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(e){console.warn("[DashHandler] Error unbinding event listeners:",e)}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){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,!0),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 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`
2040
2040
  :host {
2041
2041
  display: inline-block;
2042
2042
  width: var(--player-button-width, 40px);