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

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

$userId = $_SESSION['user_id'];
global $pdo;

// Fetch User Info
$stmtUser = $pdo->prepare("SELECT username FROM users WHERE id = ?");
$stmtUser->execute([$userId]);
$username = $stmtUser->fetchColumn() ?: "1048000" . $userId;

// ==================================================
// AUTO-CREATE TABLES FOR GLOBAL GAME STATE
// ==================================================
try {
    $pdo->exec("CREATE TABLE IF NOT EXISTS `aviator_history` (
        `id` INT AUTO_INCREMENT PRIMARY KEY,
        `crash_point` DECIMAL(10,2),
        `created_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP
    )");
    
    $pdo->exec("CREATE TABLE IF NOT EXISTS `aviator_state` (
        `id` INT PRIMARY KEY,
        `status` VARCHAR(20),
        `start_time` DOUBLE,
        `target_multiplier` DECIMAL(10,2)
    )");
} catch(Exception $e) {}

function generateTarget() {
    $r = mt_rand() / mt_getrandmax();
    if($r < 0.4) return round(1.00 + ($r/0.4)*0.5, 2); 
    if($r < 0.7) return round(1.50 + (($r-0.4)/0.3)*1.5, 2);
    if($r < 0.9) return round(3.00 + (($r-0.7)/0.2)*5.0, 2);
    return round(8.00 + (($r-0.9)/0.1)*20.0, 2);
}

// ==================================================
// SERVER-SIDE GAME ENGINE
// ==================================================
$now = microtime(true) * 1000; 

$stmt = $pdo->query("SELECT * FROM aviator_state WHERE id=1");
$state = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$state) {
    $target = generateTarget();
    $startTime = $now + 5000;
    $pdo->exec("INSERT INTO aviator_state (id, status, start_time, target_multiplier) VALUES (1, 'waiting', $startTime, $target)");
    $state = ['status' => 'waiting', 'start_time' => $startTime, 'target_multiplier' => $target];
} else {
    $startTime = (float)$state['start_time'];
    $target = (float)$state['target_multiplier'];
    $flightDuration = log($target) / 0.00008; 
    $roundEndTime = $startTime + $flightDuration + 4000;

    if ($now >= $roundEndTime) {
        if ($target >= 1.00) {
            $pdo->prepare("INSERT INTO aviator_history (crash_point) VALUES (?)")->execute([$target]);
        }
        $newTarget = generateTarget();
        $newStartTime = $now + 5000;
        $pdo->prepare("UPDATE aviator_state SET status='waiting', start_time=?, target_multiplier=? WHERE id=1")->execute([$newStartTime, $newTarget]);
        $state = ['status' => 'waiting', 'start_time' => $newStartTime, 'target_multiplier' => $newTarget];
    } elseif ($state['status'] == 'waiting' && $now >= $startTime) {
        $pdo->exec("UPDATE aviator_state SET status='flying' WHERE id=1");
        $state['status'] = 'flying';
    } elseif ($state['status'] == 'flying' && $now >= $startTime + $flightDuration) {
        $pdo->exec("UPDATE aviator_state SET status='crashed' WHERE id=1");
        $state['status'] = 'crashed';
    }
}

$histStmt = $pdo->query("SELECT crash_point FROM aviator_history ORDER BY id DESC LIMIT 20");
$historyData = $histStmt->fetchAll(PDO::FETCH_COLUMN);

// ==================================================
// AJAX REQUESTS
// ==================================================
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    header('Content-Type: application/json');
    $action = $_POST['action'];

    if ($action === 'sync') {
        $publicState = [
            'status' => $state['status'],
            'start_time' => $state['start_time']
        ];
        if ($state['status'] === 'crashed') {
            $publicState['crash_point'] = $state['target_multiplier'];
        }
        echo json_encode(['success' => true, 'state' => $publicState, 'server_time' => $now, 'history' => $historyData]);
        exit;
    }

    if ($action === 'place_bet') {
        $amount = (float)$_POST['amount'];
        $chk = $pdo->prepare("SELECT balance FROM users WHERE id = ?");
        $chk->execute([$userId]);
        $balance = (float)$chk->fetchColumn();

        if ($balance >= $amount && $amount >= 10) {
            $pdo->prepare("UPDATE users SET balance = balance - ? WHERE id = ?")->execute([$amount, $userId]);
            $chk->execute([$userId]);
            echo json_encode(['success' => true, 'new_balance' => number_format((float)$chk->fetchColumn(), 2, '.', '')]);
        } else {
            echo json_encode(['success' => false, 'msg' => 'Insufficient Balance or Invalid Amount']);
        }
        exit;
    }

    if ($action === 'cash_out') {
        if($state['status'] !== 'flying') {
            echo json_encode(['success' => false, 'msg' => 'Wait flying phase!']); exit;
        }
        $winAmount = (float)$_POST['win_amount'];
        $pdo->prepare("UPDATE users SET balance = balance + ? WHERE id = ?")->execute([$winAmount, $userId]);
        $chk = $pdo->prepare("SELECT balance FROM users WHERE id = ?");
        $chk->execute([$userId]);
        echo json_encode(['success' => true, 'new_balance' => number_format((float)$chk->fetchColumn(), 2, '.', '')]);
        exit;
    }
    
    if ($action === 'cancel_bet') {
        if($state['status'] === 'waiting') {
            $amount = (float)$_POST['amount'];
            $pdo->prepare("UPDATE users SET balance = balance + ? WHERE id = ?")->execute([$amount, $userId]);
            $chk = $pdo->prepare("SELECT balance FROM users WHERE id = ?");
            $chk->execute([$userId]);
            echo json_encode(['success' => true, 'new_balance' => number_format((float)$chk->fetchColumn(), 2, '.', '')]);
        } else {
            echo json_encode(['success' => false, 'msg' => 'Cannot cancel while flying!']);
        }
        exit;
    }
}

$stmtBal = $pdo->prepare("SELECT balance FROM users WHERE id = ?");
$stmtBal->execute([$userId]);
$mainBalance = number_format((float)$stmtBal->fetchColumn(), 2, '.', '');
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1,user-scalable=0">
    <title>Aviator Pro</title>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
    <style>
        @import url('https://fonts.googleapis.com/css2?family=Oswald:wght@700&display=swap');

        * { box-sizing: border-box; margin: 0; padding: 0; font-family: -apple-system, Roboto, Arial, sans-serif; user-select: none; }
        html, body { height: 100%; background-color: #000; overflow-y: auto; scrollbar-width: none; color: #fff;}
        ::-webkit-scrollbar { display: none; }
        
        .start-loading { position: fixed; width: 100%; height: 100vh; top: 0; left: 0; outline: 0; text-align: center; background-color: #000; z-index: 99999; }
        .start-loading-content { position: relative; top: 50%; transform: translateY(-50%); text-align: center; }
        .loading-propeller { width: 60px; height: 60px; margin: 0 auto 15px; animation: spin 2s linear infinite; }
        .start-loading-content span { font-size: 14px; color: #e61d2d; font-weight: bold; letter-spacing: 1px;}
        @keyframes spin { 100% { transform: rotate(360deg); } }

        /* Pro UI Toasts */
        .toast {
            position: fixed; top: 20px; left: 50%; transform: translateX(-50%);
            color: #fff; padding: 12px 24px; border-radius: 8px;
            font-size: 14px; font-weight: bold; z-index: 100000;
            opacity: 0; transition: opacity 0.3s ease-in-out;
            box-shadow: 0 5px 15px rgba(0,0,0,0.5); font-family: 'Oswald', sans-serif;
            text-transform: uppercase; letter-spacing: 1px; pointer-events: none;
        }

        :root {
            --bg-dark: #000000; 
            --panel-bg: #2b2b2b; 
            --btn-green: #145c22; 
            --btn-green-dark: #0d3b15;
            --btn-red: #e61d2d; 
            --btn-red-dark: #b3101e; 
            --btn-orange: #d38000; 
            --btn-orange-dark: #a36300;
            --hist-blue: #34b4ff; 
            --hist-purple: #913fe2; 
            --hist-pink: #900113; 
        }

        #app { display: none; justify-content: center; min-height: 100vh; }
        .game-container { width: 100%; max-width: 480px; margin: 0 auto; background-color: var(--bg-dark); display: flex; flex-direction: column; position: relative; padding-bottom: 20px;}

        .header { display: flex; justify-content: space-between; align-items: center; padding: 8px 12px; background: #1c1c1e; border-bottom: 1px solid #333; }
        .logo-area { display: flex; align-items: center; gap: 8px; color: var(--btn-red); font-size: 24px; font-weight: 900; font-style: italic; font-family: 'Oswald', sans-serif;}
        .back-icon { color: #888; font-size: 18px; cursor: pointer; padding-right: 5px;}
        .help-icon { width: 18px; height: 18px; color: #aaa; border-radius: 50%; display: flex; align-items: center; justify-content: center; font-size: 11px; cursor: pointer; border: 2px solid #555;}
        .balance-area { display: flex; align-items: center; gap: 12px; }
        .balance-text { color: #28a745; font-weight: 900; font-size: 16px; }
        .menu-icon { color: #888; font-size: 22px; cursor: pointer; }

        .menu-overlay { position: absolute; top: 50px; right: 10px; width: 260px; background: #2b2b2b; border-radius: 10px; border: 1px solid #444; z-index: 2000; display: none; flex-direction: column; box-shadow: 0 5px 20px rgba(0,0,0,0.8);}
        .menu-user { display: flex; align-items: center; gap: 10px; padding: 15px; border-bottom: 1px solid #444; color: #fff;}
        .menu-user img { width: 40px; height: 40px; border-radius: 50%; } 
        .menu-user span { font-size: 14px; font-weight: bold; flex: 1; }
        .menu-item { display: flex; justify-content: space-between; align-items: center; padding: 15px; font-size: 13px; color: #ccc; border-bottom: 1px solid #444; cursor: pointer;}
        
        .switch { position: relative; display: inline-block; width: 34px; height: 18px; }
        .switch input { opacity: 0; width: 0; height: 0; }
        .slider { position: absolute; cursor: pointer; top: 0; left: 0; right: 0; bottom: 0; background-color: #555; border-radius: 34px; transition: .2s; }
        .slider:before { position: absolute; content: ""; height: 14px; width: 14px; left: 2px; bottom: 2px; background-color: white; border-radius: 50%; transition: .2s; }
        input:checked + .slider { background-color: #28a745; }
        input:checked + .slider:before { transform: translateX(16px); }

        .history-wrap { position: relative; background: #000; }
        .history-bar { display: flex; overflow-x: hidden; gap: 6px; padding: 8px 10px; align-items: center; }
        .hist-pill { padding: 4px 10px; border-radius: 15px; font-size: 12px; font-weight: 800; background: #1c1c1e; color: #fff; border: 1px solid #333; cursor: pointer;}
        .c-blue { color: var(--hist-blue); border-color: rgba(52, 180, 255, 0.3); } 
        .c-purp { color: var(--hist-purple); border-color: rgba(145, 63, 226, 0.3); } 
        .c-red { color: var(--hist-pink); border-color: rgba(203, 1, 26, 0.3); }
        
        .hist-right { position: absolute; right: 0; top: 0; height: 100%; background: #000; display: flex; align-items: center; padding: 0 10px; box-shadow: -10px 0 10px #000; cursor: pointer;}
        .hist-dropdown { position: absolute; top: 100%; left: 0; width: 100%; background: #1c1c1e; border-radius: 0 0 10px 10px; padding: 15px; display: none; z-index: 500; border: 1px solid #333; border-top: none; box-shadow: 0 10px 20px rgba(0,0,0,0.8); }
        .hist-dropdown.show { display: block; }
        .dropdown-header { display: flex; justify-content: space-between; align-items: center; font-size: 12px; color: #888; margin-bottom: 10px; padding-bottom: 10px; border-bottom: 1px solid #333; font-weight: bold;}
        .dropdown-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(50px, 1fr)); gap: 8px; max-height: 200px; overflow-y: auto;}

        .round-id { font-size: 10px; color: #666; padding: 2px 12px;}

        .screen-area { height: 260px; position: relative; background: #0b0b0c; border-radius: 12px; margin: 0 10px; border: 1px solid #333; overflow: hidden; flex-shrink: 0;}
        
        /* THE ROTATING FAN SVG (Increased Opacity to 0.3) */
        .fan-bg { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); width: 250%; height: 250%; opacity: 0.3; z-index: 0; pointer-events: none;}
        .fan-spin { animation: spin 20s linear infinite; }
        
        #gameCanvas { position: absolute; top: 0; left: 0; width: 100%; height: 100%; z-index: 1;}
        
        .multiplier-display { position: absolute; top: 45%; left: 50%; transform: translate(-50%, -50%); text-align: center; z-index: 2;}
        .huge-multiplier { font-size: 70px; font-weight: 900; font-family: 'Oswald', sans-serif; color: #fff; transition: 0.1s;}
        .crashed-text { color: var(--btn-red); font-size: 32px; font-weight: 900; display: none; margin-bottom: -10px; font-family: 'Oswald', sans-serif; text-transform: uppercase;}
        
        /* CRASH SHAKE */
        @keyframes shake { 0% { transform: translate(1px, 1px) rotate(0deg); } 20% { transform: translate(-3px, 0px) rotate(1deg); } 40% { transform: translate(1px, -1px) rotate(1deg); } 60% { transform: translate(-3px, 1px) rotate(0deg); } 80% { transform: translate(-1px, -1px) rotate(1deg); } 100% { transform: translate(1px, -2px) rotate(-1deg); } }
        .shake-anim { animation: shake 0.4s; color: var(--btn-red) !important; text-shadow: 0 4px 10px rgba(230,29,45,0.5); }

        .loading-display { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); text-align: center; z-index: 2; display: none;}
        .loading-text { color: #e61d2d; font-size: 22px; font-weight: 900; font-family: 'Oswald', sans-serif; margin-bottom: 10px;}
        .loading-bar { width: 200px; height: 6px; background: #333; margin: 0 auto; border-radius: 3px; overflow: hidden;}
        .loading-fill { height: 100%; background: var(--btn-red); width: 0%; transition: width 0.1s linear;}

        /* IMPROVED PARACHUTE DROP CASHOUT UI */
        .fly-cashout {
            position: absolute;
            background: rgba(40, 167, 69, 0.9);
            color: #fff;
            padding: 4px 10px;
            border-radius: 12px;
            font-weight: 900;
            font-family: 'Oswald', sans-serif;
            z-index: 10;
            opacity: 0;
            border: 2px solid #145c22;
            box-shadow: 0 5px 15px rgba(0,0,0,0.6);
            animation: parachuteDrop 1.5s ease-out forwards;
            pointer-events: none;
            text-align: center;
            display: flex;
            flex-direction: column;
            line-height: 1.1;
            min-width: 60px;
        }
        .fly-cashout .user { font-size: 9px; color: #d4edda; font-family: sans-serif; font-weight: bold; margin-bottom: 1px;}
        .fly-cashout .mul { font-size: 16px; color: #fff; display: block; text-shadow: 1px 1px 2px rgba(0,0,0,0.5);}
        .fly-cashout .amt { font-size: 11px; color: #e2ffe8; }
        
        @keyframes parachuteDrop {
            0% { opacity: 0; transform: translateY(0) scale(0.5); }
            15% { opacity: 1; transform: translateY(-20px) scale(1.1); }
            30% { transform: translateY(-10px) scale(1); }
            80% { opacity: 1; }
            100% { opacity: 0; transform: translateY(50px) scale(0.8); } 
        }

        /* RECTANGULAR DARK GREEN CONTROLS */
        .controls-wrapper { display: flex; flex-direction: column; gap: 8px; padding: 10px; flex-shrink: 0; }
        .bet-panel { background: var(--panel-bg); border-radius: 12px; padding: 8px; }
        .bp-tabs { display: flex; gap: 5px; margin-bottom: 8px; font-size: 12px; color: #aaa; font-weight: bold; padding-left: 5px;}
        .bp-tabs span { cursor: pointer; transition: 0.2s;}
        .bp-tabs span.active { color: #fff; }
        
        .bp-main { display: flex; gap: 10px; align-items: stretch;}
        .bp-left { flex: 1; display: flex; flex-direction: column; gap: 5px;}
        .input-row { display: flex; align-items: center; background: #121212; border-radius: 6px; padding: 2px 5px;}
        .btn-math { width: 25px; height: 25px; border-radius: 4px; background: transparent; border: 1px solid #444; color: #fff; font-size: 18px; cursor: pointer; display: flex; align-items: center; justify-content: center;}
        .bet-input { flex: 1; width: 100%; background: transparent; border: none; color: #fff; font-size: 16px; font-weight: bold; text-align: center; outline: none;}
        .quick-bets { display: flex; gap: 3px; }
        .btn-quick { background: #121212; border: 1px solid #333; color: #aaa; border-radius: 4px; flex: 1; padding: 4px 0; font-size: 11px; cursor: pointer; text-align: center;}
        
        .bp-right { flex: 1; display: flex;}
        /* EXACT SQUARE/RECTANGLE BUTTONS AS REQUESTED */
        .btn-action { width: 100%; border-radius: 8px; border: none; color: #fff; cursor: pointer; display: flex; flex-direction: column; align-items: center; justify-content: center; padding: 10px 0;}
        .btn-action:active { transform: translateY(2px); box-shadow: none !important; }
        
        .state-bet { background: var(--btn-green); box-shadow: inset 0 2px 0 rgba(255,255,255,0.1), 0 4px 0 0 var(--btn-green-dark); }
        .state-cancel { background: var(--btn-red); box-shadow: inset 0 2px 0 rgba(255,255,255,0.1), 0 4px 0 0 var(--btn-red-dark); }
        .state-cashout { background: var(--btn-orange); box-shadow: inset 0 2px 0 rgba(255,255,255,0.1), 0 4px 0 0 var(--btn-orange-dark); }
        
        .btn-action .lbl { font-size: 20px; font-weight: 900; font-family: 'Oswald', sans-serif;}
        .btn-action .lbl-sm { font-size: 12px; font-weight: bold; text-transform: uppercase; line-height: 1;}
        .btn-action .amt { font-size: 14px; font-weight: bold; }

        .auto-options { display: none; align-items: center; justify-content: space-between; margin-bottom: 8px;}
        .btn-auto-play { background: #444; color: white; border: none; padding: 5px 10px; border-radius: 5px; font-size: 10px; cursor: pointer;}
        .btn-auto-play.active { background: var(--btn-red); }
        .auto-cash-group { display: flex; align-items: center; gap: 5px; font-size: 11px; color: #aaa; font-weight: bold;}
        .auto-input { width: 50px; background: #000; border: 1px solid #444; color: #fff; border-radius: 5px; padding: 3px; text-align: center;}

        /* BOTTOM TABS & LISTS */
        .bottom-nav { display: flex; justify-content: space-between; padding: 0 10px; background: #1c1c1e; margin-top: 5px; border-radius: 10px 10px 0 0; }
        .b-tab { flex: 1; text-align: center; color: #888; padding: 10px 0; font-size: 12px; font-weight: bold; cursor: pointer;}
        .b-tab.active { color: #fff; border-bottom: 2px solid var(--btn-red);}
        
        .bets-container { flex: 1; background: #1c1c1e; padding: 10px; overflow-y: auto; scrollbar-width: none; }
        .bets-container::-webkit-scrollbar { display: none; }
        
        .bet-view { display: none; }
        .bet-view.active { display: block; }
        
        .bet-header { display: flex; justify-content: space-between; color: #666; font-size: 11px; border-bottom: 1px solid #333; padding-bottom: 5px; margin-bottom: 5px;}
        .bet-row { display: flex; justify-content: space-between; align-items: center; font-size: 12px; padding: 6px 0; font-weight: bold; color: #fff; border-bottom: 1px solid #222;}
        .bet-row.cashed-out { background: rgba(40,167,69,0.1); border: 1px solid #28a745; border-radius: 6px; padding: 6px 4px; border-bottom: none;}
        
        .bet-user { display: flex; align-items: center; gap: 5px; width: 35%; color: #aaa; font-size: 11px;}
        .bet-user img { width: 22px; height: 22px; border-radius: 50%; }
        .bet-amt { width: 20%; text-align: center; }
        .bet-mul { width: 15%; text-align: center; color: #cb011a; background: rgba(203, 1, 26, 0.1); border-radius: 10px; padding: 2px 0;}
        .bet-win { width: 30%; text-align: right; }
        
        .cashed-out .bet-mul { color: #28a745; background: transparent; }
        .cashed-out .bet-win { color: #28a745; }

        .top-headers { display: flex; gap: 10px; border-bottom: 1px solid #333; margin-bottom: 10px;}
        .top-h-btn { font-size: 12px; color: #888; padding: 5px 0; cursor: pointer;}
        .top-h-btn.active { color: var(--hist-pink); font-weight: bold;} 
    </style>
</head>
<body>

<div class="start-loading" id="startLoading">
    <div class="start-loading-content">
        <img class="loading-propeller" src="data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIxMjAiIGhlaWdodD0iMTIwIiB2aWV3Qm94PSIwIDAgMTIwIDEyMCI+CiAgICA8ZyBmaWxsPSIjRTUwNTM5IiBmaWxsLXJ1bGU9Im5vbnplcm8iPgogICAgICAgIDxwYXRoIGQ9Ik02Ny43ODUgNjcuNzdhMTAuODgyIDEwLjg4MiAwIDAgMC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><span>Connecting...</span>
    </div>
</div>

<div id="app">
    <div class="game-container">
        
        <div class="header">
            <div class="logo-area">
                <i class="fas fa-arrow-left back-icon" onclick="window.location.href='../index.php'"></i>
                Aviator 
            </div>
            <div class="balance-area">
                <div class="balance-text" id="displayBalance"><?= $mainBalance ?> INR</div>
                <i class="fas fa-bars menu-icon" onclick="toggleMenu()"></i>
            </div>
        </div>

        <div class="menu-overlay" id="menuOverlay">
            <div class="menu-user">
                <img src="data:image/svg+xml;base64,PHN2ZyB4bWxucz0naHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmcnIHZpZXdCb3g9JzAgMCAxMDAgMTAwJz48Y2lyY2xlIGN4PSc1MCcgY3k9JzUwJyByPSc1MCcgZmlsbD0nIzMzMycvPjxjaXJjbGUgY3g9JzUwJyBjeT0nNDAnIHI9JzIwJyBmaWxsPScjNzc3Jy8+PHBhdGggZD0nTTIwIDkwIEEzMCAzMCAwIDAgMSA4MCA5MCBaJyBmaWxsPScjNzc3Jy8+PC9zdmc+" alt="User">
                <span><?= htmlspecialchars($username) ?></span>
            </div>
            <div class="menu-item"><span>Sound</span> <label class="switch"><input type="checkbox" id="soundToggle" checked onchange="toggleSound(this.checked)"><span class="slider"></span></label></div>
            <div class="menu-item"><span>Music</span> <label class="switch"><input type="checkbox" checked><span class="slider"></span></label></div>
            <div class="menu-item" onclick="switchBottomTab('my'); toggleMenu();"><span>My Bet History</span> <i class="fas fa-history"></i></div>
        </div>

        <div class="history-wrap">
            <div style="display:flex; position: relative; width:100%;">
                <div class="history-bar" id="historyBar"></div>
                <div class="hist-right" onclick="toggleHistory()">
                    <i class="fas fa-history" style="color:#cb011a;"></i><i class="fas fa-caret-down" style="color:#666; margin-left:4px;"></i>
                </div>
            </div>
            <div class="hist-dropdown" id="histDropdown">
                <div class="dropdown-header">Round History <i class="fas fa-times" style="float:right; cursor:pointer; color:#fff;" onclick="toggleHistory()"></i></div>
                <div class="dropdown-grid" id="histDropdownGrid"></div>
            </div>
        </div>
        
        <div class="round-id">Round ID: <span id="roundIdText">22020757</span> <div style="color:#28a745;">Ping: 189ms</div></div>

        <div class="screen-area">
            
            <img class="fan-bg fan-spin" id="fanBg" src="data:image/svg+xml;base64, ">
            
            <canvas id="gameCanvas"></canvas>

            <div class="multiplier-display" id="mulDisplay">
                <div class="crashed-text" id="crashedText">FLEW AWAY!</div>
                <div class="huge-multiplier" id="currentMul">1.00x</div>
            </div>
            
            <div class="loading-display" id="loadDisplay">
                <img class="loading-propeller" src="data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIxMjAiIGhlaWdodD0iMTIwIiB2aWV3Qm94PSIwIDAgMTIwIDEyMCI+CiAgICA8ZyBmaWxsPSIjRTUwNTM5IiBmaWxsLXJ1bGU9Im5vbnplcm8iPgogICAgICAgIDxwYXRoIGQ9Ik02Ny43ODUgNjcuNzdhMTAuODgyIDEwLjg4MiAwIDAgMCAyLjk5NS01LjUwMmwxOC4zNy02LjM2Yy40Ny0uMTYzLjg3Ni0uNDcxIDEuMTYtLjg4bDI5LjI2My00Mi4xOGEyLjM0MyAyLjM0MyAwIDAgMC0uMjY4LTIuOTkzTDExMC4xNTMuNzA0YTIuMzQ0IDIuMzQ0IDAgMCAwLTMuMzE0IDBMOTUuNzMgMTEuODEzQzcxLjk2NS01Ljg2MSAzOC42ODMtMy41MTQgMTcuNTggMTcuNTg4YTYwLjI2IDYwLjI2IDAgMCAwLTguODI5IDExLjIxIDIuMzQzIDIuMzQzIDAgMCAwIDQuMDAxIDIuNDQxIDU1LjU3NSA1NS41NzUgMCAwIDEgOC4xNDItMTAuMzM2QzQwLjE4NCAxLjYxMyA3MC41MTItLjY4IDkyLjM3OCAxNS4xNjVsLTUuNzIgNS43MmMtOC43NDItNS45NjctMTkuMzAyLTguODM3LTI5Ljk0Ny04LjFhNDcuMzEgNDcuMzEgMCAwIDAtMzAuMTgzIDEzLjc1MSA0Ny43MjIgNDcuN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CAwIDAtLjAzNS41NzkgNi4yMiA2LjIyIDAgMCAxLTEuODEyIDMuNzY2Yy0yLjQ3IDIuNDU4LTYuNDg3IDIuNDU3LTguOTU2IDB6Ii8+CiAgICAgICAgPHBhdGggZD0iTTExMy4zNDEgODIuMDY0YTIuMzQ0IDIuMzQ0IDAgMCAwLTMuMTE1IDEuMTMxbC0uMDI2LjA1N2EyLjM0MyAyLjM0MyAwIDEgMCA0LjI2IDEuOTU1bC4wMTMtLjAyOGEyLjM0NCAyLjM0NCAwIDAgMC0xLjEzMi0zLjExNXpNNy42NSAzNS43NjVhMi4zNDMgMi4zNDMgMCAwIDAtMy4wNzIgMS4yNDFsLS4wMjEuMDVhMi4zMzggMi4zMzggMCAwIDAgMi4xNjUgMy4yMjhjLjkyMiAwIDEuOC0uNTUgMi4xNzMtMS40NTQuNS0xLjE5LS4wNTYtMi41Ni0xLjI0NS0zLjA2NXoiLz4KICAgIDwvZz4KPC9zdmc+Cg==">
                <div class="loading-text">WAITING FOR NEXT ROUND</div>
                <div class="loading-bar"><div class="loading-fill" id="loadFill"></div></div>
            </div>
        </div>

        <div class="controls-wrapper">
            
            <div class="bet-panel" id="panel1">
                <div class="bp-tabs">
                    <span class="active" onclick="switchTab(1, 'bet')">Bet</span>
                    <span onclick="switchTab(1, 'auto')">Auto</span>
                </div>
                
                <div class="auto-options" id="autoOpt1">
                    <button class="btn-auto-play" id="autoPlayBtn1" onclick="toggleAutoPlay(1)">AUTO PLAY</button>
                    <div class="auto-cash-group">
                        Auto Cash Out 
                        <label class="switch"><input type="checkbox" id="autoCash1"><span class="slider"></span></label> 
                        <input type="number" id="autoMul1" class="auto-input" value="1.50">
                    </div>
                </div>

                <div class="bp-main">
                    <div class="bp-left">
                        <div class="input-row">
                            <button class="btn-math" onclick="adjBet(1, -1)">-</button>
                            <input type="number" id="betAmt1" class="bet-input" value="10.00" readonly>
                            <button class="btn-math" onclick="adjBet(1, 1)">+</button>
                        </div>
                        <div class="quick-bets">
                            <button class="btn-quick" onclick="setBet(1, 10)">10</button>
                            <button class="btn-quick" onclick="setBet(1, 100)">100</button>
                            <button class="btn-quick" onclick="setBet(1, 500)">500</button>
                            <button class="btn-quick" onclick="setBet(1, 1000)">1,000</button>
                        </div>
                    </div>
                    <div class="bp-right">
                        <button class="btn-action state-bet" id="actionBtn1" onclick="handleAction(1)">
                            <div class="lbl">BET</div>
                            <div class="amt">10.00 INR</div>
                        </button>
                    </div>
                </div>
            </div>

            <div class="bet-panel" id="panel2">
                <div class="bp-tabs">
                    <span class="active" onclick="switchTab(2, 'bet')">Bet</span>
                    <span onclick="switchTab(2, 'auto')">Auto</span>
                </div>
                
                <div class="auto-options" id="autoOpt2">
                    <button class="btn-auto-play" id="autoPlayBtn2" onclick="toggleAutoPlay(2)">AUTO PLAY</button>
                    <div class="auto-cash-group">
                        Auto Cash Out 
                        <label class="switch"><input type="checkbox" id="autoCash2"><span class="slider"></span></label> 
                        <input type="number" id="autoMul2" class="auto-input" value="2.00">
                    </div>
                </div>

                <div class="bp-main">
                    <div class="bp-left">
                        <div class="input-row">
                            <button class="btn-math" onclick="adjBet(2, -1)">-</button>
                            <input type="number" id="betAmt2" class="bet-input" value="10.00" readonly>
                            <button class="btn-math" onclick="adjBet(2, 1)">+</button>
                        </div>
                        <div class="quick-bets">
                            <button class="btn-quick" onclick="setBet(2, 10)">10</button>
                            <button class="btn-quick" onclick="setBet(2, 100)">100</button>
                            <button class="btn-quick" onclick="setBet(2, 500)">500</button>
                            <button class="btn-quick" onclick="setBet(2, 1000)">1,000</button>
                        </div>
                    </div>
                    <div class="bp-right">
                        <button class="btn-action state-bet" id="actionBtn2" onclick="handleAction(2)">
                            <div class="lbl">BET</div>
                            <div class="amt">10.00 INR</div>
                        </button>
                    </div>
                </div>
            </div>

        </div>

        <div class="bottom-nav">
            <div class="b-tab active" onclick="switchBottomTab('all', this)">All Bets</div>
            <div class="b-tab" onclick="switchBottomTab('my', this)">My Bets</div>
            <div class="b-tab" onclick="switchBottomTab('top', this)">Top</div>
        </div>
        
        <div class="bets-container">
            <div id="view-all" class="bet-view active">
                <div style="font-size:12px; font-weight:bold; color:#fff; margin-bottom:10px;">ALL BETS <span id="allBetsCount" style="color:#aaa; font-weight:normal; margin-left:5px;">366</span></div>
                <div class="bet-header">
                    <span style="width:35%;">User</span>
                    <span style="width:20%; text-align:center;">Bet INR</span>
                    <span style="width:15%; text-align:center;">X</span>
                    <span style="width:30%; text-align:right;">Cash out INR</span>
                </div>
                <div id="fakeBetsContainer"></div>
            </div>

            <div id="view-my" class="bet-view">
                <div class="bet-header">
                    <span style="width:30%;">Date</span>
                    <span style="width:25%; text-align:center;">Bet INR</span>
                    <span style="width:15%; text-align:center;">X</span>
                    <span style="width:30%; text-align:right;">Cash out INR</span>
                </div>
                <div id="myBetsContainer">
                    <div style="text-align:center; padding:20px; color:#666; font-size:12px;">No bets placed yet.</div>
                </div>
            </div>

            <div id="view-top" class="bet-view">
                <div class="top-headers">
                    <div class="top-h-btn active">Huge Wins</div>
                    <div class="top-h-btn">Biggest Multipliers</div>
                </div>
                <div class="bet-header">
                    <span style="width:35%;">User</span>
                    <span style="width:20%; text-align:center;">Bet INR</span>
                    <span style="width:15%; text-align:center;">X</span>
                    <span style="width:30%; text-align:right;">Cash out INR</span>
                </div>
                <div id="topBetsContainer"></div>
            </div>
        </div>

    </div>
</div>

<img id="planeAsset" src="data:image/svg+xml;base64, " style="display:none;">

<script>
    // Unlock Audio API on first interaction
    document.body.addEventListener('click', () => {
        if(audioCtx && audioCtx.state === 'suspended') {
            audioCtx.resume();
        }
    }, { once: true });

    // SERVER SYNC LOGIC
    let serverTimeOffset = 0;
    let serverStartTime = 0;

    function syncWithServer() {
        let fd = new FormData(); fd.append('action', 'sync');
        fetch('', {method: 'POST', body: fd})
        .then(r => r.text())
        .then(text => {
            try {
                let data = JSON.parse(text);
                if(data.success) {
                    let localNow = Date.now();
                    serverTimeOffset = localNow - data.server_time;
                    serverStartTime = data.state.start_time;
                    
                    targetMultiplier = parseFloat(data.state.target_multiplier); 
                    
                    const bar = document.getElementById('historyBar');
                    const grid = document.getElementById('histDropdownGrid');
                    bar.innerHTML = ''; grid.innerHTML = '';
                    data.history.forEach(mul => {
                        const html = addHistoryPill(parseFloat(mul));
                        bar.insertAdjacentHTML('beforeend', html);
                        grid.insertAdjacentHTML('beforeend', html);
                    });

                    let newState = data.state.status;
                    if(newState !== gameState) {
                        gameState = newState;
                        if(gameState === 'waiting') startWaitingVisuals();
                        if(gameState === 'flying') startFlightVisuals();
                        if(gameState === 'crashed') triggerCrashVisuals();
                    }
                }
            } catch(e) {
                console.error("Server sync error (not valid JSON): ", text);
            }
        }).catch(err => console.error(err));
    }

    setInterval(syncWithServer, 1500); 
    syncWithServer();

    var wrapperScale = 1;
    handleResize();
    window.addEventListener('resize', function () {
        handleResize();
        if(document.getElementById('app').style.display === 'flex') resizeCanvas();
    });

    function handleResize() {
        var scale = 1;
        if (window.innerWidth < 300) { scale = window.innerWidth / 300; }
        if (wrapperScale != scale) { resizeBody(scale); }
    }

    function resizeBody(scale) {
        if (document.body) {
            wrapperScale = scale;
            if (wrapperScale < 1) {
                document.body.style.width = '300px';
                document.body.style.height = (1/wrapperScale * 100).toString() + '%';
            } else {
                document.body.style.width = '100%';
                document.body.style.height = 'auto'; 
            }
            document.body.style.transform = 'scale(' + wrapperScale.toString() + ')';
            document.body.style.transformOrigin = `top left`;
        }
    }

    setTimeout(() => {
        document.getElementById('startLoading').style.display = 'none';
        document.getElementById('app').style.display = 'flex';
        resizeCanvas();
        requestAnimationFrame(gameLoop);
    }, 1500);

    // ==================================================
    // SOUND SYSTEM (Web Audio API)
    // ==================================================
    const audioCtx = new (window.AudioContext || window.webkitAudioContext)();
    let isSoundEnabled = true;
    let flightOsc = null;
    let flightGain = null;

    function toggleSound(checked) {
        isSoundEnabled = checked;
        if(!checked) stopFlightSound();
    }

    function playTone(freq, type, duration, vol) {
        if(!isSoundEnabled) return;
        if (audioCtx.state === 'suspended') audioCtx.resume();
        const osc = audioCtx.createOscillator();
        const gain = audioCtx.createGain();
        osc.type = type;
        osc.frequency.setValueAtTime(freq, audioCtx.currentTime);
        gain.gain.setValueAtTime(vol, audioCtx.currentTime);
        gain.gain.exponentialRampToValueAtTime(0.01, audioCtx.currentTime + duration);
        osc.connect(gain); gain.connect(audioCtx.destination);
        osc.start(); osc.stop(audioCtx.currentTime + duration);
    }

    function playCrashSound() {
        if(!isSoundEnabled) return;
        if (audioCtx.state === 'suspended') audioCtx.resume();
        
        // Realistic Crash Boom
        const osc = audioCtx.createOscillator();
        const gain = audioCtx.createGain();
        osc.type = 'sawtooth';
        osc.frequency.setValueAtTime(100, audioCtx.currentTime);
        osc.frequency.exponentialRampToValueAtTime(10, audioCtx.currentTime + 0.5);
        gain.gain.setValueAtTime(0.5, audioCtx.currentTime);
        gain.gain.exponentialRampToValueAtTime(0.01, audioCtx.currentTime + 0.5);
        osc.connect(gain); gain.connect(audioCtx.destination);
        osc.start(); osc.stop(audioCtx.currentTime + 0.5);

        const bufferSize = audioCtx.sampleRate * 0.5;
        const buffer = audioCtx.createBuffer(1, bufferSize, audioCtx.sampleRate);
        const data = buffer.getChannelData(0);
        for (let i = 0; i < bufferSize; i++) data[i] = Math.random() * 2 - 1;
        const noise = audioCtx.createBufferSource();
        noise.buffer = buffer;
        const noiseFilter = audioCtx.createBiquadFilter();
        noiseFilter.type = 'lowpass';
        noiseFilter.frequency.value = 1000;
        const noiseGain = audioCtx.createGain();
        noiseGain.gain.setValueAtTime(1, audioCtx.currentTime);
        noiseGain.gain.exponentialRampToValueAtTime(0.01, audioCtx.currentTime + 0.5);
        noise.connect(noiseFilter); noiseFilter.connect(noiseGain); noiseGain.connect(audioCtx.destination);
        noise.start();
    }

    function playCashoutSound() {
        if(!isSoundEnabled) return;
        playTone(880, 'sine', 0.1, 0.2); 
        setTimeout(() => playTone(1108.73, 'sine', 0.3, 0.2), 100); 
    }

    function startFlightSound() {
        if(!isSoundEnabled) return;
        if (audioCtx.state === 'suspended') audioCtx.resume();
        if(flightOsc) return; 
        flightOsc = audioCtx.createOscillator();
        flightGain = audioCtx.createGain();
        flightOsc.type = 'square';
        flightOsc.frequency.setValueAtTime(45, audioCtx.currentTime); 
        flightGain.gain.setValueAtTime(0.03, audioCtx.currentTime);
        flightOsc.connect(flightGain); flightGain.connect(audioCtx.destination);
        flightOsc.start();
    }

    function updateFlightSound(multiplier) {
        if(flightOsc && isSoundEnabled) {
            let freq = 45 + (multiplier * 2.5);
            if (freq > 150) freq = 150;
            flightOsc.frequency.setTargetAtTime(freq, audioCtx.currentTime, 0.1);
        }
    }

    function stopFlightSound() {
        if(flightOsc) {
            flightOsc.stop(); flightOsc.disconnect(); flightOsc = null;
        }
    }

    // ==================================================
    // GAME ENGINE & VARIABLES
    // ==================================================
    let currentBalance = <?= empty($mainBalance) ? '0.00' : $mainBalance ?>;
    const username = "<?= htmlspecialchars($username) ?>";
    
    let gameState = 'waiting'; 
    let currentMultiplier = 1.00;
    let targetMultiplier = 1.00;
    let animFrame;
    
    let pState = { 1: 0, 2: 0 };
    let pBet = { 1: 10.00, 2: 10.00 };
    let isAutoBet = { 1: false, 2: false };
    let autoCashOutEnabled = { 1: false, 2: false };
    let autoCashMul = { 1: 1.50, 2: 2.00 };
    
    // Canvas vars
    const canvas = document.getElementById('gameCanvas');
    const ctx = canvas.getContext('2d');
    const planeImg = document.getElementById('planeAsset');
    let cw, ch;
    let historyPoints = []; 
    let globalPlaneX = 0;
    let globalPlaneY = 0;
    
    function resizeCanvas() {
        cw = canvas.parentElement.clientWidth;
        ch = canvas.parentElement.clientHeight;
        canvas.width = cw;
        canvas.height = ch;
    }

    function showToast(msg, isSuccess=true) {
        const toast = document.createElement('div');
        toast.className = 'toast';
        toast.style.background = isSuccess ? '#28a745' : '#cb011a';
        toast.innerText = msg;
        document.body.appendChild(toast);
        setTimeout(() => toast.style.opacity = 1, 10);
        setTimeout(() => {
            toast.style.opacity = 0;
            setTimeout(()=>toast.remove(), 300);
        }, 2500);
    }

    function updateBalanceUI(amt) {
        currentBalance = parseFloat(amt);
        document.getElementById('displayBalance').innerText = currentBalance.toFixed(2) + ' INR';
    }

    function toggleMenu() {
        const menu = document.getElementById('menuOverlay');
        menu.style.display = menu.style.display === 'flex' ? 'none' : 'flex';
    }

    function toggleHistory() {
        const drop = document.getElementById('histDropdown');
        drop.classList.toggle('show');
    }

    document.addEventListener('click', function(e) {
        if(!e.target.closest('.balance-area') && !e.target.closest('.menu-overlay')) {
            document.getElementById('menuOverlay').style.display = 'none';
        }
        if(!e.target.closest('.history-wrap')) {
            document.getElementById('histDropdown').classList.remove('show');
        }
    });

    function switchTab(pid, mode) {
        let panel = document.getElementById('panel' + pid);
        let tabs = panel.querySelectorAll('.bp-tabs span');
        tabs[0].classList.remove('active'); tabs[1].classList.remove('active');
        if (mode === 'bet') {
            tabs[0].classList.add('active'); document.getElementById('autoOpt'+pid).style.display = 'none';
        } else {
            tabs[1].classList.add('active'); document.getElementById('autoOpt'+pid).style.display = 'flex';
        }
    }

    function toggleAutoPlay(pid) {
        isAutoBet[pid] = !isAutoBet[pid];
        const btn = document.getElementById('autoPlayBtn'+pid);
        if(isAutoBet[pid]) { btn.classList.add('active'); btn.innerText = "STOP AUTO"; } 
        else { btn.classList.remove('active'); btn.innerText = "AUTO PLAY"; }
    }

    document.getElementById('autoCash1').addEventListener('change', (e) => autoCashOutEnabled[1] = e.target.checked);
    document.getElementById('autoCash2').addEventListener('change', (e) => autoCashOutEnabled[2] = e.target.checked);
    document.getElementById('autoMul1').addEventListener('input', (e) => autoCashMul[1] = parseFloat(e.target.value) || 1.50);
    document.getElementById('autoMul2').addEventListener('input', (e) => autoCashMul[2] = parseFloat(e.target.value) || 2.00);

    function switchBottomTab(viewName, el = null) {
        document.querySelectorAll('.b-tab').forEach(t => t.classList.remove('active'));
        document.querySelectorAll('.bet-view').forEach(v => v.classList.remove('active'));
        if(el) el.classList.add('active');
        else document.querySelectorAll('.b-tab').forEach(t => { if(t.innerText.toLowerCase().includes(viewName)) t.classList.add('active'); });
        document.getElementById('view-' + viewName).classList.add('active');
    }

    function adjBet(pid, dir) {
        if(pState[pid] !== 0) return;
        let input = document.getElementById('betAmt'+pid);
        let val = parseFloat(input.value) + (dir * 10);
        if(val < 10) val = 10;
        input.value = val.toFixed(2); pBet[pid] = val; updateBtnUI(pid);
    }
    function setBet(pid, val) {
        if(pState[pid] !== 0) return;
        document.getElementById('betAmt'+pid).value = val.toFixed(2); pBet[pid] = val; updateBtnUI(pid);
    }

    function updateBtnUI(pid) {
        const btn = document.getElementById('actionBtn'+pid);
        const state = pState[pid]; const amt = pBet[pid];
        btn.className = 'btn-action'; 
        
        if (state === 0) {
            btn.classList.add('state-bet');
            btn.innerHTML = `<div class="lbl">BET</div><div class="amt">${amt.toFixed(2)} INR</div>`;
        } else if (state === 1) {
            btn.classList.add('state-cancel');
            btn.innerHTML = `<div class="lbl-sm">Waiting next round</div><div class="lbl">CANCEL</div>`;
        } else if (state === 2) {
            btn.classList.add('state-cashout');
            let cashOutVal = (amt * currentMultiplier).toFixed(2);
            btn.innerHTML = `<div class="lbl">CASH OUT</div><div class="amt">${cashOutVal} INR</div>`;
        }
    }

    let myBetHistoryData = [];
    function addToMyBets(betAmt, mul, winAmt) {
        myBetHistoryData.unshift({ date: new Date().toLocaleTimeString(), bet: betAmt, mul: mul, win: winAmt });
        const cont = document.getElementById('myBetsContainer');
        if(myBetHistoryData.length === 1) cont.innerHTML = ''; 
        
        const isWin = winAmt > 0;
        const row = document.createElement('div');
        row.className = 'bet-row' + (isWin ? ' cashed-out' : '');
        row.innerHTML = `
            <div style="width:30%; font-size:11px; color:#aaa;">${new Date().toLocaleTimeString()}</div>
            <div style="width:25%; text-align:center;">${betAmt.toFixed(2)}</div>
            <div style="width:15%; text-align:center;">${mul > 0 ? mul.toFixed(2)+'x' : '-'}</div>
            <div style="width:30%; text-align:right;">${isWin ? winAmt.toFixed(2) : '-'}</div>
        `;
        cont.insertBefore(row, cont.firstChild);
    }

    // MODERN PARACHUTE CASHOUT BUBBLE
    function spawnCashoutBubble(user, amt, mul) {
        const wrap = document.querySelector('.screen-area');
        const bubble = document.createElement('div');
        bubble.className = 'fly-cashout';
        bubble.innerHTML = `<span class="user">${user}</span><span class="mul">${mul.toFixed(2)}x</span><span class="amt">₹${amt.toFixed(2)}</span>`;
        
        // Spawn exactly centered around the plane's tail
        bubble.style.left = (globalPlaneX - 40) + 'px';
        bubble.style.top = (globalPlaneY - 20) + 'px';
        
        wrap.appendChild(bubble);
        setTimeout(() => bubble.remove(), 1500);
    }

    function handleAction(pid) {
        let state = pState[pid]; let amt = pBet[pid];
        if (state === 0) {
            if(currentBalance < amt) { showToast("Insufficient balance", false); return; }
            let fd = new FormData(); fd.append('action', 'place_bet'); fd.append('amount', amt);
            fetch('', {method: 'POST', body: fd})
            .then(res=>res.text())
            .then(text=>{
                try {
                    let data = JSON.parse(text);
                    if(data.success) { 
                        updateBalanceUI(data.new_balance); 
                        pState[pid] = 1; // 1 means queued or ready
                        updateBtnUI(pid);
                        showToast("Bet Placed Successfully!", true);
                    } else { 
                        showToast(data.msg, false); 
                    }
                } catch(e) {
                    showToast("Server response error!", false);
                }
            }).catch(err => { showToast("Network Error!", false); });
            
        } else if (state === 1) {
            let fd = new FormData(); fd.append('action', 'cancel_bet'); fd.append('amount', amt);
            fetch('', {method: 'POST', body: fd}).then(res=>res.json()).then(data=>{
                if(data.success) { updateBalanceUI(data.new_balance); pState[pid] = 0; updateBtnUI(pid); showToast("Bet Cancelled");}
                else { showToast(data.msg, false); }
            }).catch(e => showToast("Error cancelling bet", false));
            
        } else if (state === 2) {
            if (gameState !== 'flying') return;
            let winAmt = amt * currentMultiplier;
            let fd = new FormData(); fd.append('action', 'cash_out'); 
            fd.append('win_amount', winAmt.toFixed(2));
            fd.append('multiplier', currentMultiplier.toFixed(2));
            
            fetch('', {method: 'POST', body: fd}).then(res=>res.json()).then(data=>{
                if(data.success) {
                    playCashoutSound();
                    updateBalanceUI(data.new_balance);
                    pState[pid] = 0; updateBtnUI(pid);
                    addFakeBet(username, amt, currentMultiplier, winAmt, true);
                    addToMyBets(amt, currentMultiplier, winAmt);
                    spawnCashoutBubble(username, winAmt, currentMultiplier);
                    showToast(`Cashed out: ${winAmt.toFixed(2)} INR`, true);
                } else {
                    showToast(data.msg, false);
                }
            }).catch(e => showToast("Cashout Failed!", false));
        }
    }

    // FAKE BETS
    let fakeBets = [];
    function addHistoryPill(mul) {
        let c = 'c-blue';
        if(mul >= 2 && mul < 10) c = 'c-purp';
        if(mul >= 10) c = 'c-pink';
        return `<div class="hist-pill ${c}">${mul.toFixed(2)}x</div>`;
    }

    function generateFakeBets() {
        fakeBets = [];
        document.getElementById('allBetsCount').innerText = Math.floor(300 + Math.random() * 100);
        for(let i=0; i<15; i++) {
            fakeBets.push({
                user: Math.floor(100 + Math.random()*900) + '***' + Math.floor(10 + Math.random()*90),
                bet: [10, 20, 50, 100, 200, 500, 1000, 5000][Math.floor(Math.random()*8)],
                cashedOut: false, cashOutMul: 0, targetMul: 1.05 + (Math.random() * 5) 
            });
        }
        renderFakeBets();
    }

    function updateFakeBets() {
        let changed = false;
        fakeBets.forEach(b => {
            if(!b.cashedOut && currentMultiplier >= b.targetMul) {
                b.cashedOut = true; b.cashOutMul = currentMultiplier; changed = true;
                spawnCashoutBubble(b.user, b.bet * currentMultiplier, currentMultiplier);
            }
        });
        if(changed) renderFakeBets();
    }

    function renderFakeBets() {
        const container = document.getElementById('fakeBetsContainer');
        container.innerHTML = '';
        fakeBets.sort((a, b) => b.bet - a.bet).forEach(b => {
            addFakeBet(b.user, b.bet, b.cashOutMul, b.cashedOut ? (b.bet * b.cashOutMul) : 0, false);
        });
    }

    function addFakeBet(user, bet, mul, win, isMe) {
        const container = document.getElementById('fakeBetsContainer');
        const isCashed = win > 0;
        const mulText = isCashed ? `<span style="color:#28a745; background:rgba(40,167,69,0.1); padding:2px 8px; border-radius:10px;">${mul.toFixed(2)}x</span>` : '-';
        const winText = isCashed ? `<span>${win.toFixed(2)}</span>` : '-';
        
        const row = document.createElement('div');
        row.className = 'bet-row' + (isCashed ? ' cashed-out' : '');
        if(isMe) row.style.borderLeft = '3px solid #28a745';
        
        // Use user avatar array randomly
        const av = Math.random() > 0.5 ? 'av_61.png' : 'av_71.png';

        row.innerHTML = `
            <div class="bet-user"><img src="https://dd.55dk.site/photo/${av}"><span>${user}</span></div>
            <div class="bet-amt">${bet.toFixed(2)}</div>
            <div class="bet-mul">${mulText}</div>
            <div class="bet-win">${winText}</div>
        `;
        if(isMe) container.insertBefore(row, container.firstChild);
        else container.appendChild(row);
    }

    function populateTop() {
        const c = document.getElementById('topBetsContainer');
        let d = '';
        for(let i=0; i<6; i++) {
            let b = [5350, 5000, 4000, 3780, 3390, 2610][i];
            let mul = (10 + Math.random()*50).toFixed(2);
            d += `
            <div class="bet-row">
                <div class="bet-user"><img src="https://dd.55dk.site/photo/av_61.png"><span>x***${i}</span></div>
                <div class="bet-amt">${b.toFixed(2)}</div>
                <div class="bet-mul"><span style="color:#cb011a;">${mul}x</span></div>
                <div class="bet-win"><span style="color:#cb011a;">${(b * mul).toFixed(2)}</span></div>
            </div>`;
        }
        c.innerHTML = d;
    }
    populateTop();

    // CANVAS DRAW WITH EXHAUST TRAIL
    function drawFrame() {
        ctx.clearRect(0, 0, cw, ch);
        
        if(gameState === 'flying' || gameState === 'crashed') {
            let progress = Math.min(1, (currentMultiplier - 1) / 3); 
            if(progress < 0.1) progress = 0.1;
            
            let endX = cw * 0.1 + (cw * 0.8 * progress);
            let endY = ch * 0.85 - (ch * 0.6 * progress);

            globalPlaneX = endX; 
            globalPlaneY = endY;

            // Record points for exhaust
            if(gameState === 'flying') {
                historyPoints.push({x: endX, y: endY});
                if(historyPoints.length > 20) historyPoints.shift();
            }

            // Glow Fill
            ctx.beginPath(); ctx.moveTo(0, ch); ctx.lineTo(0, ch * 0.85); ctx.quadraticCurveTo(endX * 0.5, ch * 0.85, endX, endY); ctx.lineTo(endX, ch); ctx.closePath();
            let grad = ctx.createLinearGradient(0, ch*0.2, 0, ch);
            grad.addColorStop(0, 'rgba(230, 29, 45, 0.4)'); grad.addColorStop(1, 'rgba(230, 29, 45, 0.0)');
            ctx.fillStyle = grad; ctx.fill();

            // Main Line
            ctx.beginPath(); ctx.moveTo(0, ch * 0.85); ctx.quadraticCurveTo(endX * 0.5, ch * 0.85, endX, endY); ctx.strokeStyle = '#e61d2d'; ctx.lineWidth = 4; ctx.stroke();

            // Exhaust Trail Particles
            if(gameState === 'flying') {
                for(let i=0; i<historyPoints.length; i++) {
                    ctx.beginPath();
                    ctx.arc(historyPoints[i].x - 30, historyPoints[i].y, Math.random()*4, 0, Math.PI*2);
                    ctx.fillStyle = `rgba(230, 29, 45, ${i/20})`;
                    ctx.fill();
                }
            }

            // Plane Image
            if(gameState === 'flying') {
                ctx.drawImage(planeImg, endX - 50, endY - 25, 100, 50); 
            } else {
                ctx.globalAlpha = 0.3; ctx.drawImage(planeImg, cw + 50, -50, 100, 50); ctx.globalAlpha = 1.0;
            }
        }
    }

    // STATE CONTROLLERS
    function startWaitingVisuals() {
        historyPoints = [];
        // Opacity increased here for better visibility
        document.getElementById('fanBg').style.opacity = '0.3'; 
        document.getElementById('currentMul').style.color = '#fff';
        document.getElementById('crashedText').style.display = 'none';
        document.getElementById('currentMul').classList.remove('shake-anim');
        document.getElementById('mulDisplay').style.display = 'none';
        document.getElementById('loadDisplay').style.display = 'block';
        ctx.clearRect(0,0,cw,ch);
        
        generateFakeBets();

        if(isAutoBet[1] && pState[1] === 0) handleAction(1);
        if(isAutoBet[2] && pState[2] === 0) handleAction(2);
    }

    function startFlightVisuals() {
        document.getElementById('mulDisplay').style.display = 'block';
        document.getElementById('loadDisplay').style.display = 'none';
        startFlightSound();
        if(pState[1] === 1) { pState[1] = 2; updateBtnUI(1); }
        if(pState[2] === 1) { pState[2] = 2; updateBtnUI(2); }
    }

    function triggerCrashVisuals() {
        document.getElementById('currentMul').innerText = currentMultiplier.toFixed(2) + 'x';
        document.getElementById('currentMul').classList.add('shake-anim');
        document.getElementById('crashedText').style.display = 'block';
        document.getElementById('fanBg').style.opacity = '0';
        
        stopFlightSound();
        playCrashSound();

        // If user didn't cashout, bet is lost (set state to 0). But if state is 1 (they queued bet for next round), leave it as 1!
        if(pState[1] === 2) { pState[1] = 0; updateBtnUI(1); addToMyBets(pBet[1], 0, 0); }
        if(pState[2] === 2) { pState[2] = 0; updateBtnUI(2); addToMyBets(pBet[2], 0, 0); }

        fakeBets.forEach(b => { if(!b.cashedOut) b.cashOutMul = 0; });
        renderFakeBets();
    }

    // MAIN GAME LOOP
    function gameLoop() {
        let localNow = Date.now();
        let serverNow = localNow - serverTimeOffset;

        if (gameState === 'waiting') {
            let waitElapsed = serverNow - (serverStartTime - 5000); 
            let fill = document.getElementById('loadFill');
            if(waitElapsed < 0) waitElapsed = 0;
            let percent = (waitElapsed / 5000) * 100;
            if(percent > 100) percent = 100;
            fill.style.width = percent + '%';
        }
        else if (gameState === 'flying') {
            let elapsed = serverNow - serverStartTime;
            if (elapsed < 0) elapsed = 0;

            currentMultiplier = Math.exp(0.00008 * elapsed);
            document.getElementById('currentMul').innerText = currentMultiplier.toFixed(2) + 'x';
            updateFlightSound(currentMultiplier); 
            
            if(pState[1] === 2) {
                updateBtnUI(1);
                if(autoCashOutEnabled[1] && currentMultiplier >= autoCashMul[1]) handleAction(1);
            }
            if(pState[2] === 2) {
                updateBtnUI(2);
                if(autoCashOutEnabled[2] && currentMultiplier >= autoCashMul[2]) handleAction(2);
            }

            updateFakeBets();
        }
        
        drawFrame();
        animFrame = requestAnimationFrame(gameLoop);
    }
</script>
</body>
</html>