<?php
session_start();
error_reporting(0); 

require_once __DIR__ . '/../config.php';

// Auth Check
if (!isset($_SESSION['user_id'])) {
    if (isset($_POST['action'])) {
        header('Content-Type: application/json');
        echo json_encode(['success' => false, 'message' => 'Please login first!']);
        exit;
    }
    header("Location: ../login.php");
    exit;
}

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

// PRO MULTIPLIERS
$MULTIPLIERS = [
    'easy'     => [1.01, 1.02, 1.04, 1.06, 1.09, 1.13, 1.18, 1.25, 1.35, 1.50, 1.70, 2.00, 2.40, 3.00, 3.80, 5.00, 6.50, 8.50, 11.00, 15.00, 22.00, 32.00, 45.00, 65.00, 100.00],
    'medium'   => [1.02, 1.04, 1.07, 1.11, 1.16, 1.22, 1.30, 1.45, 1.65, 1.95, 2.40, 3.00, 3.80, 5.00, 7.00, 10.00, 14.00, 20.00, 28.00, 40.00, 60.00, 90.00, 130.00, 200.00, 300.00],
    'hard'     => [1.03, 1.07, 1.12, 1.18, 1.25, 1.35, 1.50, 1.75, 2.10, 2.60, 3.30, 4.50, 6.00, 8.50, 12.00, 18.00, 28.00, 45.00, 70.00, 110.00, 180.00, 300.00, 500.00, 800.00, 1200.00],
    'hardcore' => [1.05, 1.12, 1.20, 1.30, 1.45, 1.65, 1.90, 2.30, 2.90, 3.80, 5.50, 8.00, 12.00, 18.00, 28.00, 45.00, 75.00, 130.00, 220.00, 380.00, 650.00, 1100.00, 2000.00, 3500.00, 5000.00]
];

if (isset($_POST['action'])) {
    header('Content-Type: application/json');
    
    // --- FETCH HISTORY API ---
    if ($_POST['action'] == 'get_history') {
        try {
            $stmt = $pdo->prepare("SELECT bet_amount, win_amount, multiplier, status, created_at FROM game_history WHERE user_id = ? AND game_name LIKE '%Chicken%' ORDER BY id DESC LIMIT 20");
            $stmt->execute([$user_id]);
            $history = $stmt->fetchAll(PDO::FETCH_ASSOC);
            echo json_encode(['success' => true, 'data' => $history]);
        } catch(Exception $e) {
            echo json_encode(['success' => true, 'data' => []]);
        }
        exit;
    }

    // 1. START GAME
    if ($_POST['action'] == 'start_game') {
        $bet_amount = (float)$_POST['bet_amount'];
        $difficulty = isset($_POST['difficulty']) && array_key_exists($_POST['difficulty'], $MULTIPLIERS) ? $_POST['difficulty'] : 'easy';
        
        $stmt = $pdo->prepare("SELECT balance FROM users WHERE id = ? FOR UPDATE");
        $stmt->execute([$user_id]);
        $balance = (float)$stmt->fetchColumn();
        
        if ($balance < $bet_amount || $bet_amount < 1) {
            echo json_encode(['success' => false, 'message' => 'Insufficient balance!']);
            exit;
        }
        
        $new_balance = $balance - $bet_amount;
        $pdo->prepare("UPDATE users SET balance = ? WHERE id = ?")->execute([$new_balance, $user_id]);
        
        try {
            $stmt = $pdo->prepare("SELECT setting_value FROM settings WHERE setting_key = 'chicken_win_percent'");
            $stmt->execute();
            $win_percent = (int)$stmt->fetchColumn();
        } catch(Exception $e) { $win_percent = 40; }
        if($win_percent <= 0) $win_percent = 40;

        if (rand(1, 100) <= $win_percent) {
            $crash_step = 26; 
        } else {
            $r = rand(1, 100);
            if($r < 50) $crash_step = rand(1, 5);       
            else if($r < 80) $crash_step = rand(6, 15); 
            else $crash_step = rand(16, 24);            
        }
        
        $_SESSION['cr_active_bet'] = $bet_amount;
        $_SESSION['cr_difficulty'] = $difficulty;
        $_SESSION['cr_crash_step'] = $crash_step;
        $_SESSION['cr_current_step'] = 0;
        
        echo json_encode(['success' => true, 'balance' => number_format($new_balance, 2, '.', ''), 'bet_id' => 'EBO' . time() . rand(100, 999) . 'A25']);
        exit;
    }

    // 2. NEXT STEP
    if ($_POST['action'] == 'next_step') {
        if(!isset($_SESSION['cr_active_bet'])) { echo json_encode(['status' => 'error']); exit; }
        
        $next_step = $_SESSION['cr_current_step'] + 1;
        if ($next_step >= $_SESSION['cr_crash_step']) {
            $bet_amount = $_SESSION['cr_active_bet'];
            try {
                $pdo->prepare("INSERT INTO game_history (user_id, game_name, bet_amount, win_amount, multiplier, status) VALUES (?, 'Chicken Road', ?, 0, 0, 'loss')")->execute([$user_id, $bet_amount]);
            } catch(Exception $e) {}
            unset($_SESSION['cr_active_bet']);
            echo json_encode(['status' => 'crashed']);
            exit;
        } else {
            $_SESSION['cr_current_step'] = $next_step;
            echo json_encode(['status' => 'safe']);
            exit;
        }
    }

    // 3. CASHOUT
    if ($_POST['action'] == 'cash_out') {
        if (!isset($_SESSION['cr_active_bet']) || $_SESSION['cr_current_step'] == 0) {
            echo json_encode(['success' => false]); exit;
        }
        $bet_amount = $_SESSION['cr_active_bet'];
        $multiplier = $MULTIPLIERS[$_SESSION['cr_difficulty']][$_SESSION['cr_current_step'] - 1]; 
        $win_amount = $bet_amount * $multiplier;
        
        $stmt = $pdo->prepare("SELECT balance FROM users WHERE id = ?");
        $stmt->execute([$user_id]);
        $new_balance = (float)$stmt->fetchColumn() + $win_amount;
        
        $pdo->prepare("UPDATE users SET balance = ? WHERE id = ?")->execute([$new_balance, $user_id]);
        try {
            $pdo->prepare("INSERT INTO game_history (user_id, game_name, bet_amount, win_amount, multiplier, status) VALUES (?, 'Chicken Road', ?, ?, ?, 'win')")->execute([$user_id, $bet_amount, $win_amount, $multiplier]);
        } catch(Exception $e) { }
        unset($_SESSION['cr_active_bet']);
        echo json_encode(['success' => true, 'win_amount' => $win_amount, 'balance' => number_format($new_balance, 2, '.', '')]);
        exit;
    }
}

$stmt = $pdo->prepare("SELECT balance FROM users WHERE id = ?");
$stmt->execute([$user_id]);
$user_balance = number_format((float)$stmt->fetchColumn(), 2, '.', '');
?>
<!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>Chicken Road - Pro Working</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">
    <script src="https://cdn.jsdelivr.net/npm/canvas-confetti@1.6.0/dist/confetti.browser.min.js"></script>

    <style>
        @import url('https://fonts.googleapis.com/css2?family=Inter:wght@500;700;800&family=Montserrat:wght@800;900&display=swap');

        :root {
            --bg-dark: #1E1F24; --bg-panel: #2E3035; --color-green: #28A745; --color-green-dark: #1E7E34;
            --color-yellow: #F5A623; --color-yellow-dark: #C2821A; --color-red: #ff3b30; --text-gray: #A1A3A7;
            --road-bg: #5E6064; --sidewalk: #adb5bd;
        }

        * { box-sizing: border-box; margin: 0; padding: 0; user-select: none; -webkit-tap-highlight-color: transparent;}
        body { background-color: #000; font-family: 'Inter', sans-serif; display: flex; justify-content: center; height: 100vh; overflow: hidden; color: #fff;}
        .game-wrapper { width: 100%; max-width: 450px; height: 100%; display: flex; flex-direction: column; background: var(--bg-dark); position: relative; box-shadow: 0 0 50px rgba(0,0,0,0.9); overflow: hidden;}

        /* HEADER */
        .header { height: 55px; display: flex; justify-content: space-between; align-items: center; padding: 0 15px; background: rgba(30, 31, 36, 0.95); z-index: 100; border-bottom: 1px solid #333;}
        .back-btn { color: #fff; font-size: 18px; text-decoration: none;}
        .wallet-badge { background: #132448; border: 1px solid #203A70; padding: 4px 15px; border-radius: 20px; color: #fff; font-weight: 700; font-size: 14px; display: flex; align-items: center; gap: 6px;}
        .wallet-badge i { color: #F5A623; font-size: 14px;}
        .menu-icon { width: 35px; height: 35px; background: #2E3035; border-radius: 50%; display: flex; align-items: center; justify-content: center; color: #fff; font-size: 14px; cursor: pointer;}

        /* MENU MODAL */
        .menu-modal { display: none; position: absolute; top: 60px; right: 15px; width: 180px; background: var(--bg-panel); border-radius: 12px; z-index: 200; border: 1px solid #444; box-shadow: 0 10px 30px rgba(0,0,0,0.8); overflow: hidden; }
        .menu-item { display: flex; align-items: center; gap: 12px; padding: 15px 20px; color: var(--text-gray); font-size: 14px; font-weight: 700; cursor: pointer; border-bottom: 1px solid #444; }
        .menu-item:last-child { border-bottom: none; }
        .menu-item:active { background: #3d4047; color: #fff;}
        .switch-toggle { width: 34px; height: 18px; background: #555; border-radius: 10px; position: relative; margin-left: auto; transition: 0.3s; }
        .switch-toggle::after { content:''; position: absolute; right: 2px; top: 2px; width: 14px; height: 14px; background: #fff; border-radius: 50%; }
        .sound-on { background: var(--color-green) !important;}

        /* HISTORY MODAL (NEW) */
        .history-modal { display: none; position: absolute; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.8); z-index: 300; flex-direction: column; align-items: center; justify-content: flex-end; }
        .history-content { width: 100%; height: 75%; background: var(--bg-dark); border-top-left-radius: 20px; border-top-right-radius: 20px; padding: 20px; display: flex; flex-direction: column; animation: slideUp 0.3s ease-out; }
        @keyframes slideUp { from { transform: translateY(100%); } to { transform: translateY(0); } }
        .history-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 15px; }
        .history-header h4 { margin: 0; font-family: 'Montserrat', sans-serif; font-weight: 800; font-size: 18px; color: #fff; }
        .close-history { color: var(--text-gray); font-size: 20px; cursor: pointer; }
        .history-list { flex: 1; overflow-y: auto; padding-bottom: 20px; }
        .hist-card { background: var(--bg-panel); border-radius: 10px; padding: 12px 15px; margin-bottom: 10px; display: flex; justify-content: space-between; align-items: center; border-left: 4px solid transparent;}
        .hist-card.win { border-left-color: var(--color-green); }
        .hist-card.loss { border-left-color: var(--color-red); }
        .hist-left div { font-size: 11px; color: var(--text-gray); margin-bottom: 4px;}
        .hist-left span { font-weight: 800; font-size: 15px; color: #fff; }
        .hist-right { text-align: right; }
        .hist-right .mult { font-size: 12px; font-weight: 700; color: #fff; background: #444; padding: 2px 8px; border-radius: 4px; margin-bottom: 5px; display: inline-block;}
        .hist-right .amt.win { color: var(--color-green); font-weight: 800; font-size: 16px; }
        .hist-right .amt.loss { color: var(--color-red); font-weight: 800; font-size: 16px; }

        /* VIEWPORT */
        .viewport { flex: 1; position: relative; background: var(--road-bg); overflow: hidden; display: flex; align-items: center;}
        .road-slider { position: absolute; left: 0; height: 100%; display: flex; transition: transform 0.4s cubic-bezier(0.25, 0.8, 0.25, 1); padding-right: 150px; }
        .sidewalk-start { width: 150px; height: 100%; background: var(--sidewalk); border-right: 6px solid #495057; flex-shrink: 0; position: relative; }
        .lane { width: 150px; height: 100%; position: relative; display: flex; justify-content: center; align-items: center; flex-shrink: 0;}
        .dashed-line { position: absolute; right: 0; top: -100%; height: 300%; width: 6px; z-index: 1; background: repeating-linear-gradient(to bottom, transparent 0, transparent 30px, rgba(255,255,255,0.7) 30px, rgba(255,255,255,0.7) 70px); }
        .scrolling-line { animation: scrollRoad 0.6s linear infinite; }
        @keyframes scrollRoad { 100% { transform: translateY(100px); } }

        .manhole { width: 90px; height: 90px; border-radius: 50%; background: #484a4f; border: 6px solid #3c3e42; box-shadow: inset 0 0 15px rgba(0,0,0,0.6), 0 5px 10px rgba(0,0,0,0.3); display: flex; justify-content: center; align-items: center; position: relative; z-index: 3; transition: all 0.3s ease; }
        .manhole::before { content: ''; position: absolute; width: 100%; height: 100%; background: repeating-linear-gradient(to right, transparent 0, transparent 10px, rgba(0,0,0,0.3) 10px, rgba(0,0,0,0.3) 16px); z-index: 1;}
        .manhole-text { position: relative; z-index: 2; font-family: 'Montserrat', sans-serif; font-weight: 800; font-size: 16px; color: #ced4da; text-shadow: 1px 1px 2px #000;}
        .manhole.active { border-color: #ced4da; transform: scale(1.1); }
        .manhole.passed { border-color: #ced4da; transform: scale(1); }
        .manhole.danger { border-color: var(--color-red); box-shadow: 0 0 20px rgba(255, 59, 48, 0.8); }
        .lane.last-lane .manhole { background: radial-gradient(circle, #FDE047, #D97706); border-color: #fff; box-shadow: 0 0 30px rgba(245,158,11,0.8); }
        .lane.last-lane .manhole-text { color: #fff; font-size: 20px;}

        /* ACTORS */
        .actor-layer { position: absolute; left: 0; top: 0; width: 100%; height: 100%; z-index: 20; pointer-events: none;}
        #chicken { position: absolute; left: 35px; top: 58%; transform: translateY(-50%); width: 70px; height: 70px; transition: 0.3s; filter: drop-shadow(0 15px 10px rgba(0,0,0,0.5)); }
        .anim-jump { animation: jumpArc 0.4s ease-in-out; }
        @keyframes jumpArc { 0% { transform: translateY(-50%) scale(1); } 50% { transform: translateY(-130px) scale(1.2); } 100% { transform: translateY(-50%) scale(1); } }
        .anim-dead { transform: translateY(-40%) scale(1.3) rotate(90deg) !important; filter: grayscale(100%); }

        #car { position: absolute; width: 65px; height: 140px; top: -200px; left: 40px; z-index: 25; display: none; filter: drop-shadow(0 20px 15px rgba(0,0,0,0.6)); }
        .anim-crash-drive { display: block !important; animation: crashDrive 0.35s cubic-bezier(0.4, 0, 1, 1) forwards; }
        @keyframes crashDrive { 0% { top: -200px; } 100% { top: calc(58% - 60px); } }

        /* TOAST */
        .hud-toast { position: absolute; top: 30%; left: 50%; transform: translate(-50%, -50%) scale(0); background: rgba(30, 31, 36, 0.95); padding: 15px 40px; border-radius: 12px; font-family: 'Montserrat', sans-serif; font-size: 28px; font-weight: 900; color: #fff; border: 3px solid; z-index: 100; box-shadow: 0 20px 40px rgba(0,0,0,0.8); transition: all 0.3s; text-align: center; }
        .hud-toast.show { transform: translate(-50%, -50%) scale(1); }

        /* CONTROLS */
        .controls { background: var(--bg-dark); padding: 15px 20px 25px; z-index: 30;}
        .bet-info { display: flex; justify-content: space-between; font-size: 11px; font-weight: 700; color: var(--text-gray); margin-bottom: 12px;}
        .fair-text { color: var(--color-green); display: flex; align-items: center; gap: 4px;}
        
        .input-wrapper { display: flex; background: var(--bg-panel); border-radius: 8px; padding: 4px; margin-bottom: 15px;}
        .bet-btn { background: transparent; color: var(--text-gray); border: none; width: 45px; height: 45px; font-weight: 900; font-size: 24px; cursor: pointer;}
        .bet-input-box { flex: 1; display: flex; justify-content: center; align-items: center; }
        .bet-input { background: transparent; border: none; color: #fff; font-family: 'Inter', sans-serif; font-size: 20px; font-weight: 800; text-align: center; outline: none; width: 80px;}
        .bet-currency { color: var(--text-gray); font-size: 14px; font-weight: 700; margin-left: 5px; margin-top: 3px;}
        
        .divider { width: 1px; background: #3c3e42; margin: 5px 10px; }
        .multi-btns { display: flex; gap: 5px; align-items: center; padding-right: 5px;}
        .m-btn { background: transparent; color: var(--text-gray); border: none; font-weight: 700; font-size: 15px; cursor: pointer; padding: 0 10px;}
        .m-btn:active { color: #fff;}

        .diff-tabs { display: flex; gap: 8px; margin-bottom: 20px;}
        .diff-tab { flex: 1; background: var(--bg-panel); border: 1px solid transparent; color: var(--text-gray); font-size: 11px; font-weight: 700; padding: 10px 0; border-radius: 6px; cursor: pointer; transition: 0.2s; text-align: center; text-transform: capitalize;}
        .diff-tab.active { background: #363940; color: #fff; border-color: #4a4d54;}

        .action-area { height: 60px; position: relative;}
        .btn-massive { width: 100%; height: 100%; background: var(--color-green); color: #fff; border: none; border-radius: 8px; font-family: 'Montserrat', sans-serif; font-size: 22px; font-weight: 800; cursor: pointer; box-shadow: 0 5px 0 var(--color-green-dark); transition: 0.1s;}
        .btn-massive:active { transform: translateY(5px); box-shadow: 0 0 0 var(--color-green-dark); }
        .btn-massive:disabled { background: var(--bg-panel); color: var(--text-gray); box-shadow: 0 5px 0 #1a1b1f; cursor: not-allowed;}

        .play-grid { display: none; height: 100%; gap: 15px;}
        .btn-cashout { flex: 1; background: var(--color-yellow); color: #000; border: none; border-radius: 8px; font-family: 'Montserrat', sans-serif; font-weight: 900; font-size: 20px; box-shadow: 0 5px 0 var(--color-yellow-dark); display: flex; flex-direction: column; align-items: center; justify-content: center; line-height: 1.1; transition: 0.1s;}
        .btn-cashout small { font-size: 13px; font-family: 'Inter'; font-weight: 700;}
        .btn-go { flex: 1; background: var(--color-green); color: #fff; border: none; border-radius: 8px; font-family: 'Montserrat', sans-serif; font-size: 26px; font-weight: 900; box-shadow: 0 5px 0 var(--color-green-dark); display: flex; align-items: center; justify-content: center; transition: 0.1s;}
        .btn-cashout:active, .btn-go:active { transform: translateY(5px); box-shadow: none;}
        .btn-go:disabled { background: var(--bg-panel); color: var(--text-gray); box-shadow: 0 5px 0 #1a1b1f; }
    </style>
</head>
<body>

    <audio id="aud-jump" src="https://assets.mixkit.co/active_storage/sfx/2568/2568-preview.mp3"></audio>
    <audio id="aud-crash" src="https://assets.mixkit.co/active_storage/sfx/1468/1468-preview.mp3"></audio>
    <audio id="aud-win" src="https://assets.mixkit.co/active_storage/sfx/2013/2013-preview.mp3"></audio>

    <div class="game-wrapper">
        <div class="header">
            <a href="../index.php" class="back-btn"><i class="fas fa-chevron-left"></i></a>
            <div class="wallet-badge"><i class="fas fa-coins"></i> ₹<span id="uiBalance"><?php echo $user_balance; ?></span></div>
            <div class="menu-icon" onclick="GameEngine.toggleMenu()"><i class="fas fa-bars"></i></div>
        </div>

        <div class="menu-modal" id="menuModal">
            <div class="menu-item" onclick="GameEngine.toggleSound()">
                <i class="fas fa-volume-up"></i> Sound
                <div class="switch-toggle sound-on" id="soundToggle"></div>
            </div>
            <div class="menu-item" onclick="GameEngine.openHistory()"><i class="fas fa-history"></i> My Bets</div>
        </div>

        <div class="history-modal" id="historyModal">
            <div class="history-content">
                <div class="history-header">
                    <h4><i class="fas fa-history text-warning"></i> Bet History</h4>
                    <i class="fas fa-times close-history" onclick="GameEngine.closeHistory()"></i>
                </div>
                <div class="history-list" id="historyList">
                    </div>
            </div>
        </div>

        <div class="viewport" id="viewportArea">
            <div class="road-slider" id="roadSlider"></div>

            <div class="actor-layer">
                <div id="chicken">
                    <svg viewBox="0 0 100 100" width="100%" height="100%">
                        <circle cx="50" cy="55" r="35" fill="#fff" stroke="#000" stroke-width="4"/>
                        <path d="M 25 50 Q 10 50 15 70 Q 25 75 35 65 Z" fill="#fff" stroke="#000" stroke-width="3"/>
                        <path d="M 60 25 Q 75 25 80 40 Q 60 50 50 40 Z" fill="#ff3b30" stroke="#000" stroke-width="2"/>
                        <circle cx="65" cy="45" r="5" fill="#000"/>
                        <path d="M 80 50 L 95 55 L 80 60 Z" fill="#facc15" stroke="#000" stroke-width="2"/>
                        <path d="M 75 60 Q 75 75 65 70 Z" fill="#ff3b30" stroke="#000" stroke-width="2"/>
                    </svg>
                </div>
                <div id="car">
                    <svg viewBox="0 0 100 200" width="100%" height="100%">
                        <rect x="10" y="10" width="80" height="180" rx="15" fill="#2c3e50" stroke="#000" stroke-width="3"/>
                        <rect x="20" y="50" width="60" height="100" rx="8" fill="#34495e" stroke="#000" stroke-width="2"/>
                        <rect x="15" y="30" width="70" height="20" rx="4" fill="#111"/>
                        <rect x="15" y="150" width="70" height="15" rx="3" fill="#111"/>
                        <rect x="25" y="80" width="50" height="15" rx="2" fill="#ff3b30"/>
                        <rect x="50" y="80" width="25" height="15" rx="2" fill="#0984e3"/>
                        <rect x="15" y="5" width="20" height="10" rx="3" fill="#facc15"/>
                        <rect x="65" y="5" width="20" height="10" rx="3" fill="#facc15"/>
                    </svg>
                </div>
                <div class="hud-toast" id="toastBox">TEXT</div>
            </div>
        </div>

        <div class="controls">
            <div class="bet-info">
                <span id="uiBetId">Bet ID: ----</span>
                <span class="fair-text"><i class="fas fa-shield-alt"></i> Fair</span>
            </div>

            <div class="input-wrapper">
                <button class="bet-btn" onclick="GameEngine.adjustBet(-10)">-</button>
                <div class="bet-input-box">
                    <input type="number" id="uiBetInput" class="bet-input" value="10.00" readonly>
                    <span class="bet-currency">INR</span>
                </div>
                <button class="bet-btn" onclick="GameEngine.adjustBet(10)">+</button>
                <div class="divider"></div>
                <div class="multi-btns">
                    <button class="m-btn" onclick="GameEngine.adjustBet('half')">x0.5</button>
                    <button class="m-btn" onclick="GameEngine.adjustBet('double')">x2.0</button>
                </div>
            </div>

            <div class="diff-tabs">
                <div class="diff-tab active" data-diff="easy" onclick="GameEngine.setDifficulty('easy', this)">Easy</div>
                <div class="diff-tab" data-diff="medium" onclick="GameEngine.setDifficulty('medium', this)">Medium</div>
                <div class="diff-tab" data-diff="hard" onclick="GameEngine.setDifficulty('hard', this)">Hard</div>
                <div class="diff-tab" data-diff="hardcore" onclick="GameEngine.setDifficulty('hardcore', this)">Hardcore</div>
            </div>

            <div class="action-area">
                <button class="btn-massive" id="btnStart" onclick="GameEngine.startGame()">Play</button>
                
                <div class="play-grid" id="btnPlayGrid">
                    <button class="btn-cashout" id="btnCashout" onclick="GameEngine.cashOut()">CASH OUT<br><small>₹<span id="uiCashAmt">0.00</span></small></button>
                    <button class="btn-go" id="btnGo" onclick="GameEngine.stepForward()">GO</button>
                </div>
            </div>
        </div>
    </div>

    <script>
        const GameEngine = (function() {
            
            const MULTIPLIERS = {
                'easy':     [1.01, 1.02, 1.04, 1.06, 1.09, 1.13, 1.18, 1.25, 1.35, 1.50, 1.70, 2.00, 2.40, 3.00, 3.80, 5.00, 6.50, 8.50, 11.00, 15.00, 22.00, 32.00, 45.00, 65.00, 100.00],
                'medium':   [1.02, 1.04, 1.07, 1.11, 1.16, 1.22, 1.30, 1.45, 1.65, 1.95, 2.40, 3.00, 3.80, 5.00, 7.00, 10.00, 14.00, 20.00, 28.00, 40.00, 60.00, 90.00, 130.00, 200.00, 300.00],
                'hard':     [1.03, 1.07, 1.12, 1.18, 1.25, 1.35, 1.50, 1.75, 2.10, 2.60, 3.30, 4.50, 6.00, 8.50, 12.00, 18.00, 28.00, 45.00, 70.00, 110.00, 180.00, 300.00, 500.00, 800.00, 1200.00],
                'hardcore': [1.05, 1.12, 1.20, 1.30, 1.45, 1.65, 1.90, 2.30, 2.90, 3.80, 5.50, 8.00, 12.00, 18.00, 28.00, 45.00, 75.00, 130.00, 220.00, 380.00, 650.00, 1100.00, 2000.00, 3500.00, 5000.00]
            };
            
            const LANE_WIDTH = 150; 
            let soundEnabled = true;

            let state = { status: 'idle', bet: 10, difficulty: 'easy', currentStep: 0 };

            const els = {
                slider: document.getElementById('roadSlider'),
                chicken: document.getElementById('chicken'),
                car: document.getElementById('car'),
                toast: document.getElementById('toastBox'),
                menu: document.getElementById('menuModal'),
                historyMod: document.getElementById('historyModal'),
                historyList: document.getElementById('historyList'),
                soundToggle: document.getElementById('soundToggle'),
                btnStart: document.getElementById('btnStart'),
                btnGrid: document.getElementById('btnPlayGrid'),
                btnGo: document.getElementById('btnGo'),
                btnCashout: document.getElementById('btnCashout'),
                uiBet: document.getElementById('uiBetInput'),
                uiBal: document.getElementById('uiBalance'),
                uiCash: document.getElementById('uiCashAmt'),
                uiId: document.getElementById('uiBetId'),
                diffTabs: document.querySelectorAll('.diff-tab')
            };

            function buildRoad() {
                els.slider.innerHTML = '<div class="sidewalk-start"></div>';
                for(let i=1; i<=25; i++) {
                    let lane = document.createElement('div');
                    lane.className = 'lane' + (i === 25 ? ' last-lane' : '');
                    if(i < 25) {
                        let line = document.createElement('div');
                        line.className = 'dashed-line road-line-anim';
                        lane.appendChild(line);
                    }
                    let manhole = document.createElement('div');
                    manhole.className = 'manhole';
                    manhole.id = 'mh-' + i;
                    let text = document.createElement('div');
                    text.className = 'manhole-text';
                    text.innerText = (i === 25 ? '💥' : MULTIPLIERS[state.difficulty][i-1].toFixed(2) + 'x');
                    manhole.appendChild(text);
                    lane.appendChild(manhole);
                    els.slider.appendChild(lane);
                }
            }

            function playAudio(id) { if(!soundEnabled) return; let a = document.getElementById(id); if(a) { a.currentTime = 0; a.play().catch(()=>{}); } }

            function updateCamera(smooth = true) {
                let offset = 150 + (state.currentStep * LANE_WIDTH);
                els.slider.style.transition = smooth ? 'transform 0.4s cubic-bezier(0.25, 0.8, 0.25, 1)' : 'none';
                els.slider.style.transform = `translateX(-${offset}px)`;
            }

            function updateUI() {
                els.uiBet.value = state.bet.toFixed(2);
                buildRoad(); updateCamera(false);
            }

            function toggleMenu() { els.menu.style.display = els.menu.style.display === 'block' ? 'none' : 'block'; }
            function toggleSound() { soundEnabled = !soundEnabled; els.soundToggle.className = soundEnabled ? 'switch-toggle sound-on' : 'switch-toggle'; }
            
            function openHistory() {
                els.menu.style.display = 'none';
                els.historyMod.style.display = 'flex';
                els.historyList.innerHTML = '<div class="text-center text-muted mt-5"><i class="fas fa-spinner fa-spin fs-2"></i></div>';
                
                let fd = new FormData(); fd.append('action', 'get_history');
                fetch('', { method: 'POST', body: fd }).then(r=>r.json()).then(data => {
                    if(data.success && data.data.length > 0) {
                        let html = '';
                        data.data.forEach(h => {
                            let type = h.status === 'win' ? 'win' : 'loss';
                            let sign = h.status === 'win' ? '+' : '-';
                            html += `
                            <div class="hist-card ${type}">
                                <div class="hist-left">
                                    <div>${new Date(h.created_at).toLocaleString()}</div>
                                    <span>Bet: ₹${parseFloat(h.bet_amount).toFixed(2)}</span>
                                </div>
                                <div class="hist-right">
                                    <div class="mult">${parseFloat(h.multiplier).toFixed(2)}x</div>
                                    <div class="amt ${type}">${sign}₹${parseFloat(h.win_amount).toFixed(2)}</div>
                                </div>
                            </div>`;
                        });
                        els.historyList.innerHTML = html;
                    } else {
                        els.historyList.innerHTML = '<div class="text-center text-muted mt-5">No bet history found.</div>';
                    }
                });
            }
            function closeHistory() { els.historyMod.style.display = 'none'; }

            window.onclick = function(e) { if (!e.target.closest('.menu-icon') && !e.target.closest('.menu-modal')) { els.menu.style.display = 'none'; } }

            function adjustBet(val) {
                if(state.status !== 'idle') return;
                if(val === 'half') state.bet /= 2;
                else if(val === 'double') state.bet *= 2;
                else state.bet += val;
                if(state.bet < 1) state.bet = 1;
                els.uiBet.value = state.bet.toFixed(2);
            }

            function setDifficulty(diff, btn) {
                if(state.status !== 'idle') return;
                state.difficulty = diff;
                els.diffTabs.forEach(t => t.classList.remove('active'));
                btn.classList.add('active');
                updateUI();
            }

            function showToast(text, color) { els.toast.innerText = text; els.toast.style.borderColor = color; els.toast.style.color = color; els.toast.classList.add('show'); }

            async function startGame() {
                if(state.status !== 'idle') return;
                els.btnStart.innerHTML = '<i class="fas fa-spinner fa-spin"></i>'; els.btnStart.disabled = true;

                let fd = new FormData(); fd.append('action', 'start_game'); fd.append('bet_amount', state.bet); fd.append('difficulty', state.difficulty);

                try {
                    let res = await fetch('', { method: 'POST', body: fd });
                    let data = await res.json();
                    if(data.success) {
                        state.status = 'playing'; state.currentStep = 0; 
                        els.uiBal.innerText = data.balance; els.uiId.innerText = 'Bet ID: ' + data.bet_id;
                        els.uiCash.innerText = (state.bet * MULTIPLIERS[state.difficulty][0]).toFixed(2);
                        
                        els.toast.classList.remove('show'); els.chicken.classList.remove('anim-dead'); els.car.classList.remove('anim-crash-drive');
                        buildRoad(); updateCamera(false); 
                        document.querySelectorAll('.road-line-anim').forEach(l => l.classList.add('scrolling-line'));

                        els.btnStart.style.display = 'none'; els.btnGrid.style.display = 'flex';
                        els.btnGo.disabled = false; els.btnCashout.disabled = true; 
                    } else { alert(data.message); }
                } catch(e) {}
                els.btnStart.innerHTML = 'Play'; els.btnStart.disabled = false;
            }

            async function stepForward() {
                if(state.status !== 'playing') return;
                els.btnGo.disabled = true; els.btnCashout.disabled = true;
                
                let fd = new FormData(); fd.append('action', 'next_step');
                try {
                    let res = await fetch('', { method: 'POST', body: fd });
                    let data = await res.json();
                    if(data.status === 'error') { alert("Game Sync Error"); return resetGame(); }

                    state.currentStep++;
                    els.chicken.classList.add('anim-jump'); playAudio('aud-jump'); updateCamera(true); 
                    
                    setTimeout(() => {
                        els.chicken.classList.remove('anim-jump');
                        if(data.status === 'crashed') { triggerCrash(); } 
                        else if(data.status === 'safe') {
                            let mh = document.getElementById('mh-'+state.currentStep);
                            if(mh) mh.classList.add('active');
                            if(state.currentStep < 25) els.uiCash.innerText = (state.bet * MULTIPLIERS[state.difficulty][state.currentStep]).toFixed(2);
                            if(state.currentStep === 25) { mh.classList.add('danger'); setTimeout(() => cashOut(), 500); } 
                            else { els.btnGo.disabled = false; els.btnCashout.disabled = false; }
                        }
                    }, 400);
                } catch(e) { resetGame(); }
            }

            function triggerCrash() {
                state.status = 'crashed';
                document.querySelectorAll('.road-line-anim').forEach(l => l.classList.remove('scrolling-line'));
                els.car.classList.add('anim-crash-drive'); playAudio('aud-crash');

                setTimeout(() => {
                    els.chicken.classList.add('anim-dead');
                    let mh = document.getElementById('mh-'+state.currentStep); if(mh) mh.classList.add('danger');
                    showToast('CRASHED!', 'var(--color-red)');
                    setTimeout(()=> resetGame(), 2500);
                }, 350); 
            }

            async function cashOut() {
                if(state.status !== 'playing' || state.currentStep === 0) return;
                els.btnGo.disabled = true; els.btnCashout.disabled = true;
                let oldVal = els.uiCash.innerText; els.uiCash.innerHTML = '<i class="fas fa-spinner fa-spin"></i>';

                let fd = new FormData(); fd.append('action', 'cash_out'); fd.append('multiplier', MULTIPLIERS[state.difficulty][state.currentStep - 1]);

                try {
                    let res = await fetch('', { method: 'POST', body: fd });
                    let data = await res.json();
                    if(data.success) {
                        playAudio('aud-win');
                        document.querySelectorAll('.road-line-anim').forEach(l => l.classList.remove('scrolling-line'));
                        els.uiBal.innerText = data.balance;
                        showToast(`WIN ₹${data.win_amount.toFixed(2)}`, 'var(--color-green)');
                        confetti({ particleCount: 200, spread: 100, origin: { y: 0.5 }, zIndex: 9999 });
                        setTimeout(()=> resetGame(), 3000);
                    } else { els.uiCash.innerText = oldVal; resetGame(); }
                } catch(e) { els.uiCash.innerText = oldVal; resetGame(); }
            }

            function resetGame() {
                state.status = 'idle';
                els.btnGrid.style.display = 'none'; els.btnStart.style.display = 'block'; els.btnStart.innerHTML = 'Play'; els.btnStart.disabled = false;
                state.currentStep = 0; updateCamera(true); els.chicken.classList.remove('anim-dead'); els.car.classList.remove('anim-crash-drive'); els.toast.classList.remove('show');
            }

            updateUI(); 
            return { adjustBet, setDifficulty, startGame, stepForward, cashOut, toggleMenu, toggleSound, openHistory, closeHistory };
        })();
    </script>
</body>
</html>