<?php
// player.php - Dedicated page for displaying a custom-styled YouTube video player.

// NOTE: The following lines depend on an external environment (config.php, require_login)
// and are left as-is, assuming the user's environment handles authentication and database access.
require_once 'config.php';
require_login();

$studentId = $_SESSION['user_id'];
$selectedPackId = $_GET['pack_id'] ?? null;
$selectedLessonId = $_GET['lesson_id'] ?? null;

$currentLesson = null;
$videoId = '';
$error = '';

if (!$selectedPackId || !$selectedLessonId) {
    $error = "Pack ID and Lesson ID are required to play the video.";
} else {
    // 1. Check if student has access to the selected pack
    // Assumes $pdo is defined in config.php
    $stmt = $pdo->prepare("SELECT COUNT(id) FROM student_packs WHERE student_id = ? AND pack_id = ?");
    $stmt->execute([$studentId, $selectedPackId]);
    $hasAccess = $stmt->fetchColumn() > 0;

    if (!$hasAccess) {
        $error = "You are not authorized to view this lesson pack.";
    } else {
        // 2. Fetch lesson details
        $stmt = $pdo->prepare("SELECT title, youtube_link FROM lessons WHERE id = ? AND pack_id = ?");
        $stmt->execute([$selectedLessonId, $selectedPackId]);
        $currentLesson = $stmt->fetch();

        if (!$currentLesson) {
            $error = "Lesson not found.";
        } else {
            $youtubeUrl = $currentLesson['youtube_link'];

            // Robust Video ID extraction logic
            $patterns = [
                '/youtu\.be\/([a-zA-Z0-9_-]+)/',        // Short URL (youtu.be/ID)
                '/v=([a-zA-Z0-9_-]+)/',                // Standard URL (?v=ID)
                '/embed\/([a-zA-Z0-9_-]+)/',           // Already embed URL (embed/ID)
                '/(?:youtube\.com\/(?:[^\/]+\/.+\/|(?:v|e(?:mbed)?)\/|.*[?&]v=)|youtu\.be\/)([a-zA-Z0-9_-]{11})/' // Comprehensive regex
            ];

            foreach ($patterns as $pattern) {
                if (preg_match($pattern, $youtubeUrl, $matches)) {
                    $videoId = $matches[1];
                    break;
                }
            }

            if (!$videoId) {
                $error = "Invalid video link.";
            }
        }
    }
}

$pageTitle = $currentLesson ? htmlspecialchars($currentLesson['title']) . " - Player" : "Video Player";
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo $pageTitle; ?></title>
    <script src="https://cdn.tailwindcss.com"></script>
    <style>
        /* Base styles */
        html, body {
            margin: 0;
            padding: 0;
            height: 100%;
            overflow: auto; /* Allow scrolling if content expands */
            font-family: 'Inter', sans-serif;
            background-color: #f0f0f0; 
        }

        /* Video Wrapper & Player Aspect Ratio */
        .video-wrapper {
            position: relative;
            width: 90%; 
            max-width: 1200px;
            margin: 50px auto;
            aspect-ratio: 16 / 9;
            background-color: #333; 
            box-shadow: 0 10px 20px rgba(0,0,0,0.2), 0 5px 10px rgba(0,0,0,0.1);
            border-radius: 8px; 
            overflow: hidden; 
        }

        #player {
            width: 100%;
            height: 100%;
            position: absolute;
            top: 0;
            left: 0;
        }

        /* Progress Bar (NEW LOCATION: Full width, just above controls) */
        #progressBarContainer {
            position: absolute;
            bottom: 50px; /* Position right above the 50px high control bar */
            left: 0;
            right: 0;
            height: 5px;
            background-color: rgba(255,255,255,0.3);
            cursor: pointer; /* Now seekable */
            z-index: 7;
            transition: height 0.1s ease;
        }
        #progressBarContainer:hover {
            height: 8px; /* Thicker on hover for easier seeking */
        }
        .progress-bar-fill {
            height: 100%;
            width: 0%;
            background-color: #ff0000; /* YouTube red */
            border-radius: 2px;
            transition: none; /* Disable transition for quick seeking response */
            position: relative;
        }
        /* Scrubber handle */
        .progress-bar-fill::after {
            content: '';
            position: absolute;
            right: -6px;
            top: 50%;
            transform: translateY(-50%);
            width: 12px;
            height: 12px;
            border-radius: 50%;
            background-color: #ff0000;
            opacity: 0; /* Hidden by default */
            transition: opacity 0.1s;
        }
        #progressBarContainer:hover .progress-bar-fill::after {
             opacity: 1; /* Show scrubber on hover */
        }

        /* Custom Controls Bar */
        .custom-controls {
            position: absolute;
            bottom: 0;
            left: 0;
            right: 0;
            height: 50px;
            background-color: rgba(0,0,0,0.85); 
            display: flex;
            align-items: center;
            padding: 0 15px;
            color: #fff;
            font-size: 0.9rem;
            z-index: 8; /* Ensure controls are above everything */
        }
        
        .control-button {
            background: none;
            border: none;
            color: #fff;
            padding: 5px;
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
            transition: color 0.2s ease, transform 0.1s ease;
            outline: none;
        }
        .control-button:hover {
            color: #a0aec0;
            transform: scale(1.05);
        }
        .control-button svg {
            width: 24px;
            height: 24px;
        }
        .volume-control {
            margin-right: 15px;
        }
        .time-display {
            font-variant-numeric: tabular-nums;
            margin-left: 15px; /* Added margin for separation */
        }
        .right-controls {
            margin-left: auto; /* Push right controls to the end */
            display: flex;
            align-items: center;
            gap: 10px;
            position: relative; /* Context for settings menu */
        }

        /* Settings Menu Styles (NEW) */
        .settings-menu {
            position: absolute;
            bottom: 50px; /* Position above controls */
            right: 10px;
            background-color: rgba(30, 30, 30, 0.95);
            color: #fff;
            border-radius: 6px;
            padding: 10px;
            width: 200px;
            box-shadow: 0 4px 12px rgba(0,0,0,0.4);
            z-index: 10;
        }
        .menu-item-group {
            margin-bottom: 10px;
        }
        .menu-title {
            font-size: 0.8rem;
            text-transform: uppercase;
            color: #bbb;
            margin-bottom: 5px;
            padding: 3px 8px;
        }
        .settings-menu ul {
            list-style: none;
            padding: 0;
            margin: 0;
        }
        .settings-menu li {
            padding: 6px 8px;
            cursor: pointer;
            border-radius: 4px;
            font-size: 0.9rem;
            display: flex;
            justify-content: space-between;
            align-items: center;
            transition: background-color 0.15s;
        }
        .settings-menu li:hover {
            background-color: rgba(255, 255, 255, 0.1);
        }
        .settings-menu li.active {
            color: #ff0000;
            font-weight: bold;
        }
        .hidden { display: none !important; }

        /* Overlays and Click Guard */
        .click-guard-overlay, .main-play-overlay {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
        }
        .click-guard-overlay {
            background: transparent;
            z-index: 6;
            display: none;
        }
        .main-play-overlay {
            background-color: rgba(0,0,0,0.5); 
            display: flex;
            justify-content: center;
            align-items: center;
            cursor: pointer;
            z-index: 5;
            transition: background-color 0.3s;
        }
        .main-play-overlay:hover {
            background-color: rgba(0,0,0,0.6);
        }
        .main-play-icon {
            width: 80px;
            height: 80px;
            color: #fff;
            opacity: 0.9;
            transition: opacity 0.3s;
        }
    </style>
</head>
<body>

<?php if ($error): ?>
    <div class="h-screen flex items-center justify-center p-8 bg-gray-900">
        <div class="max-w-xl p-8 bg-white rounded-xl shadow-2xl text-center">
            <h1 class="text-3xl font-bold text-red-600 mb-4">Playback Error</h1>
            <p class="text-gray-700 mb-6"><?php echo $error; ?></p>
            <a href="myclass.php" class="inline-flex items-center px-4 py-2 border border-transparent text-sm font-medium rounded-md shadow-sm text-white bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500">
                <svg class="w-5 h-5 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M10 19l-7-7m0 0l7-7m-7 7h18"></path></svg>
                Go to My Classes
            </a>
        </div>
    </div>
<?php elseif ($videoId): ?>
    
    <div class="video-wrapper">
        <div id="mainPlayOverlay" class="main-play-overlay">
            <svg class="main-play-icon" fill="currentColor" viewBox="0 0 20 20" xmlns="http://www.w3.org/2000/svg"><path fill-rule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zM9.555 7.168A1 1 0 008 8v4a1 1 0 001.555.832l3-2a1 1 0 000-1.664l-3-2z" clip-rule="evenodd"></path></svg>
        </div>

        <div id="player"></div>

        <div id="clickGuardOverlay" class="click-guard-overlay"></div>

        <div id="progressBarContainer">
            <div id="progressBarFill" class="progress-bar-fill"></div>
        </div>

        <div id="settingsMenu" class="settings-menu hidden">
            <div class="menu-item-group">
                <div class="menu-title">Quality</div>
                <ul id="qualityList">
                    </ul>
            </div>
            <div class="menu-item-group">
                <div class="menu-title">Playback Speed</div>
                <ul id="speedList">
                    </ul>
            </div>
        </div>

        <div class="custom-controls">
            <button id="playPauseBtn" class="control-button">
                <svg id="playIcon" class="w-6 h-6" fill="currentColor" viewBox="0 0 20 20" xmlns="http://www.w3.org/2000/svg"><path fill-rule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zM9.555 7.168A1 1 0 008 8v4a1 1 0 001.555.832l3-2a1 1 0 000-1.664l-3-2z" clip-rule="evenodd"></path></svg>
                <svg id="pauseIcon" class="w-6 h-6 hidden" fill="currentColor" viewBox="0 0 20 20" xmlns="http://www.w3.org/2000/svg"><path fill-rule="evenodd" d="M18 10a8 8 0 11-16 0 8 8 0 0116 0zM8 7a1 1 0 011-1h2a1 1 0 110 2H9a1 1 0 01-1-1zm1 5a1 1 0 000 2h2a1 1 0 100-2H9z" clip-rule="evenodd"></path></svg>
            </button>

            <button id="muteUnmuteBtn" class="control-button volume-control">
                <svg id="volumeHighIcon" class="w-6 h-6" fill="currentColor" viewBox="0 0 20 20" xmlns="http://www.w3.org/2000/svg"><path fill-rule="evenodd" d="M9.383 3.017A1 1 0 0110 4v12a1 1 0 01-1.617.78L5 12H3a1 1 0 01-1-1V9a1 1 0 011-1h2l3.383-3.782zM15.536 8.464a1 1 0 010 3.072 2.992 2.992 0 000-3.072z" clip-rule="evenodd"></path></svg>
                <svg id="volumeMuteIcon" class="w-6 h-6 hidden" fill="currentColor" viewBox="0 0 20 20" xmlns="http://www.w3.org/2000/svg"><path fill-rule="evenodd" d="M9.383 3.017A1 1 0 0110 4v12a1 1 0 01-1.617.78L5 12H3a1 1 0 01-1-1V9a1 1 0 011-1h2l3.383-3.782zM11.536 8.464a.5.5 0 010 1.072l.536.536a.5.5 0 01.708-.708l-.536-.536a.5.5 0 01-.708 0z" clip-rule="evenodd"></path></svg>
            </button>
            
            <div class="time-display">
                <span id="currentTime">00:00</span> / <span id="duration">00:00</span>
            </div>

            <div class="right-controls">
                <button id="settingsBtn" class="control-button">
                    <svg class="w-6 h-6" fill="currentColor" viewBox="0 0 20 20" xmlns="http://www.w3.org/2000/svg"><path fill-rule="evenodd" d="M11.49 3.17c-.38-1.56-2.6-1.56-2.98 0a1.532 1.532 0 01-2.286.948c-1.3-.837-2.926.653-2.285 2.223.22.72.016 1.5-.536 2.053a1.532 1.532 0 01-0.948 2.286c-1.56.38-1.56 2.6 0 2.98a1.532 1.532 0 01.948 2.286c-.837 1.3.653 2.926 2.223 2.285.72-.22 1.5-.016 2.053.536a1.532 1.532 0 012.286.948c.38 1.56 2.6 1.56 2.98 0a1.532 1.532 0 012.286-.948c1.3.837 2.926-.653 2.223-2.285-.22-.72-.016-1.5.536-2.053a1.532 1.532 0 010.948-2.286c1.56-.38 1.56-2.6 0-2.98a1.532 1.532 0 01-.948-2.286c.837-1.3-.653-2.926-2.223-2.285-.72.22-1.5.016-2.053-.536zm-2.432 8.44a1 1 0 100-2 1 1 0 000 2z" clip-rule="evenodd"></path></svg>
                </button>
                <button id="fullscreenBtn" class="control-button">
                    <svg id="fullscreenEnterIcon" class="w-6 h-6" fill="currentColor" viewBox="0 0 20 20" xmlns="http://www.w3.org/2000/svg"><path fill-rule="evenodd" d="M3 5a1 1 0 011-1h3a1 1 0 110 2H5v2a1 1 0 11-2 0V5zm0 8a1 1 0 011-1h3a1 1 0 110 2H5v2a1 1 0 11-2 0v-3zm14-3a1 1 0 01-1 1h-3a1 1 0 110-2h2V6a1 1 0 112 0v3zm-1 4a1 1 0 011-1h-3a1 1 0 110 2h2v2a1 1 0 11-2 0v-3z" clip-rule="evenodd"></path></svg>
                    <svg id="fullscreenExitIcon" class="w-6 h-6 hidden" fill="currentColor" viewBox="0 0 20 20" xmlns="http://www.w3.org/2000/svg"><path fill-rule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zM5.293 6.707a1 1 0 011.414 0L10 10.586l3.293-3.293a1 1 0 111.414 1.414L11.414 12l3.293 3.293a1 1 0 01-1.414 1.414L10 13.414l-3.293 3.293a1 1 0 01-1.414-1.414L8.586 12 5.293 8.707a1 1 0 010-1.414z" clip-rule="evenodd"></path></svg>
                </button>
            </div>
        </div>
    </div>

    <script>
        // --- Utility Functions ---
        /**
         * Converts seconds into MM:SS format.
         * @param {number} seconds - The time in seconds.
         * @returns {string} The formatted time string.
         */
        function formatTime(seconds) {
            const minutes = Math.floor(seconds / 60);
            const remainingSeconds = Math.floor(seconds % 60);
            return `${minutes.toString().padStart(2, '0')}:${remainingSeconds.toString().padStart(2, '0')}`;
        }

        // --- YouTube IFrame API Setup ---
        var player;
        const videoId = "<?php echo $videoId; ?>";
        let duration = 0; 
        let updateInterval;

        // 1. Load the IFrame Player API code asynchronously.
        var tag = document.createElement('script');
        tag.src = "https://www.youtube.com/iframe_api";
        var firstScriptTag = document.getElementsByTagName('script')[0];
        firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

        // 2. The API will call this function when the player is ready.
        function onYouTubeIframeAPIReady() {
            player = new YT.Player('player', {
                height: '100%',
                width: '100%',
                videoId: videoId,
                playerVars: {
                    'controls': 0, // Disable native controls
                    'modestbranding': 1,
                    'rel': 0,
                    'showinfo': 0,
                    'fs': 1, 
                    'autoplay': 0
                },
                events: {
                    'onReady': onPlayerReady,
                    'onStateChange': onPlayerStateChange
                }
            });
        }

        // 3. Called when the video player is ready.
        function onPlayerReady(event) {
            duration = player.getDuration();
            document.getElementById('duration').textContent = formatTime(duration);

            // Start the progress update interval
            updateInterval = setInterval(updateProgressBar, 100); // Faster update for smoother progress bar

            // Populate the settings menu now that the player is ready
            populateSettingsMenu();
        }

        // 4. Called when the player's state changes.
        function onPlayerStateChange(event) {
            const mainPlayOverlay = document.getElementById('mainPlayOverlay');
            const clickGuardOverlay = document.getElementById('clickGuardOverlay');
            const playIcon = document.getElementById('playIcon');
            const pauseIcon = document.getElementById('pauseIcon');

            if (event.data === YT.PlayerState.PLAYING) {
                mainPlayOverlay.classList.add('hidden');
                clickGuardOverlay.style.display = 'block'; 
                playIcon.classList.add('hidden');
                pauseIcon.classList.remove('hidden');
            } else if (event.data === YT.PlayerState.PAUSED || event.data === YT.PlayerState.BUFFERING) {
                mainPlayOverlay.classList.remove('hidden');
                clickGuardOverlay.style.display = 'none'; 
                playIcon.classList.remove('hidden');
                pauseIcon.classList.add('hidden');
            } else if (event.data === YT.PlayerState.ENDED) {
                mainPlayOverlay.classList.remove('hidden');
                clickGuardOverlay.style.display = 'none'; 
                playIcon.classList.remove('hidden');
                pauseIcon.classList.add('hidden');
                document.getElementById('progressBarFill').style.width = '100%';
                document.getElementById('currentTime').textContent = formatTime(duration);
            }
        }

        // --- Settings Menu Logic (NEW) ---

        /**
         * Populates the Quality and Speed lists based on player API responses.
         */
        function populateSettingsMenu() {
            if (!player || !player.getAvailableQualityLevels) return;

            // 1. Quality Levels
            const qualityList = document.getElementById('qualityList');
            qualityList.innerHTML = '';
            const availableQualities = player.getAvailableQualityLevels();
            const currentQuality = player.getPlaybackQuality();

            // Default to 'auto' if player doesn't report current quality immediately
            const activeQuality = currentQuality && currentQuality !== 'unknown' ? currentQuality : 'auto'; 

            availableQualities.forEach(q => {
                const li = document.createElement('li');
                li.textContent = q === 'auto' ? 'Auto' : q.toUpperCase();
                li.setAttribute('data-quality', q);
                if (q === activeQuality) {
                    li.classList.add('active');
                }
                li.addEventListener('click', () => changeQuality(q));
                qualityList.appendChild(li);
            });

            // 2. Playback Rates
            const speedList = document.getElementById('speedList');
            speedList.innerHTML = '';
            const availableRates = player.getAvailablePlaybackRates().sort((a, b) => a - b);
            const currentRate = player.getPlaybackRate();

            availableRates.forEach(rate => {
                const li = document.createElement('li');
                // Format rate to show 'Normal' for 1 and include 'x' otherwise
                const rateText = rate === 1 ? 'Normal' : `${rate}x`; 
                li.innerHTML = `<span>${rateText}</span>`;
                li.setAttribute('data-rate', rate);
                if (rate === currentRate) {
                    li.classList.add('active');
                }
                li.addEventListener('click', () => changeSpeed(rate));
                speedList.appendChild(li);
            });
        }

        /**
         * Sets the new playback quality and updates the UI.
         * @param {string} quality - The quality level string (e.g., 'hd1080', 'auto').
         */
        function changeQuality(quality) {
            player.setPlaybackQuality(quality);
            // Update UI to reflect change
            document.querySelectorAll('#qualityList li').forEach(li => {
                li.classList.remove('active');
                if (li.getAttribute('data-quality') === quality) {
                    li.classList.add('active');
                }
            });
            document.getElementById('settingsMenu').classList.add('hidden');
        }

        /**
         * Sets the new playback speed and updates the UI.
         * @param {number} rate - The playback rate (e.g., 1.5, 0.25).
         */
        function changeSpeed(rate) {
            player.setPlaybackRate(rate);
            // Update UI to reflect change
            document.querySelectorAll('#speedList li').forEach(li => {
                li.classList.remove('active');
                // We use parseFloat to compare the rate number
                if (parseFloat(li.getAttribute('data-rate')) === rate) {
                    li.classList.add('active');
                }
            });
            document.getElementById('settingsMenu').classList.add('hidden');
        }

        // --- Custom Control Functions & Event Listeners ---

        // Play/Pause button
        document.getElementById('playPauseBtn').addEventListener('click', () => {
            if (!player) return;
            const state = player.getPlayerState();
            if (state === YT.PlayerState.PLAYING) {
                player.pauseVideo();
            } else if (state === YT.PlayerState.PAUSED || state === YT.PlayerState.ENDED) {
                player.playVideo();
            }
        });

        // Main Play Overlay click handler
        document.getElementById('mainPlayOverlay').addEventListener('click', () => {
            if (player) {
                player.playVideo();
            }
        });

        // Mute/Unmute button
        document.getElementById('muteUnmuteBtn').addEventListener('click', () => {
            if (!player) return;

            const volumeHighIcon = document.getElementById('volumeHighIcon');
            const volumeMuteIcon = document.getElementById('volumeMuteIcon');

            if (player.isMuted()) {
                player.unMute();
                volumeHighIcon.classList.remove('hidden');
                volumeMuteIcon.classList.add('hidden');
            } else {
                player.mute();
                volumeHighIcon.classList.add('hidden');
                volumeMuteIcon.classList.remove('hidden');
            }
        });

        // Fullscreen button
        document.getElementById('fullscreenBtn').addEventListener('click', () => {
            const videoWrapper = document.querySelector('.video-wrapper');
            if (document.fullscreenElement) { 
                document.exitFullscreen();
            } else {
                // Cross-browser request fullscreen
                if (videoWrapper.requestFullscreen) {
                    videoWrapper.requestFullscreen();
                } else if (videoWrapper.webkitRequestFullscreen) {
                    videoWrapper.webkitRequestFullscreen();
                } else if (videoWrapper.msRequestFullscreen) {
                    videoWrapper.msRequestFullscreen();
                }
            }
        });

        // Settings Button Toggle
        document.getElementById('settingsBtn').addEventListener('click', (event) => {
            event.stopPropagation(); // Prevent document click listener from firing immediately
            const settingsMenu = document.getElementById('settingsMenu');
            settingsMenu.classList.toggle('hidden');
        });

        // Close settings menu when clicking outside (on the document body)
        document.addEventListener('click', (event) => {
            const settingsMenu = document.getElementById('settingsMenu');
            const settingsBtn = document.getElementById('settingsBtn');

            // If the menu is visible AND the click target is NOT the menu or settings button
            if (!settingsMenu.classList.contains('hidden') && 
                !settingsMenu.contains(event.target) && 
                !settingsBtn.contains(event.target)) {
                settingsMenu.classList.add('hidden');
            }
        });


        // Progress Bar Seek Functionality (NEW)
        document.getElementById('progressBarContainer').addEventListener('click', (e) => {
            if (!player || duration === 0) return;

            const rect = e.currentTarget.getBoundingClientRect();
            const clickX = e.clientX - rect.left;
            const percentage = clickX / rect.width;
            const seekToTime = duration * percentage;

            player.seekTo(seekToTime, true); // Seek and buffer immediately
            
            // Hide the main play overlay if we seek, as we assume the user wants to play/continue
            document.getElementById('mainPlayOverlay').classList.add('hidden');
        });


        // Update Fullscreen button state on native fullscreen change 
        document.addEventListener('fullscreenchange', () => {
            const fullscreenEnterIcon = document.getElementById('fullscreenEnterIcon');
            const fullscreenExitIcon = document.getElementById('fullscreenExitIcon');
            
            if (document.fullscreenElement) {
                fullscreenEnterIcon.classList.add('hidden');
                fullscreenExitIcon.classList.remove('hidden');
                document.querySelector('.video-wrapper').style.margin = '0'; // Remove margin in fullscreen
                document.querySelector('.video-wrapper').style.width = '100vw'; // Full width in fullscreen
            } else {
                fullscreenEnterIcon.classList.remove('hidden');
                fullscreenExitIcon.classList.add('hidden');
                document.querySelector('.video-wrapper').style.margin = '50px auto'; // Restore margin
                document.querySelector('.video-wrapper').style.width = '90%'; // Restore width
            }
        });

        // **FIX**: Prevent the native YouTube context menu (Share button) from appearing on right-click.
        document.querySelector('.video-wrapper').addEventListener('contextmenu', (e) => {
            e.preventDefault();
        });


        /**
         * Updates the progress bar width and current time display.
         */
        function updateProgressBar() {
            if (player && typeof player.getCurrentTime === 'function' && duration > 0) {
                const currentTime = player.getCurrentTime();
                
                const progressPercent = (currentTime / duration) * 100;
                document.getElementById('progressBarFill').style.width = `${progressPercent}%`;
                document.getElementById('currentTime').textContent = formatTime(currentTime);

                // Check and update quality/speed in case YouTube changes them automatically (e.g., bandwidth change)
                const currentQuality = player.getPlaybackQuality();
                const currentRate = player.getPlaybackRate();
                
                // Re-highlight quality if it changes automatically
                document.querySelectorAll('#qualityList li').forEach(li => {
                    li.classList.remove('active');
                    if (li.getAttribute('data-quality') === currentQuality) {
                         li.classList.add('active');
                    }
                });
                
                // Re-highlight speed if it changes automatically
                 document.querySelectorAll('#speedList li').forEach(li => {
                    li.classList.remove('active');
                    if (parseFloat(li.getAttribute('data-rate')) === currentRate) {
                         li.classList.add('active');
                    }
                });
            }
        }
    </script>
<?php endif; ?>

</body>
</html>