(function () {
    let isSafari = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);

    let isAdPlaying = false; // Track if an ad is currently playing
    const AD_PROGRESS_COLOR = '#FFD700'; // Yellow for ads
    const VIDEO_PROGRESS_COLOR = '#FF0000'; // Red for main video
    let timeDisplay;

    const videoContainer = document.getElementById('video-container');

    // Create a play button overlay
    const playButton = document.createElement('div');
    playButton.innerHTML = '<i class="fas fa-play-circle fa-5x"></i>';
    playButton.className = 'play-button-overlay';
    videoContainer.appendChild(playButton);
  
    // Parse the playlist from data attribute
    const playlistData = videoContainer.getAttribute('data-playlist');
    const playlist = playlistData ? JSON.parse(playlistData) : [];
  
    if (playlist.length === 0) {
      console.error('No videos found in the playlist.');
      return;
    }
  
    let currentVideoIndex = 0;
    let adPlaying = false;
    let isAutoplayEnabled = false;
  
    // Initialize autoplay preference from localStorage
    const storedAutoplay = localStorage.getItem('videoAutoplay');
    if (storedAutoplay === 'true') {
      isAutoplayEnabled = true;
    }
  
    // Create main video element
    const video = document.createElement('video');
    video.id = 'mainVideo';
    video.style.width = '100%';
    video.style.height = '100%';
    video.style.objectFit = 'contain';
    videoContainer.appendChild(video);

    // Add dynamic styles for ad overlay
    const styleSheet = document.createElement('style');
    styleSheet.textContent = `
      .ad-overlay {
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: calc(100% - 70px); /* Leave space for controls and skip button */
        z-index: 1001;
      }
    
      .skip-button {
        position: absolute;
        bottom: 60px;
        right: 10px;
        padding: 8px 16px;
        background: rgba(0, 0, 0, 0.7);
        color: #fff;
        border: none;
        border-radius: 4px;
        cursor: pointer;
        z-index: 1002; /* Ensure it's above the overlay */
        font-size: 14px;
        display: flex;
        align-items: center;
        gap: 8px;
      }
    
      .skip-button:hover {
        background: rgba(0, 0, 0, 0.9);
      }
    `;
    document.head.appendChild(styleSheet);   
    
    // Function to load a video from the playlist
    function loadVideo(index) {
        if (index >= playlist.length) {
          console.log('Playlist ended.');
          return;
        }
      
        const videoData = playlist[index];
        video.innerHTML = '';
      
        const source = document.createElement('source');
        source.src = videoData.media_url;
        source.type = 'video/mp4';
        video.appendChild(source);
      
        if (videoData.subtitles_src) {
          const track = document.createElement('track');
          track.kind = 'subtitles';
          track.label = 'Subtitles';
          track.srclang = 'en';
          track.src = videoData.subtitles_src;
          track.default = true;
          video.appendChild(track);
        }
      
        // Show play button overlay when loading new video
        playButton.style.display = 'block';
        video.load();
    }
  
    // Initially load the first video
    loadVideo(currentVideoIndex);
  
    
    // Make play button accessible
    playButton.setAttribute('role', 'button');
    playButton.setAttribute('aria-label', 'Play Video');
    playButton.tabIndex = 0;
    
    // Play Button click handler
    playButton.addEventListener('click', () => {
        playButton.style.display = 'none';
        startPlayback();
    });
    
    // Allow play button activation via keyboard
    playButton.addEventListener('keydown', (event) => {
      if (event.key === 'Enter' || event.key === ' ') {
        event.preventDefault();
        playButton.click();
      }
    });

    // Start playback, handling pre-roll ads
    function startPlayback(forceMainVideo = false) {
        const currentVideoData = playlist[currentVideoIndex];
        
        // Handle Safari's autoplay restriction
        if (isSafari) {
          video.setAttribute('playsinline', '');
          video.setAttribute('webkit-playsinline', '');
        }
      
        // Check for pre-roll ad
        const preRollAd = !forceMainVideo && currentVideoData.ads.find(
          (ad) => ad.type === 'preroll' && !ad.played
        );
        
        if (preRollAd) {
          playAd(preRollAd, () => {
            preRollAd.played = true;
            // For Safari, we need to ensure user interaction
            if (isSafari) {
              video.muted = true;
            }
            video.play().then(() => {
              if (isSafari) {
                video.muted = false;
              }
            }).catch((error) => {
              console.error('Error playing main video:', error);
            });
          });
        } else {
          if (isSafari) {
            video.muted = true;
          }
          video.play().then(() => {
            if (isSafari) {
              video.muted = false;
            }
          }).catch((error) => {
            console.error('Error playing video:', error);
          });
        }
    }

  
    // Function to play an ad
    function playAd(ad, callback) {
        isAdPlaying = true;
        const adVideo = document.createElement('video');
        adVideo.id = 'adVideo';
        adVideo.style.width = '100%';
        adVideo.style.height = '100%';
        adVideo.style.objectFit = 'contain';
        adVideo.setAttribute('playsinline', '');
        adVideo.setAttribute('webkit-playsinline', '');
        adVideo.muted = true; // Start muted to help with autoplay
        adVideo.playbackRate = 1.0; // Force 1x speed for ads
      
        const adSource = document.createElement('source');
        adSource.src = ad.src;
        adSource.type = 'video/mp4';
        adVideo.appendChild(adSource);
      
        // Replace main video with ad video
        videoContainer.replaceChild(adVideo, video);
        updateCurrentVideo(adVideo);
      
        // Add timeupdate listener specifically for ad video
        adVideo.addEventListener('timeupdate', onTimeUpdate);
      
        // Disable progress bar seeking during ad
        progressBarContainer.style.pointerEvents = 'none';
      
        // Create skip button (before overlay)
        const skipButton = document.createElement('button');
        skipButton.innerHTML = '<i class="fas fa-skip-forward"></i> Skip Ad';
        skipButton.className = 'skip-button';
        skipButton.style.display = 'none';
        videoContainer.appendChild(skipButton);
      
        // Create overlay to prevent accidental ad clicks
        const adOverlay = document.createElement('div');
        adOverlay.className = 'ad-overlay';
        videoContainer.appendChild(adOverlay);
      
        // Handle ad click properly
        if (ad.link) {
          adOverlay.style.cursor = 'pointer';
          adOverlay.addEventListener('click', (event) => {
            event.preventDefault();
            event.stopPropagation();
            window.open(ad.link, '_blank', 'noopener,noreferrer');
          });
        }
      
        // Special handling for Safari autoplay
        const startAdPlayback = () => {
          adVideo.muted = true; // Ensure muted for autoplay
          adVideo.play().then(() => {
            // Once playing, unmute if not Safari
            if (!isSafari) {
              adVideo.muted = false;
            }
          }).catch((error) => {
            console.error('Error playing ad video:', error);
            skipAd();
          });
        };
      
        // Show skip button after 10 seconds
        adVideo.addEventListener('loadedmetadata', () => {
          if (adVideo.duration >= 10) {
            setTimeout(() => {
              skipButton.style.display = 'block';
            }, 10000);
          }
          startAdPlayback();
        });
      
        function skipAd() {
          // First pause and cleanup the ad video
          adVideo.pause();
          adVideo.removeEventListener('timeupdate', onTimeUpdate);
          adVideo.removeAttribute('src'); // Remove source
          adVideo.load(); // Reset the video element
          
          // Remove skip button and overlay
          if (skipButton && skipButton.parentNode) {
            videoContainer.removeChild(skipButton);
          }
          if (adOverlay && adOverlay.parentNode) {
            videoContainer.removeChild(adOverlay);
          }
      
          isAdPlaying = false;
          progressBarContainer.style.pointerEvents = 'auto';
      
          // Replace ad video with main video
          videoContainer.replaceChild(video, adVideo);
          updateCurrentVideo(video);
      
          // Re-enable speed changes
          if (document.getElementById('playback-speed')) {
            document.getElementById('playback-speed').disabled = false;
          }
      
          // Cleanup all event listeners
          adVideo.removeEventListener('ended', skipAd);
          adVideo.removeEventListener('error', onAdError);
          adVideo.removeEventListener('loadedmetadata', onAdLoadedMetadata);
      
          // Ensure the ad video is fully stopped and cleaned up
          setTimeout(() => {
            adVideo.src = '';
            adVideo.load();
          }, 0);
      
          if (typeof callback === 'function') {
            callback();
          }
        }
      
        // Store event listener functions for proper cleanup
        const onAdError = () => {
          console.error('Error loading ad video.');
          skipAd();
        };
      
        const onAdLoadedMetadata = () => {
          if (adVideo.duration >= 10) {
            setTimeout(() => {
              skipButton.style.display = 'block';
            }, 10000);
          }
          startAdPlayback();
        };
      
        skipButton.addEventListener('click', skipAd);
      
        // Ad ended handler
        adVideo.addEventListener('ended', skipAd);
      
        // Ad error handler
        adVideo.addEventListener('error', onAdError);
      
        // Loadedmetadata handler
        adVideo.addEventListener('loadedmetadata', onAdLoadedMetadata);
      
        // Ensure timeDisplay is still in the DOM after video replacement
        const timeDisplay = document.querySelector('.time-display');
        if (!timeDisplay) {
          // Recreate time display if it was lost
          const newTimeDisplay = document.createElement('div');
          newTimeDisplay.className = 'time-display';
          controlsContainer.appendChild(newTimeDisplay);
        }
      
        // Disable speed changes during ad
        if (document.getElementById('playback-speed')) {
          document.getElementById('playback-speed').disabled = true;
        }
      
        // Start playing the ad
        startAdPlayback();
    }
    
  
    // Function to load the next video in the playlist
    function loadNextVideo() {
      currentVideoIndex += 1;
      if (currentVideoIndex >= playlist.length) {
        console.log('End of playlist.');
        return;
      }
      loadVideo(currentVideoIndex);
      playButton.style.display = 'block';
    }
  
    // Function to update currentVideo and manage event listeners
    function updateCurrentVideo(newVideo) {
        // Remove event listeners from previous video
        if (currentVideo) {
          currentVideo.removeEventListener('play', onPlay);
          currentVideo.removeEventListener('pause', onPause);
          currentVideo.removeEventListener('ended', onEnded);
          currentVideo.removeEventListener('timeupdate', onTimeUpdate);
          currentVideo.removeEventListener('volumechange', onVolumeChange);
        }
      
        currentVideo = newVideo;
      
        // Add event listeners to new video
        currentVideo.addEventListener('play', onPlay);
        currentVideo.addEventListener('pause', onPause);
        currentVideo.addEventListener('ended', onEnded);
        currentVideo.addEventListener('timeupdate', onTimeUpdate);
        currentVideo.addEventListener('volumechange', onVolumeChange);
    }
  
    // Event Handlers
    function onPlay() {
      playPauseButton.innerHTML = '<i class="fas fa-pause"></i>';
    }
  
    function onPause() {
      playPauseButton.innerHTML = '<i class="fas fa-play"></i>';
    }
  
    function onEnded() {
      playPauseButton.innerHTML = '<i class="fas fa-play"></i>';
      if (!adPlaying && isAutoplayEnabled) {
        loadNextVideo();
      }
    }

    function onTimeUpdate() {
        if (!currentVideo || isNaN(currentVideo.duration)) return;
      
        const current = formatTime(currentVideo.currentTime);
        const total = formatTime(currentVideo.duration);
        
        // Find timeDisplay in the DOM
        const timeDisplay = document.querySelector('.time-display');
        if (timeDisplay) {
          timeDisplay.textContent = `${current} / ${total}`;
        }
      
        // Update progress bar
        const percentage = (currentVideo.currentTime / currentVideo.duration) * 100;
        progressBar.style.width = `${percentage}%`;
        progressBar.style.backgroundColor = isAdPlaying ? '#FFD700' : '#FF0000';
    }

    function formatTime(timeInSeconds) {
        if (isNaN(timeInSeconds)) return "0:00";
        
        const hours = Math.floor(timeInSeconds / 3600);
        const minutes = Math.floor((timeInSeconds % 3600) / 60);
        const seconds = Math.floor(timeInSeconds % 60);
      
        if (hours > 0) {
          return `${hours}:${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
        }
        return `${minutes}:${seconds.toString().padStart(2, '0')}`;
    }
  
    function onVolumeChange() {
      volumeButton.innerHTML = currentVideo.muted
        ? '<i class="fas fa-volume-mute"></i>'
        : '<i class="fas fa-volume-up"></i>';
    }
  
    // Create custom controls container
    const controlsContainer = document.createElement('div');
    controlsContainer.className = 'video-controls';
    videoContainer.appendChild(controlsContainer);
  
    // Left Controls
    const leftControls = document.createElement('div');
    leftControls.className = 'left-controls';
    controlsContainer.appendChild(leftControls);
  
    // Play/Pause button
    const playPauseButton = document.createElement('button');
    playPauseButton.innerHTML = '<i class="fas fa-play"></i>';
    playPauseButton.className = 'control-button';
    playPauseButton.title = 'Play/Pause';
    leftControls.appendChild(playPauseButton);
  
    // Volume button
    const volumeButton = document.createElement('button');
    volumeButton.innerHTML = '<i class="fas fa-volume-up"></i>';
    volumeButton.className = 'control-button';
    volumeButton.title = 'Mute/Unmute';
    leftControls.appendChild(volumeButton);
  
    // Progress bar container
    const progressBarContainer = document.createElement('div');
    progressBarContainer.className = 'progress-bar-container';
    controlsContainer.appendChild(progressBarContainer);
  
    // Progress bar fill
    const progressBar = document.createElement('div');
    progressBar.className = 'progress-bar';
    progressBarContainer.appendChild(progressBar);
  
    // Right Controls
    const rightControls = document.createElement('div');
    rightControls.className = 'right-controls';
    controlsContainer.appendChild(rightControls);
  
    // Autoplay Switch
    const autoplaySwitch = document.createElement('button');
    autoplaySwitch.innerHTML = '<i class="fas fa-sync-alt"></i>';
    autoplaySwitch.className = 'control-button';
    autoplaySwitch.title = 'Autoplay';
    rightControls.appendChild(autoplaySwitch);
  
    // Closed Captions Toggle
    const ccToggle = document.createElement('button');
    ccToggle.innerHTML = '<i class="fas fa-closed-captioning"></i>';
    ccToggle.className = 'control-button';
    ccToggle.title = 'Toggle Subtitles';
    rightControls.appendChild(ccToggle);
  
    // Mini Player Button
    const miniPlayerButton = document.createElement('button');
    miniPlayerButton.innerHTML = '<i class="fas fa-window-restore"></i>';
    miniPlayerButton.className = 'control-button';
    miniPlayerButton.title = 'Mini Player';
    rightControls.appendChild(miniPlayerButton);
  
    // Theatre Mode Button
    const theatreModeButton = document.createElement('button');
    theatreModeButton.innerHTML = '<i class="fas fa-expand"></i>';
    theatreModeButton.className = 'control-button';
    theatreModeButton.title = 'Theatre Mode';
    rightControls.appendChild(theatreModeButton);
  
    // Fullscreen Button
    const fullscreenButton = document.createElement('button');
    fullscreenButton.innerHTML = '<i class="fas fa-expand-arrows-alt"></i>';
    fullscreenButton.className = 'control-button';
    fullscreenButton.title = 'Fullscreen';
    rightControls.appendChild(fullscreenButton);
  
    // Settings Button
    const settingsButton = document.createElement('button');
    settingsButton.innerHTML = '<i class="fas fa-cog"></i>';
    settingsButton.className = 'control-button';
    settingsButton.title = 'Settings';
    rightControls.appendChild(settingsButton);
  
    // Control Event Listeners
    playPauseButton.addEventListener('click', () => {
        if (currentVideo === video) { // Only for main video
          if (video.paused) {
            // If video hasn't started yet, start with ad
            if (video.currentTime === 0) {
              startPlayback();
            } else {
              // Resume from current position
              video.play().catch((error) => {
                console.error('Error playing video:', error);
              });
            }
          } else {
            video.pause();
          }
        } else {
          // For ad video, just toggle play/pause
          if (currentVideo.paused) {
            currentVideo.play().catch((error) => {
              console.error('Error playing video:', error);
            });
          } else {
            currentVideo.pause();
          }
        }
    });

    video.addEventListener('click', (event) => {
        // Only handle click for main video
        if (currentVideo === video) {
          event.preventDefault();
          if (video.paused) {
            if (video.currentTime === 0) {
              startPlayback();
            } else {
              video.play().catch((error) => {
                console.error('Error playing video:', error);
              });
            }
          } else {
            video.pause();
          }
        }
    });
  
    volumeButton.addEventListener('click', () => {
      currentVideo.muted = !currentVideo.muted;
    });
  
    progressBarContainer.addEventListener('click', (e) => {
      const rect = progressBarContainer.getBoundingClientRect();
      const pos = (e.clientX - rect.left) / rect.width;
      currentVideo.currentTime = pos * currentVideo.duration;
    });
  
    autoplaySwitch.addEventListener('click', () => {
      isAutoplayEnabled = !isAutoplayEnabled;
      autoplaySwitch.style.color = isAutoplayEnabled ? 'red' : '#fff';
      localStorage.setItem('videoAutoplay', isAutoplayEnabled);
    });
  
    if (isAutoplayEnabled) {
      autoplaySwitch.style.color = 'red';
    }
  
    ccToggle.addEventListener('click', () => {
      const tracks = video.textTracks;
      if (tracks.length > 0) {
        for (let i = 0; i < tracks.length; i++) {
          tracks[i].mode = tracks[i].mode === 'showing' ? 'hidden' : 'showing';
        }
      }
    });
  
    // Mini Player functionality
    miniPlayerButton.addEventListener('click', () => {
      toggleMiniPlayer();
    });
  
    function toggleMiniPlayer() {
      const miniPlayer = document.getElementById('mini-player');
      if (miniPlayer) {
        miniPlayer.remove();
        document.body.style.marginBottom = '0';
        currentVideo.play().catch((error) => {
          console.error('Error resuming main video:', error);
        });
        updateCurrentVideo(video);
      } else {
        const miniPlayerDiv = document.createElement('div');
        miniPlayerDiv.id = 'mini-player';
        miniPlayerDiv.style.position = 'fixed';
        miniPlayerDiv.style.bottom = '10px';
        miniPlayerDiv.style.right = '10px';
        miniPlayerDiv.style.width = '300px';
        miniPlayerDiv.style.height = '169px';
        miniPlayerDiv.style.zIndex = '10000';
        miniPlayerDiv.style.backgroundColor = '#000';
        miniPlayerDiv.style.boxShadow = '0 0 10px rgba(0, 0, 0, 0.5)';
        miniPlayerDiv.style.borderRadius = '4px';
        miniPlayerDiv.style.overflow = 'hidden';
  
        const miniVideo = video.cloneNode(true);
        miniVideo.style.width = '100%';
        miniVideo.style.height = '100%';
        miniVideo.style.objectFit = 'cover';
        miniVideo.id = 'miniVideo';
  
        miniPlayerDiv.appendChild(miniVideo);
        document.body.appendChild(miniPlayerDiv);
  
        miniVideo.currentTime = currentVideo.currentTime;
        if (!currentVideo.paused) {
          miniVideo.play().catch((error) => {
            console.error('Error playing mini video:', error);
          });
        }
  
        currentVideo.pause();
  
        miniVideo.addEventListener('play', () => {
          video.pause();
        });
  
        miniVideo.addEventListener('pause', () => {
          video.pause();
        });
  
        const restoreButton = document.createElement('button');
        restoreButton.innerHTML = '<i class="fas fa-window-restore"></i>';
        restoreButton.className = 'restore-button';
        miniPlayerDiv.appendChild(restoreButton);

        restoreButton.addEventListener('click', () => {
          miniVideo.pause();
          miniPlayerDiv.remove();
          document.body.style.marginBottom = '0';
          currentVideo.currentTime = miniVideo.currentTime;
          currentVideo.play().catch((error) => {
            console.error('Error resuming main video:', error);
          });
          updateCurrentVideo(video);
        });
  
        updateCurrentVideo(miniVideo);
        document.body.style.marginBottom = '200px';
      }
    }
  
    // Theatre Mode functionality
    theatreModeButton.addEventListener('click', () => {
      toggleTheatreMode();
    });
  
    function toggleTheatreMode() {
      if (videoContainer.classList.contains('theatre-mode')) {
        videoContainer.classList.remove('theatre-mode');
        theatreModeButton.innerHTML = '<i class="fas fa-expand"></i>';
      } else {
        videoContainer.classList.add('theatre-mode');
        theatreModeButton.innerHTML = '<i class="fas fa-compress"></i>';
      }
    }
  
    // Fullscreen functionality
    fullscreenButton.addEventListener('click', () => {
      if (!document.fullscreenElement) {
        videoContainer.requestFullscreen().catch((err) => {
          console.error(
            `Error attempting to enable full-screen mode: ${err.message} (${err.name})`
          );
        });
      } else {
        document.exitFullscreen();
      }
    });
  
    // Settings functionality
    settingsButton.addEventListener('click', () => {
      openSettingsModal();
    });
  
    function openSettingsModal() {
      let modal = document.getElementById('settings-modal');
      if (!modal) {
        modal = document.createElement('div');
        modal.id = 'settings-modal';
        modal.style.position = 'fixed';
        modal.style.top = '0';
        modal.style.left = '0';
        modal.style.width = '100%';
        modal.style.height = '100%';
        modal.style.backgroundColor = 'rgba(0, 0, 0, 0.8)';
        modal.style.display = 'flex';
        modal.style.alignItems = 'center';
        modal.style.justifyContent = 'center';
        modal.style.zIndex = '10001';
  
        const modalContent = document.createElement('div');
        modalContent.style.backgroundColor = '#000';
        modalContent.style.padding = '20px';
        modalContent.style.borderRadius = '8px';
        modalContent.style.color = '#fff';
        modalContent.style.width = '300px';
        modalContent.style.textAlign = 'center';
  
        const title = document.createElement('h2');
        title.innerText = 'Settings';
        modalContent.appendChild(title);
  
        const speedLabel = document.createElement('label');
        speedLabel.innerText = 'Playback Speed:';
        speedLabel.style.display = 'block';
        speedLabel.style.marginBottom = '10px';
        modalContent.appendChild(speedLabel);
  
        const speedSelect = document.createElement('select');
        speedSelect.id = 'playback-speed';
        const speeds = [0.5, 0.75, 1, 1.25, 1.5, 2];
        speeds.forEach((speed) => {
          const option = document.createElement('option');
          option.value = speed;
          option.innerText = `${speed}x`;
          if (speed === 1) option.selected = true;
          speedSelect.appendChild(option);
        });
        modalContent.appendChild(speedSelect);
  
        const closeButton = document.createElement('button');
        closeButton.innerHTML = '<i class="fas fa-times"></i>';
        closeButton.className = 'close-settings-button';
        modalContent.appendChild(closeButton);
  
        closeButton.addEventListener('click', () => {
          modal.style.display = 'none';
        });
  
        speedSelect.addEventListener('change', () => {
            const selectedSpeed = parseFloat(speedSelect.value);
            if (!isAdPlaying) { // Only allow speed changes for main video
              video.playbackRate = selectedSpeed;
              if (currentVideo !== video) {
                currentVideo.playbackRate = selectedSpeed;
              }
            } else {
              // Reset speed select to 1x if trying to change during ad
              speedSelect.value = "1";
            }
        });

        modal.appendChild(modalContent);
        document.body.appendChild(modal);
      } else {
        modal.style.display = 'flex';
      }
    }
  
    // Remember current time if video is interrupted
    function rememberCurrentTime() {
      const videoKey = `videoCurrentTime_${playlist[currentVideoIndex].media_url}`;
      localStorage.setItem(videoKey, currentVideo.currentTime);
    }
  
    window.addEventListener('beforeunload', rememberCurrentTime);
  
    // Load saved time
    function loadSavedTime() {
      const videoKey = `videoCurrentTime_${playlist[currentVideoIndex].media_url}`;
      let savedTime = localStorage.getItem(videoKey);
      const urlParams = new URLSearchParams(window.location.search);
      const startTime = urlParams.get('t');
  
      if (startTime) {
        currentVideo.currentTime = parseFloat(startTime);
      } else if (savedTime) {
        currentVideo.currentTime = parseFloat(savedTime);
      }
    }
  
    video.addEventListener('loadedmetadata', loadSavedTime);
  
    // Initialize currentVideo with the main video
    let currentVideo = video;
  
})();