<!-- templates/series_detail.html -->
{% extends 'base.html' %}
{% block title %}Series - BlickBox{% endblock %}
{% block content %}
<div class="content-box">
    <div class="series-detail-container">
        <div class="poster-section">
            <img id="series-image" src="" alt="Series Image">
            <div class="gradient-overlay"></div>
            <div class="series-info">
                <div class="thumbnail-container">
                    <img id="series-thumbnail" src="" alt="Series Thumbnail">
                    <div class="series-meta">
                        <h2 id="series-title">Loading...</h2>
                        <div class="meta-row">
                            <span class="icon">🎬</span>
                            <span id="series-genre">Loading...</span>
                        </div>
                        <div class="meta-row">
                            <span class="icon">📅</span>
                            <span id="series-release">Loading...</span>
                        </div>
                    </div>
                </div>
                <div class="action-buttons">
                    <button id="play-button">Play</button>
                    <button id="download-button">Download</button>
                </div>
            </div>
        </div>
        <div class="overview-section">
            <h3>Overview</h3>
            <p id="series-description">Loading...</p>
            <a id="toggle-description" style="display: none;">Show More</a>
        </div>
        <div class="seasons-section">
            <h3>Seasons</h3>
            <div id="seasons-list"></div>
        </div>
        <!-- Manual Ad Unit Below Seasons -->
        <div class="ad-container" style="margin: 20px 0; text-align: center;">
            <ins class="adsbygoogle"
                 style="display:block"
                 data-ad-client="ca-pub-XXXXXXXXXXXXXXXX"
                 data-ad-slot="XXXXXXXXXX"
                 data-ad-format="auto"
                 data-full-width-responsive="true"></ins>
            <script>
                (adsbygoogle = window.adsbygoogle || []).push({});
            </script>
        </div>
        <p class="error" id="error-message" style="display: none;"></p>
    </div>
</div>
{% endblock %}
{% block scripts %}
<!-- Google AdSense Auto Ads -->
<script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-XXXXXXXXXXXXXXXX"
        crossorigin="anonymous"></script>
<script>
    (adsbygoogle = window.adsbygoogle || []).push({
        google_ad_client: "ca-pub-XXXXXXXXXXXXXXXX",
        enable_page_level_ads: true,
        overlays: { bottom: false, top: false, vignette: false },
        non_personalized_ads: true
    });
</script>
<script>
    const baseUrl = 'http://localhost:8000';

    async function fetchSeries(id) {
        const token = localStorage.getItem('access_token');
        if (!token) throw new Error('Please log in to view content');
        try {
            console.log('Fetching series with URL:', `/api/series/${id}/`); // Debug log
            const response = await fetch(`/api/series/${id}/`, {
                headers: {
                    'Authorization': `Bearer ${token}`,
                    'Content-Type': 'application/json'
                }
            });
            if (!response.ok) {
                const errorData = await response.json().catch(() => ({}));
                throw new Error(errorData.error || `Failed to fetch series (Status: ${response.status})`);
            }
            const data = await response.json();
            console.log('Series API response:', data); // Debug log
            return data;
        } catch (err) {
            console.error('Fetch error details:', err); // Debug log
            throw err;
        }
    }

    function saveContinueWatching(series, episode) {
        const continueWatching = JSON.parse(localStorage.getItem('continue_watching') || '[]');
        const seriesData = {
            id: series.id,
            title: series.title,
            poster: series.image,
            video_file: episode.video_720p || episode.video_file
        };
        if (!continueWatching.some(s => s.id === series.id)) {
            continueWatching.unshift(seriesData);
            localStorage.setItem('continue_watching', JSON.stringify(continueWatching));
        }
    }

    function renderSeasons(seasons) {
        const seasonsList = document.getElementById('seasons-list');
        seasonsList.innerHTML = '';
        if (!seasons || seasons.length === 0) {
            seasonsList.innerHTML = '<p>No seasons available.</p>';
            return;
        }
        seasons.forEach(season => {
            const seasonDiv = document.createElement('div');
            seasonDiv.className = 'season-container';
            seasonDiv.innerHTML = `
                <div class="season-title">Season ${season.season_number}<span>▼</span></div>
                <div class="season-content">
                    ${season.episodes.map(ep => `
                        <div class="episode-item">
                            <div class="episode-info">
                                <h4>${ep.title}</h4>
                                <p>Release Date: ${ep.release_date || 'Unknown'}</p>
                            </div>
                            <div class="episode-actions">
                                <span class="play-episode">▶</span>
                                <span class="download-episode">↓</span>
                            </div>
                        </div>
                    `).join('')}
                </div>
            `;
            seasonsList.appendChild(seasonDiv);
        });

        document.querySelectorAll('.season-title').forEach(title => {
            title.addEventListener('click', () => {
                const content = title.nextElementSibling;
                content.classList.toggle('active');
                title.querySelector('span').textContent = content.classList.contains('active') ? '▲' : '▼';
            });
        });

        document.querySelectorAll('.play-episode').forEach((btn, index) => {
            btn.addEventListener('click', () => {
                const season = seasons[Math.floor(index / seasons[0].episodes.length)];
                const episode = season.episodes[index % season.episodes.length];
                saveContinueWatching(series, episode);
                const videoWindow = window.open('', '_blank');
                videoWindow.document.write(`
                    <html>
                        <head><title>${episode.title}</title></head>
                        <body style="margin:0;background:#000;">
                            <video controls autoplay style="width:100%;height:100vh;">
                                <source src="${episode.video_720p || episode.video_file || ''}" type="video/mp4">
                                Your browser does not support the video tag.
                            </video>
                        </body>
                    </html>
                `);
            });
        });

        document.querySelectorAll('.download-episode').forEach((btn, index) => {
            btn.addEventListener('click', () => {
                const season = seasons[Math.floor(index / seasons[0].episodes.length)];
                const episode = season.episodes[index % season.episodes.length];
                const videoUrl = episode.video_720p || episode.video_file;
                if (videoUrl) {
                    const link = document.createElement('a');
                    link.href = videoUrl;
                    link.download = `${series.title} - S${season.season_number}E${episode.episode_number}.mp4`;
                    link.click();
                } else {
                    document.getElementById('error-message').textContent = 'No video available for download';
                    document.getElementById('error-message').style.display = 'block';
                }
            });
        });
    }

    let series;
    document.addEventListener('DOMContentLoaded', async () => {
        const errorMessage = document.getElementById('error-message');
        const pathParts = window.location.pathname.split('/');
        const seriesId = pathParts[pathParts.indexOf('series') + 1];

        if (!seriesId || isNaN(seriesId)) {
            errorMessage.textContent = 'Invalid or missing series ID';
            errorMessage.style.display = 'block';
            return;
        }

        try {
            console.log('Attempting to fetch series with ID:', seriesId); // Debug log
            series = await fetchSeries(seriesId);
            document.getElementById('series-title').textContent = series.title || 'Untitled';
            document.getElementById('series-image').src = series.image ? `${baseUrl}${series.image}` : 'https://via.placeholder.com/1280x720';
            document.getElementById('series-thumbnail').src = series.image ? `${baseUrl}${series.image}` : 'https://via.placeholder.com/150';
            document.getElementById('series-genre').textContent = series.genre || 'Unknown';
            document.getElementById('series-release').textContent = series.release_date || 'Unknown';
            document.getElementById('series-description').textContent = series.description || 'No description';
            
            const description = document.getElementById('series-description');
            const toggle = document.getElementById('toggle-description');
            if (series.description && series.description.length > 100) {
                toggle.style.display = 'block';
                toggle.addEventListener('click', () => {
                    description.classList.toggle('expanded');
                    toggle.textContent = description.classList.contains('expanded') ? 'Show Less' : 'Show More';
                });
            }

            renderSeasons(series.seasons || []);

            document.getElementById('play-button').addEventListener('click', () => {
                const firstEpisode = series.seasons[0]?.episodes[0];
                if (firstEpisode) {
                    saveContinueWatching(series, firstEpisode);
                    const videoWindow = window.open('', '_blank');
                    videoWindow.document.write(`
                        <html>
                            <head><title>${firstEpisode.title}</title></head>
                            <body style="margin:0;background:#000;">
                                <video controls autoplay style="width:100%;height:100vh;">
                                    <source src="${firstEpisode.video_720p || firstEpisode.video_file || ''}" type="video/mp4">
                                    Your browser does not support the video tag.
                                </video>
                            </body>
                        </html>
                    `);
                }
            });

            document.getElementById('download-button').addEventListener('click', () => {
                const firstEpisode = series.seasons[0]?.episodes[0];
                const videoUrl = firstEpisode?.video_720p || firstEpisode?.video_file;
                if (videoUrl) {
                    const link = document.createElement('a');
                    link.href = videoUrl;
                    link.download = `${series.title} - S1E1.mp4`;
                    link.click();
                } else {
                    errorMessage.textContent = 'No video available for download';
                    errorMessage.style.display = 'block';
                }
            });
        } catch (err) {
            errorMessage.textContent = err.message;
            errorMessage.style.display = 'block';
            console.error('Error loading series:', err);
        }
    });
</script>
{% endblock %}