document.addEventListener('DOMContentLoaded', function() {
    // Initialize koto-Style Hero Spotlight Slider
    const hotestEl = document.getElementById('hotest');
    if (hotestEl && typeof Swiper !== 'undefined') {
        new Swiper('#hotest', {
            loop: true,
            grabCursor: true,
            speed: 600,
            autoplay: {
                delay: 5000,
                disableOnInteraction: false,
                pauseOnMouseEnter: true,
            },
            pagination: {
                el: '#hotest .swiper-pagination',
                clickable: true,
            },

        });
    }

    // Generic Track Navigation Handler
    function setupTrackNav(trackId, prevBtnId, nextBtnId, hdrPrevId, hdrNextId) {
        const track = document.getElementById(trackId);
        const prevBtn = document.getElementById(prevBtnId);
        const nextBtn = document.getElementById(nextBtnId);
        const hdrPrev = document.getElementById(hdrPrevId);
        const hdrNext = document.getElementById(hdrNextId);

        if (!track) return;

        function getScrollStep() {
            const firstCard = track.querySelector('.anime-card');
            if (firstCard) {
                const gap = 16;
                const cardWidth = firstCard.offsetWidth + gap;
                const visibleCount = Math.max(1, Math.round(track.clientWidth / cardWidth));
                return cardWidth * visibleCount;
            }
            return track.clientWidth * 0.85;
        }

        function scrollRight() {
            track.scrollBy({ left: getScrollStep(), behavior: 'smooth' });
        }

        function scrollLeft() {
            track.scrollBy({ left: -getScrollStep(), behavior: 'smooth' });
        }

        if (nextBtn) nextBtn.addEventListener('click', scrollRight);
        if (prevBtn) prevBtn.addEventListener('click', scrollLeft);
        if (hdrNext) hdrNext.addEventListener('click', scrollRight);
        if (hdrPrev) hdrPrev.addEventListener('click', scrollLeft);

        function updateNavVisibility() {
            const maxScroll = track.scrollWidth - track.clientWidth - 5;
            if (prevBtn) {
                const isStart = track.scrollLeft <= 5;
                prevBtn.style.opacity = isStart ? '0.3' : '1';
                prevBtn.style.pointerEvents = isStart ? 'none' : 'auto';
            }
            if (nextBtn) {
                const isEnd = track.scrollLeft >= maxScroll;
                nextBtn.style.opacity = isEnd ? '0.3' : '1';
                nextBtn.style.pointerEvents = isEnd ? 'none' : 'auto';
            }
            if (hdrPrev) {
                hdrPrev.disabled = track.scrollLeft <= 5;
                hdrPrev.style.opacity = track.scrollLeft <= 5 ? '0.4' : '1';
            }
            if (hdrNext) {
                hdrNext.disabled = track.scrollLeft >= maxScroll;
                hdrNext.style.opacity = track.scrollLeft >= maxScroll ? '0.4' : '1';
            }
        }

        track.addEventListener('scroll', updateNavVisibility, { passive: true });
        window.addEventListener('resize', updateNavVisibility, { passive: true });
        updateNavVisibility();
    }

    setupTrackNav('latest-track', 'latest-track-prev', 'latest-track-next', 'latest-hdr-prev', 'latest-hdr-next');
    setupTrackNav('upcoming-track', 'upcoming-track-prev', 'upcoming-track-next', 'upcoming-hdr-prev', 'upcoming-hdr-next');

    // =========================================================================
    // Continue Watching Dynamic Renderer (Re:ANIME Style - LocalStorage)
    // =========================================================================
    function escapeHtml(str) {
        if (!str) return '';
        return String(str)
            .replace(/&/g, '&amp;')
            .replace(/</g, '&lt;')
            .replace(/>/g, '&gt;')
            .replace(/"/g, '&quot;')
            .replace(/'/g, '&#039;');
    }

    function renderContinueWatching() {
        const section = document.getElementById('continue-watching-section');
        const track = document.getElementById('continue-watching-track');
        if (!section || !track) return;

        const STORAGE_KEY = 'kototv_continue_watching';
        let list = [];
        try {
            const raw = localStorage.getItem(STORAGE_KEY) || localStorage.getItem('reanime_continue_watching');
            if (raw) list = JSON.parse(raw);
            if (!Array.isArray(list)) list = [];
        } catch (e) {
            list = [];
        }

        // Filter out corrupted / empty entries
        list = list.filter(item => item && (item.anime_slug || item.slug));

        if (!list.length) {
            section.style.display = 'none';
            track.innerHTML = '';
            return;
        }

        let html = '';
        list.forEach(item => {
            const slug = escapeHtml(item.anime_slug || item.slug);
            const title = escapeHtml(item.anime_title || item.title || item.anime_slug);
            const epNum = Number(item.ep_num || item.episode_number || 1);
            const subCount = Number(item.sub_count || epNum);
            const dubCount = Number(item.dub_count || 0);
            const totalCount = escapeHtml(String(item.total_count || '?'));
            const displayFormat = escapeHtml(item.format || 'TV');
            const poster = escapeHtml(item.poster || item.poster_url || '/images/og_banner.jpg');
            const pct = Math.min(100, Math.max(0, Number(item.progress_percent) || 0));
            const watchUrl = item.watch_url || `/anime/${encodeURIComponent(item.anime_slug || item.slug)}/watch/${epNum}/${encodeURIComponent((item.type || 'sub').toLowerCase())}`;

            html += `
            <div class="anime-card cw-card" data-slug="${slug}">
                <button type="button" 
                        class="cw-remove-btn" 
                        title="Remove from Continue Watching" 
                        onclick="removeContinueWatchingItem('${slug}', ${epNum}, event)">
                    <i class="bi bi-x-lg"></i>
                </button>
                <a href="${watchUrl}" class="card-poster-wrap">
                    <img src="${poster}" 
                         class="card-poster" 
                         alt="${title}" 
                         loading="lazy" 
                         referrerpolicy="no-referrer" 
                         onerror="this.onerror=null;this.src='/images/og_banner.jpg';">
                    
                    <!-- Bottom-Left Sub / Dub / Total Episode Capsule (Identical to Latest Episodes) -->
                    <div class="card-badge-bottom">
                        <div class="badge-pill-item" title="Subbed Episodes">
                            <svg class="badge-pill-icon"><use href="#ico-sub"/></svg>
                            <span>${subCount}</span>
                        </div>
                        <span class="badge-pill-slash">/</span>
                        <div class="badge-pill-item" title="Dubbed Episodes">
                            <svg class="badge-pill-icon"><use href="#ico-dub"/></svg>
                            <span>${dubCount}</span>
                        </div>
                        <span class="badge-pill-slash">/</span>
                        <div class="badge-pill-item" title="Total Episodes">
                            <svg class="badge-pill-icon"><use href="#ico-ep"/></svg>
                            <span>${totalCount}</span>
                        </div>
                    </div>

                    <div class="cw-progress-container">
                        <div class="cw-progress-bar" style="width: ${pct}%;"></div>
                    </div>

                    <div class="card-play-overlay">
                        <div class="card-play-circle">
                            <svg class="card-play-svg"><use href="#ico-play"/></svg>
                        </div>
                    </div>
                </a>
                <div class="card-details">
                    <div class="card-title-row">
                        <span class="card-status-dot"></span>
                        <a href="${watchUrl}" class="card-title" title="${title}">
                            ${title}
                        </a>
                    </div>
                    <p class="card-meta-row">
                        <span>${displayFormat}</span>
                        <span class="meta-bullet">•</span>
                        <span>EP ${epNum}</span>
                        <span class="meta-bullet">•</span>
                        <span class="cw-percent-text">${pct > 0 ? pct + '%' : 'Started'}</span>
                    </p>
                </div>
            </div>`;
        });

        track.innerHTML = html;
        section.style.display = 'block';

        // Initialize track navigation for continue watching
        setupTrackNav('continue-watching-track', 'cw-track-prev', 'cw-track-next', 'cw-hdr-prev', 'cw-hdr-next');
    }

    window.removeContinueWatchingItem = function(slug, epNum, e) {
        if (e) {
            e.preventDefault();
            e.stopPropagation();
        }
        const STORAGE_KEY = 'kototv_continue_watching';
        try {
            let list = JSON.parse(localStorage.getItem(STORAGE_KEY) || '[]');
            if (Array.isArray(list)) {
                list = list.filter(item => item && (item.anime_slug || item.slug) !== slug);
                localStorage.setItem(STORAGE_KEY, JSON.stringify(list));
            }
        } catch (err) {}

        const card = document.querySelector(`.cw-card[data-slug="${slug}"]`);
        if (card) {
            card.style.transition = 'all 0.25s ease';
            card.style.opacity = '0';
            card.style.transform = 'scale(0.85)';
            setTimeout(() => {
                renderContinueWatching();
            }, 250);
        } else {
            renderContinueWatching();
        }
    };

    const clearBtn = document.getElementById('cw-clear-all');
    if (clearBtn) {
        clearBtn.addEventListener('click', function() {
            if (confirm('Are you sure you want to clear your Continue Watching history?')) {
                localStorage.removeItem('kototv_continue_watching');
                localStorage.removeItem('reanime_continue_watching');
                renderContinueWatching();
            }
        });
    }

    renderContinueWatching();
});