<?php
include __DIR__ . "/deepanshu/conn.php";

$telegramLink = '#';
$tgResult = $conn->query("SELECT setting_value FROM site_settings WHERE setting_key = 'social_telegram' LIMIT 1");
if ($tgResult) {
    $tgRow = $tgResult->fetch_assoc();
    if ($tgRow && !empty($tgRow['setting_value'])) $telegramLink = $tgRow['setting_value'];
}
?>
<!DOCTYPE html>
<html lang="bn">
<head>
<meta charset="UTF-8">
<title>CV111 - Casino</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="https://cdn.tailwindcss.com"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Poppins:wght@400;500;600;700;800;900&display=swap">
<style>
    :root{
        --bg:#0A0714; --card:#181129; --border:rgba(255,255,255,.07); --border-hi:rgba(155,93,229,.35);
        --gold:#F5C542; --purple:#9B5DE5;
        --grad-main:linear-gradient(135deg,#6C3FC5 0%,#9B5DE5 50%,#B57EF0 100%);
        --grad-gold:linear-gradient(135deg,#F5C542,#E0A926);
        --muted:#9691B0;
    }
    body { background-color: var(--bg); font-family: 'Poppins', -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif; color: #f5f5f5; }
    .neon-green { color: var(--gold); }
    .neon-border { border-color: var(--border-hi) !important; }
    .gold-text { color: var(--gold); }
    .gold-gradient { background: var(--grad-gold); }
    .green-gradient { background: var(--grad-main); }
    .card-bg { background: rgba(24,17,41,.65); backdrop-filter: blur(14px); -webkit-backdrop-filter: blur(14px); transition: transform .15s ease, border-color .2s ease; }
    .card-bg:active { transform: scale(.97); }
    .scrollbar-none::-webkit-scrollbar { display: none; }
    .scrollbar-none { -ms-overflow-style: none; scrollbar-width: none; }
    .tab-active { background: var(--grad-main) !important; color: #fff !important; font-weight: 800; box-shadow: 0 8px 20px -8px rgba(155,93,229,.6); }

    .jackpot-box { background: linear-gradient(160deg, #1D1533 0%, #120D24 100%); border: 1px solid var(--border-hi); box-shadow: 0 20px 50px -12px rgba(108,63,197,.35); }
    .digit-box { background: #0D0918; border: 1px solid rgba(245,197,66,.3); color: var(--gold); font-family: 'Courier New', monospace; text-shadow: 0 0 8px rgba(245,197,66,.6); }
    @keyframes pulse-glow { 0%,100% { box-shadow: 0 0 20px rgba(155,93,229,.15) inset; } 50% { box-shadow: 0 0 35px rgba(155,93,229,.3) inset; } }
    .jackpot-box { animation: pulse-glow 2.5s ease-in-out infinite; }

    .game-card-hover { transition: transform 0.15s ease; }
    .game-card-hover:active { transform: scale(0.95); }
    .fav-icon { position: absolute; top: 6px; right: 6px; width: 22px; height: 22px; background: rgba(0,0,0,.5); border-radius: 50%; display: flex; align-items: center; justify-content: center; z-index: 2; }

    .float-social { position: fixed; right: 10px; top: 45%; z-index: 40; display: flex; flex-direction: column; gap: 10px; }
    .float-social a { width: 42px; height: 42px; border-radius: 50%; display: flex; align-items: center; justify-content: center; box-shadow: 0 2px 10px rgba(0,0,0,.4); }

    .bottom-nav { background: var(--card); border-top: 1px solid var(--border-hi); }
    .fade-in-up { animation: fadeInUp .3s ease both; }
    @keyframes scrollTicker { from { transform: translateX(0); } to { transform: translateX(-50%); } }
    @keyframes fadeInUp { from { opacity: 0; transform: translateY(8px); } to { opacity: 1; transform: translateY(0); } }
</style>
</head>
<body class="pb-20">

<?php include __DIR__ . '/newbonuspopup.php'; ?>
<?php include __DIR__ . '/newsitepopup.php'; ?>


<!-- ✅ App Download Banner -->
<div class="green-gradient text-center py-1.5 text-[11px] font-bold text-gray-900 flex items-center justify-center gap-2">
    <i class="fa-solid fa-download"></i> App Download করে, আরও দ্রুত খেলো!
</div>

<!-- Header -->
<header class="bg-[#181129]/80 backdrop-blur-xl border-b neon-border px-4 py-3 flex items-center justify-between sticky top-0 z-40">
    <button class="text-gray-300 text-lg"><i class="fa-solid fa-bars"></i></button>
    <div class="text-lg font-black italic gold-text tracking-wide">SPORTS<span class="neon-green">365</span></div>

    <!-- ✅ নতুন যোগ — Login না করা থাকলে, Login/Register Button দেখাবে -->
    <div id="loggedOutButtons" class="hidden items-center gap-2">
        <a href="/newlogin.php" class="text-gray-300 text-xs font-bold px-3 py-1.5">Login</a>
        <a href="/newregister.php" class="green-gradient text-white text-xs font-bold px-4 py-1.5 rounded-full">Register</a>
    </div>

    <a href="/newdeposit_panel.php" id="loggedInBadge" class="card-bg border neon-border rounded-full px-3 py-1.5 items-center gap-1.5 backdrop-blur-md">
        <i class="fa-solid fa-coins gold-text text-xs"></i>
        <span id="balanceBadge" class="text-white text-xs font-bold">...</span>
    </a>
</header>

<!-- ✅ নতুন যোগ — Deposit/Withdraw সরাসরি Homepage-এ (আসল Payment-Logo সহ) -->
<div class="px-4 pt-4 grid grid-cols-2 gap-3">
    <a href="/newdeposit_panel.php" class="card-bg border neon-border rounded-2xl p-4 flex items-center gap-3 backdrop-blur-md transition-transform active:scale-95">
        <div class="w-11 h-11 rounded-xl flex items-center justify-center overflow-hidden flex-shrink-0">
            <img src="/assets/png/rechargeIcon-efb79f43.png" alt="Deposit" class="w-full h-full object-contain p-1">
        </div>
        <div>
            <div class="text-white font-bold text-sm">Deposit</div>
            <div class="text-gray-400 text-[10px]">Instant Add</div>
        </div>
    </a>
    <a href="/newwithdraw_premium.php" class="card-bg border neon-border rounded-2xl p-4 flex items-center gap-3 backdrop-blur-md transition-transform active:scale-95">
        <div class="w-11 h-11 rounded-xl flex items-center justify-center overflow-hidden flex-shrink-0">
            <img src="/assets/png/withdrawHistory-033a34f8.png" alt="Withdraw" class="w-full h-full object-contain p-1">
        </div>
        <div>
            <div class="text-white font-bold text-sm">Withdraw</div>
            <div class="text-gray-400 text-[10px]">15-30 Min</div>
        </div>
    </a>
</div>

<main class="px-4">

    <!-- ✅ Jackpot Counter (আসল Image-Asset দিয়ে) -->
    <div class="pt-4">
        <div class="jackpot-box rounded-2xl p-4 text-center relative overflow-hidden">
            <img src="/assets/png/jackpot-banner.18b6f58e.png" alt="" class="absolute inset-0 w-full h-full object-cover opacity-40">
            <div class="relative z-10">
                <img src="/assets/png/jp-title.3e25a2ff.png" alt="Mega Jackpot" class="h-8 mx-auto mb-2">
                <div id="jackpotDigits" class="flex justify-center gap-1"></div>
            </div>
        </div>
    </div>

    <!-- ✅ Real Banner Slider (GetBannerList.php থেকে) -->
    <div class="relative rounded-xl overflow-hidden shadow-2xl my-4 border neon-border">
        <div id="bannerContainer" class="relative w-full aspect-[16/7] bg-black/30">
            <div class="absolute inset-0 flex items-center justify-center text-gray-500 text-xs">Banner লোড হচ্ছে...</div>
        </div>
        <div id="bannerDots" class="absolute bottom-2 left-1/2 -translate-x-1/2 flex gap-1.5"></div>
    </div>

    <!-- ✅ নতুন যোগ — Recent Winners Live Feed -->
    <div class="card-bg border neon-border rounded-lg mt-3 py-2 overflow-hidden">
        <div id="winnersTicker" class="flex items-center gap-2 text-xs whitespace-nowrap"></div>
    </div>

    <!-- ✅ নতুন যোগ — Big Wins Showcase (Decorative) -->
    <div class="mt-3">
        <div class="text-[11px] gold-text font-bold tracking-widest mb-2 flex items-center gap-1"><i class="fa-solid fa-fire"></i> BIG WINS</div>
        <div id="awardShowcase" class="flex gap-2.5 overflow-x-auto scrollbar-none pb-1"></div>
    </div>

    <div class="card-bg rounded-lg px-3 py-2 border neon-border flex items-center gap-2 mb-4 text-xs text-gray-300">
        <i class="fa-solid fa-volume-high neon-green animate-pulse"></i>
        <marquee behavior="scroll" direction="left" class="w-full">CV111-এ স্বাগতম! দ্রুত Deposit, দ্রুত Withdraw, ২৪/৭ Support।</marquee>
    </div>

    <!-- Category Tabs -->
    <div class="flex items-center gap-2 overflow-x-auto scrollbar-none mb-1">
        <button onclick="filterMainCategory('all')" class="cat-btn main-cat-btn tab-active text-xs font-bold px-4 py-1.5 rounded-full flex-shrink-0" data-cat="all">All</button>
        <button onclick="filterMainCategory('popular')" class="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" data-cat="popular">Popular</button>
        <button onclick="filterMainCategory('slot')" class="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" data-cat="slot">Slot</button>
        <button onclick="filterMainCategory('fish')" class="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" data-cat="fish">Fish</button>
        <button onclick="filterMainCategory('sport')" class="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" data-cat="sport">Sport</button>
        <button onclick="filterMainCategory('video')" class="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" data-cat="video">Casino</button>
    </div>

    <!-- Provider Tabs (শুধু Slot-এ দেখাবে) -->
    <div id="vendor-tabs-row" class="hidden items-center gap-1.5 overflow-x-auto scrollbar-none py-2">
        <button onclick="filterVendor('')" class="vendor-btn tab-active px-3 py-1 rounded text-xs font-bold flex-shrink-0" data-vendor="">ALL</button>
        <button onclick="filterVendor('JILI')" class="vendor-btn card-bg border neon-border text-gray-300 px-3 py-1 rounded text-xs font-bold flex-shrink-0" data-vendor="JILI">JILI</button>
        <button onclick="filterVendor('G9')" class="vendor-btn card-bg border neon-border text-gray-300 px-3 py-1 rounded text-xs font-bold flex-shrink-0" data-vendor="G9">G9</button>
        <button onclick="filterVendor('INOUT')" class="vendor-btn card-bg border neon-border text-gray-300 px-3 py-1 rounded text-xs font-bold flex-shrink-0" data-vendor="INOUT">INOUT</button>
        <button onclick="filterVendor('BGAMING')" class="vendor-btn card-bg border neon-border text-gray-300 px-3 py-1 rounded text-xs font-bold flex-shrink-0" data-vendor="BGAMING">BGaming</button>
        <button onclick="filterVendor('TURBO')" class="vendor-btn card-bg border neon-border text-gray-300 px-3 py-1 rounded text-xs font-bold flex-shrink-0" data-vendor="TURBO">Turbo</button>
        <button onclick="filterVendor('CQ9')" class="vendor-btn card-bg border neon-border text-gray-300 px-3 py-1 rounded text-xs font-bold flex-shrink-0" data-vendor="CQ9">CQ9</button>
        <button onclick="filterVendor('MG')" class="vendor-btn card-bg border neon-border text-gray-300 px-3 py-1 rounded text-xs font-bold flex-shrink-0" data-vendor="MG">MG</button>
        <button onclick="filterVendor('PG')" class="vendor-btn card-bg border neon-border text-gray-300 px-3 py-1 rounded text-xs font-bold flex-shrink-0" data-vendor="PG">PG</button>
        <button onclick="filterVendor('JDB')" class="vendor-btn card-bg border neon-border text-gray-300 px-3 py-1 rounded text-xs font-bold flex-shrink-0" data-vendor="JDB">JDB</button>
        <button onclick="filterVendor('EVO_Electronic')" class="vendor-btn card-bg border neon-border text-gray-300 px-3 py-1 rounded text-xs font-bold flex-shrink-0" data-vendor="EVO_Electronic">EVO</button>
        <button onclick="filterVendor('PP')" class="vendor-btn card-bg border neon-border text-gray-300 px-3 py-1 rounded text-xs font-bold flex-shrink-0" data-vendor="PP">PP</button>
    </div>

    <div class="flex items-center justify-between my-3">
        <h2 id="section-title" class="text-sm font-bold text-white flex items-center gap-2">
            <span class="w-2 h-5 green-gradient rounded-full inline-block"></span> All Games
        </h2>
        <span id="game-count" class="text-xs card-bg text-gray-400 px-2 py-0.5 rounded-full">লোড হচ্ছে...</span>
    </div>

    <div class="mb-3 relative">
        <input type="text" id="search-input" onkeyup="searchGames()" placeholder="Game খুঁজো..."
               class="w-full card-bg border neon-border rounded-lg px-4 py-2 pl-10 text-xs text-white placeholder-gray-500 focus:outline-none">
        <i class="fa-solid fa-magnifying-glass absolute left-3.5 top-2.5 text-gray-500 text-xs"></i>
    </div>

    <div id="vendor-back-btn" style="display:none;" class="mb-3 neon-green text-xs font-bold flex items-center gap-1 cursor-pointer"></div>

    <!-- Games Grid (৩-Column) -->
    <div id="games-grid" class="grid grid-cols-3 gap-2.5"></div>

    <button id="load-more-btn" onclick="loadMoreGames()" class="w-full mt-4 py-2.5 rounded-lg card-bg border neon-border text-gray-300 text-xs font-bold">আরও দেখাও</button>

</main>

<!-- Floating Social -->
<div class="float-social">
    <a href="https://wa.me/8801XXXXXXXXX" class="overflow-hidden" style="background:#fff;">
        <img src="/assets/png/CStype2-d7b94bf8.png" alt="WhatsApp" class="w-full h-full object-contain p-2">
    </a>
    <a href="/chatbot_widget.html" class="overflow-hidden" style="background:#fff;">
        <img src="/assets/png/customer-4afe1e50.png" alt="Support" class="w-full h-full object-contain p-2">
    </a>
    <a href="<?= htmlspecialchars($telegramLink) ?>" class="overflow-hidden" style="background:#fff;">
        <img src="/assets/png/CStype5-6b3a66e3.png" alt="Telegram" class="w-full h-full object-contain p-2">
    </a>
</div>

<!-- Bottom Nav -->
<div class="bottom-nav fixed bottom-0 left-0 right-0 py-2 px-2 flex justify-between items-center z-40">
    <a href="/newhome.php" class="neon-green flex flex-col items-center text-[10px] gap-0.5 flex-1"><i class="fa-solid fa-house text-base"></i>Home</a>
    <a href="/newpromotions.php" class="text-gray-400 flex flex-col items-center text-[10px] gap-0.5 flex-1"><i class="fa-solid fa-fire text-base"></i>Promotion</a>
    <a href="/newreferral.php" class="text-gray-400 flex flex-col items-center text-[10px] gap-0.5 flex-1"><i class="fa-solid fa-user-group text-base"></i>Invite</a>
    <a href="/newbonusterms.php" class="text-gray-400 flex flex-col items-center text-[10px] gap-0.5 flex-1"><i class="fa-solid fa-gift text-base"></i>Reward</a>
    <a href="/newprofile.php" class="text-gray-400 flex flex-col items-center text-[10px] gap-0.5 flex-1"><i class="fa-solid fa-user text-base"></i>Member</a>
</div>

<script>
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 = []; document.getElementById('games-grid').innerHTML = ''; }
    const btn = document.getElementById('load-more-btn');
    btn.textContent = 'লোড হচ্ছে...';
    try {
        const url = vendorMode
            ? '/get_vendor_games.php?vendor=' + currentVendor + '&page=' + currentPage + '&limit=15'
            : '/get_all_games_merged.php?category=' + currentCategory + '&vendor=' + currentVendor + '&page=' + currentPage + '&limit=15';
        const res = await fetch(url);
        const data = await res.json();
        allLoadedGames = allLoadedGames.concat(data.games);
        renderGames(allLoadedGames);
        currentPage++;
        btn.textContent = 'আরও দেখাও';
        btn.style.display = data.has_more ? 'block' : 'none';
        document.getElementById('game-count').innerText = data.total + ' Games';
    } catch (e) { btn.textContent = 'আবার চেষ্টা করো'; }
}
function loadMoreGames() { loadGames(false); }

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; }
    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 (currentCategory === 'slot' && !vendorMode && game.vendorCode) {
            card.onclick = () => openVendor(game.vendorCode, game.slotsName || game.vendorCode);
        } else {
            card.onclick = () => launchGame(code, name);
        }

        card.innerHTML = `
            <div class="fav-icon"><i class="fa-regular fa-heart text-white text-[10px]"></i></div>
            <div class="relative w-full aspect-square bg-black/30 overflow-hidden pointer-events-none">
                <img src="${img}" alt="${name}" class="w-full h-full object-cover pointer-events-none" onerror="this.style.display='none'">
            </div>
            <div class="px-2 py-1.5 pointer-events-none">
                <div class="text-white text-[10px] font-semibold truncate">${name}</div>
                ${vendor ? `<div class="gold-text text-[8px] font-bold mt-0.5">${vendor}</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');
    if (cat === 'slot') { vendorRow.classList.remove('hidden'); vendorRow.classList.add('flex'); }
    else { 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');
    backBtn.innerHTML = '<i class="fa-solid fa-arrow-left"></i> Slot-এ ফিরে যাও';
    backBtn.onclick = exitVendorMode;
    backBtn.style.display = 'flex';
    loadGames(true);
}

function exitVendorMode() {
    vendorMode = false;
    currentVendor = '';
    document.getElementById('vendor-back-btn').style.display = 'none';
    filterMainCategory('slot');
}

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 (!confirm(`"${gameName || 'এই Game'}" খেলতে চাও?`)) return;
    if (!token) { window.location.href = '/newlogin.php'; return; }
    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();
        if (data.code === 0 && data.data && data.data.url) window.location.href = data.data.url;
        else if (data.code === 4) { localStorage.removeItem('token'); window.location.href = '/newlogin.php'; }
        else alert('Game চালু করা যায়নি: ' + (data.msg || 'অজানা সমস্যা'));
    } catch (e) { alert('একটা সমস্যা হয়েছে, আবার চেষ্টা করো।'); }
}

loadBalance();
// ✅ নতুন যোগ — সত্যিকারের 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;

        // ✅ নতুন যোগ — নিজে থেকেই ধীরে ধীরে Scroll হতে থাকা
        let scrollPos = 0;
        setInterval(() => {
            scrollPos += 0.6;
            if (scrollPos >= container.scrollWidth / 2) scrollPos = 0;
            container.scrollLeft = scrollPos;
        }, 20);
    } catch (e) {
        document.getElementById('awardShowcase').parentElement.style.display = 'none';
    }
}

loadWinners();
loadAwardShowcase();
</script>

</body>
</html>
