<?php
// ==============================================================================
//  FORTUNE WHEEL — Redesign Premium
// ==============================================================================
ini_set('display_errors', 0);
ini_set('log_errors', 1);
error_reporting(E_ALL);
session_start();

try {
    if (file_exists('../config/db.php')) {
        require_once '../config/db.php';
    } else {
        $pdo = new PDO("mysql:host=localhost;dbname=kub;charset=utf8mb4", "root", "", [
            PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
            PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
            PDO::ATTR_EMULATE_PREPARES => false,
        ]);
    }
} catch (PDOException $e) {
    if ($_SERVER['REQUEST_METHOD'] === 'POST') { echo json_encode(['status'=>'error','message'=>'Erro de conexão']); exit; }
    die("Erro de sistema.");
}

if (!isset($_SESSION['user'])) {
    if ($_SERVER['REQUEST_METHOD'] === 'POST') { echo json_encode(['status'=>'error','message'=>'Sessão expirada']); exit; }
    header('Location: login.php'); exit;
}

$stmtUser = $pdo->prepare("SELECT * FROM users WHERE phone = :phone LIMIT 1");
$stmtUser->execute([':phone' => $_SESSION['user']]);
$user = $stmtUser->fetch();
if (!$user) { session_destroy(); header('Location: login.php'); exit; }

// ==============================================================================
//  API
// ==============================================================================
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';
    ob_clean();
    header('Content-Type: application/json');
    try {

        if ($action === 'get_status') {
            $stmt = $pdo->prepare("SELECT qtd_spins, balance FROM users WHERE id = ?");
            $stmt->execute([$user['id']]);
            $d = $stmt->fetch();
            echo json_encode([
                'status'     => 'success',
                'qtd_spins'  => (int)($d['qtd_spins'] ?? 0),
                'balance'    => number_format((float)($d['balance'] ?? 0), 2, ',', '.'),
            ]);
            exit;
        }

        if ($action === 'spin') {
            $pdo->beginTransaction();
            $stmt = $pdo->prepare("SELECT qtd_spins, balance FROM users WHERE id = ? FOR UPDATE");
            $stmt->execute([$user['id']]);
            $ud = $stmt->fetch();
            $spins = (int)($ud['qtd_spins'] ?? 0);

            if ($spins <= 0) {
                $pdo->rollBack();
                echo json_encode(['status'=>'error','message'=>'Sem giros disponíveis!']);
                exit;
            }

            // ================================================================
            //  ARRAY ÚNICO — ordem idêntica ao JS.
            //  Cada índice = um segmento visual = prêmio real que será pago.
            //  Nunca há dissociação entre o que a roleta mostra e o que credita.
            // ================================================================
            $prizes = [
                ['label'=>'R$ 0,50','value'=>0.50,'weight'=>25],  // index 0
                ['label'=>'R$ 1,00','value'=>1.00,'weight'=>22],  // index 1
                ['label'=>'R$ 0,50','value'=>0.50,'weight'=>18],  // index 2
                ['label'=>'R$ 2,00','value'=>2.00,'weight'=>15],  // index 3
                ['label'=>'R$ 1,00','value'=>1.00,'weight'=>10],  // index 4
                ['label'=>'R$ 3,00','value'=>3.00,'weight'=>6],   // index 5
                ['label'=>'R$ 4,00','value'=>4.00,'weight'=>3],   // index 6
                ['label'=>'R$ 5,00','value'=>5.00,'weight'=>1],   // index 7
            ];
            // Total pesos = 100

            $total = array_sum(array_column($prizes, 'weight'));
            $rand  = mt_rand(1, $total);
            $cum   = 0;
            $won   = $prizes[0];
            $wonIdx = 0;
            foreach ($prizes as $i => $p) {
                $cum += $p['weight'];
                if ($rand <= $cum) { $won = $p; $wonIdx = $i; break; }
            }

            $newBalance = (float)$ud['balance'] + $won['value'];
            $pdo->prepare("UPDATE users SET qtd_spins=qtd_spins-1, total_spins=total_spins+1, balance=?, awards_spins=awards_spins+? WHERE id=?")
                ->execute([$newBalance, $won['value'], $user['id']]);
            $pdo->prepare("INSERT INTO history (user_id, action, created_at) VALUES (?,?,NOW())")
                ->execute([$user['id'], "Fortune Wheel: ganhou " . $won['label']]);
            $pdo->commit();

            echo json_encode([
                'status'          => 'success',
                'prize'           => ['label' => $won['label'], 'value' => $won['value']],
                'prize_index'     => $wonIdx,
                'new_balance'     => number_format($newBalance, 2, ',', '.'),
                'remaining_spins' => $spins - 1,
            ]);
            exit;
        }

    } catch (Exception $e) {
        if ($pdo->inTransaction()) $pdo->rollBack();
        echo json_encode(['status'=>'error','message'=>$e->getMessage()]);
        exit;
    }
}
?>
<!DOCTYPE html>
<html lang="pt-BR">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1.0,maximum-scale=1.0,user-scalable=no">
<title>Fortune Wheel — <?= htmlspecialchars($user['name'] ?? 'Usuário') ?></title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link href="https://fonts.googleapis.com/css2?family=Cinzel:wght@400;600;700;900&family=Raleway:wght@300;400;500;600&display=swap" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/canvas-confetti@1.9.2/dist/confetti.browser.min.js"></script>
<style>
:root {
  --gold:    #D4AF37;
  --gold-l:  #FFE57C;
  --gold-d:  #9A7B20;
  --gold-dk: #5C3D00;
  --bg:      #06060A;
  --txt:     #EDE8D8;
  --muted:   #706858;
  --glass:   rgba(212,175,55,.05);
  --gborder: rgba(212,175,55,.2);
}
*, *::before, *::after { margin:0; padding:0; box-sizing:border-box }
html { -webkit-tap-highlight-color: transparent }

body {
  min-height: 100vh;
  background: var(--bg);
  background-image:
    radial-gradient(ellipse 90% 55% at 50% -8%, rgba(130,85,0,.28) 0%, transparent 62%),
    radial-gradient(ellipse 55% 45% at 88% 92%, rgba(65,0,95,.2) 0%, transparent 55%),
    radial-gradient(ellipse 45% 35% at 5%  55%, rgba(0,28,68,.15) 0%, transparent 50%);
  font-family: 'Raleway', sans-serif;
  color: var(--txt);
  overflow-x: hidden;
}

/* Grain overlay */
body::after {
  content: '';
  position: fixed; inset: 0;
  background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='200' height='200'%3E%3Cfilter id='n'%3E%3CfeTurbulence type='fractalNoise' baseFrequency='0.8' stitchTiles='stitch'/%3E%3C/filter%3E%3Crect width='200' height='200' filter='url(%23n)' opacity='0.04'/%3E%3C/svg%3E");
  pointer-events: none; z-index: 0; opacity: .55;
}

/* Background blobs */
.blob { position:fixed; border-radius:50%; filter:blur(130px); pointer-events:none; z-index:0 }
.b1 { width:620px;height:620px; background:radial-gradient(circle,rgba(155,95,0,.12) 0%,transparent 70%); top:-220px;left:-160px; animation:bm 30s ease-in-out infinite }
.b2 { width:480px;height:480px; background:radial-gradient(circle,rgba(65,0,100,.12) 0%,transparent 70%); bottom:-130px;right:-110px; animation:bm 24s ease-in-out infinite reverse }
.b3 { width:300px;height:300px; background:radial-gradient(circle,rgba(0,40,80,.1) 0%,transparent 70%); top:40%;left:-80px; animation:bm 18s ease-in-out infinite 5s }
@keyframes bm { 0%,100%{transform:translate(0,0) scale(1)} 33%{transform:translate(22px,-18px) scale(1.04)} 66%{transform:translate(-14px,14px) scale(.96)} }

/* Layout */
.wrap {
  position: relative; z-index: 1;
  max-width: 440px;
  margin: 0 auto;
  padding: 24px 20px 52px;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 26px;
}

/* Header */
.hdr { text-align:center; width:100% }
.back {
  display: inline-flex; align-items:center; gap:6px;
  color:var(--muted); text-decoration:none;
  font-size:11px; letter-spacing:.14em; text-transform:uppercase;
  transition:color .2s; margin-bottom:18px;
}
.back:hover { color:var(--gold) }
.back svg { width:14px;height:14px }

.title {
  font-family: 'Cinzel', serif;
  font-weight: 700;
  font-size: clamp(19px, 5.5vw, 33px);
  letter-spacing: .13em;
  background: linear-gradient(135deg, var(--gold-d) 0%, var(--gold-l) 42%, var(--gold) 65%, var(--gold-d) 100%);
  -webkit-background-clip: text; -webkit-text-fill-color: transparent; background-clip: text;
  line-height: 1.1;
}
.sub {
  font-size: 10px; letter-spacing:.24em; text-transform:uppercase;
  color:var(--muted); margin-top:8px;
}
.orn { display:flex;align-items:center;gap:10px;margin-top:13px;width:75%;margin-left:auto;margin-right:auto }
.oln { flex:1;height:1px;background:linear-gradient(90deg,transparent,var(--gborder),transparent) }
.odm { width:5px;height:5px;background:var(--gold);transform:rotate(45deg);flex-shrink:0 }

/* Cards */
.cards { display:grid;grid-template-columns:1fr 1fr;gap:12px;width:100% }
.card {
  background: var(--glass);
  border: 1px solid var(--gborder);
  border-radius: 18px;
  padding: 18px 12px;
  text-align: center;
  position: relative; overflow:hidden;
}
.card::before {
  content:'';position:absolute;top:0;left:0;right:0;height:1px;
  background:linear-gradient(90deg,transparent,rgba(212,175,55,.5),transparent);
}
.clbl { font-size:9px;letter-spacing:.22em;text-transform:uppercase;color:var(--muted);margin-bottom:8px }
.cval { font-family:'Cinzel',serif;font-size:clamp(17px,4.2vw,23px);font-weight:700;color:var(--gold) }

/* Wheel section */
.wsect { position:relative;width:100%;display:flex;justify-content:center }
#wc {
  display: block;
  width: 100%;
  max-width: 400px;
  height: auto;
  transition: filter .4s;
}
.spinning #wc { filter: drop-shadow(0 0 28px rgba(212,175,55,.55)) }

/* Spin button */
.sbtn {
  width:100%; max-width:340px;
  padding: 19px 28px;
  font-family: 'Cinzel', serif;
  font-size: clamp(13px, 3.5vw, 15px);
  font-weight: 700; letter-spacing:.14em; text-transform:uppercase;
  color: #1A0E00;
  background: linear-gradient(135deg, var(--gold-dk) 0%, var(--gold) 28%, var(--gold-l) 50%, var(--gold) 72%, var(--gold-dk) 100%);
  background-size: 200% 100%;
  border: none; border-radius: 50px; cursor: pointer;
  box-shadow: 0 0 30px rgba(212,175,55,.18), 0 5px 20px rgba(0,0,0,.65), inset 0 1px 0 rgba(255,255,255,.22);
  transition: transform .25s, box-shadow .25s;
  animation: shs 5s ease-in-out infinite;
}
@keyframes shs { 0%,100%{background-position:0%} 50%{background-position:100%} }
.sbtn:hover:not(:disabled) { transform:translateY(-2px); box-shadow:0 0 48px rgba(212,175,55,.35),0 8px 28px rgba(0,0,0,.65),inset 0 1px 0 rgba(255,255,255,.22) }
.sbtn:active:not(:disabled) { transform:translateY(1px) }
.sbtn:disabled { opacity:.22; cursor:not-allowed; animation:none }
.sbtn-i { display:flex;align-items:center;justify-content:center;gap:10px;pointer-events:none }

/* Legend */
.legend { display:flex;gap:6px;flex-wrap:wrap;justify-content:center }
.pill {
  background:var(--glass);border:1px solid var(--gborder);border-radius:50px;
  padding:4px 11px;font-size:10px;color:var(--muted);letter-spacing:.04em;
}
.pill strong { color:var(--gold);font-weight:600 }

/* Win Modal */
.modal {
  position:fixed;inset:0;
  background:rgba(0,0,0,.84);
  backdrop-filter:blur(12px);-webkit-backdrop-filter:blur(12px);
  display:flex;align-items:center;justify-content:center;
  z-index:999;
  opacity:0;pointer-events:none;
  transition:opacity .35s;
}
.modal.show { opacity:1;pointer-events:all }
.mcard {
  background: linear-gradient(148deg, #0C0C1A, #16102A);
  border: 1px solid rgba(212,175,55,.38);
  border-radius: 30px;
  padding: 40px 30px;
  text-align: center;
  max-width: 310px; width:88%;
  position: relative; overflow:hidden;
  transform: scale(.78) translateY(22px);
  transition: transform .42s cubic-bezier(.34,1.56,.64,1);
  box-shadow: 0 0 70px rgba(212,175,55,.1), 0 28px 64px rgba(0,0,0,.85);
}
.mcard::before {
  content:'';position:absolute;inset:0;
  background:radial-gradient(ellipse at 50% 0%,rgba(212,175,55,.08) 0%,transparent 58%);
  pointer-events:none;
}
.mcard::after {
  content:'';position:absolute;bottom:0;left:0;right:0;height:1px;
  background:linear-gradient(90deg,transparent,rgba(212,175,55,.3),transparent);
}
.modal.show .mcard { transform:scale(1) translateY(0) }

.mtag { font-size:9px;letter-spacing:.3em;text-transform:uppercase;color:var(--muted);margin-bottom:8px }
.mico { font-size:38px;margin:6px 0;line-height:1 }
.mhead { font-family:'Cinzel',serif;font-size:clamp(19px,5vw,26px);font-weight:700;color:var(--gold);margin-bottom:2px }
.mamount {
  font-family: 'Cinzel', serif;
  font-size: clamp(42px,12vw,58px);
  font-weight: 900;
  background: linear-gradient(135deg, var(--gold-d), var(--gold-l), var(--gold));
  -webkit-background-clip:text;-webkit-text-fill-color:transparent;background-clip:text;
  line-height: 1; margin: 20px 0;
}
.msub { font-size:11px;color:var(--muted);letter-spacing:.1em;margin-bottom:28px }
.mbtn {
  background:var(--glass);border:1px solid var(--gborder);border-radius:50px;
  color:var(--gold);font-family:'Cinzel',serif;font-size:12px;font-weight:600;letter-spacing:.1em;
  padding:14px 30px;cursor:pointer;transition:all .2s;
}
.mbtn:hover { background:rgba(212,175,55,.1);box-shadow:0 0 22px rgba(212,175,55,.18) }

/* New balance flash */
.mbalance {
  display:inline-block;
  margin-top:-6px; margin-bottom:6px;
  padding:3px 12px;
  background:rgba(212,175,55,.1);
  border:1px solid rgba(212,175,55,.25);
  border-radius:50px;
  font-size:11px;color:var(--gold);letter-spacing:.06em;
}

/* Mobile */
@media (max-width:380px) {
  .wrap{padding:18px 14px 40px;gap:20px}
  .sbtn{padding:16px 22px}
}
@media (prefers-reduced-motion:reduce) {
  *{animation:none!important;transition:none!important}
}
</style>
</head>
<body>
<div class="blob b1"></div>
<div class="blob b2"></div>
<div class="blob b3"></div>

<div class="wrap">

  <!-- Header -->
  <div class="hdr">
    <a href="index.php" class="back">
      <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M19 12H5M12 5l-7 7 7 7"/></svg>
      Início
    </a>
    <div class="title">✦ FORTUNE WHEEL ✦</div>
    <div class="sub">Gire e conquiste sua sorte</div>
    <div class="orn"><div class="oln"></div><div class="odm"></div><div class="oln"></div></div>
  </div>

  <!-- Info cards -->
  <div class="cards">
    <div class="card"><div class="clbl">Giros disponíveis</div><div class="cval" id="spins">–</div></div>
    <div class="card"><div class="clbl">Saldo atual</div><div class="cval" id="balance">–</div></div>
  </div>

  <!-- Wheel canvas -->
  <div class="wsect" id="wsect">
    <canvas id="wc" width="400" height="426"></canvas>
  </div>

  <!-- Spin button -->
  <button class="sbtn" id="sbtn" disabled>
    <div class="sbtn-i"><span>✦</span><span>Girar Agora</span><span>✦</span></div>
  </button>

  <!-- Prize legend -->
  <div class="legend">
    <div class="pill"><strong>R$ 0,50</strong></div>
    <div class="pill"><strong>R$ 1,00</strong></div>
    <div class="pill"><strong>R$ 2,00</strong></div>
    <div class="pill"><strong>R$ 3,00</strong></div>
    <div class="pill"><strong>R$ 4,00</strong></div>
    <div class="pill"><strong>R$ 5,00</strong></div>
  </div>

</div><!-- .wrap -->

<!-- Win Modal -->
<div class="modal" id="modal">
  <div class="mcard">
    <div class="mtag">✦ resultado ✦</div>
    <div class="mico">🏆</div>
    <div class="mhead">Você ganhou</div>
    <div class="mamount" id="mamount">–</div>
    <div class="mbalance" id="mbalance"></div>
    <div class="msub">creditado ao seu saldo</div>
    <button class="mbtn" onclick="closeModal()">Continuar</button>
  </div>
</div>

<audio id="aSpin" preload="auto"><source src="https://www.soundhelix.com/examples/mp3/SoundHelix-Song-2.mp3"></audio>
<audio id="aWin"  preload="auto"><source src="https://www.soundhelix.com/examples/mp3/SoundHelix-Song-3.mp3"></audio>

<script>
// ============================================================
//  PRIZES — ordem exatamente igual ao PHP (índice = segmento)
// ============================================================
const PRIZES = [
  { label:'R$ 0,50', c0:'#0B3020', c1:'#1A6B42', hi:'#2DBF74' }, // 0
  { label:'R$ 1,00', c0:'#0A1848', c1:'#1A3D92', hi:'#3068D8' }, // 1
  { label:'R$ 0,50', c0:'#3C0A0A', c1:'#821818', hi:'#CC3030' }, // 2
  { label:'R$ 2,00', c0:'#1E0848', c1:'#4C18A0', hi:'#7F38E0' }, // 3
  { label:'R$ 1,00', c0:'#08203C', c1:'#144E88', hi:'#2488D0' }, // 4
  { label:'R$ 3,00', c0:'#2E1200', c1:'#6A2C00', hi:'#A85A12' }, // 5
  { label:'R$ 4,00', c0:'#0A0A3A', c1:'#1A1A80', hi:'#3535C8' }, // 6
  { label:'R$ 5,00', c0:'#3A2000', c1:'#825000', hi:'#D48A00' }, // 7
];

const N = PRIZES.length;
const cnv = document.getElementById('wc');
const ctx = cnv.getContext('2d');
const W = cnv.width;       // 400
const H = cnv.height;      // 426
const CX = W / 2;          // 200
const CY = H / 2 + 13;     // 226  → shifts wheel down to leave room for pointer above
const R  = 168;             // wheel radius
const APR = (2 * Math.PI) / N;   // angle per segment (radians)

let rot     = 0;     // accumulated degrees
let running = false;

// ── Draw ────────────────────────────────────────────────────
function draw() {
  ctx.clearRect(0, 0, W, H);
  ctx.save();
  ctx.translate(CX, CY);

  const rad = rot * Math.PI / 180;

  // ── Outer ambient glow ──────────────────────────────────
  const aGlow = ctx.createRadialGradient(0,0, R-10, 0,0, R+40);
  aGlow.addColorStop(0, 'transparent');
  aGlow.addColorStop(0.7, 'rgba(212,175,55,0.09)');
  aGlow.addColorStop(1, 'transparent');
  ctx.beginPath(); ctx.arc(0,0, R+40, 0, Math.PI*2);
  ctx.fillStyle = aGlow; ctx.fill();

  // ── Chrome outer ring ───────────────────────────────────
  ctx.beginPath(); ctx.arc(0,0, R+18, 0, Math.PI*2);
  const rg = ctx.createLinearGradient(-R-18, -R-18, R+18, R+18);
  rg.addColorStop(0,   '#3A2400');
  rg.addColorStop(0.2, '#C8A030');
  rg.addColorStop(0.42,'#FFE57C');
  rg.addColorStop(0.58,'#FFE57C');
  rg.addColorStop(0.8, '#C8A030');
  rg.addColorStop(1,   '#3A2400');
  ctx.strokeStyle = rg; ctx.lineWidth = 18; ctx.stroke();

  // ── Inner shadow band ───────────────────────────────────
  ctx.beginPath(); ctx.arc(0,0, R+9, 0, Math.PI*2);
  ctx.strokeStyle = 'rgba(0,0,0,.75)'; ctx.lineWidth = 4; ctx.stroke();

  // ── Segments + text (rotated) ───────────────────────────
  ctx.save();
  ctx.rotate(rad);

  for (let i = 0; i < N; i++) {
    const sa = i * APR - Math.PI/2;
    const ea = (i+1) * APR - Math.PI/2;
    const p  = PRIZES[i];

    // Radial gradient: mid-tone inner → dark outer
    const sg = ctx.createRadialGradient(0,0, 12, 0,0, R);
    sg.addColorStop(0,   p.c1);
    sg.addColorStop(0.5, p.c0);
    sg.addColorStop(1,   p.c0);

    ctx.beginPath(); ctx.moveTo(0,0); ctx.arc(0,0, R, sa, ea); ctx.closePath();
    ctx.fillStyle = sg; ctx.fill();

    // Segment border
    ctx.strokeStyle = 'rgba(0,0,0,.55)'; ctx.lineWidth = 2; ctx.stroke();

    // Outer arc highlight (sheen)
    ctx.save();
    ctx.beginPath(); ctx.arc(0,0, R-8, sa+0.05, ea-0.05);
    ctx.strokeStyle = 'rgba(255,255,255,0.06)'; ctx.lineWidth = 10; ctx.stroke();
    ctx.restore();
  }

  // Text pass (on top of all fills)
  for (let i = 0; i < N; i++) {
    const ma = i * APR - Math.PI/2 + APR/2;
    ctx.save();
    ctx.rotate(ma);

    // Label shadow
    ctx.font = 'bold 13px "Cinzel", serif';
    ctx.textAlign = 'center';
    ctx.textBaseline = 'middle';
    ctx.shadowColor = 'rgba(0,0,0,.95)';
    ctx.shadowBlur  = 8;
    ctx.fillStyle   = '#FFFFFF';
    ctx.fillText(PRIZES[i].label, R * 0.64, 0);
    ctx.shadowBlur  = 0;

    // Outer diamond gem
    ctx.save();
    ctx.translate(R - 17, 0);
    ctx.rotate(Math.PI / 4);
    ctx.fillStyle = `rgba(255,229,124,.5)`;
    ctx.fillRect(-3.5, -3.5, 7, 7);
    ctx.restore();

    ctx.restore();
  }

  // Segment divider notches on outer chrome ring
  for (let i = 0; i < N; i++) {
    const a  = i * APR - Math.PI/2;
    const x1 = Math.cos(a) * (R + 2);
    const y1 = Math.sin(a) * (R + 2);
    const x2 = Math.cos(a) * (R + 22);
    const y2 = Math.sin(a) * (R + 22);
    ctx.beginPath(); ctx.moveTo(x1,y1); ctx.lineTo(x2,y2);
    ctx.strokeStyle = 'rgba(0,0,0,.7)'; ctx.lineWidth = 3; ctx.stroke();

    // Gold gem at each notch
    ctx.save();
    ctx.translate(Math.cos(a)*(R+26), Math.sin(a)*(R+26));
    ctx.rotate(Math.PI/4);
    const gg = ctx.createLinearGradient(-4,-4,4,4);
    gg.addColorStop(0,'#FFE57C'); gg.addColorStop(1,'#9A7B20');
    ctx.fillStyle = gg;
    ctx.fillRect(-4,-4,8,8);
    ctx.restore();
  }

  ctx.restore(); // undo rotate(rad)

  // ── Center hub ──────────────────────────────────────────
  // Dark plate
  ctx.shadowColor = 'rgba(0,0,0,.9)'; ctx.shadowBlur = 20;
  ctx.beginPath(); ctx.arc(0,0, 46, 0, Math.PI*2);
  ctx.fillStyle = '#06060A'; ctx.fill(); ctx.shadowBlur = 0;

  // Gold ring
  const hg = ctx.createRadialGradient(-9,-9, 2, 0,0, 42);
  hg.addColorStop(0,   '#FFE57C');
  hg.addColorStop(0.35,'#D4AF37');
  hg.addColorStop(0.72,'#9A7B20');
  hg.addColorStop(1,   '#4A2E00');
  ctx.beginPath(); ctx.arc(0,0, 40, 0, Math.PI*2);
  ctx.fillStyle = hg; ctx.fill();

  // Inner dark well
  ctx.beginPath(); ctx.arc(0,0, 26, 0, Math.PI*2);
  ctx.fillStyle = '#08080E'; ctx.fill();

  // Center dot
  ctx.beginPath(); ctx.arc(0,0, 8, 0, Math.PI*2);
  ctx.fillStyle = '#D4AF37'; ctx.fill();

  // Hub lens sheen
  ctx.beginPath(); ctx.arc(-7,-7, 13, 0, Math.PI*2);
  ctx.fillStyle = 'rgba(255,255,255,0.055)'; ctx.fill();

  // ── Pointer (static, drawn last) ────────────────────────
  const py = -(R + 32);   // tip of diamond
  ctx.save();
  ctx.translate(0, py);

  // Glow halo
  ctx.shadowColor = 'rgba(212,175,55,.9)'; ctx.shadowBlur = 18;

  // Diamond shape
  const pg = ctx.createLinearGradient(-8,-10, 8,10);
  pg.addColorStop(0, '#FFE57C');
  pg.addColorStop(0.5,'#D4AF37');
  pg.addColorStop(1,  '#9A7B20');
  ctx.beginPath();
  ctx.moveTo(0,-10); ctx.lineTo(9,0); ctx.lineTo(0,10); ctx.lineTo(-9,0);
  ctx.closePath();
  ctx.fillStyle = pg; ctx.fill();
  ctx.shadowBlur = 0;

  // Inner highlight
  ctx.beginPath();
  ctx.moveTo(0,-7); ctx.lineTo(4,0); ctx.lineTo(0,3); ctx.lineTo(-4,0);
  ctx.closePath();
  ctx.fillStyle = 'rgba(255,255,255,0.3)'; ctx.fill();

  // Stem connecting to wheel
  const stemG = ctx.createLinearGradient(0,10, 0,36);
  stemG.addColorStop(0, 'rgba(212,175,55,.7)');
  stemG.addColorStop(1, 'rgba(212,175,55,0)');
  ctx.beginPath(); ctx.moveTo(0,10); ctx.lineTo(0,34);
  ctx.strokeStyle = stemG; ctx.lineWidth = 2.5; ctx.stroke();

  ctx.restore();

  ctx.restore(); // undo translate(CX, CY)
}

// ── Floating particles ───────────────────────────────────────
(function spawnParticles() {
  const div = document.createElement('div');
  div.style.cssText = 'position:fixed;inset:0;pointer-events:none;z-index:0;overflow:hidden';
  document.body.appendChild(div);
  const st = document.createElement('style');
  st.textContent = '@keyframes frise{0%{transform:translateY(0)rotate(0deg);opacity:0}8%{opacity:1}88%{opacity:.5}100%{transform:translateY(-110vh)rotate(540deg);opacity:0}}';
  document.head.appendChild(st);
  for (let i = 0; i < 22; i++) {
    const p = document.createElement('div');
    const sz = Math.random() * 2.5 + 1;
    const alpha = (.14 + Math.random() * .32).toFixed(2);
    p.style.cssText = `position:absolute;width:${sz}px;height:${sz}px;border-radius:50%;` +
      `background:rgba(212,175,55,${alpha});` +
      `left:${(Math.random()*100).toFixed(1)}%;bottom:-6px;` +
      `animation:frise ${(14+Math.random()*14).toFixed(1)}s ${(Math.random()*20).toFixed(1)}s linear infinite`;
    div.appendChild(p);
  }
})();

// ── Load status ─────────────────────────────────────────────
async function loadStatus() {
  try {
    const fd = new FormData(); fd.append('action','get_status');
    const d = await (await fetch('',{method:'POST',body:fd})).json();
    if (d.status === 'success') {
      document.getElementById('spins').textContent   = d.qtd_spins;
      document.getElementById('balance').textContent = 'R$ ' + d.balance;
      document.getElementById('sbtn').disabled = d.qtd_spins <= 0;
    }
  } catch(e) { console.error(e) }
}

// ── Spin ────────────────────────────────────────────────────
async function spin() {
  if (running) return;
  const btn = document.getElementById('sbtn');
  btn.disabled = true; running = true;
  document.getElementById('wsect').classList.add('spinning');

  try {
    const fd = new FormData(); fd.append('action','spin');
    const d = await (await fetch('',{method:'POST',body:fd})).json();

    if (d.status !== 'success') {
      alert(d.message || 'Erro ao girar');
      btn.disabled = false; running = false;
      document.getElementById('wsect').classList.remove('spinning');
      return;
    }

    // ── Spin math ──
    const idx  = d.prize_index ?? 0;
    const apd  = 360 / N;                          // degrees per segment
    const segC = idx * apd + apd / 2;              // center of winning segment (°)
    const tgt  = (360 - segC) % 360;               // target rotation to align pointer
    const cur  = rot % 360;
    let extra  = (tgt - cur + 360) % 360;
    if (extra < apd) extra += 360;                 // ensure forward movement
    const total = 5 * 360 + extra;                 // 5 full spins + land on prize
    const dur   = 4800;

    const t0  = performance.now();
    const r0  = rot;

    // play audio
    try { const a = document.getElementById('aSpin'); a.currentTime=0; a.play(); } catch(e){}

    // Quintic ease-out: snappy start, smooth graceful deceleration
    function ease(t) { return 1 - Math.pow(1-t, 5); }

    function frame(now) {
      const t = Math.min((now - t0) / dur, 1);
      rot = r0 + total * ease(t);
      draw();
      if (t < 1) {
        requestAnimationFrame(frame);
      } else {
        rot = r0 + total; draw();
        document.getElementById('wsect').classList.remove('spinning');
        setTimeout(() => showWin(d.prize, d.new_balance), 380);
      }
    }
    requestAnimationFrame(frame);

  } catch(e) {
    console.error(e);
    btn.disabled = false; running = false;
    document.getElementById('wsect').classList.remove('spinning');
  }
}

// ── Confetti ────────────────────────────────────────────────
function boom() {
  const c = ['#D4AF37','#FFE57C','#9A7B20','#FFFFFF','#AA2020','#FFD700'];
  confetti({ particleCount:120, spread:70, origin:{y:.62}, colors:c });
  setTimeout(() => confetti({ particleCount:80, angle:62, spread:56, origin:{x:0}, colors:c }), 220);
  setTimeout(() => confetti({ particleCount:80, angle:118,spread:56, origin:{x:1}, colors:c }), 400);
}

// ── Win Modal ───────────────────────────────────────────────
function showWin(prize, newBalance) {
  document.getElementById('mamount').textContent  = prize.label;
  document.getElementById('mbalance').textContent = 'Saldo: R$ ' + newBalance;
  document.getElementById('modal').classList.add('show');
  running = false;
  loadStatus();
  try { const a = document.getElementById('aWin'); a.currentTime=0; a.play(); } catch(e){}
  boom();
}

function closeModal() {
  document.getElementById('modal').classList.remove('show');
  document.getElementById('sbtn').disabled = false;
}

// ── Init ─────────────────────────────────────────────────────
draw();
loadStatus();
document.getElementById('sbtn').addEventListener('click', spin);
</script>
</body>
</html>
