
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Full-Screen Movie Banner</title>
    <style>
        body {
            margin: 0;
            padding: 0;
            display: flex;
            justify-content: flex-start;
            align-items: center;
            height: 100vh;
            background-color: #222;
            backdrop-filter: blur(0px); 
            background-repeat: no-repeat;
            background-size: cover; 
            position: relative;
            overflow: hidden; 
            font-family: Arial, sans-serif;
        }
        #movie-container {
            opacity: 0; 
            transition: opacity 0.2s ease-in-out; 
            width: 100%;
            height: 100%;
        }
        .movie-banner {
            display: flex;
            flex-direction: column;
            justify-content: space-between; 
            align-items: flex-start; 
            color: #fff;
            padding-left: 0; 
            position: relative;
            z-index: 2; 
            height: 100%;
        }

        #movie-poster-container {
            position: relative;
            width: auto;
            max-height: 100%; 
        }

        #movie-poster {
            width: 100%;
            height: 100%; 
            -webkit-mask-image: -webkit-gradient(linear, right top, left top, from(rgba(0,0,0,0)), to(rgba(0,0,0,1))); 
        }

        .overlay {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            z-index: 1; 
        }

        /* * MUDANÇA (Card de Informações - Direita):
         * Tamanho fixo (150x70px) e posicionado a 0.3px do canto superior direito.
         */
        .info-box {
            position: fixed;
            right: 5px; /* POSIÇÃO: 0.3px da margem direita */
            top: 140px; /* POSIÇÃO: 7px da margem superior */
            transform: translateY(0);
            width: 165px; /* TAMANHO FIXO */
            height: 150px; /* TAMANHO FIXO */
            overflow: hidden; 
            background-color: rgba(20, 20, 20, 0.85);
            padding: 3px; /* Padding reduzido ao máximo */
            border-radius: 8px; 
            color: #fff;
            box-shadow: 0 1px 5px rgba(0,0,0,0.5); 
            z-index: 10;
        }

        .title-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 0px; 
            height: 15px; /* AJUSTADO PARA DAR ESPAÇO AO SUBTÍTULO */
        }

        #movie-title {
            font-size: 10px; /* Fonte minúscula para caber */
            color: #ff0;
            margin: 0;
            font-weight: bold;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
            padding-right: 2px;
        }

        #top-ten-badge {
            background-color: #f0b900;
            color: #111;
            width: 15px; /* Tamanho muito reduzido */
            height: 15px; 
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 8px; 
            font-weight: bold;
            flex-shrink: 0;
            margin-left: 3px;
        }

        /* --- MUDANÇA AQUI: Subtítulo Ativado e Estilizado --- */
        #msubtitial {
            display: block; /* MUDANÇA: Exibir o subtítulo */
            font-size: 8px; /* Fonte minúscula para caber */
            color: #aaa; /* Cor cinza claro para diferenciá-lo do título */
            margin: 1px 0 2px 0; /* Margem reduzida */
            padding: 0 0 0 0;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
        }
        /* --------------------------------------------------- */
        
        #movie-overview {
            font-size: 8px; /* Fonte minúscula para caber */
            color: #fff;
            line-height: 1.2;
            max-height: 40px; 
            overflow: hidden;
            text-overflow: ellipsis;
            display: -webkit-box;
            -webkit-line-clamp: 4; 
            -webkit-box-orient: vertical;
        }

        /* * MUDANÇA (Mini Capa - Esquerda):
         * Reposicionada a 0.3px da margem esquerda.
         */
        #mini-poster {
            position: fixed;
            left: 5px; /* POSIÇÃO: 0.3px da margem esquerda */
            top: 95px; /* POSIÇÃO: 7px da margem superior */
            transform: translateY(0);
            width: 150px; 
            height: auto; 
            border-radius: 8px;
            box-shadow: 0 1px 5px rgba(0,0,0,0.5);
            z-index: 10;
            border: 1px solid rgba(255, 255, 255, 0.2);
            display: none; 
        }

        /* Ocultar elementos que não estão na imagem de referência */
        #rating-rtx,
        #overview-title {
            display: none;
        }
        
    </style>
</head>
<body>
    <div class="movie-container" id="movie-container">
        <div class="overlay" id="viewport_capture">
            <div class="movie-banner">
                <div id="movie-poster-container"></div>
            </div> 
            
            <img id="mini-poster" />

            <div class="info-box">
                <div class="title-header">
                    <h1 id="movie-title"></h1>
                    <div id="top-ten-badge"></div>
                </div>
                <p id="msubtitial"></p>
                <h3 id="movie-overview"></h3>
            </div>
            
            <rating-bar class="ratingbar-location" id="rating-rtx"></rating-bar>
            <h1 id="overview-title" class="overview-location">Sinopse</h1>
        </div>
    </div>
    
    <script>
        const apiKey = 'b0145679685defe26249bc7abe8433d1';
        let currentIndex = 0;
        let currentPage = 1;
        let totalPageCount = 15;
        let movieIds = [];
        let nextImage = null;
        let nextPoster = null; 

        async function fetchPopularMovieIds() {
            while (currentPage <= totalPageCount) {
                try {
                    const response = await fetch(`https://api.themoviedb.org/3/discover/movie?api_key=${apiKey}&page=${currentPage}&sort_by=popularity.desc&language=pt-BR`);
                    const data = await response.json();
                    
                    if (data.results && data.results.length > 0) {
                        movieIds = [...movieIds, ...data.results.map(movie => movie.id)];
                        currentPage++;
                    } else {
                        break;
                    }
                } catch (error) {
                    console.error('Erro ao buscar IDs:', error);
                    break;
                }
            }
        }

        function preloadNextImage() {
            if (movieIds.length === 0) {
                console.error('Falha ao obter IDs dos filmes.');
                return;
            }

            const nextIndex = (currentIndex + 1) % movieIds.length;
            const nextMovieId = movieIds[nextIndex];

            fetch(`https://api.themoviedb.org/3/movie/${nextMovieId}?api_key=${apiKey}&language=pt-BR`)
                .then((response) => response.json())
                .then((data) => {
                    // Pré-carrega o background
                    if (data.backdrop_path) {
                        nextImage = new Image();
                        nextImage.src = `https://image.tmdb.org/t/p/original${data.backdrop_path}`;
                    }
                    // Pré-carrega o poster (mini capa)
                    if (data.poster_path) {
                        nextPoster = new Image();
                        nextPoster.src = `https://image.tmdb.org/t/p/w500${data.poster_path}`;
                    }
                })
                .catch((error) => console.error('Erro no pré-carregamento:', error));
        }

        async function updateMovieInfo() {
            if (movieIds.length === 0) {
                console.error('Nenhum ID de filme disponível.');
                return;
            }

            const movieId = movieIds[currentIndex];

            try {
                const response = await fetch(`https://api.themoviedb.org/3/movie/${movieId}?api_key=${apiKey}&language=pt-BR`);
                const data = await response.json();

                const movieContainer = document.getElementById('movie-container');
                movieContainer.style.opacity = 0;

                setTimeout(() => {
                    const movieTitle = document.getElementById('movie-title');
                    const mcategory = document.getElementById('msubtitial');
                    const movieOverview = document.getElementById('movie-overview');
                    const rtxratingbar = document.getElementById('rating-rtx');
                    const topTenBadge = document.getElementById('top-ten-badge');
                    
                    const miniPoster = document.getElementById('mini-poster');

                    // Atualizar background
                    if (data.backdrop_path) {
                        const posterPath = `https://image.tmdb.org/t/p/original${data.backdrop_path}`;
                        document.body.style.backgroundImage = `url('${posterPath}')`;
                    }

                    // Atualizar a mini capa
                    if (data.poster_path) {
                        const posterUrl = `https://image.tmdb.org/t/p/w500${data.poster_path}`;
                        miniPoster.src = posterUrl;
                        miniPoster.style.display = 'block'; 
                    } else {
                        miniPoster.style.display = 'none'; 
                    }

                    // Atualizar título
                    const releaseDate = data.release_date;
                    const releaseYear = new Date(releaseDate).getFullYear();
                    const maintital = data.title; 
                    
                    movieTitle.className = '';
                    movieTitle.innerText = maintital;

                    // Atualizar subtítulo
                    const fullSubtitial = `Filme (${releaseYear}) - Top 10 Filmes`;
                    mcategory.innerText = fullSubtitial;

                    // Atualizar o selo
                    topTenBadge.innerText = currentIndex + 1;

                    // Atualizar sinopse
                    movieOverview.innerText = data.overview;

                    movieContainer.style.opacity = 1;
                    currentIndex = (currentIndex + 1) % movieIds.length;
                    preloadNextImage();
                }, 200);
            } catch (error) {
                console.error('Erro ao atualizar informações:', error);
            }
        }

        // Inicializar
        fetchPopularMovieIds().then(() => {
            if (movieIds.length > 0) {
                preloadNextImage();
                setTimeout(updateMovieInfo, 2000);
                setInterval(updateMovieInfo, 9000);
            }
        });
    </script>
    
    <script>  
        customElements.define("rating-bar", class RatingBar extends HTMLElement {   
            constructor() {
                super();      
                this.attachShadow({ mode: "open" });
            }
            
            static get observedAttributes() {
                return ["value"];
            }
         
            attributeChangedCallback(name, old, current) {
                this[name] = Number(current ?? 1);
                this.render();
            }
        
            showStars(selector) {
                const stars = [];
                
                const wholeStars = Math.floor(this.value);
                const fractionalStar = this.value - wholeStars;
            
                for (let i = 0; i < this.maxValue; i++) {
                    const star = document.createElement("span");
                    star.textContent = "⭐";
                    star.addEventListener("click", () => this.select(i));
                    if (i < wholeStars) {
                        star.classList.add("full");
                    } else if (i === wholeStars) {
                        star.classList.add("partial");
                        star.style.width = `${fractionalStar * 100}%`;
                    } else {
                        star.classList.add("off");
                    }
                    stars.push(star);
                }
        
                const parent = this.shadowRoot.querySelector(selector);
                stars.forEach(star => parent.appendChild(star));
                const text = document.createElement("span");
                
                if (this.value === Math.floor(this.value)) {
                    text.textContent = `(${this.value})`;
                } else {
                    text.textContent = `(${this.value.toFixed(1)})`;
                }
                
                parent.appendChild(text);
            }

            select(num) {
                console.log("Select ", num);
                this.value = num;
                this.render();
            }
        
            connectedCallback() {
                this.maxValue = Number(this.getAttribute("max-value") ?? 10);      
                this.value = Number(this.getAttribute("value") ?? 0);
                this.render();
            }
            
            render() {
                this.shadowRoot.innerHTML = `
                    <style>
                        span { 
                            font-size: 15px; 
                            color: white;
                        }
                        .off { filter: grayscale(1); }
                        span:hover {
                            filter: hue-rotate(160deg);
                            cursor: pointer;
                        }
                    </style>
                    <div class="rating"></div>
                `;
                this.showStars(".rating");
            }
        });
    </script>
</body>
</html>
