<?php
// Configuración de la API de TMDB
$api_key = '6b8e3eaa1a03ebb45642e9531d8a76d2';
$base_url = 'https://api.themoviedb.org/3';
$language = 'es-MX';

// Obtener películas populares
$movie_url = $base_url . '/movie/popular?api_key=' . $api_key . '&language=' . $language;
$movie_response = file_get_contents($movie_url);
if ($movie_response === FALSE) {
    die('Error al conectar con la API de TMDB.');
}
$movies = json_decode($movie_response, true)['results'];

?>
<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Anuncios Dinámicos TMDB</title>
    <style>
        body {
            margin: 0;
            padding: 0;
            font-family: Arial, sans-serif;
            background-color: #000;
            color: white;
            text-align: center;
            height: 100vh;
            display: flex;
            justify-content: center;
            align-items: center; /* Cambiado de flex-end a center */
            position: relative;
        }
        .background {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-size: cover;
            background-position: center;
            z-index: -1;
            filter: brightness(0.5);
            transition: all 1.5s cubic-bezier(0.4, 0.0, 0.2, 1);
        }
        .container {
            position: relative;
            width: min(360px, 90vw); /* Adaptativo al ancho de la ventana */
            height: auto;
            min-height: 132px; /* Era 120px, ahora es 120px * 1.1 = 132px */
            max-height: min(198px, 80vh); /* Era 180px, ahora es 180px * 1.1 = 198px */
            background: radial-gradient(circle at 50% 50%, rgba(0, 0, 0, 0.7), rgba(166, 104, 103, 0.2));
            padding: clamp(8px, 2vw, 15px); /* Padding adaptativo */
            border-radius: clamp(8px, 2vw, 15px); /* Border radius adaptativo */
            box-shadow: 0px 4px 10px rgba(0, 0, 0, 0.5);
            overflow: hidden;
            color: #fff;
            text-align: center;
            box-sizing: border-box;
            display: flex;
            flex-direction: column;
            opacity: 1;
            transform: translateY(0);
            transition: all 0.8s cubic-bezier(0.4, 0.0, 0.2, 1);
        }
        
        .container.fade-out {
            opacity: 0;
            transform: translateY(20px);
        }
        
        /* Media queries para diferentes tamaños de pantalla */
        @media screen and (max-width: 480px) {
            .container {
                width: 95vw;
                max-height: 77vh; /* Ajustado proporcionalmente */
                padding: 8px;
                border-radius: 8px;
            }
        }
        
        @media screen and (max-height: 300px) {
            .container {
                max-height: 90vh;
                min-height: 88px; /* Era 80px, ahora 80px * 1.1 = 88px */
                padding: 5px;
            }
        }
        
        @media screen and (max-width: 300px) {
            .container {
                width: 98vw;
                max-height: 66vh; /* Era 60vh, ahora aproximadamente 66vh */
                padding: 5px;
                border-radius: 5px;
            }
        }
        #title-container {
            margin-bottom: clamp(4px, 1vh, 8px);
        }
        .logo {
            max-width: 80%;
            height: auto;
            max-height: clamp(30px, 8vh, 60px); /* Altura máxima adaptativa */
            margin: 0 auto clamp(0.1em, 1vh, 0.25em);
            transform: scale(clamp(0.6, 1.5vw, 0.85)); /* Escala adaptativa */
            transform-origin: center top;
            transition: opacity 0.6s ease-in-out, transform 0.6s ease-in-out;
        }
        .title-text {
            font-size: clamp(0.9em, 3vw, 1.2em); /* Tamaño de fuente adaptativo */
            font-weight: bold;
            margin-bottom: clamp(0.2em, 1vh, 0.5em);
            text-align: center;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
            transition: opacity 0.6s ease-in-out, transform 0.6s ease-in-out;
            line-height: 1.2;
        }
        .rating {
            margin: clamp(3px, 1vh, 8px) 0;
            transition: opacity 0.5s ease-in-out 0.1s;
            font-size: clamp(0.8em, 2.5vw, 1em);
        }
        .rating span {
            font-size: 1.1em;
            color: gold;
        }
        .overview {
            font-size: clamp(0.7em, 2vw, 0.9em); /* Tamaño de fuente adaptativo */
            margin-bottom: clamp(3px, 1vh, 8px);
            overflow: hidden;
            text-overflow: ellipsis;
            display: -webkit-box;
            -webkit-line-clamp: clamp(1, 1 + 1vh, 3); /* Líneas adaptativas */
            -webkit-box-orient: vertical;
            flex-grow: 1;
            transition: opacity 0.5s ease-in-out 0.2s;
            line-height: 1.3;
        }
        .platform-badge {
            display: inline-block;
            padding: clamp(0.1em, 1vw, 0.2em) clamp(0.3em, 2vw, 0.5em); /* Padding adaptativo */
            margin-top: clamp(0.2em, 1vh, 0.5em);
            border-radius: clamp(0.2em, 1vw, 0.3em);
            font-size: clamp(0.6em, 1.8vw, 0.8em); /* Tamaño de fuente adaptativo */
            font-weight: bold;
            text-transform: uppercase;
            transition: all 0.4s ease-in-out 0.3s;
        }
        .cinema {
            background: linear-gradient(135deg, #FFD700, #FFA500);
            color: black;
        }
        .netflix {
            background-color: #E50914;
            color: white;
        }
        .amazon {
            background-color: #00A8E1;
            color: white;
        }
        .apple {
            background-color: #000000;
            color: white;
        }
        .release-date {
            font-size: clamp(0.6em, 1.5vw, 0.8em); /* Tamaño de fuente adaptativo */
            margin-top: clamp(0.15em, 1vh, 0.3em);
            color: #ccc;
            transition: opacity 0.4s ease-in-out 0.4s;
            line-height: 1.2;
        }
        
        .fade-in-element {
            opacity: 0;
            transform: translateY(10px);
        }
        
        .fade-in-element.active {
            opacity: 1;
            transform: translateY(0);
        }
        
        /* Estilos adicionales para pantallas muy pequeñas */
        @media screen and (max-width: 250px) {
            .title-text {
                font-size: 0.8em;
                white-space: normal;
                line-height: 1.1;
                -webkit-line-clamp: 2;
                display: -webkit-box;
                -webkit-box-orient: vertical;
            }
            
            .overview {
                -webkit-line-clamp: 1;
            }
            
            .platform-badge {
                font-size: 0.5em;
                padding: 0.1em 0.2em;
            }
        }
        
        /* Estilos para pantallas muy bajas */
        @media screen and (max-height: 200px) {
            .container {
                min-height: 66px; /* Era 60px, ahora 60px * 1.1 = 66px */
                padding: 3px;
            }
            
            .overview {
                -webkit-line-clamp: 1;
                font-size: 0.6em;
            }
            
            .title-text {
                font-size: 0.8em;
                margin-bottom: 0.2em;
            }
            
            .rating {
                font-size: 0.7em;
                margin: 2px 0;
            }
            
            .platform-badge {
                font-size: 0.5em;
                margin-top: 0.2em;
            }
            
            .release-date {
                font-size: 0.5em;
                margin-top: 0.1em;
            }
        }
    </style>
</head>
<body>
    <div id="backdrop" class="background"></div>
    <div class="container">
        <div id="title-container">
            <img id="logo" class="logo" src="" alt="Logo" style="display: none;">
            <div id="title-text" class="title-text">Cargando...</div>
        </div>
        <div id="rating" class="rating"></div>
        <div id="overview" class="overview">Por favor, espera mientras cargamos el anuncio.</div>
        <div id="platform-info"></div>
        <div id="release-date" class="release-date"></div>
    </div>

    <script>
        const movies = <?php echo json_encode($movies); ?>;
        const apiKey = "<?php echo $api_key; ?>";
        const baseUrl = "https://api.themoviedb.org/3";
        let currentIndex = 0;
        
        // Función para ajustar el contenido según el tamaño de la pantalla
        function adjustContentForScreenSize() {
            const container = document.querySelector('.container');
            const overview = document.getElementById('overview');
            const titleText = document.getElementById('title-text');
            const viewport = {
                width: window.innerWidth,
                height: window.innerHeight
            };
            
            // Ajustar número de líneas del overview según el espacio disponible
            if (viewport.height < 200) {
                overview.style.webkitLineClamp = '1';
            } else if (viewport.height < 300) {
                overview.style.webkitLineClamp = '2';
            } else {
                overview.style.webkitLineClamp = '3';
            }
            
            // Ajustar el título para pantallas muy pequeñas
            if (viewport.width < 250) {
                titleText.style.whiteSpace = 'normal';
                titleText.style.webkitLineClamp = '2';
                titleText.style.display = '-webkit-box';
                titleText.style.webkitBoxOrient = 'vertical';
            } else {
                titleText.style.whiteSpace = 'nowrap';
                titleText.style.display = 'block';
                titleText.style.webkitLineClamp = 'unset';
            }
        }
        
        // Escuchar cambios de tamaño de ventana
        window.addEventListener('resize', adjustContentForScreenSize);
        window.addEventListener('orientationchange', adjustContentForScreenSize);
        
        // IDs de proveedores en TMDB
        const NETFLIX_ID = 8;
        const AMAZON_ID = 9;
        const APPLE_TV_ID = 350;
        const CINEMA = 'cinema'; // Valor especial para películas en cines

        async function fetchMediaLogo(movieId) {
            try {
                const response = await fetch(${baseUrl}/movie/${movieId}?api_key=${apiKey}&append_to_response=images&language=es-MX);
                if (!response.ok) {
                    throw new Error('Failed to fetch movie details');
                }
                const data = await response.json();

                // Try to find the logo in Spanish first
                let logoPath = data.images?.logos ? data.images.logos.find(logo => logo.iso_639_1 === 'es')?.file_path : null;

                // If not found, try to find the logo in English
                if (!logoPath) {
                    logoPath = data.images?.logos ? data.images.logos.find(logo => logo.iso_639_1 === 'en')?.file_path : null;
                }

                // If a logo was found, return its path
                if (logoPath) {
                    return https://image.tmdb.org/t/p/w500${logoPath};
                }

                // If no logo was found, return null
                return null;
            } catch (error) {
                console.error('Error fetching media logo:', error);
                return null;
            }
        }

        async function fetchWatchProviders(movieId) {
            try {
                const response = await fetch(${baseUrl}/movie/${movieId}/watch/providers?api_key=${apiKey});
                if (!response.ok) {
                    throw new Error('Failed to fetch watch providers');
                }
                const data = await response.json();
                
                // Intentar obtener proveedores para México primero
                let providers = data.results?.MX?.flatrate || [];
                
                // Si no hay proveedores para México, intentar con US
                if (providers.length === 0) {
                    providers = data.results?.US?.flatrate || [];
                }
                
                return providers;
            } catch (error) {
                console.error('Error fetching watch providers:', error);
                return [];
            }
        }

        function getProviderName(providerId) {
            switch(providerId) {
                case NETFLIX_ID:
                    return 'netflix';
                case AMAZON_ID:
                    return 'amazon';
                case APPLE_TV_ID:
                    return 'apple';
                case CINEMA:
                    return 'cinema';
                default:
                    return 'cinema'; // Por defecto, asumimos que está en cines
            }
        }

        function getProviderLabel(providerId) {
            switch(providerId) {
                case NETFLIX_ID:
                    return 'Netflix';
                case AMAZON_ID:
                    return 'Amazon Prime';
                case APPLE_TV_ID:
                    return 'Apple TV+';
                case CINEMA:
                    return 'Cines';
                default:
                    return 'Cines'; // Por defecto, asumimos que está en cines
            }
        }

        function formatDate(dateString) {
            if (!dateString) return 'Fecha desconocida';
            
            const options = { year: 'numeric', month: 'long', day: 'numeric' };
            return new Date(dateString).toLocaleDateString('es-MX', options);
        }

        async function updateAd() {
            const movie = movies[currentIndex];
            const backdrop = document.getElementById('backdrop');
            const titleText = document.getElementById('title-text');
            const logoElement = document.getElementById('logo');
            const overview = document.getElementById('overview');
            const rating = document.getElementById('rating');
            const platformInfo = document.getElementById('platform-info');
            const releaseDate = document.getElementById('release-date');
            const container = document.querySelector('.container');

            // Iniciar transición de salida
            container.classList.add('fade-out');
            
            // Esperar a que termine la transición de salida
            await new Promise(resolve => setTimeout(resolve, 400));

            // Actualizar fondo con transición suave
            backdrop.style.backgroundImage = url('https://image.tmdb.org/t/p/original${movie.backdrop_path}');
            
            // Actualizar descripción
            overview.textContent = movie.overview;

            // Intentar obtener el logo de la película
            const logoUrl = await fetchMediaLogo(movie.id);
            
            // Manejar el título/logo
            if (logoUrl) {
                logoElement.src = logoUrl;
                logoElement.style.display = 'block';
                titleText.style.display = 'none';
            } else {
                logoElement.style.display = 'none';
                titleText.style.display = 'block';
                titleText.textContent = movie.title;
            }

            // Mostrar estrellas para el puntaje
            const starRating = Math.round(movie.vote_average / 2); // Escala de 5 estrellas
            rating.innerHTML = '★'.repeat(starRating) + '☆'.repeat(5 - starRating);

            // Obtener proveedores de streaming
            const providers = await fetchWatchProviders(movie.id);
            let providerId = CINEMA; // Por defecto, asumimos que está en cines
            
            // Si hay proveedores, tomamos el primero (generalmente el principal)
            if (providers.length > 0) {
                providerId = providers[0].provider_id;
            }
            
            // Mostrar plataforma
            const providerName = getProviderName(providerId);
            const providerLabel = getProviderLabel(providerId);
            platformInfo.innerHTML = <div class="platform-badge ${providerName}">${providerLabel}</div>;
            
            // Mostrar fecha de estreno
            const today = new Date();
            const releaseDay = new Date(movie.release_date);
            let releaseDateText = '';
            
            if (releaseDay > today) {
                releaseDateText = Próximo estreno: ${formatDate(movie.release_date)};
            } else {
                releaseDateText = Estrenado: ${formatDate(movie.release_date)};
            }
            
            releaseDate.textContent = releaseDateText;

            // Iniciar transición de entrada
            container.classList.remove('fade-out');
            
            // Animación en cascada de los elementos
            setTimeout(() => {
                rating.style.opacity = '1';
            }, 100);
            
            setTimeout(() => {
                overview.style.opacity = '1';
            }, 200);
            
            setTimeout(() => {
                platformInfo.style.opacity = '1';
            }, 300);
            
            setTimeout(() => {
                releaseDate.style.opacity = '1';
            }, 400);

            // Cambiar al siguiente anuncio
            currentIndex = (currentIndex + 1) % movies.length;
        }

        // Actualizar anuncio cada 8 segundos
        setInterval(updateAd, 8000);

        // Mostrar el primer anuncio de inmediato con animación inicial
        setTimeout(() => {
            adjustContentForScreenSize(); // Ajustar contenido al cargar
            updateAd();
        }, 500);
    </script>
</body>
</html>