const token = localStorage.getItem('token');

function md5(str) {
    function rotateLeft(n, s) { return (n << s) | (n >>> (32 - s)); }
    function toHex(n) { let s = '', v; for (let i = 0; i < 4; i++) { v = (n >>> (i * 8)) & 255; s += ('0' + v.toString(16)).slice(-2); } return s; }
    function utf8Encode(str) { return unescape(encodeURIComponent(str)); }
    str = utf8Encode(str);
    const msgLen = str.length;
    const numBlocks = (((msgLen + 8) >>> 6) + 1) * 16;
    const M = new Array(numBlocks).fill(0);
    for (let i = 0; i < msgLen; i++) M[i >> 2] |= str.charCodeAt(i) << ((i % 4) * 8);
    M[msgLen >> 2] |= 0x80 << ((msgLen % 4) * 8);
    M[numBlocks - 2] = msgLen * 8;
    let a = 1732584193, b = -271733879, c = -1732584194, d = 271733878;
    const S = [7,12,17,22,7,12,17,22,7,12,17,22,7,12,17,22,5,9,14,20,5,9,14,20,5,9,14,20,5,9,14,20,4,11,16,23,4,11,16,23,4,11,16,23,4,11,16,23,6,10,15,21,6,10,15,21,6,10,15,21,6,10,15,21];
    const K = [];
    for (let i = 0; i < 64; i++) K[i] = (Math.floor(Math.abs(Math.sin(i + 1)) * 4294967296)) | 0;
    for (let i = 0; i < numBlocks; i += 16) {
        let A = a, B = b, C = c, D = d;
        for (let j = 0; j < 64; j++) {
            let F, g;
            if (j < 16) { F = (B & C) | (~B & D); g = j; }
            else if (j < 32) { F = (D & B) | (~D & C); g = (5 * j + 1) % 16; }
            else if (j < 48) { F = B ^ C ^ D; g = (3 * j + 5) % 16; }
            else { F = C ^ (B | ~D); g = (7 * j) % 16; }
            F = (F + A + K[j] + (M[i + g] | 0)) | 0;
            A = D; D = C; C = B;
            B = (B + rotateLeft(F, S[j])) | 0;
        }
        a = (a + A) | 0; b = (b + B) | 0; c = (c + C) | 0; d = (d + D) | 0;
    }
    return toHex(a) + toHex(b) + toHex(c) + toHex(d);
}

async function loadBalance() {
    // ✅ নতুন যোগ — Login না থাকলে, Login/Register Button দেখানো,
    // Balance-Badge লুকানো
    if (!token) {
        document.getElementById('loggedOutButtons').classList.remove('hidden');
        document.getElementById('loggedOutButtons').classList.add('flex');
        document.getElementById('loggedInBadge').classList.add('hidden');
        return;
    }
    document.getElementById('loggedInBadge').classList.remove('hidden');
    document.getElementById('loggedInBadge').classList.add('flex');

    const random = Math.random().toString(36).substring(2, 15);
    const shonustr = `{"language":1,"random":"${random}"}`;
    const signature = md5(shonustr).toUpperCase();
    try {
        const res = await fetch('/deepanshu/api/webapi/GetBalance.php', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json', 'Authorization': 'Bearer ' + token },
            body: JSON.stringify({ language: 1, random, signature, timestamp: Date.now() })
        });
        const data = await res.json();
        if (data.code === 0 && data.data) {
            document.getElementById('balanceBadge').textContent = '৳' + Number(data.data.amount).toLocaleString('en-IN', {maximumFractionDigits: 0});
        }
    } catch (e) {
        document.getElementById('balanceBadge').textContent = '৳ --';
    }
}

// ✅ Jackpot Counter
let jackpotValue = 8345621;
function renderJackpot() {
    const el = document.getElementById('jackpotDigits');
    const str = Math.floor(jackpotValue).toLocaleString('en-US').replace(/,/g, '');
    el.innerHTML = str.split('').map(d => `<span class="digit-box w-7 h-9 flex items-center justify-center rounded text-lg font-black">${d}</span>`).join('');
}
renderJackpot();
setInterval(() => { jackpotValue += Math.floor(Math.random() * 50) + 5; renderJackpot(); }, 2000);

// ✅ Real Banner Slider
let bannerImages = [];
let bannerIndex = 0;
async function loadBanners() {
    try {
        const res = await fetch('/deepanshu/api/webapi/GetBannerList.php');
        const data = await res.json();
        bannerImages = (data.data || []).map(b => b.bannerUrl).filter(Boolean);
        const container = document.getElementById('bannerContainer');
        const dotsContainer = document.getElementById('bannerDots');
        if (bannerImages.length === 0) { container.innerHTML = ''; return; }
        container.innerHTML = bannerImages.map((url, i) => `<img src="${url}" class="banner-img absolute inset-0 w-full h-full object-cover transition-opacity duration-500" style="opacity: ${i === 0 ? 1 : 0};">`).join('');
        dotsContainer.innerHTML = bannerImages.map((_, i) => `<span class="banner-dot w-2 h-2 rounded-full ${i === 0 ? 'gold-gradient' : 'bg-gray-600'}"></span>`).join('');
        if (bannerImages.length > 1) {
            setInterval(() => {
                bannerIndex = (bannerIndex + 1) % bannerImages.length;
                document.querySelectorAll('.banner-img').forEach((img, i) => img.style.opacity = i === bannerIndex ? '1' : '0');
                document.querySelectorAll('.banner-dot').forEach((dot, i) => dot.className = 'banner-dot w-2 h-2 rounded-full ' + (i === bannerIndex ? 'gold-gradient' : 'bg-gray-600'));
            }, 3500);
        }
    } catch (e) {}
}

// ✅ 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();

        // ✅ Casino-Vendor-তালিকা হলে, vendorCode-কেই "Game" হিসেবে দেখানো
        // (Click করলে সেই Vendor-এর ভেতরে ঢুকবে, Slot-এর মতোই)
        let gamesArray;
        if (currentCategory === 'video' && !vendorMode) {
            gamesArray = (data.vendors || []).map(v => ({ vendorCode: v.vendorCode, slotsName: v.vendorCode, vendorImg: v.previewImg, isCasinoVendorCard: true }));
        } else 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 কিনা (Backend-এ যথেষ্ট Real
// Popular-Data না থাকায়, এই Smart-Heuristic ব্যবহার করা)
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');
    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 করবে)
    const isVendorListing = (currentCategory === 'slot' || currentCategory === 'video') && !vendorMode;

    // ✅ নতুন যোগ — "All" Tab-এ, Popular-Game-গুলো উপরে
    // সাজিয়ে দেওয়া (Sort করে)
    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}" 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);
}

async function launchGame(gameCode, gameName) {
    if (!gameCode) { alert('এই Game-এর Code পাওয়া যায়নি।'); return; }
    if (!token) { window.location.href = '/newlogin.php'; return; }

    // ✅ ঠিক করা হলো — আগে "খেলতে চাও?" Confirm-Popup একটা
    // Extra ধাপ ছিল, যেটা User-কে থামিয়ে দিতো। এখন সেটা
    // সরিয়ে, সরাসরি তাৎক্ষণিক Loading-Feedback দেখানো হচ্ছে
    showGameLoadingOverlay(gameName);

    // ✅ ঠিক করা হলো — Click-Gesture থাকা অবস্থাতেই (Async-এর
    // আগে) window.open() Call করা হচ্ছে, যাতে Browser এটাকে
    // Popup-Blocker দিয়ে না আটকায়।
    const gameWindow = window.open('about:blank', '_blank');

    // ✅ নতুন যোগ — সাদা/Blank Page-এর বদলে, নতুন Tab-এই সাথে
    // সাথে Premium, Full-Brand Loading-Page লিখে দেওয়া হচ্ছে
    if (gameWindow) {
        gameWindow.document.write(`
            <!DOCTYPE html><html><head><meta charset="UTF-8"><title>CV111 - Loading</title>
            <meta name="viewport" content="width=device-width, initial-scale=1">
            <link rel="preconnect" href="https://fonts.googleapis.com">
            <link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Poppins:wght@600;700;800;900&display=swap">
            <style>
                *{margin:0;padding:0;box-sizing:border-box;}
                html,body{width:100%;height:100%;margin:0;padding:0;}
                body{
                    min-height:100vh;min-width:100vw;background:radial-gradient(circle at 20% 0%, rgba(155,93,229,.18), transparent 45%),
                    radial-gradient(circle at 90% 100%, rgba(245,197,66,.1), transparent 40%), #0A0714;
                    display:flex;align-items:center;justify-content:center;flex-direction:column;
                    font-family:'Poppins',sans-serif;overflow:hidden;position:relative;
                }
                body::before{content:'';position:absolute;width:300px;height:300px;border-radius:50%;
                    background:radial-gradient(circle, rgba(155,93,229,.15), transparent 70%);top:-100px;left:-100px;animation:float 8s ease-in-out infinite;}
                body::after{content:'';position:absolute;width:220px;height:220px;border-radius:50%;
                    background:radial-gradient(circle, rgba(245,197,66,.12), transparent 70%);bottom:-80px;right:-60px;animation:float 10s ease-in-out infinite reverse;}
                @keyframes float{0%,100%{transform:translateY(0);}50%{transform:translateY(-20px);}}

                .brand{font-size:20px;font-weight:900;font-style:italic;letter-spacing:1.5px;margin-bottom:36px;position:relative;z-index:1;
                    background:linear-gradient(135deg,#F5C542,#E0A926);-webkit-background-clip:text;background-clip:text;color:transparent;}

                .spin-box{width:70px;height:70px;border-radius:20px;background:linear-gradient(135deg,#F5C542,#E0A926);
                    display:flex;align-items:center;justify-content:center;animation:spin 1s linear infinite;
                    box-shadow:0 0 40px rgba(245,197,66,.5), 0 0 80px rgba(155,93,229,.2);margin-bottom:20px;position:relative;z-index:1;}
                .spin-box .dice{font-size:30px;}
                @keyframes spin{to{transform:rotate(360deg);}}

                .txt{color:#fff;font-weight:800;font-size:15px;letter-spacing:.3px;margin-bottom:6px;position:relative;z-index:1;}
                .sub{color:#9691B0;font-size:11.5px;position:relative;z-index:1;margin-bottom:24px;}

                .bar-wrap{width:160px;height:4px;border-radius:10px;background:rgba(255,255,255,.08);overflow:hidden;position:relative;z-index:1;}
                .bar-fill{position:absolute;top:0;left:-40%;height:100%;width:40%;border-radius:10px;
                    background:linear-gradient(90deg,#6C3FC5,#9B5DE5,#F5C542);animation:slide 1.1s ease-in-out infinite;}
                @keyframes slide{0%{left:-40%;}100%{left:100%;}}
            </style></head>
            <body>
                <div class="brand">CV111</div>
                <div class="spin-box"><span class="dice">🎲</span></div>
                <div class="txt">${gameName || 'Game'} খোলা হচ্ছে...</div>
                <div class="sub">একটু অপেক্ষা করো, প্রায় হয়ে এসেছে</div>
                <div class="bar-wrap"><div class="bar-fill"></div></div>
            </body></html>
        `);
        gameWindow.document.close();
    }

    try {
        const res = await fetch('/deepanshu/api/webapi/GetGameUrl.php', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json', 'Authorization': 'Bearer ' + token },
            body: JSON.stringify({ gameCode: gameCode })
        });
        const data = await res.json();
        hideGameLoadingOverlay();

        if (data.code === 0 && data.data && data.data.url) {
            if (gameWindow) gameWindow.location.href = data.data.url;
            else window.location.href = data.data.url; // Popup Block হলে, একই Tab-এ Fallback
        } else if (data.code === 4) {
            if (gameWindow) gameWindow.close();
            localStorage.removeItem('token');
            window.location.href = '/newlogin.php';
        } else {
            if (gameWindow) gameWindow.close();
            alert('Game চালু করা যায়নি: ' + (data.msg || 'অজানা সমস্যা'));
        }
    } catch (e) {
        hideGameLoadingOverlay();
        if (gameWindow) gameWindow.close();
        alert('একটা সমস্যা হয়েছে, আবার চেষ্টা করো।');
    }
}

// ✅ নতুন যোগ — Game-Loading-Overlay (Confirm-Dialog-এর বদলে,
// তাৎক্ষণিক, Non-Blocking Visual Feedback)
function showGameLoadingOverlay(gameName) {
    let overlay = document.getElementById('gameLoadingOverlay');
    if (!overlay) {
        overlay = document.createElement('div');
        overlay.id = 'gameLoadingOverlay';
        overlay.style.cssText = 'position:fixed; inset:0; z-index:9998; background:rgba(10,7,20,.85); display:flex; align-items:center; justify-content:center; flex-direction:column; backdrop-filter:blur(4px);';
        document.body.appendChild(overlay);
    }
    overlay.innerHTML = `
        <div style="width:50px; height:50px; border-radius:14px; background:linear-gradient(135deg,#F5C542,#E0A926); display:flex; align-items:center; justify-content:center; animation:gameLoadSpin 0.8s linear infinite; margin-bottom:14px;">
            <i class="fa-solid fa-dice" style="color:#1a1400; font-size:20px;"></i>
        </div>
        <div style="color:#fff; font-weight:800; font-size:13px;">${gameName || 'Game'} খোলা হচ্ছে...</div>
    `;
    overlay.style.display = 'flex';
    if (!document.getElementById('gameLoadSpinStyle')) {
        const style = document.createElement('style');
        style.id = 'gameLoadSpinStyle';
        style.textContent = '@keyframes gameLoadSpin { to { transform: rotate(360deg); } }';
        document.head.appendChild(style);
    }
}
function hideGameLoadingOverlay() {
    const overlay = document.getElementById('gameLoadingOverlay');
    if (overlay) overlay.style.display = 'none';
}


loadBalance();

// ✅ নতুন যোগ — প্রতি ১০ সেকেন্ডে, স্বয়ংক্রিয়ভাবে Balance
// নতুন করে Load করা (Game খেলে Balance বাড়া/কমা সাথে সাথেই
// দেখা যাবে, Page Reload করা লাগবে না)
setInterval(() => {
    if (token) loadBalance();
}, 10000);
// ✅ নতুন যোগ — সত্যিকারের Recent Winners (game_bet_logs থেকে) দেখানো
async function loadWinners() {
    try {
        const res = await fetch('/get_recent_winners.php');
        const data = await res.json();
        const ticker = document.getElementById('winnersTicker');
        if (!data.winners || data.winners.length === 0) {
            ticker.parentElement.style.display = 'none';
            return;
        }
        const items = data.winners.map(w =>
            `<span class="px-3"><i class="fa-solid fa-trophy gold-text mr-1"></i><span class="text-gray-300">${w.mobile}</span> <span class="neon-green font-bold">৳${w.amount}</span> জিতেছে</span>`
        ).join('');
        ticker.innerHTML = items + items; // Loop-এর জন্য দুইবার বসানো
        ticker.style.animation = 'scrollTicker 25s linear infinite';
    } catch (e) {
        document.getElementById('winnersTicker').parentElement.style.display = 'none';
    }
}

loadBanners();
loadGames(true);
// ✅ নতুন যোগ — Big Wins Showcase (GetAllGameList.php-এর
// awardRecordList থেকে — এটা Static/Template Data, তবুও
// শুধু দেখতে-সুন্দর Effect হিসেবে দেখানো হচ্ছে)
async function loadAwardShowcase() {
    try {
        const res = await fetch('/get_award_showcase.php');
        const data = await res.json();
        const container = document.getElementById('awardShowcase');
        if (!data.records || data.records.length === 0) { container.parentElement.style.display = 'none'; return; }

        // ✅ Loop স্বাভাবিক দেখানোর জন্য, তালিকা দুইবার বসানো হচ্ছে
        const cardsHtml = data.records.slice(0, 10).map(r => `
            <div class="card-bg border neon-border rounded-xl p-2.5 flex-shrink-0" style="width:110px;">
                <img src="${r.imgUrl}" class="w-full aspect-square object-cover rounded-lg mb-1.5" onerror="this.style.display='none'">
                <div class="text-white text-[9.5px] font-bold truncate">${r.gameName}</div>
                <div class="gold-text text-[11px] font-black mt-0.5">৳${Number(r.bonusAmount).toLocaleString()}</div>
            </div>
        `).join('');
        container.innerHTML = cardsHtml + cardsHtml;

        // ✅ ঠিক করা হলো — আগে প্রতি ২০ms-এ (সেকেন্ডে ৫০ বার!)
        // চলতো, যেটা পুরো System Slow করে দিচ্ছিল। এখন
        // requestAnimationFrame ব্যবহার করে, Browser নিজে
        // Optimize করে চালাবে (অনেক বেশি Efficient)
        let scrollPos = 0;
        let lastTime = 0;
        function autoScrollStep(timestamp) {
            if (!lastTime) lastTime = timestamp;
            const delta = timestamp - lastTime;
            lastTime = timestamp;
            scrollPos += delta * 0.03;
            if (scrollPos >= container.scrollWidth / 2) scrollPos = 0;
            container.scrollLeft = scrollPos;
            requestAnimationFrame(autoScrollStep);
        }
        requestAnimationFrame(autoScrollStep);
    } catch (e) {
        document.getElementById('awardShowcase').parentElement.style.display = 'none';
    }
}

loadWinners();
loadAwardShowcase();
