

<!-- templates/movie_detail.html -->
{% extends 'base.html' %}
{% block title %}Movie - BlickBox{% endblock %}
{% block content %}
<div class="content-box">
    <div class="movie-detail-container">
        <div class="poster-section">
            <img id="movie-poster" src="" alt="Movie Poster">
            <div class="gradient-overlay"></div>
            <div class="movie-info">
                <div class="thumbnail-container">
                    <img id="movie-thumbnail" src="" alt="Movie Thumbnail">
                    <div class="movie-meta">
                        <h2 id="movie-title">Loading...</h2>
                        <div class="meta-row">
                            <span class="icon">🎬</span>
                            <span id="movie-genre">Loading...</span>
                        </div>
                        <div class="meta-row">
                            <span class="icon">📅</span>
                            <span id="movie-release">Loading...</span>
                        </div>
                        <div class="meta-row">
                            <span class="icon">⭐</span>
                            <span id="movie-rating">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="movie-description">Loading...</p>
            <a id="toggle-description" style="display: none;">Show More</a>
        </div>
        <!-- Manual Ad Unit Below Overview -->
        <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>

     // Redirect to login if not authenticated
    if (!localStorage.getItem('access_token')) {
        window.location.href = '/login/';
    }

    

    async function refreshToken() {
        const refreshToken = localStorage.getItem('refresh_token');
        if (!refreshToken) {
            localStorage.removeItem('access_token');
            window.location.href = '/login/';
            throw new Error('No refresh token available. Please log in.');
        }

        const response = await fetch('/api/token/refresh/', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({ refresh: refreshToken }),
        });

        if (!response.ok) {
            localStorage.removeItem('access_token');
            localStorage.removeItem('refresh_token');
            window.location.href = '/login/';
            throw new Error('Failed to refresh token. Please log in again.');
        }

        const data = await response.json();
        localStorage.setItem('access_token', data.access);
        if (data.refresh) {
            localStorage.setItem('refresh_token', data.refresh);
        }
        return data.access;
    }

    async function fetchWithAuth(url, options = {}) {
        let token = localStorage.getItem('access_token');
        if (!token) {
            throw new Error('Please log in to view content');
        }

        options.headers = {
            ...options.headers,
            'Authorization': `Bearer ${token}`,
            'Content-Type': 'application/json',
        };

        let response = await fetch(url, options);
        if (response.status === 401) {
            token = await refreshToken();
            options.headers['Authorization'] = `Bearer ${token}`;
            response = await fetch(url, options);
        }

        if (!response.ok) {
            const errorData = await response.json().catch(() => ({}));
            throw new Error(errorData.error || `Failed to fetch data from ${url}`);
        }

        return response.json();
    }

    async function fetchMovie(id) {
        const token = localStorage.getItem('access_token');
        if (!token) throw new Error('Please log in to view content');
        const response = await fetch(`/api/movies/${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 movie (Status: ${response.status})`);
        }
        return await response.json();
    }

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

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

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

        try {
            const movie = await fetchMovie(movieId);
            document.getElementById('movie-title').textContent = movie.title || 'Untitled';
            document.getElementById('movie-poster').src = movie.poster || 'https://via.placeholder.com/1280x720';
            document.getElementById('movie-thumbnail').src = movie.poster || 'https://via.placeholder.com/150';
            document.getElementById('movie-genre').textContent = movie.genre || 'Unknown';
            document.getElementById('movie-release').textContent = movie.release_date || 'Unknown';
            document.getElementById('movie-rating').textContent = movie.rating || 'N/A';
            document.getElementById('movie-description').textContent = movie.description || 'No description';
            
            const description = document.getElementById('movie-description');
            const toggle = document.getElementById('toggle-description');
            if (movie.description && movie.description.length > 100) {
                toggle.style.display = 'block';
                toggle.addEventListener('click', () => {
                    description.classList.toggle('expanded');
                    toggle.textContent = description.classList.contains('expanded') ? 'Show Less' : 'Show More';
                });
            }

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

            document.getElementById('download-button').addEventListener('click', () => {
                const videoUrl = movie.video_720p || movie.video_file;
                if (videoUrl) {
                    const link = document.createElement('a');
                    link.href = videoUrl;
                    link.download = `${movie.title}.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 movie:', err);
        }
    });
</script>
{% endblock %}
