// ✅ Games System (Category+Vendor+Search+Pagination)
let currentPage = 1;
let currentCategory = 'all';
let currentVendor = '';
let vendorMode = false;
let allLoadedGames = [];

async function loadGames(reset) {
    if (reset) {
        currentPage = 1; allLoadedGames = [];
        // ✅ নতুন যোগ — খালি Screen না দেখিয়ে, সাথে সাথেই
        // Skeleton (Shimmer) Placeholder দেখানো — User মনে
        // করবে সবকিছু তাৎক্ষণিক শুরু হয়ে গেছে
        document.getElementById('games-grid').innerHTML = Array(9).fill(0).map(() => `
            <div class="rounded-2xl overflow-hidden" style="background:#181129;">
                <div class="aspect-square skeleton-shimmer"></div>
                <div style="height:34px; padding:6px 8px;">
                    <div class="skeleton-shimmer" style="height:8px; width:70%; border-radius:4px;"></div>
                </div>
            </div>
        `).join('');
    }
    const btn = document.getElementById('load-more-btn');
    btn.textContent = 'লোড হচ্ছে...';
    try {
        // ✅ নতুন যোগ — "Casino" (video) Category-তে, Vendor-Grouped
        // আসল Live-Casino Data (GetVideWithChildGame.php) ব্যবহার করা
        let url;
        if (currentCategory === 'video' && !vendorMode) {
            url = '/get_casino_vendors.php';
        } else if (currentCategory === 'video' && vendorMode) {
            url = '/get_casino_vendors.php?vendor=' + currentVendor;
        } else if (vendorMode) {
            url = '/get_vendor_games.php?vendor=' + currentVendor + '&page=' + currentPage + '&limit=15';
        } else {
            url = '/get_all_games_merged.php?category=' + currentCategory + '&vendor=' + currentVendor + '&page=' + currentPage + '&limit=15';
        }

        const res = await fetch(url);
        const data = await res.json();

        // ✅ FIX — এখন "Casino" Tab-এও সরাসরি Game-লিস্ট আসে
        // (Vendor-Card না), তাই বাকি Category-র মতোই সরাসরি
        // data.games ব্যবহার করা হচ্ছে।
        let gamesArray;
        if (currentCategory === 'video' && vendorMode) {
            gamesArray = data.games || [];
        } else {
            gamesArray = data.games || [];
            // ✅ Update — FASTSPIN, EAZYGAME-এর আসল Logo যোগ করা হলো,
            // বাকিগুলো এখনো Text-Card হিসেবে দেখাবে (Real Logo না থাকায়)
            if (currentCategory === 'slot' && !vendorMode) {
                const manualVendors = [
                    { code: '5G', img: 'https://files.catbox.moe/9poq52.png', noLogo: false },
                    { code: '2J', img: 'https://files.catbox.moe/ah763l.png', noLogo: false },
                    { code: 'BNG', img: 'https://files.catbox.moe/99mrrv.png', noLogo: false },
                    { code: 'BTG', img: 'https://files.catbox.moe/9kx8e9.png', noLogo: false },
                    { code: '100HP', img: 'https://files.catbox.moe/gx849v.png', noLogo: false },
                    { code: 'EAZYGAME', img: 'https://files.catbox.moe/moholm.webp', noLogo: false },
                    { code: 'FASTSPIN', img: 'https://files.catbox.moe/qm35dm.jpg', noLogo: false },
                    { code: 'IDG', img: '', noLogo: true }
                ];
                manualVendors.forEach(v => {
                    gamesArray.push({
                        vendorCode: v.code,
                        slotsName: v.code,
                        vendorImg: v.img,
                        noLogo: v.noLogo
                    });
                });
            }
        }

        allLoadedGames = allLoadedGames.concat(gamesArray);

        // ✅ নতুন যোগ — Vendor-তালিকায় (Slot/Casino) যেন কোনো
        // Vendor দুইবার না দেখায়, তা নিশ্চিত করা
        if (currentCategory === 'slot' && !vendorMode) {
            const seen = new Set();
            allLoadedGames = allLoadedGames.filter(g => {
                if (seen.has(g.vendorCode)) return false;
                seen.add(g.vendorCode);
                return true;
            });
        }
        renderGames(allLoadedGames);
        currentPage++;
        btn.style.display = 'none'; // Casino-তে Pagination দরকার নেই (Vendor সংখ্যা কম)
        if (data.total !== undefined) {
            document.getElementById('game-count').innerText = data.total + ' Games';
            btn.textContent = 'আরও দেখাও';
            btn.style.display = data.has_more ? 'block' : 'none';
        } else {
            document.getElementById('game-count').innerText = gamesArray.length + ' Items';
        }
    } catch (e) { btn.textContent = 'আবার চেষ্টা করো'; }
}
function loadMoreGames() { loadGames(false); }

// ✅ Game-এর নাম দেখে, Auto-Detect করা এটা "Popular"
// Type-এর Game কিনা
const popularKeywords = [
    'fortune', 'dragon', 'gold', 'jackpot', 'wild', 'tiger', 'phoenix',
    'treasure', 'lucky', 'wealth', 'gems', 'diamond', 'ways', 'megaways',
    'bonanza', 'rich', 'money', 'coin', 'king', 'crown', 'empire', 'legend',
    'hot', 'blaze', 'fire', 'thunder', 'super', 'mega', 'grand'
];
function isPopularGame(name) {
    const lower = (name || '').toLowerCase();
    return popularKeywords.some(kw => lower.includes(kw));
}

function renderGames(games) {
    const grid = document.getElementById('games-grid');

    // ✅ নতুন যোগ — Frontend-Level Safety-Net — Backend থেকে বা
    // Race-Condition-এর কারণে যদি কখনো Duplicate Game আসেও,
    // এখানেই সেটা সরিয়ে দেওয়া হচ্ছে (Final Safety-Check)
    const seenCodes = new Set();
    games = games.filter(g => {
        const gCode = g.gameCode || g.gameID || g.code || g.vendorCode || JSON.stringify(g);
        if (seenCodes.has(gCode)) return false;
        seenCodes.add(gCode);
        return true;
    });

    grid.innerHTML = '';
    if (games.length === 0) { grid.innerHTML = '<div class="col-span-full text-center py-12 text-gray-500 text-sm">কোনো Game পাওয়া যায়নি।</div>'; return; }

    // ✅ ঠিক করা হলো — Vendor-Card (Provider-Logo) হলে
    // "object-contain" (পুরো ছবি দেখাবে), Game-Thumbnail হলে
    // "object-cover" (Square-ভাবে সুন্দর করে Fill করবে)
    // ✅ FIX — "video" (Casino) Category এখন আর Vendor-Card
    // Listing না (সরাসরি Game দেখায়), তাই এখানে বাদ দেওয়া হলো।
    // শুধু "slot" Category-ই এখনো Vendor-Card Listing ব্যবহার করে।
    const isVendorListing = (currentCategory === 'slot') && !vendorMode;

    // ✅ "All" Tab-এ, Popular-Game-গুলো উপরে সাজিয়ে দেওয়া
    if (currentCategory === 'all' && !isVendorListing) {
        games = [...games].sort((a, b) => {
            const nameA = a.gameNameEn || a.gameName || a.name || '';
            const nameB = b.gameNameEn || b.gameName || b.name || '';
            return (isPopularGame(nameB) ? 1 : 0) - (isPopularGame(nameA) ? 1 : 0);
        });
    }

    games.forEach(game => {
        const name = game.gameNameEn || game.gameName || game.slotsName || game.name || 'Game';
        const img = game.imgUrl || game.img || game.vendorImg || game.icon || game.image || '';
        const code = game.gameCode || game.gameID || game.code || '';
        const vendor = game.vendorCode || '';
        const card = document.createElement('div');
        card.className = 'game-card-hover card-bg rounded-xl overflow-hidden relative border neon-border cursor-pointer';

        if (isVendorListing && game.vendorCode) {
            card.onclick = () => openVendor(game.vendorCode, game.slotsName || game.vendorCode);
        } else {
            card.onclick = () => launchGame(code, name);
        }

        // ✅ Premium Upgrade — আরও Refined Card-Style
        card.className = 'game-card-hover rounded-2xl relative cursor-pointer';
        card.style.cssText = 'background:linear-gradient(160deg, #1D1533, #120D24); border:1px solid rgba(155,93,229,.18); box-shadow:0 10px 26px -10px rgba(108,63,197,.35); transition:transform .18s, box-shadow .18s, border-color .18s; overflow:hidden; display:flex; flex-direction:column;';
        card.onmouseenter = () => { card.style.borderColor = 'rgba(155,93,229,.5)'; card.style.boxShadow = '0 16px 34px -8px rgba(108,63,197,.55)'; };
        card.onmouseleave = () => { card.style.borderColor = 'rgba(155,93,229,.18)'; card.style.boxShadow = '0 10px 26px -10px rgba(108,63,197,.35)'; };

        const imgClass = isVendorListing
            ? 'w-full h-full object-contain pointer-events-none transition-transform duration-300'
            : 'w-full h-full object-cover pointer-events-none transition-transform duration-300';

        const imageBlock = game.noLogo
            ? `<div class="relative w-full aspect-square overflow-hidden pointer-events-none flex items-center justify-center" style="flex-shrink:0; background:linear-gradient(135deg, #F5C542, #E0A926);">
                   <span class="text-gray-900 font-black text-sm">${name}</span>
               </div>`
            : `<div class="relative w-full aspect-square overflow-hidden pointer-events-none flex items-center justify-center" style="flex-shrink:0;">
                   <img src="${img}" alt="${name}" class="${imgClass}" loading="lazy" onerror="this.style.display='none'; this.parentElement.innerHTML+='<div class=\\'text-gray-500 text-[9px] absolute inset-0 flex items-center justify-center\\'>${name}</div>'">
                   ${!isVendorListing ? `<div class="absolute inset-0 flex items-center justify-center opacity-0 hover:opacity-100 transition-opacity" style="background:rgba(10,7,20,.55);"><div class="w-9 h-9 rounded-full flex items-center justify-center" style="background:var(--grad-main, linear-gradient(135deg,#6C3FC5,#9B5DE5));"><i class="fa-solid fa-play text-white text-xs ml-0.5"></i></div></div>` : ''}
               </div>`;

        card.innerHTML = `
            <div class="fav-icon" style="pointer-events:none;"><i class="fa-regular fa-heart text-white text-[10px]"></i></div>
            ${!isVendorListing && isPopularGame(name) ? `<div style="position:absolute; top:6px; left:6px; z-index:3; background:linear-gradient(135deg,#F5C542,#E0A926); color:#1a1400; font-size:8px; font-weight:900; padding:2px 6px; border-radius:6px; pointer-events:none;">🔥 HOT</div>` : ''}
            ${imageBlock}
            <div class="px-2 py-1.5 pointer-events-none" style="min-height:34px; box-sizing:border-box; display:flex; flex-direction:column; justify-content:center; border-top:1px solid rgba(255,255,255,.05); background:rgba(0,0,0,.15); position:relative; z-index:5; flex-shrink:0;">
                <div class="text-white text-[10px] font-bold truncate">${name}</div>
                ${vendor && !isVendorListing ? `<div style="color:#F5C542; font-size:8px; font-weight:700; margin-top:1px;">${vendor}</div>` : ''}
                ${isVendorListing ? `<div style="color:#9691B0; font-size:8px; font-weight:600; margin-top:1px;">Tap to Explore →</div>` : ''}
            </div>
        `;
        grid.appendChild(card);
    });
}

function filterMainCategory(cat) {
    currentCategory = cat;
    currentVendor = '';
    vendorMode = false;
    const backBtn = document.getElementById('vendor-back-btn');
    if (backBtn) backBtn.style.display = 'none';
    document.querySelectorAll('.main-cat-btn').forEach(btn => {
        if (btn.dataset.cat === cat) btn.className = 'cat-btn main-cat-btn tab-active text-xs font-bold px-4 py-1.5 rounded-full flex-shrink-0';
        else btn.className = 'cat-btn main-cat-btn card-bg border neon-border text-gray-300 text-xs font-bold px-4 py-1.5 rounded-full flex-shrink-0';
    });
    document.getElementById('section-title').innerHTML = `<span class="w-2 h-5 green-gradient rounded-full inline-block"></span> ${cat.charAt(0).toUpperCase() + cat.slice(1)} Games`;

    const vendorRow = document.getElementById('vendor-tabs-row');
    vendorRow.classList.add('hidden'); vendorRow.classList.remove('flex');

    loadGames(true);
}

function filterVendor(vendor) {
    currentVendor = vendor;
    document.querySelectorAll('.vendor-btn').forEach(btn => {
        if (btn.dataset.vendor === vendor) btn.className = 'vendor-btn tab-active px-3 py-1 rounded text-xs font-bold flex-shrink-0';
        else btn.className = 'vendor-btn card-bg border neon-border text-gray-300 px-3 py-1 rounded text-xs font-bold flex-shrink-0';
    });
    loadGames(true);
}

function openVendor(vendorCode, vendorName) {
    vendorMode = true;
    currentVendor = vendorCode;
    document.getElementById('section-title').innerHTML = `<span class="w-2 h-5 green-gradient rounded-full inline-block"></span> ${vendorName}`;
    document.getElementById('vendor-tabs-row').classList.add('hidden');
    document.getElementById('vendor-tabs-row').classList.remove('flex');
    const backBtn = document.getElementById('vendor-back-btn');
    const categoryLabel = currentCategory === 'video' ? 'Casino' : 'Slot';
    backBtn.innerHTML = '<i class="fa-solid fa-arrow-left"></i> ' + categoryLabel + '-এ ফিরে যাও';
    backBtn.onclick = exitVendorMode;
    backBtn.style.display = 'flex';
    loadGames(true);
}

function exitVendorMode() {
    const returnCategory = currentCategory; // ✅ নতুন যোগ — সঠিক Category মনে রাখা
    vendorMode = false;
    currentVendor = '';
    document.getElementById('vendor-back-btn').style.display = 'none';
    filterMainCategory(returnCategory);
}

function searchGames() {
    const query = document.getElementById('search-input').value.toLowerCase();
    const filtered = allLoadedGames.filter(g => (g.gameNameEn || g.gameName || g.slotsName || '').toLowerCase().includes(query));
    renderGames(filtered);
}

