<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>9Streams.xyz - Watch TV Shows and more Online for Free in HD!</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.3.0/css/all.min.css">
                <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.3.0/css/all.min.css">
         <script src="/apis/dtd.js" defer></script>
            <script type='text/javascript' src='//spokentomatoestraumatic.com/29/44/32/294432dcc07bb2f46fa506e1e78d45e4.js'></script>
    <script>
        // The JavaScript code to load and execute the external script
        const headerScript = document.createElement("script");
        headerScript.src = "https://9streams.xyz/config/sidenav.js";
        headerScript.onload = function() {
            console.log("Header script has been loaded and executed.");
            // Add any additional logic here if needed
        };
        document.head.appendChild(headerScript);
    </script> 
        

    
  <link rel="icon" type="image/x-icon" href="https://9streams.xyz/9streams_logo.png">
    <style>
body {
    background-color: #161616;
    margin: 0;
    padding: 0;
    font-family: Arial, sans-serif;
}

#sideNav {
    width: 250px;
    height: 100%;
    background-color: rgba(34, 34, 34, 0.8);
    backdrop-filter: blur(10px);
    position: fixed;
    top: 0;
    left: -250px;
    transition: left 0.3s;
    overflow-x: hidden;
    padding-top: 20px;
    z-index: 3;
}

#sideNav.show {
    left: 0;
}

#sideNav img {
    width: 80%;
    margin: 0 auto;
    display: block;
}

#sideNav button {
    background-color: transparent;
    color: white;
    border: none;
    padding: 15px 25px;
    text-align: left;
    width: 100%;
    cursor: pointer;
    transition: 0.3s;
    display: flex;
    justify-content: flex-start;
    align-items: center;
}

#sideNav button i {
    margin-right: 10px;
    font-size: 20px;
}

#sideNav button:hover {
    background-color: #444;
}

#mainContent {
    padding: 20px;
    margin-left: 0;
}

        .movie-info-container {
            background-color: #333;
            color: white;
            padding: 20px;
            border-radius: 10px;
            margin-top: 20px;
            display: flex;
            flex-wrap: wrap;
        }

        .movie-info-details {
            flex: 1;
            padding-right: 20px;
        }

        .movie-info-poster {
            flex: 0 0 200px;
            margin-right: 20px;
        }

        .movie-poster {
            width: 100%;
            height: auto;
            border-radius: 10px;
        }

        .movie-info-title {
            font-size: 24px;
            font-weight: bold;
        }

        .movie-info-genre {
            font-size: 18px;
            color: white;
            margin-top: 10px;
            cursor: pointer;
        }

        .movie-info-genre:hover {
            color: #007bff;
        }

        .movie-info-description {
            font-size: 16px;
            margin-top: 20px;
        }

        .spacer {
            margin-bottom: 20px;
        }

        .movie-info-director {
            font-size: 18px;
            margin-top: 20px;
        }

        .movie-info-rating {
            font-size: 18px;
            margin-top: 10px;
        }

        .movie-info-buttons {
            margin-top: 20px;
        }

        .watch-button {
            background-color: #fff;
            color: #000;
            border: none;
            padding: 10px 20px;
            font-size: 18px;
            cursor: pointer;
            margin-right: 10px;
            display: inline-flex;
            align-items: center;
            border-radius: 5px;
            text-decoration: none;
        }

        .watch-button:hover {
            background-color: #f2f2f2;
        }

        .trailer-button {
            background-color: #888;
            color: #fff;
            border: none;
            padding: 10px 20px;
            font-size: 18px;
            cursor: pointer;
            display: inline-flex;
            align-items: center;
            border-radius: 5px;
            text-decoration: none;
        }

/* Server Embed */
.server-embed iframe {
    width: 100%;
    height: 500px;
    margin-bottom: 0;
}

.server-embed {
    margin-top: 20px;
}

/* Episode Title */
.episode-title {
    font-size: 24px;
    font-weight: bold;
    margin-top: 10px;
    margin-bottom: 10px;
    color: white;
    text-align: center;
}

/* Server Container */
#server-container {
    max-width: 800px;
    margin: 0 auto;
    padding: 20px;
    background-color: #1f1f1f;
    border-radius: 12px;
    box-shadow: 0 0 15px rgba(0, 0, 0, 0.5);
    color: #fff;
    text-align: center;
}

#server-container h2 {
    font-size: 24px;
    font-weight: bold;
    margin-bottom: 20px;
}

#server-container .choose-server-label {
    font-weight: bold;
    margin-bottom: 10px;
    color: #ddd;
    display: flex;
    align-items: center;
    justify-content: center;
}

#server-container .server-buttons {
    display: flex;
    flex-wrap: wrap;
    gap: 10px;
    justify-content: center;
    margin-bottom: 20px;
}

#server-container .server-button {
    padding: 12px 20px;
    font-size: 16px;
    color: #fff;
    background-color: #2b2b2b;
    border: 2px solid transparent;
    border-radius: 20px;
    box-shadow: 0 5px 10px rgba(0, 0, 0, 0.3);
    transition: all 0.3s ease;
    position: relative;
}

#server-container .server-button:before {
    content: '';
    position: absolute;
    top: -4px;
    left: -4px;
    right: -4px;
    bottom: -4px;
    border: 2px solid rgba(255, 255, 255, 0.2);
    border-radius: 24px;
    z-index: -1;
}

#server-container .server-button:hover {
    background-color: #6a1b9a;
    box-shadow: 0 8px 16px rgba(0, 0, 0, 0.3);
}

#server-container #superPlayerButton {
    background-color: #6a1b9a;
}

#server-container #superPlayerButton:before {
    border-color: rgba(255, 255, 255, 0.4);
}

#server-container #superPlayerButton:hover {
    background-color: #9c27b0;
}

/* Flags */
.flag-icon {
    width: 30px;
    height: auto;
    margin-right: 10px;
    border-radius: 4px;
    overflow: hidden;
}

/* Season Dropdown */
.season-dropdown {
    margin-top: 20px;
    margin-bottom: 20px;
    display: flex;
    justify-content: center;
}

.season-dropdown label {
    font-size: 18px;
    color: white;
    margin-right: 10px;
}

.season-dropdown select {
    background-color: #444;
    color: white;
    border: none;
    padding: 10px 20px;
    font-size: 16px;
    cursor: pointer;
    border-radius: 5px;
}

/* Episode List */
.episode-list {
    margin-top: 20px;
    list-style-type: none;
    padding: 0;
    display: flex;
    flex-wrap: wrap;
}

.episode-list-item {
    margin-right: 10px;
    margin-bottom: 10px;
    background-color: #444;
    color: white;
    border: none;
    padding: 10px 20px;
    font-size: 16px;
    cursor: pointer;
    border-radius: 5px;
    transition: background-color 0.3s;
}

.episode-list-item:hover {
    background-color: #007bff;
}
            
body {
  margin: 0;
}

.slider {
  width: 100%;
  overflow-x: auto;
  scroll-behavior: smooth;
  white-space: nowrap;
  padding-left: 20px;
  padding-right: 20px;
  box-sizing: border-box;
}

.movie-card {
  display: inline-block;
  margin-right: 10px;
  border-radius: 10px;
  width: 200px;
  height: 300px;
  overflow: hidden;
  text-align: center;
  background-color: #333;
}

.movie-card img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 10px;
}

.movie-title {
  display: none;
}

.recommendations {
  font-weight: bold;
  margin-left: 20px;
  color: white;
  margin-bottom: 10px;
}

/* Responsive adjustments */
@media (max-width: 768px) {
  .slider {
    padding-left: 10px;
    padding-right: 10px;
  }

  .movie-card {
    width: 150px;
    height: 225px;
  }
}

@media (max-width: 480px) {
  .slider {
    padding-left: 5px;
    padding-right: 5px;
  }

  .movie-card {
    width: 120px;
    height: 180px;
  }
}


::-webkit-scrollbar {
            width: 10px; /* Adjust the width */
        }

        /* Customize the thumb */
        ::-webkit-scrollbar-thumb {
            background: #525252; /* Change the thumb color */
            border-radius: 10px; /* Add rounded corners */
        }

        /* Customize the track */
        ::-webkit-scrollbar-track {
            background: #0d0d0d; /* Change the track color */
        }

    .ad-banner {
        width: 100%;
        height: 100px;
        max-width: 800px;
        border: none;
        box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
        border-radius: 25px;
        display: block;
        margin: 20px auto;
    }

    </style>
</head>
<body>

    <div id="mainContent">
        <div class="movie-info-container">
            <div class="movie-info-details">
                <div class="movie-info-title" id="movieTitle"></div>
                <div class="movie-info-genre" id="movieGenre"></div>
                <div class="movie-info-rating" id="movieDescription"></div>
                <div class="spacer"></div>
                <div class="movie-info-director" id="movieDirector"></div>
                <div class="movie-info-rating" id="movieRating"></div>
                <div class="movie-info-rating" id="movieAir"></div>
                <div class="movie-info-rating" id="movieStatus"></div>
                <div class="movie-info-buttons">
                    <a class="watch-button" href="?tv=12345#movieEmbed"><i class="fas fa-play"></i> Watch now</a>
                    <a class="trailer-button" id="trailerButton" href="#" target="_blank"><i class="fas fa-video"></i> Trailer</a>
                </div>
            </div>
            <div class="movie-info-poster">
                <img src="" alt="TV Show Poster" class="movie-poster" id="moviePoster">
            </div>
        </div>
        <div class="server-embed" id="serverEmbed">
            <iframe frameborder="0" allowfullscreen></iframe>
            <div id="episodeTitle" class="episode-title"></div>
        </div>
            
                    <div class="season-dropdown">
            <label for="seasonSelect">Select a season:</label>
            <select id="seasonSelect"></select>
        </div>
        <ul class="episode-list"></ul>
    </div>
        
        
        <div id="server-container">
            <h1>Select Server:</h1>

            <div>
                <label for="serverSelect" class="choose-server-label">
                    <img src="/flags/uk_flag.png" alt="UK Flag" class="flag-icon"> English Servers (Original):
                </label>
            </div>

            <div class="server-buttons">
                <button class="server-button" id="superPlayerButton" onclick="changeServer('1')">VidPlay - Fast, Low Ads</button>
                <button class="server-button" id="embedsuButton" onclick="changeServer('2')">Embedsu - Fast, Medium Ads</button>
                <button class="server-button" id="vipCloudButton" onclick="changeServer('3')">VidLink - Fast, Medium Ads</button>
                <button class="server-button" id="vidProButton" onclick="changeServer('4')">VidBinge (4K) - Fast, Medium Ads</button>
                <button class="server-button" id="primeWireButton" onclick="changeServer('5')">MultiServer - Medium, High Ads</button>
                <button class="server-button" id="2EmbedButton" onclick="changeServer('6')">MoviesAPI - Fast, High Ads</button>
            </div>

            <div>
                <label for="serverSelect" class="choose-server-label">
                    <img src="/flags/portugal_flag.jpg" alt="Portugal Flag" class="flag-icon"> Portugese/Português Servers:
                </label>
            </div>

            <div class="server-buttons">
                <button class="server-button" id="superFlixButton" onclick="changeServer('7')">SuperFlix - Fast, Medium Ads</button>
                <button class="server-button" id="embedderButton" onclick="changeServer('8')">Embedder - Fast, Medium Ads</button>
            </div>

            <div>
                <label for="serverSelect" class="choose-server-label">
                    <img src="/flags/india_flag.png" alt="India Flag" class="flag-icon"> Hindi/हिंदी Servers:
                </label>
            </div>

            <div class="server-buttons">
                <button class="server-button" id="hindiCloudButton" onclick="changeServer('9')">RGShows Hindi - Fast, AdFree</button>
            </div>

            <div>
                <label for="serverSelect" class="choose-server-label">
                    <img src="/flags/france_flag.png" alt="France Flag" class="flag-icon"> French/Français Servers:
                </label>
            </div>

            <div class="server-buttons">
                <button class="server-button" id="frenchCloudButton" onclick="changeServer('11')">Frembed - Fast, High Ads</button>
            </div>
                            </div>

<iframe src="/apis/trustzone" class="ad-banner" frameborder="0" scrolling="no" allowfullscreen></iframe>


        <div class="slider-container">
  <h2 class="recommendations">Recommendations:</h2>
  <div id="movieSlider" class="slider">
    <!-- Movie cards will be dynamically added here -->
  </div>
</div>

<script>
// Get the TMDB ID from the URL
const urlParams = new URLSearchParams(window.location.search);
const tmdbId = urlParams.get('tv');

// Function to get stored state for a specific show
function getStoredShowState(showId) {
    const storedState = localStorage.getItem(`show_${showId}_state`);
    return storedState ? JSON.parse(storedState) : null;
}

// Function to store state for a specific show
function storeShowState(showId, season, episode, server, episodeTitle) {
    localStorage.setItem(`show_${showId}_state`, JSON.stringify({
        season,
        episode,
        server,
        episodeTitle
    }));
}

// Initialize state based on stored state or defaults
let storedState = getStoredShowState(tmdbId);
let seasonNumber = storedState ? storedState.season : 1;
let episodeNumber = storedState ? storedState.episode : 1;
let currentServer = storedState ? storedState.server : '1';
let currentEpisodeTitle = storedState ? storedState.episodeTitle : '';

// Fetch TV show details from TMDB API
fetch(`https://9streams.xyz/apis/tmdb.php?path=tv/${tmdbId}`)
    .then(response => response.json())
    .then(data => {
        document.getElementById('moviePoster').src = `https://image.tmdb.org/t/p/w500${data.poster_path}`;
        document.getElementById('movieTitle').textContent = data.name || 'Title not available';
        document.getElementById('movieGenre').textContent = (data.genres?.map(genre => genre.name).join(', ')) || 'No genres available';
        document.getElementById('movieDescription').textContent = data.overview || 'No description available';
        document.getElementById('movieDirector').textContent = `Directed by: ${(data.created_by?.map(creator => creator.name).join(', ')) || 'N/A'}`;
        document.getElementById('movieRating').textContent = `Average Rating: ${data.vote_average} (${data.vote_count} Ratings)`;
        document.getElementById('movieStatus').textContent = `Current Status: ${data.status}`;
        document.getElementById('movieAir').textContent = `First Air Date: ${data.first_air_date}; Last Air Date: ${data.last_air_date}`;
        document.getElementById('trailerButton').href = `https://www.youtube.com/watch?v=${data.trailer_key}`;
    })
    .catch(error => console.error('Error fetching data:', error));

function highlightActiveServer() {
    const serverButtons = document.querySelectorAll('#server-container #superPlayerButton');
    serverButtons.forEach(button => {
        button.classList.remove('active-server');
        button.style.backgroundColor = '';
    });

    const activeServerButton = document.querySelector(`#server-container #superPlayerButton[data-server="${currentServer}"]`);
    if (activeServerButton) {
        activeServerButton.classList.add('active-server');
        activeServerButton.style.backgroundColor = '#007bff';
    }
}

function fetchSeasons() {
    return fetch(`https://9streams.xyz/apis/tmdb.php?path=tv/${tmdbId}`)
        .then(response => response.json())
        .then(data => {
            const seasons = data.seasons.filter(season => season.season_number !== 0);
            const seasonSelect = document.getElementById('seasonSelect');
            seasonSelect.innerHTML = ''; // Clear existing options
            
            seasons.forEach(season => {
                const option = document.createElement('option');
                option.value = season.season_number;
                option.textContent = `Season ${season.season_number}`;
                seasonSelect.appendChild(option);
            });

            // Set the stored season if it exists
            seasonSelect.value = seasonNumber;
            
            seasonSelect.addEventListener('change', () => {
                seasonNumber = parseInt(seasonSelect.value);
                fetchSeasonEpisodes(seasonNumber, true);
            });

            // Load initial season and episode
            fetchSeasonEpisodes(seasonNumber, false);
        })
        .catch(error => console.error('Error fetching seasons:', error));
}

function fetchSeasonEpisodes(seasonNum, resetEpisode = false) {
    const episodeList = document.querySelector('.episode-list');
    
    fetch(`https://9streams.xyz/apis/tmdb.php?path=tv/${tmdbId}/season/${seasonNum}`)
        .then(response => response.json())
        .then(data => {
            if (episodeList) {
                episodeList.innerHTML = '';
            }

            data.episodes.forEach(episode => {
                const listItem = document.createElement('li');
                listItem.className = 'episode-list-item';
                listItem.textContent = `Episode ${episode.episode_number} - ${episode.name}`;
                
                // Add active class if this is the current episode
                if (episode.episode_number === episodeNumber && seasonNum === seasonNumber) {
                    listItem.classList.add('active-episode');
                    // Update episode title if it's not set (first load)
                    if (!currentEpisodeTitle) {
                        currentEpisodeTitle = episode.name;
                        updateEpisodeTitle(episodeNumber, currentEpisodeTitle);
                    }
                }

                listItem.addEventListener('click', () => {
                    // Remove active class from all episodes
                    document.querySelectorAll('.episode-list-item').forEach(item => {
                        item.classList.remove('active-episode');
                    });
                    
                    // Add active class to clicked episode
                    listItem.classList.add('active-episode');
                    
                    episodeNumber = episode.episode_number;
                    currentEpisodeTitle = episode.name;
                    changeServer(currentServer, seasonNum, episodeNumber);
                    updateEpisodeTitle(episodeNumber, episode.name);
                    storeShowState(tmdbId, seasonNum, episodeNumber, currentServer, episode.name);
                });
                
                episodeList.appendChild(listItem);
            });

            // If this is the initial load (not changing seasons), load the stored episode
            if (!resetEpisode && storedState) {
                // Find and click the stored episode
                const storedEpisodeItem = Array.from(episodeList.children)
                    .find(item => item.textContent.startsWith(`Episode ${episodeNumber}`));
                if (storedEpisodeItem) {
                    changeServer(currentServer, seasonNumber, episodeNumber);
                    updateEpisodeTitle(episodeNumber, currentEpisodeTitle);
                }
            } else if (resetEpisode) {
                // If changing seasons, start from episode 1
                episodeNumber = 1;
                const firstEpisode = data.episodes[0];
                if (firstEpisode) {
                    currentEpisodeTitle = firstEpisode.name;
                    changeServer(currentServer, seasonNum, 1);
                    updateEpisodeTitle(1, firstEpisode.name);
                    storeShowState(tmdbId, seasonNum, 1, currentServer, firstEpisode.name);
                }
            }
        })
        .catch(error => console.error('Error fetching episodes:', error));
}

function updateEpisodeTitle(episodeNumber, episodeTitle) {
    const episodeTitleElement = document.getElementById('episodeTitle');
    if (episodeTitleElement) {
        episodeTitleElement.textContent = `Episode ${episodeNumber}: ${episodeTitle}`;
    }
}

function changeServer(server, season = seasonNumber, episode = episodeNumber) {
    currentServer = server;
    seasonNumber = season;
    episodeNumber = episode;
    
    storeShowState(tmdbId, season, episode, server, currentEpisodeTitle);
    highlightActiveServer();

    const serverEmbed = document.getElementById('serverEmbed')?.querySelector('iframe');
    let serverUrl;

    const newUrl = new URL(window.location.href);
    newUrl.searchParams.set('season', season);
    newUrl.searchParams.set('episode', episode);
    window.history.pushState({ path: newUrl.href }, '', newUrl.href);

    // Server URL mapping
    const serverUrls = {
        '1': `https://vidsrc.cc/v2/embed/tv/${tmdbId}/${season}/${episode}?autoPlay=true`,
        '2': `https://embed.su/embed/tv/${tmdbId}/${season}/${episode}`,
        '3': `https://vidlink.pro/tv/${tmdbId}/${season}/${episode}`,
        '4': `https://vidsrc.dev/embed/tv/${tmdbId}/${season}/${episode}`,
        '5': `https://www.primewire.tf/embed/tv?tmdb=${tmdbId}&season=${season}&episode=${episode}`,
        '6': `https://moviesapi.club/tv/${tmdbId}-${season}-${episode}`,
        '7': `https://superflixapi.dev/serie/${tmdbId}/${season}/${episode}`,
        '8': `https://embedder.net/e/${tmdbId}/${season}/${episode}`,
        '9': `https://rgshows.me/player/series/api1/index.html?id=${tmdbId}&s=${season}&e=${episode}`,
        '10': `https://frembed.lol/api/serie.php?id=${tmdbId}&sa=${season}&epi=${episode}`
    };

    serverUrl = serverUrls[server];
    if (serverUrl && serverEmbed) {
        serverEmbed.src = serverUrl;
    }
}

document.addEventListener('DOMContentLoaded', function() {
    const watchButton = document.querySelector('.watch-button');
    if (watchButton) {
        watchButton.addEventListener('click', function(event) {
            event.preventDefault();
            scrollToIframe();
        });
    }

    // Initialize with stored or default values
    const serverButtons = document.querySelectorAll('#server-container #superPlayerButton');
    serverButtons.forEach(button => {
        button.addEventListener('click', () => {
            const server = button.getAttribute('data-server');
            changeServer(server);
        });
    });

    // Initial setup
    highlightActiveServer();
    
    // If we have stored state, update the episode title immediately
    if (storedState && storedState.episodeTitle) {
        updateEpisodeTitle(storedState.episode, storedState.episodeTitle);
    }
    
    fetchSeasons();
});

// Recommendations slider
const movieSlider = document.getElementById("movieSlider");

fetch(`https://9streams.xyz/apis/tmdb.php?path=tv/${tmdbId}/recommendations`)
    .then(response => response.json())
    .then(data => {
        data.results.forEach(movie => {
            const movieCard = createMovieCard(movie);
            if (movieSlider) {
                movieSlider.appendChild(movieCard);
            }
        });
    })
    .catch(error => console.error("Error fetching movie recommendations:", error));

function createMovieCard(movie) {
    const movieCard = document.createElement("div");
    movieCard.classList.add("movie-card");

    const img = document.createElement("img");
    img.src = `https://image.tmdb.org/t/p/w200/${movie.poster_path}`;
    img.alt = movie.title;

    const title = document.createElement("div");
    title.classList.add("movie-title");
    title.textContent = movie.title;

    movieCard.appendChild(img);
    movieCard.appendChild(title);

    movieCard.addEventListener("click", function() {
        window.location.href = `/tv/default?tv=${movie.id}`;
    });

    return movieCard;
}

document.getElementById("movieSlider").addEventListener("wheel", function(event) {
    event.preventDefault();
    const delta = Math.sign(event.deltaY);
    const scrollAmount = 200;
    this.scrollBy({
        left: delta * scrollAmount,
        behavior: "smooth"
    });
});

function scrollToIframe() {
    const iframeSection = document.getElementById('serverEmbed');
    if (iframeSection) {
        iframeSection.scrollIntoView({ behavior: 'smooth' });
    }
}

const adBanner = document.querySelector('.ad-banner');
if (adBanner) {
    adBanner.onload = function() {
        const iframeDoc = adBanner.contentDocument || adBanner.contentWindow.document;
        adBanner.style.height = iframeDoc.body.scrollHeight + 'px';
    };
}
</script>

</body>
</html>