<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Movie Banner</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/OwlCarousel2/2.3.4/assets/owl.carousel.min.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/OwlCarousel2/2.3.4/assets/owl.theme.default.min.css">

    <style>
        body {
            margin: 0;
            padding: 0;
            overflow: hidden;
            background-color: transparent;
            display: flex;
            align-items: center;
            justify-content: center;
            height: 100vh;
            width: 100vw;
        }

        .carousel-container {
            width: 100%;
            height: 100vh;
            display: flex;
            align-items: center;
            justify-content: center;
            position: relative;
        }

        .owl-carousel {
            display: flex;
            width: 100%;
            height: 100vh;
        }

        .owl-stage-outer, .owl-stage {
            height: 100%;
        }
        
        .owl-item {
            height: 100%;
            display: flex;
            align-items: center;
            justify-content: center;
        }

        .carousel-item {
            height: 100%;
            display: flex;
            align-items: center;
            justify-content: center;
            padding: 0 5px;
        }

        .carousel-item img {
            height: 90vh;
            width: auto;
            object-fit: cover;
            aspect-ratio: 2/3;
            border-radius: 10px;
            box-shadow: 0 8px 16px rgba(0,0,0,0.4);
        }
        
        /* Eliminar botones de navegación y puntos */
        .owl-nav, .owl-dots {
            display: none;
        }
    </style>
</head>
<body>
    <div class="carousel-container">
        <div class="owl-carousel" id="movie-carousel">
            <!-- Movie posters will be added here dynamically -->
        </div>
    </div>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/OwlCarousel2/2.3.4/owl.carousel.min.js"></script>

    <script>
        const apiKey = '6b8e3eaa1a03ebb45642e9531d8a76d2'; // Tu API Key de TMDb
        let allMovies = [];

        async function fetchMovies() {
            try {
                // Obtener fechas del año previo y actual
                const currentDate = new Date();
                const currentYear = currentDate.getFullYear();
                const previousYear = currentYear - 1;
                
                const startDate = `${previousYear}-01-01`;
                const endDate = `${currentYear}-12-31`;

                // 1. Películas populares del año previo y actual
                const popularResponse = await fetch(`https://api.themoviedb.org/3/discover/movie?api_key=${apiKey}&language=es-MX&sort_by=popularity.desc&primary_release_date.gte=${startDate}&primary_release_date.lte=${endDate}&page=1`);
                const popularData = await popularResponse.json();

                // 2. Películas mejor calificadas del año previo y actual
                const topRatedResponse = await fetch(`https://api.themoviedb.org/3/discover/movie?api_key=${apiKey}&language=es-MX&sort_by=vote_average.desc&primary_release_date.gte=${startDate}&primary_release_date.lte=${endDate}&vote_count.gte=100&page=1`);
                const topRatedData = await topRatedResponse.json();

                // 3. Películas de Netflix (usando watch providers)
                const netflixResponse = await fetch(`https://api.themoviedb.org/3/discover/movie?api_key=${apiKey}&language=es-MX&sort_by=popularity.desc&primary_release_date.gte=${startDate}&primary_release_date.lte=${endDate}&with_watch_providers=8&watch_region=MX&page=1`);
                const netflixData = await netflixResponse.json();

                // 4. Películas de Amazon Prime (usando watch providers)
                const amazonResponse = await fetch(`https://api.themoviedb.org/3/discover/movie?api_key=${apiKey}&language=es-MX&sort_by=popularity.desc&primary_release_date.gte=${startDate}&primary_release_date.lte=${endDate}&with_watch_providers=119&watch_region=MX&page=1`);
                const amazonData = await amazonResponse.json();

                // 5. Próximos estrenos de cine
                const upcomingResponse = await fetch(`https://api.themoviedb.org/3/movie/upcoming?api_key=${apiKey}&language=es-MX&page=1`);
                const upcomingData = await upcomingResponse.json();

                // 6. Películas actualmente en cines
                const nowPlayingResponse = await fetch(`https://api.themoviedb.org/3/movie/now_playing?api_key=${apiKey}&language=es-MX&page=1`);
                const nowPlayingData = await nowPlayingResponse.json();

                // Combinar todas las películas
                allMovies = [
                    ...popularData.results.slice(0, 15),
                    ...topRatedData.results.slice(0, 10),
                    ...netflixData.results.slice(0, 10),
                    ...amazonData.results.slice(0, 10),
                    ...upcomingData.results.slice(0, 15),
                    ...nowPlayingData.results.slice(0, 10)
                ];

                // Eliminar duplicados basados en ID
                const uniqueIds = new Set();
                allMovies = allMovies.filter(movie => {
                    if (uniqueIds.has(movie.id)) {
                        return false;
                    }
                    uniqueIds.add(movie.id);
                    return true;
                });

                // Filtrar solo películas con póster
                allMovies = allMovies.filter(movie => movie.poster_path);

                // Filtrar películas con buena calificación (opcional, para calidad)
                allMovies = allMovies.filter(movie => movie.vote_average >= 6.0 || !movie.vote_average);

                // Mezclar array para variedad
                allMovies = shuffleArray(allMovies);
                
                // Duplicar el array para hacer un loop infinito
                allMovies = [...allMovies, ...allMovies];

                updateCarousel();
            } catch (error) {
                console.error("Error fetching movies from TMDb:", error);
            }
        }

        // Función para mezclar un array (algoritmo Fisher-Yates)
        function shuffleArray(array) {
            for (let i = array.length - 1; i > 0; i--) {
                const j = Math.floor(Math.random() * (i + 1));
                [array[i], array[j]] = [array[j], array[i]];
            }
            return array;
        }

        function updateCarousel() {
            const movieCarousel = document.getElementById('movie-carousel');
            
            // Limpiar el carrusel antes de agregar elementos
            movieCarousel.innerHTML = '';

            allMovies.forEach((movie) => {
                const title = movie.title;
                const posterPath = `https://image.tmdb.org/t/p/w780${movie.poster_path}`;
                const movieLink = `https://www.themoviedb.org/movie/${movie.id}`;

                const carouselItem = document.createElement('div');
                carouselItem.className = 'carousel-item';
                
                carouselItem.innerHTML = `<a href="${movieLink}" target="_blank">
                    <img src="${posterPath}" alt="${title}">
                </a>`;

                movieCarousel.appendChild(carouselItem);
            });

            // Inicializar Owl Carousel con la velocidad ajustada
            $('.owl-carousel').owlCarousel({
                loop: true,
                margin: 5,
                nav: false,
                dots: false,
                autoplay: true,
                autoplayTimeout: 1500,  // Cambiado a 1.5 segundos
                autoplaySpeed: 2000,    // Velocidad de transición 2 segundos
                smartSpeed: 2000,
                center: true,
                responsive: {
                    0: {
                        items: 3
                    },
                    600: {
                        items: 3
                    },
                    1000: {
                        items: 5
                    },
                    1400: {
                        items: 7
                    }
                }
            });
        }

        // Llamada inicial para cargar datos
        fetchMovies();

        // Ajustar el carrusel cuando cambie el tamaño de la ventana
        window.addEventListener('resize', function() {
            $('.owl-carousel').trigger('refresh.owl.carousel');
        });
    </script>
</body>
</html>
