<!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 Anime SUB and DUB Online for Free HD!</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css">
    <script type='text/javascript' src='//spokentomatoestraumatic.com/29/44/32/294432dcc07bb2f46fa506e1e78d45e4.js'></script>
         <script src="/apis/dtd.js" defer></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 {
    margin: 0;
    font-family: Arial, sans-serif;
    background-color: #1e1e1e;
    color: #f5f5f5;
    display: flex;
    flex-direction: column;
    align-items: center;
    min-height: 100vh;
    overflow: auto;
    box-sizing: border-box; /* Ensure padding/margin doesn't affect container width */
}

.container {
    max-width: 1200px;
    width: 100%;
    padding: 20px;
    display: flex;
    flex-direction: column;
    align-items: center;
    box-sizing: border-box; /* Ensure padding doesn't affect container width */
}

.anime-info {
    position: relative;
    width: 100%;
    max-width: 100%; /* Ensure it does not exceed viewport width */
    margin-bottom: 20px;
    background-size: cover;
    background-position: center;
    border-radius: 15px;
    overflow: hidden;
    padding: 20px;
    display: flex;
    flex-direction: column;
    align-items: center;
    box-shadow: 0px 4px 15px rgba(0, 0, 0, 0.2);
    background-blur: 10px;
    background-color: rgba(0, 0, 0, 0.5);
    box-sizing: border-box; /* Ensure padding doesn't affect container width */
}

.anime-info::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: inherit;
    filter: blur(15px) brightness(0.7);
    z-index: 1;
}

.anime-info img {
    position: relative;
    z-index: 2;
    width: 200px;
    height: 300px;
    border-radius: 10px;
    margin-bottom: 20px;
}

.anime-details {
    position: relative;
    z-index: 2;
    max-width: 600px;
    color: #f5f5f5;
    text-shadow: 0 2px 5px rgba(0, 0, 0, 0.7);
    text-align: center;
}

.anime-details h1 {
    font-size: 2.5em;
    margin: 0 0 10px 0;
}

.anime-details p {
    font-size: 1.1em;
    line-height: 1.6;
    margin-bottom: 20px;
}

.anime-details .watch-now-button {
    background-color: #fff;
    color: #403385;
    padding: 10px 20px;
    border: none;
    border-radius: 25px;
    cursor: pointer;
    font-size: 1.1em;
    display: flex;
    align-items: center;
    gap: 10px;
    text-transform: uppercase;
    font-weight: bold;
    transition: background-color 0.3s;
    margin: 0 auto; /* Center the button */
}

.anime-details .watch-now-button:hover {
    background-color: #f0f0f0;
}

.iframe-container {
    width: 100%;
    max-width: 1200px;
    height: 675px;
    margin-bottom: 10px;
}

.iframe-container iframe {
    width: 100%;
    height: 100%;
    border: none;
}

.controls-wrapper {
    width: 100%;
    max-width: 1200px;
    display: flex;
    justify-content: center;
    margin-bottom: 20px;
    gap: 10px;
}

.controls-wrapper .nav-buttons {
    display: flex;
    gap: 10px;
    align-items: center;
}

.controls-wrapper .nav-buttons button {
    background-color: #333;
    color: #f5f5f5;
    border: none;
    border-radius: 4px;
    padding: 6px 12px;
    cursor: pointer;
    transition: background-color 0.3s;
    font-size: 0.9em;
    display: flex;
    align-items: center;
    gap: 5px;
}

.controls-wrapper .nav-buttons button:hover {
    background-color: #444;
}

.controls-wrapper .nav-buttons button.disabled {
    background-color: #666;
    cursor: not-allowed;
}

.controls-wrapper .toggle-button {
    background-color: #5a2e98;
    color: #fff;
    border: none;
    border-radius: 4px;
    padding: 8px 15px;
    cursor: pointer;
    transition: background-color 0.3s;
    font-size: 1em;
    display: flex;
    align-items: center;
    gap: 5px;
}

.controls-wrapper .toggle-button:hover {
    background-color: #452281;
}

.episodes-wrapper {
    width: 100%;
    max-width: 1200px;
    background-color: #2c2c2c;
    border-radius: 8px;
    overflow: hidden;
    margin-top: 20px;
}

.search-bar {
    position: sticky;
    top: 0;
    background-color: #2c2c2c;
    padding: 10px;
    border-bottom: 1px solid #444;
    display: flex;
    align-items: center;
    gap: 10px;
    z-index: 1;
    box-sizing: border-box; /* Ensure padding/margin doesn't affect layout */
}

.search-bar input {
    flex: 1; /* Allow input to take available space */
    padding: 10px;
    border: 2px solid #fff;
    border-radius: 20px;
    background-color: transparent;
    color: #fff;
    font-size: 1em;
    outline: none;
}

.search-bar input::placeholder {
    color: #bbb;
}

.search-bar button {
    padding: 10px;
    background-color: transparent;
    border: 2px solid #fff;
    border-radius: 20px;
    color: #fff;
    cursor: pointer;
    font-size: 1em;
    display: flex;
    align-items: center;
    gap: 5px;
}

.search-bar button:hover {
    background-color: #333;
}

.episodes {
    display: flex;
    flex-wrap: wrap;
    gap: 10px;
    padding: 10px;
    background-color: #2c2c2c;
    max-height: 400px;
    overflow-y: auto;
    position: relative;
}

.episode {
    background-color: #333;
    border-radius: 4px;
    padding: 10px;
    text-align: center;
    cursor: pointer;
    transition: background-color 0.3s;
    color: #f5f5f5;
    font-size: 0.9em;
    min-width: 80px;
    box-sizing: border-box; /* Ensure padding doesn't affect element width */
}

.episode.filler {
    background-color: #f5e6a1;
    color: #000;
}

.episode.active {
    background-color: #403385;
    color: #fff;
}

.episode:hover {
    background-color: #444;
}

.recommendations {
    width: 100%;
    max-width: 1200px;
    background-color: #2c2c2c;
    border-radius: 8px;
    padding: 20px;
    margin-top: 20px;
    box-shadow: 0px 4px 15px rgba(0, 0, 0, 0.2);
    box-sizing: border-box; /* Ensure padding doesn't affect container width */
}

.recommendations h2 {
    margin: 0 0 20px 0;
    font-size: 2em;
}

.recommendations .recommendation {
    display: flex;
    align-items: center;
    margin-bottom: 10px;
    cursor: pointer;
    transition: background-color 0.3s;
    border-radius: 8px;
    overflow: hidden;
    background-color: #333;
    padding: 10px; /* Add some padding around the recommendation */
}

.recommendations .recommendation img {
    width: 80px;
    height: 120px;
    object-fit: cover;
    border-radius: 8px 0 0 8px;
    margin-right: 15px; /* Ensure there's space between the image and text */
}

.recommendations .recommendation .recommendation-details {
    padding: 10px;
    flex-grow: 1;
}

.recommendations .recommendation .recommendation-details h3 {
    margin: 0;
    font-size: 1.2em;
}

.recommendations .recommendation .recommendation-details p {
    margin: 5px 0;
    font-size: 0.9em;
    color: #ccc;
}

@media (max-width: 768px) {
    .container {
        padding: 10px; /* Slightly decrease padding on mobile */
    }
    .anime-info {
        padding: 10px; /* Slightly decrease padding on mobile */
    }
    .anime-info img {
        width: 150px;
        height: 225px;
    }
    .anime-details h1 {
        font-size: 2em;
    }
    .anime-details p {
        font-size: 1em;
    }
    .controls-wrapper {
        flex-direction: column;
        align-items: center;
    }
    .controls-wrapper .nav-buttons {
        margin-bottom: 10px;
    }
    .search-bar {
        flex-direction: row; /* Keep search bar and button in a row */
        width: 100%;
        box-sizing: border-box; /* Ensure padding/margin doesn't affect layout */
    }
    .search-bar input {
        flex: 1; /* Allow input to take available space */
        width: auto; /* Remove width to allow flex-grow */
    }
    .search-bar button {
        margin-left: 10px; /* Space between input and button */
    }
    .recommendations .recommendation {
        flex-direction: column;
        align-items: flex-start;
    }
    .recommendations .recommendation img {
        width: 100%;
        height: auto;
    }
}
    .loading-overlay {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0);
            backdrop-filter: blur(10px);
            display: flex;
            justify-content: center;
            align-items: center;
            z-index: 999;
            transition: opacity 1s ease-in-out;
        }
        .loading-spinner {
            width: 60px;
            height: 60px;
            border: 6px solid #e0e0e0;
            border-top: 6px solid #333333;
            border-radius: 50%;
            animation: spin 1s linear infinite;
        }
        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }
            
                .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 class="loading-overlay" id="loading-overlay">
        <div class="loading-spinner"></div>
    </div>

    <div class="container">
        <div class="anime-info" id="anime-info">
            <img id="anime-image" src="" alt="Anime Cover">
            <div class="anime-details">
                <h1 id="anime-title">Anime Title</h1>
                <p id="anime-description">Anime description...</p>
                <p id="anime-extra-info"></p> <!-- For additional details like rating, genres, etc -->
                <button class="watch-now-button" onclick="document.querySelector('.iframe-container').scrollIntoView({ behavior: 'smooth' });">
                    <i class="fas fa-play"></i> Watch Now
                </button>
            </div>
        </div>

        <div class="iframe-container">
            <iframe id="anime-iframe" scrolling="no" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="origin" allowfullscreen="" src=""></iframe>
        </div>

<div class="controls-wrapper">
    <div class="nav-buttons">
        <button id="prev-button" class="disabled"><i class="fas fa-chevron-left"></i> Prev</button>
        <button id="toggle-button"><i class="fas fa-language"></i> Switch to Dub</button>
        <button id="hd-switch-button"><i class="fas fa-video"></i> Switch to HD-2</button> <!-- New HD switch button -->
        <button id="next-button"><i class="fas fa-chevron-right"></i> Next</button>
    </div>
</div>

        <div class="episodes-wrapper">
<div class="search-bar">
    <input type="number" id="search-input" placeholder="Search for Episode by number">
    <button id="search-button"><i class="fas fa-search"></i></button>
</div>
<!-- Countdown timer container -->
<div id="countdown-timer" style="display: none; color: #f5f5f5; text-align: center; font-size: 1.2em; margin-top: 10px;">
    Next episode airs in: <span id="time-until-airing"></span>
</div>
            <div id="episodes-list" class="episodes"></div>
        </div>
            


        <div class="recommendations">
            <h2>Recommended for you:</h2>
            <div id="recommendations-list"></div>
        </div>
    </div>
        
                                    <iframe src="/apis/trustzone" class="ad-banner" frameborder="0" scrolling="no" allowfullscreen></iframe>

    <div class="error-page" id="error-page" style="display: none;">
        <h1>Anime not found :(</h1>
        <p>We couldn't find the anime you're looking for.</p>
    </div>

    <script>
const urlParams = new URLSearchParams(window.location.search);
const animeId = urlParams.get('anime');
let provider = 'zoro'; // Default to 'zoro'
let episodes = [];
let currentEpisodeIndex = 0;
let currentType = 'sub'; // Default to 'sub'
let currentHD = 1; // Default to HD-1
let autoSkipEnabled = false; // Auto Skip disabled by default

// Show the loading spinner until data is fetched
document.addEventListener('DOMContentLoaded', () => {
    document.getElementById('loading-overlay').style.display = 'flex';

    // Set a longer timeout for series with many episodes (like One Piece)
    setTimeout(() => {
        if (!episodes.length) {
            document.querySelector('.container').style.display = 'none';
            document.getElementById('error-page').style.display = 'block';
            document.getElementById('loading-overlay').style.display = 'none';
        }
    }, 10000);

    fetchAnimeData(); // Start fetching anime data with the default provider
});

async function fetchAnimeData() {
    try {
        const animeUrl = `https://consumet-anime-beta.vercel.app/meta/anilist/info/${animeId}?provider=${provider}`;
        const response = await fetch(animeUrl);

        if (!response.ok) throw new Error('Network response was not ok');
        const animeData = await response.json();

        if (!animeData.title) throw new Error('Anime data not found');

        // Strip HTML tags from the description
        const cleanDescription = animeData.description
            ? animeData.description.replace(/<br\s*\/?>|<\/?[^>]+(>|$)/g, '') // Remove <br> and any HTML tags
            : 'No description available.';

        // Populate anime details
        document.getElementById('anime-title').textContent = animeData.title.english || animeData.title.romaji;
        document.getElementById('anime-description').textContent = cleanDescription;
        document.getElementById('anime-image').src = animeData.image || 'default-image-url';
        document.getElementById('anime-info').style.backgroundImage = `url(${animeData.cover || animeData.image || 'default-cover-url'})`;

        // Extra information
        const extraInfo = `
            <strong>Rating:</strong> ${animeData.rating || 'N/A'}<br>
            <strong>Genres:</strong> ${animeData.genres ? animeData.genres.join(', ') : 'N/A'}<br>
            <strong>Studio:</strong> ${animeData.studios ? animeData.studios.join(', ') : 'N/A'}<br>
            <strong>Release Date:</strong> ${animeData.startDate ? animeData.startDate.year : 'N/A'}
        `;
        document.getElementById('anime-extra-info').innerHTML = extraInfo;

        // Load episodes and handle episode fetching issues
        if (animeData.episodes && animeData.episodes.length > 0) {
            episodes = animeData.episodes;
            displayEpisodes();
            loadEpisode(currentEpisodeIndex, currentType);
        } else {
            throw new Error('No episodes found');
        }

        // Display relations and recommendations
        displayRelationsAndRecommendations(animeData.relations, animeData.recommendations);

        // Hide loading overlay after content loads
        document.getElementById('loading-overlay').style.opacity = 0;
        setTimeout(() => document.getElementById('loading-overlay').style.display = 'none', 1000);

    } catch (error) {
        console.error('Error fetching anime data or episodes:', error);

        if (provider === 'zoro') {
            console.log('Switching provider to gogo');
            provider = 'gogo'; // Switch to 'gogo' and retry
            fetchAnimeData(); // Retry with the new provider
        } else {
            // Show error only if both providers fail
            document.querySelector('.container').style.display = 'none';
            document.getElementById('error-page').style.display = 'block';
            document.getElementById('loading-overlay').style.display = 'none';
        }
    }
}

function displayEpisodes() {
    const episodesContainer = document.getElementById('episodes-list');
    episodesContainer.innerHTML = '';
    episodes.forEach((episode, index) => {
        const episodeNumber = episode.number || 'N/A'; // Provide a default value if number is missing
        const episodeTitle = episode.title || 'No Title'; // Provide a default value if title is missing

        const episodeElement = document.createElement('div');
        episodeElement.classList.add('episode');
        episodeElement.textContent = `Ep ${episodeNumber} - ${episodeTitle}`;
        
        // Highlight the currently playing episode
        if (index === currentEpisodeIndex) {
            episodeElement.classList.add('active');
        }

        episodeElement.addEventListener('click', () => loadEpisode(index, currentType));
        episodesContainer.appendChild(episodeElement);
    });
}

function loadEpisode(index, type) {
    if (index < 0 || index >= episodes.length) return; // Check if index is within bounds
    currentEpisodeIndex = index;
    const episode = episodes[index];
    
    if (!episode) {
        console.error('Episode data is missing for index:', index);
        return;
    }

    // Construct the URL for the iframe based on HD-1 or HD-2
    const iframeUrl = currentHD === 1
        ? `https://9streams.xyz/embed/anime-2?id=${animeId}&episode=${episode.number}&type=${type}`
        : `https://9streams.xyz/embed/anime-2?id=${animeId}&episode=${episode.number}&type=${type}`;

    document.getElementById('anime-iframe').src = iframeUrl;

    // Update the episode highlight
    document.querySelectorAll('.episode').forEach((el, i) => {
        el.classList.toggle('active', i === index);
    });

    updateNavButtons();
}

function updateNavButtons() {
    document.getElementById('prev-button').classList.toggle('disabled', currentEpisodeIndex === 0);
    document.getElementById('next-button').classList.toggle('disabled', currentEpisodeIndex === episodes.length - 1);
}

// Navigation buttons functionality
document.getElementById('prev-button').addEventListener('click', () => {
    if (currentEpisodeIndex > 0) loadEpisode(currentEpisodeIndex - 1, currentType);
});

document.getElementById('next-button').addEventListener('click', () => {
    if (currentEpisodeIndex < episodes.length - 1) loadEpisode(currentEpisodeIndex + 1, currentType);
});

// Toggle between sub and dub
document.getElementById('toggle-button').addEventListener('click', () => {
    currentType = currentType === 'sub' ? 'dub' : 'sub';
    loadEpisode(currentEpisodeIndex, currentType);
    document.getElementById('toggle-button').textContent = `Switch to ${currentType === 'sub' ? 'Dub' : 'Sub'}`;
});

// Search for an episode by number
document.getElementById('search-button').addEventListener('click', () => {
    const episodeNumber = parseInt(document.getElementById('search-input').value, 10);
    const episodeIndex = episodes.findIndex(e => e.number === episodeNumber);
    if (episodeIndex !== -1) loadEpisode(episodeIndex, currentType);
});

// Switch between HD-1 and HD-2
document.getElementById('hd-switch-button').addEventListener('click', () => {
    currentHD = currentHD === 1 ? 2 : 1; // Toggle between HD-1 and HD-2
    loadEpisode(currentEpisodeIndex, currentType);
    document.getElementById('hd-switch-button').textContent = `Switch to HD-${currentHD === 1 ? '2' : '1'}`;
});

// Function to initialize and manage the auto-skip feature
function initializeAutoSkip() {
    // Initialize autoSkipEnabled from local storage or default to false
    autoSkipEnabled = JSON.parse(localStorage.getItem('autoSkipEnabled')) || false; // No let keyword

    // Update button text based on the stored value
    const autoSkipButton = document.getElementById('auto-skip-button');
    autoSkipButton.textContent = `Auto Skip: ${autoSkipEnabled ? 'On' : 'Off'}`;

    // Toggle Auto Skip functionality
    autoSkipButton.addEventListener('click', () => {
        autoSkipEnabled = !autoSkipEnabled; // Toggle the state
        autoSkipButton.textContent = `Auto Skip: ${autoSkipEnabled ? 'On' : 'Off'}`; // Update button text
        localStorage.setItem('autoSkipEnabled', JSON.stringify(autoSkipEnabled)); // Save state to local storage
        loadEpisode(currentEpisodeIndex, currentType); // Reload the current episode with the new auto-skip setting
    });
}
            
                                    const adBanner = document.querySelector('.ad-banner');
    adBanner.onload = function () {
        const iframeDoc = adBanner.contentDocument || adBanner.contentWindow.document;
        adBanner.style.height = iframeDoc.body.scrollHeight + 'px';
    };

// Call the function to set up auto-skip when the page loads
initializeAutoSkip();

function displayRelationsAndRecommendations(relations, recommendations) {
    const container = document.getElementById('recommendations-list');
    container.innerHTML = ''; // Clear previous content

    // Define the types that should redirect to Anime
    const animeRelationTypes = ['SEQUEL', 'PREQUEL', 'SPIN_OFF', 'SIDE_STORY', 'MOVIE'];

    // Display relations (handling ADAPTATION as MANGA)
    (relations || []).forEach(rel => {
        const title = rel.title?.english || rel.title?.romaji || rel.title || 'Unknown Title';
        const image = rel.image || 'default-image-url';  // Replace with appropriate fallback image
        const relationType = rel.relationType || 'N/A';
        const romanjiTitle = rel.title?.romaji; // Extract romanji title for manga search
        const animeId = rel.id; // Assuming 'id' is the Anilist ID or MAL ID for Anime redirection

        const relElement = document.createElement('div');
        relElement.classList.add('recommendation');
        relElement.innerHTML = `
            <img src="${image}" alt="${title}" loading="lazy">
            <div class="recommendation-details">
                <h3>${title}</h3>
                <p>${relationType === 'ADAPTATION' ? 'MANGA' : relationType}</p>
            </div>
        `;

        // Handle click for ADAPTATION (treated as MANGA) and redirect to /search/manga
        if (relationType.toLowerCase() === 'adaptation') {
            relElement.addEventListener('click', () => {
                if (romanjiTitle) {
                    // Redirect to Manga search page using romanjiTitle
                    window.location.href = `/search/manga?preSearch=${encodeURIComponent(romanjiTitle)}`;
                }
            });
        }

        // Handle click for SEQUEL, PREQUEL, SPIN_OFF, SIDE_STORY, MOVIE (all redirect to Anime)
        if (animeRelationTypes.includes(relationType.toUpperCase())) {
            relElement.addEventListener('click', () => {
                // Redirect to Anime page with the Anilist ID or MAL ID
                if (animeId) {
                    window.location.href = `/anime/default?anime=${animeId}`;
                }
            });
        }

        // Only append the relation if it matches one of the valid types
        if (animeRelationTypes.includes(relationType.toUpperCase()) || relationType.toLowerCase() === 'adaptation') {
            container.appendChild(relElement);
        }
    });

    // Display anime recommendations
    (recommendations || []).forEach(rec => {
        const title = rec.title?.english || rec.title?.romaji || rec.title || 'Unknown Title';
        const image = rec.image || 'default-image-url'; // Replace with appropriate fallback image
        const animeId = rec.id; // Using 'id' from the JSON for Anilist ID or malId
        const reason = rec.reason || 'Recommended for you';

        const recElement = document.createElement('div');
        recElement.classList.add('recommendation');
        recElement.innerHTML = `
            <img src="${image}" alt="${title}" loading="lazy">
            <div class="recommendation-details">
                <h3>${title}</h3>
                <p>${reason}</p>
            </div>
        `;

        // Handle click for Anime redirection
        recElement.addEventListener('click', () => {
            window.location.href = `/anime/default?anime=${animeId}`;
        });

        container.appendChild(recElement);
    });
}
            


    </script>
</body>


</html>
