<?php
$category = isset($_GET['category']) ? preg_replace('/[^a-zA-Z0-9_]/', '', $_GET['category']) : 'popular';
$title = isset($_GET['title']) ? htmlspecialchars($_GET['title']) : 'Games';
?>
<!DOCTYPE html>
<html lang="bn">
<head>
<meta charset="UTF-8">
<title><?php echo $title; ?> - CV111</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<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=Hind+Siliguri:wght@400;600;700;800;900&display=swap">
<style>
    * { box-sizing: border-box; margin: 0; padding: 0; -webkit-tap-highlight-color: transparent; }
    body {
        min-height: 100vh; font-family: 'Hind Siliguri', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
        color: #fff; background: #012222; padding-bottom: 30px;
    }
    ::-webkit-scrollbar { display: none; }

    .top {
        display: flex; align-items: center; gap: 12px; padding: 14px 16px;
        position: sticky; top: 0; z-index: 20; background: rgba(3,36,36,.9);
        backdrop-filter: blur(14px); border-bottom: 1px solid #0d7474;
    }
    .top a {
        width: 36px; height: 36px; border-radius: 12px; background: #022828; border: 1px solid #0d7474;
        display: flex; align-items: center; justify-content: center; color: #fbbf24; text-decoration: none; font-size: 15px; flex-shrink: 0;
    }
    .top h1 { flex: 1; text-align: center; font-size: 17px; font-weight: 800; padding-right: 36px; text-transform: uppercase; }

    .search-row { padding: 12px 16px 4px; }
    .search-box {
        display: flex; align-items: center; gap: 10px; background: #022828; border: 1px solid #0d7474;
        border-radius: 14px; padding: 10px 14px;
    }
    .search-box input { flex: 1; background: none; border: none; outline: none; color: #fff; font-size: 13.5px; }
    .search-box i { color: #94a3b8; font-size: 13px; }

    .grid-wrap { padding: 12px 16px; }
    .games-grid { display: grid; grid-template-columns: repeat(3, 1fr); gap: 10px; }
    @media (min-width: 768px) { .games-grid { grid-template-columns: repeat(5, 1fr); } }

    .game-card {
        position: relative; border-radius: 14px; overflow: hidden; border: 1px solid #0d7474;
        background: #022828; cursor: pointer; transition: transform .15s ease; aspect-ratio: 1/1.15;
    }
    .game-card:active { transform: scale(.94); }
    .game-card img { width: 100%; height: 100%; object-fit: cover; display: block; }
    .game-card .vendor-badge {
        position: absolute; top: 5px; right: 5px; background: rgba(0,0,0,.6); color: #fbbf24;
        font-size: 8px; font-weight: 800; padding: 2px 6px; border-radius: 5px;
    }
    .game-card .name-strip {
        position: absolute; bottom: 0; left: 0; right: 0; background: linear-gradient(0deg, rgba(0,0,0,.9), transparent);
        padding: 16px 6px 6px; font-size: 10px; font-weight: 700; color: #fff;
        white-space: nowrap; overflow: hidden; text-overflow: ellipsis;
    }
    .skeleton {
        background: linear-gradient(90deg, #022828 25%, #033838 50%, #022828 75%);
        background-size: 200% 100%; animation: shimmer 1.4s ease-in-out infinite;
    }
    @keyframes shimmer { 0% { background-position: 200% 0; } 100% { background-position: -200% 0; } }

    .load-more-btn {
        display: block; width: calc(100% - 32px); margin: 14px 16px; padding: 12px; border-radius: 12px;
        background: #022828; border: 1px solid #0d7474; color: #d1d5db; font-weight: 700; font-size: 13px; cursor: pointer;
    }
    .empty-state { grid-column: 1/-1; text-align: center; color: #6b7280; padding: 40px 0; font-size: 13px; }
    .empty-state i { font-size: 30px; display: block; margin-bottom: 10px; }
</style>
</head>
<body>

<div class="top">
    <a href="/newhome.php"><i class="fa-solid fa-arrow-left"></i></a>
    <h1><?php echo $title; ?></h1>
</div>

<div class="search-row">
    <div class="search-box">
        <i class="fa-solid fa-magnifying-glass"></i>
        <input type="text" id="searchInput" placeholder="Game খুঁজো..." onkeyup="onSearchInput()">
    </div>
</div>

<div class="grid-wrap">
    <div class="games-grid" id="gamesGrid"></div>
    <button class="load-more-btn" id="loadMoreBtn" onclick="loadMore()" style="display:none;">আরও দেখাও</button>
</div>

<script>
const category = <?php echo json_encode($category); ?>;
const jsonSource = <?php echo json_encode(isset($_GET['source']) && $_GET['source'] === 'json'); ?>;
const jsonFile = <?php echo json_encode(isset($_GET['file']) ? preg_replace('/[^a-zA-Z0-9_.\-]/', '', $_GET['file']) : ''); ?>;
let currentPage = 1;
let allGames = [];
let searchQuery = '';
const token = localStorage.getItem('token');

function showSkeleton() {
    const grid = document.getElementById('gamesGrid');
    grid.innerHTML = Array(9).fill(0).map(() => `<div class="game-card skeleton"></div>`).join('');
}

async function loadGames(reset) {
    if (reset) { currentPage = 1; allGames = []; showSkeleton(); }

    // ✅ poker.json/lottery.json/esports.json-এর মতো Static JSON
    // ফাইল থেকে হলে, শুধু একবারই লোড হবে (কোনো Pagination লাগবে না)
    if (jsonSource && jsonFile) {
        try {
            const res = await fetch('/' + jsonFile);
            const data = await res.json();
            allGames = data.games || [];
            document.getElementById('loadMoreBtn').style.display = 'none';
            renderGrid();
        } catch (e) {
            document.getElementById('gamesGrid').innerHTML = `<div class="empty-state"><i class="fa-solid fa-ghost"></i>/${jsonFile} লোড করা যায়নি।</div>`;
        }
        return;
    }

    try {
        const res = await fetch('/get_all_games_merged.php?category=' + encodeURIComponent(category) + '&page=' + currentPage + '&limit=21');
        const data = await res.json();
        allGames = allGames.concat(data.games || []);
        currentPage++;
        document.getElementById('loadMoreBtn').style.display = data.has_more ? 'block' : 'none';
        renderGrid();
    } catch (e) {
        document.getElementById('gamesGrid').innerHTML = `<div class="empty-state"><i class="fa-solid fa-ghost"></i>Game লোড করা যায়নি।</div>`;
    }
}
function loadMore() { loadGames(false); }

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

function renderGrid() {
    const grid = document.getElementById('gamesGrid');
    // ✅ শুধু আসল Playable Game রাখা হচ্ছে (যাদের gameCode/gameID/code আছে)
    let list = allGames.filter(g => (g.gameCode || g.gameID || g.code));
    if (searchQuery) {
        list = list.filter(g => (g.gameNameEn || g.gameName || g.name || g.slotsName || '').toLowerCase().includes(searchQuery));
    }
    if (list.length === 0) {
        grid.innerHTML = `<div class="empty-state"><i class="fa-solid fa-ghost"></i>কোনো Game পাওয়া যায়নি।</div>`;
        return;
    }
    grid.innerHTML = list.map(g => {
        const name = (g.gameNameEn || g.gameName || g.name || g.slotsName || 'Game');
        const img = g.imgUrl || g.imageUrl || g.img || g.image || g.vendorImg || '';
        const code = g.gameCode || g.gameID || g.code || '';
        const vendor = g.vendorCode || g.vendor || '';
        return `
            <div class="game-card" onclick="launchRealGame('${code.replace(/'/g,"\\'")}', '${name.replace(/'/g,"\\'")}')">
                <img src="${img}" alt="${name}" loading="lazy" onerror="this.style.display='none'">
                ${vendor ? `<div class="vendor-badge">${vendor}</div>` : ''}
                <div class="name-strip">${name}</div>
            </div>
        `;
    }).join('');
}

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

    const gameWindow = window.open('about:blank', '_blank');
    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">
            <style>
                *{margin:0;padding:0;box-sizing:border-box;}
                body{min-height:100vh;background:#012222;display:flex;align-items:center;justify-content:center;
                    flex-direction:column;font-family:sans-serif;color:#fff;}
                .brand{font-size:20px;font-weight:900;font-style:italic;letter-spacing:1.5px;margin-bottom:24px;color:#fbbf24;}
                .spin-box{width:60px;height:60px;border-radius:16px;background:linear-gradient(135deg,#fbbf24,#d97706);
                    display:flex;align-items:center;justify-content:center;animation:spin 1s linear infinite;margin-bottom:18px;}
                @keyframes spin{to{transform:rotate(360deg);}}
                .txt{font-weight:700;font-size:14px;}
            </style></head>
            <body>
                <div class="brand">CV111</div>
                <div class="spin-box">🎰</div>
                <div class="txt">${gameName || 'Game'} খোলা হচ্ছে...</div>
            </body></html>
        `);
        gameWindow.document.close();
    }

    fetch('/deepanshu/api/webapi/GetGameUrl.php', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json', 'Authorization': 'Bearer ' + token },
        body: JSON.stringify({ gameCode: gameCode })
    })
    .then(res => res.json())
    .then(data => {
        if (data.code === 0 && data.data && data.data.url) {
            if (gameWindow) gameWindow.location.href = data.data.url;
            else window.location.href = data.data.url;
        } 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(() => {
        if (gameWindow) gameWindow.close();
        alert('একটা সমস্যা হয়েছে, আবার চেষ্টা করো।');
    });
}

loadGames(true);
</script>

</body>
</html>
