const videoContainer = document.querySelector('.video-container');
const video = document.querySelector('.video-container video');
const controlsContainer = document.querySelector('.video-container .controls-container');
const enableSoundButton = document.getElementById("enableSound");

const playPauseButton = document.querySelector('.video-container .controls button.play-pause');
const rewindButton = document.querySelector('.video-container .controls button.rewind');
const fastForwardButton = document.querySelector('.video-container .controls button.fast-forward');
const volumeButton = document.querySelector('.video-container .controls button.volume');
const fullScreenButton = document.querySelector('.video-container .controls button.full-screen');
const castButton = document.querySelector('.video-container .controls button.cast');

const playButton = playPauseButton.querySelector('.playing');
const pauseButton = playPauseButton.querySelector('.paused');
const fullVolumeButton = volumeButton.querySelector('.full-volume');
const mutedButton = volumeButton.querySelector('.muted');
const maximizeButton = fullScreenButton.querySelector('.maximize');
const minimizeButton = fullScreenButton.querySelector('.minimize');

const progressBar = document.querySelector('.video-container .progress-controls .progress-bar');
const watchedBar = document.querySelector('.video-container .progress-controls .progress-bar .watched-bar');
const timeLeft = document.querySelector('.video-container .progress-controls .time-remaining');

let controlsTimeout;

let subtitlesEnabled = false;
const captionsButton = document.querySelector('.captions');

// Activar carga perezosa (lazy load) para video
video.setAttribute('loading', 'lazy');  // Lazy load para mejorar la carga inicial
video.setAttribute('preload', 'metadata');  // Solo carga metadatos del video

// Hacer visible el reproductor y los controles de inmediato
controlsContainer.style.opacity = '1';
controlsContainer.style.display = 'flex';

// Función para alternar subtítulos
function toggleSubtitles() {
    const tracks = video.textTracks;
    subtitlesEnabled = !subtitlesEnabled;

    for (let i = 0; i < tracks.length; i++) {
        tracks[i].mode = subtitlesEnabled ? 'showing' : 'hidden';
    }

    if (subtitlesEnabled) {
        captionsButton.setAttribute('aria-label', 'Desactivar Subtítulos');
    } else {
        captionsButton.setAttribute('aria-label', 'Activar Subtítulos');
    }
}

captionsButton.addEventListener('click', toggleSubtitles);

video.addEventListener('loadeddata', () => {
    video.play();
    playButton.style.display = 'none';
    pauseButton.style.display = 'block';
    controlsContainer.style.display = 'flex'; // Mostrar controles
    controlsContainer.style.opacity = '1';  // Asegurarnos de que los controles sean visibles
    if (video.muted) {
        enableSoundButton.style.display = "block";
    }
});

enableSoundButton.addEventListener("click", () => {
    video.muted = false;
    video.volume = 1.0;
    enableSoundButton.style.display = "none";
});

const displayControls = () => {
    controlsContainer.style.opacity = '1';
    document.body.style.cursor = 'initial';
    if (controlsTimeout) clearTimeout(controlsTimeout);
    controlsTimeout = setTimeout(() => {
        controlsContainer.style.opacity = '0';
        document.body.style.cursor = 'none';
    }, 3000);
};

const playPause = () => {
    if (video.paused) {
        video.play();
        playButton.style.display = 'none';
        pauseButton.style.display = 'block';
    } else {
        video.pause();
        playButton.style.display = 'block';
        pauseButton.style.display = 'none';
    }
};

const toggleMute = () => {
    video.muted = !video.muted;
    fullVolumeButton.style.display = video.muted ? 'none' : 'block';
    mutedButton.style.display = video.muted ? 'block' : 'none';

    if (video.muted) {
        enableSoundButton.style.display = "block";
    } else {
        enableSoundButton.style.display = "none";
    }
};

const toggleFullScreen = () => {
    if (!document.fullscreenElement) {
        videoContainer.requestFullscreen();
    } else {
        document.exitFullscreen();
    }
};

document.addEventListener('fullscreenchange', () => {
    maximizeButton.style.display = document.fullscreenElement ? 'none' : 'block';
    minimizeButton.style.display = document.fullscreenElement ? 'block' : 'none';
});

document.addEventListener('keyup', (event) => {
    if (event.code === 'Space') playPause();
    if (event.code === 'KeyM') toggleMute();
    if (event.code === 'KeyF') toggleFullScreen();
    displayControls();
});

document.addEventListener('mousemove', displayControls);

video.addEventListener('loadedmetadata', () => {
    updateTotalDuration();
});

function updateTotalDuration() {
    if (!isNaN(video.duration)) {
        timeLeft.textContent = formatTime(video.duration);
    }
}

video.addEventListener('timeupdate', () => {
    watchedBar.style.width = ((video.currentTime / video.duration) * 100) + '%';
    const totalSecondsRemaining = video.duration - video.currentTime;
    timeLeft.textContent = formatTime(totalSecondsRemaining);
});

function formatTime(seconds) {
    const time = new Date(null);
    time.setSeconds(seconds);
    const hours = Math.floor(seconds / 3600).toString().padStart(2, '0');
    const minutes = Math.floor((seconds % 3600) / 60).toString().padStart(2, '0');
    const sec = Math.floor(seconds % 60).toString().padStart(2, '0');
    return `${hours}:${minutes}:${sec}`;
}

// Eventos de los botones de control
playPauseButton.addEventListener('click', playPause);
rewindButton.addEventListener('click', () => { video.currentTime -= 10; });
fastForwardButton.addEventListener('click', () => { video.currentTime += 10; });
volumeButton.addEventListener('click', toggleMute);
fullScreenButton.addEventListener('click', toggleFullScreen);

// Agregar funcionalidad al botón de episodios
const episodesButton = document.querySelector('.episodes');
const episodesMenu = document.querySelector('.episodes-menu');

if (episodesButton && episodesMenu) {
    episodesButton.addEventListener('click', () => {
        episodesMenu.style.display = (episodesMenu.style.display === 'none' || episodesMenu.style.display === '') ? 'block' : 'none';
    });
}

// Función para activar/desactivar Picture-in-Picture (Cast)
async function togglePictureInPicture() {
    try {
        if (document.pictureInPictureElement) {
            await document.exitPictureInPicture();
        } else {
            await video.requestPictureInPicture();
        }
    } catch (error) {
        console.error('Error al alternar Picture-in-Picture:', error);
    }
}

// Evento del botón Cast (Picture-in-Picture)
if (castButton) {
    castButton.addEventListener('click', togglePictureInPicture);
}

document.addEventListener("DOMContentLoaded", function () {
    const seasonTitles = document.querySelectorAll(".season-title");

    seasonTitles.forEach(title => {
        title.addEventListener("click", function () {
            // Ocultar todas las temporadas menos la actual
            document.querySelectorAll(".season-content").forEach(season => {
                season.classList.add("hidden");
            });

            // Quitar la clase 'active' de todos los títulos
            seasonTitles.forEach(t => t.classList.remove("active"));

            // Mostrar la temporada seleccionada
            const selectedSeason = document.getElementById(this.dataset.season);
            selectedSeason.classList.remove("hidden");

            // Agregar la clase 'active' al título seleccionado
            this.classList.add("active");
        });
    });
});

// Evento para hacer clic en la barra de progreso y adelantar el video
progressBar.addEventListener('click', (event) => {
    const clickPosition = event.offsetX; 
    const progressBarWidth = progressBar.offsetWidth; 
    const newTime = (clickPosition / progressBarWidth) * video.duration;
    video.currentTime = newTime;
});
