const token = localStorage.getItem('token');
let currentVendor = '';
let currentPage = 1;
let allGames = [];
let viewMode = 'all';
let searchQuery = '';
let isLoadingMore = false;

async function loadGames(reset) {
    if (reset) { currentPage = 1; allGames = []; showSkeleton(); }
    try {
        const url = currentVendor
            ? '/get_vendor_games.php?vendor=' + currentVendor + '&page=' + currentPage + '&limit=21'
            : '/get_all_slots_combined.php?page=' + currentPage + '&limit=21';
        const res = await fetch(url);
        const data = await res.json();
        allGames = allGames.concat(data.games || []);
        currentPage++;
        document.getElementById('loadMoreBtn').style.display = data.has_more ? 'block' : 'none';
        renderGrid();
    } catch (e) {
        console.error("Games fetch error", e);
    }
}

function loadMore() { loadGames(false); }

function toggleRecent() {
    const isActive = document.getElementById('recentBtn').classList.contains('active');
    document.getElementById('recentBtn').classList.toggle('active', !isActive);
    document.getElementById('favBtn').classList.remove('active');
    viewMode = isActive ? 'all' : 'recent';
    renderGrid();
}

function toggleFavView() {
    const isActive = document.getElementById('favBtn').classList.contains('active');
    document.getElementById('favBtn').classList.toggle('active', !isActive);
    document.getElementById('recentBtn').classList.remove('active');
    viewMode = isActive ? 'all' : 'favorite';
    renderGrid();
}

function onSearchInput() {
    searchQuery = document.getElementById('searchInput').value.toLowerCase().trim();
    renderGrid();
}

// Infinite Scroll Observer
const scrollObserver = new IntersectionObserver((entries) => {
    entries.forEach(entry => {
        if (entry.isIntersecting && !isLoadingMore && document.getElementById('loadMoreBtn').style.display === 'block') {
            isLoadingMore = true;
            loadGames(false).finally(() => { isLoadingMore = false; });
        }
    });
}, { rootMargin: '400px' });

document.addEventListener("DOMContentLoaded", () => {
    scrollObserver.observe(document.getElementById('loadMoreBtn'));
    loadProviderTabs();
    loadGames(true);
});