Vue.component("video-player",{props:{referenceId:{type:String,required:!0},customBackgroundColor:{type:String,"default":"rgba(19, 21, 34)"},customIconColor:{type:String,"default":"white"},enableStopButton:{type:Boolean,"default":!1},enableCaptionButton:{type:Boolean,"default":!0},enableFullscreenButton:{type:Boolean,"default":!0},enablePlaybackSpeedButton:{type:Boolean,"default":!0},enableVideoQualityButton:{type:Boolean,"default":!0},roundedBottomBar:{type:String,"default":"0px"},autoplay:{type:Boolean,"default":!1},chapters:{type:Array,"default":()=>[]},enablePreview:{type:Boolean,"default":!1},vttFile:{type:String},backgroundVideo:{type:Boolean,"default":!1},hideDefaultControls:{type:Boolean,"default":!1}},data(){return{videoData:{},isPlaying:!1,isMuted:!1,volumeValue:1,seekValue:0,videoDuration:0,currentTime:0,totalWatchTime:0,liveWatchTime:0,watchTimeFormatted:"00:00:00",intervalId:null,showCaptions:!1,isFullScreen:!1,controlsVisible:!0,controlsHideTimeout:!0,controlsTimer:null,hideControlsTimer:null,isBuffering:!1,bufferedPercentage:0,playbackSpeed:1,showSpeedDropdown:!1,availableSpeeds:[.5,1,1.25,1.5,2],showQualityDropdown:!1,availableQualities:[],currentQuality:null,isPipSupported:!1,showShareOptions:!1,showMainDropdown:!1,socialPlatforms:[{name:"Facebook",icon:"icon-facebook",color:"customIconColor"},{name:"Twitter",icon:"icon-x",color:"customIconColor"},{name:"LinkedIn",icon:"icon-linkedin2",color:"customIconColor"},{name:"Instagram",icon:"icon-instagram",color:"customIconColor"},],dropdownTimer:null,isFocused:!1,isPreviewing:!1,hasStartedPlaying:!1,isMobile:!0,showSpeedModal:!1,showQualityModal:!1,showShareModal:!1,showDropdownModal:!1,showUnmuteButton:this.autoplay,isControlsHidden:!1}},computed:{playPauseIcon(){return this.isPlaying?"icon-pause2":"icon-play3"},formattedCurrentTime(){return this.formatTime(this.currentTime)},formattedDuration(){return this.formatTime(this.videoDuration)},fullscreenIcon(){return this.isFullScreen?"icon-exit2":"icon-fullscreen-landscape1"},captionIcon(){return this.showCaptions?"icon-subtitles_off":"icon-subtitles_on"},chapterMarkers(){return this.chapters.map(n=>({...n,position:n.timestamp/this.videoDuration*100}))}},mounted(){this.fetchVideoData();const n=this.$refs.video;n.playbackRate=this.playbackSpeed;screen.orientation&&screen.orientation.addEventListener("change",this.handleOrientationChange);window.addEventListener("orientationchange",this.handleOrientationChange);this.updateVideoOrientation();document.addEventListener("fullscreenchange",this.onFullScreenChange);document.addEventListener("webkitfullscreenchange",this.onFullScreenChange);document.addEventListener("mozfullscreenchange",this.onFullScreenChange);document.addEventListener("msfullscreenchange",this.onFullScreenChange);document.addEventListener("click",this.closeDropdownsOnOutsideClick);this.$el.addEventListener("click",this.handleVideoFocus);document.addEventListener("click",this.handleVideoBlur);n.addEventListener("loadedmetadata",()=>{this.updateVideoDuration(),this.updateSeekBar()});n.addEventListener("timeupdate",this.updateSeekBar);n.addEventListener("click",this.togglePlayPauseOnClick);this.$refs.videoPlay.addEventListener("input",this.seekVideo);this.$refs.volumeBar.addEventListener("click",this.adjustVolumeFromBar);n.addEventListener("ended",this.onVideoEnded);n.addEventListener("play",this.onVideoPlay);n.addEventListener("pause",this.onVideoPause);n.addEventListener("ended",this.onVideoPause);n.addEventListener("waiting",this.onBuffering);n.addEventListener("playing",this.onPlaying);this.autoplay&&(n.muted=!0,n.addEventListener("loadedmetadata",()=>{n.play().then(()=>{this.isPlaying=!0,this.isMuted=!0,this.resetControlsTimer()}).catch(n=>{console.warn("Autoplay failed:",n)})}),n.load());this.$el.addEventListener("mouseover",this.showControls);this.$el.addEventListener("mousemove",this.resetControlsTimer);this.$el.addEventListener("mousemove",this.onMouseMove);this.$el.addEventListener("mouseleave",this.onMouseLeave);n.addEventListener("mouseenter",this.startPreview);n.addEventListener("mouseleave",this.stopPreview);n.addEventListener("click",this.handleVideoClick);this.updateIsMobile();window.addEventListener("resize",this.updateIsMobile);document.addEventListener("click",n=>{this.$el.contains(n.target)||this.closeAllModals()});this.backgroundVideo&&(n.muted=!0,n.loop=!0,n.addEventListener("loadedmetadata",()=>{(n.paused||n.ended)&&(n.load(),n.play().catch(n=>{console.warn("Autoplay was blocked by the browser:",n)}))}),n.load(),this.controlsVisible=!1);n.addEventListener("loadedmetadata",()=>{if(n.textTracks&&n.textTracks.length>0){const t=n.textTracks[0];t.mode=this.showCaptions?"showing":"hidden";t.addEventListener("cuechange",()=>{if(t.activeCues&&t.activeCues.length>0){const n=t.activeCues[0],r=n.text.length,i=Math.ceil(r/80);n.line=this.isControlsHidden?-1-i:-2-i}})}});this.isPipSupported="pictureInPictureEnabled"in document},beforeDestroy(){screen.orientation&&screen.orientation.removeEventListener("change",this.handleOrientationChange);window.removeEventListener("orientationchange",this.handleOrientationChange);document.removeEventListener("fullscreenchange",this.onFullScreenChange);document.removeEventListener("webkitfullscreenchange",this.onFullScreenChange);document.removeEventListener("mozfullscreenchange",this.onFullScreenChange);document.removeEventListener("msfullscreenchange",this.onFullScreenChange);document.removeEventListener("click",this.handleVideoBlur);document.removeEventListener("click",this.closeDropdownsOnOutsideClick);const n=this.$refs.video;n.removeEventListener("timeupdate",this.updateSeekBar);this.$refs.videoPlay.removeEventListener("input",this.seekVideo);n.removeEventListener("click",this.togglePlayPauseOnClick);this.$refs.volumeBar.removeEventListener("click",this.adjustVolumeFromBar);n.removeEventListener("loadedmetadata",this.updateVideoDuration);n.removeEventListener("ended",this.onVideoEnded);n.removeEventListener("mouseenter",this.startPreview);n.removeEventListener("mouseleave",this.stopPreview);n.removeEventListener("click",this.handleVideoClick);n.removeEventListener("timeupdate",this.handlePreviewLoop);n.removeEventListener("waiting",this.onBuffering);n.removeEventListener("playing",this.onPlaying);this.intervalId&&clearInterval(this.intervalId);this.$el.removeEventListener("mouseover",this.showControls);this.$el.removeEventListener("mousemove",this.resetControlsTimer);this.$el.removeEventListener("mousemove",this.onMouseMove);this.$el.removeEventListener("mouseleave",this.onMouseLeave);this.controlsTimer&&clearTimeout(this.controlsTimer);this.hideControlsTimer&&clearTimeout(this.hideControlsTimer);window.removeEventListener("resize",this.updateIsMobile)},methods:{logInfo(n){console.log(`INFO: ${n}`)},logError(n){console.error(`ERROR: ${n}`)},jumpToChapter(n){const t=this.$refs.video;t.readyState>=3?(t.currentTime=n,t.play()):t.addEventListener("canplay",()=>{t.currentTime=n,t.play()},{once:!0});this.$nextTick(()=>{this.updateChapterMarkers()})},updateChapterMarkers(){const n=this.videoDuration;this.chapterMarkers.forEach(t=>{const i=document.querySelector(`.chapter-marker[data-index="${t.index}"]`);if(i){const r=t.timestamp/n*100;i.style.left=`${r}%`}})},handleKeyboardControls(n){if(this.isFocused){const t=this.$refs.video;switch(n.key){case" ":this.togglePlayPause();this.showControls();n.preventDefault();break;case"s":this.stopVideo();this.showControls();break;case"ArrowRight":t.currentTime=Math.min(t.duration,t.currentTime+10);this.showControls();break;case"ArrowLeft":t.currentTime=Math.max(0,t.currentTime-10);this.showControls();break;case"f":this.toggleFullScreen();this.showControls();break;case"m":this.toggleMute();this.showControls()}}},formatTimeToHHMMSS(n){(typeof n!="number"||isNaN(n))&&(console.error("Invalid seconds value:",n),n=0);const t=Math.floor(n/3600),i=Math.floor(n%3600/60),r=Math.floor(n%60);return`${t.toString().padStart(2,"0")}:${i.toString().padStart(2,"0")}:${r.toString().padStart(2,"0")}`},fetchVideoData(){const n=VideoPlayers.videoDataMap[this.referenceId];n?(this.videoData=n,this.processVideoSources(),this.totalWatchTime=n.watchTime?n.watchTime:0,this.lastRecordedTime=0,this.playSessionTime=0):console.error(`No video data found for referenceId: ${this.referenceId}`)},processVideoSources(){const n=this.videoData.sources.filter(n=>n.codec==="H264"&&n.height&&n.width),t=n.reduce((n,t)=>{const i=`${t.height}x${t.width}`;return n[i]||(n[i]=[]),n[i].push(t),n},{});this.availableQualities=Object.entries(t).map(([n,t])=>{const[i,r]=n.split("x").map(Number),u=this.getQualityLabel(i),f=t.find(n=>n.src.startsWith("https://")),e=t.find(n=>n.src.startsWith("http://")),o=f||e;return{label:u,height:i,width:r,src:o.src}}).sort((n,t)=>t.height-n.height);this.availableQualities.length>0&&this.setVideoQuality(this.availableQualities[0].label)},getQualityLabel(n){return n>=2160?"4K":n>=1440?"1440p":n>=1080?"1080p":n>=720?"720p":n>=480?"480p":n>=360?"360p":"240p"},togglePlayPauseOnClick(){this.togglePlayPause()},togglePlayPause(){const n=this.$refs.video;this.backgroundVideo||(n.paused||n.ended?(n.play(),this.isPlaying=!0,this.hasStartedPlaying=!0):(n.pause(),this.isPlaying=!1),this.updatePlayPauseIcon())},updatePlayPauseIcon(){this.$nextTick(()=>{this.$refs.playPauseIcon&&(this.$refs.playPauseIcon.className=this.isPlaying?"icon-pause2":"icon-play3")})},stopVideo(){const n=this.$refs.video;n.pause();n.currentTime=0;this.isPlaying=!1;this.seekValue=0;this.currentTime=0;this.updateSeekBar()},onVideoEnded(){this.stopVideo()},setPlaybackSpeed(n){this.playbackSpeed=n;this.$refs.video.playbackRate=n;this.showSpeedDropdown=!1;this.showSpeedModal=!1;this.showQualityModal=!1;this.showShareModal=!1;this.showDropdownModal=!1},setVideoQuality(n){const t=this.availableQualities.find(t=>t.label===n);if(t&&t.label!==this.currentQuality){const n=this.$refs.video.currentTime,i=!this.$refs.video.paused;this.currentQuality=t.label;this.$refs.video.src=t.src;this.$refs.video.load();this.$refs.video.currentTime=n;this.$refs.video.oncanplay=()=>{i&&this.$refs.video.play(),this.$refs.video.oncanplay=null}}this.showQualityDropdown=!1;this.showSpeedModal=!1;this.showQualityModal=!1;this.showShareModal=!1;this.showDropdownModal=!1},toggleMainDropdown(){this.showMainDropdown=!this.showMainDropdown;const n=this.$refs.dropdownButton;this.showMainDropdown?n.classList.add("rotate-right"):n.classList.remove("rotate-right");this.showSpeedDropdown=!1;this.showQualityDropdown=!1;this.showShareOptions=!1},toggleSpeedDropdown(){this.showSpeedDropdown=!this.showSpeedDropdown;this.showQualityDropdown=!1;this.showShareOptions=!1},toggleQualityDropdown(){this.showQualityDropdown=!this.showQualityDropdown;this.showSpeedDropdown=!1;this.showShareOptions=!1},toggleShareOptions(n){n.stopPropagation();this.showShareOptions=!this.showShareOptions;this.showSpeedDropdown=!1;this.showQualityDropdown=!1},updateSeekBar(){const n=this.$refs.video;this.seekValue=n.currentTime;this.currentTime=n.currentTime;const r=this.currentTime/this.videoDuration*100,t=n.buffered;let i=0;if(t.length>0){const n=t.end(t.length-1);i=n/this.videoDuration*100}this.$refs.playedProgress&&(this.$refs.playedProgress.style.width=`${r}%`);this.$refs.bufferBar&&(this.$refs.bufferBar.style.width=`${i}%`);this.$nextTick(()=>{this.$refs.videoPlay&&(this.$refs.videoPlay.value=this.seekValue)})},seekVideo(n){this.$nextTick(()=>{if(this.$refs.videoPlay){const t=n.target.value;this.$refs.video.currentTime=t}})},formatTime(n){const t=Math.floor(n/3600),i=Math.floor(n%3600/60),r=Math.floor(n%60);return`${t.toString().padStart(2,"0")}:${i.toString().padStart(2,"0")}:${r.toString().padStart(2,"0")}`},toggleMute(){const n=this.$refs.video;n.muted=!n.muted;this.isMuted=n.muted;this.volumeValue=this.isMuted?0:n.volume;this.updateVolumeBar();this.isMuted||(this.showUnmuteButton=!1)},changeVolume(){const n=parseFloat(this.volumeValue),t=this.$refs.video;t.volume=n;this.isMuted=n===0;t.muted=this.isMuted;this.updateVolumeBar()},updateVolumeBar(){const n=this.volumeValue*100;this.$refs.volumeProgress&&(this.$refs.volumeProgress.style.width=`${n}%`)},adjustVolumeFromBar(n){const i=this.$refs.volumeBar.getBoundingClientRect(),r=n.clientX-i.left,u=i.width,t=Math.max(0,Math.min(1,r/u));this.volumeValue=t;this.$refs.video.volume=t;this.isMuted=t===0;this.$refs.video.muted=this.isMuted;this.updateVolumeBar()},toggleFullScreen(){const n=this.$el;document.fullscreenElement?document.exitFullscreen&&document.exitFullscreen():n.requestFullscreen?n.requestFullscreen():n.mozRequestFullScreen?n.mozRequestFullScreen():n.webkitRequestFullscreen?n.webkitRequestFullscreen():n.msRequestFullscreen&&n.msRequestFullscreen()},toggleCC(){this.showCaptions=!this.showCaptions;const n=this.$refs.video.textTracks[0];n.mode=this.showCaptions?"showing":"hidden"},async shareVideo(){const n=window.location.href;if(navigator.share)try{await navigator.share({title:"Check out this video!",url:n})}catch(t){console.error("Error sharing video:",t)}else prompt("Copy this link to share:",n)},onFullScreenChange(){this.isFullScreen=!!document.fullscreenElement;this.isFullScreen?(this.showControls(),this.resetScreenTimer()):(this.showControls(),this.controlsTimer&&clearTimeout(this.controlsTimer))},updateFullScreenState(){this.isFullScreen=!!(document.fullscreenElement||document.webkitFullscreenElement||document.mozFullScreenElement||document.msFullscreenElement);console.log("Is Fullscreen:",this.isFullScreen);this.isFullScreen?(console.log("Entered fullscreen"),this.resetScreenTimer()):(console.log("Exited fullscreen"),this.showControls(),this.controlsTimer&&clearTimeout(this.controlsTimer))},closeDropdownsOnOutsideClick(n){this.$el.contains(n.target)||(this.showSpeedDropdown=!1,this.showQualityDropdown=!1,this.showShareOptions=!1,this.resetScreenTimer())},handleVideoFocus(n){n.stopPropagation();window.currentFocusedVideo&&window.currentFocusedVideo!==this&&(window.currentFocusedVideo.isFocused=!1,document.removeEventListener("keydown",window.currentFocusedVideo.handleKeyboardControls));this.isFocused=!0;window.currentFocusedVideo=this;document.addEventListener("keydown",this.handleKeyboardControls)},handleVideoBlur(n){this.$el.contains(n.target)||(this.isFocused=!1,document.removeEventListener("keydown",this.handleKeyboardControls),window.currentFocusedVideo=null)},animateCueLine(){const n=this.$refs.video.textTracks[0];if(n&&n.activeCues.length>0){const t=n.activeCues[0],e=window.innerWidth<=768?50:80,o=t.text.length,i=Math.ceil(o/e),r=this.isControlsHidden?-1-i:-2-i,u=t.line,s=500,h=performance.now(),f=n=>{const e=n-h,i=Math.min(e/s,1);t.line=u+(r-u)*i;i<1?requestAnimationFrame(f):t.line=r};requestAnimationFrame(f)}},showControls(){this.controlsVisible=!0;this.isControlsHidden=!1;this.animateCueLine();this.hideControlsTimer&&clearTimeout(this.hideControlsTimer);this.$nextTick(()=>{this.$refs.controls&&(this.$refs.controls.style.transition="transform 1s ease-in-out, opacity 1s ease-in-out",this.$refs.controls.style.transform="translateY(1px)",this.$refs.controls.style.opacity="1",setTimeout(()=>{document.querySelector(".video-player").classList.remove("captionMoveBottom")},600))});this.resetControlsTimer()},hideControls(){this.showQualityDropdown||this.showShareOptions||this.showSpeedDropdown||!this.isPlaying||(this.controlsVisible=!0,this.isControlsHidden=!0,this.animateCueLine(),this.$nextTick(()=>{this.$refs.controls&&(this.$refs.controls.style.transition="transform 1s ease-in-out, opacity 1s ease-in-out",this.$refs.controls.style.transform="translateY(100%)",this.$refs.controls.style.opacity="0",setTimeout(()=>{document.querySelector(".video-player").classList.add("captionMoveBottom")},600))}))},resetControlsTimer(){this.controlsTimer&&clearTimeout(this.controlsTimer);this.controlsTimer=setTimeout(()=>{this.$el.matches(":hover")||this.hideControls()},3e3)},resetScreenTimer(){this.controlsHideTimeout&&clearTimeout(this.controlsHideTimeout);this.showQualityDropdown||this.showShareOptions||this.showSpeedDropdown||(this.controlsHideTimeout=setTimeout(()=>{this.hideControls(),this.$el.style.cursor="none"},3e3))},onMouseMove(){this.showControls();this.$el.style.cursor="default";this.resetScreenTimer()},onMouseLeave(){this.hideControlsTimer&&clearTimeout(this.hideControlsTimer);this.hideControlsTimer=setTimeout(()=>{this.isFullScreen||this.hideControls()},2e3)},updateVideoDuration(){const n=this.$refs.video;this.videoDuration=n.duration},onBuffering(){this.isBuffering=!0},onPlaying(){this.isBuffering=!1;this.isPlaying&&(this.lastRecordedTime=this.$refs.video.currentTime)},togglePictureInPicture(){document.pictureInPictureElement?document.exitPictureInPicture():document.pictureInPictureEnabled&&this.$refs.video.requestPictureInPicture()},async updateWatchTimeOnServer(n){try{const t=this.formatTimeToHHMMSS(n);console.log("Watch time being sent to server:",t);const i=await axios.post("https://britecove-api.connectid.cloud/api/updatewatchtime",{referenceids:this.referenceId,watchTime:t});console.log("Watch time updated on server:",i.data)}catch(t){console.error("Error updating watch time on server:",t);t.response&&console.error("Server error:",t.response.data)}},onVideoPlay(){this.isPlaying=!0;this.lastRecordedTime=this.$refs.video.currentTime},onVideoPause(){this.isPlaying=!1;const t=this.$refs.video.currentTime,n=t-this.lastRecordedTime;n>0&&(this.totalWatchTime+=n,this.playSessionTime=n);this.updateWatchTimeOnServer(this.playSessionTime)},onVideoEnded(){this.isPlaying=!1;this.updateWatchTimeOnServer(this.playSessionTime);this.stopVideo()},formatTime(n){const t=Math.floor(n/3600),i=Math.floor(n%3600/60),r=Math.floor(n%60);return`${t.toString().padStart(2,"0")}:${i.toString().padStart(2,"0")}:${r.toString().padStart(2,"0")}`},shareVideo(n){const i=window.location.href;let t;try{switch(n){case"Facebook":t=`https://www.facebook.com/sharer/sharer.php?u=${encodeURIComponent(i)}`;break;case"Twitter":t=`https://twitter.com/intent/tweet?url=${encodeURIComponent(i)}`;break;case"LinkedIn":t=`https://www.linkedin.com/sharing/share-offsite/?url=${encodeURIComponent(i)}`;break;case"Instagram":t=`https://www.instagram.com/?igshid=${encodeURIComponent(i)}`;break;case"CopyLink":navigator.clipboard.writeText(i).then(()=>{this.logInfo("URL copied to clipboard."),this.showToast("Link copied to clipboard!")}).catch(n=>{console.error(`Failed to copy the URL:`,n),this.errorMessage="Unable to copy the link. Please try again."});return;default:t=i}t&&window.open(t,"_blank");this.showShareOptions=!1;this.showSpeedModal=!1;this.showQualityModal=!1;this.showShareModal=!1;this.showDropdownModal=!1;this.logInfo(`Shared video to ${n}`)}catch(r){console.error(`Error sharing video to ${n}:`,r);this.errorMessage="An error occurred while trying to share the video. Please try again."}},startPreview(){if(this.enablePreview&&!this.isPlaying&&!this.hasStartedPlaying){const n=this.$refs.video;n.currentTime=0;n.muted=!0;this.isPreviewing=!0;n.play();n.addEventListener("timeupdate",this.handlePreviewLoop);this.controlsVisible=!1}},stopPreview(){if(this.isPreviewing){const n=this.$refs.video;n.pause();this.isPreviewing=!1;n.currentTime=0;n.removeEventListener("timeupdate",this.handlePreviewLoop);this.controlsVisible=!1}},handlePreviewLoop(){const n=this.$refs.video;n.currentTime>=5&&(n.currentTime=0)},handleVideoClick(){this.isPreviewing&&this.stopPreview();this.togglePlayPause();this.hasStartedPlaying=!0},updateIsMobile(){const n="ontouchstart"in window||navigator.maxTouchPoints>0,t=window.innerWidth<=768;this.isMobile=n&&t;console.log("Mobile device detection:",this.isMobile)},showToast(n){const u=()=>document.fullscreenElement||document.webkitFullscreenElement||document.mozFullScreenElement||document.msFullscreenElement||document.body;let t=document.getElementById("toast-container");t||(t=document.createElement("div"),t.id="toast-container",t.classList.add("toast-container"));const i=document.createElement("div");i.className="toast-message";i.textContent=n;t.appendChild(i);const r=u();r.contains(t)||r.appendChild(t);requestAnimationFrame(()=>{i.classList.add("toast-show")});setTimeout(()=>{i.classList.remove("toast-show"),setTimeout(()=>{t.removeChild(i),t.children.length||t.remove()},300)},3e3)},handleFullscreenChange(){const n=document.getElementById("toast-container");if(n){const t=getFullscreenElement();t.contains(n)||t.appendChild(n)}},async handleFullscreenChange(){const n=document.fullscreenElement||document.webkitFullscreenElement||document.mozFullScreenElement||document.msFullscreenElement;n?await this.setFullscreenOrientation():screen.orientation&&screen.orientation.unlock&&await screen.orientation.unlock()},async setFullscreenOrientation(){const n=this.$refs.video;if(n){const t=n.videoWidth,i=n.videoHeight,r=t>i;try{screen.orientation&&screen.orientation.lock&&await screen.orientation.lock(r?"landscape":"portrait")}catch(u){console.warn("Failed to lock orientation:",u)}}},handleOrientationChange(){this.updateVideoOrientation()},updateVideoOrientation(){const n=this.$refs.video;if(n){const t=window.innerWidth>window.innerHeight;t?(n.classList.add("landscape"),n.classList.remove("portrait")):(n.classList.add("portrait"),n.classList.remove("landscape"))}},async toggleFullScreen(){const n=this.$el;document.fullscreenElement||document.webkitFullscreenElement||document.mozFullScreenElement||document.msFullscreenElement?document.exitFullscreen?await document.exitFullscreen():document.webkitExitFullscreen?await document.webkitExitFullscreen():document.mozCancelFullScreen?await document.mozCancelFullScreen():document.msExitFullscreen&&await document.msExitFullscreen():n.requestFullscreen?await n.requestFullscreen():n.webkitRequestFullscreen?await n.webkitRequestFullscreen():n.mozRequestFullScreen?await n.mozRequestFullScreen():n.msRequestFullscreen&&await n.msRequestFullscreen()},toggleDropdownModal(){this.showDropdownModal=!this.showDropdownModal},openSubModal(n){this.showDropdownModal=!1;n==="speed"&&(this.showSpeedModal=!0);n==="quality"&&(this.showQualityModal=!0);n==="share"&&(this.showShareModal=!0)},closeAllModals(){this.showDropdownModal=!1;this.showSpeedModal=!1;this.showQualityModal=!1;this.showShareModal=!1},handleContextMenu(n){n.preventDefault();console.log("Custom context menu triggered")}},template:`
        <div class="video-player" :class="{ 'full-screen': isFullScreen }" @mousemove="onMouseMove">
            <video ref="video" preload="none" class="video" :poster="videoData.poster" @click="togglePlayPause" @contextmenu.prevent="handleContextMenu($event)">
                <source v-for="source in videoData.sources" :key="source.src" :src="source.src" :type="source.type" />

                <!-- Captions track -->
                <track v-if="vttFile" kind="subtitles" :src="vttFile" default />

                Your browser does not support the video tag.
            </video>
            <div class="loader" v-if="isBuffering"></div> <!-- Loader element -->
            
            <!-- Picture-in-Picture button -->
            <button class="pip-button" @click="togglePictureInPicture" v-if="isPipSupported && !isMobile && !backgroundVideo">
                <i class="icon-pip-icon" ></i>
            </button>

            <div v-if="showUnmuteButton" class="unmute-button" @click="toggleMute" :style="{ background: customBackgroundColor, color: customIconColor }">
                <i class="icon-volume-mute2" :style="{ color: customIconColor }"></i> <span>Tap to unmute</span>
            </div>

            <div class="main-options-button-wrapper" v-if="isMobile && !hideDefaultControls">
                <button class="main-options-button" @click="toggleDropdownModal" ref="dropdownButton" >
                    <i class="icon-cog" :style="{ color: customIconColor }"></i>
                </button>
            </div>

            <!-- Main Settings Modal -->
            <div id="dropdownModal" class="custom-modal" v-show="showDropdownModal" @click.self="closeAllModals">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5>Settings</h5>
                        <!-- <button class="close-btn" @click="closeAllModals">×</button> -->
                    </div>
                    <div class="modal-body">
                        <button class="sub-option" @click="openSubModal('speed')">
                            <i class="icon-playback1"></i>
                            <span>Playback Speed</span>
                        </button>
                        <button class="sub-option" @click="openSubModal('quality')">
                            <i class="icon-cog"></i>
                            <span>Video Quality</span>
                        </button>
                        <button class="sub-option" @click="openSubModal('share')">
                            <i class="icon-share2"></i>
                            <span>Share</span>
                        </button>
                    </div>
                </div>
            </div>

            <!-- Playback Speed Modal -->
            <div class="custom-modal" id="speedModal" tabindex="-1" aria-labelledby="speedModalLabel" v-if="showSpeedModal" @click.self="closeAllModals">
                <div class="modal-dialog modal-dialog-centered">
                    <div class="modal-content">
                        <div class="modal-header">
                            <h5 class="modal-title" id="speedModalLabel">Playback Speed</h5>
                        <!--    <button type="button" class="btn-close" @click="toggleSpeedModal"></button>-->
                        </div>
                        <div class="modal-body">
                            <button v-for="speed in availableSpeeds" :key="speed" 
                                @click="setPlaybackSpeed(speed)"
                                :class="{ 'active-speed': speed === playbackSpeed }">{{ speed }}x
                            </button>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Video Quality Modal -->
            <div class="custom-modal" id="qualityModal" tabindex="-1" aria-labelledby="qualityModalLabel" v-if="showQualityModal" @click.self="closeAllModals">
                <div class="modal-dialog modal-dialog-centered">
                    <div class="modal-content">
                        <div class="modal-header"> 
                            <h5 class="modal-title" id="qualityModalLabel">Video Quality</h5>
                        <!--<button type="button" class="btn-close" @click="toggleQualityModal"></button> -->
                        </div>
                        <div class="modal-body">
                            <button v-for="quality in availableQualities" :key="quality.label" @click="setVideoQuality(quality.label)" :class="{ 'active-quality': currentQuality === quality.label }">
                            {{ quality.label }}
                            </button>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Share Options Modal -->
            <div class="custom-modal" id="shareModal" tabindex="-1" aria-labelledby="shareModalLabel" v-if="showShareModal" @click.self="closeAllModals">
                <div class="modal-dialog modal-dialog-centered">
                    <div class="modal-content">
                        <div class="modal-header">
                            <h5 class="modal-title" id="shareModalLabel">Share Options</h5>
                        <!--    <button type="button" class="btn-close" @click="toggleShareModal"></button> -->
                        </div>
                        <div class="modal-body">
                            <button v-for="platform in socialPlatforms" :key="platform.name" @click="shareVideo(platform.name)">
                                <i :class="platform.icon"></i>
                                <span>{{platform.name}}</span> 
                            </button>
                            <button @click="shareVideo('CopyLink')">
                                <i class="icon-link"></i> 
                                <span>Copy Link</span> 

                            </button>
                        </div>
                    </div>
                </div>
            </div>


        
            
            <div class="controls" ref="controls" :style="{ background: customBackgroundColor, borderRadius: roundedBottomBar}" v-show="!isPreviewing && controlsVisible && !backgroundVideo && !hideDefaultControls">
                <button @click="togglePlayPause" >
                    <i :class="playPauseIcon" :style="{ color: customIconColor }"></i>
                </button>
                
                <!-- Stop Button -->
                <button @click="stopVideo" v-if="enableStopButton">
                    <i class="icon-stop2" :style="{ color: customIconColor }"></i>
                </button>

                <span class="timer-start" :style="{ color: customIconColor }">{{ formattedCurrentTime }}</span>
               
            <div class="video-play-container">
                <!-- Custom video progress bar -->
                <div class="video-progress-bar" ref="playedProgress" :style="{ backgroundColor: customIconColor }"></div>
                
                <!-- Buffered progress bar -->
                <div class="buffer-bar" ref="bufferBar"></div>

                <!-- Chapter markers -->
                    <div class="chapter-marker" v-for="(marker, index) in chapterMarkers" :key="index"
                         :style="{ left: marker.position + '%', background: customBackgroundColor }" @click="jumpToChapter(marker.timestamp)">
                        <div class="chapter-tooltip">{{ marker.title }}</div> <!-- Tooltip showing chapter title -->
                    </div>
                
                <!-- The actual range input -->
                <input class="video-play no-thumb" type="range" @input="seekVideo" v-model="seekValue" :max="videoDuration" ref="videoPlay" />
            </div>
       
                
                <span class="timer-end" :style="{ color: customIconColor }">{{ formattedDuration }}</span>
                

                <button class="volume" @click="toggleMute" v-show="!isMobile">
                    <i :class="isMuted ? 'icon-volume-mute2' : 'icon-volume-high'" :style="{ color: customIconColor }"></i>
                </button>

                <!-- Volume bar container -->
                <div class="volume-bar" ref="volumeBar" v-show="!isMobile">
                    <!-- Hidden range input for volume control -->
                    <input class="video-setting no-thumb" type="range" max="1" step="0.01" v-model="volumeValue" @input="changeVolume">
                    
                    <!-- Custom volume progress bar -->
                    <div class="volume-progress-bar" :style="{ backgroundColor: customIconColor }" ref="volumeProgress"></div>
                </div>
                
                <div class="playback-speed" v-if="enablePlaybackSpeedButton" v-show="!isMobile">
                    <button @click="toggleSpeedDropdown">
                    <i class="icon-playback-speed" :style="{ color: customIconColor }"></i>
                    </button>
                   <div class="dropdown-menu" :class="{ 'active': showSpeedDropdown }" :style="{background: customBackgroundColor}">
                    <button v-for="speed in availableSpeeds" :key="speed" 
                    @click="setPlaybackSpeed(speed)"
                    :class="{ 'active-speed': speed === playbackSpeed }" :style="{color: customIconColor}">{{ speed }}x
                    </button>
                   </div>
                </div>
                <!-- Video Quality Button -->
                <div class="video-quality" v-if="enableVideoQualityButton && availableQualities.length > 0" v-show="!isMobile">
                     <button @click="toggleQualityDropdown">
                     <i class="icon-cog" :style="{ color: customIconColor }"></i>
                     </button>
                  <div class="dropdown-menu" :class="{ 'active': showQualityDropdown }" :style="{background: customBackgroundColor}">
                     <button v-for="quality in availableQualities" 
                     :key="quality.label" 
                     @click="setVideoQuality(quality.label)"
                     :class="{ 'active-quality': currentQuality === quality.label }" :style="{color: customIconColor}">
                     {{ quality.label }}
                     </button>
                  </div>
                </div>
                <div class="share-options" v-show="!isMobile">
                     <button class="share-button" @click="toggleShareOptions">
                     <i class="icon-share2" :style="{ color: customIconColor }"></i>
                    </button>
                  <div class="share-dropdown" :class="{ 'active': showShareOptions }" :style="{ background: customBackgroundColor }">
                    <button v-for="platform in socialPlatforms" :key="platform.name" @click="shareVideo(platform.name)" :style="{ color: customIconColor }">
                    <i :class="platform.icon"></i> 
                    </button>
                    <button @click="shareVideo('CopyLink')" :style="{   color: customIconColor}">
                    <i class="icon-link"></i> 
                    </button>
                  </div>
                </div>
            <button class="cc-button" @click="toggleCC" v-if="enableCaptionButton">
                <i :class=" captionIcon" aria-hidden="true" :style="{ color: customIconColor }"></i>
            </button>
            <button class="full-screen" @click="toggleFullScreen" v-if="enableFullscreenButton">
                <i :class="fullscreenIcon" :style="{ color: customIconColor }"></i>
            </button>
        </div>
    </div>
            
    `});window.VideoPlayers={instances:{},videoDataMap:{},async init(n=null){this.selectors=n;console.log("Instances before initialization:",VideoPlayers.instances);let t;if(n===null)t=document.querySelectorAll(".playerapp");else if(Array.isArray(n))t=n.reduce((n,t)=>n.concat(Array.from(document.querySelectorAll(t))),[]);else if(typeof n=="string")t=document.querySelectorAll(n);else{console.error("Invalid input for VideoPlayers.init(). Expected null, string, or array of strings.");return}const i=Array.from(t).map((n,t)=>{const i=n.id||`inv-player-${t}`;return n.id=i,n.querySelector("video-player").getAttribute("reference-id")});try{const n=await axios.get(`https://britecove-api.connectid.cloud/videos`,{params:{referenceids:i.join(",")}});this.videoDataMap=n.data.videos.reduce((n,t)=>(n[t.reference_id]=t,n),{});t.forEach(n=>{const t=n.id,i=n.querySelector("video-player").getAttribute("reference-id"),r=this.videoDataMap[i];if(!this.instances[t]){const u=new Vue({el:n.querySelector("video-player"),propsData:{referenceId:i},props:{referenceId:{type:String,required:!0}},data(){return{videoData:r||{}}}});this.instances[t]=u}})}catch(r){console.error("Error fetching video data:",r)}this.applyVideoFunctions();console.log("Instances after initialization:",VideoPlayers.instances)},applyVideoFunctions:function(){document.querySelectorAll("[data-action]").forEach(n=>{n.addEventListener("click",t=>{t.preventDefault();const e=n.getAttribute("data-action"),u=n.getAttribute("data-player");if(u){const f=document.querySelector(u);if(f){const i=this.getPlayer(f);if(i){const r=i.$refs.video;switch(e){case"play":(r.paused||r.ended)&&(r.play(),i.isPlaying=!0);break;case"pause":r.paused||(r.pause(),i.isPlaying=!1);break;case"stop":r.pause();r.currentTime=0;i.isPlaying=!1;i.seekValue=0;i.currentTime=0;i.updateSeekBar();break;case"fullscreen":i.toggleFullScreen()}}}}})})},getPlayer:function(n){const t=n.id;return this.instances[t]?.$children[0]}};HTMLElement.prototype.play=function(){const n=VideoPlayers.getPlayer(this);if(n){const t=n.$refs.video;(t.paused||t.ended)&&(t.play(),n.isPlaying=!0)}};HTMLElement.prototype.pause=function(){const n=VideoPlayers.getPlayer(this);if(n){const t=n.$refs.video;t.paused||(t.pause(),n.isPlaying=!1)}};HTMLElement.prototype.stop=function(){const n=VideoPlayers.getPlayer(this);if(n){const t=n.$refs.video;t.pause();t.currentTime=0;n.isPlaying=!1;n.seekValue=0;n.currentTime=0;n.updateSeekBar()}};HTMLElement.prototype.fullscreen=function(){const n=VideoPlayers.getPlayer(this);n&&n.toggleFullScreen()};document.addEventListener("DOMContentLoaded",()=>{VideoPlayers.init([".playerapp","#abcd"])})