<!-- templates/category_detail.html -->
{% extends 'base.html' %}
{% block title %}{{ category_name }} - BlickBox{% endblock %}
{% block content %}
<div class="content-box">
    <div class="category-detail-container">
        <div class="header">
            <h2>{{ category_name }}</h2>
        </div>
        <div class="tabs">
            <div class="tab active" onclick="showTab('movies')">Movies</div>
            <div class="tab" onclick="showTab('series')">Series</div>
        </div>
        <div id="movies" class="tab-content">
            <div id="movies-grid" class="grid"></div>
        </div>
        <div id="series" class="tab-content" style="display: none;">
            <div id="series-grid" class="grid"></div>
        </div>
        <p class="error" id="error-message" style="display: none;"></p>
    </div>
</div>
{% endblock %}
{% block scripts %}
<script>
    function showTab(tab) {
        document.querySelectorAll('.tab').forEach(t => t.classList.remove('active'));
        document.querySelectorAll('.tab-content').forEach(t => t.style.display = 'none');
        document.querySelector(`[onclick="showTab('${tab}')"]`).classList.add('active');
        document.getElementById(tab).style.display = 'block';
    }

    async function fetchItemsByCategory(category, type) {
    const token = localStorage.getItem('access_token');
    if (!token) throw new Error('Please log in to view content');
    const response = await fetch(`/api/categories/${encodeURIComponent(category)}/${type}/`, {
        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 ${type}`);
    }
    const data = await response.json();
    return data[type]; // Extract the movies or series array from the response
}

    function renderGrid(gridId, items, type) {
        const grid = document.getElementById(gridId);
        grid.innerHTML = items.length ? '' : `<p>No ${type} found.</p>`;
        items.forEach(item => {
            const card = document.createElement('div');
            card.className = 'movie-card';
            card.innerHTML = `
                <img src="${item.poster || item.image}" alt="${item.title}">
                <div class="card-content">
                    <h3>${item.title}</h3>
                    <p>${item.genre || 'Unknown'}</p>
                </div>
            `;
            card.addEventListener('click', () => {
                const path = type === 'movies' ? 'movie' : 'series';
                window.location.href = `/${path}/${item.id}/`;
            });
            grid.appendChild(card);
        });
    }

    document.addEventListener('DOMContentLoaded', async () => {
        const errorMessage = document.getElementById('error-message');
        const category = "{{ category_name | escapejs }}";

        try {
            const movies = await fetchItemsByCategory(category, 'movies');
            const series = await fetchItemsByCategory(category, 'series');
            renderGrid('movies-grid', movies, 'movies');
            renderGrid('series-grid', series, 'series');
        } catch (err) {
            errorMessage.textContent = err.message;
            errorMessage.style.display = 'block';
            console.error('Error loading items:', err);
        }
    });
</script>
{% endblock %}