<?php
// Chicken Road 2 game frontend
session_start();
if (!isset($_SESSION['user_id']) || empty($_SESSION['user_id'])) {
    header('Location: /login.php');
    exit;
}
require_once __DIR__ . '/../config.php';
$pdo = $GLOBALS['pdo'];
$stmt = $pdo->prepare('SELECT * FROM users WHERE id = ?');
$stmt->execute([$_SESSION['user_id']]);
$user = $stmt->fetch();
if (!$user) {
    header('Location: /login.php');
    exit;
}
if ((int)($user['is_demo'] ?? 0) === 1) {
    $_SESSION['is_demo'] = 1;
    header('Location: ../index.php?err=demo_restriction');
    exit;
}
$balance = (float)$user['balance'];

$minBetLocal = 10; // Minimum bet in PKR
$cur = 'Rs';
$balLocal = number_format($balance, 2);
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, viewport-fit=cover"/>
<title>Chicken Trap</title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Poppins:wght@400;600;800;900&display=swap" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
<style>
/*
 =============================
   AAA GOLDEN ROYAL & DARK NEON
   Premium Casino Theme
 =============================
*/

:root {
  --bg-base: #050505;
  --bg-card: #121214;
  --gold-light: #FFDF00;
  --gold-main: #D4AF37;
  --gold-dark: #996515;
  --neon-green: #22c55e;
  --neon-green-dark: #16a34a;
  --neon-red: #FF2A54;
  --neon-red-dark: #990011;
  --neon-blue: #00E5FF;
  --border-subtle: rgba(255, 255, 255, 0.08);
  --text-main: #F8F8F8;
  --text-muted: #8A8A93;
  --glass: rgba(18, 18, 20, 0.85);
  
  --tile: 72px; 
  --chicken: 118px; 
  --world-max: 520px;
}

@media (min-width:420px){ :root{ --tile:84px; --chicken:132px } }
@media (min-width:640px){ :root{ --tile:96px; --chicken:140px } }

* { box-sizing: border-box; -webkit-tap-highlight-color: transparent; }
html, body { height: 100%; overflow: hidden; }

body {
  margin: 0; 
  font-family: 'Poppins', sans-serif; 
  color: var(--text-main);
  background: var(--bg-base);
  display: flex; 
  align-items: stretch; 
  justify-content: center;
}

/* -------- App Frame -------- */
.app {
  width: 100%; 
  max-width: var(--world-max); 
  height: 100svh; 
  display: flex; 
  flex-direction: column; 
  overflow: hidden;
  background: radial-gradient(circle at 50% 0%, #1a1a2e 0%, var(--bg-base) 100%);
  box-shadow: 0 0 40px rgba(0,0,0,0.9);
  position: relative;
}

/* -------- Top Bar -------- */
.top {
  display: flex; align-items: center; justify-content: space-between; 
  padding: 16px 20px; 
  background: var(--glass);
  backdrop-filter: blur(10px);
  -webkit-backdrop-filter: blur(10px);
  border-bottom: 1px solid var(--border-subtle); 
  z-index: 3000;
}
.back {
  color: #fff; text-decoration: none; font-size: 1.2rem; 
  background: rgba(255,255,255,0.05); 
  width: 40px; height: 40px; 
  display: flex; align-items: center; justify-content: center; 
  border-radius: 50%; border: 1px solid rgba(255,255,255,0.1);
  transition: all 0.2s;
  font-size: 0; 
}
.back svg { width: 20px; height: 20px; stroke: #fff; }
.back:active { transform: scale(0.95); background: rgba(255,255,255,0.1); }

.brand {
  font-weight: 900; letter-spacing: 2px; font-size: 16px; text-transform: uppercase;
  background: linear-gradient(90deg, var(--gold-light), var(--gold-main));
  -webkit-background-clip: text; background-clip: text; color: transparent;
  filter: drop-shadow(0 2px 4px rgba(0,0,0,0.8));
}

.balance {
  background: rgba(0, 0, 0, 0.6); 
  border: 2px solid var(--gold-main); 
  border-radius: 999px; 
  padding: 6px 14px; 
  display: flex; align-items: center; gap: 6px; 
  font-size: 14px; font-weight: 900; color: var(--gold-light);
  box-shadow: 0 0 15px rgba(212, 175, 55, 0.2);
}

/* -------- Stage / World -------- */
.stage {
  position: relative; flex: 1; min-height: 0;
  background: radial-gradient(circle at 50% 100%, rgba(212,175,55,0.05) 0%, transparent 60%);
}
.world {
  position: absolute; inset: 0; transform-origin: 50% 80%; 
  will-change: transform; transform-style: preserve-3d; z-index: 1;
}

/* -------- Road Grid -------- */
.road { position: absolute; inset: 0; display: grid; grid-template-columns: 1fr 1fr; }
.lane { position: relative; }
.lane::before {
  content: ""; position: absolute; left: 50%; top: -4000px; bottom: -4000px; width: 2px; transform: translateX(-50%);
  background: repeating-linear-gradient(to bottom, rgba(212,175,55,0.3) 0 20px, transparent 20px 50px);
  filter: drop-shadow(0 0 5px var(--gold-main));
}
.tarmac::before {
  content: ""; position: absolute; left: 0; right: 0; top: -3000px; bottom: -3000px;
  background: 
    linear-gradient(180deg, rgba(255,255,255,0.01), transparent 40%),
    repeating-linear-gradient(180deg, rgba(0,0,0,0.4) 0 100px, transparent 100px 200px);
  opacity: 0.5; pointer-events: none;
}

/* -------- Path Lines -------- */
svg.fx { position: absolute; inset: 0; width: 100%; height: 100%; pointer-events: none; z-index: 40; }
.route { fill: none; stroke: var(--gold-light); stroke-width: 4; stroke-linecap: round; stroke-linejoin: round; filter: drop-shadow(0 0 6px var(--gold-main)); }
.routeGlow { fill: none; stroke: rgba(212,175,55,0.3); stroke-width: 16; filter: blur(6px); }

#stage { position: relative; }
#fx { position: absolute; inset: 0; pointer-events: none; z-index: 1; }
#world { position: relative; z-index: 2; }
#spots { position: relative; z-index: 3; }
#chicken { position: relative; z-index: 4; }

/* -------- Bubbles / Spots -------- */
.spots { position: absolute; inset: 0; }
.spot { position: absolute; width: var(--tile); height: var(--tile); left: 50%; top: 50%; transform: translate(-50%,-50%); }

.bubble {
  position: absolute; left: 50%; top: 50%; transform: translate(-50%,-30%);
  display: flex; align-items: center; justify-content: center;
  width: 86px; height: 86px; border-radius: 50%; 
  font-weight: 900; font-size: 15px; letter-spacing: 0.5px; color: #fff;
  background: radial-gradient(circle at 50% 20%, rgba(255,255,255,0.1), rgba(0,0,0,0.8));
  border: 2px solid rgba(255,255,255,0.1);
  box-shadow: 0 10px 20px rgba(0,0,0,0.8), inset 0 2px 10px rgba(255,255,255,0.1);
  backdrop-filter: blur(5px);
  z-index: 100;
  transition: transform 0.15s cubic-bezier(0.4, 0, 0.2, 1), box-shadow 0.2s, border-color 0.2s;
  text-shadow: 0 2px 4px rgba(0,0,0,0.8);
}
.bubble.blue {
  border-color: rgba(0, 229, 255, 0.4);
  box-shadow: 0 10px 20px rgba(0,0,0,0.8), inset 0 0 20px rgba(0, 229, 255, 0.2);
  color: var(--neon-blue);
  text-shadow: 0 0 8px rgba(0, 229, 255, 0.4);
}
.bubble.trap {
  background: radial-gradient(circle at 50% 50%, rgba(255,42,84,0.2), rgba(0,0,0,0.9));
  border-color: var(--neon-red); color: var(--neon-red);
  box-shadow: 0 10px 20px rgba(0,0,0,0.8), inset 0 0 30px rgba(255,42,84,0.4);
  text-shadow: 0 0 10px var(--neon-red);
}
.bubble.start {
  border-color: var(--neon-green); color: var(--neon-green);
  box-shadow: 0 10px 20px rgba(0,0,0,0.8), inset 0 0 20px rgba(34,197,94,0.2);
  text-shadow: 0 0 8px var(--neon-green);
}

.bubble.pop { animation: bubble-pop 0.2s cubic-bezier(0.175, 0.885, 0.32, 1.275); }
@keyframes bubble-pop {
  0% { transform: translate(-50%,-30%) scale(0.85); }
  100% { transform: translate(-50%,-30%) scale(1); }
}

/* -------- Chicken -------- */
.chicken { position: absolute; width: var(--chicken); height: var(--chicken); pointer-events: none; z-index: 500; }
.chicken img { width: 100%; height: 100%; filter: drop-shadow(0 15px 15px rgba(0,0,0,0.8)); transform-origin: 50% 50%; }

/* -------- Status Badge -------- */
.status {
  position: absolute; left: 50%; top: calc(20px + env(safe-area-inset-top,0) + 60px); 
  transform: translateX(-50%); z-index: 3200;
  display: inline-flex; align-items: center; gap: 8px; padding: 8px 20px; 
  font-weight: 900; font-size: 14px; text-transform: uppercase; letter-spacing: 1px; 
  border-radius: 999px; color: #fff;
  background: rgba(0,0,0,0.6); border: 1px solid rgba(255,255,255,0.1);
  box-shadow: 0 10px 20px rgba(0,0,0,0.5); backdrop-filter: blur(10px);
  pointer-events: none; user-select: none;
}
.status.safe { border-color: var(--neon-green); color: var(--neon-green); box-shadow: 0 0 20px rgba(34,197,94,0.2); text-shadow: 0 0 8px rgba(34,197,94,0.5); }
.status.status-cash { border-color: var(--gold-main); color: var(--gold-light); box-shadow: 0 0 20px rgba(212,175,55,0.2); text-shadow: 0 0 8px rgba(212,175,55,0.5); background: rgba(0,0,0,0.6); }
.status.danger { border-color: var(--neon-red); color: var(--neon-red); box-shadow: 0 0 20px rgba(255,42,84,0.2); text-shadow: 0 0 8px rgba(255,42,84,0.5); }
.status.pulse { animation: status-pop 0.4s cubic-bezier(0.175, 0.885, 0.32, 1.275); }
@keyframes status-pop { 0% { transform: translateX(-50%) scale(0.9); opacity: 0; } 100% { transform: translateX(-50%) scale(1); opacity: 1; } }

/* -------- Bottom Control Panel -------- */
.panel {
  position: relative; z-index: 30;
  background: linear-gradient(180deg, rgba(18,18,20,0.9) 0%, #050505 100%);
  backdrop-filter: blur(15px); -webkit-backdrop-filter: blur(15px);
  border-top: 1px solid var(--border-subtle);
  padding: 20px 16px max(20px, calc(10px + env(safe-area-inset-bottom,0)));
  box-shadow: 0 -15px 40px rgba(0,0,0,0.8);
}
.row { display: flex; flex-direction: column; gap: 12px; }
.betbox { display: flex; gap: 10px; }
.chips { display: grid; grid-template-columns: repeat(4, 1fr); gap: 10px; }

.btn {
  display: inline-flex; align-items: center; justify-content: center; height: 50px; padding: 0 16px; 
  font-weight: 900; letter-spacing: 1px; border-radius: 12px; border: none;
  background: rgba(255,255,255,0.05); color: var(--text-muted); cursor: pointer; user-select: none;
  transition: all 0.15s; border: 1px solid rgba(255,255,255,0.05);
}
.btn:active:not(.disabled) { transform: translateY(2px); background: rgba(255,255,255,0.08); }
.btn.disabled { opacity: 0.4; pointer-events: none; filter: grayscale(1); }
.chipBtn { height: 44px; font-size: 13px; flex: 1; }
#minBtn, #maxBtn { flex: 0 0 65px; font-size: 12px; color: #fff; background: rgba(255,255,255,0.1); }

input[type=number] {
  flex: 1; width: 100%; background: rgba(0,0,0,0.6); color: var(--gold-light); 
  border: 2px solid rgba(212,175,55,0.3); border-radius: 12px; height: 50px; 
  padding: 0 12px; font-size: 18px; font-weight: 900; text-align: center;
  box-shadow: inset 0 4px 10px rgba(0,0,0,0.6); outline: none; transition: border 0.2s; font-family: monospace;
}
input[type=number]:focus { border-color: var(--gold-main); }

.cta { display: flex; gap: 12px; margin-top: 16px; }
.cash {
  flex: 1; background: linear-gradient(180deg, var(--gold-light), var(--gold-main)); color: #000;
  box-shadow: inset 0 2px 0 rgba(255,255,255,0.6), 0 6px 0 var(--gold-dark), 0 10px 20px rgba(0,0,0,0.5);
  font-size: 15px; text-shadow: 0 1px 1px rgba(255,255,255,0.5);
}
.cash:active:not(.disabled) { box-shadow: inset 0 2px 0 rgba(255,255,255,0.6), 0 0px 0 var(--gold-dark), 0 2px 5px rgba(0,0,0,0.5); transform: translateY(6px); }

.go {
  flex: 1; background: linear-gradient(180deg, var(--neon-green), var(--neon-green-dark)); color: #fff;
  box-shadow: inset 0 2px 0 rgba(255,255,255,0.4), 0 6px 0 #0f5132, 0 10px 20px rgba(0,0,0,0.5);
  font-size: 16px; text-shadow: 0 2px 2px rgba(0,0,0,0.3);
}
.go:active:not(.disabled) { box-shadow: inset 0 2px 0 rgba(255,255,255,0.4), 0 0px 0 #0f5132, 0 2px 5px rgba(0,0,0,0.5); transform: translateY(6px); }

/* -------- Modals (Result Screens) -------- */
.modal { position: fixed; inset: 0; display: none; align-items: flex-end; justify-content: center; z-index: 5000; background: rgba(0,0,0,0.8); backdrop-filter: blur(8px); }
.modal.show { display: flex; animation: fadeIn 0.3s ease; }
@keyframes fadeIn { from { opacity: 0; } to { opacity: 1; } }

.sheet {
  background: linear-gradient(180deg, #1A1A1D 0%, #050505 100%); border-radius: 24px 24px 0 0; 
  width: 100%; max-width: 460px; padding: 30px 20px 40px; text-align: center;
  border-top: 1px solid rgba(255,255,255,0.1); box-shadow: 0 -10px 40px rgba(0,0,0,0.8);
  animation: slideUp 0.4s cubic-bezier(0.16, 1, 0.3, 1);
}
@keyframes slideUp { from { transform: translateY(100%); } to { transform: translateY(0); } }

.sheet h3 { margin: 0 0 10px; font-size: 26px; font-weight: 900; text-transform: uppercase; letter-spacing: 2px; }
#loseModal h3 { color: var(--neon-red); text-shadow: 0 2px 10px rgba(255,42,84,0.4); }
#cashModal h3 { color: var(--gold-light); text-shadow: 0 2px 10px rgba(255,223,0,0.4); }

.sheet p { margin: 0 0 24px; font-size: 15px; color: var(--text-muted); font-weight: 700; }
.sheet span { color: #fff; font-size: 18px; font-weight: 900; }
#cashWin { color: var(--neon-green); font-size: 24px; }
.sheet .btn.go { width: 100%; height: 56px; margin: 0; }

/* FX overlays */
.fx-overlay, .fx-vignette, .fx-flash, .fx-shockwave { position: absolute; inset: 0; pointer-events: none; }
.fx-vignette { z-index: 6; opacity: 0; background: radial-gradient(ellipse at center, transparent 45%, rgba(0,0,0,0.8) 100%); transition: opacity 0.25s ease; }
.fx-flash { z-index: 8; opacity: 0; }
.fx-flash.win { background: radial-gradient(circle at center, rgba(255,255,255,0.9) 0%, transparent 70%); }
.fx-flash.lose { background: radial-gradient(circle at center, rgba(255,42,84,0.8) 0%, transparent 70%); }
.fx-shockwave { z-index: 7; display: none; --x: 50%; --y: 60%; background: radial-gradient(circle at var(--x) var(--y), rgba(255,255,255,0.9) 0%, var(--gold-main) 10%, var(--neon-red) 20%, transparent 30%); mix-blend-mode: screen; }
.fx-debris { position: absolute; width: 6px; height: 6px; background: var(--neon-red); box-shadow: 0 2px 10px rgba(255,42,84,0.8); border-radius: 50%; z-index: 7; }
.fx-rays { position: absolute; inset: -10% -10%; z-index: 7; opacity: 0; background: repeating-conic-gradient(rgba(212,175,55,0.2) 0 10deg, transparent 10deg 20deg); filter: blur(4px); }

@keyframes camShake {
  0% { transform: translate3d(-3px, 2px, 0) rotate(0.1deg); }
  20% { transform: translate3d(4px, -3px, 0) rotate(-0.1deg); }
  40% { transform: translate3d(-5px, 3px, 0) rotate(0.15deg); }
  60% { transform: translate3d(4px, -2px, 0) rotate(-0.1deg); }
  80% { transform: translate3d(-3px, 2px, 0) rotate(0.05deg); }
  100% { transform: translate3d(0, 0, 0) rotate(0deg); }
}
.shake-quick { animation: camShake 300ms ease-in-out 1; }
.loss-aberration { filter: drop-shadow(2px 0 0 rgba(255,42,84,0.8)) drop-shadow(-2px 0 0 rgba(0,229,255,0.8)); }
.win-bloom { filter: drop-shadow(0 0 15px rgba(212,175,55,0.8)) drop-shadow(0 0 30px rgba(212,175,55,0.4)); }

.confetti { position: fixed; inset: 0; pointer-events: none; z-index: 6000; overflow: hidden; }

@media (max-width: 480px), (max-height: 760px) {
  :root { --tile: 94px; --chicken: 112px; }
  .bubble { width: calc(var(--tile)*0.85); height: calc(var(--tile)*0.85); font-size: clamp(13px, calc(var(--tile)*0.18), 16px); }
  .route { stroke-width: 3px; } .routeGlow { stroke-width: 12px; }
}

/* Toast System */
.toast {
  position: fixed; left: 50%; top: 40px; transform: translateX(-50%) translateY(-20px) scale(0.95);
  background: rgba(18,18,20,0.95); color: var(--gold-light); padding: 14px 24px; border-radius: 16px;
  font-weight: 800; letter-spacing: 0.5px; z-index: 99999; opacity: 0; 
  border: 1px solid rgba(255,255,255,0.1); 
  box-shadow: 0 15px 35px rgba(0,0,0,0.9), 0 0 0 1px var(--gold-dark);
  transition: all 0.4s cubic-bezier(0.34, 1.56, 0.64, 1); white-space: nowrap; font-size: 15px;
  display: flex; align-items: center; gap: 12px; backdrop-filter: blur(10px);
}
.toast.error {
  color: #fff;
  box-shadow: 0 15px 35px rgba(0,0,0,0.9), 0 0 0 1px var(--neon-red);
}
.toast-icon { font-size: 20px; }
.toast.error .toast-icon { color: var(--neon-red); text-shadow: 0 0 10px rgba(255,42,84,0.5); }
.toast:not(.error) .toast-icon { color: var(--gold-light); text-shadow: 0 0 10px rgba(255,223,0,0.5); }

.glow-cyan { box-shadow: 0 0 20px rgba(0,229,255,0.5); }
.hidden { display: none !important; }
.opacity-0 { opacity: 0; }
</style>
</head>
<body>
<div class="app" id="app">
  <div class="top">
    <a class="back" id="backBtn" href="/" aria-label="Back">
      <svg viewBox="0 0 24 24" fill="none"><path d="M15 18l-6-6 6-6" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"/></svg>
    </a>
    <div class="brand">Chicken Trap</div>
    <div class="balance"><i class="fa-solid fa-coins"></i> <span id="balance">0.00</span></div>
  </div>

  <div class="stage" id="stage">
    <div class="world tarmac" id="world">
      <div class="road"><div class="lane"></div><div class="lane"></div></div>
      <svg class="fx" id="fx" viewBox="0 0 100 100" preserveAspectRatio="none">
        <path class="routeGlow" id="routeGlow" d=""/>
        <path class="route" id="route" d=""/>
      </svg>
      <div class="spots" id="spots"></div>
      <div class="chicken" id="chicken"><img id="chickenImg" src="https://i.redd.it/1saq67xpfxxd1.gif" alt="Chicken"></div>
    </div>
  </div>

  <div class="status" id="status">Ready</div>

  <div class="modal" id="loseModal">
    <div class="sheet">
      <h3>You Lost</h3>
      <p>Hit trap at <span id="loseMult">1.00x</span>.</p>
      <div class="btn go" id="retryBtn">TRY AGAIN</div>
    </div>
  </div>

  <div class="modal" id="cashModal">
    <div class="sheet">
      <h3>Cashed Out</h3>
      <p><span id="cashWin">+0.00</span> at <span id="cashMult">1.00x</span></p>
      <div class="btn go" id="cashOkBtn">COLLECT</div>
    </div>
  </div>

  <div class="confetti" id="confetti"></div>

  <div class="panel">
    <div class="row">
      <div class="betbox">
        <div class="btn" id="minBtn">MIN</div>
        <input id="bet" type="number" min="<?= htmlspecialchars($minBetLocal) ?>" step="1" value="<?= htmlspecialchars($minBetLocal) ?>" inputmode="decimal"/>
        <div class="btn" id="maxBtn">MAX</div>
      </div>
      <div class="chips">
        <div class="btn chipBtn" data-chip="10">+10</div>
        <div class="btn chipBtn" data-chip="50">+50</div>
        <div class="btn chipBtn" data-chip="100">+100</div>
        <div class="btn chipBtn" data-chip="500">+500</div>
      </div>
    </div>
    <div class="cta">
      <div class="btn cash disabled" id="cashBtn">CASH OUT <span id="cashVal" style="margin-left: 6px;">0.00</span></div>
      <div class="btn go" id="goBtn">GO</div>
    </div>
  </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/gsap@3.12.5/dist/gsap.min.js"
        onerror="(function(){var s=document.createElement('script');s.src='https://unpkg.com/gsap@3.12.5/dist/gsap.min.js';document.head.appendChild(s);}())"></script>

<script>
// ==============================
// Chicken Road 2 — Frontend JS
// Custom API Adapter for Single-File Backend (api.php)
// ==============================

let toastTimeout;
function showToast(msg, isError = false) {
  let t = document.querySelector('.toast');
  if (!t) {
    t = document.createElement('div');
    t.className = 'toast';
    document.body.appendChild(t);
  }
  clearTimeout(toastTimeout);
  
  const icon = isError ? '<i class="fa-solid fa-circle-exclamation toast-icon"></i>' : '<i class="fa-solid fa-bell toast-icon"></i>';
  t.className = 'toast ' + (isError ? 'error' : '');
  t.innerHTML = `${icon} <span>${msg}</span>`;
  
  requestAnimationFrame(()=> { t.style.opacity='1'; t.style.transform='translateX(-50%) translateY(0) scale(1)'; });
  toastTimeout = setTimeout(()=>{ 
      t.style.opacity='0'; 
      t.style.transform='translateX(-50%) translateY(-20px) scale(0.95)'; 
  }, 2500);
}

async function backendApi(action, payload = null) {
  const opts = { credentials: 'same-origin' };
  if (payload) {
    opts.method = 'POST';
    opts.headers = { 'Content-Type': 'application/json' };
    opts.body = JSON.stringify(payload);
  }
  const r = await fetch('api.php?action=' + action, opts);
  return r.json();
}

function fetchSettingsRequest() {
  return Promise.resolve({status: 'success', settings: {}}); // Mocked, handled client-side or defaults
}

function fetchBalanceRequest() {
  return backendApi('get_state').then(r => {
    if (r && r.ok) return { balance: r.balance_usd };
    throw new Error('Failed to fetch balance');
  });
}

function placeBetRequest(amount) {
  return backendApi('place_bet', { amount }).then(r => {
    if (r && r.ok) return { status: 'success', round_token: r.round_token, new_balance: r.balance_usd };
    return { status: 'error', message: r.error };
  });
}

function stepRequest(roundToken, nextMultiplier) {
  return backendApi('step', { round_token: roundToken, next_multiplier: nextMultiplier }).then(r => {
    if (r && r.ok) return { status: 'success', trap: r.trap, multiplier: r.multiplier };
    return { status: 'error', message: r.error };
  });
}

function settleBetRequest(roundToken) {
  return backendApi('settle', { round_token: roundToken }).then(r => {
    if (r && r.ok) {
        return { status: 'success', balance: r.balance_usd, payout: r.payout };
    }
    return { status: 'error', message: r.error };
  });
}

(function boot(){
  function ready(){ return typeof window.gsap !== 'undefined'; }
  (function tick(){ ready()? main(): setTimeout(tick, 30); })();
})();

function main(){
  const CFG = {
    winRate: 0.78, winFalloffPerStep: 0.04, minSafeSteps: 1,
    buildAhead: 24, maxSteps: 200,
    speed: 1.0, stepDuration: 0.55, cameraDuration: 0.55, cameraZoom: 1.08, modalDelay: 650,
    bubblePressScale: 0.9, bubblePressTime: 0.12,
    trapShakeRepeats: 12, trapCineTime: 0.75, cashCineTime: 0.8,
    bgVolume: 0.1, sfxVolume: 0.95,
    GIF_IDLE: 'https://i.redd.it/1saq67xpfxxd1.gif',
    GIF_WALK: 'https://i.redd.it/14x31s6rfxxd1.gif',
  };

  let currentRoundToken = null;
  const gsapRef = window.gsap, $ = s=>document.querySelector(s);
  gsapRef.defaults({ force3D:true }); gsapRef.ticker.lagSmoothing(500, 32);

  const stage = $('#stage'), world = $('#world'), spots = $('#spots'), statusEl = $('#status');
  const balanceEl = $('#balance');
  const betInput = $('#bet'), minBtn = $('#minBtn'), maxBtn = $('#maxBtn'),
        goBtn = $('#goBtn'), cashBtn = $('#cashBtn'), cashVal = $('#cashVal');
  const chicken = $('#chicken'), chickenImg = $('#chickenImg');

  const loseModal = $('#loseModal'), retryBtn = $('#retryBtn'), loseMultEl = $('#loseMult');
  const cashModal = $('#cashModal'), cashOkBtn = $('#cashOkBtn'), cashWinEl = $('#cashWin'), cashMultEl = $('#cashMult');
  const confettiWrap = $('#confetti');

  const fxSvg = document.getElementById('fx');
  const pathGlow = document.getElementById('routeGlow');
  const pathRoute = document.getElementById('route');
  if (fxSvg && stage && fxSvg.parentNode !== stage) { stage.insertBefore(fxSvg, world); }
  if (fxSvg){ Object.assign(fxSvg.style,{position:'absolute', inset:'0', pointerEvents:'none'});
    fxSvg.setAttribute('preserveAspectRatio','none'); fxSvg.setAttribute('shape-rendering','geometricPrecision'); }
  if (pathRoute){ pathRoute.setAttribute('vector-effect','non-scaling-stroke'); }
  if (pathGlow){ pathGlow.setAttribute('vector-effect','non-scaling-stroke'); }

  const sfx = (()=> {
    const src = {
      bg:   '/Chicken/sounds/bg.mp3',
      trap: '/Chicken/sounds/trap.mp3',
      btn:  '/Chicken/sounds/btn.mp3',
      win:  '/Chicken/sounds/win.mp3',
      loss: '/Chicken/sounds/loss.mp3',
      tile: '/Chicken/sounds/tile.mp3',
    };
    const a = {};
    function mk(name, loop=false){ const el = new Audio(src[name]); el.loop=loop; el.preload='auto';
      el.volume = name==='bg' ? CFG.bgVolume : CFG.sfxVolume; return el; }
    function init(){ if (a._inited) return;
      a.bg = mk('bg', true); a.trap = mk('trap'); a.btn = mk('btn'); a.win = mk('win'); a.loss = mk('loss'); a.tile = mk('tile'); a._inited = true; }
    async function unlock(){ init(); try { await a.bg.play(); } catch(e){} }
    function ensureGestureUnlock(){ const once = ()=>{ unlock(); window.removeEventListener('pointerdown', once, true); window.removeEventListener('keydown', once, true); };
      window.addEventListener('pointerdown', once, true); window.addEventListener('keydown', once, true); }
    function play(name){ init(); if (!a[name]) return; try { a[name].currentTime = 0; a[name].play(); } catch(e){} }
    ensureGestureUnlock(); return { play, unlock, init, a };
  })();

  function readSizes(){ const cs=getComputedStyle(document.documentElement);
    TILE=parseFloat(cs.getPropertyValue('--tile'))||72; CHICK=parseFloat(cs.getPropertyValue('--chicken'))||118; }
  let TILE=72, CHICK=118; readSizes();

  const laneX = lane => Math.round(stage.clientWidth * (lane===0 ? 0.40 : 0.60));
  function metrics(){ const h = stage.clientHeight, mobile=(window.innerWidth<=480)||(h<=760);
    const topPad= mobile?60:90, botPad= mobile?36:56;
    const usable=Math.max(160, h-topPad-botPad), bubblePx= mobile?Math.round(TILE*.82):84;
    const minStep=Math.round(bubblePx*1.28), baseStep=Math.round(usable/8);
    return { topPad, botPad, step:Math.max(minStep, baseStep) }; }
  function centerFor(i){ const {botPad, step}=metrics(); const lane=i%2; const cx=laneX(lane), cy=Math.round(stage.clientHeight - botPad - step*(i+1));
    return {cx,cy,step}; }

  const GIF = { idle: CFG.GIF_IDLE, walk: CFG.GIF_WALK };
  let balance=0.00, bet=<?= $minBetLocal ?>, lockedBet=0;

  let inRound=false, crashed=false, stepping=false, movingToIndex=null, animLock=false, confettiOn=false;
  let stepCount = 1;
  let multipliers = [], bubbles = [], centers = [];
  let camTween = null, moveTween = null;
  let visited = [0];

  let cameraLocked=false, lockTransform=null, lockTick=null;
  function freezeCamera(){
    cameraLocked = true;
    if (camTween) camTween.kill();
    lockTransform = getComputedStyle(world).transform;
    if (!lockTransform || lockTransform === 'none') lockTransform = 'matrix(1,0,0,1,0,0)';
    if (lockTick) gsap.ticker.remove(lockTick);
    lockTick = ()=>{ world.style.transform = lockTransform; };
    gsap.ticker.add(lockTick);
  }
  function unfreezeCamera(){
    cameraLocked = false;
    if (lockTick){ gsap.ticker.remove(lockTick); lockTick=null; }
    lockTransform=null;
  }

  const fmt = x => Number(x).toFixed(2);
  const clamp = (n,a,b)=> Math.max(a,Math.min(b,n));
  function status(text){
    const t=(text||'').toLowerCase(); let kind='';
    if (t.includes('safe')) kind='safe'; else if (t.includes('cash')) kind='status-cash';
    else if (t.includes('trap')||t.includes('lost')) kind='danger';
    statusEl.textContent=text; statusEl.className='status '+kind;
    statusEl.classList.remove('pulse'); statusEl.offsetWidth; statusEl.classList.add('pulse');
  }
  function setBalance(v){ balance=Math.max(0,v); if (balanceEl) balanceEl.textContent=fmt(balance); }
  function setBet(v){ bet=clamp(Math.round(v||0),1,999999); if (betInput) betInput.value=bet; updateButtons(); }
  function updateButtons(){
    const enableCash = (inRound && !crashed && stepCount>1);
    if (cashBtn){ cashBtn.classList.toggle('disabled', !enableCash); cashBtn.disabled = !enableCash; }
  }
  function lockBetUI(lock){
    if (!betInput) return; betInput.disabled=lock;
    [minBtn,maxBtn].filter(Boolean).forEach(b=>b.classList.toggle('disabled',lock));
    document.querySelectorAll('.chipBtn').forEach(c=>c.classList.toggle('disabled',lock));
  }
  function setControlsEnabled(enabled){
    animLock = !enabled;
    if (goBtn){ goBtn.classList.toggle('disabled', !enabled); goBtn.disabled = !enabled; }
    updateButtons();
  }

  function multiplierAt(i){ return Math.min(1.05 + 0.05 * (i-1), 50); }
  function labelFor(i){ return i===0 ? 'START' : multiplierAt(i).toFixed(2)+'x'; }
  function trapRollForStep(i){
    if (i <= CFG.minSafeSteps) return false;
    const safeChance = clamp(CFG.winRate - CFG.winFalloffPerStep*(i-1), 0.01, 0.99);
    return Math.random() > safeChance;
  }

  function ensureIndex(i){
    if(bubbles[i]) return;
    const s=document.createElement('div'); s.className='spot';
    const {cx,cy}=centerFor(i); s.style.left=cx+'px'; s.style.top=cy+'px';
    const cls='bubble '+(i===0?'start':(i%2===0?'':'blue'));
    const b=document.createElement('div'); b.className=cls; b.textContent=labelFor(i);
    s.appendChild(b); spots.appendChild(s);
    bubbles[i]=b; centers[i]={cx,cy};
  }
  function ensureRange(from,to){
    const hi = Math.min(CFG.maxSteps, to);
    for(let i=from;i<=hi;i++){ if(i>=1) multipliers[i] = multipliers[i] ?? multiplierAt(i); ensureIndex(i); }
  }

  function cameraTarget(i){
    const {cy}=centerFor(i);
    const focusY = i===0 ? Math.round(stage.clientHeight - CHICK*1.2) : Math.round(stage.clientHeight*0.55);
    return { yShift: Math.round(focusY - cy) };
  }
  function cameraFollow(i, keep){
    if (cameraLocked) return;
    const {yShift}=cameraTarget(i); if (camTween) camTween.kill();
    camTween=gsap.to(world,{ x:0, y:yShift, scale:CFG.cameraZoom, rotationZ:0, duration:CFG.cameraDuration, ease:'power3.out' });
    if(typeof keep==='number') camTween.progress(keep);
  }

  function placeChickenAtStart(){
    const {cx,cy}=centerFor(0);
    gsap.set(chicken,{x:Math.round(cx-CHICK/2), y:Math.round(cy-CHICK/2), autoAlpha:1});
    faceTo(laneX(0)-CHICK/2); chickenImg.src=CFG.GIF_IDLE;
  }
  function faceTo(targetX){ const currX=Number(gsap.getProperty(chicken,'x'))||0; gsap.set(chickenImg,{scaleX:(targetX-currX)>=0?-1:1}); }

  function updateViewBox(){ if(fxSvg) fxSvg.setAttribute('viewBox', `0 0 ${stage.clientWidth} ${stage.clientHeight}`); }
  updateViewBox();
  function getCenterInStage(el){ const r = el.getBoundingClientRect(), sr = stage.getBoundingClientRect();
    return [ Math.round(r.left - sr.left + r.width/2), Math.round(r.top - sr.top + r.height/2) ]; }
  function pointForIndex(i){
    if (bubbles[i]) return getCenterInStage(bubbles[i].parentElement || bubbles[i]);
    const {cx,cy}=centerFor(i); return [cx,cy];
  }
  function chickenCenter(){ return getCenterInStage(chicken); }
  function buildPathD(){
    if (!visited.length) return '';
    const pts = []; for (let k=0;k<visited.length;k++){ const i = visited[k]; const [x,y] = pointForIndex(i); pts.push([x,y]); }
    const [hx,hy] = chickenCenter(); pts.push([hx,hy]);
    const compact=[]; for(let i=0;i<pts.length;i++){ const [x,y]=pts[i]; if(!compact.length){ compact.push([x,y]); continue; }
      const [px,py]=compact[compact.length-1]; if(px!==x || py!==y) compact.push([x,y]); }
    if(!compact.length) return '';
    let d='M'+compact[0][0]+','+compact[0][1]; for(let i=1;i<compact.length;i++){ d+=' L'+compact[i][0]+','+compact[i][1]; }
    return d;
  }
  function renderPath(){
    updateViewBox(); const d = buildPathD();
    if (pathGlow) pathGlow.setAttribute('d', d); if (pathRoute) pathRoute.setAttribute('d', d);
  }
  gsap.ticker.add(renderPath);

  window.addEventListener('resize', ()=>{
    readSizes(); updateViewBox();
    document.querySelectorAll('.spot').forEach((el,i)=>{ const {cx,cy}=centerFor(i); el.style.left=cx+'px'; el.style.top=cy+'px'; centers[i]={cx,cy}; });
    if (!cameraLocked && camTween){ const p=camTween.progress(); cameraFollow(Math.max(0,stepCount-1), p); }
    if (moveTween && movingToIndex!=null){
      const{cx,cy}=centerFor(movingToIndex); const p=moveTween.progress();
      moveTween.vars.x=Math.round(cx-CHICK/2); moveTween.vars.y=Math.round(cy-CHICK/2); moveTween.invalidate().progress(p);
    }
    renderPath();
  });

  function placeStart(){ ensureRange(0, CFG.buildAhead); placeChickenAtStart(); unfreezeCamera(); cameraFollow(0); visited=[0]; updateButtons(); renderPath(); confettiOn=false; }
  function resetAll(){
    inRound=false; crashed=false; stepping=false; movingToIndex=null; animLock=false; confettiOn=false; unfreezeCamera();
    stepCount=1; multipliers=[]; centers=[]; bubbles=[]; visited=[0];
    spots.innerHTML=''; if(pathGlow) pathGlow.setAttribute('d',''); if (pathRoute) pathRoute.setAttribute('d','');
    if(moveTween) moveTween.kill(); if(camTween) camTween.kill();
    gsap.to(world,{scale:1,x:0,y:0,rotationZ:0,duration:.2});
    lockBetUI(false); status('Ready'); placeStart(); setControlsEnabled(true); updateButtons();
    currentRoundToken = null;
  }
  async function newRound(){
    inRound=true; crashed=false; unfreezeCamera(); ensureRange(0, CFG.buildAhead); lockBetUI(true);
    status('Placing bet...');
    try {
      const res = await placeBetRequest(lockedBet);
      if (res && res.status === 'success') {
        currentRoundToken = res.round_token;
        setBalance(res.new_balance);
        status('Bet placed -' + fmt(lockedBet));
      } else {
        throw new Error((res && res.message) || 'Bet error');
      }
    } catch (err) {
      showToast(err.message || 'Bet error', true);
      inRound = false;
      lockBetUI(false);
      setControlsEnabled(true);
      currentRoundToken = null;
      return;
    }
    placeChickenAtStart(); cameraFollow(0); visited=[0]; renderPath(); updateButtons();
  }

  function bubblePress(i){ const b=bubbles[i]; if(!b) return;
    gsap.fromTo(b,{ scale:1 },{ scale:CFG.bubblePressScale, duration:CFG.bubblePressTime, yoyo:true, repeat:1, ease:'power2.out', transformOrigin:'50% 50%' }); }
  function confettiBurst(n=160){
    if (confettiOn) return; confettiOn = true;
    const W=confettiWrap.clientWidth, H=confettiWrap.clientHeight;
    for(let i=0;i<n;i++){ const p=document.createElement('div'); const size=6+Math.random()*6;
      p.style.cssText = `position:absolute; left:${Math.random()*W}px; top:-12px; width:${size}px; height:${size*0.6}px;
        background:hsl(${Math.random()*360},90%,60%); transform:rotate(${Math.random()*180}deg); border-radius:2px; box-shadow:0 2px 8px rgba(0,0,0,.35);`;
      confettiWrap.appendChild(p);
      const dx=(Math.random()*2-1)*80, dy=H+80+Math.random()*100, rot=(Math.random()*720+360);
      gsap.to(p,{duration:1.2+Math.random()*0.8, x:dx, y:dy, rotation:rot, ease:'power2.in', onComplete:()=>p.remove()});
    }
  }
  function flashOverlay(color='rgba(255,255,255,0.95)', fade=0.22){
    const f=document.createElement('div');
    Object.assign(f.style,{position:'absolute', inset:'0', background:color, opacity:'0', pointerEvents:'none'});
    stage.appendChild(f);
    gsap.fromTo(f,{opacity:0.9},{opacity:0, duration:fade, ease:'power2.out', onComplete:()=>f.remove()});
  }
  function glowPingAt(x,y){
    const g=document.createElement('div');
    Object.assign(g.style,{position:'absolute', left:(x-12)+'px', top:(y-12)+'px', width:'24px', height:'24px',
      borderRadius:'999px', boxShadow:'0 0 0 0 rgba(255,255,255,0.9), 0 0 30px 10px rgba(212,175,55,0.6)', pointerEvents:'none'});
    stage.appendChild(g);
    gsap.fromTo(g,{scale:0.4,opacity:1},{scale:3,opacity:0,duration:0.6,ease:'power2.out',onComplete:()=>g.remove()});
  }
  function coinSprayAt(x,y,count=18){
    for(let k=0;k<count;k++){
      const c=document.createElement('div'); c.textContent='◆';
      Object.assign(c.style,{position:'absolute', left:x+'px', top:y+'px', fontSize:'16px', color:'#FFDF00', filter:'drop-shadow(0 2px 6px rgba(0,0,0,.5))', pointerEvents:'none'});
      stage.appendChild(c);
      const ang=(Math.PI*2)*Math.random(), dist=60+Math.random()*120, t=0.8+Math.random()*0.4;
      gsap.to(c,{x:Math.cos(ang)*dist, y:Math.sin(ang)*dist-30, opacity:0, rotation:Math.random()*360, duration:t, ease:'power2.out', onComplete:()=>c.remove()});
    }
  }
  function ringAt(x,y, color='#fff', time=0.6, scale=8){
    const r=document.createElement('div');
    Object.assign(r.style,{position:'absolute', left:(x-4)+'px', top:(y-4)+'px', width:'8px', height:'8px',
      border:'3px solid '+color, borderRadius:'999px', pointerEvents:'none', boxShadow:`0 0 14px ${color}`});
    stage.appendChild(r);
    gsap.fromTo(r,{scale:0.2, opacity:1},{scale:scale, opacity:0, duration:time, ease:'power2.out', onComplete:()=>r.remove()});
  }
  function smokeAt(x,y,count=12){
    for(let k=0;k<count;k++){
      const s=document.createElement('div');
      Object.assign(s.style,{position:'absolute', left:x+'px', top:y+'px', width:'12px', height:'12px', borderRadius:'999px',
        background:'radial-gradient(circle, rgba(200,200,200,0.9), rgba(120,120,120,0.0))', pointerEvents:'none'});
      stage.appendChild(s);
      const dx=(Math.random()*2-1)*60, dy=(Math.random()*2-1)*40-20, t=0.8+Math.random()*0.5;
      gsap.to(s,{x:dx, y:dy, scale:2+Math.random(), opacity:0, duration:t, ease:'power1.out', onComplete:()=>s.remove()});
    }
  }

  async function animateChickenTo(i){
    const {cx,cy}=centerFor(i); const targetX=Math.round(cx-CHICK/2), targetY=Math.round(cy-CHICK/2);
    movingToIndex=i; faceTo(targetX); chickenImg.src=CFG.GIF_WALK;
    return new Promise(resolve=>{
      if(moveTween) moveTween.kill();
      moveTween=gsap.to(chicken,{
        duration:CFG.stepDuration, x:targetX, y:targetY, ease:'power1.inOut',
        modifiers:{x:v=>Math.round(parseFloat(v))+'px', y:v=>Math.round(parseFloat(v))+'px'},
        onStart:()=>cameraFollow(i),
        onUpdate:renderPath,
        onComplete:()=>{ chickenImg.src=CFG.GIF_IDLE; movingToIndex=null; renderPath(); resolve(); }
      });
    });
  }

  function showLose(i){
    const mTxt = (multipliers[i]||1).toFixed(2)+'x';
    if (loseMultEl) loseMultEl.textContent = mTxt;
    setTimeout(()=> loseModal && loseModal.classList.add('show'), CFG.modalDelay);
  }
  function showCash(win, mult){
    if (cashWinEl) cashWinEl.textContent = '+'+fmt(win);
    if (cashMultEl) cashMultEl.textContent = mult.toFixed(2)+'x';
    setTimeout(()=> { if (cashModal) cashModal.classList.add('show'); }, CFG.modalDelay);
  }

  function trapCinematic(i){
    freezeCamera();
    setControlsEnabled(false);
    sfx.play('trap'); sfx.play('loss');

    ensureIndex(i);
    const center = bubbles[i] ? bubbles[i].parentElement : null;
    let x = stage.clientWidth/2, y = stage.clientHeight/2;
    if (center){
      const r = center.getBoundingClientRect(), sr = stage.getBoundingClientRect();
      x = r.left - sr.left + r.width/2; y = r.top - sr.top + r.height/2;
    }

    flashOverlay('rgba(255,255,255,0.95)', 0.18);
    ringAt(x,y,'#FF2A54',0.5,6);
    gsap.fromTo(stage,{x:'-1px',y:'1px'},{x:'1px',y:'-1px', duration:0.035, repeat:CFG.trapShakeRepeats, yoyo:true, ease:'none'});
    smokeAt(x,y,14);

    gsap.set(chicken, {autoAlpha:0});
    const b=bubbles[i]; if(b){ b.classList.add('trap'); b.textContent='TRAP'; }
    status('Trap at '+(multipliers[i]||1).toFixed(2)+'x');

    if (currentRoundToken) {
      // The server already settled the bet as a loss during the 'step' request.
      // We just need to clear the token and fetch fresh balance just in case.
      currentRoundToken = null;
      fetchBalanceRequest().then(r => r && typeof r.balance === 'number' && setBalance(r.balance)).catch(()=>{});
    }

    setTimeout(()=>{ setControlsEnabled(true); showLose(i); }, CFG.trapCineTime*1000);
  }

  function cashCinematic(win, m){
    setControlsEnabled(false);
    sfx.play('win');

    const [hx,hy] = chickenCenter();
    glowPingAt(hx,hy); ringAt(hx,hy,'#FFDF00',0.55,7); coinSprayAt(hx,hy,20);

    gsap.to(world,{ scale: CFG.cameraZoom+0.06, duration: CFG.cashCineTime, ease:'power2.out',
      onComplete:()=>gsap.to(world,{scale:CFG.cameraZoom, duration:0.2})});

    confettiBurst(160);
    status('Cashed out: +'+fmt(win));
    setTimeout(()=>{ setControlsEnabled(true); showCash(win, m); }, CFG.cashCineTime*1000);
  }

  function highlightSafe(i){ const b=bubbles[i]; if(!b) return;
    b.classList.remove('trap'); b.classList.toggle('blue', (i%2===1 && i!==0)); }
  function updateCash(){ if(stepCount<=1){ if (cashVal) cashVal.textContent='0.00'; return; }
    const idx = stepCount-1; if (cashVal) cashVal.textContent = fmt(lockedBet*(multipliers[idx]||1)); }

  async function stepForward(){
    if(stepping || animLock) return;
    sfx.play('btn'); sfx.play('tile'); sfx.unlock();

    if(!inRound){
      if(bet>balance){ showToast('Low balance', true); return; }
      lockedBet = bet;
      await newRound();
      updateButtons();
      if(!inRound) return; 
    }
    if(crashed) return;

    const next=stepCount;
    if(next >= multipliers.length-4) ensureRange(0, next+CFG.buildAhead);
    
    // Validate step on server before moving
    stepping=true; setControlsEnabled(false);
    const targetMult = multipliers[next] || multiplierAt(next);
    let stepRes;
    
    try {
      stepRes = await stepRequest(currentRoundToken, targetMult);
      if (stepRes.status !== 'success') {
          throw new Error(stepRes.message || 'Network error');
      }
    } catch(e) {
      showToast(e.message, true);
      stepping=false; setControlsEnabled(true);
      return;
    }

    if (visited[visited.length-1] !== next-1 && next>0){ visited.push(next-1); }

    await animateChickenTo(next); stepCount = next+1; stepping=false; setControlsEnabled(true);
    bubblePress(next); updateCash();

    if (visited[visited.length-1] !== next) visited.push(next);
    renderPath();

    if(stepRes.trap){
      crashed=true; inRound=false; updateButtons();
      trapCinematic(next);
    }else{
      highlightSafe(next); status('Safe: '+(multipliers[next]||1).toFixed(2)+'x'); updateButtons();
    }
  }

  if (minBtn) minBtn.onclick=()=>{ sfx.play('btn'); setBet(1); };
  if (maxBtn) maxBtn.onclick=()=>{ sfx.play('btn'); setBet(Math.min(999999,Math.floor(balance))); };
  document.querySelectorAll('.chipBtn').forEach(el=>el.onclick=()=>{ sfx.play('btn'); setBet(Number(betInput.value)+Number(el.dataset.chip)); });
  if (betInput) betInput.oninput=()=>setBet(betInput.value);

  if (goBtn) goBtn.onclick=()=>{ if(!inRound && stepCount>1) resetAll(); stepForward(); };
  if (cashBtn) cashBtn.onclick=()=>{
    if(!(inRound && !crashed && stepCount>1)) return;
    const idx = stepCount-1, m = multipliers[idx] || 1;
    const win = lockedBet * m;            
    inRound=false; crashed=false; updateButtons();
    cashCinematic(win, m);

    if (currentRoundToken) {
      settleBetRequest(currentRoundToken)
        .then(r => {
            if (r.status === 'success' && r.balance !== undefined) setBalance(r.balance);
        })
        .finally(() => {
          currentRoundToken = null;
          fetchBalanceRequest().then(r => r && typeof r.balance === 'number' && setBalance(r.balance)).catch(()=>{});
        });
    }
  };
  if (cashOkBtn) cashOkBtn.onclick=()=>{ sfx.play('btn'); if (cashModal) cashModal.classList.remove('show'); resetAll(); };
  if (retryBtn) retryBtn.onclick=()=>{ sfx.play('btn'); if (loseModal) loseModal.classList.remove('show'); resetAll(); };

  setBalance(balance);
  setBet(bet);
  resetAll();

  fetchSettingsRequest().then(res => {
    if (res && res.status === 'success' && res.settings) {
      if (!isNaN(parseFloat(res.settings.win_rate))) CFG.winRate = parseFloat(res.settings.win_rate);
      if (!isNaN(parseInt(res.settings.min_safe_steps))) CFG.minSafeSteps = parseInt(res.settings.min_safe_steps);
      if (!isNaN(parseFloat(res.settings.win_falloff_per_step))) CFG.winFalloffPerStep = parseFloat(res.settings.win_falloff_per_step);
    }
  }).catch(()=>{});
  fetchBalanceRequest().then(res => {
    if (res && typeof res.balance === 'number') setBalance(res.balance);
  }).catch(()=>{});

  let lastTouchEnd=0; document.addEventListener('touchend', e=>{ const now=Date.now(); if(now-lastTouchEnd<=300){ e.preventDefault(); } lastTouchEnd=now; }, {passive:false});
}
</script>
</body>
</html>