// --- SOUND (WEB AUDIO API) ---
let soundOn = localStorage.getItem('coin_arcade_sound') !== 'false';
let audioCtx = null;

function beep(freq = 500, dur = 0.07, type = 'sine', vol = 0.05) {
  if (!soundOn) return;
  try {
    if (!audioCtx) {
      const Ctx = window.AudioContext || window.webkitAudioContext;
      audioCtx = new Ctx();
    }
    if (audioCtx.state === 'suspended') audioCtx.resume();
    const o = audioCtx.createOscillator();
    const g = audioCtx.createGain();
    o.type = type;
    o.frequency.setValueAtTime(freq, audioCtx.currentTime);
    g.gain.setValueAtTime(vol, audioCtx.currentTime);
    g.gain.exponentialRampToValueAtTime(0.001, audioCtx.currentTime + dur);
    o.connect(g);
    g.connect(audioCtx.destination);
    o.start();
    o.stop(audioCtx.currentTime + dur);
  } catch (_) {}
}

const soundBtn = document.getElementById('soundBtn');
function syncSoundBtn() {
  soundBtn.textContent = soundOn ? 'Sound: ON' : 'Sound: OFF';
}
syncSoundBtn();
soundBtn.addEventListener('click', () => {
  soundOn = !soundOn;
  localStorage.setItem('coin_arcade_sound', String(soundOn));
  syncSoundBtn();
});

// --- COINS WALLET (LOCALSTORAGE ONLY) ---
let coins = parseInt(localStorage.getItem('coin_arcade_coins') || '0', 10);
let bonusClaimed = localStorage.getItem('coin_arcade_bonus') === 'true';

const coinBalanceEl = document.getElementById('coinBalance');
const claimBonusBtn = document.getElementById('claimBonusBtn');
const refillCoinsBtn = document.getElementById('refillCoinsBtn');

function renderCoins() {
  coinBalanceEl.textContent = coins.toLocaleString();
  localStorage.setItem('coin_arcade_coins', String(coins));
  if (bonusClaimed) {
    claimBonusBtn.disabled = true;
    claimBonusBtn.textContent = 'Bonus Claimed';
  }
}

claimBonusBtn.addEventListener('click', () => {
  if (bonusClaimed) return;
  coins += 1000; // 500 starter + 500 free coins
  bonusClaimed = true;
  localStorage.setItem('coin_arcade_bonus', 'true');
  beep(680, 0.14, 'triangle', 0.07);
  renderCoins();
});

refillCoinsBtn.addEventListener('click', () => {
  coins += 500;
  beep(580, 0.11, 'triangle', 0.06);
  renderCoins();
});

function spendCoins(amount) {
  if (!Number.isFinite(amount) || amount < 10 || coins < amount) return false;
  coins -= amount;
  renderCoins();
  return true;
}

function addCoins(amount) {
  coins += Math.round(amount);
  renderCoins();
}

renderCoins();

// Coin Presets
document.querySelectorAll('.presets').forEach((group) => {
  const input = document.getElementById(group.dataset.for);
  group.querySelectorAll('.preset').forEach((btn) => {
    btn.addEventListener('click', () => {
      input.value = btn.dataset.val;
      beep(450, 0.03, 'sine', 0.03);
    });
  });
});

// Game Tabs
document.querySelectorAll('.nav-btn').forEach((tab) => {
  tab.addEventListener('click', () => {
    document.querySelectorAll('.nav-btn').forEach((b) => b.classList.remove('active'));
    document.querySelectorAll('.panel').forEach((p) => p.classList.remove('active'));
    tab.classList.add('active');
    document.getElementById('game-' + tab.dataset.game).classList.add('active');
  });
});

// ==========================================
// 1. CRASH
// ==========================================
const cCanvas = document.getElementById('crashCanvas');
const cCtx = cCanvas.getContext('2d');
const crashStage = document.getElementById('crashStage');
const crashMultEl = document.getElementById('crashMult');
const crashSubEl = document.getElementById('crashSub');
const crashStartBtn = document.getElementById('crashStartBtn');
const crashCashBtn = document.getElementById('crashCashBtn');
const crashMsg = document.getElementById('crashMsg');
const crashHistoryEl = document.getElementById('crashHistory');

let cRunning = false;
let cMult = 1.0;
let cEndMult = 1.0;
let cPlayCoins = 0;
let cRaf = null;
let cLastTick = 1.0;
const cHist = [];

function renderCrashHist() {
  crashHistoryEl.innerHTML = cHist
    .slice(-7)
    .reverse()
    .map((item) => `<span class="chip num ${item.win ? 'win' : 'loss'}">${item.m.toFixed(2)}x</span>`)
    .join('');
}

function drawCrash(m, ended) {
  const w = cCanvas.width;
  const h = cCanvas.height;
  cCtx.clearRect(0, 0, w, h);

  cCtx.strokeStyle = '#161d29';
  cCtx.lineWidth = 1;
  for (let x = 50; x < w; x += 70) {
    cCtx.beginPath(); cCtx.moveTo(x, 0); cCtx.lineTo(x, h); cCtx.stroke();
  }
  for (let y = 40; y < h; y += 50) {
    cCtx.beginPath(); cCtx.moveTo(0, y); cCtx.lineTo(w, y); cCtx.stroke();
  }

  const p = Math.min((m - 1) / 4.5, 1);
  const sx = 46;
  const sy = h - 36;
  const px = sx + p * (w - 96);
  const py = sy - Math.pow(p, 1.3) * (h - 80);

  cCtx.beginPath();
  cCtx.moveTo(sx, sy);
  cCtx.quadraticCurveTo(sx + (px - sx) * 0.5, sy, px, py);
  cCtx.strokeStyle = ended ? '#ef4444' : '#10b981';
  cCtx.lineWidth = 3.5;
  cCtx.stroke();

  cCtx.save();
  cCtx.translate(px, py);
  cCtx.rotate(-0.32 - p * 0.2);
  cCtx.font = '20px sans-serif';
  cCtx.textAlign = 'center';
  cCtx.textBaseline = 'middle';
  cCtx.fillText(ended ? '💥' : '✈️', 0, 0);
  cCtx.restore();
}

drawCrash(1.0, false);

function cashOutCrash() {
  if (!cRunning) return;
  cRunning = false;
  cancelAnimationFrame(cRaf);
  const won = Math.round(cPlayCoins * cMult);
  addCoins(won);
  crashStartBtn.disabled = false;
  crashCashBtn.disabled = true;
  crashMultEl.style.color = '#10b981';
  crashSubEl.textContent = `COLLECTED +${won} COINS`;
  crashMsg.textContent = `Cashed out at ${cMult.toFixed(2)}x for +${won} coins.`;
  cHist.push({ m: cMult, win: true });
  renderCrashHist();
  beep(750, 0.14, 'triangle', 0.07);
}

crashStartBtn.addEventListener('click', () => {
  if (cRunning) return;
  const playAmt = parseInt(document.getElementById('crashCoins').value, 10);
  const autoVal = parseFloat(document.getElementById('crashAuto').value);
  if (!spendCoins(playAmt)) {
    crashMsg.textContent = 'Not enough coins. Click Claim 500 + 500 Coins or +500 Free Coins.';
    return;
  }

  cPlayCoins = playAmt;
  cMult = 1.0;
  cLastTick = 1.0;
  cEndMult = +(1.1 + Math.pow(Math.random(), 1.8) * 5.5).toFixed(2);
  cRunning = true;
  crashStartBtn.disabled = true;
  crashCashBtn.disabled = false;
  crashMultEl.style.color = '#ffffff';
  crashSubEl.textContent = 'IN FLIGHT';
  crashMsg.textContent = 'Multiplier climbing — press Cash Out before it ends.';
  beep(440, 0.08, 'triangle', 0.05);

  let prev = performance.now();
  function loop(now) {
    if (!cRunning) return;
    const dt = (now - prev) / 1000;
    prev = now;
    cMult += dt * (0.36 + cMult * 0.16);

    if (cMult - cLastTick >= 0.3) {
      cLastTick = cMult;
      beep(500 + Math.min(cMult * 80, 500), 0.03, 'sine', 0.025);
    }

    if (Number.isFinite(autoVal) && autoVal >= 1.1 && cMult >= autoVal && cMult < cEndMult) {
      cMult = autoVal;
      crashMultEl.textContent = cMult.toFixed(2) + 'x';
      drawCrash(cMult, false);
      cashOutCrash();
      return;
    }

    if (cMult >= cEndMult) {
      cRunning = false;
      crashStartBtn.disabled = false;
      crashCashBtn.disabled = true;
      crashMultEl.textContent = cEndMult.toFixed(2) + 'x';
      crashMultEl.style.color = '#ef4444';
      crashSubEl.textContent = 'ENDED';
      crashMsg.textContent = `Flight ended at ${cEndMult.toFixed(2)}x.`;
      cHist.push({ m: cEndMult, win: false });
      renderCrashHist();
      drawCrash(cEndMult, true);
      crashStage.classList.remove('shake');
      void crashStage.offsetWidth;
      crashStage.classList.add('shake');
      beep(180, 0.22, 'sawtooth', 0.07);
      return;
    }

    crashMultEl.textContent = cMult.toFixed(2) + 'x';
    drawCrash(cMult, false);
    cRaf = requestAnimationFrame(loop);
  }
  cRaf = requestAnimationFrame(loop);
});

crashCashBtn.addEventListener('click', cashOutCrash);

// ==========================================
// 2. DRAGON VS TIGER
// ==========================================
const ranks = ['A', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K'];
const suits = ['♠', '♥', '♦', '♣'];
const dtHist = [];

function renderDtHist() {
  document.getElementById('dtHistory').innerHTML = dtHist
    .slice(-7)
    .reverse()
    .map((r) => `<span class="chip ${r.win ? 'win' : 'loss'}">${r.label}</span>`)
    .join('');
}

function paintCard(el, rIdx, sIdx, isWin) {
  const suit = suits[sIdx];
  const isRed = suit === '♥' || suit === '♦';
  el.className = 'card-slot num' + (isWin ? ' win' : '') + (isRed ? ' red' : '');
  el.textContent = ranks[rIdx] + suit;
}

function playDT(choice) {
  const playAmt = parseInt(document.getElementById('dtCoins').value, 10);
  const msg = document.getElementById('dtMsg');
  if (!spendCoins(playAmt)) {
    msg.textContent = 'Not enough coins. Click Claim 500 + 500 Coins or +500 Free Coins.';
    return;
  }

  const dVal = Math.floor(Math.random() * 13);
  const tVal = Math.floor(Math.random() * 13);
  const dSuit = Math.floor(Math.random() * 4);
  const tSuit = Math.floor(Math.random() * 4);

  const winner = dVal > tVal ? 'dragon' : tVal > dVal ? 'tiger' : 'tie';
  paintCard(document.getElementById('dragonCard'), dVal, dSuit, winner === 'dragon');
  paintCard(document.getElementById('tigerCard'), tVal, tSuit, winner === 'tiger');

  if (choice === winner) {
    const won = playAmt * (winner === 'tie' ? 8 : 2);
    addCoins(won);
    msg.textContent = `${winner.toUpperCase()} wins! +${won} coins.`;
    dtHist.push({ label: `${winner[0].toUpperCase()} +${won}`, win: true });
    beep(720, 0.13, 'triangle', 0.07);
  } else {
    msg.textContent = `${winner.toUpperCase()} took the round.`;
    dtHist.push({ label: winner[0].toUpperCase(), win: false });
    beep(230, 0.11, 'sine', 0.05);
  }
  renderDtHist();
}

// ==========================================
// 3. PLINKO
// ==========================================
const pCanvas = document.getElementById('plinkoCanvas');
const pCtx = pCanvas.getContext('2d');
const pMults = [3.0, 1.5, 0.8, 0.5, 0.8, 1.5, 3.0];
const pRows = 6;

function drawPlinko(ball = null) {
  pCtx.clearRect(0, 0, pCanvas.width, pCanvas.height);
  const topY = 42, rGap = 38, cGap = 54;
  pCtx.fillStyle = '#64748b';
  for (let r = 0; r < pRows; r++) {
    const n = r + 3;
    const sx = (pCanvas.width - (n - 1) * cGap) / 2;
    for (let c = 0; c < n; c++) {
      pCtx.beginPath();
      pCtx.arc(sx + c * cGap, topY + r * rGap, 3.8, 0, Math.PI * 2);
      pCtx.fill();
    }
  }

  const by = topY + pRows * rGap + 14;
  const bw = 50, gap = 6;
  const startX = (pCanvas.width - (pMults.length * (bw + gap) - gap)) / 2;
  pMults.forEach((m, i) => {
    const x = startX + i * (bw + gap);
    pCtx.fillStyle = '#171d29';
    pCtx.strokeStyle = m >= 1.5 ? '#10b981' : '#232b3b';
    pCtx.lineWidth = 1.5;
    pCtx.fillRect(x, by, bw, 26);
    pCtx.strokeRect(x, by, bw, 26);
    pCtx.fillStyle = m >= 1.5 ? '#10b981' : '#eef2f7';
    pCtx.font = 'bold 11px monospace';
    pCtx.textAlign = 'center';
    pCtx.fillText(m + 'x', x + bw / 2, by + 17);
  });

  if (ball) {
    pCtx.beginPath();
    pCtx.arc(ball.x, ball.y, 6.5, 0, Math.PI * 2);
    pCtx.fillStyle = '#f59e0b';
    pCtx.fill();
  }
}

drawPlinko();

document.getElementById('plinkoDropBtn').addEventListener('click', () => {
  const playAmt = parseInt(document.getElementById('plinkoCoins').value, 10);
  const msg = document.getElementById('plinkoMsg');
  const btn = document.getElementById('plinkoDropBtn');
  if (!spendCoins(playAmt)) {
    msg.textContent = 'Not enough coins. Click Claim 500 + 500 Coins or +500 Free Coins.';
    return;
  }

  btn.disabled = true;
  let step = 0, slot = 3, x = pCanvas.width / 2, y = 22;
  const iv = setInterval(() => {
    if (step < pRows) {
      const dir = Math.random() < 0.5 ? -0.5 : 0.5;
      slot += dir; x += dir * 54; y += 38; step++;
      beep(560 + step * 40, 0.035, 'sine', 0.035);
      drawPlinko({ x, y });
    } else {
      clearInterval(iv);
      btn.disabled = false;
      const idx = Math.max(0, Math.min(pMults.length - 1, Math.round(slot)));
      const m = pMults[idx];
      const won = Math.round(playAmt * m);
      addCoins(won);
      msg.textContent = `Landed on ${m}x — +${won} coins.`;
      beep(m >= 1 ? 730 : 270, 0.13, 'triangle', 0.06);
    }
  }, 140);
});

// ==========================================
// 4. STEP CLIMB
// ==========================================
const climbMults = [1.25, 1.6, 2.1, 2.8, 3.8, 5.2];
const climbGrid = document.getElementById('climbGrid');
const climbStartBtn = document.getElementById('climbStartBtn');
const climbStepBtn = document.getElementById('climbStepBtn');
const climbCashBtn = document.getElementById('climbCashBtn');
const climbMsg = document.getElementById('climbMsg');

let climbActive = false, climbIdx = 0, climbPlayCoins = 0;

function drawClimb(blockIdx = -1) {
  climbGrid.innerHTML = climbMults
    .map((m, i) => {
      let cls = 'climb-step num', label = `${m}x`;
      if (i === blockIdx) { cls += ' blocked'; label = 'BLOCK'; }
      else if (i < climbIdx) { cls += ' cleared'; label = `${m}x ✓`; }
      return `<div class="${cls}">${label}</div>`;
    })
    .join('');
}
drawClimb();

climbStartBtn.addEventListener('click', () => {
  const playAmt = parseInt(document.getElementById('climbCoins').value, 10);
  if (!spendCoins(playAmt)) {
    climbMsg.textContent = 'Not enough coins. Click Claim 500 + 500 Coins or +500 Free Coins.';
    return;
  }
  climbPlayCoins = playAmt;
  climbIdx = 0;
  climbActive = true;
  climbStartBtn.disabled = true;
  climbStepBtn.disabled = false;
  climbCashBtn.disabled = true;
  drawClimb();
  climbMsg.textContent = 'Climb started. Press Climb Step to advance.';
  beep(460, 0.08, 'triangle', 0.05);
});

climbStepBtn.addEventListener('click', () => {
  if (!climbActive) return;
  if (Math.random() < 0.25) {
    climbActive = false;
    climbStartBtn.disabled = false;
    climbStepBtn.disabled = true;
    climbCashBtn.disabled = true;
    drawClimb(climbIdx);
    climbMsg.textContent = 'Hit a block! Start a new climb.';
    beep(190, 0.18, 'sawtooth', 0.06);
    return;
  }

  climbIdx++;
  drawClimb();
  climbCashBtn.disabled = false;
  beep(520 + climbIdx * 45, 0.07, 'sine', 0.05);

  if (climbIdx === climbMults.length) {
    const won = Math.round(climbPlayCoins * climbMults[climbIdx - 1]);
    addCoins(won);
    climbActive = false;
    climbStartBtn.disabled = false;
    climbStepBtn.disabled = true;
    climbCashBtn.disabled = true;
    climbMsg.textContent = `Top reached! Collected +${won} coins.`;
    beep(770, 0.15, 'triangle', 0.07);
  } else {
    const cur = climbMults[climbIdx - 1];
    climbMsg.textContent = `Step ${climbIdx} clear (${cur}x). Climb again or collect ${Math.round(climbPlayCoins * cur)} coins.`;
  }
});

climbCashBtn.addEventListener('click', () => {
  if (!climbActive || climbIdx === 0) return;
  const won = Math.round(climbPlayCoins * climbMults[climbIdx - 1]);
  addCoins(won);
  climbActive = false;
  climbStartBtn.disabled = false;
  climbStepBtn.disabled = true;
  climbCashBtn.disabled = true;
  climbMsg.textContent = `Collected +${won} coins.`;
  beep(740, 0.14, 'triangle', 0.07);
});

// ==========================================
// 5. SPIN WHEEL
// ==========================================
const wCanvas = document.getElementById('wheelCanvas');
const wCtx = wCanvas.getContext('2d');
const wSegs = [0, 1.5, 0.5, 3.0, 0, 2.0, 1.0, 5.0];
const wCols = ['#171d29', '#065f46', '#1e293b', '#047857', '#171d29', '#1e3a8a', '#1e293b', '#b45309'];
let wAngle = 0;

function drawWheel(a) {
  const cx = 150, cy = 150, r = 138, arc = (Math.PI * 2) / wSegs.length;
  wCtx.clearRect(0, 0, 300, 300);
  wSegs.forEach((m, i) => {
    const s = a + i * arc;
    wCtx.beginPath(); wCtx.moveTo(cx, cy); wCtx.arc(cx, cy, r, s, s + arc);
    wCtx.fillStyle = wCols[i]; wCtx.fill();
    wCtx.strokeStyle = '#080a0f'; wCtx.lineWidth = 2; wCtx.stroke();
    wCtx.save();
    wCtx.translate(cx, cy); wCtx.rotate(s + arc / 2);
    wCtx.fillStyle = '#eef2f7'; wCtx.font = 'bold 13px monospace';
    wCtx.fillText(m + 'x', r * 0.62, 4);
    wCtx.restore();
  });
}
drawWheel(wAngle);

document.getElementById('wheelSpinBtn').addEventListener('click', () => {
  const playAmt = parseInt(document.getElementById('wheelCoins').value, 10);
  const msg = document.getElementById('wheelMsg');
  const btn = document.getElementById('wheelSpinBtn');
  if (!spendCoins(playAmt)) {
    msg.textContent = 'Not enough coins. Click Claim 500 + 500 Coins or +500 Free Coins.';
    return;
  }

  btn.disabled = true;
  const delta = Math.PI * 8 + Math.random() * Math.PI * 2;
  const startA = wAngle, t0 = performance.now(), dur = 2000;

  function anim(now) {
    const t = Math.min((now - t0) / dur, 1);
    wAngle = startA + delta * (1 - Math.pow(1 - t, 3));
    drawWheel(wAngle);
    if (t < 1) {
      requestAnimationFrame(anim);
    } else {
      btn.disabled = false;
      const arc = (Math.PI * 2) / wSegs.length;
      const norm = (((-Math.PI / 2 - wAngle) % (Math.PI * 2)) + Math.PI * 2) % (Math.PI * 2);
      const m = wSegs[Math.floor(norm / arc)];
      const won = Math.round(playAmt * m);
      addCoins(won);
      msg.textContent = `Wheel landed on ${m}x — +${won} coins.`;
      beep(m >= 1 ? 750 : 250, 0.14, 'triangle', 0.07);
    }
  }
  requestAnimationFrame(anim);
});