<!-- templates/explore.html -->
{% extends 'base.html' %}
{% block title %}Explore - BlickBox{% endblock %}
{% block content %}
<div class="content-box">
    <h2>Explore Movies & Series</h2>
    <div class="form-group">
        <input type="text" id="search-input" placeholder="Search movies or series...">
    </div>
    <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px;">
        <div>
            <label for="letter-filter">Filter A-Z:</label>
            <select id="letter-filter">
                <option value="All">All</option>
                {% for letter in 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' %}
                <option value="{{ letter }}">{{ letter }}</option>
                {% endfor %}
            </select>
        </div>
        <button onclick="window.location.href='/request-movie/'">Request Movie</button>
    </div>
    <div class="grid" id="results-grid"></div>
    <p class="error" id="error-message" style="display: none;"></p>
</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 searchItems(query) {
        return await fetchWithAuth(`/api/search/?q=${encodeURIComponent(query)}`);
    }

    function renderItems(movies, series) {
        const grid = document.getElementById('results-grid');
        grid.innerHTML = '';
        if (!movies.length && !series.length) {
            grid.innerHTML = '<p>No results found. Try requesting a movie!</p>';
            return;
        }
        [...movies, ...series].forEach(item => {
            const type = item.poster ? 'movie' : 'series';
            const image = item.poster || item.image || 'https://via.placeholder.com/150';
            const card = document.createElement('div');
            card.className = 'card';
            card.innerHTML = `
                <img src="${image}" alt="${item.title}">
                <div class="card-content">
                    <h3>${item.title}</h3>
                    <p>${item.genre || 'Unknown'}</p>
                </div>
            `;
            card.onclick = () => {
                window.location.href = `/${type}/${item.id}/`;
            };
            grid.appendChild(card);
        });
    }

    function filterByLetter(letter, movies, series) {
        if (letter === 'All') return { movies, series };
        return {
            movies: movies.filter(m => m.title.toLowerCase().startsWith(letter.toLowerCase())),
            series: series.filter(s => s.title.toLowerCase().startsWith(letter.toLowerCase()))
        };
    }

    document.addEventListener('DOMContentLoaded', () => {
        const searchInput = document.getElementById('search-input');
        const letterFilter = document.getElementById('letter-filter');
        const errorMessage = document.getElementById('error-message');
        let movies = [], series = [];

        searchInput.addEventListener('input', async () => {
            const query = searchInput.value.trim();
            if (!query) {
                renderItems([], []);
                return;
            }
            try {
                const data = await searchItems(query);
                movies = data.movies || [];
                series = data.series || [];
                const filtered = filterByLetter(letterFilter.value, movies, series);
                renderItems(filtered.movies, filtered.series);

                const searches = JSON.parse(localStorage.getItem('recent_searches') || '[]');
                if (!searches.includes(query)) {
                    searches.unshift(query);
                    if (searches.length > 10) searches.pop();
                    localStorage.setItem('recent_searches', JSON.stringify(searches));
                }
            } catch (err) {
                errorMessage.textContent = err.message;
                errorMessage.style.display = 'block';
                console.error('Search error:', err);
            }
        });

        letterFilter.addEventListener('change', () => {
            const filtered = filterByLetter(letterFilter.value, movies, series);
            renderItems(filtered.movies, filtered.series);
        });
    });
</script>
{% endblock %}

