<!DOCTYPE html>
<html lang="pl">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Autoplaying Backdrops with Top Movies</title>
    <style>
        body {
            margin: 0;
            padding: 0;
            position: relative;
            height: 100vh;
            background-color: #222;
            display: flex;
            justify-content: center;
            align-items: center;
            overflow: hidden;
        }
        #backdrop {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            object-fit: cover;
        }
        .logo-container {
            position: absolute;
            bottom: 150px;
            right: 15px;
            z-index: 1;
            padding: 10px;
            background-color: rgba(0, 0, 0, 0.5);
            border-radius: 5px;
            color: #fff;
            display: flex;
            flex-direction: column;
            align-items: flex-start;
            border: 5px solid transparent; /* Base border for gradient */
            border-image: linear-gradient(45deg, rgba(0, 255, 0, 0.5), rgba(0, 150, 0, 0.5)); /* Gradient border */
            border-image-slice: 1; /* Apply the gradient to the border */
            transform: scale(0.6); /* Scale down the entire container to 60% of its original size */
            transform-origin: bottom right; /* Adjust scaling origin to keep container within the viewport */
        }
        .logo {
            max-width: 150px;
        }
        .movie-info {
            max-width: 420px; /* Restore original width */
            margin-top: 10px;
            font-size: 12px;
            box-shadow: 0 0 10px green; /* Change glow to green */
            padding: 10px;
            border-radius: 5px;
        }
        .movie-title {
            color: orange; /* Change title color to orange */
        }
        .actor-container {
            display: flex;
            flex-wrap: wrap;
            margin-top: 10px;
        }
        .actor {
            text-align: center;
            margin-right: 10px;
            font-size: 10px;
            box-shadow: 0 0 10px green; /* Change glow to green */
            padding: 10px;
            border-radius: 5px;
        }
        .actor img {
            border-radius: 4px;
            margin-bottom: 4px;
        }
    </style>
</head>
<body>
    <?php
    $jsonData = file_get_contents('tmdbkey.json');
    $data = json_decode($jsonData, true);
    if ($data !== null) {
        $tmdbkey = $data['tmdbkey'];
        $tmdblanguage = $data['tmdlng'];
    }
    ?>
    <img id="backdrop" alt="Movie Backdrop">
    <div class="logo-container">
        <img id="logo" class="logo" alt="Movie Logo">
        <div id="movie-info" class="movie-info"></div>
        <div id="actor-container" class="actor-container"></div>
    </div>

    <script>
        const apiKey = '<?php echo $tmdbkey; ?>'; // Pobierz klucz API z PHP
        const language =  "<?php echo $tmdblanguage; ?>";
        let currentIndex = 0;
        let movieIds = [];
        const numberOfActors = 3; // Maksymalna liczba aktorów do wyświetlenia

        async function fetchTopMovies() {
            try {
                const response = await fetch(`https://api.themoviedb.org/3/movie/popular?api_key=${apiKey}&language=en`);
                if (!response.ok) throw new Error('Failed to fetch top movies');
                const data = await response.json();
                movieIds = data.results.map(movie => movie.id);
                if (movieIds.length === 0) {
                    console.error('No top movies found.');
                    return;
                }
            } catch (error) {
                console.error('Error fetching top 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 backdrops');
                const data = await response.json();
                const backdropPath = data.backdrops.length ? data.backdrops[0].file_path : null;
                return backdropPath ? `https://image.tmdb.org/t/p/original${backdropPath}` : null;
            } catch (error) {
                console.error('Error fetching movie backdrop:', error);
                return null;
            }
        }

        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;
                let englishLogo = logos.find(logo => logo.iso_639_1 === {language});
                if (!englishLogo) {
                    englishLogo = logos.find(logo => logo.iso_639_1 === 'en'); // Fallback to English logo if Polish logo not available
                }
                return englishLogo ? `https://image.tmdb.org/t/p/w500${englishLogo.file_path}` : null;
            } catch (error) {
                console.error('Error fetching movie logo:', error);
                return null;
            }
        }

        async function fetchMovieInfo(movieId) {
            try {
                const response = await fetch(`https://api.themoviedb.org/3/movie/${movieId}?api_key=${apiKey}&language=${language}`);
                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);
                return null;
            }
        }

        async function fetchMovieCast(movieId) {
            try {
                const response = await fetch(`https://api.themoviedb.org/3/movie/${movieId}/credits?api_key=${apiKey}&language=en`);
                if (!response.ok) throw new Error('Failed to fetch movie cast');
                const data = await response.json();
                return data.cast.slice(0, numberOfActors).map(actor => ({
                    name: actor.name,
                    character: actor.character,
                    profilePath: actor.profile_path ? `https://image.tmdb.org/t/p/w185${actor.profile_path}` : null
                }));
            } catch (error) {
                console.error('Error fetching movie cast:', error);
                return [];
            }
        }

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

            const movieId = movieIds[currentIndex];

            try {
                const [backdropUrl, logoUrl, movieInfo, movieCast] = await Promise.all([
                    fetchMovieBackdrop(movieId),
                    fetchMovieLogo(movieId),
                    fetchMovieInfo(movieId),
                    fetchMovieCast(movieId)
                ]);

                const backdrop = document.getElementById('backdrop');
                if (backdropUrl) {
                    backdrop.src = backdropUrl;
                    backdrop.style.display = 'block';
                } else {
                    console.warn('No backdrop available for this movie.');
                    backdrop.style.display = 'none';
                }

                const logo = document.getElementById('logo');
                if (logoUrl) {
                    logo.src = logoUrl;
                    logo.style.display = 'block';
                } else {
                    console.warn('No logo available for this movie.');
                    logo.style.display = 'none';
                }

                const movieInfoElement = document.getElementById('movie-info');
                if (movieInfo) {
                    movieInfoElement.innerHTML = `
                        <strong class="movie-title">${movieInfo.title}</strong> (${movieInfo.releaseDate.substring(0, 4)})<br>
                        ${movieInfo.overview}
                    `;
                } else {
                    movieInfoElement.innerHTML = 'Brak informacji o tym filmie.';
                }

                const actorContainer = document.getElementById('actor-container');
                if (movieCast.length > 0) {
                    actorContainer.innerHTML = movieCast.map(actor => `
                        <div class="actor">
                            ${actor.profilePath ? `<img src="${actor.profilePath}" alt="${actor.name}" width="50">` : ''}
                            <div>${actor.name}</div>
                            <div>jako ${actor.character}</div>
                        </div>
                    `).join('');
                } else {
                    actorContainer.innerHTML = 'Brak informacji o obsadzie tego filmu.';
                }

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

        fetchTopMovies().then(() => {
            if (movieIds.length > 0) {
                setInterval(updateBackdropAndLogo, 8000); // Zmieniaj tło, logo i informacje o filmie co 8 sekund
                updateBackdropAndLogo(); // Początkowa aktualizacja
            } else {
                console.error('No movie IDs found to display.');
            }
        });
    </script>
</body>
</html>
