<!-- 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>
    async function searchItems(query) {
        const token = localStorage.getItem('access_token');
        const response = await fetch(`/api/search/?q=${encodeURIComponent(query)}`, {
            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 search results');
        }
        return await response.json();
    }

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

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