<!-- templates/home.html -->
{% extends 'base.html' %}
{% block title %}Home - BlickBox{% endblock %}
{% block content %}
<div class="home-content">
    <!-- Banner Slider -->
    <div class="banner-slider">
        <div class="banner-container">
            <div class="banners"></div>
        </div>
        <div class="banner-indicators"></div>
    </div>
    <!-- Discover Text -->
    <div class="discover">
        <h2>Discover Your Next Favorite Movie.</h2>
    </div>
    <!-- Categories Grid -->
    <div class="categories">
        <div class="categories-grid"></div>
    </div>
    <!-- Tags with Movies/Series -->
    <div class="tags-section"></div>
    <!-- Manual Ad Unit Below Tags -->
    <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>
</div>
<!--<footer class="footer">-->
<!--    <div class="footer-links">-->
<!--        <a href="/terms/">Terms and Conditions</a>-->
<!--        <a href="/privacy/">Privacy Policy</a>-->
<!--        <a href="/about/">About Us</a>-->
<!--        <a href="/contact/">Contact Us</a>-->
<!--    </div>-->
<!--    <div class="footer-app-links">-->
<!--        <a href="https://play.google.com/store/apps" target="_blank"><i class="fab fa-google-play"></i> Google Play</a>-->
<!--        <a href="https://www.apple.com/app-store/" target="_blank"><i class="fab fa-app-store"></i> App Store</a>-->
<!--    </div>-->
<!--    <p>© 2025 BlickBox. All rights reserved.</p>-->
<!--</footer>-->
{% 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/';
    }

    // Base URL for API and images
    const baseUrl = 'https://blinkbox.ng';

    // Token Refresh Function
    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(`${baseUrl}/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;
    }

    // Fetch with Authentication
    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();
    }

    // Banner Slider
    let currentBannerIndex = 0;
    let banners = [];
    const bannerContainer = document.querySelector('.banners');
    const indicatorsContainer = document.querySelector('.banner-indicators');

    async function fetchBanners() {
        try {
            const data = await fetchWithAuth(`${baseUrl}/api/carousel-banners/`);
            banners = data;
            renderBanners();
            startBannerAutoSwipe();
        } catch (err) {
            console.error('Error fetching banners:', err);
        }
    }

    function renderBanners() {
        bannerContainer.innerHTML = '';
        indicatorsContainer.innerHTML = '';
        banners.forEach((banner, index) => {
            const bannerDiv = document.createElement('div');
            bannerDiv.className = 'banner';
            bannerDiv.innerHTML = `
                <div class="banner-content">
                    <img src="${baseUrl}${banner.image}" alt="${banner.title}" onerror="this.src='https://via.placeholder.com/1280x720';">
                    <div class="gradient-overlay"></div>
                    <div class="banner-info">
                        <h3>${banner.title}</h3>
                        <button onclick="handleBannerClick(${index})">${getButtonText(banner.link.type)}</button>
                    </div>
                </div>
            `;
            bannerContainer.appendChild(bannerDiv);

            const indicator = document.createElement('span');
            indicator.className = 'banner-indicator';
            indicator.dataset.index = index;
            indicatorsContainer.appendChild(indicator);
        });
        updateBannerPosition();
    }

    function updateBannerPosition() {
        bannerContainer.style.transform = `translateX(-${currentBannerIndex * 100}%)`;
        const indicators = indicatorsContainer.children;
        for (let i = 0; i < indicators.length; i++) {
            indicators[i].className = i === currentBannerIndex ? 'banner-indicator active' : 'banner-indicator';
        }
    }

    function startBannerAutoSwipe() {
        setInterval(() => {
            currentBannerIndex = (currentBannerIndex + 1) % banners.length;
            updateBannerPosition();
        }, 9000);
    }

    function getButtonText(type) {
        switch (type) {
            case 'movie':
            case 'series':
                return 'Watch Now';
            case 'external_url':
                return 'Learn More';
            default:
                return 'Watch';
        }
    }

    function handleBannerClick(index) {
        const banner = banners[index];
        const link = banner.link;
        if (link.type === 'movie') {
            window.location.href = `/movie/${link.id}/`;
        } else if (link.type === 'series') {
            window.location.href = `/series/${link.id}/`;
        } else if (link.type === 'external_url') {
            window.open(link.url, '_blank');
        }
    }

    // Categories Grid
    const categoriesGrid = document.querySelector('.categories-grid');
    async function fetchCategories() {
        try {
            const data = await fetchWithAuth(`${baseUrl}/api/categories/`);
            renderCategories(data.slice(0, 6));
        } catch (err) {
            console.error('Error fetching categories:', err);
        }
    }

    function renderCategories(categories) {
        categoriesGrid.innerHTML = '';
        categories.forEach(category => {
            const categoryDiv = document.createElement('div');
            categoryDiv.className = 'category-card';
            categoryDiv.innerHTML = `
                <img src="${baseUrl}${category.image}" alt="${category.name}" onerror="this.src='https://via.placeholder.com/150';">
                <div class="category-overlay"></div>
                <div class="category-name">${category.name}</div>
            `;
            categoryDiv.onclick = () => {
                window.location.href = `/category/${category.name}/`;
            };
            categoriesGrid.appendChild(categoryDiv);
        });
    }

    // Tags with Movies/Series
    const tagsSection = document.querySelector('.tags-section');
    async function fetchTagsWithMovies() {
        try {
            const data = await fetchWithAuth(`${baseUrl}/api/tags/`);
            console.log('Tags API response:', data);
            renderTags(data);
        } catch (err) {
            console.error('Error fetching tags:', err);
        }
    }

    function renderTags(tags) {
        tagsSection.innerHTML = '';
        tags.forEach(tagData => {
            const tagName = typeof tagData.tag === 'object' ? tagData.tag.tag : tagData.tag;
            const isSpecialTag = ['popularly viewed'].includes(tagName.toLowerCase());
            const items = tagData.movies.length > 0 ? tagData.movies : tagData.series;
            const itemType = tagData.movies.length > 0 ? 'movie' : 'series';

            if (items.length === 0) return;

            const tagDiv = document.createElement('div');
            tagDiv.className = 'tag-container';
            tagDiv.innerHTML = `
                <h3>${tagName}</h3>
                <div class="tag-items"></div>
            `;
            const itemsContainer = tagDiv.querySelector('.tag-items');
            items.forEach(item => {
                if (!item.id) {
                    console.warn(`Item "${item.title}" missing ID`);
                    return;
                }
                console.log(`Rendering ${itemType}:`, item);
                const itemDiv = document.createElement('div');
                itemDiv.className = `tag-item ${isSpecialTag ? 'special' : ''}`;
                const imageField = itemType === 'movie' ? item.poster : item.image;
                const imageUrl = imageField ? `${baseUrl}${imageField}` : `https://via.placeholder.com/${isSpecialTag ? '180x100' : '120x160'}`;
                itemDiv.innerHTML = `
                    <img src="${imageUrl}" alt="${item.title}" onerror="this.src='https://via.placeholder.com/${isSpecialTag ? '180x100' : '120x160'}';">
                    <div class="tag-title">${item.title}</div>
                    <div class="tag-genre">${item.genre || 'Unknown'}</div>
                `;
                itemDiv.onclick = () => {
                    window.location.href = `/${itemType}/${item.id}/`;
                };
                itemsContainer.appendChild(itemDiv);
            });
            tagsSection.appendChild(tagDiv);
        });
    }

    // Initialize Data Fetching
    fetchBanners();
    fetchCategories();
    fetchTagsWithMovies();

    // Pull-to-Refresh
    let touchStartY = 0;
    let touchEndY = 0;
    document.addEventListener('touchstart', e => {
        touchStartY = e.changedTouches[0].screenY;
    });
    document.addEventListener('touchend', e => {
        touchEndY = e.changedTouches[0].screenY;
        if (touchEndY - touchStartY > 100) {
            fetchBanners();
            fetchCategories();
            fetchTagsWithMovies();
        }
    });
</script>
{% endblock %}
