<!-- templates/see_all.html -->
{% extends 'base.html' %}
{% block title %}For You - BlickBox{% endblock %}
{% block content %}
<div class="content-box">
    <div class="see-all-container">
        <h2>For You</h2>
        <div class="grid" id="items-grid"></div>
        <p class="error" id="error-message" style="display: none;"></p>
    </div>
</div>
{% endblock %}
{% block scripts %}
<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 fetchItems() {
        const token = localStorage.getItem('access_token');
        if (!token) throw new Error('Please log in to view content');
        const moviesResponse = await fetch('/api/movies/', {
            headers: {
                'Authorization': `Bearer ${token}`,
                'Content-Type': 'application/json'
            }
        });
        const seriesResponse = await fetch('/api/series/', {
            headers: {
                'Authorization': `Bearer ${token}`,
                'Content-Type': 'application/json'
            }
        });
        if (!moviesResponse.ok || !seriesResponse.ok) {
            throw new Error('Failed to fetch items');
        }
        const movies = await moviesResponse.json();
        const series = await seriesResponse.json();
        return [...movies, ...series];
    }

    document.addEventListener('DOMContentLoaded', async () => {
        const grid = document.getElementById('items-grid');
        const errorMessage = document.getElementById('error-message');

        try {
            const items = await fetchItems();
            grid.innerHTML = '';
            items.forEach(item => {
                const type = item.poster ? 'movie' : 'series';
                const image = item.poster || item.image;
                const card = document.createElement('div');
                card.className = 'card';
                card.innerHTML = `<img src="${image}" alt="${item.title}">`;
                card.addEventListener('click', () => {
                    window.location.href = `/${type}/${item.id}/?id=${item.id}`;
                });
                grid.appendChild(card);
            });
        } catch (err) {
            errorMessage.textContent = err.message;
            errorMessage.style.display = 'block';
        }
    });
</script>
{% endblock %}
