<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Multiview</title>
    <style>
        .video-container {
            display: grid;
            grid-template-columns: repeat(4, 1fr); /* 5 columnas por defecto en pantallas grandes */
            gap: 2px;
            max-width: 100%;
            margin: 0px;
            width: 100%;
            
            padding: 0px;
            box-sizing: border-box;
        }

        .video-item {
            position: relative;
            display: flex;
            flex-direction: column;
            justify-content: center;
            align-items: normal;
            text-align: center;
            background-color: rgba(0, 0, 0, 0.5);
            border-radius: 8px;
            overflow: hidden;
            height: 100%;
        }

        .video-item p {
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            color: white;
            font-size: 18px;
            font-weight: bold;
            z-index: 10;
            transition: opacity 0.3s ease;
        }

        video {
            width: 100%;
            height: auto;
            object-fit: cover;
        }

        .audio-control {
            position: absolute;
            bottom: 0px;
            background-color: rgba(0, 0, 0, 0.6);
            color: white;
            padding: 5px 10px;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            z-index: 20;
            font-size: 9px;
        }

        @media (max-width: 1024px) {
            .video-container {
                grid-template-columns: repeat(3, 1fr); /* 3 columnas */
            }
        }

        @media (max-width: 600px) {
            .video-container {
                grid-template-columns: 1fr; /* 1 columna */
            }
        }
    </style>
</head>
<body style="background-color: #424242;font-family: sans-serif;">
    <div class="video-container" id="video-container"></div>

    <script src="https://cdn.jsdelivr.net/npm/hls.js@latest"></script>
    <script>
         const m3u8Urls = [
            'http://192.168.10.186:8080/live/truJillo573gtFRG75dfd.m3u8',
            'http://192.168.10.186:8080/live/chiclayo548rtshe7555stujjUY.m3u8',
            'http://192.168.10.186:8080/live/iCa5ertshe7rw5ssujsUgX.m3u8',
            'http://192.168.10.186:8080/live/piuRaherfhedsdfgssjvsfaX.m3u8',
            'http://192.168.10.186:8080/live/tacna97Ybg&3CdfRGkikJ.m3u8',
            'http://192.168.10.186:8080/live/huAcho897G54JsmkUytdA.m3u8',
            'http://192.168.10.186:8080/live/areqiPahsgsHgsddgGGkdhsg.m3u8',
            'http://192.168.10.186:8080/live/huanCayo765GydhjhGFHJK876.m3u8',
            'http://192.168.10.186:8080/live/iquiTosUYHBF56654FGhbvcxfg756.m3u8',
            'http://192.168.10.186:8080/live/tarPoto866Fhs8754skjghqaS.m3u8',
            'http://192.168.10.186:8080/live/chimboteU4Hve56dvghjGhb74356.m3u8',
            'http://192.168.10.186:8080/live/CAjArca562009shgsYTjdqaS.m3u8'
        ];

        let streamNames = [
            'TRUJLLO',
            'CHICLAYO',
            'ICA',
            'PIURA',
            'TACNA',
            'HUACHO',
            'AREQUIPA',
            'HUANCAYO',
            'IQUITOS',
            'TARAPOTO',
            'CHIMBOTE',
            'CAJAMARCA'
        ];

        const container = document.getElementById("video-container");

        let hlsInstances = []; // Para almacenar las instancias de HLS

        function loadVideos() {
            m3u8Urls.forEach((url, index) => {
                const videoItem = document.createElement("div");
                videoItem.classList.add("video-item");

                const videoElement = document.createElement("video");
                videoElement.id = `video${index + 1}`;
                videoElement.autoplay = true;
                videoElement.muted = true;
                videoElement.controls = false;

                const nameElement = document.createElement("p");
                nameElement.innerText = streamNames[index];

                const audioButton = document.createElement("button");
                audioButton.innerText = "MUTE";
                audioButton.classList.add("audio-control");
                audioButton.addEventListener("click", function() {
                    if (videoElement.muted) {
                        videoElement.muted = false;
                        audioButton.innerText = "AUDIO";
                        audioButton.style.backgroundColor = "rgb(244, 67, 54,0.5)";

                    } else {
                        videoElement.muted = true;
                        audioButton.innerText = "MUTE";
                       audioButton.style.backgroundColor = "rgba(0, 0, 0, 0.6) ";
                    }
                });
                const nameElement2 = document.createElement("div");
                nameElement2.innerText = streamNames[index];
                nameElement2.style.fontSize = "10px";
                nameElement2.style.color = "white";

                videoItem.appendChild(nameElement);
                videoItem.appendChild(videoElement);
                videoItem.appendChild(audioButton);
                container.appendChild(videoItem);
                videoItem.appendChild(nameElement2);

                nameElement.style.opacity = '1';
                nameElement2.style.opacity = '0';

                videoElement.addEventListener('loadeddata', function() {
                    nameElement.style.opacity = '0';
                    nameElement2.style.opacity = '1';
                });

                videoElement.addEventListener('play', function() {
                    nameElement.style.opacity = '0';
                    nameElement2.style.opacity = '1';
                });

                // Inicialización de HLS
                if (Hls.isSupported()) {
                    const hls = new Hls();
                    hlsInstances[index] = hls;
                    hls.loadSource(url);
                    hls.attachMedia(videoElement);
                    hls.on(Hls.Events.MANIFEST_PARSED, function () {
                        videoElement.play();
                    });

                    // Detectar cuando el stream se detiene y reiniciar
                    videoElement.addEventListener('ended', function() {
                        console.log(`Stream ${index + 1} ha terminado. Recargando...`);
                        restartStream(index, videoElement, url);
                    });

                } else if (videoElement.canPlayType('application/vnd.apple.mpegurl')) {
                    // Para Safari que soporta HLS nativamente
                    videoElement.src = url;
                    videoElement.play();

                    // Detectar cuando el stream se detiene y reiniciar
                    videoElement.addEventListener('ended', function() {
                        console.log(`Stream ${index + 1} ha terminado. Recargando...`);
                        restartStream(index, videoElement, url);
                    });
                }
            });
        }

        function restartStream(index, videoElement, url) {
            console.log(`Reiniciando stream ${index + 1}`);
            videoElement.pause();
            videoElement.src = '';  // Limpiar la fuente
            videoElement.load();    // Recargar el video

            // Si se está usando HLS.js, recargar el flujo
            if (Hls.isSupported()) {
                const hls = new Hls();
                hlsInstances[index] = hls; // Guardamos la nueva instancia de HLS
                hls.loadSource(url);
                hls.attachMedia(videoElement);
                hls.on(Hls.Events.MANIFEST_PARSED, function () {
                    videoElement.play();  // Iniciar el video de nuevo
                });
            } else if (videoElement.canPlayType('application/vnd.apple.mpegurl')) {
                videoElement.src = url;
                videoElement.play();  // Iniciar el video de nuevo
            }
        }


        function reloadPage() {
        // Aquí puedes llamar a la función de cargar los videos nuevamente.
        // Por ejemplo, si tienes `loadVideos` que carga los videos:
         location.reload(); // Carga los videos otra vez
        }
        // Función para verificar y recargar los videos
        function updateEmptyStreams() {
            const videos = document.querySelectorAll('video');
            videos.forEach((videoElement, index) => {
                if (videoElement.paused || videoElement.ended) {
                    console.log(`Recargando stream ${index + 1}`);
                    restartStream(index, videoElement, m3u8Urls[index]);
                }
            });
        }


         // Recargar los videos
        loadVideos(); // Solo carga los videos una vez al principio

        // Monitoreo: Actualizamos cada 60 segundos
        setInterval(updateEmptyStreams, 10000);  // Esto verificará si algún video ha terminado o está pausado
        setInterval(reloadPage, 600000);
        // Actualización automática de los streams cada 60 segundos (ajustable)
      /* setInterval(() => {
            // Aquí podrías actualizar m3u8Urls si tienes una fuente externa de URLs
            console.log('Recargando videos...');
            loadVideos();
        }, 20000); // 60000ms = 1 minuto
*/       
        

    </script>
</body>
</html>
