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'); // Botón Cast (Picture-in-Picture)

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;

// Ocultar controles y botón de sonido al inicio
controlsContainer.style.opacity = '0';
enableSoundButton.style.display = 'none';

// Cuando el video se cargue
video.addEventListener('loadeddata', () => {
    video.play();
    playButton.style.display = 'none';
    pauseButton.style.display = 'block';
    
    controlsContainer.style.opacity = '0';
    controlsContainer.style.display = 'flex';
    
    if (video.muted) {
        enableSoundButton.style.display = "block";
    }
});

// Botón de "Activar sonido"
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(); // Se actualiza la duración real
});

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; // Posición del clic dentro de la barra de progreso
    const progressBarWidth = progressBar.offsetWidth; // Ancho total de la barra
    const newTime = (clickPosition / progressBarWidth) * video.duration; // Calculamos el nuevo tiempo
    video.currentTime = newTime; // Establecemos el nuevo tiempo en el video
});
