<?php
session_start();
require_once '../config.php';

if (!isset($_SESSION['user_id'])) { header("Location: ../login.php"); exit; }

global $pdo;
// 🔥 FIXED: Balance fetching from 'users' table
$stmt = $pdo->prepare("SELECT balance FROM users WHERE id = ?");
$stmt->execute([$_SESSION['user_id']]);
$walletBalance = $stmt->fetchColumn() ?: 0.00;
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>WinGo - 91Club</title>
    
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800;900&display=swap" rel="stylesheet">
    
    <script src="https://cdn.jsdelivr.net/npm/canvas-confetti@1.6.0/dist/confetti.browser.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

    <style>
        :root {
            --green: #18b660;       
            --red: #f2413b;         
            --violet: #8e44ad;      
            --blue: #40ADF7;        
            --orange: #f39c12;      
            --bg-color: #f7f8ff;
            --text-dark: #333333;
        }
        * { font-family: 'Inter', sans-serif; -webkit-tap-highlight-color: transparent; user-select: none; }
        body { background: var(--bg-color); max-width: 480px; margin: 0 auto; min-height: 100vh; position: relative; box-shadow: 0 0 20px rgba(0,0,0,0.1); overflow-x: hidden; padding-top: 60px; padding-bottom: 20px;}

        /* RED HEADER */
        .top-red-bg { background: var(--red); padding: 15px 15px 60px; border-bottom-left-radius: 30px; border-bottom-right-radius: 30px; color: white; position: fixed; top:0; width: 100%; max-width: 480px; z-index: 1000;}
        .top-bar { display: flex; justify-content: space-between; align-items: center;}
        .top-bar i { font-size: 20px; cursor: pointer;}
        .top-bar h5 { margin: 0; font-weight: 800; font-size: 18px;}
        
        /* WALLET CARD */
        .wallet-card { background: white; border-radius: 16px; padding: 20px; margin: 25px 15px 15px; box-shadow: 0 4px 15px rgba(0,0,0,0.06); position: relative; z-index: 2; display: flex; flex-direction: column; align-items: center;}
        .wallet-card p { color: #888; font-weight: 700; font-size: 12px; margin: 0 0 5px;}
        .wallet-card h2 { color: var(--text-dark); font-weight: 900; margin: 0 0 15px; font-size: 26px;}
        .wallet-actions { display: flex; width: 100%; gap: 15px;}
        .btn-wallet { flex: 1; padding: 10px 0; text-align: center; border-radius: 30px; font-weight: 800; font-size: 14px; text-decoration: none; border: none;}
        .btn-withdraw { background: #f4f5f8; color: var(--text-dark);}
        .btn-deposit { background: var(--green); color: white; box-shadow: 0 4px 10px rgba(24, 182, 96, 0.3);}

        /* 🔥 NEW GAME MODES TABS 🔥 */
        .game-tabs { display: flex; background: white; margin: 0 15px 15px; border-radius: 12px; box-shadow: 0 4px 15px rgba(0,0,0,0.05); overflow: hidden; }
        .game-tab { flex: 1; text-align: center; padding: 12px 5px; font-size: 11px; font-weight: 800; color: #888; cursor: pointer; transition: 0.3s; display:flex; flex-direction:column; align-items:center; gap:5px; border-bottom: 3px solid transparent;}
        .game-tab i { font-size: 24px; color: #ccc; transition: 0.3s;}
        .game-tab.active { color: var(--red); border-bottom-color: var(--red); background: #fff5f5;}
        .game-tab.active i { color: var(--red); }

        /* TIMER AREA */
        .timer-area { background: white; margin: 0 15px 15px; border-radius: 16px; padding: 15px; box-shadow: 0 4px 15px rgba(0,0,0,0.05); display: flex; justify-content: space-between; align-items: center;}
        .how-to-play { color: var(--red); font-size: 11px; font-weight: 800; border: 1.5px solid var(--red); padding: 4px 12px; border-radius: 20px; display: inline-block; margin-bottom: 5px;}
        .timer-box { text-align: right;}
        .countdown { display: flex; gap: 3px; margin-top: 5px; align-items: center; justify-content: flex-end;}
        .time-digit { background: #f4f5f8; color: var(--red); width: 22px; height: 26px; display: flex; align-items: center; justify-content: center; font-size: 15px; font-weight: 900; border-radius: 4px; border: 1px solid #eee;}
        .time-colon { color: var(--red); font-weight: 900; font-size: 16px; margin: 0 2px;}

        /* BETTING AREA */
        .bet-area { background: white; margin: 0 15px 15px; border-radius: 16px; padding: 20px; box-shadow: 0 4px 15px rgba(0,0,0,0.05); position: relative;}
        
        .lock-overlay { position: absolute; top: 0; left: 0; width: 100%; height: 100%; background: rgba(255,255,255,0.7); backdrop-filter: blur(5px); z-index: 10; border-radius: 16px; display: none; align-items: center; justify-content: center; gap: 15px;}
        .lock-card { background: var(--red); color: white; font-size: 70px; font-weight: 900; padding: 10px 25px; border-radius: 15px; box-shadow: 0 8px 20px rgba(242, 65, 59, 0.4); text-shadow: 0 2px 4px rgba(0,0,0,0.3);}

        /* COLOR BUTTONS */
        .color-btns { display: flex; justify-content: space-between; gap: 10px; margin-bottom: 20px;}
        .btn-color { flex: 1; border: none; padding: 12px 0; border-radius: 8px; color: white; font-weight: 800; font-size: 14px; box-shadow: 0 4px 10px rgba(0,0,0,0.15); transition: 0.1s;}
        .btn-color:active { transform: scale(0.95); }
        .bg-green { background: var(--green); } 
        .bg-violet { background: var(--violet); } 
        .bg-red { background: var(--red); }

        /* REAL PNG NUMBERS GRID */
        .number-grid { display: grid; grid-template-columns: repeat(5, 1fr); gap: 12px; margin-bottom: 20px;}
        .num-img-btn { width: 100%; aspect-ratio: 1; object-fit: contain; cursor: pointer; transition: transform 0.1s; filter: drop-shadow(0px 4px 6px rgba(0,0,0,0.2));}
        .num-img-btn:active { transform: scale(0.85); }
        
        /* MULTIPLIERS */
        .multiplier-row { display: flex; gap: 5px; justify-content: space-between; margin-bottom: 20px;}
        .btn-mult-small { background: #f4f5f8; border: 1px solid #ddd; padding: 6px 8px; border-radius: 6px; font-size: 11px; font-weight: 800; color: #666; cursor:pointer;}
        .btn-mult-small.active { background: var(--green); color: white; border-color: var(--green);}
        
        /* BIG SMALL */
        .size-btns { display: flex; gap: 10px;}
        .btn-size { flex: 1; border: none; padding: 14px 0; border-radius: 30px; color: white; font-weight: 900; font-size: 16px; box-shadow: 0 4px 10px rgba(0,0,0,0.15);}
        .bg-big { background: var(--orange); } 
        .bg-small { background: var(--blue); }

        /* HISTORY AREA */
        .history-area { margin: 0 15px; background: white; border-radius: 16px; box-shadow: 0 4px 15px rgba(0,0,0,0.05); overflow: hidden;}
        .hist-tabs-wrapper { padding: 15px 15px 0; }
        .hist-tabs { display: flex; background: #f4f5f8; border-radius: 12px; overflow: hidden; }
        .hist-tab { flex: 1; text-align: center; padding: 12px 0; font-size: 12px; font-weight: 800; color: #888; cursor: pointer; transition: 0.3s; }
        .hist-tab.active { background: var(--red); color: white; border-radius: 12px; box-shadow: 0 4px 8px rgba(242, 65, 59, 0.3); }
        
        .hist-table-container { padding: 15px; }
        .hist-table { width: 100%; border-collapse: collapse; text-align: center; }
        .hist-table thead { background: var(--red); color: white; font-size: 12px; }
        .hist-table th { padding: 12px 5px; font-weight: 700; border: none; }
        .hist-table th:first-child { border-top-left-radius: 8px; border-bottom-left-radius: 8px; }
        .hist-table th:last-child { border-top-right-radius: 8px; border-bottom-right-radius: 8px; }
        .hist-table td { padding: 12px 5px; font-size: 12px; font-weight: 700; border-bottom: 1px solid #f0f0f0; color: #555; }
        .c-dot { width: 10px; height: 10px; border-radius: 50%; display: inline-block; box-shadow: inset 0 0 4px rgba(0,0,0,0.2);}

        /* BOTTOM BET MODAL */
        .bet-modal-overlay { position: fixed; top: 0; left: 0; width: 100%; height: 100vh; background: rgba(0,0,0,0.7); z-index: 2000; display: none; opacity: 0; transition: 0.3s; }
        .bet-modal { position: fixed; bottom: -100%; left: 50%; transform: translateX(-50%); width: 100%; max-width: 480px; background: white; border-radius: 20px 20px 0 0; z-index: 2001; transition: 0.3s cubic-bezier(0.25, 0.8, 0.25, 1); box-shadow: 0 -10px 25px rgba(0,0,0,0.2); overflow: hidden; display: flex; flex-direction: column;}
        .bet-modal.active { bottom: 0; }
        .bet-modal-overlay.active { display: block; opacity: 1; }
        
        .bm-header { padding: 15px; text-align: center; transition: background 0.3s; color: white; border-radius: 20px 20px 0 0;}
        .bm-header-title { font-size: 14px; font-weight: 700; margin-bottom: 8px;}
        .bm-header-box { background: white; color: var(--text-dark); display: inline-block; padding: 6px 30px; border-radius: 20px; font-weight: 900; font-size: 16px; box-shadow: 0 4px 10px rgba(0,0,0,0.15);}
        
        .bm-body { padding: 20px; background: white;}
        .bm-row { display: flex; justify-content: space-between; align-items: center; margin-bottom: 15px;}
        .bm-label { color: var(--text-dark); font-weight: 700; font-size: 14px;}
        
        .bm-amt-grid { display: flex; gap: 8px; flex: 1; justify-content: flex-end;}
        .bm-amt-btn { background: #f4f5f8; border: none; padding: 8px 15px; border-radius: 20px; font-weight: 800; color: #333; font-size: 13px; transition: 0.2s;}
        .bm-amt-btn.active { color: white; transition: background 0.3s;}
        
        .qty-controls { display: flex; align-items: center; gap: 5px;}
        .qty-btn { border: none; background: #f4f5f8; width: 35px; height: 35px; border-radius: 5px; font-weight: bold; color: #333; font-size: 20px;}
        .qty-input { width: 45px; text-align: center; border: none; font-weight: 900; font-size: 16px; color: var(--text-dark);}
        
        .bm-mult-row { display: flex; gap: 5px; justify-content: flex-end;}
        .bm-mult-btn { background: #f4f5f8; border: none; padding: 6px 12px; border-radius: 20px; font-size: 12px; font-weight: 800; color: #333;}
        .bm-mult-btn.active { color: white; transition: background 0.3s;}

        .bm-footer { display: flex; gap: 15px; padding: 15px 20px; background: white;}
        .bm-cancel { flex: 1; background: white; border: 1px solid #ddd; padding: 12px 0; border-radius: 30px; font-weight: 800; color: #666;}
        .bm-confirm { flex: 2; color: white; border: none; padding: 12px 0; border-radius: 30px; font-weight: 900; transition: background 0.3s; box-shadow: 0 4px 10px rgba(0,0,0,0.2);}

        /* RESULT POPUP */
        .result-overlay { position: fixed; top: 0; left: 0; width: 100%; height: 100vh; background: rgba(0,0,0,0.85); z-index: 3000; display: none; align-items: center; justify-content: center; backdrop-filter: blur(5px);}
        .result-overlay.active { display: flex; }
        
        .result-box { width: 320px; position: relative; transform: scale(0.5); opacity: 0; transition: all 0.4s cubic-bezier(0.175, 0.885, 0.32, 1.275); display: flex; flex-direction: column; align-items: center; justify-content: center;}
        .result-overlay.active .result-box { transform: scale(1); opacity: 1; }
        
        .res-content-area { width: 100%; height: 420px; background-size: contain; background-position: center; background-repeat: no-repeat; display: flex; flex-direction: column; align-items: center; padding-top: 190px; text-align: center;}
        
        .res-title-text { font-size: 26px; font-weight: 900; letter-spacing: 1px; margin-bottom: 5px; color: white;}
        .res-row { display: flex; align-items: center; justify-content: center; gap: 5px; font-size: 11px; font-weight: 800; margin-bottom: 10px; width: 100%; color: #666;}
        .res-btn { padding: 2px 8px; border-radius: 4px; font-weight: 900; color: white;}
        .res-btn-circle { width: 22px; height: 22px; border-radius: 50%; display: flex; justify-content: center; align-items: center; font-weight: 900; background: white; color: var(--text-dark); box-shadow: 0 2px 4px rgba(0,0,0,0.2);}
        
        .res-bonus-title { font-size: 16px; font-weight: 900; text-transform: uppercase; color: #d32f2f;}
        .res-amt-text { font-size: 36px; font-weight: 900; margin-bottom: 2px; color: #d32f2f;}
        .res-period-text { font-size: 11px; font-weight: 700; margin-top: 5px; color: #888;}
        
        .close-res-btn { margin-top: 20px; width: 40px; height: 40px; border-radius: 50%; border: 2px solid white; background: transparent; color: white; font-size: 20px; display: flex; justify-content: center; align-items: center; cursor: pointer;}
    </style>
</head>
<body>

    <audio id="winSound" src="https://assets.mixkit.co/active_storage/sfx/2000/2000-preview.mp3" preload="auto"></audio>
    <audio id="loseSound" src="https://assets.mixkit.co/active_storage/sfx/3136/3136-preview.mp3" preload="auto"></audio>

    <div class="top-red-bg">
        <div class="top-bar">
            <a href="../index.php" style="color:white; text-decoration:none;"><i class="fas fa-chevron-left"></i></a>
            <h5 id="siteHeaderName">91CLUB</h5>
            <i class="fas fa-volume-up" id="audioToggle"></i>
        </div>
    </div>
    <div style="height: 45px;"></div> 

    <div class="wallet-card">
        <p>Wallet balance</p>
        <h2 id="walletBal">₹<?= number_format($walletBalance, 2) ?></h2>
        <div class="wallet-actions">
            <a href="../withdraw.php" class="btn-wallet btn-withdraw">Withdraw</a>
            <a href="../deposit.php" class="btn-wallet btn-deposit">Deposit</a>
        </div>
    </div>

    <div class="game-tabs">
        <div class="game-tab" onclick="setGameMode(30, 'WinGo 30s', this)">
            <i class="fas fa-bolt"></i> <span>WinGo 30s</span>
        </div>
        <div class="game-tab active" onclick="setGameMode(60, 'WinGo 1Min', this)">
            <i class="fas fa-clock"></i> <span>WinGo 1Min</span>
        </div>
        <div class="game-tab" onclick="setGameMode(180, 'WinGo 3Min', this)">
            <i class="fas fa-stopwatch"></i> <span>WinGo 3Min</span>
        </div>
        <div class="game-tab" onclick="setGameMode(300, 'WinGo 5Min', this)">
            <i class="fas fa-hourglass-half"></i> <span>WinGo 5Min</span>
        </div>
    </div>

    <div class="timer-area">
        <div>
            <div class="how-to-play"><i class="fas fa-book-open"></i> How to play</div>
            <div id="gameModeTitle" style="font-size: 13px; color: var(--text-dark); font-weight:900; margin-top:5px;">WinGo 1Min</div>
            <div style="font-size: 11px; color: #888; font-weight:600;" id="periodId">Loading...</div>
        </div>
        <div class="timer-box">
            <div class="timer-title">Time remaining</div>
            <div class="countdown">
                <div class="time-digit" id="timeMin1">0</div>
                <div class="time-digit" id="timeMin2">0</div>
                <div class="time-colon">:</div>
                <div class="time-digit" id="timeSec1">0</div>
                <div class="time-digit" id="timeSec2">0</div>
            </div>
        </div>
    </div>

    <div class="bet-area">
        <div class="lock-overlay" id="lockScreen">
            <div class="lock-card">0</div>
            <div class="lock-card" id="lockSecCard">5</div>
        </div>
        
        <div class="color-btns">
            <button class="btn-color bg-green" onclick="openBet('Green')">Green</button>
            <button class="btn-color bg-violet" onclick="openBet('Violet')">Violet</button>
            <button class="btn-color bg-red" onclick="openBet('Red')">Red</button>
        </div>

        <div class="number-grid">
            <img src="../assets/images/wingo/num_0.png" class="num-img-btn" onclick="openBet('0')" onerror="this.outerHTML='<div class=\'num-circle n-0\' onclick=\'openBet(\'0\')\'>0</div>'">
            <img src="../assets/images/wingo/num_1.png" class="num-img-btn" onclick="openBet('1')" onerror="this.outerHTML='<div class=\'num-circle n-green\' onclick=\'openBet(\'1\')\'>1</div>'">
            <img src="../assets/images/wingo/num_2.png" class="num-img-btn" onclick="openBet('2')" onerror="this.outerHTML='<div class=\'num-circle n-red\' onclick=\'openBet(\'2\')\'>2</div>'">
            <img src="../assets/images/wingo/num_3.png" class="num-img-btn" onclick="openBet('3')" onerror="this.outerHTML='<div class=\'num-circle n-green\' onclick=\'openBet(\'3\')\'>3</div>'">
            <img src="../assets/images/wingo/num_4.png" class="num-img-btn" onclick="openBet('4')" onerror="this.outerHTML='<div class=\'num-circle n-red\' onclick=\'openBet(\'4\')\'>4</div>'">
            <img src="../assets/images/wingo/num_5.png" class="num-img-btn" onclick="openBet('5')" onerror="this.outerHTML='<div class=\'num-circle n-5\' onclick=\'openBet(\'5\')\'>5</div>'">
            <img src="../assets/images/wingo/num_6.png" class="num-img-btn" onclick="openBet('6')" onerror="this.outerHTML='<div class=\'num-circle n-red\' onclick=\'openBet(\'6\')\'>6</div>'">
            <img src="../assets/images/wingo/num_7.png" class="num-img-btn" onclick="openBet('7')" onerror="this.outerHTML='<div class=\'num-circle n-green\' onclick=\'openBet(\'7\')\'>7</div>'">
            <img src="../assets/images/wingo/num_8.png" class="num-img-btn" onclick="openBet('8')" onerror="this.outerHTML='<div class=\'num-circle n-red\' onclick=\'openBet(\'8\')\'>8</div>'">
            <img src="../assets/images/wingo/num_9.png" class="num-img-btn" onclick="openBet('9')" onerror="this.outerHTML='<div class=\'num-circle n-green\' onclick=\'openBet(\'9\')\'>9</div>'">
        </div>

        <div class="multiplier-row">
            <button class="btn-mult-small" onclick="randomBet()">Random</button>
            <button class="btn-mult-small active">X1</button>
            <button class="btn-mult-small">X5</button>
            <button class="btn-mult-small">X10</button>
            <button class="btn-mult-small">X20</button>
            <button class="btn-mult-small">X50</button>
            <button class="btn-mult-small">X100</button>
        </div>

        <div class="size-btns">
            <button class="btn-size bg-big" onclick="openBet('Big')">Big</button>
            <button class="btn-size bg-small" onclick="openBet('Small')">Small</button>
        </div>
    </div>

    <div class="history-area">
        <div class="hist-tabs-wrapper">
            <div class="hist-tabs">
                <div class="hist-tab active" id="tabGame" onclick="switchTab('game')">Game Record</div>
                <div class="hist-tab" id="tabChart" onclick="switchTab('chart')">Chart</div>
                <div class="hist-tab" id="tabMy" onclick="switchTab('my')">My Record</div>
            </div>
        </div>
        <div class="hist-table-container">
            <table class="hist-table" id="gameRecordTable">
                <thead><tr><th>Period</th><th>Number</th><th>Big Small</th><th>Color</th></tr></thead>
                <tbody id="historyTableBody"></tbody>
            </table>
            <table class="hist-table" id="myRecordTable" style="display:none;">
                <thead><tr><th>Period</th><th>Select</th><th>Amount</th><th>Status</th></tr></thead>
                <tbody id="myHistoryBody"></tbody>
            </table>
        </div>
    </div>

    <div class="result-overlay" id="resOverlay">
        <div class="result-box" id="resBox">
            
            <div class="res-content-area" id="resBgImg" style="background-image: url('../assets/images/wingo/win_popup.png');">
                <div class="res-title-text" id="resTitle">Congratulations</div>
                
                <div class="res-row" id="resRowText">
                    <span>Lottery results:</span>
                    <span class="res-btn" id="resColorBadge">Green</span>
                    <span class="res-btn-circle" id="resNumBadge">7</span>
                    <span class="res-btn" id="resSizeBadge">Small</span>
                </div>
                
                <div class="res-bonus-title" id="resBonusLabel">Bonus</div>
                <div class="res-amt-text" id="resAmount">₹0.00</div>
                <div class="res-period-text" id="resPeriodText">Period: <span id="resPeriodNumName">1 Minute</span> <span id="resPeriodNum"></span></div>
            </div>
            
            <div class="close-res-btn" onclick="document.getElementById('resOverlay').classList.remove('active')"><i class="fas fa-times"></i></div>
            
        </div>
    </div>

    <div class="bet-modal-overlay" id="betOverlay" onclick="closeBetModal()"></div>
    <div class="bet-modal" id="betModal">
        <div class="bm-header" id="bmHeader">
            <div class="bm-header-title" id="bmHeaderTitle">WinGo 1Min</div>
            <div class="bm-header-box" id="bmSelection">Select Small</div>
        </div>
        <div class="bm-body">
            <div class="bm-row">
                <div class="bm-label">Balance</div>
                <div class="bm-amt-grid">
                    <button class="bm-amt-btn active" id="btnColor1" onclick="selectAmount(1, this)">1</button>
                    <button class="bm-amt-btn" id="btnColor10" onclick="selectAmount(10, this)">10</button>
                    <button class="bm-amt-btn" id="btnColor100" onclick="selectAmount(100, this)">100</button>
                    <button class="bm-amt-btn" id="btnColor1000" onclick="selectAmount(1000, this)">1000</button>
                </div>
            </div>
            <div class="bm-row">
                <div class="bm-label">Quantity</div>
                <div class="qty-controls">
                    <button class="qty-btn" onclick="updateQty(-1)">-</button>
                    <input type="text" class="qty-input" id="betQty" value="1" readonly>
                    <button class="qty-btn" onclick="updateQty(1)">+</button>
                </div>
            </div>
            <div class="bm-row" style="margin-bottom:25px;">
                <div style="flex:1;"></div>
                <div class="bm-mult-row">
                    <button class="bm-mult-btn active" id="mBtn1" onclick="setMult(1, this)">X1</button>
                    <button class="bm-mult-btn" id="mBtn5" onclick="setMult(5, this)">X5</button>
                    <button class="bm-mult-btn" id="mBtn10" onclick="setMult(10, this)">X10</button>
                    <button class="bm-mult-btn" id="mBtn20" onclick="setMult(20, this)">X20</button>
                    <button class="bm-mult-btn" id="mBtn50" onclick="setMult(50, this)">X50</button>
                    <button class="bm-mult-btn" id="mBtn100" onclick="setMult(100, this)">X100</button>
                </div>
            </div>
            <div style="font-size:12px; color:#888; margin-bottom:15px; display:flex; align-items:center; gap:8px;"><i class="fas fa-check-circle" style="color:var(--red);"></i> I agree <span style="color:var(--red);">[Pre-sale rules]</span></div>
        </div>
        <div class="bm-footer">
            <button class="bm-cancel" onclick="closeBetModal()">Cancel</button>
            <button class="bm-confirm" id="confirmBetBtn" onclick="submitBet()">Total amount ₹<span id="totalBetDisplay">1.00</span></button>
        </div>
    </div>

    <script>
        const THEME = {
            'Green': '#18b660', 'Red': '#f2413b', 'Violet': '#8e44ad',
            'Big': '#f39c12', 'Small': '#40ADF7', 'Number': '#18b660'
        };

        window.alert = function(message) {
            Swal.fire({
                toast: true, position: 'center',
                icon: message.toLowerCase().includes('success') ? 'success' : 'error',
                title: message, showConfirmButton: false, timer: 2000,
                background: '#333', color: '#fff'
            });
        };

        let currentSelection = ''; let currentBaseAmount = 1; let currentQty = 1; let currentMult = 1;
        let currentPeriodId = ''; let lastPeriodId = ''; let isAudioEnabled = true;
        
        // 🔥 GAME DURATION STATE (Default 60 seconds)
        let gameDuration = 60; 
        let gameModeName = "WinGo 1Min";

        fetch('../gethomeseting.php').then(r=>r.json()).then(d=>{
            if(d.code===0) document.getElementById('siteHeaderName').innerText = d.data.projectName;
        });

        document.getElementById('audioToggle').addEventListener('click', function() {
            isAudioEnabled = !isAudioEnabled;
            this.className = isAudioEnabled ? 'fas fa-volume-up' : 'fas fa-volume-mute';
            alert(isAudioEnabled ? "Sound Enabled" : "Sound Muted"); 
        });

        // 🔥 FUNCTION TO SWITCH GAME MODE DYNAMICALLY 🔥
        function setGameMode(duration, name, el) {
            gameDuration = duration;
            gameModeName = name;
            
            // UI Update
            document.querySelectorAll('.game-tab').forEach(t => t.classList.remove('active'));
            el.classList.add('active');
            document.getElementById('gameModeTitle').innerText = name;
            document.getElementById('bmHeaderTitle').innerText = name;
            document.getElementById('resPeriodNumName').innerText = name;
            
            // Immediate update and reload history
            updateTimer();
            generateFakeHistory(currentPeriodId);
            fetchMyHistory();
        }

        // =====================================
        // 1. DYNAMIC TIMER LOGIC
        // =====================================
        function updateTimer() {
            const now = new Date();
            const totalSecs = (now.getHours() * 3600) + (now.getMinutes() * 60) + now.getSeconds();
            const remaining = gameDuration - (totalSecs % gameDuration);

            const d = now.getFullYear() + String(now.getMonth() + 1).padStart(2, '0') + String(now.getDate()).padStart(2, '0');
            const periodNum = Math.floor(totalSecs / gameDuration) + 1;
            
            // Generate unique period prefix based on mode
            let prefix = "1";
            if(gameDuration === 30) prefix = "0";
            if(gameDuration === 180) prefix = "3";
            if(gameDuration === 300) prefix = "5";

            currentPeriodId = d + prefix + String(periodNum).padStart(4, '0');
            document.getElementById('periodId').innerText = currentPeriodId;

            // Minutes and Seconds calculate
            let m = Math.floor(remaining / 60);
            let s = remaining % 60;

            document.getElementById('timeMin1').innerText = Math.floor(m / 10);
            document.getElementById('timeMin2').innerText = m % 10;
            document.getElementById('timeSec1').innerText = Math.floor(s / 10);
            document.getElementById('timeSec2').innerText = s % 10;

            const lockScreen = document.getElementById('lockScreen');
            const lockSecCard = document.getElementById('lockSecCard');
            
            // Lock screen for last 5 seconds of ANY mode
            if (remaining <= 5 && remaining > 0) {
                lockScreen.style.display = 'flex'; 
                lockSecCard.innerText = remaining; 
                closeBetModal(); 
            } else if (remaining === gameDuration || remaining === 0) {
                lockScreen.style.display = 'flex'; 
                lockSecCard.innerText = "0";
                let periodToFetch = d + prefix + String(periodNum - 1).padStart(4, '0');
                if(periodToFetch !== lastPeriodId) {
                    lastPeriodId = periodToFetch;
                    fetchResult(periodToFetch);
                }
            } else {
                lockScreen.style.display = 'none';
            }
        }
        setInterval(updateTimer, 1000);
        updateTimer();
        setTimeout(() => { generateFakeHistory(currentPeriodId); fetchMyHistory(); }, 500);

        // =====================================
        // 2. RESULT API & PERFECT POPUP
        // =====================================
        async function fetchResult(pId) {
            let fd = new FormData(); fd.append('period', pId);
            try {
                let res = await fetch('../getresult.php', { method:'POST', body:fd }).then(r=>r.json());
                
                generateFakeHistory(currentPeriodId);
                fetchMyHistory();

                if(res.success && res.played) {
                    const overlay = document.getElementById('resOverlay');
                    const bgDiv = document.getElementById('resBgImg');
                    
                    let num = parseInt(res.winNumber);
                    let colorHex = (num % 2 === 0) ? '#f2413b' : '#18b660'; 
                    let colorName = (num % 2 === 0) ? 'Red' : 'Green';
                    if(num === 0) { colorHex = '#8e44ad'; colorName = 'Red Violet'; }
                    if(num === 5) { colorHex = '#8e44ad'; colorName = 'Green Violet'; }

                    document.getElementById('resNumBadge').innerText = num;
                    document.getElementById('resNumBadge').style.color = colorHex;
                    document.getElementById('resColorBadge').innerText = colorName;
                    document.getElementById('resColorBadge').style.background = colorHex;
                    
                    document.getElementById('resSizeBadge').innerText = res.winSize;
                    document.getElementById('resSizeBadge').style.background = res.winSize === 'Big' ? '#f39c12' : '#40ADF7';
                    document.getElementById('resPeriodNum').innerText = pId;

                    if(res.isWin) {
                        bgDiv.style.backgroundImage = "url('../assets/images/wingo/win_popup.png')";
                        document.getElementById('resTitle').innerText = 'Congratulations';
                        document.getElementById('resTitle').style.color = '#fff';
                        
                        document.getElementById('resBonusLabel').innerText = 'Bonus';
                        document.getElementById('resBonusLabel').style.color = '#d32f2f'; 
                        
                        document.getElementById('resAmount').innerText = '₹' + parseFloat(res.winAmount).toFixed(2);
                        document.getElementById('resAmount').style.color = '#d32f2f'; 
                        
                        document.getElementById('resPeriodText').style.color = '#666'; 
                        document.getElementById('resRowText').style.display = 'flex';
                        
                        try { if(isAudioEnabled) document.getElementById('winSound').play(); } catch(e){}
                        confetti({ particleCount: 200, spread: 100, origin: { y: 0.6 }, zIndex: 4000 });

                    } else {
                        bgDiv.style.backgroundImage = "url('../assets/images/wingo/lose_popup.png')";
                        document.getElementById('resTitle').innerText = 'Sorry';
                        document.getElementById('resTitle').style.color = '#fff';
                        
                        document.getElementById('resBonusLabel').innerText = 'Loss Amount';
                        document.getElementById('resBonusLabel').style.color = '#fff'; 
                        
                        let lossAmt = res.totalBet ? parseFloat(res.totalBet).toFixed(2) : '0.00';
                        document.getElementById('resAmount').innerText = '-₹' + lossAmt;
                        document.getElementById('resAmount').style.color = '#fff';
                        
                        document.getElementById('resPeriodText').style.color = '#ddd';
                        document.getElementById('resRowText').style.display = 'none'; 
                        
                        try { if(isAudioEnabled) document.getElementById('loseSound').play(); } catch(e){}
                    }

                    document.getElementById('walletBal').innerText = "₹" + parseFloat(res.new_balance).toFixed(2);
                    overlay.classList.add('active');
                }
            } catch(e) { console.log(e); }
        }

        // =====================================
        // 3. PERFECT BOTTOM BETTING MODAL
        // =====================================
        async function openBet(sel) {
            try {
                let res = await fetch('../getallowbet.php').then(r=>r.json());
                if (!res.allowed) { alert(res.message); setTimeout(()=> window.location.href = '../deposit.php', 2000); return; }
            } catch(e) {}

            currentSelection = sel;
            let themeColor = THEME[sel] || THEME['Number'];
            
            document.getElementById('bmHeader').style.background = themeColor;
            document.getElementById('confirmBetBtn').style.background = themeColor;
            document.getElementById('bmSelection').innerText = "Select " + sel;
            document.getElementById('bmSelection').style.color = themeColor;
            
            document.querySelectorAll('.bm-amt-btn, .bm-mult-btn').forEach(b => { 
                b.style.background = '#f4f5f8'; 
                b.style.color = '#333'; 
                b.classList.remove('active');
            });
            
            let btn1 = document.getElementById('btnColor1');
            btn1.classList.add('active'); btn1.style.background = themeColor; btn1.style.color = 'white';
            
            let mBtn1 = document.getElementById('mBtn1');
            mBtn1.classList.add('active'); mBtn1.style.background = themeColor; mBtn1.style.color = 'white';

            currentBaseAmount = 1; currentMult = 1; currentQty = 1;
            document.getElementById('betQty').value = currentQty;
            calculateTotal();

            document.getElementById('betOverlay').classList.add('active');
            document.getElementById('betModal').classList.add('active');
        }

        function closeBetModal() { document.getElementById('betOverlay').classList.remove('active'); document.getElementById('betModal').classList.remove('active'); }
        
        function selectAmount(amt, el) { 
            currentBaseAmount = amt; 
            let themeColor = THEME[currentSelection] || THEME['Number'];
            document.querySelectorAll('.bm-amt-btn').forEach(btn => { btn.classList.remove('active'); btn.style.background = '#f4f5f8'; btn.style.color = '#333';});
            el.classList.add('active'); el.style.background = themeColor; el.style.color = 'white';
            calculateTotal(); 
        }

        function setMult(mult, el) {
            currentMult = mult; currentQty = mult;
            document.getElementById('betQty').value = currentQty;
            let themeColor = THEME[currentSelection] || THEME['Number'];
            document.querySelectorAll('.bm-mult-btn').forEach(btn => { btn.classList.remove('active'); btn.style.background = '#f4f5f8'; btn.style.color = '#333';});
            el.classList.add('active'); el.style.background = themeColor; el.style.color = 'white';
            calculateTotal();
        }

        function updateQty(change) { 
            if (currentQty + change >= 1) { 
                currentQty += change; document.getElementById('betQty').value = currentQty; 
                document.querySelectorAll('.bm-mult-btn').forEach(btn => { btn.classList.remove('active'); btn.style.background = '#f4f5f8'; btn.style.color = '#333';});
                calculateTotal(); 
            } 
        }
        
        function calculateTotal() { 
            document.getElementById('totalBetDisplay').innerText = (currentBaseAmount * currentQty).toFixed(2); 
        }

        async function submitBet() {
            const btn = document.getElementById('confirmBetBtn');
            const totalAmount = currentBaseAmount * currentQty;

            btn.innerText = "Processing..."; btn.disabled = true;

            let fd = new FormData();
            fd.append('period', currentPeriodId); fd.append('selection', currentSelection); fd.append('amount', totalAmount);

            try {
                let res = await fetch('../getbetting.php', { method: 'POST', body: fd }).then(r => r.json());
                if (res.success) {
                    document.getElementById('walletBal').innerText = "₹" + parseFloat(res.new_balance).toFixed(2);
                    alert("Bet Successfully Placed!"); 
                    closeBetModal(); fetchMyHistory();
                } else { alert(res.message); }
            } catch(e) { alert("Network Error."); }

            btn.innerHTML = `Total amount ₹<span id="totalBetDisplay">${totalAmount.toFixed(2)}</span>`; btn.disabled = false;
        }

        function randomBet() {
            const choices = ['Green', 'Violet', 'Red', 'Big', 'Small', '0','1','2','3','4','5','6','7','8','9'];
            openBet(choices[Math.floor(Math.random() * choices.length)]);
        }

        // =====================================
        // 4. ORIGINAL 91CLUB HISTORY
        // =====================================
        function switchTab(tab) {
            document.querySelectorAll('.hist-tab').forEach(t=>t.classList.remove('active'));
            document.getElementById('gameRecordTable').style.display = 'none'; 
            document.getElementById('myRecordTable').style.display = 'none';

            if(tab === 'game') {
                document.getElementById('tabGame').classList.add('active'); 
                document.getElementById('gameRecordTable').style.display = 'table';
            } else if (tab === 'chart') {
                document.getElementById('tabChart').classList.add('active'); 
                alert('Chart feature coming soon!');
                document.getElementById('gameRecordTable').style.display = 'table';
            } else {
                document.getElementById('tabMy').classList.add('active'); 
                document.getElementById('myRecordTable').style.display = 'table';
                fetchMyHistory();
            }
        }

        function fetchMyHistory() {
            fetch('../getbethistory.php').then(r => r.json()).then(res => {
                let html = '';
                if(res.success && res.data.length > 0) {
                    res.data.forEach(bet => {
                        // Filter history based on current game mode prefix
                        let prefix = "1";
                        if(gameDuration === 30) prefix = "0";
                        if(gameDuration === 180) prefix = "3";
                        if(gameDuration === 300) prefix = "5";
                        
                        // Assuming period ID structure YYYYMMDD[prefix]XXXX
                        let betPrefix = bet.period.substring(8, 9);
                        if(betPrefix !== prefix) return; // Skip if bet doesn't belong to current mode

                        let isPending = bet.status === 'pending';
                        let isWin = bet.status === 'win';
                        let sColor = isWin ? '#18b660' : (isPending ? '#f39c12' : '#f2413b');
                        let sText = isPending ? 'Pending' : (isWin ? '+₹'+bet.win_amount : '-₹'+bet.amount);
                        
                        html += `
                        <tr>
                            <td style="color:#666;">${bet.period.slice(-4)}</td>
                            <td><span style="background:#f4f5f8; padding:3px 8px; border-radius:4px; font-weight:800;">${bet.selection}</span></td>
                            <td style="color:var(--text-dark);">₹${bet.amount}</td>
                            <td style="color:${sColor}; font-weight:900;">${sText}</td>
                        </tr>`;
                    });
                } 
                if(html === '') { html = '<tr><td colspan="4" style="color:#a4b0be; padding:30px;">No Data Available</td></tr>'; }
                document.getElementById('myHistoryBody').innerHTML = html;
            });
        }

        function generateFakeHistory(currentPeriod) {
            let html = ''; let basePeriod = parseInt(currentPeriod) - 1;
            for(let i=0; i<10; i++) {
                let num = Math.floor(Math.random() * 10);
                let size = num >= 5 ? 'Big' : 'Small';
                let sizeColor = num >= 5 ? '#f39c12' : '#40ADF7';
                let colorHtml = '';
                let numColor = (num % 2 === 0) ? '#f2413b' : '#18b660';
                
                if(num === 0) {
                    colorHtml = '<div class="c-dot" style="background:#f2413b;"></div><div class="c-dot" style="background:#8e44ad;"></div>';
                    numColor = '#f2413b';
                } else if(num === 5) {
                    colorHtml = '<div class="c-dot" style="background:#18b660;"></div><div class="c-dot" style="background:#8e44ad;"></div>';
                    numColor = '#18b660';
                } else if(num % 2 === 0) {
                    colorHtml = '<div class="c-dot" style="background:#f2413b;"></div>';
                } else {
                    colorHtml = '<div class="c-dot" style="background:#18b660;"></div>';
                }

                html += `
                <tr>
                    <td style="color:#666;">${String(basePeriod - i).slice(-4)}</td>
                    <td style="font-weight:900; font-size:18px; color:${numColor};">${num}</td>
                    <td style="color:${sizeColor}; font-weight:700;">${size}</td>
                    <td><div style="display:flex; justify-content:center; gap:4px;">${colorHtml}</div></td>
                </tr>`;
            }
            document.getElementById('historyTableBody').innerHTML = html;
        }
    </script>
</body>
</html>