playron 1.0.37 → 1.0.39
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/core/PlayerCore.d.ts.map +1 -1
- package/dist/playron.cjs.js +6 -6
- package/dist/playron.es.js +367 -361
- package/dist/ui/Player.d.ts.map +1 -1
- package/package.json +1 -1
package/dist/playron.cjs.js
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
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,E={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(E).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(E.PLAY,()=>{this.isPlaying=!0,this.emitPlayEvent()}),this.videoElement.addEventListener(E.PAUSE,()=>{this.isPlaying=!1,this.emitPauseEvent()}),this.videoElement.addEventListener(E.VOLUME_CHANGE,()=>{this.videoElement&&(this.volume=this.videoElement.volume,this.isMuted=this.videoElement.muted,this.emitVolumeChangeEvent())}),this.videoElement.addEventListener(E.TIME_UPDATE,()=>{this.videoElement&&(this.currentTime=this.videoElement.currentTime)}),this.videoElement.addEventListener(E.LOADED_METADATA,()=>{this.videoElement&&(this.duration=this.videoElement.duration)}),this.videoElement.addEventListener(E.RATE_CHANGE,()=>{this.videoElement&&(this.playbackRate=this.videoElement.playbackRate)}),this.videoElement.addEventListener(E.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,isBuffering:!1,isSeeking:!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 Ge{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 Xe{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 Xe;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 Gt(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 Xt(){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 Gt(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,Xt(),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 Ge,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(E.PLAY,()=>{this.events.emit("play",{timestamp:Date.now()})}),this.videoElement.addEventListener(E.PAUSE,()=>{this.events.emit("pause",{timestamp:Date.now()})}),this.videoElement.addEventListener(E.TIME_UPDATE,()=>{this.events.emit("timeupdate",{currentTime:this.videoElement?.currentTime||0,duration:this.videoElement?.duration||0})}),this.videoElement.addEventListener(E.ENDED,()=>{this.events.emit("ended",{timestamp:Date.now()})}),this.videoElement.addEventListener(E.LOADED_METADATA,()=>{this.events.emit("loadedmetadata",{duration:this.videoElement?.duration||0,videoWidth:this.videoElement?.videoWidth||0,videoHeight:this.videoElement?.videoHeight||0})}),this.videoElement.addEventListener(E.RATE_CHANGE,()=>{const e=this.videoElement?.playbackRate||1;this.stateManager?.set("playbackRate",e),this.events.emit("ratechange",{playbackRate:e})}),this.videoElement.addEventListener(E.SEEKING,()=>{this.stateManager?.set("isSeeking",!0),this.stateManager?.set("isBuffering",!0),this.events.emit("seeking",{targetTime:this.videoElement?.currentTime??0}),this.events.emit("buffering",{isBuffering:!0})}),this.videoElement.addEventListener(E.SEEKED,()=>{this.stateManager?.set("isSeeking",!1),this.events.emit("seeked",{currentTime:this.videoElement?.currentTime??0})}),this.videoElement.addEventListener(E.WAITING,()=>{this.stateManager?.set("isBuffering",!0),this.events.emit("buffering",{isBuffering:!0})}),this.videoElement.addEventListener(E.PLAYING,()=>{this.stateManager?.set("isBuffering",!1),this.stateManager?.set("isSeeking",!1),this.events.emit("buffering",{isBuffering:!1})}),this.videoElement.addEventListener(E.CAN_PLAY,()=>{this.stateManager?.set("isBuffering",!1),this.events.emit("buffering",{isBuffering:!1})}),this.videoElement.addEventListener(E.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(E.TIME_UPDATE,d),l.addEventListener(E.PLAY,u),l.addEventListener(E.PAUSE,u),l.addEventListener(E.VOLUME_CHANGE,h),l.addEventListener(E.LOADED_METADATA,d),()=>{e.events.off("livelatencyupdate",p),l.removeEventListener(E.TIME_UPDATE,d),l.removeEventListener(E.PLAY,u),l.removeEventListener(E.PAUSE,u),l.removeEventListener(E.VOLUME_CHANGE,h),l.removeEventListener(E.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:`
|
|
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,E={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(E).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(E.PLAY,()=>{this.isPlaying=!0,this.emitPlayEvent()}),this.videoElement.addEventListener(E.PAUSE,()=>{this.isPlaying=!1,this.emitPauseEvent()}),this.videoElement.addEventListener(E.VOLUME_CHANGE,()=>{this.videoElement&&(this.volume=this.videoElement.volume,this.isMuted=this.videoElement.muted,this.emitVolumeChangeEvent())}),this.videoElement.addEventListener(E.TIME_UPDATE,()=>{this.videoElement&&(this.currentTime=this.videoElement.currentTime)}),this.videoElement.addEventListener(E.LOADED_METADATA,()=>{this.videoElement&&(this.duration=this.videoElement.duration)}),this.videoElement.addEventListener(E.RATE_CHANGE,()=>{this.videoElement&&(this.playbackRate=this.videoElement.playbackRate)}),this.videoElement.addEventListener(E.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,isBuffering:!1,isSeeking:!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 Ge{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 Xe{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 Xe;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 Gt(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 Xt(){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 Gt(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,Xt(),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 Ge,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(E.PLAY,()=>{this.events.emit("play",{timestamp:Date.now()})}),this.videoElement.addEventListener(E.PAUSE,()=>{this.events.emit("pause",{timestamp:Date.now()})}),this.videoElement.addEventListener(E.TIME_UPDATE,()=>{this.events.emit("timeupdate",{currentTime:this.videoElement?.currentTime||0,duration:this.videoElement?.duration||0})}),this.videoElement.addEventListener(E.ENDED,()=>{this.events.emit("ended",{timestamp:Date.now()})}),this.videoElement.addEventListener(E.LOADED_METADATA,()=>{this.events.emit("loadedmetadata",{duration:this.videoElement?.duration||0,videoWidth:this.videoElement?.videoWidth||0,videoHeight:this.videoElement?.videoHeight||0})}),this.videoElement.addEventListener(E.RATE_CHANGE,()=>{const e=this.videoElement?.playbackRate||1;this.stateManager?.set("playbackRate",e),this.events.emit("ratechange",{playbackRate:e})}),this.videoElement.addEventListener(E.SEEKING,()=>{this.stateManager?.set("isSeeking",!0),this.stateManager?.set("isBuffering",!0),this.events.emit("seeking",{targetTime:this.videoElement?.currentTime??0}),this.events.emit("buffering",{isBuffering:!0})}),this.videoElement.addEventListener(E.SEEKED,()=>{this.stateManager?.set("isSeeking",!1),this.events.emit("seeked",{currentTime:this.videoElement?.currentTime??0})}),this.videoElement.addEventListener(E.WAITING,()=>{this.stateManager?.set("isBuffering",!0),this.events.emit("buffering",{isBuffering:!0})}),this.videoElement.addEventListener(E.PLAYING,()=>{this.stateManager?.set("isBuffering",!1),this.stateManager?.set("isSeeking",!1),this.events.emit("buffering",{isBuffering:!1})}),this.videoElement.addEventListener(E.CAN_PLAY,()=>{this.stateManager?.set("isBuffering",!1),this.events.emit("buffering",{isBuffering:!1})}),this.videoElement.addEventListener(E.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(),this.videoElement?.autoplay&&this.videoElement.play().catch(r=>{r instanceof DOMException&&(r.name==="AbortError"||r.name==="NotAllowedError")||console.warn("[PlayerCore] Autoplay failed:",r)})}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.videoElement?.autoplay&&this.videoElement.play().catch(r=>{r instanceof DOMException&&(r.name==="AbortError"||r.name)}),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(E.TIME_UPDATE,d),l.addEventListener(E.PLAY,u),l.addEventListener(E.PAUSE,u),l.addEventListener(E.VOLUME_CHANGE,h),l.addEventListener(E.LOADED_METADATA,d),()=>{e.events.off("livelatencyupdate",p),l.removeEventListener(E.TIME_UPDATE,d),l.removeEventListener(E.PLAY,u),l.removeEventListener(E.PAUSE,u),l.removeEventListener(E.VOLUME_CHANGE,h),l.removeEventListener(E.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(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,w=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 k=L.video||L.videoElement;if(!k)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 k.addEventListener(E.SEEKING,R),k.addEventListener(E.SEEKED,N),k.addEventListener(E.WAITING,x),k.addEventListener(E.PLAYING,C),k.addEventListener(E.CAN_PLAY,I),k.addEventListener(E.LOAD_START,$),()=>{k.removeEventListener(E.SEEKING,R),k.removeEventListener(E.SEEKED,N),k.removeEventListener(E.WAITING,x),k.removeEventListener(E.PLAYING,C),k.removeEventListener(E.CAN_PLAY,I),k.removeEventListener(E.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 k=L==="play"?j:S;return k?/^https?:\/\//.test(k)||/\.(jpg|jpeg|png|svg|gif|webp)$/i.test(k)?i.jsx("img",{src:k,alt:L==="play"?"Play":"Pause",className:J.customIcon,style:{"--icon-size":`${A}px`}}):i.jsx("div",{dangerouslySetInnerHTML:{__html:k},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"||w)&&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))},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 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:`
|
|
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(j=>j.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,w=a?.ui?.showPlayPauseIcons!==!1,P=a?.ui?.overlayIcons?.playIcon,S=a?.ui?.overlayIcons?.pauseIcon,A=a?.ui?.overlayIcons?.iconSize||40,b=a?.ui?.overlayIcons?.containerSize||80;c.useEffect(()=>{const j=s();if(!j)return;const k=j.video||j.videoElement;if(!k)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 k.addEventListener(E.SEEKING,R),k.addEventListener(E.SEEKED,N),k.addEventListener(E.WAITING,x),k.addEventListener(E.PLAYING,C),k.addEventListener(E.CAN_PLAY,I),k.addEventListener(E.LOAD_START,$),()=>{k.removeEventListener(E.SEEKING,R),k.removeEventListener(E.SEEKED,N),k.removeEventListener(E.WAITING,x),k.removeEventListener(E.PLAYING,C),k.removeEventListener(E.CAN_PLAY,I),k.removeEventListener(E.LOAD_START,$),g.current&&clearTimeout(g.current)}},[s,h]),c.useEffect(()=>{if(!h){u(t?"pause":"play"),l(!0);const j=setTimeout(()=>{l(!1)},600);return()=>clearTimeout(j)}},[t,h]);const y=c.useCallback(async()=>{await r()},[r]),q=c.useCallback(()=>{n()},[n]),z=j=>{const k=j==="play"?P:S;return k?/^https?:\/\//.test(k)||/\.(jpg|jpeg|png|svg|gif|webp)$/i.test(k)?i.jsx("img",{src:k,alt:j==="play"?"Play":"Pause",className:J.customIcon,style:{"--icon-size":`${A}px`}}):i.jsx("div",{dangerouslySetInnerHTML:{__html:k},className:J.customIcon,style:{"--icon-size":`${A}px`}}):j==="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"||w)&&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 P=s,S=P?P.fairplay&&!P.widevine&&!P.playready?"drm_fairplay_needed":!P.widevine&&!P.fairplay&&!P.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))},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 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); }
|
|
@@ -13,7 +13,7 @@
|
|
|
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,d=c.useCallback(p=>{if(!a)return;const g=p.touches[0],m=Date.now(),w=o.current;if(w&&m-w.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(),w=this.parseTrackingEvents(s,t),j=this.getErrorUrls(t),S=this.parseCompanions(s);return{id:o,title:l,duration:u,mediaFile:h,clickThrough:m,trackingEvents:w,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,w=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:w,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=`
|
|
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(),w=o.current;if(w&&m-w.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(),w=this.parseTrackingEvents(s,t),P=this.getErrorUrls(t),S=this.parseCompanions(s);return{id:o,title:l,duration:u,mediaFile:h,clickThrough:m,trackingEvents:w,errorUrls:P,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,w=d?.getAttribute("creativeType")??void 0,P=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:w,clickThrough:P,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;
|
|
@@ -113,7 +113,7 @@
|
|
|
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,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 w=g[m];w.text&&d.push(w.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 w=c.useRef(null),
|
|
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 w=g[m];w.text&&d.push(w.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 w=c.useRef(null),P=c.useRef(null),[S,A]=c.useState(null),b=c.useRef(null),[y,q]=c.useState(!1),[z,j]=c.useState(!1),k=c.useCallback(()=>j(!0),[]),R=c.useCallback(()=>j(!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:k});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(()=>{P.current&&(P.current.muted=r)},[r]),c.useEffect(()=>{if(!P.current||!w.current)return;console.log("[Player] Initializing PlayerCore");const V=new ne(P.current);return ne.preloadEngines(),V.container=w.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=G=>{q(G),d?.(G)},Y=new Hr(S,_,V);return b.current=Y,Y.setup().catch(G=>{console.error("[Player] Failed to setup ads:",G)}),()=>{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:w,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:P,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:P.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; }
|
|
@@ -167,7 +167,7 @@
|
|
|
167
167
|
`).replace(/\r/g,`
|
|
168
168
|
`).split(`
|
|
169
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,w]=c.useState(null),[
|
|
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,w]=c.useState(null),[P,S]=c.useState([]),A=c.useRef(null),{currentTime:b,duration:y,isLive:q,isPlaying:z,playbackRate:j}=O(),{seekTo:k,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:L}=$.current,D=j??1,B=(performance.now()-L)/1e3,X=Math.min(y||1/0,v+B*D);C(X)}I.current=requestAnimationFrame(K)},[z,j,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,G=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 L=Math.floor(v/3600),D=Math.floor(v%3600/60),B=Math.floor(v%60);return L>0?`${L}:${D.toString().padStart(2,"0")}:${B.toString().padStart(2,"0")}`:`${D}:${B.toString().padStart(2,"0")}`},ue=v=>{if(!d.current)return 0;const L=d.current.getBoundingClientRect(),D=(v.clientX-L.left)/L.width;return Math.max(0,Math.min(1,D))},me=v=>{if(!(M&&!T)){if(M&&T){k(_.start+v*V);return}y!==0&&k(v*y)}},Ce=v=>{if(M&&!T)return;v.preventDefault(),h(!0);const L=ue(v);me(L)},Te=v=>{if(!d.current)return;const L=ue(v);if(g(L),A.current){const D=T?_.start+L*V:L*y;w(A.current.getThumbnailAt(D))}},Me=()=>{g(null),w(null)};return c.useEffect(()=>{if(!u)return;const v=D=>{if(!d.current)return;const B=ue(D);g(B),me(B)},L=()=>{h(!1)};return window.addEventListener("mousemove",v),window.addEventListener("mouseup",L),()=>{window.removeEventListener("mousemove",v),window.removeEventListener("mouseup",L)}},[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 L=5,D=30,B=T?_.start:0,X=T?_.end:y;if(X!==0)switch(v.key){case"ArrowLeft":case"ArrowDown":v.preventDefault(),k(Math.max(B,b-L));break;case"ArrowRight":case"ArrowUp":v.preventDefault(),k(Math.min(X,b+L));break;case"PageDown":v.preventDefault(),k(Math.max(B,b-D));break;case"PageUp":v.preventDefault(),k(Math.min(X,b+D));break;case"Home":v.preventDefault(),k(B);break;case"End":v.preventDefault(),k(X);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&&P.map((v,L)=>{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"}},L)}),i.jsx("div",{style:{position:"absolute",left:0,top:0,height:"100%",width:`${G}%`,backgroundColor:te,borderRadius:`${oe}px`,transition:"none"}}),!M&&e.map(v=>{const L=y>0?v.startTime/y*100:0;return i.jsx("div",{style:{position:"absolute",left:`${L}%`,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,L)=>{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=>k(B)},`timeline-${L}-${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:`${G}%`,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,L=d.current?.offsetWidth??0,D=p*100,B=p*L,X=He/2;let ae="-50%";return B<X?ae="0%":L-B<X&&(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,7 +176,7 @@
|
|
|
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:d}=U(),[u,h]=c.useState(!1),[p,g]=c.useState(!1),m=c.useRef(null),w=a==="top"||a==="bottom",j=c.useCallback((x,C)=>{if(!m.current)return;const I=m.current.getBoundingClientRect(),$=w?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,w]),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=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"},L=w?{width:"4px",height:"100%",backgroundColor:n.trackColor,borderRadius:"2px",position:"relative"}:{width:"100%",height:"4px",backgroundColor:n.trackColor,borderRadius:"2px",position:"relative"},k=w?{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=w?{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:k}),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:w,setAudioTrack:j,setPlaybackRate:S,setSubtitleTrack:A,getPlayerStats:b}=U(),y=pe(),{playbackRate:q=1,isLive:z}=O(),{style:L,setStyle:k}=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(""),[G,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":G.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")})]})]}),X=()=>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:()=>{w(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"),G.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}`)),G.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=>k({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=>k({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:()=>k({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:()=>k({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:`
|
|
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),w=a==="top"||a==="bottom",P=c.useCallback((x,C)=>{if(!m.current)return;const I=m.current.getBoundingClientRect(),$=w?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,w]),S=c.useCallback(x=>{g(!0),s&&l(),P(x.clientX,x.clientY)},[P,s,l]);c.useEffect(()=>{if(!p)return;const x=I=>P(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,P]);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=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"},j=w?{width:"4px",height:"100%",backgroundColor:n.trackColor,borderRadius:"2px",position:"relative"}:{width:"100%",height:"4px",backgroundColor:n.trackColor,borderRadius:"2px",position:"relative"},k=w?{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=w?{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:j,children:[i.jsx("div",{style:k}),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:w,setAudioTrack:P,setPlaybackRate:S,setSubtitleTrack:A,getPlayerStats:b}=U(),y=pe(),{playbackRate:q=1,isLive:z}=O(),{style:j,setStyle:k}=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(""),[G,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":G.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"})]}),L=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:L,label:"Subtitle Style",value:`${j.fontSize}px`,onClick:()=>C("subtitleStyle")}),i.jsx(Ke,{}),i.jsx(F,{icon:D,label:"Statistics",onClick:()=>C("statistics")})]})]}),X=()=>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:()=>{w(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:()=>{P(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"),G.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}`)),G.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:[j.bottomOffset,"px from bottom"]})]}),i.jsx("input",{type:"range",min:10,max:200,step:5,value:j.bottomOffset,onChange:f=>k({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:[j.fontSize,"px"]})]}),i.jsx("input",{type:"range",min:12,max:40,step:1,value:j.fontSize,onChange:f=>k({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:()=>k({background:j.background?"":"rgba(0,0,0,0.75)"}),style:{padding:"4px 12px",borderRadius:"6px",border:"1px solid rgba(255,255,255,0.2)",background:j.background?"#3b82f6":"transparent",color:"#fff",fontSize:"12px",cursor:"pointer"},children:j.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:()=>k({color:f}),title:f,style:{width:"22px",height:"22px",borderRadius:"50%",background:f,border:j.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; }
|