<!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>
        // 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>
        

    <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 = 'gogo'; // Default to 'gogo'
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', () => {
    resetSettingsForNewAnime(); // Reset settings for new anime
    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
});

// Reset settings for new anime
function resetSettingsForNewAnime() {
    currentType = 'sub'; // Default to 'sub'
    currentHD = 1; // Default to HD-1
    autoSkipEnabled = false; // Auto Skip disabled by default
}

async function fetchAnimeData() {
    try {
        // Step 1: Fetch the hianime ID from the malsync API
        const malsyncUrl = `https://api.malsync.moe/mal/anime/anilist:${animeId}`;
        let malsyncResponse;
        let retryCount = 0;
        const maxRetries = 3;

        while (retryCount < maxRetries) {
            malsyncResponse = await fetch(malsyncUrl);

            if (malsyncResponse.status === 429) {
                // Rate limited, wait 2 seconds and retry
                await new Promise(resolve => setTimeout(resolve, 2000));
                retryCount++;
                continue;
            }

            if (!malsyncResponse.ok) {
                const errorData = await malsyncResponse.json();
                if (errorData.name === "EntityNotFoundError" && errorData.code === 404) {
                    // Anime not found, do not retry
                    throw new Error('Anime not found');
                } else {
                    throw new Error('Network response was not ok');
                }
            }

            break;
        }

        if (retryCount >= maxRetries) {
            throw new Error('Max retries reached, still rate limited');
        }

        const malsyncData = await malsyncResponse.json();

        const hianimeId = malsyncData.Sites?.Zoro?.[Object.keys(malsyncData.Sites.Zoro)[0]]?.url?.replace('https://hianime.to/', '');
        if (!hianimeId) throw new Error('Hianime ID not found');

        const episodesUrl = `https://zoro-api-9streams.vercel.app/api/v2/hianime/anime/${hianimeId}/episodes`;
        const episodesResponse = await fetch(episodesUrl);

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

        if (!episodesData.success || !episodesData.data?.episodes) throw new Error('No episodes found');

        let consumetData;
        let consumetResponse;

        const consumetUrlGogo = `https://9streams.xyz/anime/info.php?id=${animeId}`;
        consumetResponse = await fetch(consumetUrlGogo);

        if (!consumetResponse.ok) {
            provider = 'zoro';
            const consumetUrlZoro = `https://consumet-anime-beta.vercel.app/meta/anilist/info/${animeId}`;
            consumetResponse = await fetch(consumetUrlZoro);

            if (!consumetResponse.ok) {
                throw new Error('Anime data not found');
            }
        }

        consumetData = await consumetResponse.json();

        // Check if the response contains valid data (e.g., title)
        if (!consumetData.title || !consumetData.title.romaji || !consumetData.title.english) {
            // If gogo response is invalid, switch to zoro and retry
            provider = 'zoro';
            const consumetUrlZoro = `https://consumet-anime-beta.vercel.app/meta/anilist/info/${animeId}?provider=zoro`;
            consumetResponse = await fetch(consumetUrlZoro);

            if (!consumetResponse.ok) {
                throw new Error('Anime data not found');
            }

            consumetData = await consumetResponse.json();

            // Check again if the zoro response is valid
            if (!consumetData.title || !consumetData.title.romaji || !consumetData.title.english) {
                throw new Error('Anime data not found');
            }
        }

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

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

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

        // Load episodes
        episodes = episodesData.data.episodes;
        displayEpisodes();

        // Load saved state from localStorage
        const savedState = JSON.parse(localStorage.getItem(`animeState_${animeId}`)) || {};
        currentEpisodeIndex = savedState.episodeIndex || 0;
        currentType = savedState.type || 'sub';
        currentHD = savedState.hd || 1;

        // Update UI to reflect saved state
        document.getElementById('toggle-button').textContent = `Switch to ${currentType === 'sub' ? 'Dub' : 'Sub'}`;
        document.getElementById('hd-switch-button').textContent = `Switch to HD-${currentHD === 1 ? '2' : '1'}`;

        // Load the saved episode
        loadEpisode(currentEpisodeIndex, currentType);

        // Display relations and recommendations
        displayRelationsAndRecommendations(consumetData.relations, consumetData.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);

        // Show error page if fetching fails
        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}${episode.isFiller ? ' (filler)' : ''}`;

        // Highlight filler episodes with light yellow background and black text
        if (episode.isFiller) {
            episodeElement.style.backgroundColor = '#ffffcc'; // Light yellow
            episodeElement.style.color = 'black'; // Black text
        }

        // Highlight the currently playing episode
        if (index === currentEpisodeIndex) {
            episodeElement.classList.add('active');
            episodeElement.style.backgroundColor = '#403385'; // Purple background for active episode
            episodeElement.style.color = '#fff'; // White text for active episode
        }

        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?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) => {
        const isActive = i === index;
        el.classList.toggle('active', isActive);

        // Dynamically update styles for active and filler episodes
        if (episodes[i].isFiller) {
            if (isActive) {
                // Active filler episode: purple background, white text
                el.style.backgroundColor = '#403385';
                el.style.color = '#fff';
            } else {
                // Inactive filler episode: light yellow background, black text
                el.style.backgroundColor = '#ffffcc';
                el.style.color = 'black';
            }
        } else if (isActive) {
            // Active non-filler episode: purple background, white text
            el.style.backgroundColor = '#403385';
            el.style.color = '#fff';
        } else {
            // Inactive non-filler episode: reset styles
            el.style.backgroundColor = '';
            el.style.color = '';
        }
    });

    // Scroll to the player
    document.getElementById('anime-iframe').scrollIntoView({ behavior: 'smooth', block: 'start' });

    // Save the current state to localStorage
    saveState();

    updateNavButtons();
}

function saveState() {
    const state = {
        episodeIndex: currentEpisodeIndex,
        type: currentType,
        hd: currentHD,
    };
    localStorage.setItem(`animeState_${animeId}`, JSON.stringify(state));
}

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;

    // 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
    });
}

// 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

    // Display relations
    (relations || []).forEach(rel => {
        // Determine the title using available properties
        const title = rel.title?.english || rel.title?.romaji || rel.title || 'Unknown Title';
        const image = rel.image || 'default-image-url';  // Replace with an appropriate fallback image

        // Check if the relation is a manga by inspecting the URL
        let relationType = 'RELATED';
        const isManga = rel.url && rel.url.includes('anilist.co/manga/');
        if (isManga) {
            relationType = 'RELATED MANGA';
        }

        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}</p>
            </div>
        `;

        // Handle click for redirection
        relElement.addEventListener('click', () => {
            if (isManga) {
                // For manga, redirect to the manga search page with the title as a search parameter
                const mangaName = encodeURIComponent(title);
                window.location.href = `https://9streams.xyz/search/manga?preSearch=${mangaName}`;
            } else if (rel.id) {
                // Otherwise, redirect to the anime details page
                window.location.href = `/anime/default?anime=${rel.id}`;
            }
        });

        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>
