<?php
session_start();
if (!isset($_SESSION['user_id']) || empty($_SESSION['user_id'])) {
    header('Location: /login.php');
    exit;
}
require_once __DIR__ . '/../config.php';

// Fetch native balance
$stmt = $pdo->prepare("SELECT balance FROM users WHERE id = ?");
$stmt->execute([$_SESSION['user_id']]);
$balance = (float)$stmt->fetchColumn();
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>92Rush - Fortune Slots</title>
<meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1,viewport-fit=cover">
<meta name="theme-color" content="#2cd3b1">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link href="https://fonts.googleapis.com/css2?family=Nunito:wght@400;600;700;800;900&display=swap" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css">
<style>
:root{
  --g1:#2cd3b1;--g2:#06a182;--orange:#f15533;--amber:#ff9e34;--gold:#ffcc4d;--gold-dark:#c8960c;
  --bg:#f4f6fb;--card:#ffffff;--text:#0a1628;--soft:#6c7a8a;--border:rgba(10,22,40,.06);
  --radius:16px;--pill:999px;--shadow:0 4px 24px rgba(0,0,0,.08);
}
*,*::before,*::after{box-sizing:border-box;margin:0;padding:0}
html{font-size:16px}
body{font-family:'Nunito',system-ui,sans-serif;background:#e8ecf2;color:var(--text);-webkit-font-smoothing:antialiased}
.app-wrap{max-width:460px;margin:0 auto;min-height:100vh;background:var(--bg);position:relative;overflow-x:hidden;box-shadow:0 0 80px rgba(0,0,0,.18)}
@media(min-width:520px){body{background:#1a1f2e}.app-wrap{border-radius:28px;margin-top:12px;margin-bottom:12px;min-height:calc(100vh - 24px)}}

.top-bar{display:flex;align-items:center;justify-content:space-between;padding:10px 14px 8px;background:linear-gradient(135deg,var(--g1),var(--g2));color:#fff;position:sticky;top:0;z-index:100}
.top-logo{display:flex;align-items:center;gap:8px}
.logo-icon{width:36px;height:36px;border-radius:50%;background:radial-gradient(circle at 30% 25%,var(--gold),var(--amber));display:flex;align-items:center;justify-content:center;font-weight:900;font-size:15px;color:#3a2200;box-shadow:0 3px 12px rgba(255,158,52,.6)}
.logo-text{font-weight:900;font-size:18px;letter-spacing:-.3px}
.logo-sub{font-size:9px;opacity:.8;display:block;margin-top:-2px}
.top-right{display:flex;align-items:center;gap:8px}
.bal-pill{display:flex;align-items:center;gap:5px;background:rgba(0,0,0,.25);border-radius:var(--pill);padding:4px 10px;font-size:11px;backdrop-filter:blur(6px)}
.bal-pill .cur{opacity:.8;font-size:10px}.bal-pill .amt{font-weight:800;font-size:13px}
.top-icon{width:32px;height:32px;border-radius:50%;background:rgba(0,0,0,.3);border:none;color:#fff;font-size:14px;cursor:pointer;display:flex;align-items:center;justify-content:center;text-decoration:none}

.page-body{padding:10px 12px 80px;min-height:calc(100vh - 130px)}

@media(max-width:380px){
  .top-bar{padding:8px 10px 6px}
  .logo-icon{width:30px;height:30px;font-size:13px}
  .logo-text{font-size:15px}
  .bal-pill .amt{font-size:11px}
  .page-body{padding:8px 8px 74px}
}

/* Slots CSS */
.slots-page{min-height:100vh;background:linear-gradient(180deg,#b91c1c 0%,#991b1b 25%,#7f1d1d 60%,#450a0a 100%);position:relative;overflow:hidden;border-radius:inherit;}
.slots-page::before{content:'';position:absolute;inset:0;background:radial-gradient(circle at 50% 20%,rgba(254,240,138,.12) 0%,transparent 50%);pointer-events:none;}
.slots-petals{position:absolute;inset:0;pointer-events:none;overflow:hidden;}
.slots-petal{position:absolute;width:12px;height:12px;border-radius:50%;background:radial-gradient(circle,#fecdd3,#fda4af);opacity:.5;animation:spFall 8s linear infinite;}
.slots-petal:nth-child(1){left:5%;top:-5%;animation-delay:0s;}
.slots-petal:nth-child(2){left:25%;top:-8%;animation-delay:1.5s;}
.slots-petal:nth-child(3){left:50%;top:-4%;animation-delay:3s;}
.slots-petal:nth-child(4){left:75%;top:-6%;animation-delay:2s;}
.slots-petal:nth-child(5){left:90%;top:-3%;animation-delay:4s;}
@keyframes spFall{0%{transform:translateY(0) rotate(0deg);opacity:.5}100%{transform:translateY(100vh) rotate(360deg);opacity:0}}

.slots-head{text-align:center;padding:12px 12px 6px;position:relative;}
.slots-head h1{font-size:22px;font-weight:900;color:#fef08a;text-shadow:0 2px 12px rgba(0,0,0,.5),0 0 24px rgba(254,240,138,.4);letter-spacing:1px;}
.slots-bal{text-align:center;padding:6px 12px 12px;}
.slots-bal-lbl{font-size:11px;color:rgba(255,255,255,.85);font-weight:700;margin-bottom:4px;}
.slots-bal-amt{font-size:26px;font-weight:900;color:#fef08a;text-shadow:0 2px 12px rgba(0,0,0,.4);}

.slots-mascot{text-align:center;padding:4px 0 8px;font-size:48px;line-height:1;filter:drop-shadow(0 4px 12px rgba(0,0,0,.4));}
.slots-mascot span{display:inline-block;animation:slotsBounce 1.2s ease-in-out infinite;}

.slots-arena{position:relative;padding:8px 16px 16px;}
.slots-frame{background:linear-gradient(180deg,#1c1917 0%,#292524 50%,#1c1917 100%);border-radius:20px;padding:14px;border:4px solid #fbbf24;box-shadow:0 0 0 3px #92400e,0 12px 40px rgba(0,0,0,.6),inset 0 0 30px rgba(251,191,36,.15);position:relative;}

/* Confetti canvas */
#slots-confetti{position:absolute;inset:0;pointer-events:none;z-index:10;width:100%;height:100%;}

.slots-paylines{display:flex;justify-content:space-between;margin-bottom:8px;padding:0 4px;}
.slots-payline{width:28px;height:36px;background:linear-gradient(180deg,#b91c1c,#7f1d1d);border:2px solid #fbbf24;border-radius:6px;display:flex;align-items:center;justify-content:center;font-size:11px;font-weight:900;color:#fef08a;cursor:pointer;position:relative;transition:transform .2s;}
.slots-payline:hover{transform:scale(1.1);}
.slots-payline.active-line{background:linear-gradient(180deg,#eab308,#ca8a04);box-shadow:0 0 10px #fef08a;}

/* Glowing Payline Indicators */
.payline-glow{position:absolute;background:rgba(251,191,36,0.85);z-index:5;pointer-events:none;border-radius:4px;box-shadow:0 0 12px #fbbf24;display:none;animation:linePulse 0.5s ease-in-out infinite alternate;}
@keyframes linePulse{0%{opacity:0.4;box-shadow:0 0 6px #fbbf24;}100%{opacity:1;box-shadow:0 0 16px #fef08a;}}

.slots-grid{display:grid;grid-template-columns:repeat(3,1fr);gap:8px;aspect-ratio:1;max-width:260px;margin:0 auto;position:relative;z-index:2;}
.slots-cell{background:linear-gradient(145deg,#44403c,#292524);border-radius:12px;border:2px solid #57534e;display:flex;align-items:center;justify-content:center;font-size:16px;font-weight:900;color:#fef08a;text-shadow:0 1px 4px rgba(0,0,0,.5);min-height:64px;transition:transform .2s,box-shadow .2s;user-select:none;}
.slots-cell.reveal{animation:slotsReveal .4s ease-out;}
.slots-cell.win{box-shadow:0 0 24px rgba(134,239,172,.85);border-color:#86efac;animation:winPulse 0.6s ease-in-out infinite alternate;}
@keyframes slotsReveal{0%{transform:scale(0.8);opacity:.5}100%{transform:scale(1);opacity:1}}
@keyframes slotsBounce{0%,100%{transform:translateY(0)}50%{transform:translateY(-6px)}}
@keyframes winPulse{0%{transform:scale(1);}100%{transform:scale(1.05);}}

@keyframes blur-spin {
  0% { filter: blur(0px); transform: translateY(0); }
  50% { filter: blur(3px); transform: translateY(-8px); }
  100% { filter: blur(0px); transform: translateY(0); }
}
.slots-cell.spinning {
  animation: blur-spin 0.12s linear infinite;
  background: linear-gradient(145deg, #2b2520, #141210) !important;
  color: rgba(254,240,138,0.5) !important;
}

.slots-cell[data-id="wild"]{background:linear-gradient(145deg,#fbbf24,#d97706);color:#1c1917;border-color:#fef08a;}
.slots-cell[data-id="x5"]{background:linear-gradient(145deg,#dc2626,#b91c1c);color:#fef08a;}
.slots-cell[data-id="x3"]{background:linear-gradient(145deg,#059669,#047857);color:#a7f3d0;}
.slots-cell[data-id="x2"]{background:linear-gradient(145deg,#7c3aed,#5b21b6);color:#e9d5ff;}
.slots-cell[data-id="x1"]{background:linear-gradient(145deg,#0284c7,#0369a1);color:#bae6fd;}
.slots-cell[data-id="x05"]{background:linear-gradient(145deg,#64748b,#475569);color:#e2e8f0;}
.slots-cell[data-id="x0"]{background:linear-gradient(145deg,#44403c,#292524);color:#78716c;}

.slots-banner{text-align:center;padding:10px 16px;margin:0 16px 12px;background:linear-gradient(90deg,#b91c1c,#dc2626,#b91c1b);border-radius:12px;border:2px solid #fbbf24;box-shadow:0 4px 16px rgba(0,0,0,.3);display:flex;justify-content:space-between;align-items:center;}
.slots-banner span{font-size:13px;font-weight:900;color:#fef08a;text-shadow:0 1px 4px rgba(0,0,0,.5);}
.slots-info-btn{background:rgba(0,0,0,0.3);border:1px solid rgba(254,240,138,0.5);color:#fef08a;font-size:11px;font-weight:800;padding:4px 8px;border-radius:6px;cursor:pointer;outline:none;transition:all 0.2s;}
.slots-info-btn:hover{background:rgba(254,240,138,0.2);transform:scale(1.05);}

.slots-dock{background:rgba(0,0,0,.35);backdrop-filter:blur(10px);margin:0 12px 20px;border-radius:16px;padding:14px 12px;border:1px solid rgba(251,191,36,.3);}
.slots-dock-row{display:flex;align-items:center;gap:8px;margin-bottom:10px;}
.slots-dock-input{flex:1;position:relative;}
.slots-dock-input input{width:100%;border-radius:12px;border:2px solid rgba(251,191,36,.4);padding:12px 42px 12px 14px;font-size:14px;font-weight:800;background:rgba(28,25,23,.8);color:#fef08a;outline:none;}
.slots-dock-input input::placeholder{color:rgba(254,240,138,.5);}
.slots-dock-input input:focus{border-color:#fbbf24;}
.slots-dock-input span{position:absolute;right:12px;top:50%;transform:translateY(-50%);font-size:11px;font-weight:700;color:rgba(254,240,138,.9);}
.slots-spin-btn{min-width:110px;border:none;border-radius:14px;padding:14px 0;font-size:16px;font-weight:900;color:#1c1917;cursor:pointer;background:linear-gradient(135deg,#86efac,#22c55e);box-shadow:0 4px 20px rgba(34,197,94,.5);transition:transform .1s;}
.slots-spin-btn:active{transform:scale(.97);}
.slots-spin-btn:disabled{opacity:.6;cursor:not-allowed;transform:none;}

.slots-aux-row{display:flex;justify-content:space-between;align-items:center;margin-bottom:10px;padding:0 4px;}
.slots-auto-btn{background:rgba(255,255,255,0.08);border:1px solid rgba(255,255,255,0.15);color:#fff;font-size:12px;font-weight:700;padding:6px 12px;border-radius:10px;cursor:pointer;display:flex;align-items:center;gap:6px;transition:all 0.2s;}
.slots-auto-btn.active{background:rgba(234,179,8,0.2);border-color:#eab308;color:#fef08a;box-shadow:0 0 10px rgba(234,179,8,0.3);}
.slots-audio-btn{background:rgba(255,255,255,0.08);border:1px solid rgba(255,255,255,0.15);color:#fff;font-size:12px;font-weight:700;width:32px;height:32px;border-radius:50%;cursor:pointer;display:flex;align-items:center;justify-content:center;transition:all 0.2s;}
.slots-audio-btn:hover{background:rgba(255,255,255,0.15);}

.slots-dock-hint{font-size:10px;color:rgba(255,255,255,.7);text-align:center;}
.slots-msg{text-align:center;font-size:13px;font-weight:800;margin-top:10px;min-height:20px;transition:all 0.2s;}
.slots-msg.win{color:#86efac;text-shadow:0 0 12px rgba(134,239,172,.5);font-size:15px;animation:winTextBounce 0.4s ease-in-out;}
.slots-msg.lose{color:#fca5a5;}
@keyframes winTextBounce{0%{transform:scale(0.8);}50%{transform:scale(1.15);}100%{transform:scale(1);}}

/* Modal popup */
.slots-modal{position:absolute;inset:0;background:rgba(0,0,0,0.85);backdrop-filter:blur(8px);z-index:100;display:flex;align-items:center;justify-content:center;opacity:0;pointer-events:none;transition:opacity 0.25s;}
.slots-modal.open{opacity:1;pointer-events:auto;}
.slots-modal-content{background:#292524;border:2px solid #fbbf24;border-radius:18px;width:90%;max-width:360px;padding:20px;box-shadow:0 12px 32px rgba(0,0,0,0.6);color:#fff;position:relative;}
.slots-modal-close{position:absolute;top:12px;right:14px;background:none;border:none;color:rgba(255,255,255,0.6);font-size:18px;cursor:pointer;}
.slots-modal-close:hover{color:#fff;}
.slots-modal-title{font-size:18px;font-weight:900;color:#fef08a;margin-bottom:12px;text-align:center;}
.slots-table{width:100%;border-collapse:collapse;margin-top:10px;font-size:13px;}
.slots-table th, .slots-table td{padding:8px 10px;text-align:left;border-bottom:1px solid #44403c;}
.slots-table th{color:#fef08a;font-weight:800;}
.slots-table td span{display:inline-block;padding:2px 6px;border-radius:6px;font-weight:800;}

/* Bottom Navbar style overrides matching Footer.php */
.bottom-nav{position:fixed;bottom:0;left:50%;transform:translateX(-50%);width:100%;max-width:460px;display:flex;align-items:flex-end;justify-content:space-around;padding:6px 4px 10px;background:var(--card);border-top:1px solid var(--border);z-index:200}
.bnav{display:flex;flex-direction:column;align-items:center;gap:2px;text-decoration:none;color:var(--soft);font-size:10px;flex:1}
.bnav i{font-size:18px}
.bnav-on{color:var(--g2);font-weight:700}
.fab-wrap{display:flex;flex-direction:column;align-items:center;gap:2px;text-decoration:none;flex:1;margin-top:-28px}
.fab{width:52px;height:52px;border-radius:50%;background:conic-gradient(from 200deg,var(--orange),var(--amber),var(--gold),var(--orange));display:flex;align-items:center;justify-content:center;color:#2a0f00;font-size:20px;box-shadow:0 6px 20px rgba(241,85,51,.5)}
.fab-txt{font-size:9px;color:var(--orange);font-weight:700;margin-top:2px}
@media(max-width:380px){.fab{width:44px;height:44px;font-size:17px}.fab-wrap{margin-top:-22px}.bottom-nav{padding:4px 2px 8px}.bnav i{font-size:15px}.bnav{font-size:9px}}
</style>
</head>
<body>
<div class="app-wrap">
  <header class="top-bar">
    <div class="top-logo">
      <div class="logo-icon">92</div>
      <div><span class="logo-text">92Rush</span><span class="logo-sub">Crypto Casino</span></div>
    </div>
    <div class="top-right">
      <div class="bal-pill"><span class="cur" id="hdr-cur">PKR</span><span class="amt" id="hdr-bal"><?php echo number_format($balance, 2); ?></span></div>
      <a class="top-icon" href="/Account.php"><i class="fa-solid fa-user"></i></a>
    </div>
  </header>

  <div class="page-body" style="padding:0; min-height:calc(100vh - 120px);">
    <div class="slots-page">
      <div class="slots-petals">
        <div class="slots-petal"></div><div class="slots-petal"></div><div class="slots-petal"></div>
        <div class="slots-petal"></div><div class="slots-petal"></div>
      </div>
      
      <!-- Payline glowing lines -->
      <!-- row 0 -->
      <div class="payline-glow" id="glow-line-0" style="left:14px; top:calc(14px + 30px); width:calc(100% - 28px); height:4px;"></div>
      <!-- row 1 -->
      <div class="payline-glow" id="glow-line-1" style="left:14px; top:calc(14px + 30px + 72px); width:calc(100% - 28px); height:4px;"></div>
      <!-- row 2 -->
      <div class="payline-glow" id="glow-line-2" style="left:14px; top:calc(14px + 30px + 144px); width:calc(100% - 28px); height:4px;"></div>
      <!-- diag \ -->
      <div class="payline-glow" id="glow-line-3" style="left:14px; top:14px; width:calc(100% - 28px); height:4px; transform:rotate(45deg); transform-origin:top left;"></div>
      <!-- diag / -->
      <div class="payline-glow" id="glow-line-4" style="left:14px; bottom:14px; width:calc(100% - 28px); height:4px; transform:rotate(-45deg); transform-origin:bottom left;"></div>

      <div class="slots-head">
        <h1>Fortune Slots</h1>
      </div>
      <div class="slots-mascot"><span>🐯</span></div>
      <div class="slots-bal">
        <div class="slots-bal-lbl">Balance</div>
        <div class="slots-bal-amt" id="slots-bal-amt">PKR <?php echo number_format($balance, 2); ?></div>
      </div>
      
      <div class="slots-arena">
        <div class="slots-frame">
          <canvas id="slots-confetti"></canvas>
          <div class="slots-paylines">
            <div class="slots-payline" data-line="0" title="Top Row">1</div>
            <div class="slots-payline" data-line="1" title="Middle Row">2</div>
            <div class="slots-payline" data-line="2" title="Bottom Row">3</div>
            <div class="slots-payline" data-line="3" title="Diagonal Down">4</div>
            <div class="slots-payline" data-line="4" title="Diagonal Up">5</div>
          </div>
          <div class="slots-grid">
            <div class="slots-cell" data-id="">?</div>
            <div class="slots-cell" data-id="">?</div>
            <div class="slots-cell" data-id="">?</div>
            <div class="slots-cell" data-id="">?</div>
            <div class="slots-cell" data-id="">?</div>
            <div class="slots-cell" data-id="">?</div>
            <div class="slots-cell" data-id="">?</div>
            <div class="slots-cell" data-id="">?</div>
            <div class="slots-cell" data-id="">?</div>
          </div>
        </div>
        <div class="slots-banner">
          <span>Win up to 5x!</span>
          <button class="slots-info-btn" id="slots-paytable-btn"><i class="fa-solid fa-circle-info"></i> Paytable</button>
        </div>
      </div>

      <div class="slots-dock">
        <div class="slots-aux-row">
          <button type="button" class="slots-auto-btn" id="slots-auto">
            <i class="fa-solid fa-rotate"></i><span>AUTO SPIN: OFF</span>
          </button>
          <button type="button" class="slots-audio-btn" id="slots-audio" title="Toggle Sound">
            <i class="fa-solid fa-volume-high"></i>
          </button>
        </div>
        <div class="slots-dock-row">
          <div class="slots-dock-input">
            <input type="number" id="slots-amt" min="10" step="10" value="100" inputmode="decimal">
            <span id="slots-currency-lbl">PKR</span>
          </div>
          <button type="button" class="slots-spin-btn" id="slots-spin">SPIN</button>
        </div>
        <div class="slots-dock-hint" id="slots-hint">Min PKR 10. 5 paylines. WILD substitutes all.</div>
        <div class="slots-msg" id="slots-msg"></div>
      </div>
    </div>
  </div>

  <!-- Paytable Modal -->
  <div class="slots-modal" id="slots-modal">
    <div class="slots-modal-content">
      <button class="slots-modal-close" id="slots-modal-close"><i class="fa-solid fa-xmark"></i></button>
      <div class="slots-modal-title"><i class="fa-solid fa-list-ol"></i> Symbols & Multipliers</div>
      <table class="slots-table">
        <thead>
          <tr>
            <th>Symbol</th>
            <th>Type</th>
            <th>Payout (3-in-a-row)</th>
          </tr>
        </thead>
        <tbody>
          <tr>
            <td><span style="background:linear-gradient(145deg,#fbbf24,#d97706); color:#1c1917;">WILD</span></td>
            <td>Wild Card</td>
            <td>5x / Substitutes all</td>
          </tr>
          <tr>
            <td><span style="background:linear-gradient(145deg,#dc2626,#b91c1c); color:#fef08a;">5x</span></td>
            <td>Premium</td>
            <td>5x Bet</td>
          </tr>
          <tr>
            <td><span style="background:linear-gradient(145deg,#059669,#047857); color:#a7f3d0;">3x</span></td>
            <td>High</td>
            <td>3x Bet</td>
          </tr>
          <tr>
            <td><span style="background:linear-gradient(145deg,#7c3aed,#5b21b6); color:#e9d5ff;">2x</span></td>
            <td>Medium</td>
            <td>2x Bet</td>
          </tr>
          <tr>
            <td><span style="background:linear-gradient(145deg,#0284c7,#0369a1); color:#bae6fd;">1x</span></td>
            <td>Standard</td>
            <td>1x Bet</td>
          </tr>
          <tr>
            <td><span style="background:linear-gradient(145deg,#64748b,#475569); color:#e2e8f0;">0.5x</span></td>
            <td>Low</td>
            <td>0.5x Bet</td>
          </tr>
          <tr>
            <td><span style="background:linear-gradient(145deg,#44403c,#292524); color:#78716c;">0</span></td>
            <td>Blank</td>
            <td>No Payout</td>
          </tr>
        </tbody>
      </table>
      <div style="font-size:11px; color:rgba(255,255,255,0.7); margin-top:14px; line-height:1.4;">
        * Wins are calculated across 5 paylines (3 horizontal rows, 2 diagonals).<br>
        * Wild matches any symbol. Wild-only wins trigger 5x payout.
      </div>
    </div>
  </div>

  <nav class="bottom-nav">
    <a href="/Dashboard.php" class="bnav"><i class="fa-solid fa-house"></i><span>Home</span></a>
    <a href="/Activity.php" class="bnav"><i class="fa-solid fa-fire"></i><span>Activity</span></a>
    <a href="/Refer.php" class="fab-wrap">
      <span class="fab"><i class="fa-solid fa-crown"></i></span>
      <span class="fab-txt">Promote</span>
    </a>
    <a href="/Wingo.php" class="bnav"><i class="fa-solid fa-dice"></i><span>Wingo</span></a>
    <a href="/Account.php" class="bnav"><i class="fa-solid fa-wallet"></i><span>Account</span></a>
  </nav>
</div>

<script>
(function(){
  const $=s=>document.querySelector(s);
  const $$=s=>document.querySelectorAll(s);

  const SLOTS_SYMBOLS = [
    {id: 'wild', mult: 5,  label: 'WILD', weight: 5},
    {id: 'x5',   mult: 5,  label: '5x',   weight: 5},
    {id: 'x3',   mult: 3,  label: '3x',   weight: 8},
    {id: 'x2',   mult: 2,  label: '2x',   weight: 12},
    {id: 'x1',   mult: 1,  label: '1x',   weight: 15},
    {id: 'x05',  mult: 0.5,label: '0.5x', weight: 15},
    {id: 'x0',   mult: 0,  label: '0',    weight: 40}
  ];

  const symMap = {};
  SLOTS_SYMBOLS.forEach(s => symMap[s.id] = s);

  const SLOTS_PAYLINES = [
    [0, 1, 2],
    [3, 4, 5],
    [6, 7, 8],
    [0, 4, 8],
    [2, 4, 6]
  ];

  let state = {
    balance: <?php echo $balance; ?>,
    currency: 'PKR',
    isSpinning: false,
    autoSpin: false,
    soundEnabled: true,
    autoSpinTimer: null
  };

  let audioCtx = null;
  function initAudio() {
    if (!audioCtx) {
      audioCtx = new (window.AudioContext || window.webkitAudioContext)();
    }
    if (audioCtx.state === 'suspended') {
      audioCtx.resume();
    }
  }

  function playSound(type) {
    if (!state.soundEnabled) return;
    try {
      initAudio();
      if (!audioCtx) return;
      const osc = audioCtx.createOscillator();
      const gain = audioCtx.createGain();
      osc.connect(gain);
      gain.connect(audioCtx.destination);
      const now = audioCtx.currentTime;

      if (type === 'spin_tick') {
        osc.type = 'sine';
        osc.frequency.setValueAtTime(600, now);
        osc.frequency.exponentialRampToValueAtTime(100, now + 0.04);
        gain.gain.setValueAtTime(0.04, now);
        gain.gain.exponentialRampToValueAtTime(0.001, now + 0.04);
        osc.start(now);
        osc.stop(now + 0.04);
      } else if (type === 'stop') {
        osc.type = 'triangle';
        osc.frequency.setValueAtTime(260, now);
        osc.frequency.setValueAtTime(130, now + 0.06);
        gain.gain.setValueAtTime(0.12, now);
        gain.gain.exponentialRampToValueAtTime(0.001, now + 0.1);
        osc.start(now);
        osc.stop(now + 0.1);
      } else if (type === 'win') {
        const notes = [261.63, 329.63, 392.00, 523.25, 659.25, 783.99, 1046.50];
        notes.forEach((freq, idx) => {
          const o = audioCtx.createOscillator();
          const g = audioCtx.createGain();
          o.connect(g);
          g.connect(audioCtx.destination);
          const t = now + idx * 0.07;
          o.type = 'triangle';
          o.frequency.setValueAtTime(freq, t);
          g.gain.setValueAtTime(0.08, t);
          g.gain.exponentialRampToValueAtTime(0.001, t + 0.12);
          o.start(t);
          o.stop(t + 0.14);
        });
      } else if (type === 'lose') {
        osc.type = 'sine';
        osc.frequency.setValueAtTime(200, now);
        osc.frequency.linearRampToValueAtTime(90, now + 0.25);
        gain.gain.setValueAtTime(0.12, now);
        gain.gain.exponentialRampToValueAtTime(0.001, now + 0.25);
        osc.start(now);
        osc.stop(now + 0.25);
      } else if (type === 'click') {
        osc.type = 'sine';
        osc.frequency.setValueAtTime(400, now);
        gain.gain.setValueAtTime(0.05, now);
        gain.gain.exponentialRampToValueAtTime(0.001, now + 0.05);
        osc.start(now);
        osc.stop(now + 0.05);
      }
    } catch (e) {
      console.error('Audio error:', e);
    }
  }

  function triggerConfetti() {
    const canvas = $('#slots-confetti');
    if (!canvas) return;
    const ctx = canvas.getContext('2d');
    canvas.width = canvas.parentElement.clientWidth;
    canvas.height = canvas.parentElement.clientHeight;

    const particles = [];
    const colors = ['#fecdd3', '#fda4af', '#fbbf24', '#fef08a', '#86efac', '#60a5fa', '#c084fc'];
    
    for (let i = 0; i < 70; i++) {
      particles.push({
        x: canvas.width / 2,
        y: canvas.height / 2 + (Math.random() - 0.5) * 20,
        vx: (Math.random() - 0.5) * 10,
        vy: (Math.random() - 0.5) * 10 - 5,
        size: Math.random() * 6 + 4,
        color: colors[Math.floor(Math.random() * colors.length)],
        alpha: 1,
        decay: Math.random() * 0.015 + 0.01
      });
    }

    function anim() {
      ctx.clearRect(0, 0, canvas.width, canvas.height);
      let active = false;
      for (const p of particles) {
        if (p.alpha <= 0) continue;
        active = true;
        p.x += p.vx;
        p.y += p.vy;
        p.vy += 0.2;
        p.alpha -= p.decay;

        ctx.save();
        ctx.globalAlpha = p.alpha;
        ctx.fillStyle = p.color;
        ctx.beginPath();
        ctx.arc(p.x, p.y, p.size, 0, Math.PI * 2);
        ctx.fill();
        ctx.restore();
      }
      if (active) requestAnimationFrame(anim);
    }
    anim();
  }

  function fmt(val) {
    return state.currency + ' ' + val.toLocaleString('en-US', {minimumFractionDigits: 2, maximumFractionDigits: 2});
  }

  function updateBalanceDisplay() {
    $('#hdr-cur').textContent = state.currency;
    $('#hdr-bal').textContent = state.balance.toLocaleString('en-US', {minimumFractionDigits: 2, maximumFractionDigits: 2});
    $('#slots-bal-amt').textContent = fmt(state.balance);
  }

  function updateAudioBtn() {
    const btn = $('#slots-audio');
    if (state.soundEnabled) {
      btn.innerHTML = '<i class="fa-solid fa-volume-high"></i>';
      btn.style.color = '#fbbf24';
    } else {
      btn.innerHTML = '<i class="fa-solid fa-volume-xmark"></i>';
      btn.style.color = '#9ca3af';
    }
  }

  function clearHighlights() {
    $$('.slots-cell').forEach(c => {
      c.className = 'slots-cell';
      c.style.animation = '';
    });
    $$('.payline-glow').forEach(l => l.style.display = 'none');
    $$('.slots-payline').forEach(p => p.classList.remove('active-line'));
  }

  function highlightWin(grid) {
    let winningLines = [];
    SLOTS_PAYLINES.forEach((line, index) => {
      const ids = [grid[line[0]], grid[line[1]], grid[line[2]]];
      const mults = [];
      let wildCount = 0;
      let valid = true;

      for (const id of ids) {
        const s = symMap[id];
        if (!s) { valid = false; break; }
        if (id === 'wild') { wildCount++; mults.push(5.0); } 
        else { mults.push(parseFloat(s.mult)); }
      }
      if (!valid) return;

      let lineMult = 0.0;
      if (wildCount === 3) {
        lineMult = 5.0;
      } else {
        const nonWildMults = [];
        for (let i = 0; i < ids.length; i++) {
          if (ids[i] !== 'wild') {
            nonWildMults.push(mults[i]);
          }
        }
        if (wildCount === 2) {
          lineMult = nonWildMults[0];
        } else if (wildCount === 1) {
          lineMult = (nonWildMults[0] === nonWildMults[1]) ? nonWildMults[0] : 0.0;
        } else {
          lineMult = (mults[0] === mults[1] && mults[1] === mults[2]) ? mults[0] : 0.0;
        }
      }
      if (lineMult > 0.0) {
        winningLines.push(index);
      }
    });

    winningLines.forEach(lineIdx => {
      const badge = $(`.slots-payline[data-line="${lineIdx}"]`);
      if (badge) badge.classList.add('active-line');
      const glow = $(`#glow-line-${lineIdx}`);
      if (glow) glow.style.display = 'block';

      const cells = SLOTS_PAYLINES[lineIdx];
      cells.forEach(cIdx => {
        const cell = $$('.slots-cell')[cIdx];
        if (cell) cell.classList.add('win');
      });
    });
  }

  async function spin() {
    if (state.isSpinning) return;

    const input = $('#slots-amt');
    const betVal = parseFloat(input.value);

    if (isNaN(betVal) || betVal < 10) {
      showMsg('Minimum bet is ' + fmt(10), 'lose');
      stopAutoSpin();
      return;
    }

    if (betVal > state.balance) {
      showMsg('Insufficient balance', 'lose');
      stopAutoSpin();
      return;
    }

    state.isSpinning = true;
    state.balance -= betVal;
    updateBalanceDisplay();
    clearHighlights();

    $('#slots-spin').disabled = true;
    input.disabled = true;
    showMsg('Spinning...', '');

    const cells = $$('.slots-cell');
    const spinIntervals = [];
    const soundInterval = setInterval(() => { playSound('spin_tick'); }, 130);

    cells.forEach((c, idx) => {
      c.classList.add('spinning');
      const col = idx % 3;
      const interval = setInterval(() => {
        const randId = SLOTS_SYMBOLS[Math.floor(Math.random() * SLOTS_SYMBOLS.length)].id;
        c.textContent = symMap[randId].label;
        c.dataset.id = randId;
      }, 70 + col * 20);
      spinIntervals.push(interval);
    });

    try {
      const res = await fetch('api.php?action=spin', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ amount: betVal })
      });
      const data = await res.json();
      
      if (!data.ok) {
        throw new Error(data.msg || 'Server Error');
      }

      state.balance = data.balance;
      const finalGrid = data.grid;
      const multiplier = data.multiplier;
      const payout = data.payout;
      const isWin = data.is_win;

      const stopCol = (colIdx) => {
        [0, 1, 2].forEach(row => {
          const i = row * 3 + colIdx;
          clearInterval(spinIntervals[i]);
          const c = cells[i];
          c.classList.remove('spinning');
          c.textContent = symMap[finalGrid[i]].label;
          c.dataset.id = finalGrid[i];
          c.classList.add('reveal');
        });
        playSound('stop');
      };

      setTimeout(() => stopCol(0), 600);
      setTimeout(() => stopCol(1), 1100);
      setTimeout(() => {
        stopCol(2);
        clearInterval(soundInterval);

        updateBalanceDisplay();

        if (isWin) {
          highlightWin(finalGrid);
          triggerConfetti();
          playSound('win');
          showMsg(`You won ${fmt(payout)} (${multiplier}x)!`, 'win');
        } else {
          playSound('lose');
          showMsg('No win this spin.', 'lose');
        }

        state.isSpinning = false;
        $('#slots-spin').disabled = false;
        input.disabled = false;

        if (state.autoSpin) {
          state.autoSpinTimer = setTimeout(() => { spin(); }, 1500);
        }
      }, 1600);

    } catch (e) {
      clearInterval(soundInterval);
      spinIntervals.forEach(i => clearInterval(i));
      cells.forEach(c => c.classList.remove('spinning'));
      showMsg('Error: ' + e.message, 'lose');
      state.isSpinning = false;
      $('#slots-spin').disabled = false;
      input.disabled = false;
      stopAutoSpin();
    }
  }

  function showMsg(text, type) {
    const el = $('#slots-msg');
    el.textContent = text;
    el.className = 'slots-msg ' + type;
  }

  function toggleAutoSpin() {
    playSound('click');
    if (state.autoSpin) {
      stopAutoSpin();
    } else {
      state.autoSpin = true;
      $('#slots-auto').classList.add('active');
      $('#slots-auto span').textContent = 'AUTO SPIN: ON';
      if (!state.isSpinning) spin();
    }
  }

  function stopAutoSpin() {
    state.autoSpin = false;
    $('#slots-auto').classList.remove('active');
    $('#slots-auto span').textContent = 'AUTO SPIN: OFF';
    if (state.autoSpinTimer) {
      clearTimeout(state.autoSpinTimer);
      state.autoSpinTimer = null;
    }
  }

  function toggleSound() {
    state.soundEnabled = !state.soundEnabled;
    updateAudioBtn();
    playSound('click');
  }

  function openModal() {
    playSound('click');
    $('#slots-modal').classList.add('open');
  }

  function closeModal() {
    playSound('click');
    $('#slots-modal').classList.remove('open');
  }

  document.addEventListener('DOMContentLoaded', () => {
    updateAudioBtn();
    $('#slots-spin').addEventListener('click', () => {
      stopAutoSpin();
      spin();
    });
    $('#slots-auto').addEventListener('click', toggleAutoSpin);
    $('#slots-audio').addEventListener('click', toggleSound);
    $('#slots-paytable-btn').addEventListener('click', openModal);
    $('#slots-modal-close').addEventListener('click', closeModal);
    $('#slots-modal').addEventListener('click', (e) => {
      if (e.target === $('#slots-modal')) closeModal();
    });
  });
})();
</script>
</body>
</html>
