playron 1.0.35 → 1.0.36
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/playron.cjs.js
CHANGED
|
@@ -1,19 +1,19 @@
|
|
|
1
|
-
"use strict";Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const i=require("react/jsx-runtime"),c=require("react");class Ye{listeners=new Map;on(e,t){this.listeners.has(e)||this.listeners.set(e,new Set),this.listeners.get(e).add(t)}off(e,t){const r=this.listeners.get(e);r&&(r.delete(t),r.size===0&&this.listeners.delete(e))}emit(e){const t=this.listeners.get(e.type);t&&t.forEach(r=>{try{r(e)}catch(n){console.error(`Error in event listener for ${e.type}:`,n)}})}clear(){this.listeners.clear()}listenerCount(e){return this.listeners.get(e)?.size||0}}const ie=new Ye,k={PLAY:"play",PAUSE:"pause",PLAYING:"playing",ENDED:"ended",SEEKING:"seeking",SEEKED:"seeked",WAITING:"waiting",VOLUME_CHANGE:"volumechange",TIME_UPDATE:"timeupdate",DURATION_CHANGE:"durationchange",LOADED_METADATA:"loadedmetadata",LOADED_DATA:"loadeddata",CAN_PLAY:"canplay",CAN_PLAY_THROUGH:"canplaythrough",RATE_CHANGE:"ratechange",LOAD_START:"loadstart",PROGRESS:"progress",SUSPEND:"suspend",ABORT:"abort",STALLED:"stalled",ERROR:"error",EMPTIED:"emptied",RESIZE:"resize"},he={MEDIA_ERR_ABORTED:1,MEDIA_ERR_NETWORK:2,MEDIA_ERR_DECODE:3,MEDIA_ERR_SRC_NOT_SUPPORTED:4};function Ft(a){return Object.values(k).includes(a)}class Ut{videoElement=null;isPlaying=!1;isMuted=!1;volume=1;playbackRate=1;currentTime=0;duration=0;constructor(e){this.videoElement=e,this.setupEventListeners(),this.initializeVideo()}setupEventListeners(){this.videoElement&&(this.videoElement.addEventListener(k.PLAY,()=>{this.isPlaying=!0,this.emitPlayEvent()}),this.videoElement.addEventListener(k.PAUSE,()=>{this.isPlaying=!1,this.emitPauseEvent()}),this.videoElement.addEventListener(k.VOLUME_CHANGE,()=>{this.videoElement&&(this.volume=this.videoElement.volume,this.isMuted=this.videoElement.muted,this.emitVolumeChangeEvent())}),this.videoElement.addEventListener(k.TIME_UPDATE,()=>{this.videoElement&&(this.currentTime=this.videoElement.currentTime)}),this.videoElement.addEventListener(k.LOADED_METADATA,()=>{this.videoElement&&(this.duration=this.videoElement.duration)}),this.videoElement.addEventListener(k.RATE_CHANGE,()=>{this.videoElement&&(this.playbackRate=this.videoElement.playbackRate)}),this.videoElement.addEventListener(k.ERROR,e=>{console.error("Video error:",e),this.videoElement?.error&&console.error("Video error details:",{code:this.videoElement.error.code,message:this.videoElement.error.message,MEDIA_ERR_ABORTED:this.videoElement.error.code===he.MEDIA_ERR_ABORTED,MEDIA_ERR_NETWORK:this.videoElement.error.code===he.MEDIA_ERR_NETWORK,MEDIA_ERR_DECODE:this.videoElement.error.code===he.MEDIA_ERR_DECODE,MEDIA_ERR_SRC_NOT_SUPPORTED:this.videoElement.error.code===he.MEDIA_ERR_SRC_NOT_SUPPORTED})}))}initializeVideo(){this.videoElement&&(this.volume=this.videoElement.volume,this.isMuted=this.videoElement.muted,this.playbackRate=this.videoElement.playbackRate)}emitPlayEvent(){if(!this.videoElement)return;const e={type:"play",data:{currentTime:this.videoElement.currentTime,duration:this.videoElement.duration},timestamp:Date.now()};ie.emit(e)}emitPauseEvent(){if(!this.videoElement)return;const e={type:"pause",data:{currentTime:this.videoElement.currentTime,duration:this.videoElement.duration},timestamp:Date.now()};ie.emit(e)}emitVolumeChangeEvent(){const e={type:"volumechange",data:{volume:this.volume,muted:this.isMuted},timestamp:Date.now()};ie.emit(e)}emitMuteEvent(){const e={type:"mute",data:{muted:this.isMuted,volume:this.volume},timestamp:Date.now()};ie.emit(e)}async play(){if(!this.videoElement)throw new Error("Video element not found");try{await this.videoElement.play()}catch(e){throw console.error("Play failed:",e),e}}pause(){this.videoElement&&this.videoElement.pause()}toggleMute(){this.videoElement&&(this.videoElement.muted=!this.videoElement.muted,this.isMuted=this.videoElement.muted,this.emitMuteEvent())}setVolume(e){this.videoElement&&(this.videoElement.volume=Math.max(0,Math.min(1,e)))}seekTo(e){this.videoElement&&(this.videoElement.currentTime=Math.max(0,Math.min(this.duration,e)))}setPlaybackRate(e){this.videoElement&&(this.videoElement.playbackRate=Math.max(.25,Math.min(4,e)),this.playbackRate=this.videoElement.playbackRate)}setSource(e){this.videoElement&&(this.videoElement.src=e)}setPoster(e){this.videoElement&&(this.videoElement.poster=e)}setDimensions(e,t){this.videoElement&&(this.videoElement.width=typeof e=="number"?e:parseInt(e),this.videoElement.height=typeof t=="number"?t:parseInt(t))}getState(){return{isPlaying:this.isPlaying,isMuted:this.isMuted,volume:this.volume,playbackRate:this.playbackRate,currentTime:this.currentTime,duration:this.duration,src:this.videoElement?.src||"",poster:this.videoElement?.poster||""}}getVideoElement(){return this.videoElement}destroy(){this.videoElement&&(this.videoElement.removeEventListener("play",()=>{}),this.videoElement.removeEventListener("pause",()=>{}),this.videoElement.removeEventListener("volumechange",()=>{}),this.videoElement.removeEventListener("timeupdate",()=>{}),this.videoElement.removeEventListener("loadedmetadata",()=>{}),this.videoElement.removeEventListener("error",()=>{})),this.videoElement=null}}class Ot{config;defaultConfig;constructor(e){this.defaultConfig=this.getDefaultConfig(),this.config=this.mergeConfig(e),this.validateConfig(this.config)}getDefaultConfig(){return{container:"",src:"",width:800,height:450,autoplay:!1,muted:!1,controls:!1,poster:"",className:""}}mergeConfig(e){return{...this.defaultConfig,...e}}validateConfig(e){if(!e.container)throw new Error("Container is required");if(!e.src)throw new Error("Source is required");const t=typeof e.width=="number"?e.width:parseInt(e.width||"800"),r=typeof e.height=="number"?e.height:parseInt(e.height||"450");if(e.width&&(t<100||t>4e3))throw new Error("Width must be between 100 and 4000");if(e.height&&(r<100||r>4e3))throw new Error("Height must be between 100 and 4000")}updateConfig(e){const t={...this.config,...e};this.validateConfig(t),this.config=t}getConfig(){return{...this.config}}get(e){return this.config[e]}set(e,t){const r={[e]:t};this.updateConfig(r)}getContainer(){return typeof this.config.container=="string"?document.querySelector(this.config.container):this.config.container}getDimensions(){return{width:typeof this.config.width=="number"?this.config.width:parseInt(this.config.width||"800"),height:typeof this.config.height=="number"?this.config.height:parseInt(this.config.height||"450")}}reset(){this.config={...this.defaultConfig}}export(){return JSON.stringify(this.config,null,2)}import(e){try{const t=JSON.parse(e);this.validateConfig(t),this.config=t}catch{throw new Error("Invalid configuration format")}}listeners=[];onChange(e){this.listeners.push(e)}offChange(e){const t=this.listeners.indexOf(e);t>-1&&this.listeners.splice(t,1)}notifyChange(){this.listeners.forEach(e=>{try{e(this.config)}catch(t){console.error("Config change listener error:",t)}})}updateConfigAndNotify(e){this.updateConfig(e),this.notifyChange()}}class Wt{state;listeners=[];history=[];maxHistorySize=50;constructor(e){this.state=this.getInitialState(e)}getInitialState(e){return{...{isPlaying:!1,isMuted:!1,volume:1,currentTime:0,duration:0,playbackRate:1},...e}}updateState(e){const t={...this.state};this.state={...this.state,...e},this.addToHistory(t),this.notifyListeners()}getState(){return{...this.state}}get(e){return this.state[e]}set(e,t){this.updateState({[e]:t})}subscribe(e){this.listeners.push(e)}unsubscribe(e){const t=this.listeners.indexOf(e);t>-1&&this.listeners.splice(t,1)}notifyListeners(){this.listeners.forEach(e=>{try{e(this.state)}catch(t){console.error("State listener error:",t)}})}addToHistory(e){this.history.push(e),this.history.length>this.maxHistorySize&&this.history.shift()}undo(){if(this.history.length===0)return!1;const e=this.history.pop();return e?(this.state=e,this.notifyListeners(),!0):!1}reset(){this.state=this.getInitialState(),this.history=[],this.notifyListeners()}setState(e){const t={...this.state};this.state={...e},this.addToHistory(t),this.notifyListeners()}clearHistory(){this.history=[]}getHistory(){return[...this.history]}isInState(e){return e(this.state)}subscribeToChanges(e,t){let r={...this.state};const n=s=>{const o={};let l=!1;e.forEach(u=>{r[u]!==s[u]&&(o[u]=s[u],l=!0)}),l&&t(o),r={...s}};this.subscribe(n)}createSnapshot(){return{...this.state}}restoreFromSnapshot(e){this.setState(e)}getStats(){return{totalListeners:this.listeners.length,historySize:this.history.length,maxHistorySize:this.maxHistorySize,lastUpdate:new Date}}}class Xe{listeners=new Map;onceListeners=new Map;on(e,t){this.listeners.has(e)||this.listeners.set(e,new Set),this.listeners.get(e).add(t)}once(e,t){this.onceListeners.has(e)||this.onceListeners.set(e,new Set),this.onceListeners.get(e).add(t)}off(e,t){const r=this.listeners.get(e);r&&(r.delete(t),r.size===0&&this.listeners.delete(e));const n=this.onceListeners.get(e);n&&(n.delete(t),n.size===0&&this.onceListeners.delete(e))}emit(e,t){const r=this.listeners.get(e);r&&r.forEach(s=>{try{s(t)}catch(o){console.error(`[Playron] Error in event listener for "${e}":`,o)}});const n=this.onceListeners.get(e);n&&(n.forEach(s=>{try{s(t)}catch(o){console.error(`[Playron] Error in once listener for "${e}":`,o)}}),this.onceListeners.delete(e))}removeAllListeners(e){e?(this.listeners.delete(e),this.onceListeners.delete(e)):(this.listeners.clear(),this.onceListeners.clear())}listenerCount(e){const t=this.listeners.get(e)?.size||0,r=this.onceListeners.get(e)?.size||0;return t+r}eventNames(){const e=new Set;return this.listeners.forEach((t,r)=>e.add(r)),this.onceListeners.forEach((t,r)=>e.add(r)),Array.from(e)}}class Ge{async detectStream(e){const t=this.detectProtocol(e);try{if(t==="hls")return await this.detectHLS(e);if(t==="dash")return await this.detectDASH(e);if(t==="progressive")return this.detectProgressive(e)}catch(r){console.warn("[StreamDetector] Failed to detect stream type:",r)}return{type:"unknown",protocol:"unknown",isDynamic:!1,hasDVR:!1,isEngineSupported:this.preCheckCapability("unknown")}}preCheckCapability(e){if(typeof MediaSource>"u")return!1;const t=MediaSource.isTypeSupported('video/mp4; codecs="avc1.42E01E"')||MediaSource.isTypeSupported('video/mp4; codecs="avc1.4d401e"')||MediaSource.isTypeSupported('video/mp4; codecs="avc1.64001F"'),r=MediaSource.isTypeSupported('video/mp4; codecs="hev1.1.6.L93.B0"')||MediaSource.isTypeSupported('video/mp4; codecs="hvc1.1.6.L93.B0"'),n=MediaSource.isTypeSupported('video/webm; codecs="vp9"')||MediaSource.isTypeSupported('video/mp4; codecs="vp09.00.10.08"'),s=t||r||n,o=/Safari/.test(navigator.userAgent)&&/Apple Computer/.test(navigator.vendor);return e==="hls"&&o?!0:s}detectProtocol(e){const t=e.toLowerCase();return t.includes(".m3u8")||t.includes(".m3u")?"hls":t.includes(".mpd")?"dash":t.match(/\.(mp4|webm|ogg)$/)?"progressive":"unknown"}async detectHLS(e){const t=await this.fetchManifest(e);if(t.includes("#EXT-X-ENDLIST")||t.includes("#EXT-X-PLAYLIST-TYPE:VOD"))return{type:"vod",protocol:"hls",isDynamic:!1,hasDVR:!1,isEngineSupported:this.preCheckCapability("hls")};const n=t.includes("#EXT-X-MEDIA-SEQUENCE"),s=t.includes("#EXT-X-ENDLIST"),o=t.includes("#EXT-X-PLAYLIST-TYPE:EVENT"),l=this.extractTargetDuration(t),u=this.extractMediaSequence(t);return n&&!s?{type:"live",protocol:"hls",isDynamic:!0,hasDVR:o,targetDuration:l,mediaSequence:u,isEngineSupported:this.preCheckCapability("hls")}:{type:"vod",protocol:"hls",isDynamic:!1,hasDVR:!1,isEngineSupported:this.preCheckCapability("hls")}}async detectDASH(e){const t=await this.fetchManifest(e),s=t.match(/<MPD[^>]*type="(static|dynamic)"/)?.[1]==="dynamic",o=t.includes("timeShiftBufferDepth");return{type:s?"live":"vod",protocol:"dash",isDynamic:s,hasDVR:o,isEngineSupported:this.preCheckCapability("dash")}}detectProgressive(e){return{type:"vod",protocol:"progressive",isDynamic:!1,hasDVR:!1,isEngineSupported:!0}}async fetchManifest(e){const t=await fetch(e,{method:"GET",headers:{Accept:"*/*"}});if(!t.ok)throw new Error(`Failed to fetch manifest: ${t.status}`);return await t.text()}extractTargetDuration(e){const t=e.match(/#EXT-X-TARGETDURATION:(\d+)/);return t?parseInt(t[1],10):void 0}extractMediaSequence(e){const t=e.match(/#EXT-X-MEDIA-SEQUENCE:(\d+)/);return t?parseInt(t[1],10):void 0}quickDetect(e){const t=this.detectProtocol(e);return t==="progressive"?{type:"vod",protocol:"progressive",isEngineSupported:!0}:{type:"unknown",protocol:t,isEngineSupported:this.preCheckCapability(t)}}}const Qe=new Ge;class Ze{video;events;options;timer=null;lastTime=-1;stallDuration=0;attempts=0;isRunning=!1;constructor(e,t,r={}){this.video=e,this.events=t,this.options={pollInterval:r.pollInterval??500,stallThreshold:r.stallThreshold??3,onQualityDowngrade:r.onQualityDowngrade}}start(){this.isRunning||(this.isRunning=!0,this.reset(),this.timer=setInterval(()=>this.tick(),this.options.pollInterval))}stop(){this.timer!==null&&(clearInterval(this.timer),this.timer=null),this.isRunning=!1,this.reset()}destroy(){this.stop()}reset(){this.lastTime=-1,this.stallDuration=0,this.attempts=0}tick(){const e=this.video;if(e.paused||e.ended||e.seeking||e.readyState<2){this.stallDuration=0,this.lastTime=e.currentTime;return}const t=e.currentTime;if(this.lastTime<0){this.lastTime=t;return}const r=t-this.lastTime;if(this.lastTime=t,r>.05){if(this.stallDuration>0){const o=this.attempts>=3?"quality":"seek";this.events.emit("stallrecovered",{duration:Math.round(this.stallDuration),method:o})}this.stallDuration=0,this.attempts=0;return}this.stallDuration+=this.options.pollInterval/1e3;const{stallThreshold:n}=this.options,s=Math.floor(this.stallDuration/n);s>this.attempts&&(this.attempts=s,this.recover())}recover(){const e=this.video;switch(this.events.emit("stall",{duration:Math.round(this.stallDuration),attempt:this.attempts}),this.attempts){case 1:e.currentTime=Math.min(e.currentTime+.5,e.duration||1/0);break;case 2:e.currentTime=Math.min(e.currentTime+2,e.duration||1/0);break;case 3:this.options.onQualityDowngrade&&this.options.onQualityDowngrade(),e.currentTime=Math.min(e.currentTime+2,e.duration||1/0);break;default:this.events.emit("error",{code:"STALL_UNRECOVERABLE",message:`Playback stalled for ${Math.round(this.stallDuration)}s and could not be recovered.`}),this.stop();break}}}const Je=[{contentType:'video/mp4; codecs="avc1.42E01E"'}],Ht=[{contentType:'audio/mp4; codecs="mp4a.40.2"'}],zt=[{initDataTypes:["cenc"],videoCapabilities:Je,audioCapabilities:Ht}];async function Le(a){try{return await navigator.requestMediaKeySystemAccess(a,zt),!0}catch{return!1}}async function et(){const[a,e,t]=await Promise.all([Le("com.widevine.alpha"),Le("com.microsoft.playready"),Le("org.w3.clearkey")]),r=await(async()=>{try{return await navigator.requestMediaKeySystemAccess("com.apple.fps",[{initDataTypes:["skd"],videoCapabilities:Je}]),!0}catch{return!1}})();let n=null;return a?n="widevine":r?n="fairplay":e?n="playready":t&&(n="clearkey"),{widevine:a,fairplay:r,playready:e,clearkey:t,preferredSystem:n}}const qt=3e4,Kt=2,Yt=1e3,Ie=new Map;async function tt(a,e,t,r,n){let s=new Error("License request failed");for(let o=0;o<=r;o++){if(o>0){const d=n*Math.pow(2,o-1);await new Promise(h=>setTimeout(h,d))}const l=new AbortController,u=setTimeout(()=>l.abort(),t);try{const d=await fetch(a,{...e,signal:l.signal});if(clearTimeout(u),!d.ok)throw new Error(`HTTP ${d.status}: ${d.statusText}`);return await d.arrayBuffer()}catch(d){clearTimeout(u),d instanceof Error&&d.name==="AbortError"?s=new Error(`Request timed out after ${t}ms (attempt ${o+1}/${r+1})`):s=d instanceof Error?d:new Error(String(d))}}throw s}async function Xt(a,e={}){const t=Ie.get(a);if(t)return console.debug("[LicenseManager] Using cached FairPlay certificate:",a),t;console.debug("[LicenseManager] Fetching FairPlay certificate:",a);const r=await tt(a,{method:"GET",headers:e},15e3,1,500);return Ie.set(a,r),r}function Gt(){Ie.clear()}async function Qt(a,e,t={},r=!1,n={}){const s=n.timeout??qt,o=n.maxRetries??Kt,l=n.retryDelay??Yt;let u=e;n.prepareLicenseRequest&&(u=await n.prepareLicenseRequest(e));const d={method:"POST",body:u,headers:{"Content-Type":"application/octet-stream",...t},credentials:r?"include":"omit"};console.debug("[LicenseManager] Acquiring license from:",a);let h=await tt(a,d,s,o,l);return n.parseLicenseResponse&&(h=await n.parseLicenseResponse(h)),h}const Be="com.apple.fps",Zt=[{initDataTypes:["skd"],videoCapabilities:[{contentType:'video/mp4; codecs="avc1.42E01E"'},{contentType:'video/mp4; codecs="hvc1.1.6.L93.B0"'}],audioCapabilities:[{contentType:'audio/mp4; codecs="mp4a.40.2"'}],sessionTypes:["temporary"],persistentState:"optional",distinctiveIdentifier:"optional"}];class Jt{keySystem=Be;config;mediaKeys=null;videoElement=null;sessions=new Set;destroyed=!1;boundOnEncrypted;constructor(e){this.config=e,this.boundOnEncrypted=t=>{this.handleEncrypted(t)}}async initialize(e){if(this.destroyed)return;this.videoElement=e;let t;try{t=await navigator.requestMediaKeySystemAccess(Be,Zt)}catch{throw new Error("FairPlay Streaming is not supported in this browser. Safari on macOS or iOS is required.")}this.mediaKeys=await t.createMediaKeys();let r;try{r=await Xt(this.config.certificateUrl,this.config.headers)}catch(n){throw new Error(`FairPlay: Failed to fetch server certificate from ${this.config.certificateUrl}: `+(n instanceof Error?n.message:String(n)))}try{await this.mediaKeys.setServerCertificate(r)||console.debug("[FairPlayAdapter] setServerCertificate returned false (certificate may not be required)")}catch(n){throw new Error(`FairPlay: setServerCertificate failed: ${n instanceof Error?n.message:String(n)}`)}await e.setMediaKeys(this.mediaKeys),e.addEventListener("encrypted",this.boundOnEncrypted),console.debug("[FairPlayAdapter] Initialized — waiting for encrypted event"),this.config.onReady?.()}async handleEncrypted(e){if(!this.mediaKeys||this.destroyed)return;console.debug("[FairPlayAdapter] Received encrypted event, initDataType:",e.initDataType);const t=this.mediaKeys.createSession("temporary");if(this.sessions.add(t),t.addEventListener("message",r=>{this.handleKeyMessage(t,r)}),t.addEventListener("keystatuseschange",()=>{this.handleKeyStatusChange(t)}),!e.initData){this.sessions.delete(t),console.warn("[FairPlayAdapter] Encrypted event has no initData — skipping session");return}try{await t.generateRequest(e.initDataType,e.initData)}catch(r){this.sessions.delete(t);const n=`FairPlay: generateRequest failed: ${r instanceof Error?r.message:String(r)}`;console.error("[FairPlayAdapter]",n),this.config.onError?.("FAIRPLAY_GENERATE_REQUEST_FAILED",n,!0)}}async handleKeyMessage(e,t){if(this.destroyed)return;const r=t.message;console.debug("[FairPlayAdapter] Received key message, acquiring license...");try{const n=await Qt(this.config.licenseUrl,r,this.config.headers??{},this.config.withCredentials??!1,this.config.licenseAcquisitionConfig??{});await e.update(n),console.debug("[FairPlayAdapter] License applied successfully")}catch(n){const s=`FairPlay: License acquisition failed: ${n instanceof Error?n.message:String(n)}`;console.error("[FairPlayAdapter]",s),this.config.onError?.("FAIRPLAY_LICENSE_FAILED",s,!0)}}handleKeyStatusChange(e){e.keyStatuses.forEach(t=>{switch(t){case"expired":this.config.onError?.("FAIRPLAY_KEY_EXPIRED","FairPlay: Content key has expired. Please reload the player.",!0);break;case"output-restricted":this.config.onError?.("FAIRPLAY_OUTPUT_RESTRICTED","FairPlay: Output restricted — HDCP connection required.",!1);break;case"internal-error":this.config.onError?.("FAIRPLAY_INTERNAL_ERROR","FairPlay: Internal key error.",!0);break;case"usable":console.debug("[FairPlayAdapter] Key status: usable");break;default:console.debug("[FairPlayAdapter] Key status:",t)}})}destroy(){this.destroyed||(this.destroyed=!0,this.videoElement&&this.videoElement.removeEventListener("encrypted",this.boundOnEncrypted),this.sessions.forEach(e=>{e.close().catch(()=>{})}),this.sessions.clear(),this.videoElement&&(this.videoElement.setMediaKeys(null).catch(()=>{}),this.videoElement=null),this.mediaKeys=null,console.debug("[FairPlayAdapter] Destroyed"))}}const Ne="com.widevine.alpha",er=[{initDataTypes:["cenc"],videoCapabilities:[{contentType:'video/mp4; codecs="avc1.42E01E"',robustness:"SW_SECURE_CRYPTO"},{contentType:'video/mp4; codecs="avc1.42E01E"'}],audioCapabilities:[{contentType:'audio/mp4; codecs="mp4a.40.2"'}],sessionTypes:["temporary"]}];class tr{keySystem=Ne;config;destroyed=!1;constructor(e){this.config=e}async initialize(e){if(!this.destroyed){try{await navigator.requestMediaKeySystemAccess(Ne,er)}catch{throw new Error("Widevine is not supported in this browser. Chrome, Firefox, or Edge (Chromium) is required for Widevine DRM.")}console.debug("[WidevineAdapter] Widevine key system confirmed — delegating EME to streaming engine"),this.config.onReady?.()}}destroy(){this.destroyed=!0,console.debug("[WidevineAdapter] Destroyed")}}const je="com.microsoft.playready",$e="com.microsoft.playready.hardware",rr=[{initDataTypes:["cenc"],videoCapabilities:[{contentType:'video/mp4; codecs="avc1.42E01E"'}],audioCapabilities:[{contentType:'audio/mp4; codecs="mp4a.40.2"'}],sessionTypes:["temporary"]}];class ir{keySystem;config;destroyed=!1;constructor(e){this.config=e,this.keySystem=e.preferHardware?$e:je}async initialize(e){if(this.destroyed)return;const t=this.config.preferHardware?[$e,je]:[je];let r=!1;for(const n of t)try{await navigator.requestMediaKeySystemAccess(n,rr),r=!0,console.debug(`[PlayReadyAdapter] Key system confirmed: ${n}`);break}catch{}if(!r)throw new Error("PlayReady is not supported in this browser. Microsoft Edge or Internet Explorer is required for PlayReady DRM.");console.debug("[PlayReadyAdapter] PlayReady key system confirmed — delegating EME to dashjs"),this.config.onReady?.()}destroy(){this.destroyed=!0,console.debug("[PlayReadyAdapter] Destroyed")}}const nr={widevine:"com.widevine.alpha",fairplay:"com.apple.fps",playready:"com.microsoft.playready"};class sr{adapter=null;selectedKeySystem=null;emitter;destroyed=!1;constructor(e){this.emitter=e}async initialize(e,t){if(this.destroyed||!t?.enabled)return null;const r=await et().catch(()=>({widevine:!1,fairplay:!1,playready:!1,clearkey:!1,preferredSystem:null})),n=t.preferredSystem;if(n&&(n==="fairplay"&&r.fairplay&&t.fairplay&&(this.selectedKeySystem="fairplay"),n==="widevine"&&r.widevine&&t.widevine&&(this.selectedKeySystem="widevine"),n==="playready"&&r.playready&&t.playready&&(this.selectedKeySystem="playready")),this.selectedKeySystem||(r.fairplay&&t.fairplay?this.selectedKeySystem="fairplay":r.widevine&&t.widevine?this.selectedKeySystem="widevine":r.playready&&t.playready&&(this.selectedKeySystem="playready")),!this.selectedKeySystem)return console.warn("[DrmManager] No supported DRM key system found for the provided configuration. Browser capabilities:",r),null;const s=nr[this.selectedKeySystem];if(console.debug("[DrmManager] Selected key system:",s),this.emitter.emit("drm:keysystem",{keySystem:s}),this.adapter=this.createAdapter(t),!this.adapter)return null;try{await this.adapter.initialize(e)}catch(o){const l=o instanceof Error?o.message:String(o);return console.error("[DrmManager] Adapter initialization failed:",l),this.emitter.emit("error",{code:"DRM_INIT_FAILED",message:l,details:o}),this.selectedKeySystem=null,null}return this.emitter.emit("drm:ready",{keySystem:s}),this.selectedKeySystem}getSelectedKeySystem(){return this.selectedKeySystem}destroy(){this.destroyed||(this.destroyed=!0,this.adapter?.destroy(),this.adapter=null,this.selectedKeySystem=null,Gt(),console.debug("[DrmManager] Destroyed"))}createAdapter(e){const t=(r,n,s=!0)=>{this.emitter.emit("error",{code:r,message:n,details:{fatal:s}})};switch(this.selectedKeySystem){case"fairplay":{const r=e.fairplay;return new Jt({licenseUrl:r.licenseUrl,certificateUrl:r.certificateUrl,headers:r.headers,withCredentials:r.withCredentials,licenseAcquisitionConfig:r.licenseAcquisitionConfig,onError:t})}case"widevine":{const r=e.widevine;return new tr({licenseUrl:r.licenseUrl,headers:r.headers,withCredentials:r.withCredentials,licenseAcquisitionConfig:r.licenseAcquisitionConfig,onError:t})}case"playready":{const r=e.playready;return new ir({licenseUrl:r.licenseUrl,headers:r.headers,withCredentials:r.withCredentials,licenseAcquisitionConfig:r.licenseAcquisitionConfig,onError:t})}default:return null}}}const or="https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1",Fe="playron-cast-sdk";class rt{appId;onChange;isAvailable=!1;sessionActive=!1;sdkLoaded=!1;castStateHandler=null;constructor(e){this.appId=e.appId??"CC1AD845",this.onChange=e.onChange}setup(){if(this.sdkLoaded)return;this.sdkLoaded=!0;const e=window.__onGCastApiAvailable;if(window.__onGCastApiAvailable=t=>{e?.(t),t?this.initContext():(console.warn("[ChromecastManager] Cast API not available (no Cast devices found or extension missing)"),this.emitState())},!document.getElementById(Fe)){const t=document.createElement("script");t.id=Fe,t.src=or,t.async=!0,document.head.appendChild(t),console.log("[ChromecastManager] Cast SDK script injected")}}async requestSession(){const e=this.getContext();if(!e){console.warn("[ChromecastManager] Cast context not ready — call setup() first");return}try{await e.requestSession()}catch(t){(t instanceof Error?t.message:String(t)).toLowerCase().includes("cancel")||console.error("[ChromecastManager] requestSession error:",t)}}endSession(e=!0){this.getContext()?.endCurrentSession(e)}async loadMedia(e,t="video/mp4",r=0,n=!1){const s=this.getContext()?.getCurrentSession();if(!s){console.warn("[ChromecastManager] No active Cast session — call requestSession() first");return}const o=window.chrome?.cast;if(o)try{const l=new o.media.MediaInfo(e,t);l.streamType=n?o.media.StreamType.LIVE:o.media.StreamType.BUFFERED,l.metadata=null;const u=new o.media.LoadRequest(l);u.currentTime=r,u.autoplay=!0,await s.loadMedia(u),console.log(`[ChromecastManager] Media loaded on receiver: ${e} (t=${r}s)`)}catch(l){console.error("[ChromecastManager] loadMedia error:",l)}}syncTime(e){const r=this.getContext()?.getCurrentSession()?.getMediaSession();r&&r.seek({currentTime:e,type:"SEEK"})}async syncVolume(e,t){const r=this.getContext()?.getCurrentSession();if(r)try{await r.setVolume(e),await r.setMute(t)}catch{}}isCastAvailable(){return this.isAvailable}isCastActive(){return this.sessionActive}getState(){const e=this.getContext()?.getCastState()??"";let t="unavailable";const r=window.cast?.framework;return r&&(e===r.CastState.NO_DEVICES_AVAILABLE?t="unavailable":e===r.CastState.NOT_CONNECTED?t="not_connected":e===r.CastState.CONNECTING?t="connecting":e===r.CastState.CONNECTED&&(t="connected")),{isAvailable:this.isAvailable,isActive:this.sessionActive,state:t}}destroy(){const e=this.getContext();if(e&&this.castStateHandler){const t=window.cast?.framework?.CastContextEventType;t&&(e.removeEventListener(t.CAST_STATE_CHANGED,this.castStateHandler),e.removeEventListener(t.SESSION_STATE_CHANGED,this.castStateHandler)),this.castStateHandler=null}console.log("[ChromecastManager] Destroyed")}getContext(){return window.cast?.framework?.CastContext?.getInstance()??null}initContext(){const e=this.getContext();if(!e)return;try{e.setOptions({receiverApplicationId:this.appId})}catch(r){console.error("[ChromecastManager] setOptions error:",r);return}this.castStateHandler=()=>{this.syncState()};const t=window.cast?.framework?.CastContextEventType;t&&(e.addEventListener(t.CAST_STATE_CHANGED,this.castStateHandler),e.addEventListener(t.SESSION_STATE_CHANGED,this.castStateHandler)),this.syncState(),console.log(`[ChromecastManager] Initialized with appId=${this.appId}`)}syncState(){const e=this.getContext()?.getCastState()??"",t=window.cast?.framework;if(!t)return;const r=this.sessionActive;this.isAvailable=e!==t.CastState.NO_DEVICES_AVAILABLE,this.sessionActive=e===t.CastState.CONNECTED,r!==this.sessionActive&&console.log(`[ChromecastManager] Session state: ${this.sessionActive?"CONNECTED":"DISCONNECTED"}`),this.emitState()}emitState(){this.onChange(this.getState())}}class ne{videoEngine=null;configManager=null;stateManager=null;videoElement=null;container=null;events;streamType="unknown";streamInfo=null;hlsEngine=null;dashEngine=null;airPlayAvailable=!1;airPlayActive=!1;onAirPlayAvailabilityChanged=null;onAirPlayTargetChanged=null;stallDetector=null;liveLatencyTimer=null;atLiveEdgeTolerance=10;drmConfig=null;drmManager=null;playerConfig=null;castManager=null;static preloadEngines(){Promise.resolve().then(()=>require("./HlsEngine-DUVHcUpc.cjs")),Promise.resolve().then(()=>require("./DashEngine-CWBT5Q9y.cjs"))}constructor(e){this.videoElement=e,this.events=new Xe,this.initialize()}initialize(){if(!this.videoElement)return;this.videoEngine=new Ut(this.videoElement);const e=this.loadPersistedVolume();e!==null&&(this.videoElement.volume=e),this.stateManager=new Wt({isPlaying:!1,isMuted:this.videoElement.muted,volume:this.videoElement.volume,currentTime:0,duration:0,playbackRate:this.videoElement.playbackRate||1}),this.setupStateListeners(),this.setupAirPlay()}setupStateListeners(){!this.stateManager||!this.videoElement||(this.videoElement.addEventListener(k.PLAY,()=>{this.events.emit("play",{timestamp:Date.now()})}),this.videoElement.addEventListener(k.PAUSE,()=>{this.events.emit("pause",{timestamp:Date.now()})}),this.videoElement.addEventListener(k.TIME_UPDATE,()=>{this.events.emit("timeupdate",{currentTime:this.videoElement?.currentTime||0,duration:this.videoElement?.duration||0})}),this.videoElement.addEventListener(k.ENDED,()=>{this.events.emit("ended",{timestamp:Date.now()})}),this.videoElement.addEventListener(k.LOADED_METADATA,()=>{this.events.emit("loadedmetadata",{duration:this.videoElement?.duration||0,videoWidth:this.videoElement?.videoWidth||0,videoHeight:this.videoElement?.videoHeight||0})}),this.videoElement.addEventListener(k.RATE_CHANGE,()=>{const e=this.videoElement?.playbackRate||1;this.stateManager?.set("playbackRate",e),this.events.emit("ratechange",{playbackRate:e})}),this.videoElement.addEventListener(k.ERROR,()=>{const e=this.videoElement?.error;if(e){const t=`MEDIA_ERR_${e.code===1?"ABORTED":e.code===2?"NETWORK":e.code===3?"DECODE":e.code===4?"SRC_NOT_SUPPORTED":"UNKNOWN"}`;Promise.resolve().then(()=>require("./ErrorManager-CDf_sFKX.cjs")).then(({errorManager:r})=>{r.dispatchError("Playback Error",t,e.message||"Video playback error",e)}),this.events.emit("error",{code:t,message:e.message||"Video playback error",details:e})}}),this.stateManager.subscribe(e=>{if(this.videoEngine){const t=this.videoEngine.getState();t.isPlaying!==e.isPlaying&&(e.isPlaying?this.videoEngine.play().catch(r=>{r instanceof DOMException&&r.name==="AbortError"||console.error("Play failed:",r)}):this.videoEngine.pause()),t.isMuted!==e.isMuted&&this.videoEngine.toggleMute(),t.volume!==e.volume&&this.videoEngine.setVolume(e.volume)}}))}static createWithConfig(e){const t=typeof e.container=="string"?document.querySelector(e.container):e.container;if(!t)throw new Error(`Container not found: ${e.container}`);const r=document.createElement("video");r.id="virtus-video-player",r.src=e.src,r.width=typeof e.width=="number"?e.width:800,r.height=typeof e.height=="number"?e.height:450,r.autoplay=e.autoplay||!1,r.muted=e.muted||!1,r.controls=e.controls||!1,r.className=`playron ${e.className||""}`,e.poster&&(r.poster=e.poster),t.appendChild(r);const n=new ne(r);return n.container=t,n.configManager=new Ot(e),n}setupDrm(e){this.drmConfig=e}setConfig(e){this.playerConfig=e}async play(){if(!this.videoEngine)throw new Error("VideoEngine not initialized");try{await this.videoEngine.play(),this.stateManager?.set("isPlaying",!0)}catch(e){if(e instanceof DOMException&&e.name==="AbortError")return;throw console.error("Play failed:",e),e}}pause(){this.videoEngine&&(this.videoEngine.pause(),this.stateManager?.set("isPlaying",!1))}toggleMute(){if(!this.videoEngine)return;this.videoEngine.toggleMute();const e=this.videoEngine.getState();this.stateManager?.set("isMuted",e.isMuted)}setVolume(e){this.videoEngine&&(this.videoEngine.setVolume(e),this.stateManager?.set("volume",e),this.persistVolume(e))}getBufferedRanges(){if(!this.videoElement)return[];const e=[],{buffered:t}=this.videoElement;for(let r=0;r<t.length;r++)e.push({start:t.start(r),end:t.end(r)});return e}getPlayerStats(){const e=this.hlsEngine?.getStats()??{bandwidth:0,bufferHealth:0,droppedFrames:0,totalFrames:0,codec:"",resolution:"",segmentUrl:this.videoElement?.currentSrc??""};if(!this.hlsEngine&&this.videoElement){const t=this.videoElement,r=t.currentTime;for(let s=0;s<t.buffered.length;s++)if(t.buffered.start(s)<=r&&t.buffered.end(s)>=r){e.bufferHealth=parseFloat((t.buffered.end(s)-r).toFixed(2));break}const n=t.getVideoPlaybackQuality?.();e.droppedFrames=n?.droppedVideoFrames??0,e.totalFrames=n?.totalVideoFrames??0,t.videoWidth&&t.videoHeight&&!e.resolution&&(e.resolution=`${t.videoWidth}×${t.videoHeight}`),e.segmentUrl=t.currentSrc??""}return{...e,streamType:this.streamType}}persistVolume(e){try{localStorage.setItem("playron:volume",String(e))}catch{}}loadPersistedVolume(){try{const e=localStorage.getItem("playron:volume");if(e===null)return null;const t=parseFloat(e);return isFinite(t)?Math.max(0,Math.min(1,t)):null}catch{return null}}seekTo(e){this.videoEngine&&this.videoEngine.seekTo(e)}setPlaybackRate(e){this.videoEngine&&(this.videoEngine.setPlaybackRate(e),this.stateManager?.set("playbackRate",e))}async setSource(e){if(!this.videoEngine||!this.videoElement)return;console.log("[PlayerCore] Setting source:",e),await this.destroyStreamingEngines(),this.drmConfig?.enabled&&this.videoElement&&(this.drmManager=new sr(this.events),await this.drmManager.initialize(this.videoElement,this.drmConfig));const t=Qe.quickDetect(e);if(console.log("[PlayerCore] Detected protocol:",t.protocol),t.protocol==="hls"){const{HlsEngine:r}=await Promise.resolve().then(()=>require("./HlsEngine-DUVHcUpc.cjs"));this.hlsEngine=new r(this.videoElement,{autoStart:!0,maxBufferAhead:30,maxBufferBehind:10,...this.drmConfig&&{drmConfig:this.drmConfig},...this.playerConfig?.player?.withCredentials&&{withCredentials:!0}}),this.hlsEngine.on("quality-changed",({quality:n})=>{this.events.emit("qualitychange",{from:"",to:n.label})}),this.hlsEngine.on("error",({error:n})=>{Promise.resolve().then(()=>require("./ErrorManager-CDf_sFKX.cjs")).then(({errorManager:s})=>{const o=String(n?.code??""),l=o.includes("NETWORK")||o.includes("CORS")?"Network Error":o.includes("PARSE")?"Manifest Parse Error":o.includes("FRAG")?"Frag Load Error":"Playback Error";s.dispatchError(l,String(n?.code??"HLS_ERROR"),String(n?.message??"HLS streaming error"),n?.details)}),this.events.emit("error",{code:String(n?.code??"HLS_ERROR"),message:String(n?.message??"HLS streaming error"),details:n})}),this.hlsEngine.on("state-change",({state:n})=>{n==="buffering"?this.stateManager?.set("isBuffering",!0):(n==="playing"||n==="paused")&&this.stateManager?.set("isBuffering",!1)});try{await this.hlsEngine.load(e),this.container&&(this.hlsEngine.attachCaptions(this.container),this.hlsEngine.attachSubtitles(this.container));const n=this.hlsEngine.isLiveStream();this.streamType=n?"live":"vod",this.streamInfo={type:this.streamType,protocol:"hls",isDynamic:n,hasDVR:n,isEngineSupported:!0},n&&this.startLiveLatencyTracking(this.atLiveEdgeTolerance),this.events.emit("tracksready",{hasQualities:this.hlsEngine.getQualities().length>1,hasAudioTracks:this.hlsEngine.getAudioTracks().length>1,hasSubtitleTracks:this.hlsEngine.getSubtitleTracks().length>0})}catch(n){console.error("[PlayerCore] HLS load failed:",n),this.streamType="unknown",this.streamInfo=null,await this.fallbackToNative(e,"hls")}}else if(t.protocol==="dash"){const{DashEngine:r}=await Promise.resolve().then(()=>require("./DashEngine-CWBT5Q9y.cjs"));this.dashEngine=new r(this.videoElement,{autoStart:!0,maxBufferAhead:30,lowLatency:!1,...this.drmConfig&&{drmConfig:this.drmConfig}}),this.dashEngine.on("quality-changed",({quality:n})=>{this.events.emit("qualitychange",{from:"",to:n.label})}),this.dashEngine.on("error",({error:n})=>{Promise.resolve().then(()=>require("./ErrorManager-CDf_sFKX.cjs")).then(({errorManager:s})=>{const o=String(n?.code??""),l=o.includes("NETWORK")||o.includes("27")?"Network Error":o.includes("PARSE")||o.includes("31")?"Manifest Parse Error":"Playback Error";s.dispatchError(l,String(n?.code??"DASH_ERROR"),String(n?.message??"DASH streaming error"),n?.details)}),this.events.emit("error",{code:String(n?.code??"DASH_ERROR"),message:String(n?.message??"DASH streaming error"),details:n})}),this.dashEngine.on("state-change",({state:n})=>{n==="buffering"?this.stateManager?.set("isBuffering",!0):(n==="playing"||n==="paused")&&this.stateManager?.set("isBuffering",!1)});try{await this.dashEngine.load(e),this.container&&(this.dashEngine.attachCaptions(this.container),this.dashEngine.attachSubtitles(this.container));const n=this.dashEngine.isLiveStream();this.streamType=n?"live":"vod",this.streamInfo={type:this.streamType,protocol:"dash",isDynamic:n,hasDVR:n,isEngineSupported:!0},n&&this.startLiveLatencyTracking(this.atLiveEdgeTolerance),this.events.emit("tracksready",{hasQualities:this.dashEngine.getQualities().length>1,hasAudioTracks:this.dashEngine.getAudioTracks().length>1,hasSubtitleTracks:this.dashEngine.getSubtitleTracks().length>0})}catch(n){console.error("[PlayerCore] DASH load failed:",n),this.streamType="unknown",this.streamInfo=null,await this.fallbackToNative(e,"dash")}}else this.streamType="vod",this.streamInfo={type:"vod",protocol:"progressive",isDynamic:!1,hasDVR:!1,isEngineSupported:!0},this.videoEngine.setSource(e);if(this.events.emit("streamTypeDetected",{type:this.streamType,info:this.streamInfo}),window.dispatchEvent(new CustomEvent("virtus:streamTypeDetected",{detail:{type:this.streamType,info:this.streamInfo}})),this.castManager?.isCastActive()){const r=this.streamInfo?.isDynamic??!1,n=t.protocol==="hls"?"application/x-mpegURL":t.protocol==="dash"?"application/dash+xml":"video/mp4";this.castManager.loadMedia(e,n,0,r)}this.startStallDetector()}async destroyStreamingEngines(){this.stopLiveLatencyTracking(),this.hlsEngine&&(await this.hlsEngine.destroy(),this.hlsEngine=null),this.dashEngine&&(await this.dashEngine.destroy(),this.dashEngine=null),this.drmManager&&(this.drmManager.destroy(),this.drmManager=null)}async fallbackToNative(e,t){if(!(!this.videoElement||!this.videoEngine))try{console.log(`[PlayerCore] Attempting native fallback for ${t} stream`),this.videoEngine.setSource(e),this.streamType="vod",this.streamInfo={type:"vod",protocol:"progressive",isDynamic:!1,hasDVR:!1,isEngineSupported:!1}}catch(r){console.error("[PlayerCore] Native fallback failed:",r),this.events.emit("error",{code:"MEDIA_ERR_SRC_NOT_SUPPORTED",message:"Could not play stream natively or via fallback",details:r})}}getStreamType(){return this.streamType}getStreamInfo(){return this.streamInfo}isLive(){return this.streamType==="live"}getLiveEdgeTime(){return this.hlsEngine?.getLiveEdgeTime()??this.dashEngine?.getLiveEdgeTime()??0}getCurrentLatency(){if(!this.isLive())return 0;const e=this.getLiveEdgeTime();return e===0?0:Math.max(0,e-(this.videoElement?.currentTime??0))}isAtLiveEdge(e){return this.isLive()?this.getCurrentLatency()<=(e??this.atLiveEdgeTolerance):!1}seekToLiveEdge(){this.isLive()&&(this.hlsEngine?.seekToLiveEdge(),this.dashEngine?.seekToLiveEdge())}getDVRRange(){return this.hlsEngine?.getDVRRange()??this.dashEngine?.getDVRRange()??null}startLiveLatencyTracking(e){this.stopLiveLatencyTracking(),this.atLiveEdgeTolerance=e,this.liveLatencyTimer=setInterval(()=>{if(!this.isLive())return;const t=this.getCurrentLatency(),r=this.getLiveEdgeTime(),n=t<=this.atLiveEdgeTolerance;this.events.emit("livelatencyupdate",{latency:t,isAtLiveEdge:n,liveEdgeTime:r})},1e3)}stopLiveLatencyTracking(){this.liveLatencyTimer!==null&&(clearInterval(this.liveLatencyTimer),this.liveLatencyTimer=null)}startStallDetector(){this.stallDetector?.destroy(),this.stallDetector=new Ze(this.videoElement,this.events,{pollInterval:500,stallThreshold:3,onQualityDowngrade:()=>{const e=this.getAvailableQualities().filter(t=>t.id!=="auto");if(e.length>1){const t=this.getQuality();if(t&&t.id!=="auto"){const r=e.findIndex(n=>n.id===t.id);r>0&&this.setQuality(e[r-1].id)}}}}),this.stallDetector.start()}setPoster(e){this.videoEngine&&this.videoEngine.setPoster(e)}setDimensions(e,t){this.videoEngine&&this.videoEngine.setDimensions(e,t)}getState(){return this.stateManager?this.stateManager.getState():null}getVideoEngine(){return this.videoEngine}getConfigManager(){return this.configManager}getStateManager(){return this.stateManager}getVideoElement(){return this.videoElement}toggleFullscreen(){this.container&&(document.fullscreenElement?document.exitFullscreen?.():this.container.requestFullscreen?.())}async togglePip(){if(this.videoElement)try{document.pictureInPictureElement?await document.exitPictureInPicture():await this.videoElement.requestPictureInPicture()}catch(e){console.error("PiP error:",e)}}skipBackward(e=15){if(!this.videoElement)return;const t=Math.max(0,this.videoElement.currentTime-e);this.seekTo(t)}skipForward(e=15){if(!this.videoElement)return;const t=Math.min(this.videoElement.duration||0,this.videoElement.currentTime+e);this.seekTo(t)}setLoop(e){this.videoElement&&(this.videoElement.loop=e)}getLoop(){return this.videoElement?.loop||!1}setQuality(e){this.hlsEngine?e==="auto"?this.hlsEngine.enableAutoQuality():this.hlsEngine.setQuality(e):this.dashEngine&&this.dashEngine.setQuality(e)}getQuality(){return this.hlsEngine?.getCurrentQuality()??this.dashEngine?.getCurrentQuality()??null}getAvailableQualities(){return this.hlsEngine?.getQualities()??this.dashEngine?.getQualities()??[]}setAudioTrack(e){this.hlsEngine?.setAudioTrack(e),this.dashEngine?.setAudioTrack(e)}getAudioTrack(){return this.hlsEngine?.getActiveAudioTrackId()??this.dashEngine?.getActiveAudioTrackId()??""}getAvailableAudioTracks(){return this.hlsEngine?.getAudioTracks()??this.dashEngine?.getAudioTracks()??[]}getSubtitleTracks(){return this.hlsEngine?.getSubtitleTracks()??this.dashEngine?.getSubtitleTracks()??[]}async setSubtitleTrack(e){await this.hlsEngine?.setSubtitleTrack(e),await this.dashEngine?.setSubtitleTrack(e)}getActiveSubtitleLanguage(){return this.hlsEngine?.getActiveSubtitleLanguage()??this.dashEngine?.getActiveSubtitleLanguage()??null}setupAirPlay(){!this.videoElement||typeof this.videoElement.webkitShowPlaybackTargetPicker!="function"||(this.onAirPlayAvailabilityChanged=t=>{const r=t;this.airPlayAvailable=r.availability==="available",this.events.emit("airplaychange",{isAvailable:this.airPlayAvailable,isActive:this.airPlayActive})},this.onAirPlayTargetChanged=()=>{this.airPlayActive=!!this.videoElement.webkitCurrentPlaybackTargetIsWireless,this.events.emit("airplaychange",{isAvailable:this.airPlayAvailable,isActive:this.airPlayActive})},this.videoElement.addEventListener("webkitplaybacktargetavailabilitychanged",this.onAirPlayAvailabilityChanged),this.videoElement.addEventListener("webkitcurrentplaybacktargetiswirelesschanged",this.onAirPlayTargetChanged))}showAirPlayPicker(){if(!this.videoElement)return;const e=this.videoElement;typeof e.webkitShowPlaybackTargetPicker=="function"?e.webkitShowPlaybackTargetPicker():console.warn("[PlayerCore] AirPlay not supported in this browser")}isAirPlayAvailable(){return this.airPlayAvailable}isAirPlayActive(){return this.airPlayActive}destroyAirPlay(){this.videoElement&&(this.onAirPlayAvailabilityChanged&&(this.videoElement.removeEventListener("webkitplaybacktargetavailabilitychanged",this.onAirPlayAvailabilityChanged),this.onAirPlayAvailabilityChanged=null),this.onAirPlayTargetChanged&&(this.videoElement.removeEventListener("webkitcurrentplaybacktargetiswirelesschanged",this.onAirPlayTargetChanged),this.onAirPlayTargetChanged=null))}setupChromecast(e){this.castManager||(this.castManager=new rt({appId:e,onChange:t=>{this.events.emit("castchange",t)}}),this.castManager.setup(),console.log("[PlayerCore] Chromecast setup complete"))}async showCastPicker(){if(!this.castManager){console.warn("[PlayerCore] Chromecast not initialised — call setupChromecast() first");return}await this.castManager.requestSession()}stopCasting(){this.castManager?.endSession(!0)}isCastAvailable(){return this.castManager?.isCastAvailable()??!1}isCastActive(){return this.castManager?.isCastActive()??!1}destroyChromecast(){this.castManager?.destroy(),this.castManager=null}toggleTheaterMode(){if(this.container){const e=this.container,t=e.isTheaterMode||!1;e.isTheaterMode=!t,window.dispatchEvent(new CustomEvent("virtus:theatermodechange",{detail:{isTheaterMode:!t},bubbles:!0}))}}isTheaterMode(){return this.container?.isTheaterMode||!1}destroy(){this.stallDetector?.destroy(),this.stallDetector=null,this.destroyAirPlay(),this.destroyChromecast(),this.destroyStreamingEngines(),this.videoEngine&&(this.videoEngine.destroy(),this.videoEngine=null),this.stateManager&&(this.stateManager.reset(),this.stateManager=null),this.configManager&&(this.configManager.reset(),this.configManager=null),this.videoElement=null,this.container=null}}const it=c.createContext(null),nt={isPlaying:!1,isMuted:!1,volume:1,currentTime:0,duration:0,isLive:!1,isAtLiveEdge:!1,liveLatency:0},st=c.createContext(nt),ot=c.createContext(null);function at({children:a,playerInstance:e}){const[t,r]=c.useState(nt);c.useEffect(()=>{if(!e)return;const s=e.getStateManager();if(!s)return;r(s.getState());const o=u=>{r(u)};s.subscribe(o);const l=e.getVideoElement();if(l){const u=()=>{const g=e.isLive();s.updateState({currentTime:l.currentTime,duration:l.duration||0,isLive:g})},d=()=>{s.set("isPlaying",!l.paused)},h=()=>{s.updateState({volume:l.volume,isMuted:l.muted})},p=({latency:g,isAtLiveEdge:m})=>{s.updateState({liveLatency:g,isAtLiveEdge:m,isLive:!0})};return e.events.on("livelatencyupdate",p),l.addEventListener(k.TIME_UPDATE,u),l.addEventListener(k.PLAY,d),l.addEventListener(k.PAUSE,d),l.addEventListener(k.VOLUME_CHANGE,h),l.addEventListener(k.LOADED_METADATA,u),()=>{e.events.off("livelatencyupdate",p),l.removeEventListener(k.TIME_UPDATE,u),l.removeEventListener(k.PLAY,d),l.removeEventListener(k.PAUSE,d),l.removeEventListener(k.VOLUME_CHANGE,h),l.removeEventListener(k.LOADED_METADATA,u),s.unsubscribe(o)}}return()=>{s.unsubscribe(o)}},[e]);const n=c.useMemo(()=>e?{play:async()=>{await e.play()},pause:()=>{e.pause()},togglePlay:async()=>{e.getState()?.isPlaying?e.pause():await e.play()},toggleMute:()=>{e.toggleMute()},setVolume:s=>{e.setVolume(s)},seekTo:s=>{e.seekTo(s)},setPlaybackRate:s=>{e.setPlaybackRate(s)},toggleFullscreen:()=>{e.toggleFullscreen()},togglePip:async()=>{await e.togglePip()},skipBackward:(s=15)=>{e.skipBackward(s)},skipForward:(s=15)=>{e.skipForward(s)},setLoop:s=>{e.setLoop(s)},getLoop:()=>e.getLoop(),setQuality:s=>{e.setQuality(s)},getQuality:()=>e.getQuality(),getAvailableQualities:()=>e.getAvailableQualities(),setAudioTrack:s=>{e.setAudioTrack(s)},getAudioTrack:()=>e.getAudioTrack(),getAvailableAudioTracks:()=>e.getAvailableAudioTracks(),toggleTheaterMode:()=>{e.toggleTheaterMode()},isTheaterMode:()=>e.isTheaterMode(),getPlayer:()=>e,getStreamType:()=>e.getStreamType(),getStreamInfo:()=>e.getStreamInfo(),isLive:()=>e.isLive(),getBufferedRanges:()=>e.getBufferedRanges(),seekToLiveEdge:()=>{e.seekToLiveEdge()},getCurrentLatency:()=>e.getCurrentLatency(),isAtLiveEdge:s=>e.isAtLiveEdge(s),getDVRRange:()=>e.getDVRRange(),getSubtitleTracks:()=>e.getSubtitleTracks(),setSubtitleTrack:async s=>{await e.setSubtitleTrack(s)},getActiveSubtitleLanguage:()=>e.getActiveSubtitleLanguage(),getPlayerStats:()=>e.getPlayerStats()}:null,[e]);return i.jsx(it.Provider,{value:e,children:i.jsx(ot.Provider,{value:n,children:i.jsx(st.Provider,{value:t,children:a})})})}function O(a){const e=c.useContext(st);if(!e)throw new Error("usePlayerState must be used within PlayerProvider");return a?a(e):e}function U(){const a=c.useContext(ot);if(!a)throw new Error("usePlayerMethods must be used within PlayerProvider");return a}function Ue({size:a=40}){return i.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"none",stroke:"#fff",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{width:`${a}px`,height:`${a}px`,animation:"spin 1s linear infinite"},children:[i.jsx("path",{d:"M12 2v4M12 18v4M4.93 4.93l2.83 2.83M16.24 16.24l2.83 2.83M2 12h4M18 12h4M4.93 19.07l2.83-2.83M16.24 7.76l2.83-2.83"}),i.jsx("style",{children:`
|
|
1
|
+
"use strict";Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const i=require("react/jsx-runtime"),c=require("react");class Ye{listeners=new Map;on(e,t){this.listeners.has(e)||this.listeners.set(e,new Set),this.listeners.get(e).add(t)}off(e,t){const r=this.listeners.get(e);r&&(r.delete(t),r.size===0&&this.listeners.delete(e))}emit(e){const t=this.listeners.get(e.type);t&&t.forEach(r=>{try{r(e)}catch(n){console.error(`Error in event listener for ${e.type}:`,n)}})}clear(){this.listeners.clear()}listenerCount(e){return this.listeners.get(e)?.size||0}}const ie=new Ye,k={PLAY:"play",PAUSE:"pause",PLAYING:"playing",ENDED:"ended",SEEKING:"seeking",SEEKED:"seeked",WAITING:"waiting",VOLUME_CHANGE:"volumechange",TIME_UPDATE:"timeupdate",DURATION_CHANGE:"durationchange",LOADED_METADATA:"loadedmetadata",LOADED_DATA:"loadeddata",CAN_PLAY:"canplay",CAN_PLAY_THROUGH:"canplaythrough",RATE_CHANGE:"ratechange",LOAD_START:"loadstart",PROGRESS:"progress",SUSPEND:"suspend",ABORT:"abort",STALLED:"stalled",ERROR:"error",EMPTIED:"emptied",RESIZE:"resize"},he={MEDIA_ERR_ABORTED:1,MEDIA_ERR_NETWORK:2,MEDIA_ERR_DECODE:3,MEDIA_ERR_SRC_NOT_SUPPORTED:4};function Ft(a){return Object.values(k).includes(a)}class Ut{videoElement=null;isPlaying=!1;isMuted=!1;volume=1;playbackRate=1;currentTime=0;duration=0;constructor(e){this.videoElement=e,this.setupEventListeners(),this.initializeVideo()}setupEventListeners(){this.videoElement&&(this.videoElement.addEventListener(k.PLAY,()=>{this.isPlaying=!0,this.emitPlayEvent()}),this.videoElement.addEventListener(k.PAUSE,()=>{this.isPlaying=!1,this.emitPauseEvent()}),this.videoElement.addEventListener(k.VOLUME_CHANGE,()=>{this.videoElement&&(this.volume=this.videoElement.volume,this.isMuted=this.videoElement.muted,this.emitVolumeChangeEvent())}),this.videoElement.addEventListener(k.TIME_UPDATE,()=>{this.videoElement&&(this.currentTime=this.videoElement.currentTime)}),this.videoElement.addEventListener(k.LOADED_METADATA,()=>{this.videoElement&&(this.duration=this.videoElement.duration)}),this.videoElement.addEventListener(k.RATE_CHANGE,()=>{this.videoElement&&(this.playbackRate=this.videoElement.playbackRate)}),this.videoElement.addEventListener(k.ERROR,e=>{console.error("Video error:",e),this.videoElement?.error&&console.error("Video error details:",{code:this.videoElement.error.code,message:this.videoElement.error.message,MEDIA_ERR_ABORTED:this.videoElement.error.code===he.MEDIA_ERR_ABORTED,MEDIA_ERR_NETWORK:this.videoElement.error.code===he.MEDIA_ERR_NETWORK,MEDIA_ERR_DECODE:this.videoElement.error.code===he.MEDIA_ERR_DECODE,MEDIA_ERR_SRC_NOT_SUPPORTED:this.videoElement.error.code===he.MEDIA_ERR_SRC_NOT_SUPPORTED})}))}initializeVideo(){this.videoElement&&(this.volume=this.videoElement.volume,this.isMuted=this.videoElement.muted,this.playbackRate=this.videoElement.playbackRate)}emitPlayEvent(){if(!this.videoElement)return;const e={type:"play",data:{currentTime:this.videoElement.currentTime,duration:this.videoElement.duration},timestamp:Date.now()};ie.emit(e)}emitPauseEvent(){if(!this.videoElement)return;const e={type:"pause",data:{currentTime:this.videoElement.currentTime,duration:this.videoElement.duration},timestamp:Date.now()};ie.emit(e)}emitVolumeChangeEvent(){const e={type:"volumechange",data:{volume:this.volume,muted:this.isMuted},timestamp:Date.now()};ie.emit(e)}emitMuteEvent(){const e={type:"mute",data:{muted:this.isMuted,volume:this.volume},timestamp:Date.now()};ie.emit(e)}async play(){if(!this.videoElement)throw new Error("Video element not found");try{await this.videoElement.play()}catch(e){throw console.error("Play failed:",e),e}}pause(){this.videoElement&&this.videoElement.pause()}toggleMute(){this.videoElement&&(this.videoElement.muted=!this.videoElement.muted,this.isMuted=this.videoElement.muted,this.emitMuteEvent())}setVolume(e){this.videoElement&&(this.videoElement.volume=Math.max(0,Math.min(1,e)))}seekTo(e){this.videoElement&&(this.videoElement.currentTime=Math.max(0,Math.min(this.duration,e)))}setPlaybackRate(e){this.videoElement&&(this.videoElement.playbackRate=Math.max(.25,Math.min(4,e)),this.playbackRate=this.videoElement.playbackRate)}setSource(e){this.videoElement&&(this.videoElement.src=e)}setPoster(e){this.videoElement&&(this.videoElement.poster=e)}setDimensions(e,t){this.videoElement&&(this.videoElement.width=typeof e=="number"?e:parseInt(e),this.videoElement.height=typeof t=="number"?t:parseInt(t))}getState(){return{isPlaying:this.isPlaying,isMuted:this.isMuted,volume:this.volume,playbackRate:this.playbackRate,currentTime:this.currentTime,duration:this.duration,src:this.videoElement?.src||"",poster:this.videoElement?.poster||""}}getVideoElement(){return this.videoElement}destroy(){this.videoElement&&(this.videoElement.removeEventListener("play",()=>{}),this.videoElement.removeEventListener("pause",()=>{}),this.videoElement.removeEventListener("volumechange",()=>{}),this.videoElement.removeEventListener("timeupdate",()=>{}),this.videoElement.removeEventListener("loadedmetadata",()=>{}),this.videoElement.removeEventListener("error",()=>{})),this.videoElement=null}}class Ot{config;defaultConfig;constructor(e){this.defaultConfig=this.getDefaultConfig(),this.config=this.mergeConfig(e),this.validateConfig(this.config)}getDefaultConfig(){return{container:"",src:"",width:800,height:450,autoplay:!1,muted:!1,controls:!1,poster:"",className:""}}mergeConfig(e){return{...this.defaultConfig,...e}}validateConfig(e){if(!e.container)throw new Error("Container is required");if(!e.src)throw new Error("Source is required");const t=typeof e.width=="number"?e.width:parseInt(e.width||"800"),r=typeof e.height=="number"?e.height:parseInt(e.height||"450");if(e.width&&(t<100||t>4e3))throw new Error("Width must be between 100 and 4000");if(e.height&&(r<100||r>4e3))throw new Error("Height must be between 100 and 4000")}updateConfig(e){const t={...this.config,...e};this.validateConfig(t),this.config=t}getConfig(){return{...this.config}}get(e){return this.config[e]}set(e,t){const r={[e]:t};this.updateConfig(r)}getContainer(){return typeof this.config.container=="string"?document.querySelector(this.config.container):this.config.container}getDimensions(){return{width:typeof this.config.width=="number"?this.config.width:parseInt(this.config.width||"800"),height:typeof this.config.height=="number"?this.config.height:parseInt(this.config.height||"450")}}reset(){this.config={...this.defaultConfig}}export(){return JSON.stringify(this.config,null,2)}import(e){try{const t=JSON.parse(e);this.validateConfig(t),this.config=t}catch{throw new Error("Invalid configuration format")}}listeners=[];onChange(e){this.listeners.push(e)}offChange(e){const t=this.listeners.indexOf(e);t>-1&&this.listeners.splice(t,1)}notifyChange(){this.listeners.forEach(e=>{try{e(this.config)}catch(t){console.error("Config change listener error:",t)}})}updateConfigAndNotify(e){this.updateConfig(e),this.notifyChange()}}class Wt{state;listeners=[];history=[];maxHistorySize=50;constructor(e){this.state=this.getInitialState(e)}getInitialState(e){return{...{isPlaying:!1,isMuted:!1,volume:1,currentTime:0,duration:0,playbackRate:1},...e}}updateState(e){const t={...this.state};this.state={...this.state,...e},this.addToHistory(t),this.notifyListeners()}getState(){return{...this.state}}get(e){return this.state[e]}set(e,t){this.updateState({[e]:t})}subscribe(e){this.listeners.push(e)}unsubscribe(e){const t=this.listeners.indexOf(e);t>-1&&this.listeners.splice(t,1)}notifyListeners(){this.listeners.forEach(e=>{try{e(this.state)}catch(t){console.error("State listener error:",t)}})}addToHistory(e){this.history.push(e),this.history.length>this.maxHistorySize&&this.history.shift()}undo(){if(this.history.length===0)return!1;const e=this.history.pop();return e?(this.state=e,this.notifyListeners(),!0):!1}reset(){this.state=this.getInitialState(),this.history=[],this.notifyListeners()}setState(e){const t={...this.state};this.state={...e},this.addToHistory(t),this.notifyListeners()}clearHistory(){this.history=[]}getHistory(){return[...this.history]}isInState(e){return e(this.state)}subscribeToChanges(e,t){let r={...this.state};const n=s=>{const o={};let l=!1;e.forEach(d=>{r[d]!==s[d]&&(o[d]=s[d],l=!0)}),l&&t(o),r={...s}};this.subscribe(n)}createSnapshot(){return{...this.state}}restoreFromSnapshot(e){this.setState(e)}getStats(){return{totalListeners:this.listeners.length,historySize:this.history.length,maxHistorySize:this.maxHistorySize,lastUpdate:new Date}}}class Xe{listeners=new Map;onceListeners=new Map;on(e,t){this.listeners.has(e)||this.listeners.set(e,new Set),this.listeners.get(e).add(t)}once(e,t){this.onceListeners.has(e)||this.onceListeners.set(e,new Set),this.onceListeners.get(e).add(t)}off(e,t){const r=this.listeners.get(e);r&&(r.delete(t),r.size===0&&this.listeners.delete(e));const n=this.onceListeners.get(e);n&&(n.delete(t),n.size===0&&this.onceListeners.delete(e))}emit(e,t){const r=this.listeners.get(e);r&&r.forEach(s=>{try{s(t)}catch(o){console.error(`[Playron] Error in event listener for "${e}":`,o)}});const n=this.onceListeners.get(e);n&&(n.forEach(s=>{try{s(t)}catch(o){console.error(`[Playron] Error in once listener for "${e}":`,o)}}),this.onceListeners.delete(e))}removeAllListeners(e){e?(this.listeners.delete(e),this.onceListeners.delete(e)):(this.listeners.clear(),this.onceListeners.clear())}listenerCount(e){const t=this.listeners.get(e)?.size||0,r=this.onceListeners.get(e)?.size||0;return t+r}eventNames(){const e=new Set;return this.listeners.forEach((t,r)=>e.add(r)),this.onceListeners.forEach((t,r)=>e.add(r)),Array.from(e)}}class Ge{async detectStream(e){const t=this.detectProtocol(e);try{if(t==="hls")return await this.detectHLS(e);if(t==="dash")return await this.detectDASH(e);if(t==="progressive")return this.detectProgressive(e)}catch(r){console.warn("[StreamDetector] Failed to detect stream type:",r)}return{type:"unknown",protocol:"unknown",isDynamic:!1,hasDVR:!1,isEngineSupported:this.preCheckCapability("unknown")}}preCheckCapability(e){if(typeof MediaSource>"u")return!1;const t=MediaSource.isTypeSupported('video/mp4; codecs="avc1.42E01E"')||MediaSource.isTypeSupported('video/mp4; codecs="avc1.4d401e"')||MediaSource.isTypeSupported('video/mp4; codecs="avc1.64001F"'),r=MediaSource.isTypeSupported('video/mp4; codecs="hev1.1.6.L93.B0"')||MediaSource.isTypeSupported('video/mp4; codecs="hvc1.1.6.L93.B0"'),n=MediaSource.isTypeSupported('video/webm; codecs="vp9"')||MediaSource.isTypeSupported('video/mp4; codecs="vp09.00.10.08"'),s=t||r||n,o=/Safari/.test(navigator.userAgent)&&/Apple Computer/.test(navigator.vendor);return e==="hls"&&o?!0:s}detectProtocol(e){const t=e.toLowerCase();return t.includes(".m3u8")||t.includes(".m3u")?"hls":t.includes(".mpd")?"dash":t.match(/\.(mp4|webm|ogg)$/)?"progressive":"unknown"}async detectHLS(e){const t=await this.fetchManifest(e);if(t.includes("#EXT-X-ENDLIST")||t.includes("#EXT-X-PLAYLIST-TYPE:VOD"))return{type:"vod",protocol:"hls",isDynamic:!1,hasDVR:!1,isEngineSupported:this.preCheckCapability("hls")};const n=t.includes("#EXT-X-MEDIA-SEQUENCE"),s=t.includes("#EXT-X-ENDLIST"),o=t.includes("#EXT-X-PLAYLIST-TYPE:EVENT"),l=this.extractTargetDuration(t),d=this.extractMediaSequence(t);return n&&!s?{type:"live",protocol:"hls",isDynamic:!0,hasDVR:o,targetDuration:l,mediaSequence:d,isEngineSupported:this.preCheckCapability("hls")}:{type:"vod",protocol:"hls",isDynamic:!1,hasDVR:!1,isEngineSupported:this.preCheckCapability("hls")}}async detectDASH(e){const t=await this.fetchManifest(e),s=t.match(/<MPD[^>]*type="(static|dynamic)"/)?.[1]==="dynamic",o=t.includes("timeShiftBufferDepth");return{type:s?"live":"vod",protocol:"dash",isDynamic:s,hasDVR:o,isEngineSupported:this.preCheckCapability("dash")}}detectProgressive(e){return{type:"vod",protocol:"progressive",isDynamic:!1,hasDVR:!1,isEngineSupported:!0}}async fetchManifest(e){const t=await fetch(e,{method:"GET",headers:{Accept:"*/*"}});if(!t.ok)throw new Error(`Failed to fetch manifest: ${t.status}`);return await t.text()}extractTargetDuration(e){const t=e.match(/#EXT-X-TARGETDURATION:(\d+)/);return t?parseInt(t[1],10):void 0}extractMediaSequence(e){const t=e.match(/#EXT-X-MEDIA-SEQUENCE:(\d+)/);return t?parseInt(t[1],10):void 0}quickDetect(e){const t=this.detectProtocol(e);return t==="progressive"?{type:"vod",protocol:"progressive",isEngineSupported:!0}:{type:"unknown",protocol:t,isEngineSupported:this.preCheckCapability(t)}}}const Qe=new Ge;class Ze{video;events;options;timer=null;lastTime=-1;stallDuration=0;attempts=0;isRunning=!1;constructor(e,t,r={}){this.video=e,this.events=t,this.options={pollInterval:r.pollInterval??500,stallThreshold:r.stallThreshold??3,onQualityDowngrade:r.onQualityDowngrade}}start(){this.isRunning||(this.isRunning=!0,this.reset(),this.timer=setInterval(()=>this.tick(),this.options.pollInterval))}stop(){this.timer!==null&&(clearInterval(this.timer),this.timer=null),this.isRunning=!1,this.reset()}destroy(){this.stop()}reset(){this.lastTime=-1,this.stallDuration=0,this.attempts=0}tick(){const e=this.video;if(e.paused||e.ended||e.seeking||e.readyState<2){this.stallDuration=0,this.lastTime=e.currentTime;return}const t=e.currentTime;if(this.lastTime<0){this.lastTime=t;return}const r=t-this.lastTime;if(this.lastTime=t,r>.05){if(this.stallDuration>0){const o=this.attempts>=3?"quality":"seek";this.events.emit("stallrecovered",{duration:Math.round(this.stallDuration),method:o})}this.stallDuration=0,this.attempts=0;return}this.stallDuration+=this.options.pollInterval/1e3;const{stallThreshold:n}=this.options,s=Math.floor(this.stallDuration/n);s>this.attempts&&(this.attempts=s,this.recover())}recover(){const e=this.video;switch(this.events.emit("stall",{duration:Math.round(this.stallDuration),attempt:this.attempts}),this.attempts){case 1:e.currentTime=Math.min(e.currentTime+.5,e.duration||1/0);break;case 2:e.currentTime=Math.min(e.currentTime+2,e.duration||1/0);break;case 3:this.options.onQualityDowngrade&&this.options.onQualityDowngrade(),e.currentTime=Math.min(e.currentTime+2,e.duration||1/0);break;default:this.events.emit("error",{code:"STALL_UNRECOVERABLE",message:`Playback stalled for ${Math.round(this.stallDuration)}s and could not be recovered.`}),this.stop();break}}}const Je=[{contentType:'video/mp4; codecs="avc1.42E01E"'}],Ht=[{contentType:'audio/mp4; codecs="mp4a.40.2"'}],zt=[{initDataTypes:["cenc"],videoCapabilities:Je,audioCapabilities:Ht}];async function Le(a){try{return await navigator.requestMediaKeySystemAccess(a,zt),!0}catch{return!1}}async function et(){const[a,e,t]=await Promise.all([Le("com.widevine.alpha"),Le("com.microsoft.playready"),Le("org.w3.clearkey")]),r=await(async()=>{try{return await navigator.requestMediaKeySystemAccess("com.apple.fps",[{initDataTypes:["skd"],videoCapabilities:Je}]),!0}catch{return!1}})();let n=null;return a?n="widevine":r?n="fairplay":e?n="playready":t&&(n="clearkey"),{widevine:a,fairplay:r,playready:e,clearkey:t,preferredSystem:n}}const qt=3e4,Kt=2,Yt=1e3,Ie=new Map;async function tt(a,e,t,r,n){let s=new Error("License request failed");for(let o=0;o<=r;o++){if(o>0){const u=n*Math.pow(2,o-1);await new Promise(h=>setTimeout(h,u))}const l=new AbortController,d=setTimeout(()=>l.abort(),t);try{const u=await fetch(a,{...e,signal:l.signal});if(clearTimeout(d),!u.ok)throw new Error(`HTTP ${u.status}: ${u.statusText}`);return await u.arrayBuffer()}catch(u){clearTimeout(d),u instanceof Error&&u.name==="AbortError"?s=new Error(`Request timed out after ${t}ms (attempt ${o+1}/${r+1})`):s=u instanceof Error?u:new Error(String(u))}}throw s}async function Xt(a,e={}){const t=Ie.get(a);if(t)return console.debug("[LicenseManager] Using cached FairPlay certificate:",a),t;console.debug("[LicenseManager] Fetching FairPlay certificate:",a);const r=await tt(a,{method:"GET",headers:e},15e3,1,500);return Ie.set(a,r),r}function Gt(){Ie.clear()}async function Qt(a,e,t={},r=!1,n={}){const s=n.timeout??qt,o=n.maxRetries??Kt,l=n.retryDelay??Yt;let d=e;n.prepareLicenseRequest&&(d=await n.prepareLicenseRequest(e));const u={method:"POST",body:d,headers:{"Content-Type":"application/octet-stream",...t},credentials:r?"include":"omit"};console.debug("[LicenseManager] Acquiring license from:",a);let h=await tt(a,u,s,o,l);return n.parseLicenseResponse&&(h=await n.parseLicenseResponse(h)),h}const Be="com.apple.fps",Zt=[{initDataTypes:["skd"],videoCapabilities:[{contentType:'video/mp4; codecs="avc1.42E01E"'},{contentType:'video/mp4; codecs="hvc1.1.6.L93.B0"'}],audioCapabilities:[{contentType:'audio/mp4; codecs="mp4a.40.2"'}],sessionTypes:["temporary"],persistentState:"optional",distinctiveIdentifier:"optional"}];class Jt{keySystem=Be;config;mediaKeys=null;videoElement=null;sessions=new Set;destroyed=!1;boundOnEncrypted;constructor(e){this.config=e,this.boundOnEncrypted=t=>{this.handleEncrypted(t)}}async initialize(e){if(this.destroyed)return;this.videoElement=e;let t;try{t=await navigator.requestMediaKeySystemAccess(Be,Zt)}catch{throw new Error("FairPlay Streaming is not supported in this browser. Safari on macOS or iOS is required.")}this.mediaKeys=await t.createMediaKeys();let r;try{r=await Xt(this.config.certificateUrl,this.config.headers)}catch(n){throw new Error(`FairPlay: Failed to fetch server certificate from ${this.config.certificateUrl}: `+(n instanceof Error?n.message:String(n)))}try{await this.mediaKeys.setServerCertificate(r)||console.debug("[FairPlayAdapter] setServerCertificate returned false (certificate may not be required)")}catch(n){throw new Error(`FairPlay: setServerCertificate failed: ${n instanceof Error?n.message:String(n)}`)}await e.setMediaKeys(this.mediaKeys),e.addEventListener("encrypted",this.boundOnEncrypted),console.debug("[FairPlayAdapter] Initialized — waiting for encrypted event"),this.config.onReady?.()}async handleEncrypted(e){if(!this.mediaKeys||this.destroyed)return;console.debug("[FairPlayAdapter] Received encrypted event, initDataType:",e.initDataType);const t=this.mediaKeys.createSession("temporary");if(this.sessions.add(t),t.addEventListener("message",r=>{this.handleKeyMessage(t,r)}),t.addEventListener("keystatuseschange",()=>{this.handleKeyStatusChange(t)}),!e.initData){this.sessions.delete(t),console.warn("[FairPlayAdapter] Encrypted event has no initData — skipping session");return}try{await t.generateRequest(e.initDataType,e.initData)}catch(r){this.sessions.delete(t);const n=`FairPlay: generateRequest failed: ${r instanceof Error?r.message:String(r)}`;console.error("[FairPlayAdapter]",n),this.config.onError?.("FAIRPLAY_GENERATE_REQUEST_FAILED",n,!0)}}async handleKeyMessage(e,t){if(this.destroyed)return;const r=t.message;console.debug("[FairPlayAdapter] Received key message, acquiring license...");try{const n=await Qt(this.config.licenseUrl,r,this.config.headers??{},this.config.withCredentials??!1,this.config.licenseAcquisitionConfig??{});await e.update(n),console.debug("[FairPlayAdapter] License applied successfully")}catch(n){const s=`FairPlay: License acquisition failed: ${n instanceof Error?n.message:String(n)}`;console.error("[FairPlayAdapter]",s),this.config.onError?.("FAIRPLAY_LICENSE_FAILED",s,!0)}}handleKeyStatusChange(e){e.keyStatuses.forEach(t=>{switch(t){case"expired":this.config.onError?.("FAIRPLAY_KEY_EXPIRED","FairPlay: Content key has expired. Please reload the player.",!0);break;case"output-restricted":this.config.onError?.("FAIRPLAY_OUTPUT_RESTRICTED","FairPlay: Output restricted — HDCP connection required.",!1);break;case"internal-error":this.config.onError?.("FAIRPLAY_INTERNAL_ERROR","FairPlay: Internal key error.",!0);break;case"usable":console.debug("[FairPlayAdapter] Key status: usable");break;default:console.debug("[FairPlayAdapter] Key status:",t)}})}destroy(){this.destroyed||(this.destroyed=!0,this.videoElement&&this.videoElement.removeEventListener("encrypted",this.boundOnEncrypted),this.sessions.forEach(e=>{e.close().catch(()=>{})}),this.sessions.clear(),this.videoElement&&(this.videoElement.setMediaKeys(null).catch(()=>{}),this.videoElement=null),this.mediaKeys=null,console.debug("[FairPlayAdapter] Destroyed"))}}const Ne="com.widevine.alpha",er=[{initDataTypes:["cenc"],videoCapabilities:[{contentType:'video/mp4; codecs="avc1.42E01E"',robustness:"SW_SECURE_CRYPTO"},{contentType:'video/mp4; codecs="avc1.42E01E"'}],audioCapabilities:[{contentType:'audio/mp4; codecs="mp4a.40.2"'}],sessionTypes:["temporary"]}];class tr{keySystem=Ne;config;destroyed=!1;constructor(e){this.config=e}async initialize(e){if(!this.destroyed){try{await navigator.requestMediaKeySystemAccess(Ne,er)}catch{throw new Error("Widevine is not supported in this browser. Chrome, Firefox, or Edge (Chromium) is required for Widevine DRM.")}console.debug("[WidevineAdapter] Widevine key system confirmed — delegating EME to streaming engine"),this.config.onReady?.()}}destroy(){this.destroyed=!0,console.debug("[WidevineAdapter] Destroyed")}}const je="com.microsoft.playready",$e="com.microsoft.playready.hardware",rr=[{initDataTypes:["cenc"],videoCapabilities:[{contentType:'video/mp4; codecs="avc1.42E01E"'}],audioCapabilities:[{contentType:'audio/mp4; codecs="mp4a.40.2"'}],sessionTypes:["temporary"]}];class ir{keySystem;config;destroyed=!1;constructor(e){this.config=e,this.keySystem=e.preferHardware?$e:je}async initialize(e){if(this.destroyed)return;const t=this.config.preferHardware?[$e,je]:[je];let r=!1;for(const n of t)try{await navigator.requestMediaKeySystemAccess(n,rr),r=!0,console.debug(`[PlayReadyAdapter] Key system confirmed: ${n}`);break}catch{}if(!r)throw new Error("PlayReady is not supported in this browser. Microsoft Edge or Internet Explorer is required for PlayReady DRM.");console.debug("[PlayReadyAdapter] PlayReady key system confirmed — delegating EME to dashjs"),this.config.onReady?.()}destroy(){this.destroyed=!0,console.debug("[PlayReadyAdapter] Destroyed")}}const nr={widevine:"com.widevine.alpha",fairplay:"com.apple.fps",playready:"com.microsoft.playready"};class sr{adapter=null;selectedKeySystem=null;emitter;destroyed=!1;constructor(e){this.emitter=e}async initialize(e,t){if(this.destroyed||!t?.enabled)return null;const r=await et().catch(()=>({widevine:!1,fairplay:!1,playready:!1,clearkey:!1,preferredSystem:null})),n=t.preferredSystem;if(n&&(n==="fairplay"&&r.fairplay&&t.fairplay&&(this.selectedKeySystem="fairplay"),n==="widevine"&&r.widevine&&t.widevine&&(this.selectedKeySystem="widevine"),n==="playready"&&r.playready&&t.playready&&(this.selectedKeySystem="playready")),this.selectedKeySystem||(r.fairplay&&t.fairplay?this.selectedKeySystem="fairplay":r.widevine&&t.widevine?this.selectedKeySystem="widevine":r.playready&&t.playready&&(this.selectedKeySystem="playready")),!this.selectedKeySystem)return console.warn("[DrmManager] No supported DRM key system found for the provided configuration. Browser capabilities:",r),null;const s=nr[this.selectedKeySystem];if(console.debug("[DrmManager] Selected key system:",s),this.emitter.emit("drm:keysystem",{keySystem:s}),this.adapter=this.createAdapter(t),!this.adapter)return null;try{await this.adapter.initialize(e)}catch(o){const l=o instanceof Error?o.message:String(o);return console.error("[DrmManager] Adapter initialization failed:",l),this.emitter.emit("error",{code:"DRM_INIT_FAILED",message:l,details:o}),this.selectedKeySystem=null,null}return this.emitter.emit("drm:ready",{keySystem:s}),this.selectedKeySystem}getSelectedKeySystem(){return this.selectedKeySystem}destroy(){this.destroyed||(this.destroyed=!0,this.adapter?.destroy(),this.adapter=null,this.selectedKeySystem=null,Gt(),console.debug("[DrmManager] Destroyed"))}createAdapter(e){const t=(r,n,s=!0)=>{this.emitter.emit("error",{code:r,message:n,details:{fatal:s}})};switch(this.selectedKeySystem){case"fairplay":{const r=e.fairplay;return new Jt({licenseUrl:r.licenseUrl,certificateUrl:r.certificateUrl,headers:r.headers,withCredentials:r.withCredentials,licenseAcquisitionConfig:r.licenseAcquisitionConfig,onError:t})}case"widevine":{const r=e.widevine;return new tr({licenseUrl:r.licenseUrl,headers:r.headers,withCredentials:r.withCredentials,licenseAcquisitionConfig:r.licenseAcquisitionConfig,onError:t})}case"playready":{const r=e.playready;return new ir({licenseUrl:r.licenseUrl,headers:r.headers,withCredentials:r.withCredentials,licenseAcquisitionConfig:r.licenseAcquisitionConfig,onError:t})}default:return null}}}const or="https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1",Fe="playron-cast-sdk";class rt{appId;onChange;isAvailable=!1;sessionActive=!1;sdkLoaded=!1;castStateHandler=null;constructor(e){this.appId=e.appId??"CC1AD845",this.onChange=e.onChange}setup(){if(this.sdkLoaded)return;this.sdkLoaded=!0;const e=window.__onGCastApiAvailable;if(window.__onGCastApiAvailable=t=>{e?.(t),t?this.initContext():(console.warn("[ChromecastManager] Cast API not available (no Cast devices found or extension missing)"),this.emitState())},!document.getElementById(Fe)){const t=document.createElement("script");t.id=Fe,t.src=or,t.async=!0,document.head.appendChild(t),console.log("[ChromecastManager] Cast SDK script injected")}}async requestSession(){const e=this.getContext();if(!e){console.warn("[ChromecastManager] Cast context not ready — call setup() first");return}try{await e.requestSession()}catch(t){(t instanceof Error?t.message:String(t)).toLowerCase().includes("cancel")||console.error("[ChromecastManager] requestSession error:",t)}}endSession(e=!0){this.getContext()?.endCurrentSession(e)}async loadMedia(e,t="video/mp4",r=0,n=!1){const s=this.getContext()?.getCurrentSession();if(!s){console.warn("[ChromecastManager] No active Cast session — call requestSession() first");return}const o=window.chrome?.cast;if(o)try{const l=new o.media.MediaInfo(e,t);l.streamType=n?o.media.StreamType.LIVE:o.media.StreamType.BUFFERED,l.metadata=null;const d=new o.media.LoadRequest(l);d.currentTime=r,d.autoplay=!0,await s.loadMedia(d),console.log(`[ChromecastManager] Media loaded on receiver: ${e} (t=${r}s)`)}catch(l){console.error("[ChromecastManager] loadMedia error:",l)}}syncTime(e){const r=this.getContext()?.getCurrentSession()?.getMediaSession();r&&r.seek({currentTime:e,type:"SEEK"})}async syncVolume(e,t){const r=this.getContext()?.getCurrentSession();if(r)try{await r.setVolume(e),await r.setMute(t)}catch{}}isCastAvailable(){return this.isAvailable}isCastActive(){return this.sessionActive}getState(){const e=this.getContext()?.getCastState()??"";let t="unavailable";const r=window.cast?.framework;return r&&(e===r.CastState.NO_DEVICES_AVAILABLE?t="unavailable":e===r.CastState.NOT_CONNECTED?t="not_connected":e===r.CastState.CONNECTING?t="connecting":e===r.CastState.CONNECTED&&(t="connected")),{isAvailable:this.isAvailable,isActive:this.sessionActive,state:t}}destroy(){const e=this.getContext();if(e&&this.castStateHandler){const t=window.cast?.framework?.CastContextEventType;t&&(e.removeEventListener(t.CAST_STATE_CHANGED,this.castStateHandler),e.removeEventListener(t.SESSION_STATE_CHANGED,this.castStateHandler)),this.castStateHandler=null}console.log("[ChromecastManager] Destroyed")}getContext(){return window.cast?.framework?.CastContext?.getInstance()??null}initContext(){const e=this.getContext();if(!e)return;try{e.setOptions({receiverApplicationId:this.appId})}catch(r){console.error("[ChromecastManager] setOptions error:",r);return}this.castStateHandler=()=>{this.syncState()};const t=window.cast?.framework?.CastContextEventType;t&&(e.addEventListener(t.CAST_STATE_CHANGED,this.castStateHandler),e.addEventListener(t.SESSION_STATE_CHANGED,this.castStateHandler)),this.syncState(),console.log(`[ChromecastManager] Initialized with appId=${this.appId}`)}syncState(){const e=this.getContext()?.getCastState()??"",t=window.cast?.framework;if(!t)return;const r=this.sessionActive;this.isAvailable=e!==t.CastState.NO_DEVICES_AVAILABLE,this.sessionActive=e===t.CastState.CONNECTED,r!==this.sessionActive&&console.log(`[ChromecastManager] Session state: ${this.sessionActive?"CONNECTED":"DISCONNECTED"}`),this.emitState()}emitState(){this.onChange(this.getState())}}class ne{videoEngine=null;configManager=null;stateManager=null;videoElement=null;container=null;events;streamType="unknown";streamInfo=null;hlsEngine=null;dashEngine=null;airPlayAvailable=!1;airPlayActive=!1;onAirPlayAvailabilityChanged=null;onAirPlayTargetChanged=null;stallDetector=null;liveLatencyTimer=null;atLiveEdgeTolerance=10;drmConfig=null;drmManager=null;playerConfig=null;castManager=null;static preloadEngines(){Promise.resolve().then(()=>require("./HlsEngine-DUVHcUpc.cjs")),Promise.resolve().then(()=>require("./DashEngine-CWBT5Q9y.cjs"))}constructor(e){this.videoElement=e,this.events=new Xe,this.initialize()}initialize(){if(!this.videoElement)return;this.videoEngine=new Ut(this.videoElement);const e=this.loadPersistedVolume();e!==null&&(this.videoElement.volume=e),this.stateManager=new Wt({isPlaying:!1,isMuted:this.videoElement.muted,volume:this.videoElement.volume,currentTime:0,duration:0,playbackRate:this.videoElement.playbackRate||1}),this.setupStateListeners(),this.setupAirPlay()}setupStateListeners(){!this.stateManager||!this.videoElement||(this.videoElement.addEventListener(k.PLAY,()=>{this.events.emit("play",{timestamp:Date.now()})}),this.videoElement.addEventListener(k.PAUSE,()=>{this.events.emit("pause",{timestamp:Date.now()})}),this.videoElement.addEventListener(k.TIME_UPDATE,()=>{this.events.emit("timeupdate",{currentTime:this.videoElement?.currentTime||0,duration:this.videoElement?.duration||0})}),this.videoElement.addEventListener(k.ENDED,()=>{this.events.emit("ended",{timestamp:Date.now()})}),this.videoElement.addEventListener(k.LOADED_METADATA,()=>{this.events.emit("loadedmetadata",{duration:this.videoElement?.duration||0,videoWidth:this.videoElement?.videoWidth||0,videoHeight:this.videoElement?.videoHeight||0})}),this.videoElement.addEventListener(k.RATE_CHANGE,()=>{const e=this.videoElement?.playbackRate||1;this.stateManager?.set("playbackRate",e),this.events.emit("ratechange",{playbackRate:e})}),this.videoElement.addEventListener(k.ERROR,()=>{const e=this.videoElement?.error;if(e){const t=`MEDIA_ERR_${e.code===1?"ABORTED":e.code===2?"NETWORK":e.code===3?"DECODE":e.code===4?"SRC_NOT_SUPPORTED":"UNKNOWN"}`;Promise.resolve().then(()=>require("./ErrorManager-CDf_sFKX.cjs")).then(({errorManager:r})=>{r.dispatchError("Playback Error",t,e.message||"Video playback error",e)}),this.events.emit("error",{code:t,message:e.message||"Video playback error",details:e})}}),this.stateManager.subscribe(e=>{if(this.videoEngine){const t=this.videoEngine.getState();t.isPlaying!==e.isPlaying&&(e.isPlaying?this.videoEngine.play().catch(r=>{r instanceof DOMException&&r.name==="AbortError"||console.error("Play failed:",r)}):this.videoEngine.pause()),t.isMuted!==e.isMuted&&this.videoEngine.toggleMute(),t.volume!==e.volume&&this.videoEngine.setVolume(e.volume)}}))}static createWithConfig(e){const t=typeof e.container=="string"?document.querySelector(e.container):e.container;if(!t)throw new Error(`Container not found: ${e.container}`);const r=document.createElement("video");r.id="virtus-video-player",r.src=e.src,r.width=typeof e.width=="number"?e.width:800,r.height=typeof e.height=="number"?e.height:450,r.autoplay=e.autoplay||!1,r.muted=e.muted||!1,r.controls=e.controls||!1,r.className=`playron ${e.className||""}`,e.poster&&(r.poster=e.poster),t.appendChild(r);const n=new ne(r);return n.container=t,n.configManager=new Ot(e),n}setupDrm(e){this.drmConfig=e}setConfig(e){this.playerConfig=e}async play(){if(!this.videoEngine)throw new Error("VideoEngine not initialized");try{await this.videoEngine.play(),this.stateManager?.set("isPlaying",!0)}catch(e){if(e instanceof DOMException&&e.name==="AbortError")return;throw console.error("Play failed:",e),e}}pause(){this.videoEngine&&(this.videoEngine.pause(),this.stateManager?.set("isPlaying",!1))}toggleMute(){if(!this.videoEngine)return;this.videoEngine.toggleMute();const e=this.videoEngine.getState();this.stateManager?.set("isMuted",e.isMuted)}setVolume(e){this.videoEngine&&(this.videoEngine.setVolume(e),this.stateManager?.set("volume",e),this.persistVolume(e))}getBufferedRanges(){if(!this.videoElement)return[];const e=[],{buffered:t}=this.videoElement;for(let r=0;r<t.length;r++)e.push({start:t.start(r),end:t.end(r)});return e}getPlayerStats(){const e=this.hlsEngine?.getStats()??{bandwidth:0,bufferHealth:0,droppedFrames:0,totalFrames:0,codec:"",resolution:"",segmentUrl:this.videoElement?.currentSrc??""};if(!this.hlsEngine&&this.videoElement){const t=this.videoElement,r=t.currentTime;for(let s=0;s<t.buffered.length;s++)if(t.buffered.start(s)<=r&&t.buffered.end(s)>=r){e.bufferHealth=parseFloat((t.buffered.end(s)-r).toFixed(2));break}const n=t.getVideoPlaybackQuality?.();e.droppedFrames=n?.droppedVideoFrames??0,e.totalFrames=n?.totalVideoFrames??0,t.videoWidth&&t.videoHeight&&!e.resolution&&(e.resolution=`${t.videoWidth}×${t.videoHeight}`),e.segmentUrl=t.currentSrc??""}return{...e,streamType:this.streamType}}persistVolume(e){try{localStorage.setItem("playron:volume",String(e))}catch{}}loadPersistedVolume(){try{const e=localStorage.getItem("playron:volume");if(e===null)return null;const t=parseFloat(e);return isFinite(t)?Math.max(0,Math.min(1,t)):null}catch{return null}}seekTo(e){this.videoEngine&&this.videoEngine.seekTo(e)}setPlaybackRate(e){this.videoEngine&&(this.videoEngine.setPlaybackRate(e),this.stateManager?.set("playbackRate",e))}async setSource(e){if(!this.videoEngine||!this.videoElement)return;console.log("[PlayerCore] Setting source:",e),await this.destroyStreamingEngines(),this.drmConfig?.enabled&&this.videoElement&&(this.drmManager=new sr(this.events),await this.drmManager.initialize(this.videoElement,this.drmConfig));const t=Qe.quickDetect(e);if(console.log("[PlayerCore] Detected protocol:",t.protocol),t.protocol==="hls"){const{HlsEngine:r}=await Promise.resolve().then(()=>require("./HlsEngine-DUVHcUpc.cjs"));this.hlsEngine=new r(this.videoElement,{autoStart:!0,maxBufferAhead:30,maxBufferBehind:10,...this.drmConfig&&{drmConfig:this.drmConfig},...this.playerConfig?.player?.withCredentials&&{withCredentials:!0}}),this.hlsEngine.on("quality-changed",({quality:n})=>{this.events.emit("qualitychange",{from:"",to:n.label})}),this.hlsEngine.on("error",({error:n})=>{Promise.resolve().then(()=>require("./ErrorManager-CDf_sFKX.cjs")).then(({errorManager:s})=>{const o=String(n?.code??""),l=o.includes("NETWORK")||o.includes("CORS")?"Network Error":o.includes("PARSE")?"Manifest Parse Error":o.includes("FRAG")?"Frag Load Error":"Playback Error";s.dispatchError(l,String(n?.code??"HLS_ERROR"),String(n?.message??"HLS streaming error"),n?.details)}),this.events.emit("error",{code:String(n?.code??"HLS_ERROR"),message:String(n?.message??"HLS streaming error"),details:n})}),this.hlsEngine.on("state-change",({state:n})=>{n==="buffering"?this.stateManager?.set("isBuffering",!0):(n==="playing"||n==="paused")&&this.stateManager?.set("isBuffering",!1)});try{await this.hlsEngine.load(e),this.container&&(this.hlsEngine.attachCaptions(this.container),this.hlsEngine.attachSubtitles(this.container));const n=this.hlsEngine.isLiveStream();this.streamType=n?"live":"vod",this.streamInfo={type:this.streamType,protocol:"hls",isDynamic:n,hasDVR:n,isEngineSupported:!0},n&&this.startLiveLatencyTracking(this.atLiveEdgeTolerance),this.events.emit("tracksready",{hasQualities:this.hlsEngine.getQualities().length>1,hasAudioTracks:this.hlsEngine.getAudioTracks().length>1,hasSubtitleTracks:this.hlsEngine.getSubtitleTracks().length>0})}catch(n){console.error("[PlayerCore] HLS load failed:",n),this.streamType="unknown",this.streamInfo=null,await this.fallbackToNative(e,"hls")}}else if(t.protocol==="dash"){const{DashEngine:r}=await Promise.resolve().then(()=>require("./DashEngine-CWBT5Q9y.cjs"));this.dashEngine=new r(this.videoElement,{autoStart:!0,maxBufferAhead:30,lowLatency:!1,...this.drmConfig&&{drmConfig:this.drmConfig}}),this.dashEngine.on("quality-changed",({quality:n})=>{this.events.emit("qualitychange",{from:"",to:n.label})}),this.dashEngine.on("error",({error:n})=>{Promise.resolve().then(()=>require("./ErrorManager-CDf_sFKX.cjs")).then(({errorManager:s})=>{const o=String(n?.code??""),l=o.includes("NETWORK")||o.includes("27")?"Network Error":o.includes("PARSE")||o.includes("31")?"Manifest Parse Error":"Playback Error";s.dispatchError(l,String(n?.code??"DASH_ERROR"),String(n?.message??"DASH streaming error"),n?.details)}),this.events.emit("error",{code:String(n?.code??"DASH_ERROR"),message:String(n?.message??"DASH streaming error"),details:n})}),this.dashEngine.on("state-change",({state:n})=>{n==="buffering"?this.stateManager?.set("isBuffering",!0):(n==="playing"||n==="paused")&&this.stateManager?.set("isBuffering",!1)});try{await this.dashEngine.load(e),this.container&&(this.dashEngine.attachCaptions(this.container),this.dashEngine.attachSubtitles(this.container));const n=this.dashEngine.isLiveStream();this.streamType=n?"live":"vod",this.streamInfo={type:this.streamType,protocol:"dash",isDynamic:n,hasDVR:n,isEngineSupported:!0},n&&this.startLiveLatencyTracking(this.atLiveEdgeTolerance),this.events.emit("tracksready",{hasQualities:this.dashEngine.getQualities().length>1,hasAudioTracks:this.dashEngine.getAudioTracks().length>1,hasSubtitleTracks:this.dashEngine.getSubtitleTracks().length>0})}catch(n){console.error("[PlayerCore] DASH load failed:",n),this.streamType="unknown",this.streamInfo=null,await this.fallbackToNative(e,"dash")}}else this.streamType="vod",this.streamInfo={type:"vod",protocol:"progressive",isDynamic:!1,hasDVR:!1,isEngineSupported:!0},this.videoEngine.setSource(e);if(this.events.emit("streamTypeDetected",{type:this.streamType,info:this.streamInfo}),window.dispatchEvent(new CustomEvent("virtus:streamTypeDetected",{detail:{type:this.streamType,info:this.streamInfo}})),this.castManager?.isCastActive()){const r=this.streamInfo?.isDynamic??!1,n=t.protocol==="hls"?"application/x-mpegURL":t.protocol==="dash"?"application/dash+xml":"video/mp4";this.castManager.loadMedia(e,n,0,r)}this.startStallDetector()}async destroyStreamingEngines(){this.stopLiveLatencyTracking(),this.hlsEngine&&(await this.hlsEngine.destroy(),this.hlsEngine=null),this.dashEngine&&(await this.dashEngine.destroy(),this.dashEngine=null),this.drmManager&&(this.drmManager.destroy(),this.drmManager=null)}async fallbackToNative(e,t){if(!(!this.videoElement||!this.videoEngine))try{console.log(`[PlayerCore] Attempting native fallback for ${t} stream`),this.videoEngine.setSource(e),this.streamType="vod",this.streamInfo={type:"vod",protocol:"progressive",isDynamic:!1,hasDVR:!1,isEngineSupported:!1}}catch(r){console.error("[PlayerCore] Native fallback failed:",r),this.events.emit("error",{code:"MEDIA_ERR_SRC_NOT_SUPPORTED",message:"Could not play stream natively or via fallback",details:r})}}getStreamType(){return this.streamType}getStreamInfo(){return this.streamInfo}isLive(){return this.streamType==="live"}getLiveEdgeTime(){return this.hlsEngine?.getLiveEdgeTime()??this.dashEngine?.getLiveEdgeTime()??0}getCurrentLatency(){if(!this.isLive())return 0;const e=this.getLiveEdgeTime();return e===0?0:Math.max(0,e-(this.videoElement?.currentTime??0))}isAtLiveEdge(e){return this.isLive()?this.getCurrentLatency()<=(e??this.atLiveEdgeTolerance):!1}seekToLiveEdge(){this.isLive()&&(this.hlsEngine?.seekToLiveEdge(),this.dashEngine?.seekToLiveEdge())}getDVRRange(){return this.hlsEngine?.getDVRRange()??this.dashEngine?.getDVRRange()??null}startLiveLatencyTracking(e){this.stopLiveLatencyTracking(),this.atLiveEdgeTolerance=e,this.liveLatencyTimer=setInterval(()=>{if(!this.isLive())return;const t=this.getCurrentLatency(),r=this.getLiveEdgeTime(),n=t<=this.atLiveEdgeTolerance;this.events.emit("livelatencyupdate",{latency:t,isAtLiveEdge:n,liveEdgeTime:r})},1e3)}stopLiveLatencyTracking(){this.liveLatencyTimer!==null&&(clearInterval(this.liveLatencyTimer),this.liveLatencyTimer=null)}startStallDetector(){this.stallDetector?.destroy(),this.stallDetector=new Ze(this.videoElement,this.events,{pollInterval:500,stallThreshold:3,onQualityDowngrade:()=>{const e=this.getAvailableQualities().filter(t=>t.id!=="auto");if(e.length>1){const t=this.getQuality();if(t&&t.id!=="auto"){const r=e.findIndex(n=>n.id===t.id);r>0&&this.setQuality(e[r-1].id)}}}}),this.stallDetector.start()}setPoster(e){this.videoEngine&&this.videoEngine.setPoster(e)}setDimensions(e,t){this.videoEngine&&this.videoEngine.setDimensions(e,t)}getState(){return this.stateManager?this.stateManager.getState():null}getVideoEngine(){return this.videoEngine}getConfigManager(){return this.configManager}getStateManager(){return this.stateManager}getVideoElement(){return this.videoElement}toggleFullscreen(){this.container&&(document.fullscreenElement?document.exitFullscreen?.():this.container.requestFullscreen?.())}async togglePip(){if(this.videoElement)try{document.pictureInPictureElement?await document.exitPictureInPicture():await this.videoElement.requestPictureInPicture()}catch(e){console.error("PiP error:",e)}}skipBackward(e=15){if(!this.videoElement)return;const t=Math.max(0,this.videoElement.currentTime-e);this.seekTo(t)}skipForward(e=15){if(!this.videoElement)return;const t=Math.min(this.videoElement.duration||0,this.videoElement.currentTime+e);this.seekTo(t)}setLoop(e){this.videoElement&&(this.videoElement.loop=e)}getLoop(){return this.videoElement?.loop||!1}setQuality(e){this.hlsEngine?e==="auto"?this.hlsEngine.enableAutoQuality():this.hlsEngine.setQuality(e):this.dashEngine&&this.dashEngine.setQuality(e)}getQuality(){return this.hlsEngine?.getCurrentQuality()??this.dashEngine?.getCurrentQuality()??null}getAvailableQualities(){return this.hlsEngine?.getQualities()??this.dashEngine?.getQualities()??[]}setAudioTrack(e){this.hlsEngine?.setAudioTrack(e),this.dashEngine?.setAudioTrack(e)}getAudioTrack(){return this.hlsEngine?.getActiveAudioTrackId()??this.dashEngine?.getActiveAudioTrackId()??""}getAvailableAudioTracks(){return this.hlsEngine?.getAudioTracks()??this.dashEngine?.getAudioTracks()??[]}getSubtitleTracks(){return this.hlsEngine?.getSubtitleTracks()??this.dashEngine?.getSubtitleTracks()??[]}async setSubtitleTrack(e){await this.hlsEngine?.setSubtitleTrack(e),await this.dashEngine?.setSubtitleTrack(e)}getActiveSubtitleLanguage(){return this.hlsEngine?.getActiveSubtitleLanguage()??this.dashEngine?.getActiveSubtitleLanguage()??null}setupAirPlay(){!this.videoElement||typeof this.videoElement.webkitShowPlaybackTargetPicker!="function"||(this.onAirPlayAvailabilityChanged=t=>{const r=t;this.airPlayAvailable=r.availability==="available",this.events.emit("airplaychange",{isAvailable:this.airPlayAvailable,isActive:this.airPlayActive})},this.onAirPlayTargetChanged=()=>{this.airPlayActive=!!this.videoElement.webkitCurrentPlaybackTargetIsWireless,this.events.emit("airplaychange",{isAvailable:this.airPlayAvailable,isActive:this.airPlayActive})},this.videoElement.addEventListener("webkitplaybacktargetavailabilitychanged",this.onAirPlayAvailabilityChanged),this.videoElement.addEventListener("webkitcurrentplaybacktargetiswirelesschanged",this.onAirPlayTargetChanged))}showAirPlayPicker(){if(!this.videoElement)return;const e=this.videoElement;typeof e.webkitShowPlaybackTargetPicker=="function"?e.webkitShowPlaybackTargetPicker():console.warn("[PlayerCore] AirPlay not supported in this browser")}isAirPlayAvailable(){return this.airPlayAvailable}isAirPlayActive(){return this.airPlayActive}destroyAirPlay(){this.videoElement&&(this.onAirPlayAvailabilityChanged&&(this.videoElement.removeEventListener("webkitplaybacktargetavailabilitychanged",this.onAirPlayAvailabilityChanged),this.onAirPlayAvailabilityChanged=null),this.onAirPlayTargetChanged&&(this.videoElement.removeEventListener("webkitcurrentplaybacktargetiswirelesschanged",this.onAirPlayTargetChanged),this.onAirPlayTargetChanged=null))}setupChromecast(e){this.castManager||(this.castManager=new rt({appId:e,onChange:t=>{this.events.emit("castchange",t)}}),this.castManager.setup(),console.log("[PlayerCore] Chromecast setup complete"))}async showCastPicker(){if(!this.castManager){console.warn("[PlayerCore] Chromecast not initialised — call setupChromecast() first");return}await this.castManager.requestSession()}stopCasting(){this.castManager?.endSession(!0)}isCastAvailable(){return this.castManager?.isCastAvailable()??!1}isCastActive(){return this.castManager?.isCastActive()??!1}destroyChromecast(){this.castManager?.destroy(),this.castManager=null}toggleTheaterMode(){if(this.container){const e=this.container,t=e.isTheaterMode||!1;e.isTheaterMode=!t,window.dispatchEvent(new CustomEvent("virtus:theatermodechange",{detail:{isTheaterMode:!t},bubbles:!0}))}}isTheaterMode(){return this.container?.isTheaterMode||!1}destroy(){this.stallDetector?.destroy(),this.stallDetector=null,this.destroyAirPlay(),this.destroyChromecast(),this.destroyStreamingEngines(),this.videoEngine&&(this.videoEngine.destroy(),this.videoEngine=null),this.stateManager&&(this.stateManager.reset(),this.stateManager=null),this.configManager&&(this.configManager.reset(),this.configManager=null),this.videoElement=null,this.container=null}}const it=c.createContext(null),nt={isPlaying:!1,isMuted:!1,volume:1,currentTime:0,duration:0,isLive:!1,isAtLiveEdge:!1,liveLatency:0},st=c.createContext(nt),ot=c.createContext(null);function at({children:a,playerInstance:e}){const[t,r]=c.useState(nt);c.useEffect(()=>{if(!e)return;const s=e.getStateManager();if(!s)return;r(s.getState());const o=d=>{r(d)};s.subscribe(o);const l=e.getVideoElement();if(l){const d=()=>{const g=e.isLive();s.updateState({currentTime:l.currentTime,duration:l.duration||0,isLive:g})},u=()=>{s.set("isPlaying",!l.paused)},h=()=>{s.updateState({volume:l.volume,isMuted:l.muted})},p=({latency:g,isAtLiveEdge:m})=>{s.updateState({liveLatency:g,isAtLiveEdge:m,isLive:!0})};return e.events.on("livelatencyupdate",p),l.addEventListener(k.TIME_UPDATE,d),l.addEventListener(k.PLAY,u),l.addEventListener(k.PAUSE,u),l.addEventListener(k.VOLUME_CHANGE,h),l.addEventListener(k.LOADED_METADATA,d),()=>{e.events.off("livelatencyupdate",p),l.removeEventListener(k.TIME_UPDATE,d),l.removeEventListener(k.PLAY,u),l.removeEventListener(k.PAUSE,u),l.removeEventListener(k.VOLUME_CHANGE,h),l.removeEventListener(k.LOADED_METADATA,d),s.unsubscribe(o)}}return()=>{s.unsubscribe(o)}},[e]);const n=c.useMemo(()=>e?{play:async()=>{await e.play()},pause:()=>{e.pause()},togglePlay:async()=>{e.getState()?.isPlaying?e.pause():await e.play()},toggleMute:()=>{e.toggleMute()},setVolume:s=>{e.setVolume(s)},seekTo:s=>{e.seekTo(s)},setPlaybackRate:s=>{e.setPlaybackRate(s)},toggleFullscreen:()=>{e.toggleFullscreen()},togglePip:async()=>{await e.togglePip()},skipBackward:(s=15)=>{e.skipBackward(s)},skipForward:(s=15)=>{e.skipForward(s)},setLoop:s=>{e.setLoop(s)},getLoop:()=>e.getLoop(),setQuality:s=>{e.setQuality(s)},getQuality:()=>e.getQuality(),getAvailableQualities:()=>e.getAvailableQualities(),setAudioTrack:s=>{e.setAudioTrack(s)},getAudioTrack:()=>e.getAudioTrack(),getAvailableAudioTracks:()=>e.getAvailableAudioTracks(),toggleTheaterMode:()=>{e.toggleTheaterMode()},isTheaterMode:()=>e.isTheaterMode(),getPlayer:()=>e,getStreamType:()=>e.getStreamType(),getStreamInfo:()=>e.getStreamInfo(),isLive:()=>e.isLive(),getBufferedRanges:()=>e.getBufferedRanges(),seekToLiveEdge:()=>{e.seekToLiveEdge()},getCurrentLatency:()=>e.getCurrentLatency(),isAtLiveEdge:s=>e.isAtLiveEdge(s),getDVRRange:()=>e.getDVRRange(),getSubtitleTracks:()=>e.getSubtitleTracks(),setSubtitleTrack:async s=>{await e.setSubtitleTrack(s)},getActiveSubtitleLanguage:()=>e.getActiveSubtitleLanguage(),getPlayerStats:()=>e.getPlayerStats()}:null,[e]);return i.jsx(it.Provider,{value:e,children:i.jsx(ot.Provider,{value:n,children:i.jsx(st.Provider,{value:t,children:a})})})}function O(a){const e=c.useContext(st);if(!e)throw new Error("usePlayerState must be used within PlayerProvider");return a?a(e):e}function U(){const a=c.useContext(ot);if(!a)throw new Error("usePlayerMethods must be used within PlayerProvider");return a}function Ue({size:a=40}){return i.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"none",stroke:"#fff",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{width:`${a}px`,height:`${a}px`,animation:"spin 1s linear infinite"},children:[i.jsx("path",{d:"M12 2v4M12 18v4M4.93 4.93l2.83 2.83M16.24 16.24l2.83 2.83M2 12h4M18 12h4M4.93 19.07l2.83-2.83M16.24 7.76l2.83-2.83"}),i.jsx("style",{children:`
|
|
2
2
|
@keyframes spin {
|
|
3
3
|
0% { transform: rotate(0deg); }
|
|
4
4
|
100% { transform: rotate(360deg); }
|
|
5
5
|
}
|
|
6
|
-
`})]})}function ar({children:a,zIndex:e=2e3,backgroundColor:t="rgba(0, 0, 0, 0.8)",onClick:r,style:n}){return i.jsx("div",{onClick:r,style:{position:"absolute",top:0,left:0,right:0,bottom:0,zIndex:e,backgroundColor:t,display:"flex",alignItems:"center",justifyContent:"center",pointerEvents:"all",...n},children:a})}const lr="_overlay_3mfq6_3",cr="_iconContainer_3mfq6_17",dr="_loading_3mfq6_30",ur="_icon_3mfq6_17",hr="_customIcon_3mfq6_46",J={overlay:lr,iconContainer:cr,loading:dr,icon:ur,customIcon:hr};function pr({config:a,isAdLoading:e}){const t=O(D=>D.isPlaying),{togglePlay:r,toggleFullscreen:n,getPlayer:s}=U(),[o,l]=c.useState(!1),[u,d]=c.useState("play"),[h,p]=c.useState(!1),g=c.useRef(null);c.useEffect(()=>{console.log("[VideoOverlay] isAdLoading changed:",e),e?(console.log("[VideoOverlay] ✅ Showing ad loading icon"),p(!0),d("loading"),l(!0)):(console.log("[VideoOverlay] ❌ Hiding ad loading icon"),p(!1),l(!1))},[e]);const m=a?.ui?.showOverlayIcons!==!1,w=a?.ui?.overlayIcons?.playIcon,L=a?.ui?.overlayIcons?.pauseIcon,b=a?.ui?.overlayIcons?.iconSize||40,M=a?.ui?.overlayIcons?.containerSize||80;c.useEffect(()=>{const D=s();if(!D)return;const S=D.video||D.videoElement;if(!S)return;const I=()=>{p(!0),d("loading"),l(!0),g.current&&clearTimeout(g.current)},j=()=>{g.current=window.setTimeout(()=>{p(!1),l(!1)},300)},$=()=>{p(!0),d("loading"),l(!0)},x=()=>{h&&(g.current=window.setTimeout(()=>{p(!1),l(!1)},300))},A=()=>{h&&(g.current=window.setTimeout(()=>{p(!1),l(!1)},300))},_=()=>{p(!0),d("loading"),l(!0)};return S.addEventListener(k.SEEKING,I),S.addEventListener(k.SEEKED,j),S.addEventListener(k.WAITING,$),S.addEventListener(k.PLAYING,x),S.addEventListener(k.CAN_PLAY,A),S.addEventListener(k.LOAD_START,_),()=>{S.removeEventListener(k.SEEKING,I),S.removeEventListener(k.SEEKED,j),S.removeEventListener(k.WAITING,$),S.removeEventListener(k.PLAYING,x),S.removeEventListener(k.CAN_PLAY,A),S.removeEventListener(k.LOAD_START,_),g.current&&clearTimeout(g.current)}},[s,h]),c.useEffect(()=>{if(!h){d(t?"pause":"play"),l(!0);const D=setTimeout(()=>{l(!1)},600);return()=>clearTimeout(D)}},[t,h]);const E=c.useCallback(async()=>{await r()},[r]),y=c.useCallback(()=>{n()},[n]),q=D=>{const S=D==="play"?w:L;return S?/^https?:\/\//.test(S)||/\.(jpg|jpeg|png|svg|gif|webp)$/i.test(S)?i.jsx("img",{src:S,alt:D==="play"?"Play":"Pause",className:J.customIcon,style:{"--icon-size":`${b}px`}}):i.jsx("div",{dangerouslySetInnerHTML:{__html:S},className:J.customIcon,style:{"--icon-size":`${b}px`}}):D==="play"?i.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",className:J.icon,style:{"--icon-size":`${b}px`},viewBox:"0 0 24 24",children:i.jsx("path",{fillRule:"evenodd",d:"M8.6 5.2A1 1 0 0 0 7 6v12a1 1 0 0 0 1.6.8l8-6a1 1 0 0 0 0-1.6l-8-6Z",clipRule:"evenodd"})}):i.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",className:J.icon,style:{"--icon-size":`${b}px`},viewBox:"0 0 24 24",children:i.jsx("path",{fillRule:"evenodd",d:"M8 5a2 2 0 0 0-2 2v10a2 2 0 0 0 2 2h1a2 2 0 0 0 2-2V7a2 2 0 0 0-2-2H8Zm7 0a2 2 0 0 0-2 2v10a2 2 0 0 0 2 2h1a2 2 0 0 0 2-2V7a2 2 0 0 0-2-2h-1Z",clipRule:"evenodd"})})};return i.jsxs(i.Fragment,{children:[e&&m&&i.jsx(ar,{children:i.jsx("div",{className:`${J.iconContainer} ${J.loading}`,style:{"--icon-container-size":`${M}px`,"--icon-size":`${b}px`},children:i.jsx(Ue,{size:b})})}),i.jsx("div",{className:`virtus-video-overlay ${J.overlay}`,onClick:E,onDoubleClick:y,children:m&&o&&!e&&i.jsx("div",{className:`${J.iconContainer} ${h?J.loading:""}`,style:{"--icon-container-size":`${M}px`,"--icon-size":`${b}px`},children:u==="loading"?i.jsx(Ue,{size:b}):q(u)})})]})}const gr=c.memo(pr);function pe(){const a=c.useContext(it);if(!a)throw new Error("usePlayer must be used within PlayerProvider");return a}const fr="_errorOverlay_4djr8_5",mr="_variant_drm_4djr8_19",yr="_variant_network_4djr8_23",vr="_variant_decode_4djr8_27",xr="_variant_generic_4djr8_31",br="_errorContent_4djr8_37",Er="_errorIcon_4djr8_51",wr="_iconPulse_4djr8_1",kr="_drmGlow_4djr8_1",Sr="_netGlow_4djr8_1",Ar="_errorTitle_4djr8_86",Cr="_errorMessage_4djr8_100",Tr="_errorHint_4djr8_109",Mr="_browserList_4djr8_117",Pr="_browserItem_4djr8_126",Lr="_errorCode_4djr8_142",jr="_retryButton_4djr8_152",Q={errorOverlay:fr,variant_drm:mr,variant_network:yr,variant_decode:vr,variant_generic:xr,errorContent:br,errorIcon:Er,iconPulse:wr,drmGlow:kr,netGlow:Sr,errorTitle:Ar,errorMessage:Cr,errorHint:Tr,browserList:Mr,browserItem:Pr,errorCode:Lr,retryButton:jr};function Rr(a,e){const t=a.code.toUpperCase(),r=(a.message??"").toUpperCase();if(t.startsWith("DRM_")||t.includes("LICENSE")||t.includes("ENCRYPTED")||t.includes("KEY_SYSTEM")||t.includes("KEYSYSTEM")||r.includes("DRM")||r.includes("LICENSE")||r.includes("ENCRYPTED")){if(e){if(e.fairplay&&!e.widevine&&!e.playready)return"drm_fairplay_needed";if(!e.widevine&&!e.fairplay&&!e.playready)return"drm_browser_unsupported"}return t.includes("LICENSE")||t==="DRM_LICENSE_FAILED"||t==="LICENSE_REQUEST_FAILED"?"drm_license_failed":"drm_generic"}return t.includes("MEDIA_ERR_NETWORK")||t.includes("NETWORK")||t.includes("FETCH")?"network":t.includes("MEDIA_ERR_DECODE")||t.includes("DECODE")||t.includes("CODEC")||t.includes("MEDIA_ERR_SRC_NOT_SUPPORTED")?"decode":"generic"}function Oe(a,e){if(!a?.enabled)return null;const t=!!a.widevine,r=!!a.playready,n=!!a.fairplay;return t&&!e.widevine||r&&!e.playready&&!t?e.fairplay?"drm_fairplay_needed":"drm_browser_unsupported":n&&!e.fairplay&&!t?"drm_browser_unsupported":null}function Dr(a){switch(a){case"drm_fairplay_needed":return{icon:"🔒",title:"DRM Protected Content",message:"This content is protected with Widevine DRM. Your browser (Safari) does not support this DRM system.",hint:"Please use one of the following browsers:",browsers:["Google Chrome","Mozilla Firefox","Microsoft Edge"],showRetry:!1,variant:"drm"};case"drm_browser_unsupported":return{icon:"🔒",title:"DRM Not Supported",message:"Your browser does not support the DRM system required to play this protected content.",hint:"Please try one of the following browsers:",browsers:["Google Chrome","Mozilla Firefox","Microsoft Edge"],showRetry:!1,variant:"drm"};case"drm_license_failed":return{icon:"🔐",title:"License Verification Failed",message:"A license could not be obtained for this content. Please check your connection and try again.",showRetry:!0,variant:"drm"};case"drm_generic":return{icon:"🔒",title:"Content Protection Error",message:"A DRM error occurred while trying to play this content. Please try again.",showRetry:!0,variant:"drm"};case"network":return{icon:"📡",title:"Connection Error",message:"A network error occurred while loading the video. Please check your internet connection and try again.",showRetry:!0,variant:"network"};case"decode":return{icon:"⚙️",title:"Format Not Supported",message:"This video format or codec is not supported by your browser.",showRetry:!1,variant:"decode"};default:return{icon:"⚠️",title:"Playback Error",message:"An error occurred while playing the video. Please try again.",showRetry:!0,variant:"generic"}}}const Ir=12e3;function _r({onRetry:a,drmConfig:e}){const t=pe(),[r,n]=c.useState(null),[s,o]=c.useState(null),l=c.useRef(null),u=c.useRef(null);u.current=r,c.useEffect(()=>{et().then(g=>{o(g);const m=Oe(e,g);m&&n({type:m,code:"DRM_NOT_SUPPORTED",rawMessage:"Browser does not support the required DRM key system.",persistent:!0})}).catch(()=>o(null))},[]),c.useEffect(()=>{if(!s||!e?.enabled)return;const g=Oe(e,s);g&&!u.current&&n({type:g,code:"DRM_NOT_SUPPORTED",rawMessage:"Browser does not support the required DRM key system.",persistent:!0})},[e,s]),c.useEffect(()=>{if(!t||!e?.enabled)return;const g=t.getVideoElement();if(!g)return;const m=()=>{g.currentTime>.5||(l.current=setTimeout(()=>{if(u.current)return;const L=s,b=L?L.fairplay&&!L.widevine&&!L.playready?"drm_fairplay_needed":!L.widevine&&!L.fairplay&&!L.playready?"drm_browser_unsupported":"drm_generic":"drm_generic";n({type:b,code:"DRM_TIMEOUT",rawMessage:"Playback stalled — possible DRM or network issue.",persistent:!0})},Ir))},w=()=>{l.current&&(clearTimeout(l.current),l.current=null)};return g.addEventListener("waiting",m),g.addEventListener("playing",w),g.addEventListener("timeupdate",w),()=>{g.removeEventListener("waiting",m),g.removeEventListener("playing",w),g.removeEventListener("timeupdate",w),w()}},[t,e,s]),c.useEffect(()=>{if(!t)return;const g=m=>{console.error("[ErrorOverlay] Player error:",m);const w=Rr(m,s);n({type:w,code:m.code,rawMessage:m.message??"Unknown error"})};return t.events.on("error",g),()=>{t.events.off("error",g)}},[t,s]),c.useEffect(()=>{if(!t)return;const g=()=>n(m=>m?.persistent?m:null);return t.events.on("play",g),t.events.on("loadedmetadata",g),()=>{t.events.off("play",g),t.events.off("loadedmetadata",g)}},[t]);const d=c.useCallback(()=>{if(n(null),a){a();return}if(t){const g=t.getVideoElement();if(g?.src){const m=g.src;g.src="",g.load(),setTimeout(()=>{g&&(g.src=m,g.load())},100)}}},[t,a]);if(!r)return null;const h=Dr(r.type),p=Q[`variant_${h.variant}`]??"";return i.jsx("div",{className:`${Q.errorOverlay} ${p}`,children:i.jsxs("div",{className:Q.errorContent,children:[i.jsx("div",{className:Q.errorIcon,children:h.icon}),i.jsx("h3",{className:Q.errorTitle,children:h.title}),i.jsx("p",{className:Q.errorMessage,children:h.message}),h.hint&&i.jsx("p",{className:Q.errorHint,children:h.hint}),h.browsers&&i.jsx("ul",{className:Q.browserList,children:h.browsers.map(g=>i.jsx("li",{className:Q.browserItem,children:g},g))}),r.code&&h.variant!=="drm"&&i.jsx("p",{className:Q.errorCode,children:r.code}),h.showRetry&&i.jsx("button",{onClick:d,className:Q.retryButton,children:"↻ Try Again"})]})})}const ee={play:i.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:[i.jsx("polygon",{points:"5 3 19 12 5 21 5 3"}),i.jsx("line",{x1:"19",y1:"3",x2:"19",y2:"21"}),i.jsx("line",{x1:"5",y1:"3",x2:"5",y2:"21"})]}),rewind:i.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:[i.jsx("polygon",{points:"19 20 9 12 19 4 19 20"}),i.jsx("line",{x1:"5",y1:"19",x2:"5",y2:"5"})]}),forward:i.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:[i.jsx("polygon",{points:"5 4 15 12 5 20 5 4"}),i.jsx("line",{x1:"19",y1:"5",x2:"19",y2:"19"})]}),volUp:i.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:[i.jsx("polygon",{points:"11 5 6 9 2 9 2 15 6 15 11 19 11 5"}),i.jsx("path",{d:"M15.54 8.46a5 5 0 0 1 0 7.07"}),i.jsx("path",{d:"M19.07 4.93a10 10 0 0 1 0 14.14"})]}),volDown:i.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:[i.jsx("polygon",{points:"11 5 6 9 2 9 2 15 6 15 11 19 11 5"}),i.jsx("line",{x1:"23",y1:"9",x2:"17",y2:"15"}),i.jsx("line",{x1:"17",y1:"9",x2:"23",y2:"15"})]}),mute:i.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:[i.jsx("polygon",{points:"11 5 6 9 2 9 2 15 6 15 11 19 11 5"}),i.jsx("line",{x1:"23",y1:"9",x2:"17",y2:"15"}),i.jsx("line",{x1:"17",y1:"9",x2:"23",y2:"15"})]}),fullscreen:i.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:i.jsx("path",{d:"M8 3H5a2 2 0 0 0-2 2v3m18 0V5a2 2 0 0 0-2-2h-3m0 18h3a2 2 0 0 0 2-2v-3M3 16v3a2 2 0 0 0 2 2h3"})}),shortcuts:i.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:[i.jsx("rect",{x:"2",y:"4",width:"20",height:"16",rx:"2"}),i.jsx("path",{d:"M6 8h.01M10 8h.01M14 8h.01M18 8h.01M8 12h.01M12 12h.01M16 12h.01M7 16h10"})]}),close:i.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:[i.jsx("circle",{cx:"12",cy:"12",r:"10"}),i.jsx("line",{x1:"15",y1:"9",x2:"9",y2:"15"}),i.jsx("line",{x1:"9",y1:"9",x2:"15",y2:"15"})]})},Vr=[{key:"Space / K",description:"Play / Pause",icon:ee.play},{key:"←",description:"Rewind 10 seconds",icon:ee.rewind},{key:"→",description:"Forward 10 seconds",icon:ee.forward},{key:"↑",description:"Volume up 10%",icon:ee.volUp},{key:"↓",description:"Volume down 10%",icon:ee.volDown},{key:"M",description:"Mute / Unmute",icon:ee.mute},{key:"F",description:"Toggle fullscreen",icon:ee.fullscreen},{key:"?",description:"Show keyboard shortcuts",icon:ee.shortcuts},{key:"Esc",description:"Close overlays",icon:ee.close}];function lt({isOpen:a,onClose:e}){const t=c.useCallback(r=>{r.key==="Escape"&&e()},[e]);return c.useEffect(()=>{if(a)return document.addEventListener("keydown",t),()=>document.removeEventListener("keydown",t)},[a,t]),a?i.jsxs("div",{role:"dialog","aria-modal":"true","aria-label":"Keyboard shortcuts",onClick:e,style:{position:"absolute",inset:0,zIndex:99999,display:"flex",alignItems:"center",justifyContent:"center",background:"rgba(0,0,0,0.55)",backdropFilter:"blur(6px)"},children:[i.jsxs("div",{onClick:r=>r.stopPropagation(),style:{background:"rgba(12, 12, 20, 0.97)",border:"1px solid rgba(255,255,255,0.1)",borderRadius:"14px",boxShadow:"0 12px 48px rgba(0,0,0,0.7), 0 0 0 1px rgba(255,255,255,0.08)",width:"320px",fontFamily:"system-ui, -apple-system, sans-serif",animation:"kbdFadeIn 0.18s ease-out",overflow:"hidden",backdropFilter:"blur(16px)"},children:[i.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",padding:"11px 14px",borderBottom:"1px solid rgba(255,255,255,0.08)"},children:[i.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px",color:"#fff",fontSize:"13px",fontWeight:600},children:[i.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"rgba(255,255,255,0.6)",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:[i.jsx("rect",{x:"2",y:"4",width:"20",height:"16",rx:"2"}),i.jsx("path",{d:"M6 8h.01M10 8h.01M14 8h.01M18 8h.01M8 12h.01M12 12h.01M16 12h.01M7 16h10"})]}),"Keyboard Shortcuts"]}),i.jsx("button",{"aria-label":"Close",onClick:e,style:{background:"rgba(255,255,255,0.08)",border:"none",borderRadius:"6px",color:"rgba(255,255,255,0.6)",cursor:"pointer",width:"26px",height:"26px",display:"flex",alignItems:"center",justifyContent:"center",transition:"background 0.15s"},onMouseEnter:r=>r.currentTarget.style.background="rgba(255,255,255,0.15)",onMouseLeave:r=>r.currentTarget.style.background="rgba(255,255,255,0.08)",children:i.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",children:[i.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),i.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})]}),i.jsx("div",{style:{padding:"4px 0"},children:Vr.map(({key:r,description:n,icon:s})=>i.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",padding:"9px 14px",gap:"10px",transition:"background 0.12s"},onMouseEnter:o=>o.currentTarget.style.background="rgba(255,255,255,0.05)",onMouseLeave:o=>o.currentTarget.style.background="transparent",children:[i.jsxs("span",{style:{display:"flex",alignItems:"center",gap:"10px"},children:[i.jsx("span",{style:{width:"28px",height:"28px",borderRadius:"7px",background:"rgba(255,255,255,0.08)",display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0,color:"rgba(255,255,255,0.65)"},children:s}),i.jsx("span",{style:{color:"rgba(255,255,255,0.7)",fontSize:"13.5px"},children:n})]}),i.jsx("kbd",{style:{background:"rgba(255,255,255,0.08)",border:"1px solid rgba(255,255,255,0.15)",borderRadius:"6px",color:"rgba(255,255,255,0.75)",fontFamily:"ui-monospace, SF Mono, monospace",fontSize:"11.5px",fontWeight:600,padding:"3px 9px",whiteSpace:"nowrap",flexShrink:0},children:r})]},r))}),i.jsxs("div",{style:{padding:"10px 14px",borderTop:"1px solid rgba(255,255,255,0.07)",fontSize:"11px",color:"rgba(255,255,255,0.28)",textAlign:"center"},children:["Press"," ",i.jsx("kbd",{style:{background:"rgba(255,255,255,0.08)",border:"1px solid rgba(255,255,255,0.15)",borderRadius:"4px",padding:"1px 5px",fontSize:"10.5px",color:"rgba(255,255,255,0.4)",fontFamily:"monospace"},children:"?"})," ","or"," ",i.jsx("kbd",{style:{background:"rgba(255,255,255,0.08)",border:"1px solid rgba(255,255,255,0.15)",borderRadius:"4px",padding:"1px 5px",fontSize:"10.5px",color:"rgba(255,255,255,0.4)",fontFamily:"monospace"},children:"Esc"})," ","to dismiss"]})]}),i.jsx("style",{children:`
|
|
6
|
+
`})]})}function ar({children:a,zIndex:e=2e3,backgroundColor:t="rgba(0, 0, 0, 0.8)",onClick:r,style:n}){return i.jsx("div",{onClick:r,style:{position:"absolute",top:0,left:0,right:0,bottom:0,zIndex:e,backgroundColor:t,display:"flex",alignItems:"center",justifyContent:"center",pointerEvents:"all",...n},children:a})}const lr="_overlay_3mfq6_3",cr="_iconContainer_3mfq6_17",dr="_loading_3mfq6_30",ur="_icon_3mfq6_17",hr="_customIcon_3mfq6_46",J={overlay:lr,iconContainer:cr,loading:dr,icon:ur,customIcon:hr};function pr({config:a,isAdLoading:e}){const t=O(L=>L.isPlaying),{togglePlay:r,toggleFullscreen:n,getPlayer:s}=U(),[o,l]=c.useState(!1),[d,u]=c.useState("play"),[h,p]=c.useState(!1),g=c.useRef(null);c.useEffect(()=>{console.log("[VideoOverlay] isAdLoading changed:",e),e?(console.log("[VideoOverlay] ✅ Showing ad loading icon"),p(!0),u("loading"),l(!0)):(console.log("[VideoOverlay] ❌ Hiding ad loading icon"),p(!1),l(!1))},[e]);const m=a?.ui?.showOverlayIcons!==!1,E=a?.ui?.showPlayPauseIcons!==!1,j=a?.ui?.overlayIcons?.playIcon,S=a?.ui?.overlayIcons?.pauseIcon,A=a?.ui?.overlayIcons?.iconSize||40,b=a?.ui?.overlayIcons?.containerSize||80;c.useEffect(()=>{const L=s();if(!L)return;const w=L.video||L.videoElement;if(!w)return;const R=()=>{p(!0),u("loading"),l(!0),g.current&&clearTimeout(g.current)},N=()=>{g.current=window.setTimeout(()=>{p(!1),l(!1)},300)},x=()=>{p(!0),u("loading"),l(!0)},C=()=>{h&&(g.current=window.setTimeout(()=>{p(!1),l(!1)},300))},I=()=>{h&&(g.current=window.setTimeout(()=>{p(!1),l(!1)},300))},$=()=>{p(!0),u("loading"),l(!0)};return w.addEventListener(k.SEEKING,R),w.addEventListener(k.SEEKED,N),w.addEventListener(k.WAITING,x),w.addEventListener(k.PLAYING,C),w.addEventListener(k.CAN_PLAY,I),w.addEventListener(k.LOAD_START,$),()=>{w.removeEventListener(k.SEEKING,R),w.removeEventListener(k.SEEKED,N),w.removeEventListener(k.WAITING,x),w.removeEventListener(k.PLAYING,C),w.removeEventListener(k.CAN_PLAY,I),w.removeEventListener(k.LOAD_START,$),g.current&&clearTimeout(g.current)}},[s,h]),c.useEffect(()=>{if(!h){u(t?"pause":"play"),l(!0);const L=setTimeout(()=>{l(!1)},600);return()=>clearTimeout(L)}},[t,h]);const y=c.useCallback(async()=>{await r()},[r]),q=c.useCallback(()=>{n()},[n]),z=L=>{const w=L==="play"?j:S;return w?/^https?:\/\//.test(w)||/\.(jpg|jpeg|png|svg|gif|webp)$/i.test(w)?i.jsx("img",{src:w,alt:L==="play"?"Play":"Pause",className:J.customIcon,style:{"--icon-size":`${A}px`}}):i.jsx("div",{dangerouslySetInnerHTML:{__html:w},className:J.customIcon,style:{"--icon-size":`${A}px`}}):L==="play"?i.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",className:J.icon,style:{"--icon-size":`${A}px`},viewBox:"0 0 24 24",children:i.jsx("path",{fillRule:"evenodd",d:"M8.6 5.2A1 1 0 0 0 7 6v12a1 1 0 0 0 1.6.8l8-6a1 1 0 0 0 0-1.6l-8-6Z",clipRule:"evenodd"})}):i.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",className:J.icon,style:{"--icon-size":`${A}px`},viewBox:"0 0 24 24",children:i.jsx("path",{fillRule:"evenodd",d:"M8 5a2 2 0 0 0-2 2v10a2 2 0 0 0 2 2h1a2 2 0 0 0 2-2V7a2 2 0 0 0-2-2H8Zm7 0a2 2 0 0 0-2 2v10a2 2 0 0 0 2 2h1a2 2 0 0 0 2-2V7a2 2 0 0 0-2-2h-1Z",clipRule:"evenodd"})})};return i.jsxs(i.Fragment,{children:[e&&m&&i.jsx(ar,{children:i.jsx("div",{className:`${J.iconContainer} ${J.loading}`,style:{"--icon-container-size":`${b}px`,"--icon-size":`${A}px`},children:i.jsx(Ue,{size:A})})}),i.jsx("div",{className:`virtus-video-overlay ${J.overlay}`,onClick:y,onDoubleClick:q,children:m&&o&&!e&&(d==="loading"||E)&&i.jsx("div",{className:`${J.iconContainer} ${h?J.loading:""}`,style:{"--icon-container-size":`${b}px`,"--icon-size":`${A}px`},children:d==="loading"?i.jsx(Ue,{size:A}):z(d)})})]})}const gr=c.memo(pr);function pe(){const a=c.useContext(it);if(!a)throw new Error("usePlayer must be used within PlayerProvider");return a}const fr="_errorOverlay_4djr8_5",mr="_variant_drm_4djr8_19",yr="_variant_network_4djr8_23",vr="_variant_decode_4djr8_27",xr="_variant_generic_4djr8_31",br="_errorContent_4djr8_37",Er="_errorIcon_4djr8_51",wr="_iconPulse_4djr8_1",kr="_drmGlow_4djr8_1",Sr="_netGlow_4djr8_1",Ar="_errorTitle_4djr8_86",Cr="_errorMessage_4djr8_100",Tr="_errorHint_4djr8_109",Mr="_browserList_4djr8_117",Pr="_browserItem_4djr8_126",Lr="_errorCode_4djr8_142",jr="_retryButton_4djr8_152",Q={errorOverlay:fr,variant_drm:mr,variant_network:yr,variant_decode:vr,variant_generic:xr,errorContent:br,errorIcon:Er,iconPulse:wr,drmGlow:kr,netGlow:Sr,errorTitle:Ar,errorMessage:Cr,errorHint:Tr,browserList:Mr,browserItem:Pr,errorCode:Lr,retryButton:jr};function Rr(a,e){const t=a.code.toUpperCase(),r=(a.message??"").toUpperCase();if(t.startsWith("DRM_")||t.includes("LICENSE")||t.includes("ENCRYPTED")||t.includes("KEY_SYSTEM")||t.includes("KEYSYSTEM")||r.includes("DRM")||r.includes("LICENSE")||r.includes("ENCRYPTED")){if(e){if(e.fairplay&&!e.widevine&&!e.playready)return"drm_fairplay_needed";if(!e.widevine&&!e.fairplay&&!e.playready)return"drm_browser_unsupported"}return t.includes("LICENSE")||t==="DRM_LICENSE_FAILED"||t==="LICENSE_REQUEST_FAILED"?"drm_license_failed":"drm_generic"}return t.includes("MEDIA_ERR_NETWORK")||t.includes("NETWORK")||t.includes("FETCH")?"network":t.includes("MEDIA_ERR_DECODE")||t.includes("DECODE")||t.includes("CODEC")||t.includes("MEDIA_ERR_SRC_NOT_SUPPORTED")?"decode":"generic"}function Oe(a,e){if(!a?.enabled)return null;const t=!!a.widevine,r=!!a.playready,n=!!a.fairplay;return t&&!e.widevine||r&&!e.playready&&!t?e.fairplay?"drm_fairplay_needed":"drm_browser_unsupported":n&&!e.fairplay&&!t?"drm_browser_unsupported":null}function Dr(a){switch(a){case"drm_fairplay_needed":return{icon:"🔒",title:"DRM Protected Content",message:"This content is protected with Widevine DRM. Your browser (Safari) does not support this DRM system.",hint:"Please use one of the following browsers:",browsers:["Google Chrome","Mozilla Firefox","Microsoft Edge"],showRetry:!1,variant:"drm"};case"drm_browser_unsupported":return{icon:"🔒",title:"DRM Not Supported",message:"Your browser does not support the DRM system required to play this protected content.",hint:"Please try one of the following browsers:",browsers:["Google Chrome","Mozilla Firefox","Microsoft Edge"],showRetry:!1,variant:"drm"};case"drm_license_failed":return{icon:"🔐",title:"License Verification Failed",message:"A license could not be obtained for this content. Please check your connection and try again.",showRetry:!0,variant:"drm"};case"drm_generic":return{icon:"🔒",title:"Content Protection Error",message:"A DRM error occurred while trying to play this content. Please try again.",showRetry:!0,variant:"drm"};case"network":return{icon:"📡",title:"Connection Error",message:"A network error occurred while loading the video. Please check your internet connection and try again.",showRetry:!0,variant:"network"};case"decode":return{icon:"⚙️",title:"Format Not Supported",message:"This video format or codec is not supported by your browser.",showRetry:!1,variant:"decode"};default:return{icon:"⚠️",title:"Playback Error",message:"An error occurred while playing the video. Please try again.",showRetry:!0,variant:"generic"}}}const Ir=12e3;function _r({onRetry:a,drmConfig:e}){const t=pe(),[r,n]=c.useState(null),[s,o]=c.useState(null),l=c.useRef(null),d=c.useRef(null);d.current=r,c.useEffect(()=>{et().then(g=>{o(g);const m=Oe(e,g);m&&n({type:m,code:"DRM_NOT_SUPPORTED",rawMessage:"Browser does not support the required DRM key system.",persistent:!0})}).catch(()=>o(null))},[]),c.useEffect(()=>{if(!s||!e?.enabled)return;const g=Oe(e,s);g&&!d.current&&n({type:g,code:"DRM_NOT_SUPPORTED",rawMessage:"Browser does not support the required DRM key system.",persistent:!0})},[e,s]),c.useEffect(()=>{if(!t||!e?.enabled)return;const g=t.getVideoElement();if(!g)return;const m=()=>{g.currentTime>.5||(l.current=setTimeout(()=>{if(d.current)return;const j=s,S=j?j.fairplay&&!j.widevine&&!j.playready?"drm_fairplay_needed":!j.widevine&&!j.fairplay&&!j.playready?"drm_browser_unsupported":"drm_generic":"drm_generic";n({type:S,code:"DRM_TIMEOUT",rawMessage:"Playback stalled — possible DRM or network issue.",persistent:!0})},Ir))},E=()=>{l.current&&(clearTimeout(l.current),l.current=null)};return g.addEventListener("waiting",m),g.addEventListener("playing",E),g.addEventListener("timeupdate",E),()=>{g.removeEventListener("waiting",m),g.removeEventListener("playing",E),g.removeEventListener("timeupdate",E),E()}},[t,e,s]),c.useEffect(()=>{if(!t)return;const g=m=>{console.error("[ErrorOverlay] Player error:",m);const E=Rr(m,s);n({type:E,code:m.code,rawMessage:m.message??"Unknown error"})};return t.events.on("error",g),()=>{t.events.off("error",g)}},[t,s]),c.useEffect(()=>{if(!t)return;const g=()=>n(m=>m?.persistent?m:null);return t.events.on("play",g),t.events.on("loadedmetadata",g),()=>{t.events.off("play",g),t.events.off("loadedmetadata",g)}},[t]);const u=c.useCallback(()=>{if(n(null),a){a();return}if(t){const g=t.getVideoElement();if(g?.src){const m=g.src;g.src="",g.load(),setTimeout(()=>{g&&(g.src=m,g.load())},100)}}},[t,a]);if(!r)return null;const h=Dr(r.type),p=Q[`variant_${h.variant}`]??"";return i.jsx("div",{className:`${Q.errorOverlay} ${p}`,children:i.jsxs("div",{className:Q.errorContent,children:[i.jsx("div",{className:Q.errorIcon,children:h.icon}),i.jsx("h3",{className:Q.errorTitle,children:h.title}),i.jsx("p",{className:Q.errorMessage,children:h.message}),h.hint&&i.jsx("p",{className:Q.errorHint,children:h.hint}),h.browsers&&i.jsx("ul",{className:Q.browserList,children:h.browsers.map(g=>i.jsx("li",{className:Q.browserItem,children:g},g))}),r.code&&h.variant!=="drm"&&i.jsx("p",{className:Q.errorCode,children:r.code}),h.showRetry&&i.jsx("button",{onClick:u,className:Q.retryButton,children:"↻ Try Again"})]})})}const ee={play:i.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:[i.jsx("polygon",{points:"5 3 19 12 5 21 5 3"}),i.jsx("line",{x1:"19",y1:"3",x2:"19",y2:"21"}),i.jsx("line",{x1:"5",y1:"3",x2:"5",y2:"21"})]}),rewind:i.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:[i.jsx("polygon",{points:"19 20 9 12 19 4 19 20"}),i.jsx("line",{x1:"5",y1:"19",x2:"5",y2:"5"})]}),forward:i.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:[i.jsx("polygon",{points:"5 4 15 12 5 20 5 4"}),i.jsx("line",{x1:"19",y1:"5",x2:"19",y2:"19"})]}),volUp:i.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:[i.jsx("polygon",{points:"11 5 6 9 2 9 2 15 6 15 11 19 11 5"}),i.jsx("path",{d:"M15.54 8.46a5 5 0 0 1 0 7.07"}),i.jsx("path",{d:"M19.07 4.93a10 10 0 0 1 0 14.14"})]}),volDown:i.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:[i.jsx("polygon",{points:"11 5 6 9 2 9 2 15 6 15 11 19 11 5"}),i.jsx("line",{x1:"23",y1:"9",x2:"17",y2:"15"}),i.jsx("line",{x1:"17",y1:"9",x2:"23",y2:"15"})]}),mute:i.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:[i.jsx("polygon",{points:"11 5 6 9 2 9 2 15 6 15 11 19 11 5"}),i.jsx("line",{x1:"23",y1:"9",x2:"17",y2:"15"}),i.jsx("line",{x1:"17",y1:"9",x2:"23",y2:"15"})]}),fullscreen:i.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:i.jsx("path",{d:"M8 3H5a2 2 0 0 0-2 2v3m18 0V5a2 2 0 0 0-2-2h-3m0 18h3a2 2 0 0 0 2-2v-3M3 16v3a2 2 0 0 0 2 2h3"})}),shortcuts:i.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:[i.jsx("rect",{x:"2",y:"4",width:"20",height:"16",rx:"2"}),i.jsx("path",{d:"M6 8h.01M10 8h.01M14 8h.01M18 8h.01M8 12h.01M12 12h.01M16 12h.01M7 16h10"})]}),close:i.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:[i.jsx("circle",{cx:"12",cy:"12",r:"10"}),i.jsx("line",{x1:"15",y1:"9",x2:"9",y2:"15"}),i.jsx("line",{x1:"9",y1:"9",x2:"15",y2:"15"})]})},Vr=[{key:"Space / K",description:"Play / Pause",icon:ee.play},{key:"←",description:"Rewind 10 seconds",icon:ee.rewind},{key:"→",description:"Forward 10 seconds",icon:ee.forward},{key:"↑",description:"Volume up 10%",icon:ee.volUp},{key:"↓",description:"Volume down 10%",icon:ee.volDown},{key:"M",description:"Mute / Unmute",icon:ee.mute},{key:"F",description:"Toggle fullscreen",icon:ee.fullscreen},{key:"?",description:"Show keyboard shortcuts",icon:ee.shortcuts},{key:"Esc",description:"Close overlays",icon:ee.close}];function lt({isOpen:a,onClose:e}){const t=c.useCallback(r=>{r.key==="Escape"&&e()},[e]);return c.useEffect(()=>{if(a)return document.addEventListener("keydown",t),()=>document.removeEventListener("keydown",t)},[a,t]),a?i.jsxs("div",{role:"dialog","aria-modal":"true","aria-label":"Keyboard shortcuts",onClick:e,style:{position:"absolute",inset:0,zIndex:99999,display:"flex",alignItems:"center",justifyContent:"center",background:"rgba(0,0,0,0.55)",backdropFilter:"blur(6px)"},children:[i.jsxs("div",{onClick:r=>r.stopPropagation(),style:{background:"rgba(12, 12, 20, 0.97)",border:"1px solid rgba(255,255,255,0.1)",borderRadius:"14px",boxShadow:"0 12px 48px rgba(0,0,0,0.7), 0 0 0 1px rgba(255,255,255,0.08)",width:"320px",fontFamily:"system-ui, -apple-system, sans-serif",animation:"kbdFadeIn 0.18s ease-out",overflow:"hidden",backdropFilter:"blur(16px)"},children:[i.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",padding:"11px 14px",borderBottom:"1px solid rgba(255,255,255,0.08)"},children:[i.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px",color:"#fff",fontSize:"13px",fontWeight:600},children:[i.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"rgba(255,255,255,0.6)",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:[i.jsx("rect",{x:"2",y:"4",width:"20",height:"16",rx:"2"}),i.jsx("path",{d:"M6 8h.01M10 8h.01M14 8h.01M18 8h.01M8 12h.01M12 12h.01M16 12h.01M7 16h10"})]}),"Keyboard Shortcuts"]}),i.jsx("button",{"aria-label":"Close",onClick:e,style:{background:"rgba(255,255,255,0.08)",border:"none",borderRadius:"6px",color:"rgba(255,255,255,0.6)",cursor:"pointer",width:"26px",height:"26px",display:"flex",alignItems:"center",justifyContent:"center",transition:"background 0.15s"},onMouseEnter:r=>r.currentTarget.style.background="rgba(255,255,255,0.15)",onMouseLeave:r=>r.currentTarget.style.background="rgba(255,255,255,0.08)",children:i.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",children:[i.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),i.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})]}),i.jsx("div",{style:{padding:"4px 0"},children:Vr.map(({key:r,description:n,icon:s})=>i.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",padding:"9px 14px",gap:"10px",transition:"background 0.12s"},onMouseEnter:o=>o.currentTarget.style.background="rgba(255,255,255,0.05)",onMouseLeave:o=>o.currentTarget.style.background="transparent",children:[i.jsxs("span",{style:{display:"flex",alignItems:"center",gap:"10px"},children:[i.jsx("span",{style:{width:"28px",height:"28px",borderRadius:"7px",background:"rgba(255,255,255,0.08)",display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0,color:"rgba(255,255,255,0.65)"},children:s}),i.jsx("span",{style:{color:"rgba(255,255,255,0.7)",fontSize:"13.5px"},children:n})]}),i.jsx("kbd",{style:{background:"rgba(255,255,255,0.08)",border:"1px solid rgba(255,255,255,0.15)",borderRadius:"6px",color:"rgba(255,255,255,0.75)",fontFamily:"ui-monospace, SF Mono, monospace",fontSize:"11.5px",fontWeight:600,padding:"3px 9px",whiteSpace:"nowrap",flexShrink:0},children:r})]},r))}),i.jsxs("div",{style:{padding:"10px 14px",borderTop:"1px solid rgba(255,255,255,0.07)",fontSize:"11px",color:"rgba(255,255,255,0.28)",textAlign:"center"},children:["Press"," ",i.jsx("kbd",{style:{background:"rgba(255,255,255,0.08)",border:"1px solid rgba(255,255,255,0.15)",borderRadius:"4px",padding:"1px 5px",fontSize:"10.5px",color:"rgba(255,255,255,0.4)",fontFamily:"monospace"},children:"?"})," ","or"," ",i.jsx("kbd",{style:{background:"rgba(255,255,255,0.08)",border:"1px solid rgba(255,255,255,0.15)",borderRadius:"4px",padding:"1px 5px",fontSize:"10.5px",color:"rgba(255,255,255,0.4)",fontFamily:"monospace"},children:"Esc"})," ","to dismiss"]})]}),i.jsx("style",{children:`
|
|
7
7
|
@keyframes kbdFadeIn {
|
|
8
8
|
from { opacity: 0; transform: scale(0.96) translateY(8px); }
|
|
9
9
|
to { opacity: 1; transform: scale(1) translateY(0); }
|
|
10
10
|
}
|
|
11
|
-
`})]}):null}function ct({isVisible:a,onNextEpisode:e,onDismiss:t,countdownSec:r=5,nextTitle:n,thumbnail:s}){const[o,l]=c.useState(r),
|
|
11
|
+
`})]}):null}function ct({isVisible:a,onNextEpisode:e,onDismiss:t,countdownSec:r=5,nextTitle:n,thumbnail:s}){const[o,l]=c.useState(r),d=c.useRef(null),u=c.useCallback(()=>{d.current&&(clearInterval(d.current),d.current=null)},[]);if(c.useEffect(()=>{if(!a){u(),l(r);return}return l(r),d.current=setInterval(()=>{l(m=>m<=1?(u(),e(),0):m-1)},1e3),u},[a,r,e,u]),!a)return null;const h=16,p=2*Math.PI*h,g=(r-o)/r*p;return i.jsxs("div",{style:{position:"absolute",inset:0,zIndex:9990,display:"flex",alignItems:"center",justifyContent:"center",background:"rgba(0,0,0,0.55)",backdropFilter:"blur(2px)",animation:"endCardIn 0.3s ease-out",fontFamily:"system-ui, -apple-system, sans-serif"},children:[i.jsxs("div",{style:{display:"flex",flexDirection:"column",alignItems:"center",gap:"20px",maxWidth:"340px",textAlign:"center"},children:[i.jsxs("button",{"aria-label":`Play next episode${n?`: ${n}`:""} in ${o} seconds`,onClick:e,style:{position:"relative",background:"transparent",border:"none",cursor:"pointer",padding:0,borderRadius:"12px",overflow:"hidden"},children:[s?i.jsx("img",{src:s,alt:n||"Next episode",style:{width:"220px",height:"124px",objectFit:"cover",borderRadius:"12px",display:"block",border:"2px solid rgba(255,255,255,0.15)"}}):i.jsx("div",{style:{width:"220px",height:"124px",borderRadius:"12px",background:"rgba(255,255,255,0.08)",border:"2px solid rgba(255,255,255,0.15)",display:"flex",alignItems:"center",justifyContent:"center"},children:i.jsx("svg",{width:"40",height:"40",viewBox:"0 0 24 24",fill:"rgba(255,255,255,0.8)",children:i.jsx("path",{d:"M8 5v14l11-7z"})})}),i.jsxs("div",{style:{position:"absolute",top:"8px",right:"8px",width:"40px",height:"40px",background:"rgba(0,0,0,0.75)",borderRadius:"50%",display:"flex",alignItems:"center",justifyContent:"center"},children:[i.jsxs("svg",{width:"40",height:"40",viewBox:"0 0 40 40",style:{position:"absolute",inset:0},children:[i.jsx("circle",{cx:"20",cy:"20",r:h,fill:"none",stroke:"rgba(255,255,255,0.2)",strokeWidth:"3"}),i.jsx("circle",{cx:"20",cy:"20",r:h,fill:"none",stroke:"#fff",strokeWidth:"3",strokeDasharray:p,strokeDashoffset:p-g,strokeLinecap:"round",transform:"rotate(-90 20 20)",style:{transition:"stroke-dashoffset 0.9s linear"}})]}),i.jsx("span",{style:{color:"#fff",fontSize:"13px",fontWeight:700,position:"relative",zIndex:1},children:o})]})]}),i.jsxs("div",{style:{color:"#fff"},children:[i.jsx("div",{style:{fontSize:"12px",color:"rgba(255,255,255,0.55)",marginBottom:"4px",textTransform:"uppercase",letterSpacing:"0.06em"},children:"Up Next"}),n&&i.jsx("div",{style:{fontSize:"15px",fontWeight:600,marginBottom:"6px"},children:n}),i.jsxs("div",{style:{fontSize:"13px",color:"rgba(255,255,255,0.55)"},children:["Starting in ",o," second",o!==1?"s":"","…"]})]}),i.jsxs("div",{style:{display:"flex",gap:"10px"},children:[i.jsx("button",{onClick:e,style:{padding:"9px 20px",borderRadius:"8px",background:"#fff",color:"#000",border:"none",fontWeight:700,fontSize:"13px",cursor:"pointer"},children:"Play Now"}),i.jsx("button",{onClick:t,style:{padding:"9px 20px",borderRadius:"8px",background:"rgba(255,255,255,0.12)",color:"#fff",border:"1px solid rgba(255,255,255,0.2)",fontWeight:600,fontSize:"13px",cursor:"pointer"},children:"Cancel"})]})]}),i.jsx("style",{children:`
|
|
12
12
|
@keyframes endCardIn {
|
|
13
13
|
from { opacity: 0; }
|
|
14
14
|
to { opacity: 1; }
|
|
15
15
|
}
|
|
16
|
-
`})]})}function dt({type:a,value:e}){if(!a)return null;const t=a==="seek-forward";return i.jsx("div",{"aria-hidden":"true",style:{position:"absolute",inset:0,zIndex:9985,pointerEvents:"none",display:"flex",alignItems:"center",justifyContent:t?"flex-end":"flex-start"},children:i.jsxs("div",{style:{width:"38%",height:"100%",display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",gap:"6px",background:t?"radial-gradient(ellipse at right, rgba(255,255,255,0.18) 0%, transparent 70%)":"radial-gradient(ellipse at left, rgba(255,255,255,0.18) 0%, transparent 70%)",animation:"gestureHintFade 0.9s ease-out forwards"},children:[i.jsx("svg",{width:"36",height:"36",viewBox:"0 0 24 24",fill:"rgba(255,255,255,0.9)",style:{transform:t?"none":"scaleX(-1)"},children:i.jsx("path",{d:"M5.59 7.41L10.18 12l-4.59 4.59L7 18l6-6-6-6zM12 6l6 6-6 6 1.41 1.41L20.83 12 13.41 4.59z"})}),i.jsx("span",{style:{color:"#fff",fontWeight:700,fontSize:"16px",textShadow:"0 1px 4px rgba(0,0,0,0.6)"},children:e})]})})}function ut({player:a,skipSec:e=10}){const[t,r]=c.useState(null),n=c.useRef(null),s=c.useCallback(p=>{r(p),n.current&&clearTimeout(n.current),n.current=setTimeout(()=>r(null),900)},[]),o=c.useRef(null),l=300,u=c.useCallback(p=>{if(!a)return;const g=p.touches[0],m=Date.now(),w=o.current;if(w&&m-w.time<l){const b=p.currentTarget.getBoundingClientRect();if(g.clientX-b.left>b.width/2){const E=a.getVideoElement();E&&a.seekTo(Math.min(E.duration||0,E.currentTime+e)),s({type:"seek-forward",value:`+${e}s`})}else{const E=a.getVideoElement();E&&a.seekTo(Math.max(0,E.currentTime-e)),s({type:"seek-backward",value:`-${e}s`})}o.current=null;return}o.current={time:m,x:g.clientX}},[a,e,s]),d=c.useCallback(p=>{},[]),h=c.useCallback(()=>{},[]);return{onTouchStart:u,onTouchMove:d,onTouchEnd:h,gestureHint:t}}function Br(a,e){let t;return function(...r){t||(a.apply(this,r),t=!0,setTimeout(()=>t=!1,e))}}function Nr({timeout:a=3e3,initialVisible:e=!0}={}){const[t,r]=c.useState(e),n=c.useRef(null),s=c.useCallback(()=>{n.current&&clearTimeout(n.current),r(!0),n.current=window.setTimeout(()=>{r(!1)},a)},[a]);return c.useEffect(()=>{const o=Br(()=>{s()},100),l=()=>{r(!0),n.current&&clearTimeout(n.current)};return window.addEventListener("mousemove",o,{passive:!0}),window.addEventListener("mouseenter",l,{passive:!0}),s(),()=>{window.removeEventListener("mousemove",o),window.removeEventListener("mouseenter",l),n.current&&clearTimeout(n.current)}},[s]),{isActive:t,setIsActive:r}}function $r({player:a,seekStep:e=10,enabled:t=!0,onShowShortcuts:r}){c.useEffect(()=>{if(!a||!t)return;const n=s=>{const o=s.target;if(o.tagName==="INPUT"||o.tagName==="TEXTAREA"||o.isContentEditable)return;const l=a.getVideoElement();if(l)switch(s.code){case"Space":s.preventDefault(),l.paused?a.play():a.pause();break;case"ArrowLeft":s.preventDefault();const u=Math.max(0,l.currentTime-e);a.seekTo(u);break;case"ArrowRight":s.preventDefault();const d=Math.min(l.duration,l.currentTime+e);a.seekTo(d);break;case"ArrowUp":s.preventDefault();const h=l.volume;a.setVolume(Math.min(1,h+.1));break;case"ArrowDown":s.preventDefault();const p=l.volume;a.setVolume(Math.max(0,p-.1));break;case"KeyM":s.preventDefault(),a.toggleMute();break;case"KeyF":s.preventDefault(),a.toggleFullscreen();break;case"Slash":s.shiftKey&&(s.preventDefault(),r?.());break}};return document.addEventListener("keydown",n),()=>{document.removeEventListener("keydown",n)}},[a,e,t,r])}class Fr{timeout;maxWrapperDepth;constructor(e=5e3,t=5){this.timeout=e,this.maxWrapperDepth=t}async parse(e,t=0,r=0){if(t>this.maxWrapperDepth)throw new Error(`VAST wrapper depth exceeded (max: ${this.maxWrapperDepth})`);try{const s=await this.fetchVAST(e),o=this.parseXML(s),l=o.querySelector("Wrapper");if(l){const u=l.querySelector("VASTAdTagURI")?.textContent?.trim();if(!u)throw new Error("Wrapper missing VASTAdTagURI");return this.parse(u,t+1,r)}return this.parseInline(o)}catch(s){if(s instanceof Error&&s.message.includes("No ads available")&&r<2)return console.warn(`[VASTParser] ⚠️ No ads on attempt ${r+1}/3, retrying in 1500ms...`),await new Promise(l=>setTimeout(l,1500)),this.parse(e,t,r+1);throw s}}async fetchVAST(e){const t=new AbortController,r=setTimeout(()=>t.abort(),this.timeout);try{const n=await fetch(e,{signal:t.signal,headers:{Accept:"application/xml, text/xml, */*"}});if(clearTimeout(r),!n.ok)throw new Error(`VAST fetch failed: ${n.status} ${n.statusText}`);const s=await n.text();if(!s||s.trim().length===0)throw new Error("VAST response is empty");return s}catch(n){throw clearTimeout(r),n instanceof Error&&n.name==="AbortError"?new Error("VAST request timeout"):n}}parseXML(e){const r=new DOMParser().parseFromString(e,"text/xml"),n=r.querySelector("parsererror");if(n){const l=n.textContent||"Unknown parse error";throw console.error("[VASTParser] XML parse error:",l),console.error("[VASTParser] XML content (first 500 chars):",e.substring(0,500)),new Error(`VAST XML parse error: ${l}`)}if(!r.querySelector("VAST"))throw console.error("[VASTParser] No VAST element found in XML"),console.error("[VASTParser] XML content:",e.substring(0,500)),new Error("Invalid VAST XML: No VAST element found");if(r.querySelectorAll("Ad").length===0)throw console.warn("[VASTParser] No Ad elements found in VAST response (empty ad pod)"),console.log("[VASTParser] Full XML:",e),new Error("No ads available in VAST response");return r}async parseAdPod(e){const t=await this.fetchVAST(e),r=this.parseXML(t),n=Array.from(r.querySelectorAll("Ad"));if(n.length===0)throw new Error("No ads available in VAST response");const s=[];for(const o of n)try{const l=o.querySelector("Wrapper");if(l){const u=l.querySelector("VASTAdTagURI")?.textContent?.trim();if(u){const d=await this.parse(u,1);s.push(d)}}else{const u=this.parseAdElement(o,r);u&&s.push(u)}}catch(l){console.warn("[VASTParser] Failed to parse Ad in pod, skipping:",l)}if(s.length===0)throw new Error("No ads available in VAST response");return s.sort((o,l)=>(o.podSequence??0)-(l.podSequence??0)),s}parseInline(e){const t=e.querySelector("Ad");if(!t)throw new Error("VAST Ad element not found");const r=this.parseAdElement(t,e);if(!r)throw new Error("VAST Ad element is empty (no ads available)");return r}parseAdElement(e,t){const r=e.getAttribute("sequence"),n=r!==null?parseInt(r,10):void 0,s=e.querySelector("InLine")??e.querySelector("Inline")??e.querySelector("inline")??t.querySelector("InLine")??t.querySelector("Inline");if(!s){const M=Array.from(e.children).map(E=>E.tagName);throw M.length===0?new Error("VAST Ad element is empty (no ads available)"):new Error(`VAST InLine not found. Found: ${M.join(", ")}`)}const o=e.getAttribute("id")||`ad-${Date.now()}`,l=s.querySelector("AdTitle")?.textContent?.trim(),u=s.querySelector("Duration")?.textContent?.trim(),d=this.parseDuration(u||"00:00:00"),{mediaFile:h,isVpaid:p,vpaidUrl:g}=this.getMediaFileInfo(s);if(!h)throw new Error("VAST MediaFile not found");const m=s.querySelector("ClickThrough")?.textContent?.trim(),w=this.parseTrackingEvents(s,t),L=this.getErrorUrls(t),b=this.parseCompanions(s);return{id:o,title:l,duration:d,mediaFile:h,clickThrough:m,trackingEvents:w,errorUrls:L,companions:b.length>0?b:void 0,isVpaid:p,vpaidUrl:g,podSequence:n}}parseCompanions(e){const t=[];return e.querySelectorAll("CompanionAds > Companion").forEach(n=>{const s=parseInt(n.getAttribute("width")||"0",10),o=parseInt(n.getAttribute("height")||"0",10),l=n.getAttribute("id")??void 0,u=n.querySelector("StaticResource"),d=n.querySelector("HTMLResource"),h=n.querySelector("IFrameResource"),p=u?.textContent?.trim()??void 0,g=d?.textContent?.trim()??void 0,m=h?.textContent?.trim()??void 0,w=u?.getAttribute("creativeType")??void 0,L=n.querySelector("CompanionClickThrough")?.textContent?.trim()??void 0,b=n.querySelector("AltText")?.textContent?.trim()??void 0,M=[];n.querySelectorAll('TrackingEvents > Tracking[event="creativeView"]').forEach(E=>{const y=E.textContent?.trim();y&&M.push(y)}),(p||g||m)&&t.push({id:l,width:s,height:o,staticResource:p,htmlResource:g,iFrameResource:m,type:w,clickThrough:L,altText:b,viewTrackingUrls:M.length>0?M:void 0})}),t}parseDuration(e){const t=e.split(":").map(Number);if(t.length===3){const[r,n,s]=t;return r*3600+n*60+s}return 0}getMediaFileInfo(e){const t=Array.from(e.querySelectorAll("MediaFile"));if(t.length===0)return{mediaFile:null,isVpaid:!1,vpaidUrl:void 0};const r=t.find(o=>o.getAttribute("apiFramework")?.toUpperCase()==="VPAID"&&(o.getAttribute("type")?.includes("javascript")||o.getAttribute("type")?.includes("application/javascript")));if(r){const o=r.textContent?.trim()||void 0;return console.log("[VASTParser] VPAID 2.0 creative detected:",o),{mediaFile:o??null,isVpaid:!0,vpaidUrl:o}}const n=t.filter(o=>o.getAttribute("delivery")==="progressive"&&o.getAttribute("type")?.includes("mp4"));return{mediaFile:(n.length>0?n[0]:t[0]).textContent?.trim()||null,isVpaid:!1,vpaidUrl:void 0}}parseTrackingEvents(e,t){const r={},n=t.querySelectorAll("Impression");n.length>0&&(r.impression=Array.from(n).map(o=>o.textContent?.trim()).filter(Boolean));const s=["start","firstQuartile","midpoint","thirdQuartile","complete","skip","pause","resume"];return e.querySelectorAll("Tracking").forEach(o=>{const l=o.getAttribute("event"),u=o.textContent?.trim();!l||!u||!s.includes(l)||(r[l]||(r[l]=[]),r[l].push(u))}),r}getErrorUrls(e){const t=[];return e.querySelectorAll("Error").forEach(r=>{const n=r.textContent?.trim();n&&t.push(n)}),t}}class Ur{timeout;constructor(e=5e3){this.timeout=e}async parse(e){const t=await this.fetchVMAP(e),r=this.parseXML(t),n="http://www.iab.net/videosuite/vmap";let s=r.querySelector("vmap\\:VMAP, VMAP");if(!s){const u=r.getElementsByTagNameNS(n,"VMAP");if(u.length>0)s=u[0];else{const d=r.getElementsByTagName("VMAP");d.length>0&&(s=d[0])}}if(!s)throw console.error("[VMAPParser] VMAP element not found. XML:",t.substring(0,500)),new Error("VMAP element not found");const o=s.getAttribute("version")||"1.0",l=this.parseAdBreaks(r);return l.length===0?(console.warn("[VMAPParser] ⚠️ No ad breaks found in VMAP"),console.warn("[VMAPParser] This might mean:"),console.warn("[VMAPParser] 1. The VMAP URL returned an empty response (common with test URLs)"),console.warn("[VMAPParser] 2. The VMAP structure is different than expected"),console.warn("[VMAPParser] 3. There are no ads available at this time"),console.warn("[VMAPParser] VMAP XML (first 1000 chars):",t.substring(0,1e3)),t.includes("AdBreak")||t.includes("adBreak")||t.includes("AdSource")||(console.error("[VMAPParser] ❌ VMAP appears to be completely empty - no AdBreak elements found"),console.error("[VMAPParser] This is likely a test URL issue. Try using a local VMAP file or a different test URL."))):console.log(`[VMAPParser] ✅ Successfully parsed ${l.length} ad break(s)`),{version:o,adBreaks:l}}async fetchVMAP(e){const t=new AbortController,r=setTimeout(()=>t.abort(),this.timeout);try{console.log("[VMAPParser] Fetching VMAP from:",e);const n=await fetch(e,{signal:t.signal,headers:{Accept:"application/xml, text/xml, */*"}});if(clearTimeout(r),!n.ok)throw console.error("[VMAPParser] VMAP fetch failed:",{status:n.status,statusText:n.statusText,url:e}),new Error(`VMAP fetch failed: ${n.status} ${n.statusText}`);const s=await n.text();if(!s||s.trim().length===0)throw console.error("[VMAPParser] VMAP response is empty"),new Error("VMAP response is empty");return console.log("[VMAPParser] VMAP fetched successfully, length:",s.length),s}catch(n){throw clearTimeout(r),n instanceof Error&&n.name==="AbortError"?(console.error("[VMAPParser] VMAP request timeout after",this.timeout,"ms"),new Error(`VMAP request timeout (${this.timeout}ms)`)):n instanceof TypeError?(console.error("[VMAPParser] Network error fetching VMAP:",n.message),new Error(`VMAP network error: ${n.message}`)):n}}parseXML(e){const r=new DOMParser().parseFromString(e,"text/xml"),n=r.querySelector("parsererror");if(n){const s=n.textContent||"Unknown parse error";throw console.error("[VMAPParser] XML parse error:",s),console.error("[VMAPParser] XML content (first 500 chars):",e.substring(0,500)),new Error(`VMAP XML parse error: ${s}`)}return r}parseAdBreaks(e){const t=[],r="http://www.iab.net/videosuite/vmap";let n=e.querySelectorAll("vmap\\:AdBreak, AdBreak");if(n.length===0&&e.documentElement){const o=e.getElementsByTagNameNS(r,"AdBreak");if(o.length>0)n=o;else{const l=e.getElementsByTagName("AdBreak");l.length>0&&(n=l)}}return Array.from(n).forEach(s=>{const o=this.parseAdBreak(s);o&&t.push(o)}),t}parseAdBreak(e){const t=e.getAttribute("timeOffset");if(!t)return console.warn("[VMAPParser] AdBreak missing timeOffset, skipping"),null;const r=this.parseTimeOffset(t),n="http://www.iab.net/videosuite/vmap";let s=e.querySelector("vmap\\:AdSource, AdSource");if(!s){const d=e.getElementsByTagNameNS(n,"AdSource");if(d.length>0)s=d[0];else{const h=e.getElementsByTagName("AdSource");h.length>0&&(s=h[0])}}if(!s)return console.warn("[VMAPParser] AdBreak missing AdSource, skipping"),null;let o=s.querySelector("vmap\\:AdTagURI, AdTagURI");if(!o){const d=s.getElementsByTagNameNS(n,"AdTagURI");if(d.length>0)o=d[0];else{const h=s.getElementsByTagName("AdTagURI");h.length>0&&(o=h[0])}}if(!o)return console.warn("[VMAPParser] AdSource missing AdTagURI, skipping"),console.warn("[VMAPParser] AdSource children:",Array.from(s.children).map(d=>d.tagName)),null;let l=o.textContent?.trim()||o.innerHTML?.trim();if(!l)return console.warn("[VMAPParser] AdTagURI is empty, skipping"),null;l=l.replace(/<!\\[CDATA\\[(.*?)\\]\\]>/g,"$1").trim();const u=document.createElement("textarea");return u.innerHTML=l,l=u.value,console.log("[VMAPParser] AdBreak parsed:",{timeOffset:r,timeOffsetStr:t,vastUrl:l.substring(0,100)+(l.length>100?"...":"")}),{timeOffset:r,vastUrl:l}}parseTimeOffset(e){const t=e.trim().toLowerCase();if(t==="start")return 0;if(t==="end")return-1;const r=t.split(":").map(Number);if(r.length===1)return r[0];if(r.length===2){const[n,s]=r;return n*60+s}else if(r.length===3){const[n,s,o]=r;return n*3600+s*60+o}return console.warn(`[VMAPParser] Invalid timeOffset format: ${e}, defaulting to 0`),0}}class Or{trackingEnabled;constructor(e=!0){this.trackingEnabled=e}trackImpression(e){!this.trackingEnabled||!e.trackingEvents.impression||e.trackingEvents.impression.forEach(t=>{this.fireTrackingPixel(t)})}trackStart(e){!this.trackingEnabled||!e.trackingEvents.start||e.trackingEvents.start.forEach(t=>{this.fireTrackingPixel(t)})}trackComplete(e){!this.trackingEnabled||!e.trackingEvents.complete||e.trackingEvents.complete.forEach(t=>{this.fireTrackingPixel(t)})}trackSkip(e){!this.trackingEnabled||!e.trackingEvents.skip||e.trackingEvents.skip.forEach(t=>{this.fireTrackingPixel(t)})}trackError(e,t){!this.trackingEnabled||!e.errorUrls||e.errorUrls.forEach(r=>{const n=r.replace("[ERRORCODE]",t);this.fireTrackingPixel(n)})}fireTrackingPixel(e){if(e)try{const t=new Image;t.src=e}catch(t){console.warn("[AdTracker] Failed to fire tracking pixel:",e,t)}}reset(){}}class Wr{player;config;tracker;hideLoadingCallback;adVideo=null;adContainer=null;companionContainer=null;mainVideoElement=null;skipButton=null;countdownElement=null;vpaidIframe=null;vpaidCreative=null;state={isPlaying:!1,ad:null,position:null,currentTime:0,canSkip:!1,remainingTime:0};constructor(e,t,r){this.player=e,this.config=t,this.tracker=new Or(!0),this.hideLoadingCallback=r}async play(e,t){if(console.log(`[AdPlayer] Playing ${t} ad:`,e.title||e.id),this.mainVideoElement=this.player.getVideoElement(),!this.mainVideoElement&&this.player.videoElement&&(this.mainVideoElement=this.player.videoElement),!this.mainVideoElement)throw new Error("Main video element not found. Player may not be initialized.");this.player.getState()?.isPlaying&&this.player.pause(),this.state={isPlaying:!0,ad:e,position:t,currentTime:0,canSkip:!1,remainingTime:e.duration},this.tracker.reset();try{this.createAdUI(),e.companions?.length&&this.showCompanionBanners(e.companions),this.tracker.trackImpression(e),e.isVpaid&&e.vpaidUrl?await this.playVpaidCreative(e):await this.playAdVideo(e),this.tracker.trackComplete(e),console.log("[AdPlayer] Ad completed")}catch(n){throw console.error("[AdPlayer] Ad playback error:",n),this.tracker.trackError(e,"400"),n}finally{this.destroyAdUI(),this.state.isPlaying=!1,this.state.ad=null,t!=="postroll"&&setTimeout(()=>{try{this.player&&typeof this.player.play=="function"&&this.player.play().catch(n=>{console.warn("[AdPlayer] Failed to resume main video:",n.message)})}catch(n){console.warn("[AdPlayer] Error resuming main video:",n)}},100)}}async playAdPod(e,t){console.log(`[AdPlayer] Playing ad pod: ${e.length} ads at ${t}`);for(const r of e)try{await this.play(r,t)}catch(n){console.warn("[AdPlayer] Ad pod: ad failed, continuing with next:",n)}console.log("[AdPlayer] Ad pod complete")}showCompanionBanners(e){if(!this.mainVideoElement)return;const r=document.getElementById("virtus-companion-slot")??this.mainVideoElement.parentElement;if(r){this.companionContainer=document.createElement("div"),this.companionContainer.className="virtus-companion-container",this.companionContainer.style.cssText=`
|
|
16
|
+
`})]})}function dt({type:a,value:e}){if(!a)return null;const t=a==="seek-forward";return i.jsx("div",{"aria-hidden":"true",style:{position:"absolute",inset:0,zIndex:9985,pointerEvents:"none",display:"flex",alignItems:"center",justifyContent:t?"flex-end":"flex-start"},children:i.jsxs("div",{style:{width:"38%",height:"100%",display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",gap:"6px",background:t?"radial-gradient(ellipse at right, rgba(255,255,255,0.18) 0%, transparent 70%)":"radial-gradient(ellipse at left, rgba(255,255,255,0.18) 0%, transparent 70%)",animation:"gestureHintFade 0.9s ease-out forwards"},children:[i.jsx("svg",{width:"36",height:"36",viewBox:"0 0 24 24",fill:"rgba(255,255,255,0.9)",style:{transform:t?"none":"scaleX(-1)"},children:i.jsx("path",{d:"M5.59 7.41L10.18 12l-4.59 4.59L7 18l6-6-6-6zM12 6l6 6-6 6 1.41 1.41L20.83 12 13.41 4.59z"})}),i.jsx("span",{style:{color:"#fff",fontWeight:700,fontSize:"16px",textShadow:"0 1px 4px rgba(0,0,0,0.6)"},children:e})]})})}function ut({player:a,skipSec:e=10}){const[t,r]=c.useState(null),n=c.useRef(null),s=c.useCallback(p=>{r(p),n.current&&clearTimeout(n.current),n.current=setTimeout(()=>r(null),900)},[]),o=c.useRef(null),l=300,d=c.useCallback(p=>{if(!a)return;const g=p.touches[0],m=Date.now(),E=o.current;if(E&&m-E.time<l){const S=p.currentTarget.getBoundingClientRect();if(g.clientX-S.left>S.width/2){const b=a.getVideoElement();b&&a.seekTo(Math.min(b.duration||0,b.currentTime+e)),s({type:"seek-forward",value:`+${e}s`})}else{const b=a.getVideoElement();b&&a.seekTo(Math.max(0,b.currentTime-e)),s({type:"seek-backward",value:`-${e}s`})}o.current=null;return}o.current={time:m,x:g.clientX}},[a,e,s]),u=c.useCallback(p=>{},[]),h=c.useCallback(()=>{},[]);return{onTouchStart:d,onTouchMove:u,onTouchEnd:h,gestureHint:t}}function Br(a,e){let t;return function(...r){t||(a.apply(this,r),t=!0,setTimeout(()=>t=!1,e))}}function Nr({timeout:a=3e3,initialVisible:e=!0}={}){const[t,r]=c.useState(e),n=c.useRef(null),s=c.useCallback(()=>{n.current&&clearTimeout(n.current),r(!0),n.current=window.setTimeout(()=>{r(!1)},a)},[a]);return c.useEffect(()=>{const o=Br(()=>{s()},100),l=()=>{r(!0),n.current&&clearTimeout(n.current)};return window.addEventListener("mousemove",o,{passive:!0}),window.addEventListener("mouseenter",l,{passive:!0}),s(),()=>{window.removeEventListener("mousemove",o),window.removeEventListener("mouseenter",l),n.current&&clearTimeout(n.current)}},[s]),{isActive:t,setIsActive:r}}function $r({player:a,seekStep:e=10,enabled:t=!0,onShowShortcuts:r}){c.useEffect(()=>{if(!a||!t)return;const n=s=>{const o=s.target;if(o.tagName==="INPUT"||o.tagName==="TEXTAREA"||o.isContentEditable)return;const l=a.getVideoElement();if(l)switch(s.code){case"Space":s.preventDefault(),l.paused?a.play():a.pause();break;case"ArrowLeft":s.preventDefault();const d=Math.max(0,l.currentTime-e);a.seekTo(d);break;case"ArrowRight":s.preventDefault();const u=Math.min(l.duration,l.currentTime+e);a.seekTo(u);break;case"ArrowUp":s.preventDefault();const h=l.volume;a.setVolume(Math.min(1,h+.1));break;case"ArrowDown":s.preventDefault();const p=l.volume;a.setVolume(Math.max(0,p-.1));break;case"KeyM":s.preventDefault(),a.toggleMute();break;case"KeyF":s.preventDefault(),a.toggleFullscreen();break;case"Slash":s.shiftKey&&(s.preventDefault(),r?.());break}};return document.addEventListener("keydown",n),()=>{document.removeEventListener("keydown",n)}},[a,e,t,r])}class Fr{timeout;maxWrapperDepth;constructor(e=5e3,t=5){this.timeout=e,this.maxWrapperDepth=t}async parse(e,t=0,r=0){if(t>this.maxWrapperDepth)throw new Error(`VAST wrapper depth exceeded (max: ${this.maxWrapperDepth})`);try{const s=await this.fetchVAST(e),o=this.parseXML(s),l=o.querySelector("Wrapper");if(l){const d=l.querySelector("VASTAdTagURI")?.textContent?.trim();if(!d)throw new Error("Wrapper missing VASTAdTagURI");return this.parse(d,t+1,r)}return this.parseInline(o)}catch(s){if(s instanceof Error&&s.message.includes("No ads available")&&r<2)return console.warn(`[VASTParser] ⚠️ No ads on attempt ${r+1}/3, retrying in 1500ms...`),await new Promise(l=>setTimeout(l,1500)),this.parse(e,t,r+1);throw s}}async fetchVAST(e){const t=new AbortController,r=setTimeout(()=>t.abort(),this.timeout);try{const n=await fetch(e,{signal:t.signal,headers:{Accept:"application/xml, text/xml, */*"}});if(clearTimeout(r),!n.ok)throw new Error(`VAST fetch failed: ${n.status} ${n.statusText}`);const s=await n.text();if(!s||s.trim().length===0)throw new Error("VAST response is empty");return s}catch(n){throw clearTimeout(r),n instanceof Error&&n.name==="AbortError"?new Error("VAST request timeout"):n}}parseXML(e){const r=new DOMParser().parseFromString(e,"text/xml"),n=r.querySelector("parsererror");if(n){const l=n.textContent||"Unknown parse error";throw console.error("[VASTParser] XML parse error:",l),console.error("[VASTParser] XML content (first 500 chars):",e.substring(0,500)),new Error(`VAST XML parse error: ${l}`)}if(!r.querySelector("VAST"))throw console.error("[VASTParser] No VAST element found in XML"),console.error("[VASTParser] XML content:",e.substring(0,500)),new Error("Invalid VAST XML: No VAST element found");if(r.querySelectorAll("Ad").length===0)throw console.warn("[VASTParser] No Ad elements found in VAST response (empty ad pod)"),console.log("[VASTParser] Full XML:",e),new Error("No ads available in VAST response");return r}async parseAdPod(e){const t=await this.fetchVAST(e),r=this.parseXML(t),n=Array.from(r.querySelectorAll("Ad"));if(n.length===0)throw new Error("No ads available in VAST response");const s=[];for(const o of n)try{const l=o.querySelector("Wrapper");if(l){const d=l.querySelector("VASTAdTagURI")?.textContent?.trim();if(d){const u=await this.parse(d,1);s.push(u)}}else{const d=this.parseAdElement(o,r);d&&s.push(d)}}catch(l){console.warn("[VASTParser] Failed to parse Ad in pod, skipping:",l)}if(s.length===0)throw new Error("No ads available in VAST response");return s.sort((o,l)=>(o.podSequence??0)-(l.podSequence??0)),s}parseInline(e){const t=e.querySelector("Ad");if(!t)throw new Error("VAST Ad element not found");const r=this.parseAdElement(t,e);if(!r)throw new Error("VAST Ad element is empty (no ads available)");return r}parseAdElement(e,t){const r=e.getAttribute("sequence"),n=r!==null?parseInt(r,10):void 0,s=e.querySelector("InLine")??e.querySelector("Inline")??e.querySelector("inline")??t.querySelector("InLine")??t.querySelector("Inline");if(!s){const A=Array.from(e.children).map(b=>b.tagName);throw A.length===0?new Error("VAST Ad element is empty (no ads available)"):new Error(`VAST InLine not found. Found: ${A.join(", ")}`)}const o=e.getAttribute("id")||`ad-${Date.now()}`,l=s.querySelector("AdTitle")?.textContent?.trim(),d=s.querySelector("Duration")?.textContent?.trim(),u=this.parseDuration(d||"00:00:00"),{mediaFile:h,isVpaid:p,vpaidUrl:g}=this.getMediaFileInfo(s);if(!h)throw new Error("VAST MediaFile not found");const m=s.querySelector("ClickThrough")?.textContent?.trim(),E=this.parseTrackingEvents(s,t),j=this.getErrorUrls(t),S=this.parseCompanions(s);return{id:o,title:l,duration:u,mediaFile:h,clickThrough:m,trackingEvents:E,errorUrls:j,companions:S.length>0?S:void 0,isVpaid:p,vpaidUrl:g,podSequence:n}}parseCompanions(e){const t=[];return e.querySelectorAll("CompanionAds > Companion").forEach(n=>{const s=parseInt(n.getAttribute("width")||"0",10),o=parseInt(n.getAttribute("height")||"0",10),l=n.getAttribute("id")??void 0,d=n.querySelector("StaticResource"),u=n.querySelector("HTMLResource"),h=n.querySelector("IFrameResource"),p=d?.textContent?.trim()??void 0,g=u?.textContent?.trim()??void 0,m=h?.textContent?.trim()??void 0,E=d?.getAttribute("creativeType")??void 0,j=n.querySelector("CompanionClickThrough")?.textContent?.trim()??void 0,S=n.querySelector("AltText")?.textContent?.trim()??void 0,A=[];n.querySelectorAll('TrackingEvents > Tracking[event="creativeView"]').forEach(b=>{const y=b.textContent?.trim();y&&A.push(y)}),(p||g||m)&&t.push({id:l,width:s,height:o,staticResource:p,htmlResource:g,iFrameResource:m,type:E,clickThrough:j,altText:S,viewTrackingUrls:A.length>0?A:void 0})}),t}parseDuration(e){const t=e.split(":").map(Number);if(t.length===3){const[r,n,s]=t;return r*3600+n*60+s}return 0}getMediaFileInfo(e){const t=Array.from(e.querySelectorAll("MediaFile"));if(t.length===0)return{mediaFile:null,isVpaid:!1,vpaidUrl:void 0};const r=t.find(o=>o.getAttribute("apiFramework")?.toUpperCase()==="VPAID"&&(o.getAttribute("type")?.includes("javascript")||o.getAttribute("type")?.includes("application/javascript")));if(r){const o=r.textContent?.trim()||void 0;return console.log("[VASTParser] VPAID 2.0 creative detected:",o),{mediaFile:o??null,isVpaid:!0,vpaidUrl:o}}const n=t.filter(o=>o.getAttribute("delivery")==="progressive"&&o.getAttribute("type")?.includes("mp4"));return{mediaFile:(n.length>0?n[0]:t[0]).textContent?.trim()||null,isVpaid:!1,vpaidUrl:void 0}}parseTrackingEvents(e,t){const r={},n=t.querySelectorAll("Impression");n.length>0&&(r.impression=Array.from(n).map(o=>o.textContent?.trim()).filter(Boolean));const s=["start","firstQuartile","midpoint","thirdQuartile","complete","skip","pause","resume"];return e.querySelectorAll("Tracking").forEach(o=>{const l=o.getAttribute("event"),d=o.textContent?.trim();!l||!d||!s.includes(l)||(r[l]||(r[l]=[]),r[l].push(d))}),r}getErrorUrls(e){const t=[];return e.querySelectorAll("Error").forEach(r=>{const n=r.textContent?.trim();n&&t.push(n)}),t}}class Ur{timeout;constructor(e=5e3){this.timeout=e}async parse(e){const t=await this.fetchVMAP(e),r=this.parseXML(t),n="http://www.iab.net/videosuite/vmap";let s=r.querySelector("vmap\\:VMAP, VMAP");if(!s){const d=r.getElementsByTagNameNS(n,"VMAP");if(d.length>0)s=d[0];else{const u=r.getElementsByTagName("VMAP");u.length>0&&(s=u[0])}}if(!s)throw console.error("[VMAPParser] VMAP element not found. XML:",t.substring(0,500)),new Error("VMAP element not found");const o=s.getAttribute("version")||"1.0",l=this.parseAdBreaks(r);return l.length===0?(console.warn("[VMAPParser] ⚠️ No ad breaks found in VMAP"),console.warn("[VMAPParser] This might mean:"),console.warn("[VMAPParser] 1. The VMAP URL returned an empty response (common with test URLs)"),console.warn("[VMAPParser] 2. The VMAP structure is different than expected"),console.warn("[VMAPParser] 3. There are no ads available at this time"),console.warn("[VMAPParser] VMAP XML (first 1000 chars):",t.substring(0,1e3)),t.includes("AdBreak")||t.includes("adBreak")||t.includes("AdSource")||(console.error("[VMAPParser] ❌ VMAP appears to be completely empty - no AdBreak elements found"),console.error("[VMAPParser] This is likely a test URL issue. Try using a local VMAP file or a different test URL."))):console.log(`[VMAPParser] ✅ Successfully parsed ${l.length} ad break(s)`),{version:o,adBreaks:l}}async fetchVMAP(e){const t=new AbortController,r=setTimeout(()=>t.abort(),this.timeout);try{console.log("[VMAPParser] Fetching VMAP from:",e);const n=await fetch(e,{signal:t.signal,headers:{Accept:"application/xml, text/xml, */*"}});if(clearTimeout(r),!n.ok)throw console.error("[VMAPParser] VMAP fetch failed:",{status:n.status,statusText:n.statusText,url:e}),new Error(`VMAP fetch failed: ${n.status} ${n.statusText}`);const s=await n.text();if(!s||s.trim().length===0)throw console.error("[VMAPParser] VMAP response is empty"),new Error("VMAP response is empty");return console.log("[VMAPParser] VMAP fetched successfully, length:",s.length),s}catch(n){throw clearTimeout(r),n instanceof Error&&n.name==="AbortError"?(console.error("[VMAPParser] VMAP request timeout after",this.timeout,"ms"),new Error(`VMAP request timeout (${this.timeout}ms)`)):n instanceof TypeError?(console.error("[VMAPParser] Network error fetching VMAP:",n.message),new Error(`VMAP network error: ${n.message}`)):n}}parseXML(e){const r=new DOMParser().parseFromString(e,"text/xml"),n=r.querySelector("parsererror");if(n){const s=n.textContent||"Unknown parse error";throw console.error("[VMAPParser] XML parse error:",s),console.error("[VMAPParser] XML content (first 500 chars):",e.substring(0,500)),new Error(`VMAP XML parse error: ${s}`)}return r}parseAdBreaks(e){const t=[],r="http://www.iab.net/videosuite/vmap";let n=e.querySelectorAll("vmap\\:AdBreak, AdBreak");if(n.length===0&&e.documentElement){const o=e.getElementsByTagNameNS(r,"AdBreak");if(o.length>0)n=o;else{const l=e.getElementsByTagName("AdBreak");l.length>0&&(n=l)}}return Array.from(n).forEach(s=>{const o=this.parseAdBreak(s);o&&t.push(o)}),t}parseAdBreak(e){const t=e.getAttribute("timeOffset");if(!t)return console.warn("[VMAPParser] AdBreak missing timeOffset, skipping"),null;const r=this.parseTimeOffset(t),n="http://www.iab.net/videosuite/vmap";let s=e.querySelector("vmap\\:AdSource, AdSource");if(!s){const u=e.getElementsByTagNameNS(n,"AdSource");if(u.length>0)s=u[0];else{const h=e.getElementsByTagName("AdSource");h.length>0&&(s=h[0])}}if(!s)return console.warn("[VMAPParser] AdBreak missing AdSource, skipping"),null;let o=s.querySelector("vmap\\:AdTagURI, AdTagURI");if(!o){const u=s.getElementsByTagNameNS(n,"AdTagURI");if(u.length>0)o=u[0];else{const h=s.getElementsByTagName("AdTagURI");h.length>0&&(o=h[0])}}if(!o)return console.warn("[VMAPParser] AdSource missing AdTagURI, skipping"),console.warn("[VMAPParser] AdSource children:",Array.from(s.children).map(u=>u.tagName)),null;let l=o.textContent?.trim()||o.innerHTML?.trim();if(!l)return console.warn("[VMAPParser] AdTagURI is empty, skipping"),null;l=l.replace(/<!\\[CDATA\\[(.*?)\\]\\]>/g,"$1").trim();const d=document.createElement("textarea");return d.innerHTML=l,l=d.value,console.log("[VMAPParser] AdBreak parsed:",{timeOffset:r,timeOffsetStr:t,vastUrl:l.substring(0,100)+(l.length>100?"...":"")}),{timeOffset:r,vastUrl:l}}parseTimeOffset(e){const t=e.trim().toLowerCase();if(t==="start")return 0;if(t==="end")return-1;const r=t.split(":").map(Number);if(r.length===1)return r[0];if(r.length===2){const[n,s]=r;return n*60+s}else if(r.length===3){const[n,s,o]=r;return n*3600+s*60+o}return console.warn(`[VMAPParser] Invalid timeOffset format: ${e}, defaulting to 0`),0}}class Or{trackingEnabled;constructor(e=!0){this.trackingEnabled=e}trackImpression(e){!this.trackingEnabled||!e.trackingEvents.impression||e.trackingEvents.impression.forEach(t=>{this.fireTrackingPixel(t)})}trackStart(e){!this.trackingEnabled||!e.trackingEvents.start||e.trackingEvents.start.forEach(t=>{this.fireTrackingPixel(t)})}trackComplete(e){!this.trackingEnabled||!e.trackingEvents.complete||e.trackingEvents.complete.forEach(t=>{this.fireTrackingPixel(t)})}trackSkip(e){!this.trackingEnabled||!e.trackingEvents.skip||e.trackingEvents.skip.forEach(t=>{this.fireTrackingPixel(t)})}trackError(e,t){!this.trackingEnabled||!e.errorUrls||e.errorUrls.forEach(r=>{const n=r.replace("[ERRORCODE]",t);this.fireTrackingPixel(n)})}fireTrackingPixel(e){if(e)try{const t=new Image;t.src=e}catch(t){console.warn("[AdTracker] Failed to fire tracking pixel:",e,t)}}reset(){}}class Wr{player;config;tracker;hideLoadingCallback;adVideo=null;adContainer=null;companionContainer=null;mainVideoElement=null;skipButton=null;countdownElement=null;vpaidIframe=null;vpaidCreative=null;state={isPlaying:!1,ad:null,position:null,currentTime:0,canSkip:!1,remainingTime:0};constructor(e,t,r){this.player=e,this.config=t,this.tracker=new Or(!0),this.hideLoadingCallback=r}async play(e,t){if(console.log(`[AdPlayer] Playing ${t} ad:`,e.title||e.id),this.mainVideoElement=this.player.getVideoElement(),!this.mainVideoElement&&this.player.videoElement&&(this.mainVideoElement=this.player.videoElement),!this.mainVideoElement)throw new Error("Main video element not found. Player may not be initialized.");this.player.getState()?.isPlaying&&this.player.pause(),this.state={isPlaying:!0,ad:e,position:t,currentTime:0,canSkip:!1,remainingTime:e.duration},this.tracker.reset();try{this.createAdUI(),e.companions?.length&&this.showCompanionBanners(e.companions),this.tracker.trackImpression(e),e.isVpaid&&e.vpaidUrl?await this.playVpaidCreative(e):await this.playAdVideo(e),this.tracker.trackComplete(e),console.log("[AdPlayer] Ad completed")}catch(n){throw console.error("[AdPlayer] Ad playback error:",n),this.tracker.trackError(e,"400"),n}finally{this.destroyAdUI(),this.state.isPlaying=!1,this.state.ad=null,t!=="postroll"&&setTimeout(()=>{try{this.player&&typeof this.player.play=="function"&&this.player.play().catch(n=>{console.warn("[AdPlayer] Failed to resume main video:",n.message)})}catch(n){console.warn("[AdPlayer] Error resuming main video:",n)}},100)}}async playAdPod(e,t){console.log(`[AdPlayer] Playing ad pod: ${e.length} ads at ${t}`);for(const r of e)try{await this.play(r,t)}catch(n){console.warn("[AdPlayer] Ad pod: ad failed, continuing with next:",n)}console.log("[AdPlayer] Ad pod complete")}showCompanionBanners(e){if(!this.mainVideoElement)return;const r=document.getElementById("virtus-companion-slot")??this.mainVideoElement.parentElement;if(r){this.companionContainer=document.createElement("div"),this.companionContainer.className="virtus-companion-container",this.companionContainer.style.cssText=`
|
|
17
17
|
position: absolute;
|
|
18
18
|
top: 0;
|
|
19
19
|
right: -320px;
|
|
@@ -26,7 +26,7 @@
|
|
|
26
26
|
<script>
|
|
27
27
|
window.getVPAIDAd = function() { return typeof window.VPAIDCreative !== 'undefined' ? new window.VPAIDCreative() : null; };
|
|
28
28
|
<\/script>
|
|
29
|
-
</body></html>`),l.close(),this.vpaidIframe.onload=()=>{const
|
|
29
|
+
</body></html>`),l.close(),this.vpaidIframe.onload=()=>{const u=this.vpaidIframe?.contentWindow?.getVPAIDAd?.()??null;if(!u){console.warn("[AdPlayer] VPAID creative not found in iframe, skipping"),this.hideLoadingCallback&&this.hideLoadingCallback(),t();return}this.vpaidCreative=u,u.handshakeVersion("2.0"),u.subscribe(t,"AdStopped"),u.subscribe(t,"AdVideoComplete"),u.subscribe(t,"AdSkipped"),u.subscribe(()=>{this.hideLoadingCallback&&this.hideLoadingCallback(),this.tracker.trackStart(e)},"AdStarted"),u.subscribe(()=>{r(new Error("VPAID AdError"))},"AdError"),u.initAd(s,o,"normal",-1,{AdParameters:""},{slot:n,videoSlot:this.adVideo,videoSlotCanAutoPlay:!0}),u.startAd()}})}createAdUI(){if(!this.mainVideoElement)return;const e=this.mainVideoElement.parentElement;if(!e)return;const t={showLabel:!0,showCountdown:!0,showSkipButton:!0,labelText:"Advertisement",labelPosition:"top-left",countdownPosition:"top-right",...this.config.ui};if(this.adContainer=document.createElement("div"),this.adContainer.className="virtus-ad-container",this.adContainer.style.cssText=`
|
|
30
30
|
position: absolute;
|
|
31
31
|
top: 0;
|
|
32
32
|
left: 0;
|
|
@@ -79,7 +79,7 @@
|
|
|
79
79
|
cursor: pointer;
|
|
80
80
|
z-index: 1001;
|
|
81
81
|
display: none;
|
|
82
|
-
`,this.skipButton.addEventListener("click",r=>{r.stopPropagation(),this.skip()}),this.adContainer.appendChild(this.skipButton)),e.appendChild(this.adContainer)}async playAdVideo(e){return new Promise((t,r)=>{if(!this.adVideo){r(new Error("Ad video element not found"));return}const n=this.adVideo;let s=!1;const o=()=>{n.play().catch(w=>{s||(m(),r(w))})},l=()=>this.tracker.trackStart(e),u=()=>{console.log("[AdPlayer] Ad video playing, hiding loading..."),this.hideLoadingCallback&&this.hideLoadingCallback()},d=()=>this.updateUI(e),h=()=>{s||(m(),t())};let p=!1;const g=()=>{if(p)return;if(p=!0,s){t();return}const w=n.error?.code;if(w===4){m(),t();return}m(),r(new Error(`Ad video playback error: ${n.error?.message??"Unknown"} (code: ${w})`))},m=()=>{if(!s){s=!0;try{n.removeEventListener("canplay",o),n.removeEventListener("play",l),n.removeEventListener("playing",u),n.removeEventListener("timeupdate",d),n.removeEventListener("ended",h),n.removeEventListener("error",g),n.pause(),n.parentNode&&n.parentNode.removeChild(n)}catch{}}};n.addEventListener("canplay",o),n.addEventListener("play",l),n.addEventListener("playing",u),n.addEventListener("timeupdate",d),n.addEventListener("ended",h),n.addEventListener("error",g),n.src=e.mediaFile,n.load(),setTimeout(()=>{this.state.isPlaying&&this.state.currentTime===0&&!s&&(m(),r(new Error("Ad video timeout")))},this.config.timeout||1e4)})}updateUI(e){if(!this.adVideo||!this.state.ad)return;const t=this.adVideo.currentTime;this.state.currentTime=t,this.state.remainingTime=e.duration-t,this.countdownElement&&(this.countdownElement.textContent=`Ad: ${Math.ceil(this.state.remainingTime)}s`);const r=this.config.skipAfter??5;t>=r&&(this.state.canSkip=!0,this.skipButton&&(this.skipButton.style.display="block"))}skip(){if(!(!this.state.canSkip||!this.state.ad)){if(console.log("[AdPlayer] Ad skipped"),this.tracker.trackSkip(this.state.ad),this.vpaidCreative){try{this.vpaidCreative.skipAd()}catch{}return}this.adVideo&&(this.adVideo.pause(),this.adVideo.currentTime=this.adVideo.duration,this.adVideo.dispatchEvent(new Event("ended")))}}handleClick(){this.state.ad&&(console.log("[AdPlayer] Ad clicked"),this.state.ad.clickThrough&&window.open(this.state.ad.clickThrough,"_blank","noopener,noreferrer"))}destroyAdUI(){if(console.log("[AdPlayer] Destroying ad UI..."),this.vpaidCreative){try{this.vpaidCreative.stopAd()}catch{}this.vpaidCreative=null}if(this.vpaidIframe&&(this.vpaidIframe.remove(),this.vpaidIframe=null),this.adVideo){try{const e=this.adVideo;e.pause(),e.muted=!0,e.parentNode&&e.parentNode.removeChild(e),e.removeAttribute("src"),e.src=""}catch{}this.adVideo=null}if(this.adContainer){try{this.adContainer.remove()}catch{}this.adContainer=null}if(this.companionContainer){try{this.companionContainer.remove()}catch{}this.companionContainer=null}this.skipButton=null,this.countdownElement=null,console.log("[AdPlayer] Ad UI destroyed")}getState(){return{...this.state}}destroy(){this.destroyAdUI(),this.state={isPlaying:!1,ad:null,position:null,currentTime:0,canSkip:!1,remainingTime:0}}}class Hr{player;config;vastParser;vmapParser;adPlayer;preRollPlayed=!1;midRollsPlayed=new Set;postRollPlayed=!1;vmapData=null;videoDuration=0;loadingContainer=null;onLoadingChange;constructor(e,t,r){this.player=e,this.config=t,this.onLoadingChange=r,this.vastParser=new Fr(t.timeout||5e3,t.maxWrapperDepth||5),this.vmapParser=new Ur(t.timeout||5e3),this.adPlayer=new Wr(e,t,()=>this.hideAdLoading()),console.log("[AdManager] Initialized with config:",t)}async waitForVideoElement(e=10,t=100){for(let r=0;r<e;r++){const n=this.player.getVideoElement();if(n)return console.log(`[AdManager] Video element ready after ${r} retries`),n;console.log(`[AdManager] Waiting for video element (attempt ${r+1}/${e})...`),await new Promise(s=>setTimeout(s,t))}return null}async setup(){if(!this.config.enabled){console.log("[AdManager] Ads disabled");return}if(!this.config.vastUrl&&!this.config.vmapUrl){console.log("[AdManager] No VAST URL or VMAP URL provided");return}const e=await this.waitForVideoElement();if(!e){console.error("[AdManager] Video element not available after retries. Cannot setup ads.");return}if(console.log("[AdManager] Video element ready:",e),this.config.vmapUrl)try{if(console.log("[AdManager] Loading VMAP from:",this.config.vmapUrl),this.vmapData=await this.vmapParser.parse(this.config.vmapUrl),console.log("[AdManager] VMAP parsed successfully:",{adBreakCount:this.vmapData.adBreaks.length,version:this.vmapData.version}),this.vmapData.adBreaks.length===0)if(console.warn("[AdManager] ⚠️ VMAP parsed but contains no ad breaks"),this.config.vastUrl)console.log("[AdManager] Falling back to VAST URL"),this.vmapData=null;else{console.log("[AdManager] No VAST URL fallback available, ads will be skipped");return}}catch(r){if(r instanceof Error?r.message.includes("timeout")?console.error("[AdManager] ⚠️ VMAP request timeout:",r.message):r.message.includes("network")?console.error("[AdManager] ⚠️ VMAP network error:",r.message):r.message.includes("empty")?console.error("[AdManager] ⚠️ VMAP response is empty:",r.message):r.message.includes("parse")?console.error("[AdManager] ⚠️ VMAP XML parse error:",r.message):console.error("[AdManager] ⚠️ VMAP error:",r.message):console.error("[AdManager] ⚠️ VMAP parse error:",r),this.config.vastUrl)console.log("[AdManager] Falling back to VAST URL");else{console.log("[AdManager] No VAST URL fallback available, ads will be skipped");return}}console.log("[AdManager] Setting up ad schedule"),this.player.events.on("loadedmetadata",r=>{this.videoDuration=r.duration||0}),this.player.events.once("play",async()=>{console.log("[AdManager] Play event received, pausing video for pre-roll..."),this.player.pause(),await this.handlePreRoll(),console.log("[AdManager] Pre-roll completed, resuming main video..."),setTimeout(()=>{const r=this.player.getVideoElement();console.log("[AdManager] Resuming main video, element:",r?.src),this.player.play().then(()=>{console.log("[AdManager] ✅ Main video resumed successfully")}).catch(n=>{console.error("[AdManager] ❌ Failed to auto-resume after pre-roll:",n),setTimeout(()=>{console.log("[AdManager] Retrying main video play..."),this.player.play().catch(s=>{console.error("[AdManager] Retry failed:",s)})},500)})},300)});const t=this.player.getState();console.log("[AdManager] Current video state after setup:",{isPlaying:t?.isPlaying,currentTime:t?.currentTime,preRollPlayed:this.preRollPlayed,hasPreRollUrl:!!this.getPreRollVastUrl()}),t?.isPlaying&&!this.preRollPlayed?(console.log("[AdManager] ✅ Video is already playing, triggering pre-roll immediately"),this.player.pause(),setTimeout(()=>{this.handlePreRoll()},100)):t?.isPlaying?this.preRollPlayed&&console.log("[AdManager] ⚠️ Pre-roll already played, skipping"):console.log("[AdManager] ✅ Video not playing yet, will wait for play event"),this.player.events.on("timeupdate",r=>{this.handleMidRoll(r.currentTime)}),this.player.events.on("ended",()=>{this.handlePostRoll()})}async handlePreRoll(){if(console.log("[AdManager] 🎬 handlePreRoll called",{preRollPlayed:this.preRollPlayed,hasVastUrl:!!this.getPreRollVastUrl()}),this.preRollPlayed){console.log("[AdManager] ⏭️ Pre-roll already played, skipping");return}const e=this.getPreRollVastUrl();if(!e){console.log("[AdManager] ⚠️ No VAST URL available for pre-roll");return}if(console.log("[AdManager] 📺 Pre-roll VAST URL:",e),this.preRollPlayed=!0,!this.player.getVideoElement()){console.error("[AdManager] ❌ Video element not available during pre-roll. Skipping ad.");return}console.log("[AdManager] ✅ Video element available, loading pre-roll ad..."),await this.playAd(e,"preroll")}async handleMidRoll(e){if(!this.vmapData)return;const t=this.vmapData.adBreaks.filter(n=>n.timeOffset>0&&n.timeOffset<this.videoDuration&&!this.midRollsPlayed.has(n.timeOffset)&&Math.abs(e-n.timeOffset)<1);if(t.length===0)return;const r=t[0];this.midRollsPlayed.add(r.timeOffset),console.log(`[AdManager] Loading mid-roll ad at ${r.timeOffset}s`),await this.playAd(r.vastUrl,"midroll")}async handlePostRoll(){if(this.postRollPlayed)return;const e=this.getPostRollVastUrl();e&&(this.postRollPlayed=!0,console.log("[AdManager] Loading post-roll ad"),await this.playAd(e,"postroll"))}getPreRollVastUrl(){if(this.vmapData){const e=this.vmapData.adBreaks.find(t=>t.timeOffset===0);if(e)return this.addCorrelator(e.vastUrl)}return this.addCorrelator(this.config.vastUrl||null)}addCorrelator(e){if(!e)return null;const t=Date.now();if(e.includes("correlator=")){const r=e.replace(/correlator=[^&]*/,`correlator=${t}`);return console.log("[AdManager] Updated correlator in URL:",t),r}else{const r=e.includes("?")?"&":"?",n=`${e}${r}correlator=${t}`;return console.log("[AdManager] Added correlator to URL:",t),n}}getPostRollVastUrl(){if(!this.vmapData)return null;const e=this.vmapData.adBreaks.find(t=>t.timeOffset===-1);return e?e.vastUrl:null}async playAd(e,t,r=0){console.log(`[AdManager] Playing ad at ${t} (attempt ${r+1}/3), URL:`,e),r===0&&(console.log("[AdManager] 🔄 Showing ad loading..."),this.showAdLoading());try{const o=await this.vastParser.parse(e);console.log("[AdManager] VAST parsed successfully:",o),await this.adPlayer.play(o,t)}catch(o){if(o instanceof Error){if(o.message.includes("No ads available")||o.message.includes("empty")||o.message.includes("Ad element is empty")){if(r<2)return console.warn(`[AdManager] ⚠️ No ads on attempt ${r+1}/3, retrying in 1500ms...`),await new Promise(l=>setTimeout(l,1500)),this.playAd(e,t,r+1);this.hideAdLoading(),console.log("[AdManager] ℹ️ No ads available after 3 attempts, continuing with main video");return}if(o.message.includes("Ad video playback error")||o.message.includes("timeout")){this.hideAdLoading(),console.warn(`[AdManager] ⚠️ Ad playback failed for ${t}:`,o.message),console.log("[AdManager] Skipping ad and continuing with main video");return}this.hideAdLoading(),console.warn(`[AdManager] ⚠️ Failed to play ${t} ad:`,o.message)}else this.hideAdLoading(),console.warn(`[AdManager] ⚠️ Failed to play ${t} ad:`,o);console.log("[AdManager] Continuing with main video despite ad error")}}skipAd(){this.adPlayer.skip()}handleAdClick(){this.adPlayer.handleClick()}getAdState(){return this.adPlayer.getState()}showAdLoading(){if(this.onLoadingChange){this.onLoadingChange(!0),console.log("[AdManager] External loading callback triggered (true)");return}const e=this.player.getVideoElement();if(!e)return;const t=e.parentElement;if(t){if(this.loadingContainer=document.createElement("div"),this.loadingContainer.className="virtus-ad-loading-container",this.loadingContainer.innerHTML=`
|
|
82
|
+
`,this.skipButton.addEventListener("click",r=>{r.stopPropagation(),this.skip()}),this.adContainer.appendChild(this.skipButton)),e.appendChild(this.adContainer)}async playAdVideo(e){return new Promise((t,r)=>{if(!this.adVideo){r(new Error("Ad video element not found"));return}const n=this.adVideo;let s=!1;const o=()=>{n.play().catch(E=>{s||(m(),r(E))})},l=()=>this.tracker.trackStart(e),d=()=>{console.log("[AdPlayer] Ad video playing, hiding loading..."),this.hideLoadingCallback&&this.hideLoadingCallback()},u=()=>this.updateUI(e),h=()=>{s||(m(),t())};let p=!1;const g=()=>{if(p)return;if(p=!0,s){t();return}const E=n.error?.code;if(E===4){m(),t();return}m(),r(new Error(`Ad video playback error: ${n.error?.message??"Unknown"} (code: ${E})`))},m=()=>{if(!s){s=!0;try{n.removeEventListener("canplay",o),n.removeEventListener("play",l),n.removeEventListener("playing",d),n.removeEventListener("timeupdate",u),n.removeEventListener("ended",h),n.removeEventListener("error",g),n.pause(),n.parentNode&&n.parentNode.removeChild(n)}catch{}}};n.addEventListener("canplay",o),n.addEventListener("play",l),n.addEventListener("playing",d),n.addEventListener("timeupdate",u),n.addEventListener("ended",h),n.addEventListener("error",g),n.src=e.mediaFile,n.load(),setTimeout(()=>{this.state.isPlaying&&this.state.currentTime===0&&!s&&(m(),r(new Error("Ad video timeout")))},this.config.timeout||1e4)})}updateUI(e){if(!this.adVideo||!this.state.ad)return;const t=this.adVideo.currentTime;this.state.currentTime=t,this.state.remainingTime=e.duration-t,this.countdownElement&&(this.countdownElement.textContent=`Ad: ${Math.ceil(this.state.remainingTime)}s`);const r=this.config.skipAfter??5;t>=r&&(this.state.canSkip=!0,this.skipButton&&(this.skipButton.style.display="block"))}skip(){if(!(!this.state.canSkip||!this.state.ad)){if(console.log("[AdPlayer] Ad skipped"),this.tracker.trackSkip(this.state.ad),this.vpaidCreative){try{this.vpaidCreative.skipAd()}catch{}return}this.adVideo&&(this.adVideo.pause(),this.adVideo.currentTime=this.adVideo.duration,this.adVideo.dispatchEvent(new Event("ended")))}}handleClick(){this.state.ad&&(console.log("[AdPlayer] Ad clicked"),this.state.ad.clickThrough&&window.open(this.state.ad.clickThrough,"_blank","noopener,noreferrer"))}destroyAdUI(){if(console.log("[AdPlayer] Destroying ad UI..."),this.vpaidCreative){try{this.vpaidCreative.stopAd()}catch{}this.vpaidCreative=null}if(this.vpaidIframe&&(this.vpaidIframe.remove(),this.vpaidIframe=null),this.adVideo){try{const e=this.adVideo;e.pause(),e.muted=!0,e.parentNode&&e.parentNode.removeChild(e),e.removeAttribute("src"),e.src=""}catch{}this.adVideo=null}if(this.adContainer){try{this.adContainer.remove()}catch{}this.adContainer=null}if(this.companionContainer){try{this.companionContainer.remove()}catch{}this.companionContainer=null}this.skipButton=null,this.countdownElement=null,console.log("[AdPlayer] Ad UI destroyed")}getState(){return{...this.state}}destroy(){this.destroyAdUI(),this.state={isPlaying:!1,ad:null,position:null,currentTime:0,canSkip:!1,remainingTime:0}}}class Hr{player;config;vastParser;vmapParser;adPlayer;preRollPlayed=!1;midRollsPlayed=new Set;postRollPlayed=!1;vmapData=null;videoDuration=0;loadingContainer=null;onLoadingChange;constructor(e,t,r){this.player=e,this.config=t,this.onLoadingChange=r,this.vastParser=new Fr(t.timeout||5e3,t.maxWrapperDepth||5),this.vmapParser=new Ur(t.timeout||5e3),this.adPlayer=new Wr(e,t,()=>this.hideAdLoading()),console.log("[AdManager] Initialized with config:",t)}async waitForVideoElement(e=10,t=100){for(let r=0;r<e;r++){const n=this.player.getVideoElement();if(n)return console.log(`[AdManager] Video element ready after ${r} retries`),n;console.log(`[AdManager] Waiting for video element (attempt ${r+1}/${e})...`),await new Promise(s=>setTimeout(s,t))}return null}async setup(){if(!this.config.enabled){console.log("[AdManager] Ads disabled");return}if(!this.config.vastUrl&&!this.config.vmapUrl){console.log("[AdManager] No VAST URL or VMAP URL provided");return}const e=await this.waitForVideoElement();if(!e){console.error("[AdManager] Video element not available after retries. Cannot setup ads.");return}if(console.log("[AdManager] Video element ready:",e),this.config.vmapUrl)try{if(console.log("[AdManager] Loading VMAP from:",this.config.vmapUrl),this.vmapData=await this.vmapParser.parse(this.config.vmapUrl),console.log("[AdManager] VMAP parsed successfully:",{adBreakCount:this.vmapData.adBreaks.length,version:this.vmapData.version}),this.vmapData.adBreaks.length===0)if(console.warn("[AdManager] ⚠️ VMAP parsed but contains no ad breaks"),this.config.vastUrl)console.log("[AdManager] Falling back to VAST URL"),this.vmapData=null;else{console.log("[AdManager] No VAST URL fallback available, ads will be skipped");return}}catch(r){if(r instanceof Error?r.message.includes("timeout")?console.error("[AdManager] ⚠️ VMAP request timeout:",r.message):r.message.includes("network")?console.error("[AdManager] ⚠️ VMAP network error:",r.message):r.message.includes("empty")?console.error("[AdManager] ⚠️ VMAP response is empty:",r.message):r.message.includes("parse")?console.error("[AdManager] ⚠️ VMAP XML parse error:",r.message):console.error("[AdManager] ⚠️ VMAP error:",r.message):console.error("[AdManager] ⚠️ VMAP parse error:",r),this.config.vastUrl)console.log("[AdManager] Falling back to VAST URL");else{console.log("[AdManager] No VAST URL fallback available, ads will be skipped");return}}console.log("[AdManager] Setting up ad schedule"),this.player.events.on("loadedmetadata",r=>{this.videoDuration=r.duration||0}),this.player.events.once("play",async()=>{console.log("[AdManager] Play event received, pausing video for pre-roll..."),this.player.pause(),await this.handlePreRoll(),console.log("[AdManager] Pre-roll completed, resuming main video..."),setTimeout(()=>{const r=this.player.getVideoElement();console.log("[AdManager] Resuming main video, element:",r?.src),this.player.play().then(()=>{console.log("[AdManager] ✅ Main video resumed successfully")}).catch(n=>{console.error("[AdManager] ❌ Failed to auto-resume after pre-roll:",n),setTimeout(()=>{console.log("[AdManager] Retrying main video play..."),this.player.play().catch(s=>{console.error("[AdManager] Retry failed:",s)})},500)})},300)});const t=this.player.getState();console.log("[AdManager] Current video state after setup:",{isPlaying:t?.isPlaying,currentTime:t?.currentTime,preRollPlayed:this.preRollPlayed,hasPreRollUrl:!!this.getPreRollVastUrl()}),t?.isPlaying&&!this.preRollPlayed?(console.log("[AdManager] ✅ Video is already playing, triggering pre-roll immediately"),this.player.pause(),setTimeout(()=>{this.handlePreRoll()},100)):t?.isPlaying?this.preRollPlayed&&console.log("[AdManager] ⚠️ Pre-roll already played, skipping"):console.log("[AdManager] ✅ Video not playing yet, will wait for play event"),this.player.events.on("timeupdate",r=>{this.handleMidRoll(r.currentTime)}),this.player.events.on("ended",()=>{this.handlePostRoll()})}async handlePreRoll(){if(console.log("[AdManager] 🎬 handlePreRoll called",{preRollPlayed:this.preRollPlayed,hasVastUrl:!!this.getPreRollVastUrl()}),this.preRollPlayed){console.log("[AdManager] ⏭️ Pre-roll already played, skipping");return}const e=this.getPreRollVastUrl();if(!e){console.log("[AdManager] ⚠️ No VAST URL available for pre-roll");return}if(console.log("[AdManager] 📺 Pre-roll VAST URL:",e),this.preRollPlayed=!0,!this.player.getVideoElement()){console.error("[AdManager] ❌ Video element not available during pre-roll. Skipping ad.");return}console.log("[AdManager] ✅ Video element available, loading pre-roll ad..."),await this.playAd(e,"preroll")}async handleMidRoll(e){if(!this.vmapData)return;const t=this.vmapData.adBreaks.filter(n=>n.timeOffset>0&&n.timeOffset<this.videoDuration&&!this.midRollsPlayed.has(n.timeOffset)&&Math.abs(e-n.timeOffset)<1);if(t.length===0)return;const r=t[0];this.midRollsPlayed.add(r.timeOffset),console.log(`[AdManager] Loading mid-roll ad at ${r.timeOffset}s`),await this.playAd(r.vastUrl,"midroll")}async handlePostRoll(){if(this.postRollPlayed)return;const e=this.getPostRollVastUrl();e&&(this.postRollPlayed=!0,console.log("[AdManager] Loading post-roll ad"),await this.playAd(e,"postroll"))}getPreRollVastUrl(){if(this.vmapData){const e=this.vmapData.adBreaks.find(t=>t.timeOffset===0);if(e)return this.addCorrelator(e.vastUrl)}return this.addCorrelator(this.config.vastUrl||null)}addCorrelator(e){if(!e)return null;const t=Date.now();if(e.includes("correlator=")){const r=e.replace(/correlator=[^&]*/,`correlator=${t}`);return console.log("[AdManager] Updated correlator in URL:",t),r}else{const r=e.includes("?")?"&":"?",n=`${e}${r}correlator=${t}`;return console.log("[AdManager] Added correlator to URL:",t),n}}getPostRollVastUrl(){if(!this.vmapData)return null;const e=this.vmapData.adBreaks.find(t=>t.timeOffset===-1);return e?e.vastUrl:null}async playAd(e,t,r=0){console.log(`[AdManager] Playing ad at ${t} (attempt ${r+1}/3), URL:`,e),r===0&&(console.log("[AdManager] 🔄 Showing ad loading..."),this.showAdLoading());try{const o=await this.vastParser.parse(e);console.log("[AdManager] VAST parsed successfully:",o),await this.adPlayer.play(o,t)}catch(o){if(o instanceof Error){if(o.message.includes("No ads available")||o.message.includes("empty")||o.message.includes("Ad element is empty")){if(r<2)return console.warn(`[AdManager] ⚠️ No ads on attempt ${r+1}/3, retrying in 1500ms...`),await new Promise(l=>setTimeout(l,1500)),this.playAd(e,t,r+1);this.hideAdLoading(),console.log("[AdManager] ℹ️ No ads available after 3 attempts, continuing with main video");return}if(o.message.includes("Ad video playback error")||o.message.includes("timeout")){this.hideAdLoading(),console.warn(`[AdManager] ⚠️ Ad playback failed for ${t}:`,o.message),console.log("[AdManager] Skipping ad and continuing with main video");return}this.hideAdLoading(),console.warn(`[AdManager] ⚠️ Failed to play ${t} ad:`,o.message)}else this.hideAdLoading(),console.warn(`[AdManager] ⚠️ Failed to play ${t} ad:`,o);console.log("[AdManager] Continuing with main video despite ad error")}}skipAd(){this.adPlayer.skip()}handleAdClick(){this.adPlayer.handleClick()}getAdState(){return this.adPlayer.getState()}showAdLoading(){if(this.onLoadingChange){this.onLoadingChange(!0),console.log("[AdManager] External loading callback triggered (true)");return}const e=this.player.getVideoElement();if(!e)return;const t=e.parentElement;if(t){if(this.loadingContainer=document.createElement("div"),this.loadingContainer.className="virtus-ad-loading-container",this.loadingContainer.innerHTML=`
|
|
83
83
|
<div style="
|
|
84
84
|
position: absolute;
|
|
85
85
|
top: 0;
|
|
@@ -113,13 +113,13 @@
|
|
|
113
113
|
0% { transform: rotate(0deg); }
|
|
114
114
|
100% { transform: rotate(360deg); }
|
|
115
115
|
}
|
|
116
|
-
`,document.head.appendChild(r)}t.appendChild(this.loadingContainer),console.log("[AdManager] Loading spinner shown")}}hideAdLoading(){if(this.onLoadingChange){this.onLoadingChange(!1),console.log("[AdManager] External loading callback triggered (false)");return}this.loadingContainer&&(this.loadingContainer.remove(),this.loadingContainer=null,console.log("[AdManager] Loading spinner hidden"))}destroy(){this.hideAdLoading(),this.adPlayer.destroy(),this.preRollPlayed=!1,this.midRollsPlayed.clear(),this.postRollPlayed=!1,this.vmapData=null,console.log("[AdManager] Destroyed")}}const ht={bottomOffset:110,fontSize:18,color:"#ffffff",background:"rgba(0,0,0,0.75)"},pt=c.createContext({style:ht,setStyle:()=>{}});function zr({children:a}){const[e,t]=c.useState(ht),r=n=>t(s=>({...s,...n}));return i.jsx(pt.Provider,{value:{style:e,setStyle:r},children:a})}function gt(){return c.useContext(pt)}function qr({videoElement:a}){const{style:e}=gt(),[t,r]=c.useState([]),n=c.useRef(""),s=c.useRef(0);return c.useEffect(()=>{if(!a)return;const o=()=>{const l=a.textTracks,
|
|
116
|
+
`,document.head.appendChild(r)}t.appendChild(this.loadingContainer),console.log("[AdManager] Loading spinner shown")}}hideAdLoading(){if(this.onLoadingChange){this.onLoadingChange(!1),console.log("[AdManager] External loading callback triggered (false)");return}this.loadingContainer&&(this.loadingContainer.remove(),this.loadingContainer=null,console.log("[AdManager] Loading spinner hidden"))}destroy(){this.hideAdLoading(),this.adPlayer.destroy(),this.preRollPlayed=!1,this.midRollsPlayed.clear(),this.postRollPlayed=!1,this.vmapData=null,console.log("[AdManager] Destroyed")}}const ht={bottomOffset:110,fontSize:18,color:"#ffffff",background:"rgba(0,0,0,0.75)"},pt=c.createContext({style:ht,setStyle:()=>{}});function zr({children:a}){const[e,t]=c.useState(ht),r=n=>t(s=>({...s,...n}));return i.jsx(pt.Provider,{value:{style:e,setStyle:r},children:a})}function gt(){return c.useContext(pt)}function qr({videoElement:a}){const{style:e}=gt(),[t,r]=c.useState([]),n=c.useRef(""),s=c.useRef(0);return c.useEffect(()=>{if(!a)return;const o=()=>{const l=a.textTracks,d=[];for(let h=0;h<l.length;h++){const p=l[h];if(p.kind!=="subtitles"&&p.kind!=="captions"||p.mode==="disabled")continue;p.mode==="showing"&&(p.mode="hidden");const g=p.activeCues;if(g)for(let m=0;m<g.length;m++){const E=g[m];E.text&&d.push(E.text)}}const u=d.join("\0");u!==n.current&&(n.current=u,r(d)),s.current=requestAnimationFrame(o)};return s.current=requestAnimationFrame(o),()=>{cancelAnimationFrame(s.current)}},[a]),t.length===0?null:i.jsx("div",{"aria-live":"polite",style:{position:"absolute",bottom:e.bottomOffset,left:"50%",transform:"translateX(-50%)",textAlign:"center",pointerEvents:"none",zIndex:200,maxWidth:"85%",display:"flex",flexDirection:"column",alignItems:"center",gap:"2px"},children:t.map((o,l)=>i.jsx("span",{style:{display:"inline-block",fontSize:e.fontSize,lineHeight:1.4,color:e.color,background:e.background||"transparent",padding:e.background?"2px 10px":"0",borderRadius:4,whiteSpace:"pre-wrap",wordBreak:"break-word",textShadow:e.background?"none":"0 1px 4px rgba(0,0,0,0.9), 0 0 8px rgba(0,0,0,0.8)"},dangerouslySetInnerHTML:{__html:o}},l))})}const be=c.createContext(!0);function ft({src:a="https://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4",defaultControls:e=!1,autoplay:t=!1,muted:r=!1,poster:n,className:s,children:o,config:l,onAdLoading:d,onNextEpisode:u,nextEpisodeTitle:h,nextEpisodeThumbnail:p,endCardCountdown:g=5,crossOrigin:m}){const E=c.useRef(null),j=c.useRef(null),[S,A]=c.useState(null),b=c.useRef(null),[y,q]=c.useState(!1),[z,L]=c.useState(!1),w=c.useCallback(()=>L(!0),[]),R=c.useCallback(()=>L(!1),[]),[N,x]=c.useState(!1),{onTouchStart:C,onTouchMove:I,onTouchEnd:$,gestureHint:K}=ut({player:S,skipSec:10}),{isActive:M}=Nr({timeout:3e3,initialVisible:!0});$r({player:S,seekStep:10,enabled:!0,onShowShortcuts:w});const _=c.useMemo(()=>!l?.ads?.enabled||!l.ads.vastUrl&&!l.ads.vmapUrl?null:{enabled:!0,vastUrl:l.ads.vastUrl,vmapUrl:l.ads.vmapUrl,skipAfter:l.ads.skipAfter,timeout:l.ads.timeout,maxWrapperDepth:l.ads.maxWrapperDepth},[l?.ads?.enabled,l?.ads?.vastUrl,l?.ads?.vmapUrl,l?.ads?.skipAfter,l?.ads?.timeout,l?.ads?.maxWrapperDepth]);c.useEffect(()=>{if(!j.current||!E.current)return;console.log("[Player] Initializing PlayerCore");const V=new ne(j.current);return ne.preloadEngines(),V.container=E.current,A(V),()=>{console.log("[Player] Cleanup called - destroying PlayerCore"),b.current&&(console.log("[Player] Destroying AdManager"),b.current.destroy(),b.current=null),V.destroy(),A(null)}},[]),c.useEffect(()=>{if(!S||!_)return;console.log("[Player] Setting up ads");const V=X=>{q(X),d?.(X)},Y=new Hr(S,_,V);return b.current=Y,Y.setup().catch(X=>{console.error("[Player] Failed to setup ads:",X)}),()=>{b.current&&(console.log("[Player] Cleaning up ads"),b.current.destroy(),b.current=null)}},[S,_]),c.useEffect(()=>{!S||!l||S.setConfig(l)},[S,l]);const T=c.useMemo(()=>l?.drm??null,[l?.drm]);return c.useEffect(()=>{!S||!T?.enabled||S.setupDrm(T)},[S,T]),c.useEffect(()=>{S&&a&&(console.log("[Player] Setting source:",a),S.setSource(a).catch(V=>{console.error("[Player] setSource failed:",V)}))},[S,a]),c.useEffect(()=>{if(!S||!u)return;const V=S.getVideoElement();if(!V)return;const Y=()=>x(!0);return V.addEventListener("ended",Y),()=>V.removeEventListener("ended",Y)},[S,u]),i.jsxs(zr,{children:[i.jsxs("div",{ref:E,role:"region","aria-label":"Video Player",className:`playron-wrapper ${s||""}`,onTouchStart:C,onTouchMove:I,onTouchEnd:$,style:{position:"relative",backgroundColor:"#000",overflow:"hidden",cursor:M?"default":"none"},children:[i.jsx("div",{"aria-live":"polite","aria-atomic":"true",style:{position:"absolute",width:"1px",height:"1px",padding:0,margin:"-1px",overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",border:0}}),i.jsx("video",{ref:j,className:`virtus-video-element ${s||""}`,style:{width:"100%",height:"100%",display:"block",aspectRatio:"16/9",objectFit:"cover",objectPosition:"center"},autoPlay:t,muted:r,controls:e,poster:n,playsInline:!0,crossOrigin:m,tabIndex:e?0:-1}),S?i.jsx(at,{playerInstance:S,children:i.jsxs(be.Provider,{value:M,children:[i.jsx(qr,{videoElement:j.current}),i.jsx(gr,{config:l,isAdLoading:y}),i.jsx(dt,{type:K?.type??null,value:K?.value??""}),i.jsx(_r,{drmConfig:l?.drm}),i.jsx(lt,{isOpen:z,onClose:R}),u&&i.jsx(ct,{isVisible:N,onNextEpisode:()=>{x(!1),u()},onDismiss:()=>x(!1),countdownSec:g,nextTitle:h,thumbnail:p}),o]})}):null]}),i.jsx("style",{children:`
|
|
117
117
|
@keyframes gestureHintFade {
|
|
118
118
|
0% { opacity: 1; }
|
|
119
119
|
60% { opacity: 1; }
|
|
120
120
|
100% { opacity: 0; }
|
|
121
121
|
}
|
|
122
|
-
`})]})}function mt({children:a}){const e=c.useContext(be);return i.jsx("div",{className:"virtus-controlbar",style:{position:"absolute",bottom:0,left:0,right:0,display:"flex",alignItems:"center",gap:"12px",padding:"12px 20px",background:"linear-gradient(to top, rgba(0, 0, 0, 0.8) 0%, rgba(0, 0, 0, 0.4) 50%, transparent 100%)",zIndex:50,opacity:e?1:0,transition:"opacity 0.3s ease",pointerEvents:e?"auto":"none"},children:a})}const Kr="_playButton_u2ehs_3",Yr={playButton:Kr};function yt({className:a,onClick:e,iconSize:t=24,hoverBackground:r,pauseIcon:n,playIcon:s,style:o,...l}){const
|
|
122
|
+
`})]})}function mt({children:a}){const e=c.useContext(be);return i.jsx("div",{className:"virtus-controlbar",style:{position:"absolute",bottom:0,left:0,right:0,display:"flex",alignItems:"center",gap:"12px",padding:"12px 20px",background:"linear-gradient(to top, rgba(0, 0, 0, 0.8) 0%, rgba(0, 0, 0, 0.4) 50%, transparent 100%)",zIndex:50,opacity:e?1:0,transition:"opacity 0.3s ease",pointerEvents:e?"auto":"none"},children:a})}const Kr="_playButton_u2ehs_3",Yr={playButton:Kr};function yt({className:a,onClick:e,iconSize:t=24,hoverBackground:r,pauseIcon:n,playIcon:s,style:o,...l}){const d=O(g=>g.isPlaying),{togglePlay:u}=U(),h=async g=>{try{await u()}catch(m){console.error("Play/Pause error:",m)}e?.(g)},p=typeof r=="string"?r:r===!1?"transparent":void 0;return i.jsx("button",{className:`virtus-btn virtus-play-button ${Yr.playButton} ${a||""}`,"aria-label":d?"Pause":"Play",onClick:h,style:{...p!==void 0?{"--btn-hover-bg":p}:{},...o},...l,children:d?n??i.jsx("svg",{"aria-hidden":"true",xmlns:"http://www.w3.org/2000/svg",width:t,height:t,fill:"currentColor",viewBox:"0 0 24 24",children:i.jsx("path",{fillRule:"evenodd",d:"M8 5a2 2 0 0 0-2 2v10a2 2 0 0 0 2 2h1a2 2 0 0 0 2-2V7a2 2 0 0 0-2-2H8Zm7 0a2 2 0 0 0-2 2v10a2 2 0 0 0 2 2h1a2 2 0 0 0 2-2V7a2 2 0 0 0-2-2h-1Z",clipRule:"evenodd"})}):s??i.jsx("svg",{"aria-hidden":"true",xmlns:"http://www.w3.org/2000/svg",width:t,height:t,fill:"currentColor",viewBox:"0 0 24 24",children:i.jsx("path",{fillRule:"evenodd",d:"M8.6 5.2A1 1 0 0 0 7 6v12a1 1 0 0 0 1.6.8l8-6a1 1 0 0 0 0-1.6l-8-6Z",clipRule:"evenodd"})})})}const Xr="_controlButton_14cpd_3",ge={controlButton:Xr};function Gr({className:a,onClick:e,...t}){const r=O(o=>o.isMuted),{toggleMute:n}=U(),s=o=>{n(),e?.(o)};return i.jsx("button",{className:`virtus-btn virtus-mute-button ${ge.controlButton} ${a||""}`,"aria-label":r?"Unmute":"Mute",onClick:s,...t,children:r?i.jsx("svg",{"aria-hidden":"true",xmlns:"http://www.w3.org/2000/svg",width:"20",height:"20",fill:"currentColor",viewBox:"0 0 24 24",children:i.jsx("path",{d:"M5.707 4.293a1 1 0 0 0-1.414 1.414l14 14a1 1 0 0 0 1.414-1.414l-.004-.005C21.57 16.498 22 13.938 22 12a9.972 9.972 0 0 0-2.929-7.071 1 1 0 1 0-1.414 1.414A7.972 7.972 0 0 1 20 12c0 1.752-.403 3.636-1.712 4.873l-1.433-1.433C17.616 14.37 18 13.107 18 12c0-1.678-.69-3.197-1.8-4.285a1 1 0 1 0-1.4 1.428A3.985 3.985 0 0 1 16 12c0 .606-.195 1.335-.59 1.996L13 11.586V6.135c0-1.696-1.978-2.622-3.28-1.536L7.698 6.284l-1.99-1.991ZM4 8h.586L13 16.414v1.451c0 1.696-1.978 2.622-3.28 1.536L5.638 16H4a2 2 0 0 1-2-2v-4a2 2 0 0 1 2-2Z"})}):i.jsxs("svg",{"aria-hidden":"true",xmlns:"http://www.w3.org/2000/svg",width:"20",height:"20",fill:"currentColor",viewBox:"0 0 24 24",children:[i.jsx("path",{d:"M13.5 4.06c0-1.336-1.616-2.005-2.56-1.06l-4.5 4.5H4.508c-1.141 0-2.318.664-2.66 1.905A9.76 9.76 0 0 0 1.5 12c0 .898.121 1.768.35 2.595.341 1.24 1.518 1.905 2.659 1.905h1.93l4.5 4.5c.945.945 2.561.276 2.561-1.06V4.06ZM18.584 5.106a.75.75 0 0 1 1.06 0 11.5 11.5 0 0 1 0 13.588.75.75 0 0 1-1.06-1.06 10 10 0 0 0 0-11.468.75.75 0 0 1 0-1.06Z"}),i.jsx("path",{d:"M15.932 7.757a.75.75 0 0 1 1.061 0 6.5 6.5 0 0 1 0 8.486.75.75 0 0 1-1.06-1.06 5 5 0 0 0 0-6.366.75.75 0 0 1 0-1.06Z"})]})})}function vt({className:a,onClick:e,iconSize:t=18,hoverBackground:r,enterIcon:n,exitIcon:s,style:o,...l}){const{toggleFullscreen:d}=U(),[u,h]=c.useState(!1);c.useEffect(()=>{const m=()=>{h(!!document.fullscreenElement)};return document.addEventListener("fullscreenchange",m),()=>{document.removeEventListener("fullscreenchange",m)}},[]);const p=m=>{d(),e?.(m)},g=typeof r=="string"?r:r===!1?"transparent":void 0;return i.jsx("button",{className:`virtus-btn virtus-fullscreen-button ${ge.controlButton} ${a||""}`,"aria-label":u?"Exit Fullscreen":"Fullscreen",onClick:p,style:{...g!==void 0?{"--btn-hover-bg":g}:{},...o},...l,children:u?s??i.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",width:t,height:t,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:i.jsx("path",{d:"M8 3v3a2 2 0 0 1-2 2H3m18 0h-3a2 2 0 0 1-2-2V3m0 18v-3a2 2 0 0 1 2-2h3M3 16h3a2 2 0 0 1 2 2v3"})}):n??i.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",width:t,height:t,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:i.jsx("path",{d:"M8 3H5a2 2 0 0 0-2 2v3m18 0V5a2 2 0 0 0-2-2h-3m0 18h3a2 2 0 0 0 2-2v-3M3 16v3a2 2 0 0 0 2 2h3"})})})}function xt({className:a,onClick:e,...t}){const{togglePip:r}=U(),[n,s]=c.useState(!1);c.useEffect(()=>{const l=()=>{s(!!document.pictureInPictureElement)};return document.addEventListener("enterpictureinpicture",l),document.addEventListener("leavepictureinpicture",l),()=>{document.removeEventListener("enterpictureinpicture",l),document.removeEventListener("leavepictureinpicture",l)}},[]);const o=async l=>{try{await r()}catch(d){console.error("PiP toggle error:",d)}e?.(l)};return i.jsx("button",{className:`virtus-btn virtus-pip-button ${ge.controlButton} ${a||""}`,"aria-label":n?"Exit Picture-in-Picture":"Picture-in-Picture",onClick:o,...t,children:i.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[i.jsx("rect",{x:"2",y:"3",width:"20",height:"14",rx:"2"}),i.jsx("rect",{x:"13",y:"13",width:"8",height:"6",rx:"1",fill:"currentColor"})]})})}function Qr(){const{toggleTheaterMode:a,isTheaterMode:e}=U(),[t,r]=c.useState(e()),n=()=>{a(),r(!t)};return c.useEffect(()=>{const s=o=>{r(o.detail.isTheaterMode)};return window.addEventListener("virtus:theatermodechange",s),()=>{window.removeEventListener("virtus:theatermodechange",s)}},[]),i.jsx("button",{className:"virtus-theater-button",onClick:n,style:{background:t?"rgba(59, 130, 246, 0.3)":"transparent",border:"none",color:"white",cursor:"pointer",padding:"8px",borderRadius:"8px",display:"flex",alignItems:"center",justifyContent:"center",width:"40px",height:"40px",transition:"all 0.2s ease",position:"relative"},onMouseEnter:s=>{s.currentTarget.style.background=t?"rgba(59, 130, 246, 0.4)":"rgba(255, 255, 255, 0.15)",s.currentTarget.style.transform="scale(1.05)"},onMouseLeave:s=>{s.currentTarget.style.background=t?"rgba(59, 130, 246, 0.3)":"transparent",s.currentTarget.style.transform="scale(1)"},title:t?"Exit Theater Mode":"Theater Mode",children:t?i.jsx("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:i.jsx("path",{d:"M8 3v3a2 2 0 0 1-2 2H3m18 0h-3a2 2 0 0 1-2-2V3m0 18v-3a2 2 0 0 1 2-2h3M3 16h3a2 2 0 0 1 2 2v3"})}):i.jsx("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:i.jsx("path",{d:"M15 3h6v6M9 21H3v-6M21 3l-7 7M3 21l7-7"})})})}function Zr(a,e,t=!0){c.useEffect(()=>{if(!t)return;const r=s=>{a.current&&!a.current.contains(s.target)&&e()},n=s=>{s.key==="Escape"&&e()};return document.addEventListener("mousedown",r),document.addEventListener("keydown",n),()=>{document.removeEventListener("mousedown",r),document.removeEventListener("keydown",n)}},[a,e,t])}const Ee=c.createContext({isOpen:!1,toggle:()=>{},close:()=>{},open:()=>{}});function bt({children:a}){const[e,t]=c.useState(!1),r=c.useRef(null),n=()=>t(d=>!d),s=()=>t(!1),o=()=>t(!0);Zr(r,s,e);const l={isOpen:e,toggle:n,close:s,open:o};return i.jsx(Ee.Provider,{value:l,children:i.jsx("div",{ref:r,style:{position:"relative",display:"inline-block"},children:a})})}function Et({children:a}){const{toggle:e,close:t}=c.useContext(Ee);return i.jsx("div",{onClick:e,onKeyDown:r=>{(r.key==="Enter"||r.key===" ")&&(r.preventDefault(),e()),r.key==="Escape"&&t()},style:{display:"inline-block"},children:a})}function wt({children:a,title:e,placement:t="top"}){const{isOpen:r}=c.useContext(Ee);if(!r)return null;const n=()=>{const o={position:"absolute",bottom:"50px",zIndex:9999};switch(t){case"top-right":return{...o,right:0};case"top-left":return{...o,left:0};default:return{...o,left:"50%",transform:"translateX(-50%)"}}},s=()=>{switch(t){case"top-right":return"dropdownFadeInRight";case"top-left":return"dropdownFadeInLeft";default:return"dropdownFadeInCenter"}};return i.jsxs("div",{role:"menu","aria-label":e,onKeyDown:o=>{o.key==="Escape"&&(o.stopPropagation(),close())},style:{...n(),minWidth:"200px",background:"rgba(0, 0, 0, 0.95)",backdropFilter:"blur(10px)",borderRadius:"12px",boxShadow:"0 8px 32px rgba(0, 0, 0, 0.5)",border:"1px solid rgba(255, 255, 255, 0.1)",overflow:"hidden",animation:`${s()} 0.2s ease-out`},children:[e&&i.jsx("div",{style:{padding:"12px 16px",borderBottom:"1px solid rgba(255, 255, 255, 0.1)",color:"#fff",fontSize:"13px",fontWeight:600,fontFamily:"system-ui, -apple-system, sans-serif"},children:e}),i.jsx("div",{style:{maxHeight:"300px",overflowY:"auto"},children:a}),i.jsx("style",{children:`
|
|
123
123
|
@keyframes dropdownFadeInCenter {
|
|
124
124
|
from {
|
|
125
125
|
opacity: 0;
|
|
@@ -152,7 +152,7 @@
|
|
|
152
152
|
transform: translateY(0) scale(1);
|
|
153
153
|
}
|
|
154
154
|
}
|
|
155
|
-
`})]})}function _e({children:a,onClick:e,selected:t=!1,disabled:r=!1,closeOnClick:n=!0}){const{close:s}=c.useContext(Ee),o=()=>{r||(e?.(),n&&s())};return i.jsxs("button",{role:"menuitem","aria-disabled":r,"aria-checked":t,onClick:o,style:{width:"100%",textAlign:"left",padding:"10px 16px",color:r?"rgba(255, 255, 255, 0.4)":"#fff",fontSize:"14px",fontFamily:"system-ui, -apple-system, sans-serif",cursor:r?"not-allowed":"pointer",background:t?"rgba(59, 130, 246, 0.2)":"transparent",border:"none",transition:"background 0.15s ease",display:"flex",alignItems:"center",gap:"8px",fontWeight:t?600:400,outline:"none"},onMouseEnter:l=>{r||(l.currentTarget.style.background=t?"rgba(59, 130, 246, 0.3)":"rgba(255, 255, 255, 0.1)")},onMouseLeave:l=>{l.currentTarget.style.background=t?"rgba(59, 130, 246, 0.2)":"transparent"},onFocus:l=>{r||(l.currentTarget.style.background="rgba(255, 255, 255, 0.1)")},onBlur:l=>{l.currentTarget.style.background=t?"rgba(59, 130, 246, 0.2)":"transparent"},children:[t&&i.jsx("svg",{"aria-hidden":"true",width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"#3b82f6",strokeWidth:"3",children:i.jsx("polyline",{points:"20 6 9 17 4 12"})}),a]})}function Jr(){const a=U(),e=O(),[t,r]=c.useState(1),[n,s]=c.useState(!1),o=[.25,.5,.75,1,1.25,1.5,1.75,2];c.useEffect(()=>{e?.playbackRate!==void 0&&r(e.playbackRate)},[e?.playbackRate]);const l=
|
|
155
|
+
`})]})}function _e({children:a,onClick:e,selected:t=!1,disabled:r=!1,closeOnClick:n=!0}){const{close:s}=c.useContext(Ee),o=()=>{r||(e?.(),n&&s())};return i.jsxs("button",{role:"menuitem","aria-disabled":r,"aria-checked":t,onClick:o,style:{width:"100%",textAlign:"left",padding:"10px 16px",color:r?"rgba(255, 255, 255, 0.4)":"#fff",fontSize:"14px",fontFamily:"system-ui, -apple-system, sans-serif",cursor:r?"not-allowed":"pointer",background:t?"rgba(59, 130, 246, 0.2)":"transparent",border:"none",transition:"background 0.15s ease",display:"flex",alignItems:"center",gap:"8px",fontWeight:t?600:400,outline:"none"},onMouseEnter:l=>{r||(l.currentTarget.style.background=t?"rgba(59, 130, 246, 0.3)":"rgba(255, 255, 255, 0.1)")},onMouseLeave:l=>{l.currentTarget.style.background=t?"rgba(59, 130, 246, 0.2)":"transparent"},onFocus:l=>{r||(l.currentTarget.style.background="rgba(255, 255, 255, 0.1)")},onBlur:l=>{l.currentTarget.style.background=t?"rgba(59, 130, 246, 0.2)":"transparent"},children:[t&&i.jsx("svg",{"aria-hidden":"true",width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"#3b82f6",strokeWidth:"3",children:i.jsx("polyline",{points:"20 6 9 17 4 12"})}),a]})}function Jr(){const a=U(),e=O(),[t,r]=c.useState(1),[n,s]=c.useState(!1),o=[.25,.5,.75,1,1.25,1.5,1.75,2];c.useEffect(()=>{e?.playbackRate!==void 0&&r(e.playbackRate)},[e?.playbackRate]);const l=u=>{a.setPlaybackRate(u),r(u)},d=()=>{const u=!n;s(u),a.setLoop(u)};return i.jsxs(bt,{children:[i.jsx(Et,{children:i.jsx("button",{className:"virtus-btn virtus-settings-button","aria-label":"Settings",style:{background:"rgba(255, 255, 255, 0.1)",border:"none",borderRadius:"8px",width:"40px",height:"40px",display:"flex",alignItems:"center",justifyContent:"center",cursor:"pointer",transition:"all 0.2s ease"},onMouseEnter:u=>{u.currentTarget.style.background="rgba(255, 255, 255, 0.2)",u.currentTarget.style.transform="scale(1.05)"},onMouseLeave:u=>{u.currentTarget.style.background="rgba(255, 255, 255, 0.1)",u.currentTarget.style.transform="scale(1)"},children:i.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"#fff",strokeWidth:"2",children:[i.jsx("circle",{cx:"12",cy:"12",r:"3"}),i.jsx("path",{d:"M12 1v6m0 6v6m9-9h-6m-6 0H3m15.4-6.4l-4.3 4.3M9.9 14.8l-4.2 4.2m0-12.4l4.2 4.2m4.3 4.2l4.2 4.2"})]})})}),i.jsxs(wt,{title:"Settings",placement:"top-right",children:[i.jsx("div",{style:{padding:"8px 16px 4px",color:"rgba(255, 255, 255, 0.6)",fontSize:"12px",fontWeight:600},children:"Playback Speed"}),o.map(u=>i.jsxs(_e,{selected:t===u,onClick:()=>l(u),children:[u,"x"]},u)),i.jsx("div",{style:{height:"1px",background:"rgba(255, 255, 255, 0.1)",margin:"8px 0"}}),i.jsxs(_e,{selected:n,onClick:d,children:["Loop ",n?"On":"Off"]})]})]})}const ei="_timeDisplay_1wupc_3",ti="_currentTime_1wupc_16",ri="_separator_1wupc_20",ii="_duration_1wupc_25",le={timeDisplay:ei,currentTime:ti,separator:ri,duration:ii},Re=a=>{if(!isFinite(a)||isNaN(a))return"0:00";const e=Math.floor(a/3600),t=Math.floor(a%3600/60),r=Math.floor(a%60);return e>0?`${e}:${t.toString().padStart(2,"0")}:${r.toString().padStart(2,"0")}`:`${t}:${r.toString().padStart(2,"0")}`};function kt({className:a,...e}){const{currentTime:t,duration:r,isLive:n}=O();return n?i.jsx("div",{className:`virtus-time-display ${le.timeDisplay} ${a||""}`,...e,children:i.jsx("span",{className:le.currentTime,style:{color:"rgba(255, 255, 255, 0.7)",fontSize:"12px"},children:Re(t)})}):i.jsxs("div",{className:`virtus-time-display ${le.timeDisplay} ${a||""}`,...e,children:[i.jsx("span",{className:le.currentTime,children:Re(t)}),i.jsx("span",{className:le.separator,children:"/"}),i.jsx("span",{className:le.duration,children:Re(r)})]})}function St(){const{isLive:a,isAtLiveEdge:e}=O(),{seekToLiveEdge:t}=U();return!a||e?null:i.jsxs("button",{className:"virtus-jump-to-live","aria-label":"Jump to live",onClick:t,style:{display:"flex",alignItems:"center",gap:"6px",padding:"4px 10px",background:"rgba(255, 32, 32, 0.9)",border:"none",borderRadius:"4px",color:"#fff",fontSize:"12px",fontWeight:"700",letterSpacing:"0.5px",cursor:"pointer",transition:"background 0.15s ease, box-shadow 0.15s ease",whiteSpace:"nowrap",flexShrink:0,boxShadow:"0 0 12px rgba(255,32,32,0.45)"},onMouseEnter:r=>{r.currentTarget.style.background="rgba(255, 32, 32, 1)",r.currentTarget.style.boxShadow="0 0 18px rgba(255,32,32,0.65)"},onMouseLeave:r=>{r.currentTarget.style.background="rgba(255, 32, 32, 0.9)",r.currentTarget.style.boxShadow="0 0 12px rgba(255,32,32,0.45)"},children:[i.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"currentColor","aria-hidden":"true",children:i.jsx("path",{d:"M5.59 7.41L10.18 12l-4.59 4.59L7 18l6-6-6-6zM16 6h2v12h-2z"})}),"LIVE"]})}function At(){const{isLive:a,isAtLiveEdge:e,liveLatency:t}=O();if(!a||e||!t||t<1)return null;const r=Math.round(t);return i.jsxs("span",{className:"virtus-live-latency","aria-live":"polite",style:{fontSize:"11px",fontWeight:"500",color:"rgba(255, 255, 255, 0.7)",whiteSpace:"nowrap",flexShrink:0},children:[r,"s behind live"]})}const ni="_container_6dw0q_3",si="_skipButton_6dw0q_11",De={container:ni,skipButton:si};function oi({introOutro:a}){const{currentTime:e}=O(),{seekTo:t}=U(),[r,n]=c.useState(!1),[s,o]=c.useState(!1);c.useEffect(()=>{if(a){if(a.intro){const u=e>=a.intro.start&&e<a.intro.end;n(u)}if(a.outro){const u=e>=a.outro.start&&e<a.outro.end;o(u)}}},[e,a]);const l=c.useCallback(()=>{a?.intro&&(t(a.intro.end),n(!1))},[a,t]),d=c.useCallback(()=>{a?.outro&&(t(a.outro.end),o(!1))},[a,t]);return!r&&!s?null:i.jsxs("div",{className:De.container,children:[r&&i.jsxs("button",{onClick:l,className:De.skipButton,children:[i.jsx("span",{children:"Skip Intro"}),i.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"currentColor",children:i.jsx("path",{d:"M4 18l8.5-6L4 6v12zm9-12v12l8.5-6L13 6z"})})]}),s&&i.jsxs("button",{onClick:d,className:De.skipButton,children:[i.jsx("span",{children:"Skip Outro"}),i.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"currentColor",children:i.jsx("path",{d:"M4 18l8.5-6L4 6v12zm9-12v12l8.5-6L13 6z"})})]}),i.jsx("style",{children:`
|
|
156
156
|
@keyframes slideInRight {
|
|
157
157
|
from {
|
|
158
158
|
opacity: 0;
|
|
@@ -163,11 +163,11 @@
|
|
|
163
163
|
transform: translateX(0);
|
|
164
164
|
}
|
|
165
165
|
}
|
|
166
|
-
`})]})}const We={goal:{icon:"⚽",color:"#22c55e"},yellow:{icon:"🟨",color:"#fbbf24"},red:{icon:"🟥",color:"#ef4444"},substitution:{icon:"🔄",color:"#3b82f6"},kickoff:{icon:"⏱️",color:"#9ca3af"},highlight:{icon:"⭐",color:"#f59e0b"},bookmark:{icon:"📌",color:"#8b5cf6"},comment:{icon:"💬",color:"#06b6d4"},event:{icon:"🎯",color:"#ec4899"}};function ai({event:a,position:e,size:t=12,showTooltip:r=!0,onClick:n}){const[s,o]=c.useState(!1),l=We[a.type]||We.event,
|
|
166
|
+
`})]})}const We={goal:{icon:"⚽",color:"#22c55e"},yellow:{icon:"🟨",color:"#fbbf24"},red:{icon:"🟥",color:"#ef4444"},substitution:{icon:"🔄",color:"#3b82f6"},kickoff:{icon:"⏱️",color:"#9ca3af"},highlight:{icon:"⭐",color:"#f59e0b"},bookmark:{icon:"📌",color:"#8b5cf6"},comment:{icon:"💬",color:"#06b6d4"},event:{icon:"🎯",color:"#ec4899"}};function ai({event:a,position:e,size:t=12,showTooltip:r=!0,onClick:n}){const[s,o]=c.useState(!1),l=We[a.type]||We.event,d=a.icon||l.icon,u=a.color||l.color,h=p=>{p.stopPropagation(),n&&n(a.time)};return i.jsxs("div",{style:{position:"absolute",left:`${e}%`,top:"50%",transform:s?"translate(-50%, -50%) scale(1.2)":"translate(-50%, -50%)",cursor:"pointer",zIndex:s?12:10,transition:"all 0.2s ease",pointerEvents:"auto"},onClick:h,onMouseEnter:()=>o(!0),onMouseLeave:()=>o(!1),children:[i.jsx("div",{style:{width:`${t}px`,height:`${t}px`,borderRadius:"50%",display:"flex",alignItems:"center",justifyContent:"center",backgroundColor:u,border:"2px solid rgba(255, 255, 255, 0.9)",boxShadow:s?"0 4px 16px rgba(0, 0, 0, 0.4)":"0 2px 8px rgba(0, 0, 0, 0.4)",transition:"transform 0.2s cubic-bezier(0.4, 0, 0.2, 1)",transform:s?"scale(1.3)":"scale(1)"},children:i.jsx("span",{style:{fontSize:`${t*.8}px`,lineHeight:1,userSelect:"none",display:"inline-block",transform:"translateY(-1px)"},children:d})}),r&&s&&a.label&&i.jsx("div",{style:{position:"absolute",bottom:"calc(100% + 12px)",left:"50%",transform:"translateX(-50%)",padding:"6px 10px",background:"rgba(0, 0, 0, 0.85)",color:"#fff",fontSize:"12px",fontWeight:"500",whiteSpace:"nowrap",borderRadius:"4px",boxShadow:"0 2px 8px rgba(0, 0, 0, 0.5)",pointerEvents:"none",zIndex:15},children:a.label})]})}class Ct{cues=[];loaded=!1;async load(e){try{const t=await fetch(e);if(!t.ok)return;const r=await t.text();this.cues=this.parseVtt(r,e),this.loaded=!0}catch{}}getThumbnailAt(e){if(!this.loaded||this.cues.length===0)return null;let t=0,r=this.cues.length-1;for(;t<=r;){const n=t+r>>>1,s=this.cues[n];if(e<s.startTime)r=n-1;else if(e>=s.endTime)t=n+1;else return s}return null}isLoaded(){return this.loaded}destroy(){this.cues=[],this.loaded=!1}parseVtt(e,t){const r=[],n=e.replace(/\r\n/g,`
|
|
167
167
|
`).replace(/\r/g,`
|
|
168
168
|
`).split(`
|
|
169
|
-
`);let s=0;for(;s<n.length&&!n[s].includes("-->");)s++;for(;s<n.length;){const o=n[s].trim();if(o.includes("-->")){const[l,
|
|
170
|
-
`).trim();if(g&&
|
|
169
|
+
`);let s=0;for(;s<n.length&&!n[s].includes("-->");)s++;for(;s<n.length;){const o=n[s].trim();if(o.includes("-->")){const[l,d]=o.split("-->").map(m=>m.trim()),u=this.parseTime(l),h=this.parseTime(d);s++;const p=[];for(;s<n.length&&n[s].trim()!==""&&!n[s].includes("-->");)p.push(n[s].trim()),s++;const g=p.join(`
|
|
170
|
+
`).trim();if(g&&u>=0&&h>u){const m=this.parseCueLine(g,t);m&&r.push({startTime:u,endTime:h,...m})}}else s++}return r}parseCueLine(e,t){const r=e.lastIndexOf("#xywh=");let n,s=0,o=0,l=0,d=0;if(r!==-1){n=e.slice(0,r);const h=e.slice(r+6).split(",").map(Number);h.length===4&&h.every(p=>!isNaN(p))&&([s,o,l,d]=h)}else n=e;const u=this.resolveUrl(n.trim(),t);return u?{url:u,x:s,y:o,w:l,h:d}:null}resolveUrl(e,t){if(e.startsWith("http://")||e.startsWith("https://")||e.startsWith("//"))return e;try{return new URL(e,t).href}catch{return e}}parseTime(e){const t=e.trim().split(":").map(Number);return t.length===3?t[0]*3600+t[1]*60+t[2]:t.length===2?t[0]*60+t[1]:-1}}const He=160,li=90;function Tt({mode:a="vod",chapters:e=[],timelineEvents:t=[],showTimelineMarkers:r=!1,markerSize:n=12,thumbnailsVttUrl:s,seekBarStyle:o}){const l=c.useContext(be),d=c.useRef(null),[u,h]=c.useState(!1),[p,g]=c.useState(null),[m,E]=c.useState(null),[j,S]=c.useState([]),A=c.useRef(null),{currentTime:b,duration:y,isLive:q,isPlaying:z,playbackRate:L}=O(),{seekTo:w,getDVRRange:R,getBufferedRanges:N}=U(),[x,C]=c.useState(b),I=c.useRef(null),$=c.useRef({time:b,ts:performance.now()});c.useEffect(()=>{$.current={time:b,ts:performance.now()},C(b)},[b]);const K=c.useCallback(()=>{if(z){const{time:v,ts:P}=$.current,D=L??1,B=(performance.now()-P)/1e3,G=Math.min(y||1/0,v+B*D);C(G)}I.current=requestAnimationFrame(K)},[z,L,y]);c.useEffect(()=>(I.current=requestAnimationFrame(K),()=>{I.current!==null&&cancelAnimationFrame(I.current)}),[K]),c.useEffect(()=>{if(!s)return;const v=new Ct;return A.current=v,v.load(s),()=>{v.destroy(),A.current=null}},[s]),c.useEffect(()=>{const v=setInterval(()=>{S(N())},500);return()=>clearInterval(v)},[N]);const M=a==="live"||!!q,_=M?R():null,T=_!==null&&_.end-_.start>5,V=T?_.end-_.start:0,Y=T&&V>0?(x-_.start)/V*100:0,X=M?Math.min(100,Math.max(0,Y)):y>0?x/y*100:0,fe=o?.trackColor??"rgba(255, 255, 255, 0.3)",te=o?.progressColor??(M?"#ff2020":"#6366f1"),se=o?.bufferedColor??"rgba(255, 255, 255, 0.25)",W=o?.handleColor??"#ffffff",we=o?.height??4,oe=o?.borderRadius??2,ce=o?.showHandle!==!1,ke=o?.showTooltip!==!1,de=o?.paddingX??20,Se=o?.paddingY??0,Ae=o?.bottom??64,re=v=>{if(!isFinite(v)||isNaN(v))return"0:00";const P=Math.floor(v/3600),D=Math.floor(v%3600/60),B=Math.floor(v%60);return P>0?`${P}:${D.toString().padStart(2,"0")}:${B.toString().padStart(2,"0")}`:`${D}:${B.toString().padStart(2,"0")}`},ue=v=>{if(!d.current)return 0;const P=d.current.getBoundingClientRect(),D=(v.clientX-P.left)/P.width;return Math.max(0,Math.min(1,D))},me=v=>{if(!(M&&!T)){if(M&&T){w(_.start+v*V);return}y!==0&&w(v*y)}},Ce=v=>{if(M&&!T)return;v.preventDefault(),h(!0);const P=ue(v);me(P)},Te=v=>{if(!d.current)return;const P=ue(v);if(g(P),A.current){const D=T?_.start+P*V:P*y;E(A.current.getThumbnailAt(D))}},Me=()=>{g(null),E(null)};return c.useEffect(()=>{if(!u)return;const v=D=>{if(!d.current)return;const B=ue(D);g(B),me(B)},P=()=>{h(!1)};return window.addEventListener("mousemove",v),window.addEventListener("mouseup",P),()=>{window.removeEventListener("mousemove",v),window.removeEventListener("mouseup",P)}},[u,y]),i.jsxs("div",{style:{position:"absolute",bottom:`${Ae}px`,left:0,right:0,padding:`${Se}px ${de}px`,zIndex:50,opacity:l?1:0,transition:"opacity 0.3s ease",pointerEvents:l?"auto":"none"},children:[M&&!T&&i.jsxs("div",{style:{position:"absolute",left:"50%",top:"50%",transform:"translate(-50%, -50%)",display:"flex",alignItems:"center",gap:"8px",padding:"6px 18px",background:"rgba(255, 30, 30, 0.95)",borderRadius:"20px",fontSize:"12px",fontWeight:"700",color:"#fff",letterSpacing:"1.5px",zIndex:10,boxShadow:"0 0 20px rgba(255, 30, 30, 0.6), 0 2px 8px rgba(0,0,0,0.4)"},children:[i.jsx("div",{style:{width:"8px",height:"8px",borderRadius:"50%",background:"#fff",boxShadow:"0 0 6px rgba(255,255,255,0.8)",animation:"pulse 1.5s ease-in-out infinite"}}),i.jsx("span",{children:"LIVE"})]}),M&&T&&i.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px",marginBottom:"4px"},children:[i.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"5px",flexShrink:0},children:[i.jsx("div",{style:{width:"8px",height:"8px",borderRadius:"50%",background:"#ff2020",boxShadow:"0 0 10px rgba(255, 32, 32, 0.8)",animation:"pulse 1.5s ease-in-out infinite"}}),i.jsx("span",{style:{fontSize:"11px",fontWeight:"700",color:"#fff",letterSpacing:"1px"},children:"LIVE"})]}),i.jsx(At,{}),i.jsx("div",{style:{flex:1}}),i.jsx(St,{})]}),i.jsxs("div",{ref:d,role:M&&!T?void 0:"slider",tabIndex:M&&!T?void 0:0,"aria-label":M?"DVR seek":"Seek","aria-valuemin":M&&!T?void 0:T?Math.floor(_.start):0,"aria-valuemax":M&&!T?void 0:T?Math.floor(_.end):Math.floor(y)||0,"aria-valuenow":M&&!T?void 0:Math.floor(b),"aria-valuetext":M&&!T?"LIVE":T?`${re(b)} (DVR)`:`${re(b)} of ${re(y)}`,"aria-disabled":M&&!T?!0:void 0,onMouseDown:Ce,onMouseMove:Te,onMouseLeave:Me,onKeyDown:v=>{if(M&&!T)return;const P=5,D=30,B=T?_.start:0,G=T?_.end:y;if(G!==0)switch(v.key){case"ArrowLeft":case"ArrowDown":v.preventDefault(),w(Math.max(B,b-P));break;case"ArrowRight":case"ArrowUp":v.preventDefault(),w(Math.min(G,b+P));break;case"PageDown":v.preventDefault(),w(Math.max(B,b-D));break;case"PageUp":v.preventDefault(),w(Math.min(G,b+D));break;case"Home":v.preventDefault(),w(B);break;case"End":v.preventDefault(),w(G);break}},style:{width:"100%",height:"32px",display:"flex",alignItems:"center",cursor:M&&!T?"default":"pointer",position:"relative",outline:"none"},children:[i.jsxs("div",{style:{position:"absolute",left:0,right:0,height:`${we}px`,backgroundColor:fe,borderRadius:`${oe}px`},children:[!M&&j.map((v,P)=>{if(y<=0)return null;const D=v.start/y*100,B=(v.end-v.start)/y*100;return i.jsx("div",{style:{position:"absolute",left:`${D}%`,top:0,height:"100%",width:`${B}%`,backgroundColor:se,borderRadius:`${oe}px`,pointerEvents:"none"}},P)}),i.jsx("div",{style:{position:"absolute",left:0,top:0,height:"100%",width:`${X}%`,backgroundColor:te,borderRadius:`${oe}px`,transition:"none"}}),!M&&e.map(v=>{const P=y>0?v.startTime/y*100:0;return i.jsx("div",{style:{position:"absolute",left:`${P}%`,top:"50%",transform:"translate(-50%, -50%)",width:"3px",height:"12px",backgroundColor:"rgba(255, 255, 255, 0.8)",borderRadius:"1px",pointerEvents:"none"}},v.id)}),r&&!M&&y>0&&t.map((v,P)=>{const D=v.time/y*100;return D<0||D>100?null:i.jsx(ai,{event:v,position:D,size:n,showTooltip:!0,onClick:B=>w(B)},`timeline-${P}-${v.time}`)}),T&&i.jsx("div",{style:{position:"absolute",right:0,top:"50%",transform:"translateY(-50%)",width:"3px",height:"14px",backgroundColor:"#ff2020",boxShadow:"0 0 8px rgba(255,32,32,0.7)",borderRadius:"1px",pointerEvents:"none",zIndex:5},title:"Live edge"}),ce&&(!M||T)&&p!==null&&i.jsx("div",{style:{position:"absolute",left:`${p*100}%`,top:"50%",transform:"translate(-50%, -50%)",width:"14px",height:"14px",backgroundColor:W,borderRadius:"50%",boxShadow:"0 2px 8px rgba(0, 0, 0, 0.3)",pointerEvents:"none",zIndex:999}}),ce&&(!M||T)&&i.jsx("div",{style:{position:"absolute",left:`${X}%`,top:"50%",transform:"translate(-50%, -50%)",width:u?"16px":"14px",height:u?"16px":"14px",backgroundColor:W,borderRadius:"50%",boxShadow:"0 2px 8px rgba(0, 0, 0, 0.3)",pointerEvents:"none",zIndex:1e3,opacity:u||p!==null?1:0,transition:u?"none":"all 0.15s ease"}})]}),ke&&(!M||T)&&p!==null&&(()=>{const v=T?_.start+p*V:p*y,P=d.current?.offsetWidth??0,D=p*100,B=p*P,G=He/2;let ae="-50%";return B<G?ae="0%":P-B<G&&(ae="-100%"),m?i.jsxs("div",{style:{position:"absolute",left:`${D}%`,bottom:"24px",transform:`translateX(${ae})`,pointerEvents:"none",zIndex:2e3,display:"flex",flexDirection:"column",alignItems:"center",gap:"4px"},children:[i.jsx("div",{style:{width:`${m.w||He}px`,height:`${m.h||li}px`,backgroundImage:`url("${m.url}")`,backgroundPosition:m.w?`-${m.x}px -${m.y}px`:"center center",backgroundRepeat:"no-repeat",backgroundSize:m.w?"auto":"cover",borderRadius:"4px",boxShadow:"0 4px 16px rgba(0,0,0,0.6)",border:"2px solid rgba(255,255,255,0.15)",overflow:"hidden",flexShrink:0}}),i.jsx("div",{style:{padding:"2px 8px",backgroundColor:"rgba(0,0,0,0.85)",color:"#fff",fontSize:"12px",fontWeight:"600",borderRadius:"3px",whiteSpace:"nowrap"},children:re(v)})]}):i.jsx("div",{style:{position:"absolute",left:`${D}%`,bottom:"20px",transform:`translateX(${ae})`,padding:"4px 8px",backgroundColor:"rgba(0,0,0,0.85)",color:"#fff",fontSize:"12px",fontWeight:"500",borderRadius:"4px",whiteSpace:"nowrap",pointerEvents:"none",zIndex:2e3},children:re(v)})})()]}),i.jsx("style",{children:`
|
|
171
171
|
@keyframes pulse {
|
|
172
172
|
0%, 100% {
|
|
173
173
|
opacity: 1;
|
|
@@ -176,17 +176,17 @@
|
|
|
176
176
|
opacity: 0.5;
|
|
177
177
|
}
|
|
178
178
|
}
|
|
179
|
-
`})]})}function Mt({seconds:a=15,iconSize:e=24,hoverBackground:t,icon:r}){const{skipBackward:n}=U(),{isLive:s}=O();if(s)return null;const o=typeof t=="string"?t:t===!1?"transparent":void 0;return i.jsx("button",{className:`virtus-btn virtus-skip-backward-button ${ge.controlButton}`,"aria-label":`Skip Backward ${a}s`,onClick:()=>n(a),style:{position:"relative",...o!==void 0?{"--btn-hover-bg":o}:{}},children:r??i.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",width:e,height:e,viewBox:"0 0 24 24",fill:"none",children:[i.jsx("path",{d:"M12 2C6.5 2 2 6.5 2 12s4.5 10 10 10 10-4.5 10-10",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round"}),i.jsx("path",{d:"M2 12l-2-2m2 2l2-2",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round"}),i.jsx("text",{x:"12",y:"16",fontSize:"10",fill:"currentColor",textAnchor:"middle",fontWeight:"bold",children:a})]})})}function Pt({seconds:a=15,iconSize:e=24,hoverBackground:t,icon:r}){const{skipForward:n}=U(),{isLive:s}=O();if(s)return null;const o=typeof t=="string"?t:t===!1?"transparent":void 0;return i.jsx("button",{className:`virtus-btn virtus-skip-forward-button ${ge.controlButton}`,"aria-label":`Skip Forward ${a}s`,onClick:()=>n(a),style:{position:"relative",...o!==void 0?{"--btn-hover-bg":o}:{}},children:r??i.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",width:e,height:e,viewBox:"0 0 24 24",fill:"none",children:[i.jsx("path",{d:"M12 2c5.5 0 10 4.5 10 10s-4.5 10-10 10-10-4.5-10-10",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round"}),i.jsx("path",{d:"M22 12l2-2m-2 2l-2-2",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round"}),i.jsx("text",{x:"12",y:"16",fontSize:"10",fill:"currentColor",textAnchor:"middle",fontWeight:"bold",children:a})]})})}function Lt({sliderDirection:a="right",theme:e,iconSize:t=20,hoverBackground:r}){const n={sliderBackground:e?.sliderBackground??"rgba(10, 10, 20, 0.88)",borderColor:e?.borderColor??"rgba(255,255,255,0.1)",buttonBackground:e?.buttonBackground??"rgba(255,255,255,0.1)",buttonHoverBackground:e?.buttonHoverBackground??"rgba(255,255,255,0.2)",iconColor:e?.iconColor??"#fff",trackColor:e?.trackColor??"rgba(255,255,255,0.3)",fillColor:e?.fillColor??"#3b82f6",handleColor:e?.handleColor??"#fff"},{isMuted:s,volume:o}=O(),{toggleMute:l,setVolume:u}=U(),[d,h]=c.useState(!1),[p,g]=c.useState(!1),m=c.useRef(null),w=a==="top"||a==="bottom",L=c.useCallback((x,A)=>{if(!m.current)return;const _=m.current.getBoundingClientRect(),W=w?Math.max(0,Math.min(1,1-(A-_.top)/_.height)):Math.max(0,Math.min(1,(x-_.left)/_.width));u(W)},[u,w]),b=c.useCallback(x=>{g(!0),s&&l(),L(x.clientX,x.clientY)},[L,s,l]);c.useEffect(()=>{if(!p)return;const x=_=>L(_.clientX,_.clientY),A=()=>g(!1);return window.addEventListener("mousemove",x),window.addEventListener("mouseup",A),()=>{window.removeEventListener("mousemove",x),window.removeEventListener("mouseup",A)}},[p,L]);const M=p?o:s?0:o,E=d||p,y={position:"absolute",opacity:E?1:0,transition:"all 0.25s ease",pointerEvents:E?"auto":"none",zIndex:10,background:n.sliderBackground,backdropFilter:"blur(12px)",boxShadow:"4px 0 16px rgba(0,0,0,0.5)",overflow:"hidden"},q=(()=>{const x=`1px solid ${n.borderColor}`;switch(a){case"left":return{...y,right:"40px",top:"0",width:E?"118px":"0px",height:"40px",paddingRight:"8px",borderRadius:"8px 0 0 8px",border:x,borderRight:"none"};case"top":return{...y,bottom:"40px",left:"0",width:"40px",height:E?"118px":"0px",paddingBottom:"8px",borderRadius:"8px 8px 0 0",border:x,borderBottom:"none"};case"bottom":return{...y,top:"40px",left:"0",width:"40px",height:E?"118px":"0px",paddingTop:"8px",borderRadius:"0 0 8px 8px",border:x,borderTop:"none"};default:return{...y,left:"40px",top:"0",width:E?"118px":"0px",height:"40px",paddingLeft:"8px",borderRadius:"0 8px 8px 0",border:x,borderLeft:"none"}}})(),D=w?{width:"40px",height:"110px",display:"flex",justifyContent:"center",alignItems:"center",cursor:"pointer",position:"relative",outline:"none"}:{width:"110px",height:"40px",display:"flex",alignItems:"center",cursor:"pointer",position:"relative",paddingRight:"8px",outline:"none"},S=w?{width:"4px",height:"100%",backgroundColor:n.trackColor,borderRadius:"2px",position:"relative"}:{width:"100%",height:"4px",backgroundColor:n.trackColor,borderRadius:"2px",position:"relative"},I=w?{position:"absolute",bottom:0,left:0,right:0,height:`${M*100}%`,backgroundColor:n.fillColor,borderRadius:"2px",transition:p?"none":"height 0.1s ease"}:{position:"absolute",left:0,top:0,bottom:0,width:`${M*100}%`,backgroundColor:n.fillColor,borderRadius:"2px",transition:p?"none":"width 0.1s ease"},j=p?14:12,$=w?{position:"absolute",bottom:`calc(${M*100}% - ${M*j}px)`,left:"50%",transform:"translateX(-50%)",width:`${j}px`,height:`${j}px`,backgroundColor:n.handleColor,borderRadius:"50%",boxShadow:"0 2px 4px rgba(0,0,0,0.3)",transition:p?"none":"all 0.2s ease"}:{position:"absolute",left:`calc(${M*100}% - ${M*j}px)`,top:"50%",transform:"translateY(-50%)",width:`${j}px`,height:`${j}px`,backgroundColor:n.handleColor,borderRadius:"50%",boxShadow:"0 2px 4px rgba(0,0,0,0.3)",transition:p?"none":"all 0.2s ease"};return i.jsxs("div",{className:"virtus-volume-control",style:{position:"relative",display:"flex",alignItems:"center",height:"40px",width:"40px"},onMouseLeave:()=>{p||h(!1)},children:[i.jsx("button",{className:"virtus-btn virtus-mute-button","aria-label":s?"Unmute":"Mute",onClick:l,style:{background:r===!1?"transparent":n.buttonBackground,border:"none",borderRadius:"8px",width:"40px",height:"40px",display:"flex",alignItems:"center",justifyContent:"center",cursor:"pointer",transition:"all 0.2s ease",flexShrink:0,position:"relative",zIndex:1},onMouseEnter:x=>{h(!0),x.currentTarget.style.background=typeof r=="string"?r:r===!1?"transparent":n.buttonHoverBackground,x.currentTarget.style.transform="scale(1.05)"},onMouseLeave:x=>{x.currentTarget.style.background=r===!1?"transparent":n.buttonBackground,x.currentTarget.style.transform="scale(1)"},children:s||o===0?i.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",width:t,height:t,fill:n.iconColor,viewBox:"0 0 24 24",children:i.jsx("path",{d:"M13.5 4.06c0-1.336-1.616-2.005-2.56-1.06l-4.5 4.5H4.508c-1.141 0-2.318.664-2.66 1.905A9.76 9.76 0 0 0 1.5 12c0 .898.121 1.768.35 2.595.341 1.24 1.518 1.905 2.659 1.905h1.93l4.5 4.5c.945.945 2.561.276 2.561-1.06V4.06ZM17.78 9.22a.75.75 0 1 0-1.06 1.06L18.44 12l-1.72 1.72a.75.75 0 1 0 1.06 1.06l1.72-1.72 1.72 1.72a.75.75 0 1 0 1.06-1.06L20.56 12l1.72-1.72a.75.75 0 1 0-1.06-1.06l-1.72 1.72-1.72-1.72Z"})}):o<.5?i.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",width:t,height:t,fill:n.iconColor,viewBox:"0 0 24 24",children:i.jsx("path",{d:"M13.5 4.06c0-1.336-1.616-2.005-2.56-1.06l-4.5 4.5H4.508c-1.141 0-2.318.664-2.66 1.905A9.76 9.76 0 0 0 1.5 12c0 .898.121 1.768.35 2.595.341 1.24 1.518 1.905 2.659 1.905h1.93l4.5 4.5c.945.945 2.561.276 2.561-1.06V4.06Z"})}):i.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",width:t,height:t,fill:n.iconColor,viewBox:"0 0 24 24",children:[i.jsx("path",{d:"M13.5 4.06c0-1.336-1.616-2.005-2.56-1.06l-4.5 4.5H4.508c-1.141 0-2.318.664-2.66 1.905A9.76 9.76 0 0 0 1.5 12c0 .898.121 1.768.35 2.595.341 1.24 1.518 1.905 2.659 1.905h1.93l4.5 4.5c.945.945 2.561.276 2.561-1.06V4.06Z"}),i.jsx("path",{d:"M18.584 5.106a.75.75 0 0 1 1.06 0 11.5 11.5 0 0 1 0 13.588.75.75 0 0 1-1.06-1.06 10 10 0 0 0 0-11.468.75.75 0 0 1 0-1.06Z"}),i.jsx("path",{d:"M15.932 7.757a.75.75 0 0 1 1.061 0 6.5 6.5 0 0 1 0 8.486.75.75 0 0 1-1.06-1.06 5 5 0 0 0 0-6.366.75.75 0 0 1 0-1.06Z"})]})}),i.jsx("div",{onMouseEnter:()=>h(!0),style:q,children:i.jsx("div",{ref:m,role:"slider",tabIndex:0,"aria-label":"Volume","aria-valuemin":0,"aria-valuemax":100,"aria-valuenow":Math.round(M*100),"aria-valuetext":s?"Muted":`${Math.round(M*100)}%`,onMouseDown:b,onKeyDown:x=>{const W=s?0:o;switch(x.key){case"ArrowRight":case"ArrowUp":x.preventDefault(),u(Math.min(1,W+.05));break;case"ArrowLeft":case"ArrowDown":x.preventDefault(),u(Math.max(0,W-.05));break;case"PageUp":x.preventDefault(),u(Math.min(1,W+.2));break;case"PageDown":x.preventDefault(),u(Math.max(0,W-.2));break;case"Home":x.preventDefault(),u(0);break;case"End":x.preventDefault(),u(1);break;case"m":case"M":x.preventDefault(),l();break}},style:D,children:i.jsxs("div",{style:S,children:[i.jsx("div",{style:I}),i.jsx("div",{style:$})]})})})]})}const ci=[.25,.5,.75,1,1.25,1.5,1.75,2];function di(){const{setPlaybackRate:a}=U(),[e,t]=c.useState(1),r=c.useCallback(s=>{a(s),t(s)},[a]),n=e===1?"1×":`${e}×`;return i.jsxs(bt,{children:[i.jsx(Et,{children:i.jsx("button",{className:"virtus-speed-button","aria-label":`Playback speed: ${n}`,"aria-haspopup":"true",style:{background:"transparent",border:"none",color:"white",cursor:"pointer",padding:"8px",borderRadius:"8px",display:"flex",alignItems:"center",justifyContent:"center",height:"40px",minWidth:"40px",transition:"all 0.2s ease",fontSize:"13px",fontWeight:"600",letterSpacing:"-0.3px",whiteSpace:"nowrap"},onMouseEnter:s=>{s.currentTarget.style.background="rgba(255, 255, 255, 0.15)",s.currentTarget.style.transform="scale(1.05)"},onMouseLeave:s=>{s.currentTarget.style.background="transparent",s.currentTarget.style.transform="scale(1)"},title:"Playback speed",children:n})}),i.jsx(wt,{placement:"top-right",children:i.jsxs("div",{style:{minWidth:"130px"},children:[i.jsx("div",{style:{padding:"8px 12px",fontSize:"12px",fontWeight:"600",color:"rgba(255, 255, 255, 0.6)",borderBottom:"1px solid rgba(255, 255, 255, 0.1)",textTransform:"uppercase",letterSpacing:"0.5px"},children:"Speed"}),[...ci].reverse().map(s=>i.jsx(_e,{selected:e===s,onClick:()=>r(s),children:i.jsx("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",width:"100%"},children:i.jsx("span",{children:s===1?"1× (Normal)":`${s}×`})})},s))]})})]})}const Ve=c.createContext({textColor:"#fff",accentColor:"#6366f1",accentAlpha15:"rgba(99,102,241,0.15)",accentAlpha30:"rgba(99,102,241,0.3)",borderColor:"rgba(255,255,255,0.07)",fontSize:"13.5px"});function ze(a,e){const t=a.replace("#",""),r=t.length===3?t.split("").map(l=>l+l).join(""):t,n=parseInt(r.slice(0,2),16),s=parseInt(r.slice(2,4),16),o=parseInt(r.slice(4,6),16);return isNaN(n)||isNaN(s)||isNaN(o)?`rgba(99,102,241,${e})`:`rgba(${n},${s},${o},${e})`}const ui=60,hi=[.25,.5,.75,1,1.25,1.5,1.75,2],pi={position:"absolute",backdropFilter:"blur(16px)",borderRadius:"14px",overflow:"hidden",zIndex:9999,animation:"settingsFadeIn 0.18s ease-out",fontFamily:"system-ui, -apple-system, sans-serif",transition:"width 0.2s ease"},gi={display:"flex",alignItems:"center",gap:"8px",padding:"11px 14px",fontSize:"13px",fontWeight:600},fi={display:"flex",alignItems:"center",width:"100%",padding:"9px 14px",background:"transparent",border:"none",cursor:"pointer",fontSize:"13.5px",textAlign:"left",gap:"10px",outline:"none",transition:"background 0.12s"};function qe({values:a,color:e,gradId:t}){if(a.length<2)return i.jsx("svg",{width:292,height:52,style:{display:"block"},children:i.jsx("line",{x1:0,y1:52/2,x2:292,y2:52/2,stroke:"rgba(255,255,255,0.08)",strokeWidth:1,strokeDasharray:"4 4"})});const s=Math.max(...a,.001),o=a.map((h,p)=>[p/(ui-1)*292,48-h/s*42]),l=o.map(([h,p],g)=>`${g===0?"M":"L"}${h.toFixed(1)},${p.toFixed(1)}`).join(" "),u=l+` L${292 .toFixed(1)},52 L0,52 Z`,d=o[o.length-1];return i.jsxs("svg",{width:292,height:52,style:{display:"block",overflow:"visible"},children:[i.jsx("defs",{children:i.jsxs("linearGradient",{id:t,x1:"0",y1:"0",x2:"0",y2:"1",children:[i.jsx("stop",{offset:"0%",stopColor:e,stopOpacity:.4}),i.jsx("stop",{offset:"100%",stopColor:e,stopOpacity:.02})]})}),i.jsx("path",{d:u,fill:`url(#${t})`}),i.jsx("path",{d:l,fill:"none",stroke:e,strokeWidth:1.8,strokeLinejoin:"round",strokeLinecap:"round"}),i.jsx("circle",{cx:d[0],cy:d[1],r:3.5,fill:e}),i.jsx("circle",{cx:d[0],cy:d[1],r:6,fill:e,fillOpacity:.25})]})}function F({label:a,value:e,icon:t,onClick:r,selected:n=!1,isBack:s=!1}){const[o,l]=c.useState(!1),{textColor:u,accentColor:d,accentAlpha15:h,accentAlpha30:p,fontSize:g}=c.useContext(Ve);return i.jsxs("button",{role:"menuitem","aria-checked":n,onClick:r,onMouseEnter:()=>l(!0),onMouseLeave:()=>l(!1),style:{...fi,color:u,fontSize:g,background:o?"rgba(255,255,255,0.07)":n?h:"transparent",fontWeight:n?600:400,justifyContent:"space-between"},children:[i.jsxs("span",{style:{display:"flex",alignItems:"center",gap:"10px",flex:1,minWidth:0},children:[s?i.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"rgba(255,255,255,0.6)",strokeWidth:"2.5",style:{flexShrink:0},children:i.jsx("polyline",{points:"15 18 9 12 15 6"})}):t?i.jsx("span",{style:{width:"28px",height:"28px",borderRadius:"7px",background:n?p:"rgba(255,255,255,0.08)",display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0,color:n?d:"rgba(255,255,255,0.65)",transition:"background 0.15s, color 0.15s"},children:t}):n?i.jsx("svg",{"aria-hidden":"true",width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:d,strokeWidth:"3",style:{flexShrink:0},children:i.jsx("polyline",{points:"20 6 9 17 4 12"})}):i.jsx("span",{style:{display:"inline-block",width:"14px",flexShrink:0}}),i.jsx("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:a})]}),e!==void 0&&i.jsxs("span",{style:{display:"flex",alignItems:"center",gap:"4px",flexShrink:0},children:[i.jsx("span",{style:{fontSize:"12px",color:"rgba(255,255,255,0.45)",maxWidth:"90px",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e}),i.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"rgba(255,255,255,0.35)",strokeWidth:"2.5",children:i.jsx("polyline",{points:"9 18 15 12 9 6"})})]})]})}function Ke(){const{borderColor:a}=c.useContext(Ve);return i.jsx("div",{style:{height:"1px",background:a,margin:"2px 0"}})}function jt({theme:a,panelPosition:e,iconSize:t=20,hoverBackground:r,gearIcon:n}={}){const s=a?.accentColor??"#6366f1",o=a?.textColor??"#fff",l=a?.background??"rgba(12, 12, 20, 0.97)",u=a?.borderColor??"rgba(255,255,255,0.1)",d=a?.fontSize??"13.5px",h={textColor:o,accentColor:s,accentAlpha15:s.startsWith("#")?ze(s,.15):"rgba(99,102,241,0.15)",accentAlpha30:s.startsWith("#")?ze(s,.3):"rgba(99,102,241,0.3)",borderColor:u.replace("0.1)","0.07)"),fontSize:d},p={...gi,color:o,fontSize:d,borderBottom:`1px solid ${u.replace("0.1)","0.08)")}`},g=e?.vertical??"top",m=e?.horizontal??"right",{setQuality:w,setAudioTrack:L,setPlaybackRate:b,setSubtitleTrack:M,getPlayerStats:E}=U(),y=pe(),{playbackRate:q=1,isLive:D}=O(),{style:S,setStyle:I}=gt(),[j,$]=c.useState(!1),[x,A]=c.useState("root");c.useEffect(()=>{D&&x==="speed"&&A("root")},[D,x]);const[_,W]=c.useState([]),[K,T]=c.useState(null),[V,C]=c.useState([]),[B,Y]=c.useState(""),[X,fe]=c.useState([]),[te,se]=c.useState(null),[H,we]=c.useState(null),[oe,ce]=c.useState([]);c.useEffect(()=>{const f=()=>{W(y.getAvailableQualities()),T(y.getQuality()),C(y.getAvailableAudioTracks()),Y(y.getAudioTrack()),fe(y.getSubtitleTracks()),se(y.getActiveSubtitleLanguage())};y.events.on("tracksready",f),y.events.on("streamTypeDetected",f),y.events.on("qualitychange",f),y.events.on("loadedmetadata",f),f();const z=setTimeout(f,100);return()=>{y.events.off("tracksready",f),y.events.off("streamTypeDetected",f),y.events.off("qualitychange",f),y.events.off("loadedmetadata",f),clearTimeout(z)}},[y]),c.useEffect(()=>{j&&(W(y.getAvailableQualities()),T(y.getQuality()),C(y.getAvailableAudioTracks()),Y(y.getAudioTrack()),fe(y.getSubtitleTracks()),se(y.getActiveSubtitleLanguage()))},[j,y]);const ke=V.length>1;c.useEffect(()=>{if(x!=="statistics")return;const f=()=>{const ye=E();we(ye),ce(Pe=>[...Pe.slice(-59),ye])};f();const z=setInterval(f,1e3);return()=>{clearInterval(z),ce([])}},[x,E]);const de=c.useRef(null);c.useEffect(()=>{if(!j)return;const f=z=>{de.current&&!de.current.contains(z.target)&&($(!1),A("root"))};return document.addEventListener("pointerdown",f),()=>document.removeEventListener("pointerdown",f)},[j]),c.useEffect(()=>{if(!j)return;const f=z=>{z.key==="Escape"&&($(!1),A("root")),z.key==="Backspace"&&x!=="root"&&A("root")};return document.addEventListener("keydown",f),()=>document.removeEventListener("keydown",f)},[j,x]);const Se=c.useCallback(()=>{$(f=>(f&&A("root"),!f))},[]),Ae=K?K.id==="auto"?"Auto":K.label:"Auto",re=q===1?"1×":`${q}×`,ue=V.find(f=>f.id===B)?.label??"Auto",me=te===null?"Off":X.find(f=>f.language===te)?.label??te,Ce=i.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:[i.jsx("rect",{x:"2",y:"3",width:"20",height:"14",rx:"2"}),i.jsx("path",{d:"M8 21h8M12 17v4"}),i.jsx("path",{d:"m7 8 2 2 4-4 2 2"})]}),Te=i.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:[i.jsx("path",{d:"M12 12m-1 0a1 1 0 1 0 2 0 1 1 0 0 0-2 0"}),i.jsx("path",{d:"M12 2a10 10 0 0 1 7.39 16.74M12 2A10 10 0 0 0 4.61 18.74"}),i.jsx("path",{d:"m16.24 7.76-2.12 2.12"})]}),Me=i.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:[i.jsx("path",{d:"M3 18v-6a9 9 0 0 1 18 0v6"}),i.jsx("path",{d:"M21 19a2 2 0 0 1-2 2h-1a2 2 0 0 1-2-2v-3a2 2 0 0 1 2-2h3zM3 19a2 2 0 0 0 2 2h1a2 2 0 0 0 2-2v-3a2 2 0 0 0-2-2H3z"})]}),v=i.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:[i.jsx("path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"}),i.jsx("line",{x1:"9",y1:"10",x2:"15",y2:"10"}),i.jsx("line",{x1:"9",y1:"14",x2:"12",y2:"14"})]}),P=i.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:[i.jsx("circle",{cx:"12",cy:"12",r:"3"}),i.jsx("path",{d:"M20.39 18.39A5 5 0 0 0 18 9h-1.26A8 8 0 1 0 3 16.3"}),i.jsx("polyline",{points:"16 16 12 20 8 16"})]}),R=i.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:[i.jsx("line",{x1:"18",y1:"20",x2:"18",y2:"10"}),i.jsx("line",{x1:"12",y1:"20",x2:"12",y2:"4"}),i.jsx("line",{x1:"6",y1:"20",x2:"6",y2:"14"})]}),N=()=>i.jsxs(i.Fragment,{children:[i.jsxs("div",{style:p,children:[i.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"rgba(255,255,255,0.6)",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:[i.jsx("circle",{cx:"12",cy:"12",r:"3"}),i.jsx("path",{d:"M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-4 0v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83-2.83l.06-.06A1.65 1.65 0 0 0 4.68 15a1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1 0-4h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 2.83-2.83l.06.06A1.65 1.65 0 0 0 9 4.68a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 2.83l-.06.06A1.65 1.65 0 0 0 19.4 9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z"})]}),"Settings"]}),i.jsxs("div",{style:{padding:"4px 0"},children:[i.jsx(F,{icon:Ce,label:"Quality",value:Ae,onClick:()=>A("quality")}),!D&&i.jsx(F,{icon:Te,label:"Speed",value:re,onClick:()=>A("speed")}),ke&&i.jsx(F,{icon:Me,label:"Audio Track",value:ue,onClick:()=>A("audio")}),i.jsx(Ke,{}),i.jsx(F,{icon:v,label:"Subtitles",value:me,onClick:()=>A("subtitles")}),i.jsx(F,{icon:P,label:"Subtitle Style",value:`${S.fontSize}px`,onClick:()=>A("subtitleStyle")}),i.jsx(Ke,{}),i.jsx(F,{icon:R,label:"Statistics",onClick:()=>A("statistics")})]})]}),G=()=>i.jsxs(i.Fragment,{children:[i.jsx("div",{style:p,children:i.jsx(F,{label:"Quality",isBack:!0,onClick:()=>A("root")})}),i.jsxs("div",{style:{padding:"4px 0",maxHeight:"280px",overflowY:"auto"},children:[_.map(f=>i.jsx(F,{label:f.id==="auto"?"Auto":f.label,selected:K?.id===f.id,onClick:()=>{w(f.id),T(f),$(!1),A("root")}},f.id)),_.length===0&&i.jsx("div",{style:{padding:"10px 14px",color:"rgba(255,255,255,0.4)",fontSize:"13px"},children:"No quality levels available"})]})]}),ae=()=>i.jsxs(i.Fragment,{children:[i.jsx("div",{style:p,children:i.jsx(F,{label:"Speed",isBack:!0,onClick:()=>A("root")})}),i.jsx("div",{style:{padding:"4px 0"},children:hi.map(f=>i.jsx(F,{label:f===1?"1× (Normal)":`${f}×`,selected:q===f,onClick:()=>{b(f),$(!1),A("root")}},f))})]}),Rt=()=>i.jsxs(i.Fragment,{children:[i.jsx("div",{style:p,children:i.jsx(F,{label:"Audio Track",isBack:!0,onClick:()=>A("root")})}),i.jsx("div",{style:{padding:"4px 0"},children:V.map(f=>i.jsx(F,{label:f.label||f.language||f.id,selected:B===f.id,onClick:()=>{L(f.id),Y(f.id),$(!1),A("root")}},f.id))})]}),Dt=()=>i.jsxs(i.Fragment,{children:[i.jsx("div",{style:p,children:i.jsx(F,{label:"Subtitles",isBack:!0,onClick:()=>A("root")})}),i.jsxs("div",{style:{padding:"4px 0"},children:[i.jsx(F,{label:"Off",selected:te===null,onClick:()=>{M(null),se(null),$(!1),A("root")}},"off"),X.map((f,z)=>i.jsx(F,{label:f.label||f.language,selected:te===f.language,onClick:()=>{M(f.language),se(f.language),$(!1),A("root")}},f.url||`${f.language}-${z}`)),X.length===0&&i.jsx("div",{style:{padding:"10px 14px",color:"rgba(255,255,255,0.4)",fontSize:"13px"},children:"No subtitle tracks available"})]})]}),It=()=>i.jsxs(i.Fragment,{children:[i.jsx("div",{style:p,children:i.jsx(F,{label:"Subtitle Style",isBack:!0,onClick:()=>A("root")})}),i.jsxs("div",{style:{padding:"8px 14px 12px",display:"flex",flexDirection:"column",gap:"14px"},children:[i.jsxs("div",{children:[i.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:"6px"},children:[i.jsx("span",{style:{fontSize:"13px",color:"rgba(255,255,255,0.8)"},children:"Position"}),i.jsxs("span",{style:{fontSize:"12px",color:"rgba(255,255,255,0.5)"},children:[S.bottomOffset,"px from bottom"]})]}),i.jsx("input",{type:"range",min:10,max:200,step:5,value:S.bottomOffset,onChange:f=>I({bottomOffset:Number(f.target.value)}),style:{width:"100%",accentColor:"#3b82f6",cursor:"pointer"}})]}),i.jsxs("div",{children:[i.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:"6px"},children:[i.jsx("span",{style:{fontSize:"13px",color:"rgba(255,255,255,0.8)"},children:"Font Size"}),i.jsxs("span",{style:{fontSize:"12px",color:"rgba(255,255,255,0.5)"},children:[S.fontSize,"px"]})]}),i.jsx("input",{type:"range",min:12,max:40,step:1,value:S.fontSize,onChange:f=>I({fontSize:Number(f.target.value)}),style:{width:"100%",accentColor:"#3b82f6",cursor:"pointer"}})]}),i.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center"},children:[i.jsx("span",{style:{fontSize:"13px",color:"rgba(255,255,255,0.8)"},children:"Background"}),i.jsx("button",{onClick:()=>I({background:S.background?"":"rgba(0,0,0,0.75)"}),style:{padding:"4px 12px",borderRadius:"6px",border:"1px solid rgba(255,255,255,0.2)",background:S.background?"#3b82f6":"transparent",color:"#fff",fontSize:"12px",cursor:"pointer"},children:S.background?"On":"Off"})]}),i.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center"},children:[i.jsx("span",{style:{fontSize:"13px",color:"rgba(255,255,255,0.8)"},children:"Text Color"}),i.jsx("div",{style:{display:"flex",gap:"6px"},children:["#ffffff","#ffff00","#00ff00","#00cfff"].map(f=>i.jsx("button",{onClick:()=>I({color:f}),title:f,style:{width:"22px",height:"22px",borderRadius:"50%",background:f,border:S.color===f?"2px solid #3b82f6":"2px solid transparent",cursor:"pointer",outline:"none",padding:0,flexShrink:0}},f))})]})]})]}),_t=()=>{const f=oe.map(Z=>Z.bandwidth),z=oe.map(Z=>Z.bufferHealth),ye=H?.bandwidth??0,Pe=H?.bufferHealth??0,Bt=Z=>Z>=1e3?`${(Z/1e3).toFixed(2)} Mbps`:`${Z.toFixed(0)} kbps`,ve=(Z,$t)=>i.jsxs("div",{style:{background:"rgba(255,255,255,0.04)",borderRadius:"8px",padding:"7px 10px",flex:"1 1 0",minWidth:0},children:[i.jsx("div",{style:{fontSize:"10px",color:"rgba(255,255,255,0.4)",textTransform:"uppercase",letterSpacing:"0.06em",marginBottom:"3px"},children:Z}),i.jsx("div",{style:{fontSize:"12px",color:"#fff",fontFamily:"monospace",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:$t})]}),xe=H?.segmentUrl??"",Nt=xe.length>36?"…"+xe.slice(-36):xe||"—";return i.jsxs(i.Fragment,{children:[i.jsxs("div",{style:{...p,justifyContent:"space-between"},children:[i.jsx("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:i.jsx(F,{label:"Statistics",isBack:!0,onClick:()=>A("root")})}),i.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"6px",paddingRight:"14px",flexShrink:0},children:[i.jsx("span",{style:{width:"7px",height:"7px",borderRadius:"50%",background:"#22c55e",boxShadow:"0 0 6px #22c55e",animation:"statsPulse 1.6s ease-in-out infinite",display:"inline-block"}}),i.jsx("span",{style:{fontSize:"11px",color:"rgba(255,255,255,0.4)"},children:"LIVE"})]})]}),i.jsxs("div",{style:{padding:"0 14px 12px",overflowY:"auto",maxHeight:"420px"},children:[i.jsxs("div",{style:{marginTop:"12px"},children:[i.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"baseline",marginBottom:"6px"},children:[i.jsx("span",{style:{fontSize:"11px",color:"rgba(255,255,255,0.45)",textTransform:"uppercase",letterSpacing:"0.07em"},children:"Connection Speed"}),i.jsx("span",{style:{fontSize:"16px",fontWeight:600,color:"#4ade80",fontFamily:"monospace"},children:H?Bt(ye):"—"})]}),i.jsx("div",{style:{background:"rgba(0,0,0,0.3)",borderRadius:"8px",padding:"6px 8px"},children:i.jsx(qe,{values:f,color:"#4ade80",gradId:"bw-grad"})})]}),i.jsxs("div",{style:{marginTop:"14px"},children:[i.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"baseline",marginBottom:"6px"},children:[i.jsx("span",{style:{fontSize:"11px",color:"rgba(255,255,255,0.45)",textTransform:"uppercase",letterSpacing:"0.07em"},children:"Buffer Health"}),i.jsx("span",{style:{fontSize:"16px",fontWeight:600,color:"#60a5fa",fontFamily:"monospace"},children:H?`${Pe.toFixed(1)} s`:"—"})]}),i.jsx("div",{style:{background:"rgba(0,0,0,0.3)",borderRadius:"8px",padding:"6px 8px"},children:i.jsx(qe,{values:z,color:"#60a5fa",gradId:"buf-grad"})})]}),i.jsx("div",{style:{height:"1px",background:"rgba(255,255,255,0.07)",margin:"14px 0 12px"}}),i.jsxs("div",{style:{display:"flex",gap:"6px"},children:[ve("Codec",H?.codec||"—"),ve("Resolution",H?.resolution||"—"),ve("Dropped",H?`${H.droppedFrames}/${H.totalFrames}`:"—")]}),i.jsxs("div",{style:{display:"flex",gap:"6px",marginTop:"6px"},children:[ve("Stream",H?.streamType||"—"),i.jsxs("div",{style:{background:"rgba(255,255,255,0.04)",borderRadius:"8px",padding:"7px 10px",flex:"2 1 0",minWidth:0},children:[i.jsx("div",{style:{fontSize:"10px",color:"rgba(255,255,255,0.4)",textTransform:"uppercase",letterSpacing:"0.06em",marginBottom:"3px"},children:"Segment"}),i.jsx("div",{style:{fontSize:"11px",color:"rgba(255,255,255,0.7)",fontFamily:"monospace",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},title:xe,children:Nt})]})]})]}),i.jsx("style",{children:`
|
|
179
|
+
`})]})}function Mt({seconds:a=15,iconSize:e=24,hoverBackground:t,icon:r}){const{skipBackward:n}=U(),{isLive:s}=O();if(s)return null;const o=typeof t=="string"?t:t===!1?"transparent":void 0;return i.jsx("button",{className:`virtus-btn virtus-skip-backward-button ${ge.controlButton}`,"aria-label":`Skip Backward ${a}s`,onClick:()=>n(a),style:{position:"relative",...o!==void 0?{"--btn-hover-bg":o}:{}},children:r??i.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",width:e,height:e,viewBox:"0 0 24 24",fill:"none",children:[i.jsx("path",{d:"M12 2C6.5 2 2 6.5 2 12s4.5 10 10 10 10-4.5 10-10",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round"}),i.jsx("path",{d:"M2 12l-2-2m2 2l2-2",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round"}),i.jsx("text",{x:"12",y:"16",fontSize:"10",fill:"currentColor",textAnchor:"middle",fontWeight:"bold",children:a})]})})}function Pt({seconds:a=15,iconSize:e=24,hoverBackground:t,icon:r}){const{skipForward:n}=U(),{isLive:s}=O();if(s)return null;const o=typeof t=="string"?t:t===!1?"transparent":void 0;return i.jsx("button",{className:`virtus-btn virtus-skip-forward-button ${ge.controlButton}`,"aria-label":`Skip Forward ${a}s`,onClick:()=>n(a),style:{position:"relative",...o!==void 0?{"--btn-hover-bg":o}:{}},children:r??i.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",width:e,height:e,viewBox:"0 0 24 24",fill:"none",children:[i.jsx("path",{d:"M12 2c5.5 0 10 4.5 10 10s-4.5 10-10 10-10-4.5-10-10",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round"}),i.jsx("path",{d:"M22 12l2-2m-2 2l-2-2",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round"}),i.jsx("text",{x:"12",y:"16",fontSize:"10",fill:"currentColor",textAnchor:"middle",fontWeight:"bold",children:a})]})})}function Lt({sliderDirection:a="right",theme:e,iconSize:t=20,hoverBackground:r}){const n={sliderBackground:e?.sliderBackground??"rgba(10, 10, 20, 0.88)",borderColor:e?.borderColor??"rgba(255,255,255,0.1)",buttonBackground:e?.buttonBackground??"rgba(255,255,255,0.1)",buttonHoverBackground:e?.buttonHoverBackground??"rgba(255,255,255,0.2)",iconColor:e?.iconColor??"#fff",trackColor:e?.trackColor??"rgba(255,255,255,0.3)",fillColor:e?.fillColor??"#3b82f6",handleColor:e?.handleColor??"#fff"},{isMuted:s,volume:o}=O(),{toggleMute:l,setVolume:d}=U(),[u,h]=c.useState(!1),[p,g]=c.useState(!1),m=c.useRef(null),E=a==="top"||a==="bottom",j=c.useCallback((x,C)=>{if(!m.current)return;const I=m.current.getBoundingClientRect(),$=E?Math.max(0,Math.min(1,1-(C-I.top)/I.height)):Math.max(0,Math.min(1,(x-I.left)/I.width));d($)},[d,E]),S=c.useCallback(x=>{g(!0),s&&l(),j(x.clientX,x.clientY)},[j,s,l]);c.useEffect(()=>{if(!p)return;const x=I=>j(I.clientX,I.clientY),C=()=>g(!1);return window.addEventListener("mousemove",x),window.addEventListener("mouseup",C),()=>{window.removeEventListener("mousemove",x),window.removeEventListener("mouseup",C)}},[p,j]);const A=p?o:s?0:o,b=u||p,y={position:"absolute",opacity:b?1:0,transition:"all 0.25s ease",pointerEvents:b?"auto":"none",zIndex:10,background:n.sliderBackground,backdropFilter:"blur(12px)",boxShadow:"4px 0 16px rgba(0,0,0,0.5)",overflow:"hidden"},q=(()=>{const x=`1px solid ${n.borderColor}`;switch(a){case"left":return{...y,right:"40px",top:"0",width:b?"118px":"0px",height:"40px",paddingRight:"8px",borderRadius:"8px 0 0 8px",border:x,borderRight:"none"};case"top":return{...y,bottom:"40px",left:"0",width:"40px",height:b?"118px":"0px",paddingBottom:"8px",borderRadius:"8px 8px 0 0",border:x,borderBottom:"none"};case"bottom":return{...y,top:"40px",left:"0",width:"40px",height:b?"118px":"0px",paddingTop:"8px",borderRadius:"0 0 8px 8px",border:x,borderTop:"none"};default:return{...y,left:"40px",top:"0",width:b?"118px":"0px",height:"40px",paddingLeft:"8px",borderRadius:"0 8px 8px 0",border:x,borderLeft:"none"}}})(),z=E?{width:"40px",height:"110px",display:"flex",justifyContent:"center",alignItems:"center",cursor:"pointer",position:"relative",outline:"none"}:{width:"110px",height:"40px",display:"flex",alignItems:"center",cursor:"pointer",position:"relative",paddingRight:"8px",outline:"none"},L=E?{width:"4px",height:"100%",backgroundColor:n.trackColor,borderRadius:"2px",position:"relative"}:{width:"100%",height:"4px",backgroundColor:n.trackColor,borderRadius:"2px",position:"relative"},w=E?{position:"absolute",bottom:0,left:0,right:0,height:`${A*100}%`,backgroundColor:n.fillColor,borderRadius:"2px",transition:p?"none":"height 0.1s ease"}:{position:"absolute",left:0,top:0,bottom:0,width:`${A*100}%`,backgroundColor:n.fillColor,borderRadius:"2px",transition:p?"none":"width 0.1s ease"},R=p?14:12,N=E?{position:"absolute",bottom:`calc(${A*100}% - ${A*R}px)`,left:"50%",transform:"translateX(-50%)",width:`${R}px`,height:`${R}px`,backgroundColor:n.handleColor,borderRadius:"50%",boxShadow:"0 2px 4px rgba(0,0,0,0.3)",transition:p?"none":"all 0.2s ease"}:{position:"absolute",left:`calc(${A*100}% - ${A*R}px)`,top:"50%",transform:"translateY(-50%)",width:`${R}px`,height:`${R}px`,backgroundColor:n.handleColor,borderRadius:"50%",boxShadow:"0 2px 4px rgba(0,0,0,0.3)",transition:p?"none":"all 0.2s ease"};return i.jsxs("div",{className:"virtus-volume-control",style:{position:"relative",display:"flex",alignItems:"center",height:"40px",width:"40px"},onMouseLeave:()=>{p||h(!1)},children:[i.jsx("button",{className:"virtus-btn virtus-mute-button","aria-label":s?"Unmute":"Mute",onClick:l,style:{background:r===!1?"transparent":n.buttonBackground,border:"none",borderRadius:"8px",width:"40px",height:"40px",display:"flex",alignItems:"center",justifyContent:"center",cursor:"pointer",transition:"all 0.2s ease",flexShrink:0,position:"relative",zIndex:1},onMouseEnter:x=>{h(!0),x.currentTarget.style.background=typeof r=="string"?r:r===!1?"transparent":n.buttonHoverBackground,x.currentTarget.style.transform="scale(1.05)"},onMouseLeave:x=>{x.currentTarget.style.background=r===!1?"transparent":n.buttonBackground,x.currentTarget.style.transform="scale(1)"},children:s||o===0?i.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",width:t,height:t,fill:n.iconColor,viewBox:"0 0 24 24",children:i.jsx("path",{d:"M13.5 4.06c0-1.336-1.616-2.005-2.56-1.06l-4.5 4.5H4.508c-1.141 0-2.318.664-2.66 1.905A9.76 9.76 0 0 0 1.5 12c0 .898.121 1.768.35 2.595.341 1.24 1.518 1.905 2.659 1.905h1.93l4.5 4.5c.945.945 2.561.276 2.561-1.06V4.06ZM17.78 9.22a.75.75 0 1 0-1.06 1.06L18.44 12l-1.72 1.72a.75.75 0 1 0 1.06 1.06l1.72-1.72 1.72 1.72a.75.75 0 1 0 1.06-1.06L20.56 12l1.72-1.72a.75.75 0 1 0-1.06-1.06l-1.72 1.72-1.72-1.72Z"})}):o<.5?i.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",width:t,height:t,fill:n.iconColor,viewBox:"0 0 24 24",children:i.jsx("path",{d:"M13.5 4.06c0-1.336-1.616-2.005-2.56-1.06l-4.5 4.5H4.508c-1.141 0-2.318.664-2.66 1.905A9.76 9.76 0 0 0 1.5 12c0 .898.121 1.768.35 2.595.341 1.24 1.518 1.905 2.659 1.905h1.93l4.5 4.5c.945.945 2.561.276 2.561-1.06V4.06Z"})}):i.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",width:t,height:t,fill:n.iconColor,viewBox:"0 0 24 24",children:[i.jsx("path",{d:"M13.5 4.06c0-1.336-1.616-2.005-2.56-1.06l-4.5 4.5H4.508c-1.141 0-2.318.664-2.66 1.905A9.76 9.76 0 0 0 1.5 12c0 .898.121 1.768.35 2.595.341 1.24 1.518 1.905 2.659 1.905h1.93l4.5 4.5c.945.945 2.561.276 2.561-1.06V4.06Z"}),i.jsx("path",{d:"M18.584 5.106a.75.75 0 0 1 1.06 0 11.5 11.5 0 0 1 0 13.588.75.75 0 0 1-1.06-1.06 10 10 0 0 0 0-11.468.75.75 0 0 1 0-1.06Z"}),i.jsx("path",{d:"M15.932 7.757a.75.75 0 0 1 1.061 0 6.5 6.5 0 0 1 0 8.486.75.75 0 0 1-1.06-1.06 5 5 0 0 0 0-6.366.75.75 0 0 1 0-1.06Z"})]})}),i.jsx("div",{onMouseEnter:()=>h(!0),style:q,children:i.jsx("div",{ref:m,role:"slider",tabIndex:0,"aria-label":"Volume","aria-valuemin":0,"aria-valuemax":100,"aria-valuenow":Math.round(A*100),"aria-valuetext":s?"Muted":`${Math.round(A*100)}%`,onMouseDown:S,onKeyDown:x=>{const $=s?0:o;switch(x.key){case"ArrowRight":case"ArrowUp":x.preventDefault(),d(Math.min(1,$+.05));break;case"ArrowLeft":case"ArrowDown":x.preventDefault(),d(Math.max(0,$-.05));break;case"PageUp":x.preventDefault(),d(Math.min(1,$+.2));break;case"PageDown":x.preventDefault(),d(Math.max(0,$-.2));break;case"Home":x.preventDefault(),d(0);break;case"End":x.preventDefault(),d(1);break;case"m":case"M":x.preventDefault(),l();break}},style:z,children:i.jsxs("div",{style:L,children:[i.jsx("div",{style:w}),i.jsx("div",{style:N})]})})})]})}const ci=[.25,.5,.75,1,1.25,1.5,1.75,2];function di(){const{setPlaybackRate:a}=U(),[e,t]=c.useState(1),r=c.useCallback(s=>{a(s),t(s)},[a]),n=e===1?"1×":`${e}×`;return i.jsxs(bt,{children:[i.jsx(Et,{children:i.jsx("button",{className:"virtus-speed-button","aria-label":`Playback speed: ${n}`,"aria-haspopup":"true",style:{background:"transparent",border:"none",color:"white",cursor:"pointer",padding:"8px",borderRadius:"8px",display:"flex",alignItems:"center",justifyContent:"center",height:"40px",minWidth:"40px",transition:"all 0.2s ease",fontSize:"13px",fontWeight:"600",letterSpacing:"-0.3px",whiteSpace:"nowrap"},onMouseEnter:s=>{s.currentTarget.style.background="rgba(255, 255, 255, 0.15)",s.currentTarget.style.transform="scale(1.05)"},onMouseLeave:s=>{s.currentTarget.style.background="transparent",s.currentTarget.style.transform="scale(1)"},title:"Playback speed",children:n})}),i.jsx(wt,{placement:"top-right",children:i.jsxs("div",{style:{minWidth:"130px"},children:[i.jsx("div",{style:{padding:"8px 12px",fontSize:"12px",fontWeight:"600",color:"rgba(255, 255, 255, 0.6)",borderBottom:"1px solid rgba(255, 255, 255, 0.1)",textTransform:"uppercase",letterSpacing:"0.5px"},children:"Speed"}),[...ci].reverse().map(s=>i.jsx(_e,{selected:e===s,onClick:()=>r(s),children:i.jsx("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",width:"100%"},children:i.jsx("span",{children:s===1?"1× (Normal)":`${s}×`})})},s))]})})]})}const Ve=c.createContext({textColor:"#fff",accentColor:"#6366f1",accentAlpha15:"rgba(99,102,241,0.15)",accentAlpha30:"rgba(99,102,241,0.3)",borderColor:"rgba(255,255,255,0.07)",fontSize:"13.5px"});function ze(a,e){const t=a.replace("#",""),r=t.length===3?t.split("").map(l=>l+l).join(""):t,n=parseInt(r.slice(0,2),16),s=parseInt(r.slice(2,4),16),o=parseInt(r.slice(4,6),16);return isNaN(n)||isNaN(s)||isNaN(o)?`rgba(99,102,241,${e})`:`rgba(${n},${s},${o},${e})`}const ui=60,hi=[.25,.5,.75,1,1.25,1.5,1.75,2],pi={position:"absolute",backdropFilter:"blur(16px)",borderRadius:"14px",overflow:"hidden",zIndex:9999,animation:"settingsFadeIn 0.18s ease-out",fontFamily:"system-ui, -apple-system, sans-serif",transition:"width 0.2s ease"},gi={display:"flex",alignItems:"center",gap:"8px",padding:"11px 14px",fontSize:"13px",fontWeight:600},fi={display:"flex",alignItems:"center",width:"100%",padding:"9px 14px",background:"transparent",border:"none",cursor:"pointer",fontSize:"13.5px",textAlign:"left",gap:"10px",outline:"none",transition:"background 0.12s"};function qe({values:a,color:e,gradId:t}){if(a.length<2)return i.jsx("svg",{width:292,height:52,style:{display:"block"},children:i.jsx("line",{x1:0,y1:52/2,x2:292,y2:52/2,stroke:"rgba(255,255,255,0.08)",strokeWidth:1,strokeDasharray:"4 4"})});const s=Math.max(...a,.001),o=a.map((h,p)=>[p/(ui-1)*292,48-h/s*42]),l=o.map(([h,p],g)=>`${g===0?"M":"L"}${h.toFixed(1)},${p.toFixed(1)}`).join(" "),d=l+` L${292 .toFixed(1)},52 L0,52 Z`,u=o[o.length-1];return i.jsxs("svg",{width:292,height:52,style:{display:"block",overflow:"visible"},children:[i.jsx("defs",{children:i.jsxs("linearGradient",{id:t,x1:"0",y1:"0",x2:"0",y2:"1",children:[i.jsx("stop",{offset:"0%",stopColor:e,stopOpacity:.4}),i.jsx("stop",{offset:"100%",stopColor:e,stopOpacity:.02})]})}),i.jsx("path",{d,fill:`url(#${t})`}),i.jsx("path",{d:l,fill:"none",stroke:e,strokeWidth:1.8,strokeLinejoin:"round",strokeLinecap:"round"}),i.jsx("circle",{cx:u[0],cy:u[1],r:3.5,fill:e}),i.jsx("circle",{cx:u[0],cy:u[1],r:6,fill:e,fillOpacity:.25})]})}function F({label:a,value:e,icon:t,onClick:r,selected:n=!1,isBack:s=!1}){const[o,l]=c.useState(!1),{textColor:d,accentColor:u,accentAlpha15:h,accentAlpha30:p,fontSize:g}=c.useContext(Ve);return i.jsxs("button",{role:"menuitem","aria-checked":n,onClick:r,onMouseEnter:()=>l(!0),onMouseLeave:()=>l(!1),style:{...fi,color:d,fontSize:g,background:o?"rgba(255,255,255,0.07)":n?h:"transparent",fontWeight:n?600:400,justifyContent:"space-between"},children:[i.jsxs("span",{style:{display:"flex",alignItems:"center",gap:"10px",flex:1,minWidth:0},children:[s?i.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"rgba(255,255,255,0.6)",strokeWidth:"2.5",style:{flexShrink:0},children:i.jsx("polyline",{points:"15 18 9 12 15 6"})}):t?i.jsx("span",{style:{width:"28px",height:"28px",borderRadius:"7px",background:n?p:"rgba(255,255,255,0.08)",display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0,color:n?u:"rgba(255,255,255,0.65)",transition:"background 0.15s, color 0.15s"},children:t}):n?i.jsx("svg",{"aria-hidden":"true",width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:u,strokeWidth:"3",style:{flexShrink:0},children:i.jsx("polyline",{points:"20 6 9 17 4 12"})}):i.jsx("span",{style:{display:"inline-block",width:"14px",flexShrink:0}}),i.jsx("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:a})]}),e!==void 0&&i.jsxs("span",{style:{display:"flex",alignItems:"center",gap:"4px",flexShrink:0},children:[i.jsx("span",{style:{fontSize:"12px",color:"rgba(255,255,255,0.45)",maxWidth:"90px",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e}),i.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"rgba(255,255,255,0.35)",strokeWidth:"2.5",children:i.jsx("polyline",{points:"9 18 15 12 9 6"})})]})]})}function Ke(){const{borderColor:a}=c.useContext(Ve);return i.jsx("div",{style:{height:"1px",background:a,margin:"2px 0"}})}function jt({theme:a,panelPosition:e,iconSize:t=20,hoverBackground:r,gearIcon:n}={}){const s=a?.accentColor??"#6366f1",o=a?.textColor??"#fff",l=a?.background??"rgba(12, 12, 20, 0.97)",d=a?.borderColor??"rgba(255,255,255,0.1)",u=a?.fontSize??"13.5px",h={textColor:o,accentColor:s,accentAlpha15:s.startsWith("#")?ze(s,.15):"rgba(99,102,241,0.15)",accentAlpha30:s.startsWith("#")?ze(s,.3):"rgba(99,102,241,0.3)",borderColor:d.replace("0.1)","0.07)"),fontSize:u},p={...gi,color:o,fontSize:u,borderBottom:`1px solid ${d.replace("0.1)","0.08)")}`},g=e?.vertical??"top",m=e?.horizontal??"right",{setQuality:E,setAudioTrack:j,setPlaybackRate:S,setSubtitleTrack:A,getPlayerStats:b}=U(),y=pe(),{playbackRate:q=1,isLive:z}=O(),{style:L,setStyle:w}=gt(),[R,N]=c.useState(!1),[x,C]=c.useState("root");c.useEffect(()=>{z&&x==="speed"&&C("root")},[z,x]);const[I,$]=c.useState([]),[K,M]=c.useState(null),[_,T]=c.useState([]),[V,Y]=c.useState(""),[X,fe]=c.useState([]),[te,se]=c.useState(null),[W,we]=c.useState(null),[oe,ce]=c.useState([]);c.useEffect(()=>{const f=()=>{$(y.getAvailableQualities()),M(y.getQuality()),T(y.getAvailableAudioTracks()),Y(y.getAudioTrack()),fe(y.getSubtitleTracks()),se(y.getActiveSubtitleLanguage())};y.events.on("tracksready",f),y.events.on("streamTypeDetected",f),y.events.on("qualitychange",f),y.events.on("loadedmetadata",f),f();const H=setTimeout(f,100);return()=>{y.events.off("tracksready",f),y.events.off("streamTypeDetected",f),y.events.off("qualitychange",f),y.events.off("loadedmetadata",f),clearTimeout(H)}},[y]),c.useEffect(()=>{R&&($(y.getAvailableQualities()),M(y.getQuality()),T(y.getAvailableAudioTracks()),Y(y.getAudioTrack()),fe(y.getSubtitleTracks()),se(y.getActiveSubtitleLanguage()))},[R,y]);const ke=_.length>1;c.useEffect(()=>{if(x!=="statistics")return;const f=()=>{const ye=b();we(ye),ce(Pe=>[...Pe.slice(-59),ye])};f();const H=setInterval(f,1e3);return()=>{clearInterval(H),ce([])}},[x,b]);const de=c.useRef(null);c.useEffect(()=>{if(!R)return;const f=H=>{de.current&&!de.current.contains(H.target)&&(N(!1),C("root"))};return document.addEventListener("pointerdown",f),()=>document.removeEventListener("pointerdown",f)},[R]),c.useEffect(()=>{if(!R)return;const f=H=>{H.key==="Escape"&&(N(!1),C("root")),H.key==="Backspace"&&x!=="root"&&C("root")};return document.addEventListener("keydown",f),()=>document.removeEventListener("keydown",f)},[R,x]);const Se=c.useCallback(()=>{N(f=>(f&&C("root"),!f))},[]),Ae=K?K.id==="auto"?"Auto":K.label:"Auto",re=q===1?"1×":`${q}×`,ue=_.find(f=>f.id===V)?.label??"Auto",me=te===null?"Off":X.find(f=>f.language===te)?.label??te,Ce=i.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:[i.jsx("rect",{x:"2",y:"3",width:"20",height:"14",rx:"2"}),i.jsx("path",{d:"M8 21h8M12 17v4"}),i.jsx("path",{d:"m7 8 2 2 4-4 2 2"})]}),Te=i.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:[i.jsx("path",{d:"M12 12m-1 0a1 1 0 1 0 2 0 1 1 0 0 0-2 0"}),i.jsx("path",{d:"M12 2a10 10 0 0 1 7.39 16.74M12 2A10 10 0 0 0 4.61 18.74"}),i.jsx("path",{d:"m16.24 7.76-2.12 2.12"})]}),Me=i.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:[i.jsx("path",{d:"M3 18v-6a9 9 0 0 1 18 0v6"}),i.jsx("path",{d:"M21 19a2 2 0 0 1-2 2h-1a2 2 0 0 1-2-2v-3a2 2 0 0 1 2-2h3zM3 19a2 2 0 0 0 2 2h1a2 2 0 0 0 2-2v-3a2 2 0 0 0-2-2H3z"})]}),v=i.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:[i.jsx("path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"}),i.jsx("line",{x1:"9",y1:"10",x2:"15",y2:"10"}),i.jsx("line",{x1:"9",y1:"14",x2:"12",y2:"14"})]}),P=i.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:[i.jsx("circle",{cx:"12",cy:"12",r:"3"}),i.jsx("path",{d:"M20.39 18.39A5 5 0 0 0 18 9h-1.26A8 8 0 1 0 3 16.3"}),i.jsx("polyline",{points:"16 16 12 20 8 16"})]}),D=i.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:[i.jsx("line",{x1:"18",y1:"20",x2:"18",y2:"10"}),i.jsx("line",{x1:"12",y1:"20",x2:"12",y2:"4"}),i.jsx("line",{x1:"6",y1:"20",x2:"6",y2:"14"})]}),B=()=>i.jsxs(i.Fragment,{children:[i.jsxs("div",{style:p,children:[i.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"rgba(255,255,255,0.6)",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:[i.jsx("circle",{cx:"12",cy:"12",r:"3"}),i.jsx("path",{d:"M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-4 0v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83-2.83l.06-.06A1.65 1.65 0 0 0 4.68 15a1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1 0-4h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 2.83-2.83l.06.06A1.65 1.65 0 0 0 9 4.68a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 2.83l-.06.06A1.65 1.65 0 0 0 19.4 9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z"})]}),"Settings"]}),i.jsxs("div",{style:{padding:"4px 0"},children:[i.jsx(F,{icon:Ce,label:"Quality",value:Ae,onClick:()=>C("quality")}),!z&&i.jsx(F,{icon:Te,label:"Speed",value:re,onClick:()=>C("speed")}),ke&&i.jsx(F,{icon:Me,label:"Audio Track",value:ue,onClick:()=>C("audio")}),i.jsx(Ke,{}),i.jsx(F,{icon:v,label:"Subtitles",value:me,onClick:()=>C("subtitles")}),i.jsx(F,{icon:P,label:"Subtitle Style",value:`${L.fontSize}px`,onClick:()=>C("subtitleStyle")}),i.jsx(Ke,{}),i.jsx(F,{icon:D,label:"Statistics",onClick:()=>C("statistics")})]})]}),G=()=>i.jsxs(i.Fragment,{children:[i.jsx("div",{style:p,children:i.jsx(F,{label:"Quality",isBack:!0,onClick:()=>C("root")})}),i.jsxs("div",{style:{padding:"4px 0",maxHeight:"280px",overflowY:"auto"},children:[I.map(f=>i.jsx(F,{label:f.id==="auto"?"Auto":f.label,selected:K?.id===f.id,onClick:()=>{E(f.id),M(f),N(!1),C("root")}},f.id)),I.length===0&&i.jsx("div",{style:{padding:"10px 14px",color:"rgba(255,255,255,0.4)",fontSize:"13px"},children:"No quality levels available"})]})]}),ae=()=>i.jsxs(i.Fragment,{children:[i.jsx("div",{style:p,children:i.jsx(F,{label:"Speed",isBack:!0,onClick:()=>C("root")})}),i.jsx("div",{style:{padding:"4px 0"},children:hi.map(f=>i.jsx(F,{label:f===1?"1× (Normal)":`${f}×`,selected:q===f,onClick:()=>{S(f),N(!1),C("root")}},f))})]}),Rt=()=>i.jsxs(i.Fragment,{children:[i.jsx("div",{style:p,children:i.jsx(F,{label:"Audio Track",isBack:!0,onClick:()=>C("root")})}),i.jsx("div",{style:{padding:"4px 0"},children:_.map(f=>i.jsx(F,{label:f.label||f.language||f.id,selected:V===f.id,onClick:()=>{j(f.id),Y(f.id),N(!1),C("root")}},f.id))})]}),Dt=()=>i.jsxs(i.Fragment,{children:[i.jsx("div",{style:p,children:i.jsx(F,{label:"Subtitles",isBack:!0,onClick:()=>C("root")})}),i.jsxs("div",{style:{padding:"4px 0"},children:[i.jsx(F,{label:"Off",selected:te===null,onClick:()=>{A(null),se(null),N(!1),C("root")}},"off"),X.map((f,H)=>i.jsx(F,{label:f.label||f.language,selected:te===f.language,onClick:()=>{A(f.language),se(f.language),N(!1),C("root")}},f.url||`${f.language}-${H}`)),X.length===0&&i.jsx("div",{style:{padding:"10px 14px",color:"rgba(255,255,255,0.4)",fontSize:"13px"},children:"No subtitle tracks available"})]})]}),It=()=>i.jsxs(i.Fragment,{children:[i.jsx("div",{style:p,children:i.jsx(F,{label:"Subtitle Style",isBack:!0,onClick:()=>C("root")})}),i.jsxs("div",{style:{padding:"8px 14px 12px",display:"flex",flexDirection:"column",gap:"14px"},children:[i.jsxs("div",{children:[i.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:"6px"},children:[i.jsx("span",{style:{fontSize:"13px",color:"rgba(255,255,255,0.8)"},children:"Position"}),i.jsxs("span",{style:{fontSize:"12px",color:"rgba(255,255,255,0.5)"},children:[L.bottomOffset,"px from bottom"]})]}),i.jsx("input",{type:"range",min:10,max:200,step:5,value:L.bottomOffset,onChange:f=>w({bottomOffset:Number(f.target.value)}),style:{width:"100%",accentColor:"#3b82f6",cursor:"pointer"}})]}),i.jsxs("div",{children:[i.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:"6px"},children:[i.jsx("span",{style:{fontSize:"13px",color:"rgba(255,255,255,0.8)"},children:"Font Size"}),i.jsxs("span",{style:{fontSize:"12px",color:"rgba(255,255,255,0.5)"},children:[L.fontSize,"px"]})]}),i.jsx("input",{type:"range",min:12,max:40,step:1,value:L.fontSize,onChange:f=>w({fontSize:Number(f.target.value)}),style:{width:"100%",accentColor:"#3b82f6",cursor:"pointer"}})]}),i.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center"},children:[i.jsx("span",{style:{fontSize:"13px",color:"rgba(255,255,255,0.8)"},children:"Background"}),i.jsx("button",{onClick:()=>w({background:L.background?"":"rgba(0,0,0,0.75)"}),style:{padding:"4px 12px",borderRadius:"6px",border:"1px solid rgba(255,255,255,0.2)",background:L.background?"#3b82f6":"transparent",color:"#fff",fontSize:"12px",cursor:"pointer"},children:L.background?"On":"Off"})]}),i.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center"},children:[i.jsx("span",{style:{fontSize:"13px",color:"rgba(255,255,255,0.8)"},children:"Text Color"}),i.jsx("div",{style:{display:"flex",gap:"6px"},children:["#ffffff","#ffff00","#00ff00","#00cfff"].map(f=>i.jsx("button",{onClick:()=>w({color:f}),title:f,style:{width:"22px",height:"22px",borderRadius:"50%",background:f,border:L.color===f?"2px solid #3b82f6":"2px solid transparent",cursor:"pointer",outline:"none",padding:0,flexShrink:0}},f))})]})]})]}),_t=()=>{const f=oe.map(Z=>Z.bandwidth),H=oe.map(Z=>Z.bufferHealth),ye=W?.bandwidth??0,Pe=W?.bufferHealth??0,Bt=Z=>Z>=1e3?`${(Z/1e3).toFixed(2)} Mbps`:`${Z.toFixed(0)} kbps`,ve=(Z,$t)=>i.jsxs("div",{style:{background:"rgba(255,255,255,0.04)",borderRadius:"8px",padding:"7px 10px",flex:"1 1 0",minWidth:0},children:[i.jsx("div",{style:{fontSize:"10px",color:"rgba(255,255,255,0.4)",textTransform:"uppercase",letterSpacing:"0.06em",marginBottom:"3px"},children:Z}),i.jsx("div",{style:{fontSize:"12px",color:"#fff",fontFamily:"monospace",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:$t})]}),xe=W?.segmentUrl??"",Nt=xe.length>36?"…"+xe.slice(-36):xe||"—";return i.jsxs(i.Fragment,{children:[i.jsxs("div",{style:{...p,justifyContent:"space-between"},children:[i.jsx("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:i.jsx(F,{label:"Statistics",isBack:!0,onClick:()=>C("root")})}),i.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"6px",paddingRight:"14px",flexShrink:0},children:[i.jsx("span",{style:{width:"7px",height:"7px",borderRadius:"50%",background:"#22c55e",boxShadow:"0 0 6px #22c55e",animation:"statsPulse 1.6s ease-in-out infinite",display:"inline-block"}}),i.jsx("span",{style:{fontSize:"11px",color:"rgba(255,255,255,0.4)"},children:"LIVE"})]})]}),i.jsxs("div",{style:{padding:"0 14px 12px",overflowY:"auto",maxHeight:"420px"},children:[i.jsxs("div",{style:{marginTop:"12px"},children:[i.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"baseline",marginBottom:"6px"},children:[i.jsx("span",{style:{fontSize:"11px",color:"rgba(255,255,255,0.45)",textTransform:"uppercase",letterSpacing:"0.07em"},children:"Connection Speed"}),i.jsx("span",{style:{fontSize:"16px",fontWeight:600,color:"#4ade80",fontFamily:"monospace"},children:W?Bt(ye):"—"})]}),i.jsx("div",{style:{background:"rgba(0,0,0,0.3)",borderRadius:"8px",padding:"6px 8px"},children:i.jsx(qe,{values:f,color:"#4ade80",gradId:"bw-grad"})})]}),i.jsxs("div",{style:{marginTop:"14px"},children:[i.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"baseline",marginBottom:"6px"},children:[i.jsx("span",{style:{fontSize:"11px",color:"rgba(255,255,255,0.45)",textTransform:"uppercase",letterSpacing:"0.07em"},children:"Buffer Health"}),i.jsx("span",{style:{fontSize:"16px",fontWeight:600,color:"#60a5fa",fontFamily:"monospace"},children:W?`${Pe.toFixed(1)} s`:"—"})]}),i.jsx("div",{style:{background:"rgba(0,0,0,0.3)",borderRadius:"8px",padding:"6px 8px"},children:i.jsx(qe,{values:H,color:"#60a5fa",gradId:"buf-grad"})})]}),i.jsx("div",{style:{height:"1px",background:"rgba(255,255,255,0.07)",margin:"14px 0 12px"}}),i.jsxs("div",{style:{display:"flex",gap:"6px"},children:[ve("Codec",W?.codec||"—"),ve("Resolution",W?.resolution||"—"),ve("Dropped",W?`${W.droppedFrames}/${W.totalFrames}`:"—")]}),i.jsxs("div",{style:{display:"flex",gap:"6px",marginTop:"6px"},children:[ve("Stream",W?.streamType||"—"),i.jsxs("div",{style:{background:"rgba(255,255,255,0.04)",borderRadius:"8px",padding:"7px 10px",flex:"2 1 0",minWidth:0},children:[i.jsx("div",{style:{fontSize:"10px",color:"rgba(255,255,255,0.4)",textTransform:"uppercase",letterSpacing:"0.06em",marginBottom:"3px"},children:"Segment"}),i.jsx("div",{style:{fontSize:"11px",color:"rgba(255,255,255,0.7)",fontFamily:"monospace",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},title:xe,children:Nt})]})]})]}),i.jsx("style",{children:`
|
|
180
180
|
@keyframes statsPulse {
|
|
181
181
|
0%, 100% { opacity: 1; }
|
|
182
182
|
50% { opacity: 0.3; }
|
|
183
183
|
}
|
|
184
|
-
`})]})},Vt=()=>{switch(x){case"quality":return G();case"speed":return ae();case"audio":return Rt();case"subtitles":return Dt();case"subtitleStyle":return It();case"statistics":return _t();default:return
|
|
184
|
+
`})]})},Vt=()=>{switch(x){case"quality":return G();case"speed":return ae();case"audio":return Rt();case"subtitles":return Dt();case"subtitleStyle":return It();case"statistics":return _t();default:return B()}};return i.jsxs("div",{ref:de,style:{position:"relative",display:"inline-block"},children:[i.jsx("button",{className:"virtus-settings-btn","aria-label":"Settings","aria-haspopup":"menu","aria-expanded":R,onClick:Se,style:{background:R?"rgba(255,255,255,0.18)":"transparent",border:"none",color:"white",cursor:"pointer",padding:"8px",borderRadius:"8px",display:"flex",alignItems:"center",justifyContent:"center",width:"40px",height:"40px",transition:"all 0.2s ease"},onMouseEnter:f=>{const H=typeof r=="string"?r:r===!1?"transparent":"rgba(255,255,255,0.15)";f.currentTarget.style.background=H,f.currentTarget.style.transform="scale(1.05)"},onMouseLeave:f=>{f.currentTarget.style.background=R?"rgba(255,255,255,0.18)":"transparent",f.currentTarget.style.transform="scale(1)"},title:"Settings",children:n??i.jsxs("svg",{width:t,height:t,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",style:{transition:"transform 0.3s ease",transform:R?"rotate(45deg)":"rotate(0deg)"},children:[i.jsx("circle",{cx:"12",cy:"12",r:"3"}),i.jsx("path",{d:"M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-4 0v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83-2.83l.06-.06A1.65 1.65 0 0 0 4.68 15a1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1 0-4h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 2.83-2.83l.06.06A1.65 1.65 0 0 0 9 4.68a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 2.83l-.06.06A1.65 1.65 0 0 0 19.4 9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z"})]})}),R&&i.jsx(Ve.Provider,{value:h,children:i.jsx("div",{role:"menu","aria-label":"Settings menu",style:{...pi,background:l,border:`1px solid ${d}`,boxShadow:`0 12px 48px rgba(0,0,0,0.7), 0 0 0 1px ${d.replace("0.1)","0.08)")}`,width:x==="statistics"?"360px":"320px",...g==="bottom"?{top:"52px"}:{bottom:"52px"},...m==="left"?{left:0}:{right:0}},children:Vt()})}),i.jsx("style",{children:`
|
|
185
185
|
@keyframes settingsFadeIn {
|
|
186
186
|
from { opacity: 0; transform: translateY(8px) scale(0.97); }
|
|
187
187
|
to { opacity: 1; transform: translateY(0) scale(1); }
|
|
188
188
|
}
|
|
189
|
-
`})]})}function mi({label:a="AirPlay",className:e=""}){const t=pe(),[r,n]=c.useState(!1),[s,o]=c.useState(!1);c.useEffect(()=>{if(!t)return;n(t.isAirPlayAvailable()),o(t.isAirPlayActive());const
|
|
189
|
+
`})]})}function mi({label:a="AirPlay",className:e=""}){const t=pe(),[r,n]=c.useState(!1),[s,o]=c.useState(!1);c.useEffect(()=>{if(!t)return;n(t.isAirPlayAvailable()),o(t.isAirPlayActive());const d=({isAvailable:u,isActive:h})=>{n(u),o(h)};return t.events.on("airplaychange",d),()=>{t.events.off("airplaychange",d)}},[t]);const l=c.useCallback(()=>{t?.showAirPlayPicker()},[t]);return r?i.jsx("button",{className:`virtus-control-btn virtus-airplay-btn${s?" virtus-airplay-btn--active":""}${e?` ${e}`:""}`,onClick:l,title:s?`${a} (Connected)`:a,"aria-label":s?`${a} connected`:`Show ${a} devices`,"aria-pressed":s,children:i.jsxs("svg",{viewBox:"0 0 24 24",width:"20",height:"20",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[i.jsx("rect",{x:"2",y:"3",width:"20",height:"13",rx:"2",ry:"2"}),i.jsx("line",{x1:"8",y1:"21",x2:"16",y2:"21"}),i.jsx("line",{x1:"12",y1:"16",x2:"12",y2:"21"}),i.jsx("polygon",{points:"12,8 8,14 16,14",fill:s?"currentColor":"none",stroke:"currentColor",strokeWidth:"1.5"})]})}):null}function yi({label:a="Cast",className:e=""}){const t=pe(),[r,n]=c.useState(!1),[s,o]=c.useState(!1);c.useEffect(()=>{if(!t)return;n(t.isCastAvailable()),o(t.isCastActive());const d=({isAvailable:u,isActive:h})=>{n(u),o(h)};return t.events.on("castchange",d),()=>{t.events.off("castchange",d)}},[t]);const l=c.useCallback(()=>{s?t?.stopCasting():t?.showCastPicker()},[t,s]);return r?i.jsx("button",{className:`virtus-control-btn virtus-cast-btn${s?" virtus-cast-btn--active":""}${e?` ${e}`:""}`,onClick:l,title:s?`Stop ${a}ing`:`${a} to TV`,"aria-label":s?"Stop casting":"Cast to a device","aria-pressed":s,children:i.jsxs("svg",{viewBox:"0 0 24 24",width:"20",height:"20",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[i.jsx("path",{d:"M2 8V6a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2v12a2 2 0 0 1-2 2h-6"}),i.jsx("line",{x1:"8",y1:"20",x2:"16",y2:"20"}),i.jsx("path",{d:"M2 15a4 4 0 0 1 4 4",fill:"none"}),i.jsx("path",{d:"M2 11a8 8 0 0 1 8 8",fill:"none"}),i.jsx("circle",{cx:"2",cy:"20",r:"1",fill:s?"currentColor":"none",stroke:"currentColor",strokeWidth:"1.5"})]})}):null}function vi({x:a,y:e,isOpen:t,onClose:r,actions:n,theme:s}){const o={background:s?.background??"rgba(12, 12, 20, 0.97)",borderColor:s?.borderColor??"rgba(255,255,255,0.1)",textColor:s?.textColor??"#fff",dangerColor:s?.dangerColor??"#f87171",hoverBackground:s?.hoverBackground??"rgba(255,255,255,0.07)",iconBackground:s?.iconBackground??"rgba(255,255,255,0.08)",dividerColor:s?.dividerColor??"rgba(255,255,255,0.07)"},l=c.useRef(null);return c.useEffect(()=>{if(!t)return;const d=u=>{if("key"in u){u.key==="Escape"&&r();return}l.current&&!l.current.contains(u.target)&&r()};return document.addEventListener("mousedown",d),document.addEventListener("keydown",d),()=>{document.removeEventListener("mousedown",d),document.removeEventListener("keydown",d)}},[t,r]),t?i.jsxs(i.Fragment,{children:[i.jsx("div",{ref:l,role:"menu","aria-label":"Video options",style:{position:"absolute",left:a,top:e,zIndex:99998,background:o.background,backdropFilter:"blur(16px)",border:`1px solid ${o.borderColor}`,borderRadius:"14px",boxShadow:`0 12px 48px rgba(0,0,0,0.7), 0 0 0 1px ${o.borderColor}`,minWidth:"240px",padding:"4px 0",fontFamily:"system-ui, -apple-system, sans-serif",animation:"ctxFadeIn 0.14s ease-out",overflow:"hidden"},children:n.map((d,u)=>i.jsxs("div",{children:[i.jsxs("button",{role:"menuitem",onClick:()=>{d.onClick(),r()},style:{display:"flex",alignItems:"center",gap:"10px",width:"100%",padding:"9px 14px",background:"transparent",border:"none",color:d.danger?o.dangerColor:o.textColor,fontSize:"13.5px",textAlign:"left",cursor:"pointer",transition:"background 0.1s"},onMouseEnter:h=>{h.currentTarget.style.background=d.danger?"rgba(239,68,68,0.12)":o.hoverBackground},onMouseLeave:h=>{h.currentTarget.style.background="transparent"},children:[d.icon!==void 0&&i.jsx("span",{style:{width:"28px",height:"28px",borderRadius:"7px",background:d.danger?"rgba(239,68,68,0.15)":o.iconBackground,display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0,color:d.danger?o.dangerColor:o.textColor,fontSize:"13px",lineHeight:1},children:d.icon}),i.jsx("span",{style:{flex:1},children:d.label})]}),d.dividerAfter&&i.jsx("div",{style:{height:"1px",background:o.dividerColor,margin:"3px 0"}})]},u))}),i.jsx("style",{children:`
|
|
190
190
|
@keyframes ctxFadeIn {
|
|
191
191
|
from { opacity: 0; transform: scale(0.96) translateY(-4px); }
|
|
192
192
|
to { opacity: 1; transform: scale(1) translateY(0); }
|