const canvas = document.getElementById('gameCanvas');
const ctx = canvas.getContext('2d');
const multiplierDisplay = document.getElementById('multiplierDisplay');
const gameStatus = document.getElementById('gameStatus');
const plane = document.getElementById('planeGif');
const betButton = document.getElementById('betButton');
const balanceAmountEl = document.getElementById('balanceAmount');
const betInput = document.getElementById('betAmount');
const increaseBetBtn = document.getElementById('increaseBet');
const decreaseBetBtn = document.getElementById('decreaseBet');
const playerCountEl = document.getElementById('playerCount');
const toastEl = document.getElementById('toast');
const toastValue = document.getElementById('toastValue');
const toastSubtitle = document.getElementById('toastSubtitle');
const countdownEl = document.getElementById('countdown');
const potentialWinEl = document.getElementById('potentialWin');

const aviatorMusic = document.getElementById('aviatorMusic');
const partidaSound = document.getElementById('partidaSound');
const cashoutSound = document.getElementById('cashoutSound');
const vooSound = document.getElementById('vooSound');

// Register Modal Elements
const registerModal = document.getElementById('registerModal');
const registerName = document.getElementById('registerName');
const registerWhatsapp = document.getElementById('registerWhatsapp');
const registerBtn = document.getElementById('registerBtn');

// Deposit Modal Elements
const depositModal = document.getElementById('depositModal');
const openDepositBtn = document.getElementById('openDepositBtn');
const closeDepositModal = document.getElementById('closeDepositModal');
// const depositSlider = document.getElementById('depositSlider');
// const depositAmountDisplay = document.getElementById('depositAmountDisplay');
// const generateDepositBtn = document.getElementById('generateDepositBtn');

// QR Modal Elements
const qrModal = document.getElementById('qrModal');
const closeQrModal = document.getElementById('closeQrModal');
const qrCodeImage = document.getElementById('qrCodeImage');
const pixCode = document.getElementById('pixCode');
const copyPixBtn = document.getElementById('copyPixBtn');
const verifyPaymentBtn = document.getElementById('verifyPaymentBtn');
const paymentStatus = document.getElementById('paymentStatus');

// Backend URL
const BACKEND_URL = '/backend';

let isPlaying = false;
let startTime = 0;
let currentMultiplier = 1.00;
let targetMultiplier = 1.00;
let balance = 0;
let currentBet = 0;
let hasCashedOut = false;
let curveAnimationProgress = 0;
let isCashingOut = false;
let cashoutSoundPlaying = false;
let currentTransactionId = null;
let verifyInterval = null;
let sessionToken = null;
let userId = null;

// Game probabilities from admin panel
let gameProbabilities = {
    range_0_1_5: 30,
    range_1_5_3: 40,
    range_3_6: 20,
    range_6_15: 10
};

// Fetch probabilities from server
async function loadProbabilities() {
    try {
        const response = await fetch(`${BACKEND_URL}/get_probabilities.php`);
        const data = await response.json();
        
        if (data.success) {
            gameProbabilities = {
                range_0_1_5: data.range_0_1_5,
                range_1_5_3: data.range_1_5_3,
                range_3_6: data.range_3_6,
                range_6_15: data.range_6_15
            };
            console.log('Probabilidades carregadas:', gameProbabilities);
        }
    } catch (error) {
        console.error('Erro ao carregar probabilidades:', error);
    }
}

// Generate multiplier based on probabilities
function generateMultiplier() {
    const random = Math.random() * 100;
    let cumulativeProbability = 0;
    
    // Range 1: 1.00x - 1.5x
    cumulativeProbability += gameProbabilities.range_0_1_5;
    if (random < cumulativeProbability) {
        return 1.0 + Math.random() * 0.5;
    }
    
    // Range 2: 1.5x - 3x
    cumulativeProbability += gameProbabilities.range_1_5_3;
    if (random < cumulativeProbability) {
        return 1.5 + Math.random() * 1.5;
    }
    
    // Range 3: 3x - 6x
    cumulativeProbability += gameProbabilities.range_3_6;
    if (random < cumulativeProbability) {
        return 3 + Math.random() * 3;
    }
    
    // Range 4: 6x - 15x
    return 6 + Math.random() * 9;
}

// Função para carregar histórico inicial de multiplicadores
async function loadInitialMultiplierHistory() {
    try {
        const response = await fetch(`${BACKEND_URL}/get_recent_multipliers.php`);
        const data = await response.json();
        
        if (data.success && data.multipliers && data.multipliers.length > 0) {
            const historyContainer = document.querySelector('.multiplier-history');
            const moreButton = historyContainer.querySelector('.more-button');
            
            // Limpar histórico padrão
            const defaultItems = historyContainer.querySelectorAll('.multiplier-item');
            defaultItems.forEach(item => item.remove());
            
            // Adicionar multiplicadores do servidor (já vêm do mais recente para o mais antigo)
            data.multipliers.forEach(multiplier => {
                const multiplierItem = document.createElement('div');
                multiplierItem.className = multiplier >= 2 ? 'multiplier-item green' : 'multiplier-item red';
                multiplierItem.textContent = multiplier.toFixed(2) + 'x';
                historyContainer.insertBefore(multiplierItem, moreButton);
            });
            
            console.log('Histórico de multiplicadores carregado:', data.multipliers);
        }
    } catch (error) {
        console.error('Erro ao carregar histórico de multiplicadores:', error);
        // Manter histórico padrão do HTML em caso de erro
    }
}

// Função para atualizar saldo do servidor
async function updateBalanceFromServer() {
    const savedToken = localStorage.getItem('session_token');
    if (!savedToken) return;
    
    try {
        const response = await fetch(`${BACKEND_URL}/get_balance.php?session_token=${encodeURIComponent(savedToken)}`);
        const data = await response.json();
        
        if (data.success) {
            balance = data.balance;
            balanceAmountEl.textContent = balance.toFixed(2).replace('.', ',');
            console.log('Saldo atualizado do servidor:', balance);
        }
    } catch (error) {
        console.error('Erro ao atualizar saldo:', error);
    }
}

// Função para salvar saldo no servidor
async function saveBalanceToServer() {
    const savedToken = localStorage.getItem('session_token');
    if (!savedToken) return;
    
    try {
        const response = await fetch(`${BACKEND_URL}/update_balance.php`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                session_token: savedToken,
                balance: balance
            })
        });
        const data = await response.json();
        
        if (data.success) {
            console.log('Saldo salvo no servidor:', data.balance);
        }
    } catch (error) {
        console.error('Erro ao salvar saldo:', error);
    }
}

// Função para salvar histórico de jogada
async function saveGameHistory(betAmount, multiplier, winAmount, result) {
    const savedToken = localStorage.getItem('session_token');
    if (!savedToken) return;
    
    try {
        const response = await fetch(`${BACKEND_URL}/save_game_history.php`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                session_token: savedToken,
                bet_amount: betAmount,
                multiplier: multiplier,
                win_amount: winAmount,
                result: result
            })
        });
        const data = await response.json();
        
        if (data.success) {
            console.log('Histórico salvo:', result, multiplier);
        }
    } catch (error) {
        console.error('Erro ao salvar histórico:', error);
    }
}

const statusThemes = {
    neutral: { bg: 'rgba(0, 0, 0, 0.7)', color: '#ffffff' },
    flying: { bg: 'rgba(34, 197, 94, 0.2)', color: '#22c55e' },
    warning: { bg: 'rgba(251, 191, 36, 0.2)', color: '#facc15' },
    error: { bg: 'rgba(239, 68, 68, 0.3)', color: '#ef4444' },
    success: { bg: 'linear-gradient(135deg, rgba(34, 197, 94, 0.95), rgba(22, 163, 74, 0.95))', color: '#ffffff' }
};

function formatCurrency(value) {
    return value.toLocaleString('pt-BR', {
        minimumFractionDigits: 2,
        maximumFractionDigits: 2
    });
}

function updateBalanceDisplay() {
    balanceAmountEl.textContent = formatCurrency(balance);
}

function updateStatus(message, variant = 'neutral') {
    const theme = statusThemes[variant] || statusThemes.neutral;
    gameStatus.textContent = message;
    gameStatus.style.background = theme.bg;
    gameStatus.style.color = theme.color;
}

function updatePlayerCount() {
    const count = Math.floor(100 + Math.random() * 101);
    playerCountEl.textContent = count;
}

function createConfetti() {
    const colors = ['#00ff00', '#00ff88', '#88ff00', '#ffff00', '#ff9800', '#00ffff'];
    const confettiCount = 60;
    
    for (let i = 0; i < confettiCount; i++) {
        const confetti = document.createElement('div');
        confetti.className = 'confetti';
        confetti.style.left = Math.random() * 100 + '%';
        confetti.style.backgroundColor = colors[Math.floor(Math.random() * colors.length)];
        confetti.style.animationDelay = Math.random() * 0.3 + 's';
        confetti.style.animationDuration = (Math.random() * 1 + 1.5) + 's';
        document.body.appendChild(confetti);
        
        setTimeout(() => {
            confetti.remove();
        }, 3000);
    }
}

function showCountdown(callback) {
    let count = 3;
    
    function displayNumber() {
        if (count === 0) {
            callback();
            return;
        }
        
        countdownEl.textContent = count;
        countdownEl.classList.add('show');
        
        setTimeout(() => {
            countdownEl.classList.remove('show');
            count--;
            setTimeout(() => {
                if (count >= 0) {
                    displayNumber();
                }
            }, 100);
        }, 900);
    }
    
    displayNumber();
}

// Sound management
function playSound(audio, loop = false) {
    try {
        audio.currentTime = 0;
        audio.loop = loop;
        audio.play().catch(err => console.log('Audio play failed:', err));
    } catch (e) {
        console.log('Audio error:', e);
    }
}

function stopSound(audio) {
    try {
        audio.pause();
        audio.currentTime = 0;
        audio.loop = false;
    } catch (e) {
        console.log('Audio stop error:', e);
    }
}

function addMultiplierToHistory(multiplier) {
    const historyContainer = document.querySelector('.multiplier-history');
    const moreButton = historyContainer.querySelector('.more-button');
    
    const multiplierItem = document.createElement('div');
    multiplierItem.className = multiplier >= 2 ? 'multiplier-item green' : 'multiplier-item red';
    multiplierItem.textContent = multiplier.toFixed(2) + 'x';
    
    // Adicionar como PRIMEIRO item (depois do último item antes do botão)
    const firstItem = historyContainer.querySelector('.multiplier-item');
    if (firstItem) {
        historyContainer.insertBefore(multiplierItem, firstItem);
    } else {
        historyContainer.insertBefore(multiplierItem, moreButton);
    }
    
    // Manter apenas os últimos 10 multiplicadores
    const items = historyContainer.querySelectorAll('.multiplier-item');
    if (items.length > 10) {
        items[items.length - 1].remove();
    }
}

// Máscara para WhatsApp
registerWhatsapp.addEventListener('input', (e) => {
    let value = e.target.value.replace(/\D/g, '');
    if (value.length > 11) value = value.substr(0, 11);
    
    if (value.length > 10) {
        e.target.value = value.replace(/(\d{2})(\d{5})(\d{4})/, '($1) $2-$3');
    } else if (value.length > 6) {
        e.target.value = value.replace(/(\d{2})(\d{4})(\d{0,4})/, '($1) $2-$3');
    } else if (value.length > 2) {
        e.target.value = value.replace(/(\d{2})(\d{0,5})/, '($1) $2');
    } else {
        e.target.value = value.replace(/(\d*)/, '$1');
    }
});

// Register/Login
registerBtn.addEventListener('click', async () => {
    const name = registerName.value.trim();
    const whatsapp = registerWhatsapp.value.replace(/\D/g, '');
    
    if (!name || name.length < 3) {
        alert('Por favor, digite seu nome completo');
        return;
    }
    
    if (!whatsapp || whatsapp.length < 10) {
        alert('Por favor, digite um WhatsApp válido');
        return;
    }
    
    registerBtn.disabled = true;
    registerBtn.textContent = 'CARREGANDO...';
    
    try {
        const response = await fetch(`${BACKEND_URL}/register.php`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({ name, whatsapp })
        });
        
        const data = await response.json();
        
        if (!data.success) {
            throw new Error(data.message || 'Erro ao fazer cadastro');
        }
        
        // Salvar sessão
        sessionToken = data.session_token;
        userId = data.user.id;
        balance = data.user.balance;
        
        localStorage.setItem('session_token', sessionToken);
        localStorage.setItem('user_id', userId);
        
        updateBalanceDisplay();
        
        // Fechar modal de registro
        registerModal.classList.remove('show');
        
        // Mostrar modal de depósito
        setTimeout(() => {
            depositModal.classList.add('show');
        }, 500);
        
    } catch (error) {
        alert(error.message);
        registerBtn.disabled = false;
        registerBtn.textContent = 'COMEÇAR A JOGAR';
    }
});

// Deposit Modal Functions
openDepositBtn.addEventListener('click', () => {
    depositModal.classList.add('show');
});

closeDepositModal.addEventListener('click', () => {
    depositModal.classList.remove('show');
});

// Menu Dropdown Functions
const menuButton = document.getElementById('menuButton');
const menuDropdown = document.getElementById('menuDropdown');
const logoutBtn = document.getElementById('logoutBtn');

menuButton.addEventListener('click', (e) => {
    e.stopPropagation();
    menuDropdown.classList.toggle('show');
});

// Close dropdown when clicking outside
document.addEventListener('click', (e) => {
    if (!menuButton.contains(e.target) && !menuDropdown.contains(e.target)) {
        menuDropdown.classList.remove('show');
    }
});

// Logout functionality
logoutBtn.addEventListener('click', () => {
    localStorage.clear();
    window.location.href = '/jogo';
});

closeQrModal.addEventListener('click', () => {
    qrModal.classList.remove('show');
    if (verifyInterval) {
        clearInterval(verifyInterval);
        verifyInterval = null;
    }
});

// Depósito agora usa links externos - slider e botão de gerar foram removidos
/*
depositSlider.addEventListener('input', (e) => {
    const value = parseFloat(e.target.value);
    depositAmountDisplay.textContent = formatCurrency(value);
    
    const percentage = ((value - 10) / (300 - 10)) * 100;
    depositSlider.style.background = `linear-gradient(to right, #22c55e 0%, #22c55e ${percentage}%, rgba(255, 255, 255, 0.2) ${percentage}%, rgba(255, 255, 255, 0.2) 100%)`;
});

generateDepositBtn.addEventListener('click', async () => {
    const amount = parseFloat(depositSlider.value);
    generateDepositBtn.disabled = true;
    generateDepositBtn.textContent = 'GERANDO...';
    
    try {
        const response = await fetch(`${BACKEND_URL}/create_deposit.php`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                session_token: sessionToken,
                amount: amount
            })
        });
        
        const data = await response.json();
        
        if (!data.success) {
            throw new Error(data.message || 'Erro ao gerar depósito');
        }
        
        currentTransactionId = data.transaction_id;
        
        // Exibir QR Code
        qrCodeImage.src = data.qr_code_url;
        pixCode.value = data.pix_code;
        
        // Fechar modal de depósito e abrir modal de QR Code
        depositModal.classList.remove('show');
        setTimeout(() => {
            qrModal.classList.add('show');
            startAutoVerification();
        }, 300);
        
        generateDepositBtn.disabled = false;
        generateDepositBtn.textContent = 'REALIZAR DEPÓSITO';
        
    } catch (error) {
        console.error('ERRO COMPLETO:', error);
        console.error('ERRO MENSAGEM:', error.message);
        alert(error.message);
        generateDepositBtn.disabled = false;
        generateDepositBtn.textContent = 'REALIZAR DEPÓSITO';
    }
});
*/

copyPixBtn.addEventListener('click', () => {
    pixCode.select();
    pixCode.setSelectionRange(0, 99999);
    
    navigator.clipboard.writeText(pixCode.value).then(() => {
        const originalText = copyPixBtn.textContent;
        copyPixBtn.textContent = 'COPIADO!';
        copyPixBtn.style.background = 'rgba(34, 197, 94, 0.4)';
        
        setTimeout(() => {
            copyPixBtn.textContent = originalText;
            copyPixBtn.style.background = 'rgba(34, 197, 94, 0.2)';
        }, 2000);
    }).catch(err => {
        console.error('Erro ao copiar:', err);
    });
});

verifyPaymentBtn.addEventListener('click', async () => {
    await checkPaymentStatus();
});

async function checkPaymentStatus() {
    if (!currentTransactionId) return;
    
    verifyPaymentBtn.disabled = true;
    verifyPaymentBtn.textContent = 'VERIFICANDO...';
    paymentStatus.className = 'payment-status pending';
    paymentStatus.textContent = 'Verificando pagamento...';
    paymentStatus.style.display = 'block';
    
    try {
        const response = await fetch(`${BACKEND_URL}/verify_payment.php`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                session_token: sessionToken,
                transaction_id: currentTransactionId
            })
        });
        
        const data = await response.json();
        
        if (!data.success) {
            throw new Error(data.message || 'Erro ao verificar pagamento');
        }
        
        if (data.status === 'approved') {
            balance = data.new_balance;
            updateBalanceDisplay();
            
            paymentStatus.className = 'payment-status success';
            paymentStatus.textContent = 'Pagamento aprovado! Saldo creditado.';
            
            if (verifyInterval) {
                clearInterval(verifyInterval);
                verifyInterval = null;
            }
            
            setTimeout(() => {
                qrModal.classList.remove('show');
            }, 2000);
            
        } else {
            paymentStatus.className = 'payment-status pending';
            paymentStatus.textContent = 'Aguardando pagamento...';
            verifyPaymentBtn.disabled = false;
            verifyPaymentBtn.textContent = 'VERIFICAR PAGAMENTO';
        }
        
    } catch (error) {
        paymentStatus.className = 'payment-status error';
        paymentStatus.textContent = error.message;
        verifyPaymentBtn.disabled = false;
        verifyPaymentBtn.textContent = 'VERIFICAR PAGAMENTO';
    }
}

function startAutoVerification() {
    if (verifyInterval) clearInterval(verifyInterval);
    
    verifyInterval = setInterval(async () => {
        if (!currentTransactionId || !qrModal.classList.contains('show')) {
            clearInterval(verifyInterval);
            verifyInterval = null;
            return;
        }
        
        await checkPaymentStatus();
    }, 5000); // Verificar a cada 5 segundos
}

updateBalanceDisplay();
updatePlayerCount();
updateStatus('Aguardando...', 'neutral');
setInterval(updatePlayerCount, 1000);

// Canvas
function resizeCanvas() {
    canvas.width = canvas.offsetWidth;
    canvas.height = canvas.offsetHeight;
}
resizeCanvas();
window.addEventListener('resize', resizeCanvas);

// Background
let stripeOffset = 0;
function drawBackground() {
    ctx.fillStyle = '#1a1d29';
    ctx.fillRect(0, 0, canvas.width, canvas.height);
    
    const gradient = ctx.createLinearGradient(0, 0, 0, canvas.height * 0.4);
    gradient.addColorStop(0, 'rgba(13, 15, 22, 0.8)');
    gradient.addColorStop(1, 'transparent');
    ctx.fillStyle = gradient;
    ctx.fillRect(0, 0, canvas.width, canvas.height * 0.4);
    
    if (isPlaying) {
        stripeOffset += 0.3;
        if (stripeOffset >= 100) stripeOffset = 0;
    }
    
    ctx.strokeStyle = 'rgba(0, 0, 0, 0.25)';
    ctx.lineWidth = 50;
    for (let i = -canvas.height + stripeOffset; i < canvas.width + canvas.height; i += 100) {
        ctx.beginPath();
        ctx.moveTo(i, canvas.height);
        ctx.lineTo(i + canvas.height, 0);
        ctx.stroke();
    }
}

// Desenhar curva
function generateCurvePoints(mult) {
    const W = canvas.width;
    const H = canvas.height;
    const xStart = W * 0.06;
    const xLimit = W * 0.94;
    const baseY = H * 0.92;
    const minY = H * 0.2;
    const heightRange = baseY - minY;
    const segments = 260;
    const fullWidthMultiplier = 1.5;
    const safeMult = Math.max(mult, 1.001);
    const growthFactor = Math.min(1, Math.pow(Math.log(safeMult) / Math.log(6.5), 0.82));
    const widthProgress = Math.min(safeMult / fullWidthMultiplier, 1);
    const xReach = xStart + (xLimit - xStart) * widthProgress;
    const overflow = Math.max(mult - fullWidthMultiplier, 0);
    const compression = 1 / (1 + overflow * 0.9);
    const points = [];

    const visibleSegments = Math.floor(segments * curveAnimationProgress);

    for (let i = 0; i <= visibleSegments; i++) {
        const t = i / segments;
        const easedT = 1 - Math.pow(1 - t, 0.9);
        const horizontalEase = 1 - Math.exp(-4.4 * easedT);
        const x = xStart + (xReach - xStart) * Math.pow(horizontalEase, compression);
        const concave = 1 - Math.exp(-1.8 * Math.pow(easedT, 1.05));
        const yOffset = heightRange * concave * growthFactor;
        const y = Math.max(baseY - yOffset, minY);
        points.push({ x, y });
    }

    return points;
}

function drawCurve(mult) {
    const H = canvas.height;
    const points = generateCurvePoints(mult);
    if (!points.length) return;

    ctx.strokeStyle = '#ff0844';
    ctx.lineWidth = 3.5;
    ctx.shadowColor = '#ff0844';
    ctx.shadowBlur = 15;

    ctx.beginPath();
    ctx.moveTo(points[0].x, points[0].y);
    for (let i = 1; i < points.length; i++) {
        ctx.lineTo(points[i].x, points[i].y);
    }
    ctx.stroke();
    ctx.shadowBlur = 0;

    const gradient = ctx.createLinearGradient(0, H * 0.4, 0, H);
    gradient.addColorStop(0, 'rgba(220, 38, 38, 0.4)');
    gradient.addColorStop(1, 'rgba(220, 38, 38, 0.0)');
    ctx.fillStyle = gradient;

    ctx.beginPath();
    ctx.moveTo(points[0].x, H);
    for (let i = 0; i < points.length; i++) {
        ctx.lineTo(points[i].x, points[i].y);
    }
    ctx.lineTo(points[points.length - 1].x, H);
    ctx.closePath();
    ctx.fill();

    const lastPoint = points[points.length - 1];
    const prevPoint = points[Math.max(points.length - 3, 0)];
    plane.style.left = `${lastPoint.x - 40}px`;
    plane.style.top = `${lastPoint.y - 40}px`;
    const angle = Math.atan2(lastPoint.y - prevPoint.y, lastPoint.x - prevPoint.x);
    const maxTilt = 15 * (Math.PI / 180);
    const minTilt = -5 * (Math.PI / 180);
    const clampedAngle = Math.max(minTilt, Math.min(maxTilt, angle));
    plane.style.transform = `rotate(${clampedAngle}rad)`;
}

// Animação
function animate(timestamp) {
    if (!isPlaying) return;
    
    if (!startTime) startTime = timestamp;
    const elapsed = (timestamp - startTime) / 1000;
    
    curveAnimationProgress = Math.min(1, elapsed / 0.8);
    currentMultiplier = 1 + elapsed * 0.22;
    
    multiplierDisplay.textContent = currentMultiplier.toFixed(2) + 'x';
    
    if (currentBet > 0) {
        const potentialWin = currentBet * currentMultiplier;
        potentialWinEl.textContent = `Multiplicador: R$ ${formatCurrency(potentialWin)}`;
        if (!hasCashedOut && betButton.classList.contains('cashout')) {
            betButton.textContent = `RETIRAR R$ ${formatCurrency(potentialWin)}`;
        }
    }
    
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    drawBackground();
    drawCurve(currentMultiplier);
    
    if (currentMultiplier >= targetMultiplier) {
        crash();
        return;
    }
    
    requestAnimationFrame(animate);
}

// Bet Flow
async function placeBet() {
    if (isPlaying) return;
    
    // Esconder animação de espera na primeira aposta
    const waitingOverlay = document.getElementById('waitingOverlay');
    if (waitingOverlay && !waitingOverlay.classList.contains('hidden')) {
        waitingOverlay.classList.add('hidden');
        setTimeout(() => {
            waitingOverlay.style.display = 'none';
        }, 500);
    }
    
    const betValue = parseFloat(betInput.value);
    if (isNaN(betValue) || betValue < 1) {
        updateStatus('Aposta minima de R$ 1,00', 'warning');
        return;
    }
    if (betValue > balance) {
        updateStatus('Saldo insuficiente para apostar', 'error');
        return;
    }

    balance -= betValue;
    updateBalanceDisplay();
    currentBet = betValue;
    hasCashedOut = false;

    // Carregar probabilidades antes de cada jogada
    await loadProbabilities();

    isPlaying = true;
    startTime = 0;
    currentMultiplier = 1.00;
    targetMultiplier = generateMultiplier();
    curveAnimationProgress = 0;

    console.log('Alvo:', targetMultiplier.toFixed(2) + 'x');

    updateStatus('Voando...', 'flying');
    multiplierDisplay.classList.add('active');
    
    plane.style.transition = 'none';
    plane.style.opacity = '0';
    
    setTimeout(() => {
        plane.classList.add('active');
        plane.style.opacity = '1';
    }, 50);

    betInput.disabled = true;
    betButton.disabled = true;
    betButton.textContent = 'INICIANDO...';
    
    increaseBetBtn.disabled = true;
    decreaseBetBtn.disabled = true;
    
    multiplierDisplay.style.opacity = '0';
    potentialWinEl.classList.remove('active');
    
    playSound(aviatorMusic, true);
    
    showCountdown(() => {
        playSound(partidaSound);
        
        multiplierDisplay.style.opacity = '1';
        potentialWinEl.classList.add('active');
        betButton.disabled = false;
        const initialWin = currentBet * 1.00;
        betButton.textContent = `RETIRAR R$ ${formatCurrency(initialWin)}`;
        betButton.classList.add('cashout');
        requestAnimationFrame(animate);
    });
}

function cashOut() {
    if (!isPlaying || hasCashedOut || isCashingOut || cashoutSoundPlaying) return;
    
    isCashingOut = true;
    hasCashedOut = true;
    cashoutSoundPlaying = true;
    
    const payout = currentBet * currentMultiplier;
    balance += payout;
    updateBalanceDisplay();
    
    // Salvar saldo no servidor
    saveBalanceToServer();
    
    // Salvar histórico da jogada
    saveGameHistory(currentBet, currentMultiplier, payout, 'cashout');
    
    cashoutSound.pause();
    cashoutSound.currentTime = 0;
    cashoutSound.play().catch(() => {});
    
    createConfetti();
    
    gameStatus.style.fontSize = '1.2rem';
    gameStatus.style.fontWeight = '800';
    updateStatus(`${currentMultiplier.toFixed(2)}x - Valor Resgatado: R$ ${formatCurrency(payout)}`, 'success');
    
    setTimeout(() => {
        gameStatus.style.fontSize = '';
        gameStatus.style.fontWeight = '';
    }, 2000);
    
    betButton.textContent = 'RETIRADA';
    betButton.disabled = true;
    betButton.classList.remove('cashout');
    currentBet = 0;
    
    setTimeout(() => {
        isCashingOut = false;
        cashoutSoundPlaying = false;
    }, 2000);
}

// Crash
function crash() {
    isPlaying = false;
    
    // Salvar saldo no servidor (perdeu a aposta)
    saveBalanceToServer();
    
    // Salvar histórico da jogada (perda)
    if (!hasCashedOut && currentBet > 0) {
        saveGameHistory(currentBet, currentMultiplier, 0, 'loss');
    }
    
    stopSound(aviatorMusic);
    playSound(vooSound);
    
    addMultiplierToHistory(currentMultiplier);
    
    if (!hasCashedOut && currentBet > 0) {
        updateStatus(`Voou em ${currentMultiplier.toFixed(2)}x ( -R$ ${formatCurrency(currentBet)} )`, 'error');
        currentBet = 0;
    }
    
    plane.style.transition = 'all 1s ease-out';
    const x = parseFloat(plane.style.left) || 0;
    const y = parseFloat(plane.style.top) || 0;
    plane.style.left = `${x + 200}px`;
    plane.style.top = `${y - 200}px`;
    plane.style.opacity = '0';
    
    let blinks = 0;
    const interval = setInterval(() => {
        multiplierDisplay.style.opacity = multiplierDisplay.style.opacity === '0' ? '1' : '0';
        if (++blinks > 6) {
            clearInterval(interval);
            multiplierDisplay.style.opacity = '1';
        }
    }, 150);
    
    betButton.disabled = true;
    betButton.classList.remove('cashout');
    betButton.textContent = hasCashedOut ? 'RETIRADA' : 'VOOU!';
    betInput.disabled = true;
    
    setTimeout(reset, 2500);
}

// Reset
function reset() {
    currentMultiplier = 1.00;
    startTime = 0;
    curveAnimationProgress = 0;
    stripeOffset = 0;
    
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    drawBackground();
    
    updateStatus('Aguardando...', 'neutral');
    
    multiplierDisplay.classList.remove('active');
    multiplierDisplay.textContent = '1.00x';
    multiplierDisplay.style.opacity = '1';
    
    potentialWinEl.classList.remove('active');
    potentialWinEl.textContent = 'Multiplicador: R$ 0,00';
    
    plane.classList.remove('active');
    plane.style.transition = 'none';
    plane.style.opacity = '0';
    plane.style.transform = 'rotate(0deg)';
    plane.style.left = '0px';
    plane.style.top = '0px';
    
    betButton.disabled = false;
    betButton.textContent = 'FAZER APOSTA';
    betButton.classList.remove('cashout');
    betInput.disabled = false;
    increaseBetBtn.disabled = false;
    decreaseBetBtn.disabled = false;
    hasCashedOut = false;
    isCashingOut = false;
    cashoutSoundPlaying = false;
    
    // Mostrar animação de espera com fade in
    const waitingOverlay = document.getElementById('waitingOverlay');
    if (waitingOverlay) {
        waitingOverlay.style.display = 'flex';
        waitingOverlay.classList.remove('hidden');
    }
}

betButton.addEventListener('click', () => {
    if (!isPlaying) {
        placeBet();
    } else if (!hasCashedOut) {
        cashOut();
    }
});

increaseBetBtn.addEventListener('click', () => {
    const currentValue = parseFloat(betInput.value) || 1;
    betInput.value = (currentValue + 1).toFixed(2);
});

decreaseBetBtn.addEventListener('click', () => {
    const currentValue = parseFloat(betInput.value) || 1;
    if (currentValue > 1) {
        betInput.value = (currentValue - 1).toFixed(2);
    }
});

drawBackground();

// Load audio on page load
window.addEventListener('load', () => {
    const allAudios = [aviatorMusic, partidaSound, cashoutSound, vooSound];
    allAudios.forEach(audio => {
        audio.load();
    });
    
    // Carregar probabilidades do painel admin
    loadProbabilities();
    
    // Carregar histórico inicial de multiplicadores
    loadInitialMultiplierHistory();
    
    // Verificar se tem sessão salva
    const savedToken = localStorage.getItem('session_token');
    const savedUserId = localStorage.getItem('user_id');
    
    if (savedToken && savedUserId) {
        sessionToken = savedToken;
        userId = parseInt(savedUserId);
        registerModal.classList.remove('show');
        // Buscar saldo atualizado do servidor
        updateBalanceFromServer();
    }
});

// Atualizar saldo quando voltar para a aba/janela
window.addEventListener('focus', () => {
    if (sessionToken) {
        updateBalanceFromServer();
    }
});
