<?php
// This file contains the video player UI and logic.
// It is designed to be included within a main page layout (like myclass.php).
// NOTE: Assumes $currentLesson, $videoId, and $selectedPackId are defined in the parent scope.

// --- Prerequisites Check ---
if (!isset($currentLesson) || !$currentLesson) {
    $error = "Lesson data is unavailable or access denied.";
    echo '<div class="bg-red-100 border-l-4 border-red-500 text-red-700 p-4 rounded-lg" role="alert">' . htmlspecialchars($error) . '</div>';
    echo '<a href="myclass.php" class="text-indigo-600 hover:text-indigo-800 font-medium mt-4 block">← Back to All Classes</a>';
    return;
}

// Ensure videoId is available (assuming it was extracted correctly earlier)
$videoId = isset($videoId) ? $videoId : '';
if (empty($videoId)) {
    $error = "Video ID is missing for this lesson.";
    echo '<div class="bg-red-100 border-l-4 border-red-500 text-red-700 p-4 rounded-lg" role="alert">' . htmlspecialchars($error) . '</div>';
    return;
}
?>

<style>
    /* Custom CSS for Fullscreen Behavior and Aesthetics */
    /* 1. Base style for the video container (target of fullscreen) */
    #videoContainer {
        transition: all 0.3s ease;
        position: relative; /* Ensure children are positioned correctly */
    }

    /* 2. Fullscreen styling: Fills the entire screen */
    #videoContainer.is-fullscreen {
        position: fixed;
        top: 0;
        left: 0;
        width: 100vw;
        height: 100vh;
        z-index: 1000;
        padding-top: 0 !important; 
        border-radius: 0;
        background-color: #000; /* Black background in fullscreen */
    }

    /* Adjust the YouTube player within the fullscreen container */
    #videoContainer.is-fullscreen #player {
        height: 100%;
    }

    /* 3. Controls positioning for fullscreen mode */
    #customControls.fixed-controls {
        position: fixed !important;
        bottom: 0 !important;
        left: 0 !important;
        width: 100%;
        z-index: 1001;
        background-color: rgba(255, 255, 255, 0.95);
        border-radius: 0;
        border: none;
        padding: 0.75rem 1rem; /* Adjust padding for mobile/fullscreen */
        box-shadow: 0 -4px 15px rgba(0,0,0,0.2); 
    }

    /* 4. Progress bar styling (Mobile-Friendly H-2) */
    #progressBar {
        cursor: pointer;
        height: 8px; /* Slightly thicker for better touch target */
        background-color: #d1d5db; /* gray-300 */
        border-radius: 9999px;
        transition: height 0.1s ease;
    }
    #progressBar:hover {
        height: 10px; /* Thicker on hover for desktop */
    }
    #progressBarFill {
        height: 100%;
        background-color: #4f46e5; /* indigo-600 */
        border-radius: 9999px;
        transition: width 0.1s linear;
    }
    
    /* 5. Style for active items in settings menu */
    #qualityList li.active, #speedList li.active {
        background-color: #eef2ff; /* indigo-50 */
        color: #4338ca; /* indigo-700 */
        font-weight: 600;
    }

    /* 6. Volume Slider Custom Styling for Webkit/Firefox */
    #volumeSlider {
        -webkit-appearance: none;
        appearance: none;
        background: transparent;
        cursor: pointer;
    }

    #volumeSlider::-webkit-slider-runnable-track {
        background: #9ca3af; /* gray-400 */
        border-radius: 9999px;
        height: 4px;
    }

    #volumeSlider::-webkit-slider-thumb {
        -webkit-appearance: none;
        appearance: none;
        margin-top: -6px; /* Center the thumb vertically */
        background-color: #4f46e5; /* indigo-600 */
        height: 16px;
        width: 16px;
        border-radius: 50%;
        border: none;
    }
    
    #volumeSlider:focus::-webkit-slider-thumb {
        box-shadow: 0 0 0 4px rgba(79, 70, 229, 0.3); /* indigo-600 ring */
    }

    #volumeSlider::-moz-range-track {
        background: #9ca3af; /* gray-400 */
        border-radius: 9999px;
        height: 4px;
    }

    #volumeSlider::-moz-range-thumb {
        background-color: #4f46e5; /* indigo-600 */
        height: 16px;
        width: 16px;
        border-radius: 50%;
        border: none;
    }
</style>

<div class="bg-white p-6 md:p-8 rounded-2xl shadow-2xl space-y-6 max-w-4xl mx-auto">
    <!-- Lesson Title and Back Button -->
    <div class="flex flex-col sm:flex-row items-start sm:items-center justify-between border-b pb-4 mb-4">
        <h1 class="text-2xl md:text-3xl font-extrabold text-indigo-700 mb-2 sm:mb-0">
            <?php echo htmlspecialchars($currentLesson['title']); ?>
        </h1>
        <a href="myclass.php?pack_id=<?php echo htmlspecialchars($selectedPackId ?? ''); ?>" 
            class="text-sm font-medium text-gray-600 hover:text-indigo-800 flex items-center p-2 rounded-lg transition-colors bg-gray-50 hover:bg-indigo-50">
            <svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4 mr-1" viewBox="0 0 20 20" fill="currentColor">
                <path fill-rule="evenodd" d="M9.707 16.707a1 1 0 01-1.414 0l-6-6a1 1 0 010-1.414l6-6a1 1 0 011.414 1.414L5.414 9H17a1 1 0 110 2H5.414l4.293 4.293a1 1 0 010 1.414z" clip-rule="evenodd" />
            </svg>
            Back to Lesson List 
        </a>
    </div>

    <!-- YouTube Player Container (Target for Fullscreen) -->
    <div id="videoContainer" class="w-full overflow-hidden rounded-xl bg-black" style="padding-top: 56.25%;">
        <div id="player" class="absolute top-0 left-0 w-full h-full"></div>
        <!-- Click Intercept Overlay: Blocks accidental clicks on the hidden YouTube controls -->
        <div id="playerOverlay" 
             class="absolute top-0 left-0 w-full h-full cursor-default" 
             style="z-index: 100; background: transparent;">
        </div>
    </div>

    <!-- Custom Controls (MOBILE FRIENDLY - Two Rows) -->
    <div id="customControls" class="flex flex-col space-y-3 bg-gray-50 p-3 rounded-lg border justify-between transition-all duration-300">
        
        <!-- ROW 1: Progress Bar & Time Display (Always full width) -->
        <div class="flex items-center space-x-3 w-full">
            <span id="currentTime" class="text-xs font-bold text-gray-800 sm:text-base">0:00</span>
            
            <!-- Progress Bar (The target for seeking) -->
            <div id="progressBar" class="flex-grow relative" title="Seek to position">
                <div id="progressBarFill" class="h-full absolute top-0 left-0" style="width: 0%"></div>
            </div>
            
            <span id="durationTime" class="text-xs font-medium text-gray-500 sm:text-base">0:00</span>
        </div>

        <!-- ROW 2: Playback, Volume, Settings, Fullscreen -->
        <div class="flex items-center justify-between w-full">
            
            <!-- LEFT GROUP: Playback & Volume -->
            <div class="flex items-center space-x-3">
                <!-- Play/Pause Button -->
                <button id="playPauseBtn" title="Play/Pause (Space)" class="p-2 rounded-full bg-indigo-600 text-white hover:bg-indigo-700 transition duration-150 shadow-md focus:outline-none focus:ring-2 focus:ring-indigo-500" onclick="togglePlayPause()">
                    <svg id="playIcon" xmlns="http://www.w3.org/2000/svg" class="h-6 w-6" viewBox="0 0 24 24" fill="currentColor"><path d="M7 6v12l10-6z"/></svg>
                    <svg id="pauseIcon" xmlns="http://www.w3.org/2000/svg" class="h-6 w-6 hidden" viewBox="0 0 24 24" fill="currentColor"><path d="M6 6h4v12H6zm8 0h4v12h-4z"/></svg>
                </button>

                <!-- NEW: Volume Control Group (Hidden on tiny screens, shown on sm+) -->
                <div class="hidden sm:flex items-center space-x-2">
                    <!-- Mute Button -->
                    <button id="muteBtn" title="Mute/Unmute (M)" class="p-2 rounded-full text-gray-700 hover:bg-gray-200 transition duration-150 focus:outline-none focus:ring-2 focus:ring-gray-300" onclick="toggleMute()">
                        <!-- Volume Icon (Default) -->
                        <svg id="volumeIcon" xmlns="http://www.w3.org/2000/svg" class="h-6 w-6" viewBox="0 0 24 24" fill="currentColor"><path d="M14.75 4.75l-4 4H5v7h5.75l4 4V4.75zM17 9.5a3.5 3.5 0 010 5M19.33 7.17a6.83 6.83 0 010 9.66"/></svg>
                        <!-- Mute Icon (Hidden by Default) -->
                        <svg id="muteIcon" xmlns="http://www.w3.org/2000/svg" class="h-6 w-6 hidden" viewBox="0 0 24 24" fill="currentColor"><path d="M14.75 4.75l-4 4H5v7h5.75l4 4V4.75zM19 12c-1.74 0-3.32-.42-4.75-1.2l1.41-1.41c1.07.57 2.27.87 3.34.87 2.45 0 4.67-1.12 6.07-2.9l-1.41-1.41C20.65 11.45 19.85 12 19 12zM5.39 4.39l-1.41 1.41L14.75 16.75l-4 4V4.75l4-4z"/></svg>
                    </button>
                    <!-- Volume Slider -->
                    <input type="range" id="volumeSlider" min="0" max="100" value="100" class="h-1 w-20 cursor-pointer" oninput="changeVolume(this.value)">
                </div>
            </div>

            <!-- RIGHT GROUP: Settings & Fullscreen -->
            <div class="relative flex items-center space-x-2">
                
                <!-- Settings Button -->
                <button id="settingsBtn" title="Settings" class="p-2 rounded-full text-gray-700 hover:bg-gray-200 transition duration-150 focus:outline-none focus:ring-2 focus:ring-gray-300" onclick="toggleSettingsMenu()">
                    <svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                        <circle cx="12" cy="12" r="3"></circle>
                        <path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1 0 2.83 2 2 0 0 1-2.83 0l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1.51 1.51V21a2 2 0 0 1-2 2 2 2 0 0 1-2-2v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83 0 2 2 0 0 1 0-2.83l.06-.06a1.65 1.65 0 0 0-.33-1.82 1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1-2-2 2 2 0 0 1 2-2h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 0-2.83 2 2 0 0 1 2.83 0l.06.06a1.65 1.65 0 0 0 1.82.33H10a1.65 1.65 0 0 0 1.51-1V3a2 2 0 0 1 2-2 2 2 0 0 1 2 2v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 0 2 2 0 0 1 0 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82V12a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 2 2z"></path>
                    </svg>
                </button>
                
                <!-- Full Screen Button -->
                <button id="fullscreenBtn" title="Fullscreen (F)" class="p-2 rounded-full text-gray-700 hover:bg-gray-200 transition duration-150 focus:outline-none focus:ring-2 focus:ring-gray-300" onclick="toggleFullScreen()">
                    <svg id="fullscreenEnterIcon" xmlns="http://www.w3.org/2000/svg" class="h-6 w-6" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                        <path d="M8 3v3a2 2 0 0 1-2 2H3m18 0h-3a2 2 0 0 1-2-2V3m0 18v-3a2 2 0 0 1 2-2h3M3 16h3a2 2 0 0 1 2 2v3"></path>
                    </svg>
                    <svg id="fullscreenExitIcon" xmlns="http://www.w3.org/2000/svg" class="h-6 w-6 hidden" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                        <path d="M15 3h6v6M9 21H3v-6M21 3l-7 7M3 21l7-7"></path>
                    </svg>
                </button>

                <!-- Settings Menu Dropdown (Initially Hidden) -->
                <div id="settingsMenu" class="absolute right-0 bottom-full mb-3 w-56 bg-white rounded-lg shadow-2xl border border-gray-100 hidden z-50 overflow-hidden" style="z-index: 1002;">
                    <div class="p-3">
                        <h4 class="text-sm font-bold text-gray-700 border-b pb-1 mb-2">Settings</h4>
                    </div>

                    <!-- Quality Selection -->
                    <div class="py-1 border-b">
                        <span class="text-xs font-semibold text-gray-500 px-3 block mb-1">Qualitypan>
                        <ul id="qualityList" class="list-none p-0 m-0">
                            <!-- Quality options will be inserted here by JavaScript -->
                        </ul>
                    </div>
                    
                    <!-- Speed Selection -->
                    <div class="py-1">
                        <span class="text-xs font-semibold text-gray-500 px-3 block mb-1">Playback Speedpan>
                        <ul id="speedList" class="list-none p-0 m-0">
                            <!-- Default speeds -->
                            <li data-rate="0.25" onclick="changeSpeed(0.25)" class="text-sm px-3 py-1.5 cursor-pointer hover:bg-indigo-50 flex justify-between items-center transition-colors">0.25x</li>
                            <li data-rate="0.5" onclick="changeSpeed(0.5)" class="text-sm px-3 py-1.5 cursor-pointer hover:bg-indigo-50 flex justify-between items-center transition-colors">0.5x</li>
                            <li data-rate="0.75" onclick="changeSpeed(0.75)" class="text-sm px-3 py-1.5 cursor-pointer hover:bg-indigo-50 flex justify-between items-center transition-colors">0.75x</li>
                            <li data-rate="1" onclick="changeSpeed(1)" class="text-sm px-3 py-1.5 cursor-pointer hover:bg-indigo-50 flex justify-between items-center transition-colors active">Normal/li>
                            <li data-rate="1.25" onclick="changeSpeed(1.25)" class="text-sm px-3 py-1.5 cursor-pointer hover:bg-indigo-50 flex justify-between items-center transition-colors">1.25x</li>
                            <li data-rate="1.5" onclick="changeSpeed(1.5)" class="text-sm px-3 py-1.5 cursor-pointer hover:bg-indigo-50 flex justify-between items-center transition-colors">1.5x</li>
                            <li data-rate="1.75" onclick="changeSpeed(1.75)" class="text-sm px-3 py-1.5 cursor-pointer hover:bg-indigo-50 flex justify-between items-center transition-colors">1.75x</li>
                            <li data-rate="2" onclick="changeSpeed(2)" class="text-sm px-3 py-1.5 cursor-pointer hover:bg-indigo-50 flex justify-between items-center transition-colors">2x</li>
                        </ul>
                    </div>
                </div>
                
            </div>
        </div>
    </div>

    <!-- Lesson Metadata -->
    <div class="pt-4 border-t">
        <h3 class="text-xl font-bold text-gray-800 mb-2">Lesson Description>
        <p class="text-gray-600 whitespace-pre-wrap"><?php echo nl2br(htmlspecialchars($currentLesson['description'])); ?></p>
    </div>
</div>

<!-- Player Script -->
<script>
    // --- Global Variables and DOM Cache ---
    let player;
    let duration = 0;
    let isDragging = false; // Flag for progress bar dragging (mouse/touch)
    let lastVolume = 100; // Store volume before muting
    const videoId = '<?php echo htmlspecialchars($videoId); ?>';
    
    // Cache DOM elements for efficiency
    const DURATION_TIME = document.getElementById('durationTime');
    const CURRENT_TIME = document.getElementById('currentTime');
    const PROGRESS_BAR = document.getElementById('progressBar');
    const PROGRESS_FILL = document.getElementById('progressBarFill');
    const PLAY_ICON = document.getElementById('playIcon');
    const PAUSE_ICON = document.getElementById('pauseIcon');
    const SETTINGS_MENU = document.getElementById('settingsMenu');
    const QUALITY_LIST = document.getElementById('qualityList');
    const SPEED_LIST = document.getElementById('speedList');
    const FULLSCREEN_ENTER_ICON = document.getElementById('fullscreenEnterIcon');
    const FULLSCREEN_EXIT_ICON = document.getElementById('fullscreenExitIcon');
    const VIDEO_CONTAINER = document.getElementById('videoContainer');
    const CUSTOM_CONTROLS = document.getElementById('customControls');
    
    // Volume elements
    const VOLUME_SLIDER = document.getElementById('volumeSlider');
    const MUTE_BTN = document.getElementById('muteBtn');
    const VOLUME_ICON = document.getElementById('volumeIcon');
    const MUTE_ICON = document.getElementById('muteIcon');
    
    // --- YouTube IFrame API Loader ---
    if (typeof YT === 'undefined' || typeof YT.Player === 'undefined') {
        const tag = document.createElement('script');
        tag.src = "https://www.youtube.com/iframe_api";
        const firstScriptTag = document.getElementsByTagName('script')[0];
        firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
    }

    // Function called by the YouTube API
    window.onYouTubeIframeAPIReady = function() {
        if (!document.getElementById('player')) {
            setTimeout(window.onYouTubeIframeAPIReady, 100);
            return;
        }

        player = new YT.Player('player', {
            videoId: videoId,
            playerVars: {
                'autoplay': 1,
                'rel': 0, 
                'modestbranding': 1, 
                'controls': 0, // IMPORTANT: Use custom controls only
                'disablekb': 1, // Disable YouTube's default keyboard controls
                'fs': 0 
            },
            events: {
                'onReady': onPlayerReady,
                'onStateChange': onPlayerStateChange
            }
        });
    }

    function onPlayerReady(event) {
        // Set duration on load 
        duration = player.getDuration();
        if (DURATION_TIME) DURATION_TIME.textContent = formatTime(duration);
        
        // Update icon based on initial state (autoplay might be blocked)
        updatePlayPauseIcon(player.getPlayerState());
        
        // Setup initial settings options
        setupQualityOptions();
        highlightSpeed(player.getPlaybackRate());

        // Initialize volume to slider value
        if(VOLUME_SLIDER) player.setVolume(parseInt(VOLUME_SLIDER.value, 10));
        updateVolumeIcon(player.isMuted(), player.getVolume());


        // Start updating player state (progress bar, time, and settings highlights) 
        setInterval(updatePlayerState, 250);
        
        // Attach event listeners for advanced interactions (keyboard, click outside, dragging, touch)
        addAdvancedEventListeners();
    }

    function onPlayerStateChange(event) {
        updatePlayPauseIcon(event.data);
    }
    
    // --- Core Player Controls ---
    
    function togglePlayPause() {
        if (!player || typeof player.getPlayerState !== 'function') return;

        const state = player.getPlayerState();
        if (state === YT.PlayerState.PLAYING || state === YT.PlayerState.BUFFERING) {
            player.pauseVideo();
        } else {
            player.playVideo();
        }
    }

    /**
     * Calculates the seek time based on a client input event (mouse or touch) and seeks the video.
     * @param {object} input - An object with clientX (e.g., MouseEvent or Touch object).
     */
    function seek(input) {
        if (!player || duration === 0 || !PROGRESS_BAR) return;
        
        const rect = PROGRESS_BAR.getBoundingClientRect();
        
        // Calculate the click position relative to the progress bar width
        let clickPosition = input.clientX - rect.left;
        const width = rect.width;

        // Clamp the position within the bounds
        clickPosition = Math.max(0, Math.min(clickPosition, width));
        
        // Calculate the new time in seconds
        const newTime = (clickPosition / width) * duration;
        
        // Seek to the new position
        player.seekTo(newTime, true);
        
        // If paused, immediately update time display for better feedback
        if (player.getPlayerState() !== YT.PlayerState.PLAYING) {
             updatePlayerState();
        }
    }
    
    // Volume control functions
    function toggleMute() {
        if (!player || typeof player.isMuted !== 'function') return;

        if (player.isMuted()) {
            player.unMute();
            // Restore volume to last non-zero level
            const restoredVolume = lastVolume > 0 ? lastVolume : 50; 
            player.setVolume(restoredVolume);
            if(VOLUME_SLIDER) VOLUME_SLIDER.value = restoredVolume;
            updateVolumeIcon(false, restoredVolume);
        } else {
            // Save current volume before muting
            lastVolume = player.getVolume();
            player.mute();
            if(VOLUME_SLIDER) VOLUME_SLIDER.value = 0;
            updateVolumeIcon(true, 0);
        }
    }

    function changeVolume(level) {
        if (!player || typeof player.setVolume !== 'function') return;

        const volume = parseInt(level, 10);
        player.setVolume(volume);

        if (volume === 0) {
            player.mute();
            updateVolumeIcon(true, 0);
        } else {
            player.unMute();
            lastVolume = volume;
            updateVolumeIcon(false, volume);
        }
    }

    function updateVolumeIcon(isMuted, volume) {
        if (!VOLUME_ICON || !MUTE_ICON) return;
        
        if (isMuted || volume === 0) {
            VOLUME_ICON.classList.add('hidden');
            MUTE_ICON.classList.remove('hidden');
        } else {
            VOLUME_ICON.classList.remove('hidden');
            MUTE_ICON.classList.add('hidden');
        }
    }

    function formatTime(seconds) {
        const minutes = Math.floor(seconds / 60);
        const remainingSeconds = Math.floor(seconds % 60);
        return minutes + ":" + (remainingSeconds < 10 ? "0" : "") + remainingSeconds;
    }
    
    function updatePlayPauseIcon(state) {
        if (!PLAY_ICON || !PAUSE_ICON) return;
        
        // State 1: Playing, State 3: Buffering. Show Pause Icon.
        if (state === YT.PlayerState.PLAYING || state === YT.PlayerState.BUFFERING) {
            PLAY_ICON.classList.add('hidden');
            PAUSE_ICON.classList.remove('hidden');
        } 
        // State 2: Paused, State 0: Ended, State -1: Unstarted/Cued. Show Play Icon.
        else {
            PLAY_ICON.classList.remove('hidden');
            PAUSE_ICON.classList.add('hidden');
        }
    }

    // --- Settings and UI Synchronization Logic ---

    function setupQualityOptions() {
        if (!player || !QUALITY_LIST || typeof player.getAvailableQualityLevels !== 'function') return;

        const availableQualities = player.getAvailableQualityLevels();
        const currentQuality = player.getPlaybackQuality();

        QUALITY_LIST.innerHTML = ''; // Clear existing list

        availableQualities.forEach(quality => {
            const li = document.createElement('li');
            
            li.className = `text-sm px-3 py-1.5 cursor-pointer hover:bg-indigo-50 flex justify-between items-center transition-colors text-gray-700`;
            li.setAttribute('data-quality', quality);
            li.onclick = () => {
                changeQuality(quality);
            };

            // Nicer display names for quality levels
            let displayName = quality.toUpperCase();
            if (quality === 'small') displayName = '240p';
            else if (quality === 'medium') displayName = '360p';
            else if (quality === 'large') displayName = '480p';
            else if (quality === 'hd720') displayName = '720p HD';
            else if (quality === 'hd1080') displayName = '1080p HD';
            else if (quality === 'highres') displayName = 'Original)';
            else if (quality === 'auto') displayName = 'Auto'; 

            li.textContent = displayName;
            QUALITY_LIST.appendChild(li);
        });
        highlightQuality(currentQuality);
    }
    
    function highlightSpeed(rate) {
        document.querySelectorAll('#speedList li').forEach(li => {
            li.classList.remove('active'); 
            if (parseFloat(li.getAttribute('data-rate')) === rate) {
                li.classList.add('active'); 
            }
        });
    }

    function highlightQuality(quality) {
        document.querySelectorAll('#qualityList li').forEach(li => {
            li.classList.remove('active');
            if (li.getAttribute('data-quality') === quality) {
                li.classList.add('active');
            }
        });
    }

    function toggleSettingsMenu() {
        if (SETTINGS_MENU) SETTINGS_MENU.classList.toggle('hidden');
        
        // Re-setup options every time it opens to ensure state is fresh 
        if (!SETTINGS_MENU.classList.contains('hidden')) {
            setupQualityOptions(); 
            highlightSpeed(player.getPlaybackRate());
        }
    }

    function changeSpeed(rate) {
        if (!player || typeof player.setPlaybackRate !== 'function') return;
        
        player.setPlaybackRate(rate);
        highlightSpeed(rate);
        toggleSettingsMenu(); 
    }

    function changeQuality(quality) {
        if (!player || typeof player.setPlaybackQuality !== 'function') {
            console.error("Player not ready or setPlaybackQuality function unavailable.");
            return;
        }
        
        // This is a suggestion, not a guarantee. The updatePlayerState interval handles
        // syncing the UI with the actual current quality.
        player.setPlaybackQuality(quality);
        highlightQuality(quality); // Immediate optimistic UI update
        toggleSettingsMenu(); 
    }
    
    // --- Full Screen Logic ---
    
    function toggleFullScreen() {
        // Check if currently in fullscreen 
        const isFullscreen = document.fullscreenElement || document.webkitFullscreenElement || document.mozFullScreenElement || document.msFullscreenElement;
        
        if (isFullscreen) {
            // Exit fullscreen 
            if (document.exitFullscreen) {
                document.exitFullscreen();
            } else if (document.mozCancelFullScreen) { 
                document.mozCancelFullScreen();
            } else if (document.webkitExitFullscreen) {
                document.webkitExitFullscreen();
            } else if (document.msExitFullscreen) { 
                document.msExitFullscreen();
            }
        } else {
            // Enter fullscreen 
            if (VIDEO_CONTAINER.requestFullscreen) {
                VIDEO_CONTAINER.requestFullscreen();
            } else if (VIDEO_CONTAINER.mozRequestFullScreen) {
                VIDEO_CONTAINER.mozRequestFullScreen();
            } else if (VIDEO_CONTAINER.webkitRequestFullscreen) {
                VIDEO_CONTAINER.webkitRequestFullscreen();
            } else if (VIDEO_CONTAINER.msRequestFullscreen) {
                VIDEO_CONTAINER.msRequestFullscreen();
            }
        }
    }

    // Handle fullscreen change event (e.g., user presses ESC)
    document.addEventListener('fullscreenchange', handleFullscreenChange);
    document.addEventListener('webkitfullscreenchange', handleFullscreenChange);
    document.addEventListener('mozfullscreenchange', handleFullscreenChange);
    document.addEventListener('MSFullscreenChange', handleFullscreenChange);

    function handleFullscreenChange() {
        const isFullscreen = document.fullscreenElement || document.webkitFullscreenElement || document.mozFullScreenElement || document.msFullscreenElement;

        if (isFullscreen) {
            // Enter State
            FULLSCREEN_ENTER_ICON.classList.add('hidden');
            FULLSCREEN_EXIT_ICON.classList.remove('hidden');
            VIDEO_CONTAINER.classList.add('is-fullscreen');
            CUSTOM_CONTROLS.classList.add('fixed-controls');
        } else {
            // Exit State
            FULLSCREEN_ENTER_ICON.classList.remove('hidden');
            FULLSCREEN_EXIT_ICON.classList.add('hidden');
            VIDEO_CONTAINER.classList.remove('is-fullscreen');
            CUSTOM_CONTROLS.classList.remove('fixed-controls');
        }
    }

    // --- State Updater (runs every 250ms) ---
    function updatePlayerState() {
        if (typeof player.getDuration === 'function' && duration > 0) {
            const currentTime = player.getCurrentTime();
            
            // Only update progress bar if we are NOT dragging
            if (!isDragging) {
                const progressPercent = (currentTime / duration) * 100;
                if (PROGRESS_FILL) PROGRESS_FILL.style.width = `${progressPercent}%`;
                if (CURRENT_TIME) CURRENT_TIME.textContent = formatTime(currentTime);
            }
            
            // Sync settings highlights (Fix for quality changing automatically)
            highlightSpeed(player.getPlaybackRate());
            highlightQuality(player.getPlaybackQuality());
            
            // Sync volume UI elements
            if (VOLUME_SLIDER) {
                const isMuted = player.isMuted();
                const volume = player.getVolume();
                
                // Keep the slider in sync, unless the user is actively dragging it
                if (!VOLUME_SLIDER.isDragging) {
                    VOLUME_SLIDER.value = isMuted ? 0 : volume;
                }

                updateVolumeIcon(isMuted, volume);
            }
        }
    }

    // --- Advanced Event Listeners (Keyboard, External Click, Dragging, TOUCH) ---
    function addAdvancedEventListeners() {
        
        // 1. Keyboard Controls (Space, F, M, Arrows)
        document.addEventListener('keydown', (e) => {
            // Only apply controls if the settings menu is closed and the player is ready
            if (!player || !SETTINGS_MENU || !SETTINGS_MENU.classList.contains('hidden')) return;

            if (e.code === 'Space') {
                e.preventDefault(); // Prevent scrolling
                togglePlayPause();
            } else if (e.key === 'ArrowRight') {
                e.preventDefault();
                player.seekTo(player.getCurrentTime() + 5, true); // Seek forward 5s
            } else if (e.key === 'ArrowLeft') {
                e.preventDefault();
                player.seekTo(player.getCurrentTime() - 5, true); // Seek backward 5s
            } else if (e.key === 'f' || e.key === 'F') {
                e.preventDefault();
                toggleFullScreen();
            } else if (e.key === 'm' || e.key === 'M') { 
                e.preventDefault();
                toggleMute();
            }
        });

        // 2. Click-Outside-Settings-Menu-to-Close
        document.addEventListener('click', (e) => {
            const settingsBtn = document.getElementById('settingsBtn');
            const menu = SETTINGS_MENU;

            if (menu && !menu.classList.contains('hidden')) {
                // Check if the click is outside the settings button and the menu itself
                if (!menu.contains(e.target) && !settingsBtn.contains(e.target)) {
                    menu.classList.add('hidden');
                }
            }
        });
        
        // 3. Progress Bar Dragging Logic (Mouse)
        
        // Mouse Down (Start Dragging)
        PROGRESS_BAR.addEventListener('mousedown', (e) => {
            e.preventDefault();
            isDragging = true;
            PROGRESS_BAR.style.cursor = 'grabbing';
            seek(e); // Seek immediately on mousedown
        });

        // Mouse Move (While Dragging)
        document.addEventListener('mousemove', (e) => {
            if (!isDragging) return;

            const rect = PROGRESS_BAR.getBoundingClientRect();
            let clickPosition = e.clientX - rect.left;
            
            // Clamp the position within the bounds of the progress bar
            clickPosition = Math.max(0, Math.min(clickPosition, rect.width));
            
            const progressPercent = (clickPosition / rect.width) * 100;
            const newTime = (clickPosition / rect.width) * duration;

            // Only update the UI while dragging
            PROGRESS_FILL.style.width = `${progressPercent}%`;
            CURRENT_TIME.textContent = formatTime(newTime);
        });

        // Mouse Up (End Dragging and Commit Seek)
        document.addEventListener('mouseup', (e) => {
            if (!isDragging) return;
            
            isDragging = false;
            PROGRESS_BAR.style.cursor = 'pointer';
            
            // Commit the final seek action based on the mouseup position
            seek(e);
        });

        // 4. Progress Bar Touch Logic (Mobile)
        
        // Touch Start (Start Dragging)
        PROGRESS_BAR.addEventListener('touchstart', (e) => {
            if (e.touches.length !== 1) return; // Only track single-touch
            e.preventDefault(); 
            isDragging = true;
            PROGRESS_BAR.style.cursor = 'grabbing';
            seek(e.touches[0]); // Seek immediately on touchstart
        }, { passive: false }); // Needs to be non-passive to prevent scrolling

        // Touch Move (While Dragging)
        document.addEventListener('touchmove', (e) => {
            if (!isDragging || e.touches.length === 0) return;
            e.preventDefault(); 
            
            const touch = e.touches[0];
            const rect = PROGRESS_BAR.getBoundingClientRect();
            let clickPosition = touch.clientX - rect.left;
            
            // Clamp
            clickPosition = Math.max(0, Math.min(clickPosition, rect.width));
            
            const progressPercent = (clickPosition / rect.width) * 100;
            const newTime = (clickPosition / rect.width) * duration;

            // Only update the UI while dragging
            PROGRESS_FILL.style.width = `${progressPercent}%`;
            CURRENT_TIME.textContent = formatTime(newTime);
        }, { passive: false });

        // Touch End (End Dragging and Commit Seek)
        document.addEventListener('touchend', (e) => {
            if (!isDragging) return;
            
            isDragging = false;
            PROGRESS_BAR.style.cursor = 'pointer';
            
            // If the touch ended, use the last known position from changedTouches
            if (e.changedTouches.length > 0) {
                 seek(e.changedTouches[0]);
            }
        });
    }
</script>