<?php
session_start();
if (!isset($_SESSION['user_id']) || empty($_SESSION['user_id'])) {
    header('Location: /login.php');
    exit;
}
require_once __DIR__ . '/../config.php';
$uid_chk = (int)$_SESSION['user_id'];
$is_demo = (int)$pdo->query("SELECT is_demo FROM users WHERE id = $uid_chk")->fetchColumn();
if ($is_demo) {
    $_SESSION['is_demo'] = 1;
    header('Location: ../index.php?err=demo_restriction');
    exit;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no, viewport-fit=cover">
    <title>Fortune Mines - PakClub</title>
    
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@600;700;800;900&display=swap" rel="stylesheet">
    
    <style>
        /* Hide the external header UI as requested */
        .main-header { display: none !important; }

        :root { 
            --bg-top: #2e084d;
            --bg-bottom: #0f011c;
            --panel-bg: rgba(30, 8, 50, 0.85);
            --gold-light: #ffe55c;
            --gold-main: #ffb703;
            --gold-dark: #b37700;
            
            --btn-green-top: #4ade80;
            --btn-green-bottom: #16a34a;
            --btn-green-shadow: #14532d;

            --cell-bg-top: #581c87;
            --cell-bg-bottom: #3b0764;
            --cell-shadow: #24043e;

            --text-glow: 0 0 10px rgba(255, 229, 92, 0.5);
            --radius-lg: 20px;
            --radius-md: 14px;
        }

        * {
            box-sizing: border-box;
            font-family: 'Poppins', sans-serif;
            -webkit-tap-highlight-color: transparent;
            touch-action: manipulation; /* Kills mobile tap delay */
        }

        body {
            margin: 0; padding: 0;
            background-color: var(--bg-bottom);
            color: #fff;
            overflow-x: hidden;
        }

        .mobile-wrapper {
            width: 100%; max-width: 420px;
            background: radial-gradient(circle at 50% 0%, var(--bg-top), var(--bg-bottom));
            min-height: 100vh; position: relative;
            display: flex; flex-direction: column;
            margin: 0 auto;
            box-shadow: 0 0 30px rgba(0,0,0,0.8);
            transition: transform 0.1s;
        }
        
        /* Screen shake class */
        .shake-screen { animation: screenShake 0.4s cubic-bezier(.36,.07,.19,.97) both; }

        /* Top Bar */
        .top-bar {
            display: flex; align-items: center; justify-content: space-between;
            padding: 16px 20px;
            background: linear-gradient(180deg, rgba(0,0,0,0.6) 0%, rgba(0,0,0,0) 100%);
            position: sticky; top: 0; z-index: 100;
        }
        .top-bar .back-btn {
            color: #fff; text-decoration: none; font-size: 1.4rem;
            background: rgba(255,255,255,0.1); width: 40px; height: 40px;
            display: flex; align-items: center; justify-content: center;
            border-radius: 50%; backdrop-filter: blur(5px);
            border: 1px solid rgba(255,255,255,0.2);
        }
        .top-bar .balance-wrapper {
            background: rgba(0, 0, 0, 0.5); border: 2px solid var(--gold-main);
            border-radius: 999px; padding: 6px 16px;
            display: flex; align-items: center; gap: 8px;
            box-shadow: 0 0 15px rgba(255, 183, 3, 0.3), inset 0 0 10px rgba(0,0,0,0.8);
        }
        .top-bar .balance {
            font-size: 1.1rem; font-weight: 800; color: var(--gold-light);
            text-shadow: 0 2px 4px rgba(0,0,0,0.8);
        }
        .top-bar .balance i { color: var(--gold-main); }

        .mines-wrap { padding: 10px 16px 20px; flex: 1; display: flex; flex-direction: column; }

        .game-logo { text-align: center; margin-bottom: 16px; }
        .game-logo h1 {
            margin: 0; font-size: 28px; font-weight: 900;
            background: linear-gradient(to bottom, #fffde7, var(--gold-main));
            -webkit-background-clip: text; -webkit-text-fill-color: transparent;
            text-transform: uppercase; letter-spacing: 2px;
            filter: drop-shadow(0 4px 6px rgba(0,0,0,0.6));
        }
        .game-logo p { margin: 0; font-size: 12px; color: #d8b4fe; font-weight: 600; text-transform: uppercase; letter-spacing: 1px; }

        /* Glassmorphism Shell */
        .mines-shell {
            background: var(--panel-bg); border-radius: var(--radius-lg);
            border: 1px solid rgba(255,255,255,0.1); border-top: 1px solid rgba(255, 183, 3, 0.5);
            box-shadow: 0 10px 30px rgba(0,0,0,0.5), inset 0 0 20px rgba(255,255,255,0.02);
            backdrop-filter: blur(10px); display: flex; flex-direction: column; overflow: hidden; position: relative;
        }

        .mines-status-row {
            display: flex; align-items: center; justify-content: space-between;
            padding: 16px 20px 10px; font-size: 13px; font-weight: 700;
        }
        .mines-status-dot {
            display: inline-flex; align-items: center; gap: 8px;
            background: rgba(0,0,0,0.4); padding: 4px 12px; border-radius: 999px; border: 1px solid rgba(255,255,255,0.05);
        }
        .mines-live { width: 10px; height: 10px; border-radius: 50%; background: #22c55e; box-shadow: 0 0 10px #22c55e; animation: pulse 1.5s infinite; }
        .mines-mult { color: var(--gold-light); font-size: 16px; text-shadow: var(--text-glow); }

        /* The Grid - True 3D Flip System */
        .mines-grid-wrap { padding: 0 20px 20px; perspective: 1000px; }
        .mines-grid {
            display: grid; grid-template-columns: repeat(5, 1fr); gap: 8px;
            background: rgba(0,0,0,0.6); padding: 10px; border-radius: var(--radius-md);
            border: 2px solid rgba(255, 183, 3, 0.2); box-shadow: inset 0 0 20px rgba(0,0,0,0.8);
        }
        
        .mines-cell {
            position: relative; padding-top: 100%; border: none; outline: none; background: transparent; cursor: pointer;
            transform-style: preserve-3d; 
            transition: transform 0.25s cubic-bezier(0.175, 0.885, 0.32, 1.275); /* SPED UP FLIP */
        }
        .mines-cell-face {
            position: absolute; inset: 0; border-radius: 10px;
            backface-visibility: hidden; -webkit-backface-visibility: hidden;
            display: flex; align-items: center; justify-content: center; font-size: 24px;
        }
        
        .mines-cell-front {
            background: linear-gradient(180deg, var(--cell-bg-top) 0%, var(--cell-bg-bottom) 100%);
            box-shadow: inset 0 2px 0 rgba(255,255,255,0.2), 0 4px 0 var(--cell-shadow), 0 5px 10px rgba(0,0,0,0.4);
        }
        .mines-cell:active:not(.open):not(.over) { transform: scale(0.92); }

        .mines-cell-back { transform: rotateY(180deg); }

        /* Flip States */
        .mines-cell.open { transform: rotateY(180deg); cursor: default; }
        
        .mines-cell.open.safe .mines-cell-back {
            background: linear-gradient(180deg, #059669 0%, #064e3b 100%);
            border: 1px solid #34d399; box-shadow: inset 0 2px 10px rgba(0,0,0,0.5), 0 0 15px rgba(52, 211, 153, 0.4);
        }
        .mines-cell.open.mine .mines-cell-back {
            background: linear-gradient(180deg, #dc2626 0%, #7f1d1d 100%);
            border: 1px solid #f87171; box-shadow: inset 0 2px 10px rgba(0,0,0,0.5), 0 0 20px rgba(220, 38, 38, 0.6);
        }
        .mines-cell.over { opacity: 0.85; }

        .mines-mine-icon { font-size: 26px; filter: drop-shadow(0 0 10px rgba(255,0,0,0.8)); }
        .mines-safe-icon { font-size: 26px; filter: drop-shadow(0 0 10px rgba(52, 211, 153, 0.8)); animation: float 2s infinite ease-in-out; }

        /* Floating Text Feedback */
        .float-text {
            position: absolute; z-index: 10; font-size: 16px; font-weight: 900;
            color: #4ade80; text-shadow: 0 2px 5px rgba(0,0,0,0.9); pointer-events: none;
            animation: floatUp 0.8s cubic-bezier(0.175, 0.885, 0.32, 1.275) forwards;
        }

        /* Messaging */
        .mines-msg {
            text-align: center; font-size: 13px; font-weight: 700; padding: 10px 20px; min-height: 40px; color: #d8b4fe;
            background: rgba(0,0,0,0.3); border-top: 1px solid rgba(255,255,255,0.05); border-bottom: 1px solid rgba(255,255,255,0.05);
        }
        .mines-msg.win { color: #4ade80; text-shadow: 0 0 8px rgba(74, 222, 128, 0.5); font-size: 15px; }
        .mines-msg.lose { color: #f87171; text-shadow: 0 0 8px rgba(248, 113, 113, 0.5); font-size: 15px;}

        /* Dock */
        .mines-dock {
            padding: 20px; background: linear-gradient(0deg, rgba(0,0,0,0.8) 0%, rgba(0,0,0,0) 100%);
            display: flex; flex-direction: column; gap: 12px;
        }
        .mines-dock-row { display: flex; align-items: center; gap: 12px; }
        .mines-dock-input {
            flex: 1; position: relative; background: rgba(0,0,0,0.5); border-radius: 12px;
            border: 2px solid rgba(255, 255, 255, 0.1); box-shadow: inset 0 4px 10px rgba(0,0,0,0.6); display: flex; align-items: center;
        }
        .mines-dock-input input {
            width: 100%; border: none; background: transparent; padding: 14px 16px;
            font-size: 16px; font-weight: 800; color: var(--gold-light); outline: none; text-shadow: 0 2px 4px rgba(0,0,0,0.8);
        }
        .mines-dock-input span { position: absolute; right: 16px; font-size: 14px; font-weight: 800; color: #a855f7; }

        .mines-dock-btn {
            min-width: 120px; border: none; border-radius: 12px; padding: 14px 0;
            font-size: 16px; font-weight: 900; text-transform: uppercase; letter-spacing: 1px; color: #fff;
            cursor: pointer; position: relative; outline: none; transition: all 0.1s;
        }
        
        .mines-dock-btn.start { background: linear-gradient(180deg, #3b82f6 0%, #1d4ed8 100%); box-shadow: inset 0 2px 0 rgba(255,255,255,0.4), 0 6px 0 #1e3a8a, 0 10px 15px rgba(0,0,0,0.5); text-shadow: 0 2px 2px rgba(0,0,0,0.3); }
        .mines-dock-btn.start:active:not(:disabled) { transform: translateY(6px); box-shadow: inset 0 2px 0 rgba(255,255,255,0.4), 0 0px 0 #1e3a8a, 0 2px 5px rgba(0,0,0,0.5); }
        
        /* Cleaned up cashout button - pure black text, zero text shadow */
        .mines-dock-btn.cashout {
            flex: 1; 
            background: linear-gradient(180deg, var(--gold-light) 0%, var(--gold-main) 100%);
            box-shadow: inset 0 2px 0 rgba(255,255,255,0.6), 0 6px 0 var(--gold-dark), 0 5px 10px rgba(0,0,0,0.5);
            color: #000000; 
            text-shadow: none; 
        }
        .mines-dock-btn.cashout:active:not(:disabled) {
            transform: translateY(6px);
            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);
        }

        .mines-dock-btn:disabled { opacity: 0.5; cursor: not-allowed; filter: grayscale(0.5); transform: translateY(6px); box-shadow: none;}

        .mines-dock-row2 { display: flex; width: 100%; }
        .mines-dock-hint { text-align: center; font-size: 11px; font-weight: 600; color: rgba(255,255,255,0.4); margin-top: 5px; }

        /* Animations */
        @keyframes pulse { 0% { opacity: 1; transform: scale(1); } 50% { opacity: 0.5; transform: scale(1.1); } 100% { opacity: 1; transform: scale(1); } }
        @keyframes float { 0%, 100% { transform: translateY(0); } 50% { transform: translateY(-4px); } }
        @keyframes screenShake { 10%, 90% { transform: translate3d(-2px, 0, 0); } 20%, 80% { transform: translate3d(4px, 0, 0); } 30%, 50%, 70% { transform: translate3d(-6px, 0, 0); } 40%, 60% { transform: translate3d(6px, 0, 0); } }
        @keyframes floatUp { 0% { transform: translateY(0) scale(0.5); opacity: 0; } 20% { transform: translateY(-20px) scale(1.3); opacity: 1; } 100% { transform: translateY(-40px) scale(1); opacity: 0; } }

    </style>
</head>
<body>

<?php
// Include the external header logic
require_once __DIR__ . '/../external/header.php';

// Prepare data for JS
$minBet = 10;
$currency = 'Rs';
$jsData = [
    'csrf'        => '',
    'balUsd'      => (float)$balance, 
    'currency'    => $currency,
    'fxRate'      => 1,
    'minBetUsd'   => $minBet,
    'minBetLocal' => $minBet,
];
?>

<div class="mobile-wrapper" id="game-wrapper">
    <div class="top-bar">
        <a href="javascript:history.back()" class="back-btn"><i class="fa-solid fa-chevron-left"></i></a>
        <div class="balance-wrapper" id="hdr-bal-wrap">
            <i class="fa-solid fa-coins"></i> 
            <span class="balance" id="hdr-bal"><?= number_format($balance, 2) ?></span>
        </div>
    </div>

    <section class="mines-wrap">
        <div class="game-logo">
            <h1>Fortune Mines</h1>
            <p>Reveal Gems • Avoid Bombs</p>
        </div>

        <div class="mines-shell">
            <div class="mines-status-row" id="mines-status">
                <span class="mines-status-dot"><span class="mines-live"></span> <span>READY TO PLAY</span></span>
                <span class="mines-mult"><strong id="mines-mult">1.00x</strong></span>
            </div>
            
            <div class="mines-grid-wrap">
                <div class="mines-grid" id="mines-grid"></div>
            </div>
            
            <div class="mines-msg" id="mines-msg">Place your bet to start the game.</div>

            <div class="mines-dock">
                <div class="mines-dock-row" id="mines-dock-bet">
                    <div class="mines-dock-input">
                        <input type="number" id="mines-amt" min="<?= $minBet ?>" step="any" placeholder="<?= $minBet ?>" value="<?= $minBet ?>" inputmode="decimal">
                        <span><?= $currency ?></span>
                    </div>
                    <button type="button" class="mines-dock-btn start" id="mines-start">PLAY</button>
                </div>
                <div class="mines-dock-row2" id="mines-dock-cashout" style="display:none">
                    <button type="button" class="mines-dock-btn cashout" id="mines-cashout">CASH OUT</button>
                </div>
                <div class="mines-dock-hint">Min <?= $currency ?> <?= $minBet ?> • 3 Mines • 5×5 Grid</div>
            </div>
        </div>
    </section>
</div>

<script>
const MINES = <?= json_encode($jsData, JSON_UNESCAPED_UNICODE) ?>;

// --- Web Audio API Synth ---
let audioCtx;
function initAudio() {
    if (!audioCtx) audioCtx = new (window.AudioContext || window.webkitAudioContext)();
    if (audioCtx.state === 'suspended') audioCtx.resume();
}
function playTone(freq, type, duration, vol=0.1) {
    if (!audioCtx) return;
    const osc = audioCtx.createOscillator();
    const gain = audioCtx.createGain();
    osc.type = type;
    osc.frequency.setValueAtTime(freq, audioCtx.currentTime);
    gain.gain.setValueAtTime(vol, audioCtx.currentTime);
    gain.gain.exponentialRampToValueAtTime(0.01, audioCtx.currentTime + duration);
    osc.connect(gain);
    gain.connect(audioCtx.destination);
    osc.start(); osc.stop(audioCtx.currentTime + duration);
}
const sfx = {
    click: () => { playTone(440, 'sine', 0.1, 0.05); },
    start: () => { playTone(440, 'triangle', 0.1); setTimeout(()=>playTone(660, 'sine', 0.3), 100); },
    gem: () => { playTone(880, 'triangle', 0.1, 0.1); setTimeout(()=>playTone(1760, 'sine', 0.4, 0.05), 80); },
    bomb: () => { playTone(100, 'square', 0.4, 0.2); playTone(50, 'sawtooth', 0.6, 0.3); },
    cashout: () => { [523.25, 659.25, 783.99, 1046.50].forEach((f, i) => setTimeout(() => playTone(f, 'sine', 0.3, 0.1), i*80)); }
};
function vibrate(ms) { if (navigator.vibrate) navigator.vibrate(ms); }

(function(){
const $=s=>document.querySelector(s);
let gameId=null;
let placing=false;
let playing=false;
let opened=new Set();
let safeClicks=0;
let mult=1.0;

function fmt(u){return Number(u).toFixed(2);}

function updBal(){
  const h=$('#hdr-bal');
  if(h)h.textContent=fmt(MINES.balUsd);
}

async function api(a,p){
  const body=JSON.stringify(Object.assign({},p||{}, {csrf:MINES.csrf}));
  const r=await fetch('api.php?action='+a,{method:'POST',headers:{'Content-Type':'application/json'},body});
  return r.json();
}

function resetBoard(){
  opened=new Set(); safeClicks=0; mult=1.0;
  const msg=$('#mines-msg');if(msg){msg.textContent='Tap cells to reveal gems. Cash out anytime.';msg.className='mines-msg';}
  const mSpan=$('#mines-mult');if(mSpan)mSpan.textContent='1.00x';
  const dockBet=$('#mines-dock-bet');const dockCash=$('#mines-dock-cashout');
  if(dockBet)dockBet.style.display='flex';
  if(dockCash)dockCash.style.display='none';
  document.querySelectorAll('.mines-cell').forEach(c=>{
    c.classList.remove('open','safe','mine','over');
    const ic=c.querySelector('.mines-cell-back');
    if(ic){ic.innerHTML='';}
  });
}

function showCashout(show){
  const dockBet=$('#mines-dock-bet');const dockCash=$('#mines-dock-cashout');
  if(dockBet)dockBet.style.display=show?'none':'flex';
  if(dockCash)dockCash.style.display=show?'flex':'none';
}

function spawnFloatText(el, text) {
    const floatEl = document.createElement('div');
    floatEl.className = 'float-text';
    floatEl.textContent = text;
    el.appendChild(floatEl);
    setTimeout(() => floatEl.remove(), 800);
}

async function startGame(){
  initAudio(); sfx.click();
  if(placing||playing)return;
  const inp=$('#mines-amt');
  const v=parseFloat((inp.value||'0').replace(/,/g,'')); 
  if(!v||v<=0){
    const msg=$('#mines-msg');if(msg){msg.textContent='Enter valid amount in '+MINES.currency;msg.className='mines-msg lose';}
    return;
  }
  if(v<MINES.minBetLocal){
    const msg=$('#mines-msg');if(msg){msg.textContent='Min bet '+MINES.currency+' '+MINES.minBetLocal.toFixed(2);msg.className='mines-msg lose';}
    return;
  }
  placing=true;
  $('#mines-start').textContent = '...';
  try{
    const d=await api('start',{amount:v});
    if(!d.ok){
      const msg=$('#mines-msg');if(msg){msg.textContent=d.error||'Server error';msg.className='mines-msg lose';}
      $('#mines-start').textContent = 'PLAY';
      placing=false;return;
    }
    sfx.start(); vibrate(50);
    MINES.balUsd=d.balance??MINES.balUsd;updBal();
    gameId=d.game_id;playing=true;
    resetBoard();
    showCashout(true);
    const cashBtn=$('#mines-cashout');if(cashBtn){cashBtn.disabled=true; cashBtn.innerHTML='CASH OUT';}
    const st=$('#mines-status .mines-status-dot span:last-child');if(st)st.textContent='GAME LIVE';
  }catch(e){
    const msg=$('#mines-msg');if(msg){msg.textContent='Network error. Please try again.';msg.className='mines-msg lose';}
  }
  $('#mines-start').textContent = 'PLAY';
  placing=false;
}

async function clickCell(idx,el){
  initAudio();
  if(!playing||gameId===null)return;
  if(el.classList.contains('over')||el.classList.contains('open'))return;
  sfx.click();
  try{
    const d=await api('click',{game_id:gameId,cell:idx});
    if(!d.ok){
      const msg=$('#mines-msg');if(msg){msg.textContent=d.error||'Server error';msg.className='mines-msg lose';}
      return;
    }
    MINES.balUsd=d.balance??MINES.balUsd;updBal();
    opened.add(idx);
    const inner=el.querySelector('.mines-cell-back');
    
    if(d.is_mine){
      el.classList.add('mine');
      if(inner)inner.innerHTML='<span class="mines-mine-icon">💣</span>';
      el.classList.add('open');
      sfx.bomb(); vibrate([100,50,100,50,200]);
      
      const wrapper = $('#game-wrapper');
      wrapper.classList.add('shake-screen');
      setTimeout(() => wrapper.classList.remove('shake-screen'), 400);

    }else{
      el.classList.add('safe');
      if(inner)inner.innerHTML='<span class="mines-safe-icon">💎</span>';
      el.classList.add('open');
      sfx.gem(); vibrate(30);
      spawnFloatText(inner, "+" + (d.multiplier || mult).toFixed(2) + "x");
    }
    
    safeClicks=d.safe_clicks||0;
    mult=d.multiplier||1.0;
    const mSpan=$('#mines-mult');if(mSpan)mSpan.textContent=(mult||1).toFixed(2)+'x';
    
    const cashBtn=$('#mines-cashout');
    if(cashBtn) {
        cashBtn.disabled=safeClicks<1;
        if(safeClicks >= 1) {
            let potentialWin = (parseFloat($('#mines-amt').value) * mult).toFixed(2);
            cashBtn.innerHTML = `TAKE ${MINES.currency} ${potentialWin}`;
        }
    }

    const msg=$('#mines-msg');
    if(msg){
      msg.className='mines-msg';
      if(d.is_over){
        if(d.is_win){
          msg.innerHTML=`<i class="fa-solid fa-trophy"></i> BIG WIN! ${MINES.currency} ${fmt(d.payout||0)}`;
          msg.classList.add('win');
        }else if(d.is_mine){
          msg.innerHTML=`<i class="fa-solid fa-explosion"></i> BOOM! You hit a mine.`;
          msg.classList.add('lose');
          if(d.mines&&Array.isArray(d.mines)){
            const grid=$('#mines-grid');
            if(grid)d.mines.forEach((m, i)=>{
              const c=grid.querySelector('.mines-cell[data-index="'+m+'"]');
              if(c&&!c.classList.contains('open')){
                // Sped up staggered bomb reveal (50ms instead of 150ms)
                setTimeout(() => {
                    const ic=c.querySelector('.mines-cell-back');
                    if(ic)ic.innerHTML='<span class="mines-mine-icon">💣</span>';
                    c.classList.add('open','mine','over');
                }, i * 50); 
              }
            });
          }
        }else{
          msg.textContent='Game over.';
        }
      }else{
        msg.innerHTML=`<i class="fa-regular fa-gem"></i> Great! Keep going or cash out.`;
      }
    }
    
    if(d.is_over){
      playing=false;
      showCashout(false);
      const st=$('#mines-status .mines-status-dot span:last-child');if(st)st.textContent='READY TO PLAY';
      document.querySelectorAll('.mines-cell:not(.mine)').forEach(c=>c.classList.add('over'));
    }
  }catch(e){
    const msg=$('#mines-msg');if(msg){msg.textContent='Network error. Please try again.';msg.className='mines-msg lose';}
  }
}

document.addEventListener('DOMContentLoaded',()=>{
  const g=$('#mines-grid');
  if(g){
    for(let i=0;i<25;i++){
      const cell=document.createElement('button');
      cell.type='button';
      cell.className='mines-cell';
      cell.dataset.index=String(i);
      cell.innerHTML=`
        <div class="mines-cell-face mines-cell-front"></div>
        <div class="mines-cell-face mines-cell-back"></div>
      `;
      ((idx,el)=>{el.addEventListener('click',()=>clickCell(idx,el));})(i,cell);
      g.appendChild(cell);
    }
  }
  const b=$('#mines-start');if(b)b.addEventListener('click',startGame);
  const cb=$('#mines-cashout');if(cb)cb.addEventListener('click',cashOut);
  
  document.body.addEventListener('click', initAudio, {once:true});
  
  resetBoard();
});

async function cashOut(){
  initAudio();
  if(!playing||gameId===null||safeClicks<1)return;
  sfx.click();
  try{
    const d=await api('cashout',{game_id:gameId});
    if(!d.ok){
      const msg=$('#mines-msg');if(msg){msg.textContent=d.error||'Server error';msg.className='mines-msg lose';}
      return;
    }
    sfx.cashout(); vibrate([50, 100, 150]);
    MINES.balUsd=d.balance??MINES.balUsd;updBal();
    playing=false;
    showCashout(false);
    const st=$('#mines-status .mines-status-dot span:last-child');if(st)st.textContent='READY TO PLAY';
    const mSpan=$('#mines-mult');if(mSpan)mSpan.textContent=(d.multiplier||1).toFixed(2)+'x';
    const msg=$('#mines-msg');if(msg){msg.innerHTML=`<i class="fa-solid fa-trophy"></i> YOU WON ${MINES.currency} ${fmt(d.payout||0)}`;msg.className='mines-msg win';}
    document.querySelectorAll('.mines-cell').forEach(c=>c.classList.add('over'));
  }catch(e){
    const msg=$('#mines-msg');if(msg){msg.textContent='Network error. Please try again.';msg.className='mines-msg lose';}
  }
}
})();
</script>
</body>
</html>
