<!DOCTYPE html>
<html lang="pt-br">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Bandeira de Filme em Tela Cheia</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; 
        }
        #movie-container {
            opacity: 0; 
            transition: opacity 0.2s ease-in-out; 
        }
        .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: flex;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: linear-gradient(to right, rgba(0, 0, 0, 1), transparent);
            z-index: 1; 
        }
        .logo-container {
            position: absolute;
            top: 37%; /* Ajuste a posição superior conforme necessário */
            right: 02%; /* Ajuste a posição esquerda conforme necessário */
            z-index: 1; /* Garante que o logo fique acima do fundo */
            background-color: rgba(0, 0, 0, 0.5); /* Cor de fundo com transparência */
            border-radius: 5px; /* Cantos arredondados */
            color: #fff; /* Cor do texto */
        }
    </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">
                    <!--<img id="movie-poster" src="" alt="Cartaz do Filme">-->
                </div>
            </div> 
        </div>
        
        <div class="logo-container">
            <h1 id="movie-title" class="movie-info"></h1>
            <h1 id="movie-idk" class="hiddin-info"></h1>
            <p id="msubtitial" class="subtitial-info"></p>
            <rating-bar class="ratingbar-location" id="rating-rtx"></rating-bar>
            <h1 id="overview-title" class="overview-location"></h1>
            <h3 id="movie-overview" class="movie-info-overview"></h3>
        </div>
    </div>

    <script>
        const apiKey = "6b8e3eaa1a03ebb45642e9531d8a76d2"; // Substitua pela sua chave da API TMDb
        let currentIndex = 0;
        let currentPage = 1; // Começar com a página 1
        let totalPageCount = 15;
        let movieIds = []; // Array para armazenar os IDs dos filmes
        let nextImage = null; // Variável para armazenar a próxima imagem

        // Função para buscar os IDs dos filmes populares desta semana da API TMDb
        async function fetchPopularMovieIds_old() {
            const currentDate = new Date();
            const lastWeekDate = new Date(currentDate.getTime() - 7 * 24 * 60 * 60 * 1000); // Calcular a data da semana passada
            const currentDateString = currentDate.toISOString().split('T')[0];
            const lastWeekDateString = lastWeekDate.toISOString().split('T')[0];

            try {
                const response = await fetch(`https://api.themoviedb.org/3/discover/movie?api_key=${apiKey}&primary_release_date.gte=${lastWeekDateString}&primary_release_date.lte=${currentDateString}&sort_by=popularity.desc`);
                const data = await response.json();
                movieIds = data.results.map(movie => movie.id);
            } catch (error) {
                console.error(error);
            }
        }

        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`);
                    const data = await response.json();
                    
                    // Adicionar os IDs dos filmes da página atual ao array
                    movieIds = [...movieIds, ...data.results.map(movie => movie.id)];
                    
                    currentPage++; // Passar para a próxima página
                } catch (error) {
                    console.error(error);
                    break; // Interromper o loop em caso de erro
                }
            }
        }

        // Função para pré-carregar a próxima imagem
        function preloadNextImage() {
            if (movieIds.length === 0) {
                console.error('Falha ao buscar os 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}`)
                .then((response) => response.json())
                .then((data) => {
                    // Pré-carregar a próxima imagem
                    nextImage = new Image();
                    nextImage.src = `https://image.tmdb.org/t/p/original${data.backdrop_path}`;
                })
                .catch((error) => console.error(error));
        }

        // Função para atualizar as informações do filme
        async function updateMovieInfo() {
            if (movieIds.length === 0) {
                console.error('Falha ao buscar os IDs dos filmes.');
                return;
            }

            const movieId = movieIds[currentIndex];

            fetch(`https://api.themoviedb.org/3/movie/${movieId}?api_key=${apiKey}`)
                .then((response) => response.json())
                .then((data) => {
                    const movieContainer = document.getElementById('movie-container');
                    const movieContainer2 = document.getElementById('viewport_capture');

                    movieContainer.style.opacity = 0;

                    setTimeout(() => {
                        preloadNextImage();

                        const moviePoster = document.getElementById('movie-poster');
                        const movieTitle = document.getElementById('movie-title');
                        const mcategory = document.getElementById('msubtitial');
                        const movieOverview = document.getElementById('movie-overview');
                        const rtxratingbar = document.getElementById('rating-rtx');

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

                        /**** Seção de título do filme ***/
                        const movieidbyrtx = data.id;
                        var movieidkms = document.getElementById("movie-idk");
                        movieidkms.innerText = movieidbyrtx;

                        var movieTitleh = document.getElementById("movie-title");
                        const releaseDate = data.release_date;
                        const releaseYear = new Date(releaseDate).getFullYear();
                        var maintital = data.title + ` (`+releaseYear+`)`;

                        movieTitleh.classList.add("movie-info");
                        movieTitle.innerText = maintital;
                        /**** Seção de título do filme ***/

                        // Atualizar subtítulo do filme
                        const releaseDate_full = data.release_date;
                        const genresArray = data.genres.map(genre => `🎬 ${genre.name}`).join(' ');
                        const origin_country = data.production_companies.map(production_companies => `${production_companies.origin_country}`).join(' ');
                        const duration = data.runtime;
                        const hours = Math.floor(duration / 60) + 'h';
                        const minutes = duration % 60 + 'm';
                        const fullSubtitial = ` 📀 ` + releaseDate_full + ` (${origin_country}) ` + ` | ` + genresArray + ` | ` + '🕝 ' + hours + ' ' + minutes;
                        mcategory.innerText = fullSubtitial;

                        const mrating = data.vote_average;
                        rtxratingbar.setAttribute("value", mrating);

                        movieContainer.style.opacity = 1;
                    }, 200);

                    currentIndex = (currentIndex + 1) % movieIds.length; // Incrementar o índice de forma cíclica

                    // Pré-carregar a próxima imagem após atualizar o filme atual
                    preloadNextImage();
                })
                .catch((error) => console.error(error));
        }

        // Chamar a função fetchPopularMovieIds inicialmente
        fetchPopularMovieIds().then(() => {
            // Pré-carregar a primeira imagem
            preloadNextImage();
            // Definir um tempo inicial para a primeira atualização
            setTimeout(updateMovieInfo, 2000);
            // Definir o intervalo para as atualizações subsequentes
            setInterval(updateMovieInfo, 9000);
        });
    </script>
    
    <style>
        .movie-info {
            position: fixed;
            right: 02%;
            text-shadow: 5px 5px 10px #000000;
            display: flex;
            color: white;
            font-size:3.2vw;
        }
        .subtitial-info{
            right: 02%;
            margin-top: 150px;
            position: fixed;
            text-shadow: 5px 5px 10px #000000;
            text-transform: uppercase;
            color: white;
            font-size: 1.2vw;
        }
                  
        .hiddin-info{
            right: 02%;
            margin-top: 150px;
            position: fixed;
            text-shadow: 5px 5px 10px #000000;
            text-transform: uppercase;
            color: #00000000;
            font-size: 0.0vw;
        }
        
        .ratingbar-location{
            right: 02%;
            position: fixed;
            text-shadow: 5px 5px 15px black;
            font-size: 0.5vw;
        }
        
        .movie-info-overview {
            text-align: left;
            position: fixed;
            top: 20.8vw;
            left: 01%;
            right: 25%;
            font-size: 0.1vm;
            color: white;;
        }
        .overview-location{
            top: 18.8vw;
            left: 01%;
            position: fixed;
            display: flex;
            align-items: center;
            justify-content: center;
            text-transform: uppercase;
            color: white;
            font-size: 1.4vw;
        }
    </style>
    <script>
        function getMovieIdkFromWebView() {
            var movieIdk = document.getElementById('movie-idk').innerText;
            AndroidInterface.getMovieIdkFromWebView(movieIdk);
        }
    </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 {
          // Estrela vazia para o restante
          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("Selecionado ", 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>

<script>  
// Obter os elementos
const movieTitle = document.getElementById('movie-title');
const subtitial = document.getElementById('msubtitial');
const rating = document.getElementById('rating-rtx');

// Função para atualizar a margem
function updateMargin() {
    const titleFontSize = parseFloat(window.getComputedStyle(movieTitle).fontSize);
    const newMarginTop = titleFontSize * 2.0; // Ajuste esse multiplicador conforme necessário
    const newMarginToprate = titleFontSize * 2.7; 
    subtitial.style.marginTop = `${newMarginTop}px`;
    rating.style.marginTop = `${newMarginToprate}px`;
}
function onPageLoad() {
    updateMargin();
}

updateMargin();

// Adicionar um ouvinte de evento para atualizar a margem quando a janela for redimensionada
window.addEventListener('resize', updateMargin);
window.addEventListener('load', onPageLoad);
</script>
</body>
</html>