<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Autoplaying Logos with Movie Info</title>
    <style>
        body {
            margin: 0; /* Remove margens padrão do corpo */
            height: 100vh; /* Altura total da viewport */
            display: flex;
            justify-content: flex-end; /* Alinha conteúdo à direita */
            align-items: center; /* Centraliza verticalmente */
            background-color: #111; /* Cor de fundo escura */
            overflow: hidden; /* Esconde overflow para evitar scrollbars */
        }

        .backdrop-container, .poster, .movie-info {
            transition: opacity 1s ease-in-out; /* Transição suave */
            opacity: 0; /* Inicia invisível */
        }

        .visible {
            opacity: 1; /* Torna visível */
        }

        .backdrop-container {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            z-index: -1; /* Garante que o backdrop esteja atrás dos outros elementos */
        }

        .backdrop {
            width: 100%;
            height: 100%;
            object-fit: cover;
        }

        .movie-info-poster-container {
            position: relative; /* Relativo para conter o overlay */
            display: flex;
            justify-content: flex-end; /* Alinha à direita */
            align-items: center; /* Centraliza verticalmente */
            background-color: transparent; /* Fundo inicial transparente */
            width: auto;
            max-width: 80%; /* Largura máxima do container */
            right: 10%;
            box-sizing: border-box; /* Inclui padding no tamanho total */
            overflow: hidden; /* Esconde overflow para evitar scrollbars */
        }

        .overlay {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.5); /* Cor de fundo com opacidade */
            opacity: 0; /* Inicia invisível */
            transition: opacity 1s ease-in-out; /* Transição suave de opacidade */
            z-index: -1; /* Deve estar acima dos outros elementos */
        }

        .overlay.visible {
            opacity: 1; /* Torna visível */
        }

        .poster-container {
            border-radius: 5px;
            color: #fff;
            max-width: 300px;
            text-align: center;
        }

        .poster {
            height: 250px;
        }

        .logo {
            max-width: 200px;
            margin-bottom: 10px;
        }

        .movie-info {
            font-size: 18px;

            margin-top: 5px;
            color: white;
            max-width: 450px; /* Ajuste a largura conforme necessário */
            overflow: hidden;
            text-overflow: ellipsis;
            line-height: 1.2em; /* Ajuste a altura da linha para corresponder ao seu design */
            max-height: calc(0.88em * 7); /* Limita o elemento a 5 linhas */
            flex: 1; /* Expande para ocupar espaço disponível */
            margin-left: 20px; /* Espaçamento à esquerda */
        }
    </style>
</head>
<body>
    <div class="backdrop-container" id="backdrop-container">
        <img id="backdrop" class="backdrop">
    </div>
    <div class="movie-info-poster-container">
        <div class="overlay"></div> <!-- Overlay para aplicar o fade in/out no background-color -->
        <div class="movie-info" id="movie-info"></div>
        <div class="poster-container">
            <img id="poster" class="poster">
            <img id="logo" class="logo">
        </div>
        
    </div>
    <script>
        const apiKey = '6b8e3eaa1a03ebb45642e9531d8a76d2';
        let currentIndex = 0;
        let movieIds = [];

        async function fetchPopularEnglishMovieIds() {
            try {
                const response = await fetch(`https://api.themoviedb.org/3/discover/movie?api_key=${apiKey}&sort_by=popularity.desc&language=pt`);
                if (!response.ok) {
                    throw new Error('Failed to fetch popular English movies');
                }
                const data = await response.json();
                movieIds = data.results.map(movie => movie.id);
            } catch (error) {
                console.error('Error fetching popular English movies:', error);
            }
        }

        async function fetchMovieBackdrop(movieId) {
            try {
                const response = await fetch(`https://api.themoviedb.org/3/movie/${movieId}/images?api_key=${apiKey}`);
                if (!response.ok) {
                    throw new Error('Failed to fetch movie backdrop');
                }
                const data = await response.json();
                const backdropPath = data.backdrops[0].file_path; // Assumindo o primeiro backdrop do array
                return `https://image.tmdb.org/t/p/original${backdropPath}`;
            } catch (error) {
                console.error('Error fetching movie backdrop:', error);
            }
        }

        async function fetchMoviePoster(movieId) {
            try {
                const response = await fetch(`https://api.themoviedb.org/3/movie/${movieId}?api_key=${apiKey}&language=pt`);
                if (!response.ok) {
                    throw new Error('Failed to fetch movie poster');
                }
                const data = await response.json();
                return `https://image.tmdb.org/t/p/w300${data.poster_path}`;
            } catch (error) {
                console.error('Error fetching movie poster:', error);
            }
        }

        async function fetchMovieLogo(movieId) {
            try {
                const response = await fetch(`https://api.themoviedb.org/3/movie/${movieId}?api_key=${apiKey}&append_to_response=images`);
                if (!response.ok) {
                    throw new Error('Failed to fetch movie logo');
                }
                const data = await response.json();
                const logos = data.images.logos;
                const englishLogo = logos.find(logo => logo.iso_639_1 === 'pt');
                if (englishLogo) {
                    return `https://image.tmdb.org/t/p/w500${englishLogo.file_path}`;
                } else {
                    return null;
                }
            } catch (error) {
                console.error('Error fetching movie logo:', error);
            }
        }

        async function fetchMovieInfo(movieId) {
            try {
                const response = await fetch(`https://api.themoviedb.org/3/movie/${movieId}?api_key=${apiKey}&language=pt`);
                if (!response.ok) {
                    throw new Error('Failed to fetch movie info');
                }
                const data = await response.json();
                return {
                    title: data.title,
                    releaseDate: data.release_date,
                    overview: data.overview
                };
            } catch (error) {
                console.error('Error fetching movie info:', error);
            }
        }

        async function updateBackdropPosterLogoAndInfo() {
            if (movieIds.length === 0) {
                console.error('No movie IDs available.');
                return;
            }

            const movieId = movieIds[currentIndex];

            try {
                const backdropUrl = await fetchMovieBackdrop(movieId);
                const posterUrl = await fetchMoviePoster(movieId);
                const movieInfo = await fetchMovieInfo(movieId);
                const movieInfoElement = document.getElementById('movie-info');
                const backdropContainer = document.getElementById('backdrop-container');
                const backdrop = document.getElementById('backdrop');
                const poster = document.getElementById('poster');
                const logo = document.getElementById('logo');
                const overlay = document.querySelector('.overlay'); // Seleciona a div de overlay

                // Fade out all elements including overlay
                backdropContainer.classList.remove('visible');
                movieInfoElement.classList.remove('visible');
                poster.classList.remove('visible');
                logo.classList.remove('visible');
                overlay.classList.remove('visible'); // Remove a classe visível do overlay

                setTimeout(() => {
                    if (backdropUrl) {
                        backdrop.src = backdropUrl;
                    }

                    if (posterUrl) {
                        poster.src = posterUrl;
                    }

                    if (movieInfo) {
                        movieInfoElement.innerHTML = `
                            <strong>${movieInfo.title}</strong> (${movieInfo.releaseDate.substring(0, 4)})<br>
                            ${movieInfo.overview}
                        `;
                    }

                    // Fade in all elements including overlay
                    backdropContainer.classList.add('visible');
                    movieInfoElement.classList.add('visible');
                    poster.classList.add('visible');
                    logo.classList.add('visible');
                    overlay.classList.add('visible'); // Adiciona a classe visível do overlay

                }, 1000); // Match the transition duration

                currentIndex = (currentIndex + 1) % movieIds.length;
            } catch (error) {
                console.error('Error updating backdrop, poster, logo, and movie info:', error);
            }
        }

        fetchPopularEnglishMovieIds().then(() => {
            setInterval(updateBackdropPosterLogoAndInfo, 10000); // Change backdrop, poster, logo, and movie info every 10 seconds (adjust as needed)
            updateBackdropPosterLogoAndInfo(); // Initial update
        });
    </script>
</body>
</html>
