<?php
session_start();
require_once 'config.php';

// Verificar modo de manutenção
try {
    $stmt = $pdo->query("SELECT setting_value FROM settings WHERE setting_key = 'maintenance_mode'");
    $maintenanceMode = $stmt->fetchColumn();
    if ($maintenanceMode == '1') {
        require_once 'maintenance.php';
        exit;
    }
} catch (Exception $e) {}

// Verificar se o cassino está ativado
$casinoEnabled = true;
try {
    $stmt = $pdo->query("SELECT setting_value FROM settings WHERE setting_key = 'casino_enabled'");
    $result = $stmt->fetchColumn();
    $casinoEnabled = ($result == '1');
    if (!$casinoEnabled) {
        header('Location: ./');
        exit;
    }
} catch (Exception $e) {}

// Verificar se os esportes estão ativados
$sportsEnabled = false;
try {
    $stmt = $pdo->query("SELECT setting_value FROM settings WHERE setting_key = 'sports_enabled'");
    $result = $stmt->fetchColumn();
    $sportsEnabled = ($result == '1');
} catch (Exception $e) {
    $sportsEnabled = false;
}

// Verificar modo de abertura de jogos (0 = modal, 1 = página dedicada)
$gameOpenMode = 0;
try {
    $stmt = $pdo->query("SELECT setting_value FROM settings WHERE setting_key = 'game_open_mode'");
    $result = $stmt->fetchColumn();
    $gameOpenMode = ($result == '1') ? 1 : 0;
} catch (Exception $e) {
    $gameOpenMode = 0;
}

// Verificar login do usuário
$isLoggedIn = isset($_SESSION['user_id']);
$userId = $isLoggedIn ? $_SESSION['user_id'] : null;
$username = '';
$userBalance = 0;

if ($isLoggedIn) {
    try {
        $stmt = $pdo->prepare("SELECT username, balance FROM users WHERE id = ?");
        $stmt->execute([$userId]);
        $user = $stmt->fetch(PDO::FETCH_ASSOC);
        if ($user) {
            $username = $user['username'];
            $userBalance = floatval($user['balance']);
            $_SESSION['username'] = $username;
            $_SESSION['balance'] = $userBalance;
        } else {
            session_destroy();
            $isLoggedIn = false;
        }
    } catch (Exception $e) {
        $userBalance = 0;
    }
}

// Buscar banners ativos
try {
    $stmt = $pdo->prepare("SELECT * FROM banners WHERE status = 'active' AND (section = 'casino' OR section = 'both') ORDER BY position ASC, created_at DESC");
    $stmt->execute();
    $banners = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (Exception $e) {
    $banners = [];
}

// Buscar jogos por provedor - ORDENADOS por sort_order
$gamesByProvider = [];
try {
    $stmt = $pdo->query("SELECT g.*, p.name as provider_name, p.id as provider_id, p.sort_order as provider_order FROM casino_games g LEFT JOIN casino_providers p ON g.provider_id = p.id WHERE g.status = 'active' AND p.status = 'active' ORDER BY p.sort_order ASC, p.name ASC, g.featured DESC, g.sort_order ASC, g.name ASC");
    $allGames = $stmt->fetchAll(PDO::FETCH_ASSOC);
    foreach ($allGames as $game) {
        $providerId = $game['provider_id'];
        $providerName = $game['provider_name'] ?: 'Outros';
        if (!isset($gamesByProvider[$providerId])) {
            $gamesByProvider[$providerId] = ['name' => $providerName, 'games' => []];
        }
        $gamesByProvider[$providerId]['games'][] = $game;
    }
} catch (Exception $e) {}
?>
<!DOCTYPE html>
<html lang="pt-BR">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Cassino - <?php echo SITE_NAME; ?></title>

<!-- Favicons para todos os dispositivos e navegadores -->
<link rel="icon" type="image/png" sizes="32x32" href="assets/logo/dark-logo.png">
<link rel="icon" type="image/png" sizes="16x16" href="assets/logo/dark-logo.png">
<link rel="apple-touch-icon" sizes="180x180" href="assets/logo/dark-logo.png">
<link rel="shortcut icon" type="image/png" href="assets/logo/dark-logo.png">

<?php include 'facebook-pixel-header.php'; ?>
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800&display=swap" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
<link rel="stylesheet" href="mytabbar.css">
<style>
:root{--bg-body:#231F36;--bg-darker:#1A1628;--bg-card:#2A2440;--bg-hover:#3D3560;--bg-input:#1A1628;--text-primary:#fff;--text-white:#fff;--text-secondary:#b1bad3;--text-muted:#b1bad3;--accent-green:#842DF7;--accent-green-hover:#6B24C8;--danger:#ff4454;--warning:#ffbf00;--border-color:#3D3560;--radius-md:8px;--font-main:'Inter',sans-serif}
*{margin:0;padding:0;box-sizing:border-box;-webkit-tap-highlight-color:transparent}
html,body{overflow-x:hidden;width:100%;max-width:100vw}
body{font-family:'Inter',sans-serif;background:var(--bg-body);color:var(--text-white);-webkit-font-smoothing:antialiased;padding-bottom:0;min-height:100vh;display:flex;flex-direction:column}
.main-nav{background:var(--bg-darker);border-bottom:1px solid var(--border-color);position:sticky;top:60px;z-index:100}
.nav-container{max-width:1560px;margin:0 auto;display:flex;padding:0 20px;width:100%}
.nav-link{display:flex;align-items:center;gap:8px;padding:14px 20px;color:var(--text-muted);text-decoration:none;font-size:14px;font-weight:700;border-bottom:2px solid transparent;transition:.2s}
.nav-link:hover{color:var(--text-white);background:rgba(255,255,255,.03)}
.nav-link.active{color:var(--text-white);border-bottom-color:var(--accent-green)}
.nav-link i{font-size:16px}
.banner-carousel-container{position:relative;width:calc(100% - 40px);max-width:1560px;margin:20px auto;overflow:hidden;border-radius:12px;box-shadow:0 4px 15px rgba(0,0,0,.2)}
.banner-carousel{position:relative;width:100%;height:0;padding-bottom:35%;overflow:hidden}
.banner-slide{position:absolute;top:0;left:0;width:100%;height:100%;opacity:0;transition:opacity .8s ease-in-out;pointer-events:none}
.banner-slide.active{opacity:1;pointer-events:auto}
.banner-slide img{width:100%;height:100%;object-fit:cover;display:block}
.banner-slide a{display:block;width:100%;height:100%}
.banner-indicators{position:absolute;bottom:15px;left:50%;transform:translateX(-50%);display:flex;gap:8px;z-index:10}
.banner-indicator{width:10px;height:10px;border-radius:50%;background:rgba(255,255,255,.5);border:none;cursor:pointer;transition:all .3s ease;padding:0}
.banner-indicator:hover{background:rgba(255,255,255,.8);transform:scale(1.2)}
.banner-indicator.active{background:#842DF7;width:30px;border-radius:5px}
.container{max-width:1560px;margin:0 auto;padding:0 20px 40px;width:100%;overflow:hidden;flex:1;min-height:60vh}
.search-bar{background:var(--bg-darker);border-radius:30px;padding:12px 20px;display:flex;align-items:center;gap:12px;margin-top:5px;margin-bottom:24px;border:1px solid transparent}
.search-bar:focus-within{border-color:var(--bg-hover)}
.search-bar i{color:var(--text-muted)}
.search-bar input{flex:1;background:none;border:none;color:var(--text-white);font-size:14px;font-weight:500;outline:none}
.search-bar input::placeholder{color:var(--text-muted)}
.game-section{margin-bottom:40px}
.section-header{display:flex;align-items:center;justify-content:space-between;margin-bottom:15px;padding:0 5px}
.section-title{display:flex;align-items:center;gap:10px;font-size:18px;font-weight:700;color:var(--text-white)}
.section-title i{color:var(--accent-green);font-size:20px}
.game-count{font-size:13px;font-weight:500;color:var(--text-muted);margin-left:5px}
.section-actions{display:flex;align-items:center;gap:10px}
.btn-ver-todos{
    background:var(--bg-card);
    border:1px solid var(--border-color);
    color:var(--text-white);
    padding:8px 16px;
    border-radius:8px;
    font-size:13px;
    font-weight:600;
    cursor:pointer;
    transition:all .2s;
    display:flex;
    align-items:center;
    gap:6px;
}
.btn-ver-todos:hover{
    background:var(--accent-green);
    color:#011e28;
    border-color:var(--accent-green);
    transform:translateY(-2px);
}
.btn-ver-todos i{font-size:12px}
.nav-buttons{display:flex;gap:8px}
.nav-btn{width:36px;height:36px;background:var(--bg-card);border:1px solid var(--border-color);border-radius:8px;color:var(--text-white);cursor:pointer;display:flex;align-items:center;justify-content:center;transition:.2s;font-size:14px}
.nav-btn:hover:not(:disabled){background:var(--bg-hover);border-color:var(--accent-green);color:var(--accent-green)}
.nav-btn:disabled{opacity:.3;cursor:not-allowed}
.games-carousel{position:relative;overflow:hidden}
.games-scroll{display:flex;gap:12px;overflow-x:auto;scroll-behavior:smooth;scrollbar-width:none;-ms-overflow-style:none;padding:5px}
.games-scroll::-webkit-scrollbar{display:none}
.game-card{width:calc((100% - 60px)/6);min-width:calc((100% - 60px)/6);flex-shrink:0;background:var(--bg-card);border-radius:12px;overflow:hidden;cursor:pointer;transition:.2s;position:relative}
.game-card:hover{transform:translateY(-4px)}
.game-card:active{transform:translateY(0)}
.game-image-wrapper{width:100%;padding-bottom:140%;background:#ecf0f1;position:relative;overflow:hidden}
.game-image-wrapper img{position:absolute;top:0;left:0;width:100%;height:100%;object-fit:cover}
.game-image-placeholder{position:absolute;top:50%;left:50%;transform:translate(-50%,-50%);color:#95a5a6;font-size:48px}
.game-overlay{position:absolute;top:0;left:0;right:0;bottom:0;background:linear-gradient(to top,rgba(0,0,0,.9) 0%,rgba(0,0,0,.4) 40%,transparent 70%);display:flex;flex-direction:column;justify-content:flex-end;padding:15px;opacity:0;transition:opacity .2s ease;pointer-events:none}
.game-card:hover .game-overlay{opacity:1}
.game-name{font-size:15px;font-weight:700;color:var(--text-white);margin-bottom:4px;text-shadow:0 2px 8px rgba(0,0,0,.8);overflow:hidden;text-overflow:ellipsis;display:-webkit-box;-webkit-line-clamp:2;-webkit-box-orient:vertical}
.game-provider{font-size:11px;color:var(--text-muted);text-shadow:0 2px 8px rgba(0,0,0,.8);text-transform:uppercase;font-weight:600}
.game-badge{position:absolute;top:10px;right:10px;background:var(--accent-green);color:#011e28;padding:5px 10px;border-radius:6px;font-size:10px;font-weight:800;text-transform:uppercase;box-shadow:0 4px 12px rgba(0,231,1,.4);z-index:1}
.no-games{text-align:center;padding:60px 20px;color:var(--text-muted)}
.game-modal{display:none;position:fixed;top:0;left:0;width:100%;height:100%;background:rgba(0,0,0,.95);z-index:9999}
.game-modal.active{display:flex;align-items:center;justify-content:center}
.modal-content{width:100%;max-width:1200px;height:80vh;background:var(--bg-card);border-radius:12px;overflow:hidden;margin:20px}
.modal-header{background:var(--bg-darker);padding:15px 20px;display:flex;justify-content:space-between;align-items:center;border-bottom:1px solid var(--border-color)}
.modal-title{font-size:16px;font-weight:700;color:var(--text-white)}
.close-btn{background:none;border:none;color:var(--text-muted);font-size:24px;cursor:pointer;width:32px;height:32px;display:flex;align-items:center;justify-content:center;border-radius:4px}
.close-btn:hover{background:var(--bg-card);color:var(--text-white)}
.game-iframe{width:100%;height:calc(100% - 60px);border:none}
.error-modal{display:none;position:fixed;top:0;left:0;width:100%;height:100%;background:rgba(0,0,0,.85);z-index:10000;align-items:center;justify-content:center;animation:fadeIn .3s ease}
.error-modal.active{display:flex}
.error-content{background:var(--bg-card);border-radius:12px;padding:30px;max-width:450px;width:90%;box-shadow:0 20px 60px rgba(0,0,0,.5);animation:slideUp .3s ease;text-align:center}
@keyframes slideUp{from{transform:translateY(50px);opacity:0}to{transform:translateY(0);opacity:1}}
.error-icon{width:70px;height:70px;margin:0 auto 20px;background:rgba(255,68,84,.1);border-radius:50%;display:flex;align-items:center;justify-content:center;border:2px solid #ff4454}
.error-icon i{font-size:32px;color:#ff4454}
.error-title{font-size:20px;font-weight:700;color:var(--text-white);margin-bottom:12px}
.error-message{font-size:14px;color:var(--text-muted);line-height:1.6;margin-bottom:25px;white-space:pre-line}
.error-buttons{display:flex;gap:10px;justify-content:center}
.error-btn{padding:12px 24px;border-radius:6px;font-weight:600;font-size:14px;cursor:pointer;transition:all .2s;border:none;outline:none}
.error-btn-primary{background:var(--accent-green);color:#011e28}
.error-btn-primary:hover{background:var(--accent-hover);transform:translateY(-2px)}
.error-btn-secondary{background:transparent;color:var(--text-muted);border:1px solid var(--border-color)}
.error-btn-secondary:hover{background:var(--bg-darker);color:var(--text-white)}
@keyframes fadeIn{from{opacity:0}to{opacity:1}}
@media (max-width:768px){
body,html{overflow-x:hidden;max-width:100vw}
.banner-carousel-container{margin:15px 0;border-radius:0;width:100%;max-width:100vw}
.banner-carousel{padding-bottom:50%}
.banner-slide img{object-fit:contain}
.banner-indicators{bottom:10px;gap:6px}
.banner-indicator{width:8px;height:8px}
.banner-indicator.active{width:24px}
.nav-container{padding:0 10px}
.game-card{width:calc((100% - 24px)/3);min-width:calc((100% - 24px)/3)}
.game-image-placeholder{font-size:32px}
.section-title{font-size:16px}
.game-count{font-size:12px}
.game-name{font-size:12px}
.game-provider{font-size:9px}
.container{padding:0 10px 20px;max-width:100%}
.modal-content{height:90vh;max-width:100%;border-radius:0;margin:0}
.game-badge{font-size:9px;padding:4px 8px}
.nav-btn{width:32px;height:32px;font-size:12px}
.game-overlay{padding:10px}
.btn-ver-todos{
    padding:6px 12px;
    font-size:11px;
}
.btn-ver-todos i{font-size:10px}
.section-actions{gap:6px}
}
</style>
</head>
<body>
<?php include 'topbar.php'; ?>
<?php include 'gift-alert.php'; ?>

<?php if ($sportsEnabled || $casinoEnabled): ?>
<div class="main-nav">
<div class="nav-container">
<?php if ($sportsEnabled): ?>
<a href="./" class="nav-link"><i class="fas fa-futbol"></i><span>Esportes</span></a>
<?php endif; ?>
<?php if ($casinoEnabled): ?>
<a href="cassino" class="nav-link active"><i class="fas fa-dice"></i><span>Cassino</span></a>
<?php endif; ?>
</div>
</div>
<?php endif; ?>

<?php if (!empty($banners)): ?>
<div class="banner-carousel-container">
<div class="banner-carousel">
<?php foreach ($banners as $index => $banner): ?>
<div class="banner-slide <?php echo $index === 0 ? 'active' : ''; ?>">
<?php if ($banner['link']): ?>
<a href="<?php echo htmlspecialchars($banner['link']); ?>" target="_blank" rel="noopener"><img src="<?php echo htmlspecialchars($banner['image']); ?>" alt="<?php echo htmlspecialchars($banner['title'] ?? 'Banner'); ?>"></a>
<?php else: ?>
<img src="<?php echo htmlspecialchars($banner['image']); ?>" alt="<?php echo htmlspecialchars($banner['title'] ?? 'Banner'); ?>">
<?php endif; ?>
</div>
<?php endforeach; ?>
</div>
<?php if (count($banners) > 1): ?>
<div class="banner-indicators">
<?php foreach ($banners as $index => $banner): ?>
<button class="banner-indicator <?php echo $index === 0 ? 'active' : ''; ?>" onclick="goToSlide(<?php echo $index; ?>)" aria-label="Ir para slide <?php echo $index + 1; ?>"></button>
<?php endforeach; ?>
</div>
<?php endif; ?>
</div>
<?php endif; ?>

<div class="container">
<div class="search-bar"><i class="fas fa-search"></i><input type="text" id="searchInput" placeholder="Buscar jogos..." onkeyup="searchGames()"></div>
<div id="sectionsContainer">
<?php foreach ($gamesByProvider as $providerId => $provider): ?>
<div class="game-section" data-provider="<?php echo $providerId; ?>">
<div class="section-header">
<div class="section-title">
<i class="fas fa-gamepad"></i>
<span><?php echo htmlspecialchars($provider['name']); ?></span>
<span class="game-count">(<?php echo count($provider['games']); ?>)</span>
</div>
<div class="section-actions">
<button class="btn-ver-todos" onclick="abrirModalVerTodos(<?php echo $providerId; ?>, '<?php echo htmlspecialchars($provider['name'], ENT_QUOTES); ?>')">
<i class="fas fa-th"></i>
Ver Todos
</button>
<div class="nav-buttons">
<button class="nav-btn" onclick="scrollCarousel(<?php echo $providerId; ?>, 'left')"><i class="fas fa-chevron-left"></i></button>
<button class="nav-btn" onclick="scrollCarousel(<?php echo $providerId; ?>, 'right')"><i class="fas fa-chevron-right"></i></button>
</div>
</div>
</div>
<div class="games-carousel">
<div class="games-scroll" id="carousel-<?php echo $providerId; ?>">
<?php foreach ($provider['games'] as $game): ?>
<div class="game-card" onclick="launchGame('<?php echo $game['game_code']; ?>', '<?php echo $game['provider_code']; ?>', <?php echo $game['is_original']; ?>, '<?php echo htmlspecialchars($game['name']); ?>')">
<?php if ($game['featured']): ?><span class="game-badge">Novo</span><?php endif; ?>
<div class="game-image-wrapper">
<?php if ($game['image']): ?>
<img src="<?php echo htmlspecialchars($game['image']); ?>" alt="<?php echo htmlspecialchars($game['name']); ?>" loading="lazy" onerror="this.style.display='none'; this.nextElementSibling.style.display='block';"><i class="fas fa-gamepad game-image-placeholder" style="display: none;"></i>
<?php else: ?>
<i class="fas fa-gamepad game-image-placeholder"></i>
<?php endif; ?>
</div>
<div class="game-overlay">
<div class="game-name"><?php echo htmlspecialchars($game['name']); ?></div>
<div class="game-provider"><?php echo htmlspecialchars($provider['name']); ?></div>
</div>
</div>
<?php endforeach; ?>
</div>
</div>
</div>
<?php endforeach; ?>
</div>
<?php if (empty($gamesByProvider)): ?>
<div class="no-games"><i class="fas fa-gamepad" style="font-size: 48px; opacity: 0.5; margin-bottom: 20px;"></i><p style="font-size: 16px; font-weight: 600;">Nenhum jogo disponível no momento</p></div>
<?php endif; ?>
</div>

<div class="game-modal" id="gameModal">
<div class="modal-content">
<div class="modal-header"><div class="modal-title" id="modalTitle">Carregando...</div><button class="close-btn" onclick="closeGame()"><i class="fas fa-times"></i></button></div>
<iframe id="gameIframe" class="game-iframe" allow="autoplay; fullscreen"></iframe>
</div>
</div>

<div class="error-modal" id="errorModal">
<div class="error-content">
<div class="error-icon"><i class="fas fa-exclamation-triangle"></i></div>
<div class="error-title" id="errorTitle">Ops! Algo deu errado</div>
<div class="error-message" id="errorMessage">Ocorreu um erro ao processar sua solicitação.</div>
<div class="error-buttons"><button class="error-btn error-btn-primary" onclick="closeErrorModal()"><i class="fas fa-check"></i> Entendi</button></div>
</div>
</div>

<?php include 'user-login.php'; ?>
<?php include 'free-spins-modal.php'; ?>
<?php include 'ver-todos.php'; ?>
<?php include 'footer.php'; ?>

<script>
// ===== REMOVER CONFIRMAÇÃO DE SAÍDA =====
window.onbeforeunload = null;
Object.defineProperty(window, 'onbeforeunload', {
    set: function(value) {},
    get: function() { return null; }
});

const isLoggedIn = <?php echo $isLoggedIn ? 'true' : 'false'; ?>;
let userBalance = <?php echo $isLoggedIn ? $userBalance : 0; ?>;
const gameOpenMode = <?php echo $gameOpenMode; ?>;

function showErrorModal(title, message){const modal=document.getElementById('errorModal');const titleEl=document.getElementById('errorTitle');const messageEl=document.getElementById('errorMessage');const buttonsEl=document.querySelector('.error-buttons');titleEl.textContent=title;messageEl.textContent=message;buttonsEl.innerHTML='<button class="error-btn error-btn-primary" onclick="closeErrorModal()"><i class="fas fa-check"></i> Entendi</button>';modal.classList.add('active');document.body.style.overflow='hidden'}

function showErrorModalWithButton(title, message, buttonText, buttonUrl){const modal=document.getElementById('errorModal');const titleEl=document.getElementById('errorTitle');const messageEl=document.getElementById('errorMessage');const buttonsEl=document.querySelector('.error-buttons');titleEl.textContent=title;messageEl.textContent=message;buttonsEl.innerHTML='<button class="error-btn error-btn-secondary" onclick="closeErrorModal()"><i class="fas fa-times"></i> Fechar</button><button class="error-btn error-btn-primary" onclick="window.open(\''+buttonUrl+'\', \'_blank\')"><i class="fas fa-external-link-alt"></i> '+buttonText+'</button>';modal.classList.add('active');document.body.style.overflow='hidden'}

function closeErrorModal(){const modal=document.getElementById('errorModal');modal.classList.remove('active');document.body.style.overflow=''}
document.addEventListener('click',function(e){const modal=document.getElementById('errorModal');if(e.target===modal){closeErrorModal()}});

let currentSlide=0;let totalSlides=<?php echo count($banners); ?>;let autoPlayInterval;
function goToSlide(index){if(index<0)index=totalSlides-1;if(index>=totalSlides)index=0;document.querySelectorAll('.banner-slide').forEach(slide=>{slide.classList.remove('active')});document.querySelectorAll('.banner-indicator').forEach(indicator=>{indicator.classList.remove('active')});document.querySelectorAll('.banner-slide')[index].classList.add('active');document.querySelectorAll('.banner-indicator')[index].classList.add('active');currentSlide=index;resetAutoPlay()}
function nextSlide(){goToSlide(currentSlide+1)}
function startAutoPlay(){if(totalSlides>1){autoPlayInterval=setInterval(nextSlide,5000)}}
function resetAutoPlay(){clearInterval(autoPlayInterval);startAutoPlay()}
document.addEventListener('DOMContentLoaded',function(){startAutoPlay();document.querySelectorAll('.banner-slide').forEach((slide,index)=>{slide.addEventListener('click',function(e){if(!this.querySelector('a')){e.preventDefault();nextSlide()}})})});

const carouselContainer=document.querySelector('.banner-carousel-container');if(carouselContainer){carouselContainer.addEventListener('mouseenter',function(){clearInterval(autoPlayInterval)});carouselContainer.addEventListener('mouseleave',function(){startAutoPlay()})}

function openModal(modalId){const modal=document.getElementById(modalId);if(modal){modal.classList.add('active');document.body.style.overflow='hidden'}}
function closeModal(modalId){const modal=document.getElementById(modalId);if(modal){modal.classList.remove('active');document.body.style.overflow=''}}

function scrollCarousel(providerId,direction){const carousel=document.getElementById('carousel-'+providerId);if(!carousel)return;const scrollAmount=carousel.offsetWidth;const currentScroll=carousel.scrollLeft;if(direction==='left'){carousel.scrollLeft=currentScroll-scrollAmount}else{carousel.scrollLeft=currentScroll+scrollAmount}}

async function launchGame(gameCode,providerCode,isOriginal,gameName){
    if(!isLoggedIn){
        console.log('Usuário não logado - abrindo modal de login');
        openModal('loginModal');
        return;
    }
    
    if(gameOpenMode === 1){
        try {
            const response = await fetch('api/get-game-id.php?code=' + gameCode + '&provider=' + providerCode);
            const data = await response.json();
            if(data.success && data.game_id){
                window.location.href = 'jogo?id=' + data.game_id;
                return;
            }
        } catch(error) {
            console.error('Erro ao buscar ID do jogo:', error);
        }
    }
    
    const modal=document.getElementById('gameModal');
    const iframe=document.getElementById('gameIframe');
    const title=document.getElementById('modalTitle');
    
    title.textContent='Carregando '+gameName+'...';
    modal.classList.add('active');
    document.body.style.overflow='hidden';
    iframe.src='';
    
    try{
        const response=await fetch('api/casino-launch.php',{
            method:'POST',
            headers:{'Content-Type':'application/json'},
            body:JSON.stringify({
                game_code:gameCode,
                provider:providerCode,
                game_original:isOriginal===1
            })
        });
        const data=await response.json();
        
        if(data.success){
            iframe.src=data.launch_url;
            title.textContent=gameName;
            
            const giftAlert=document.getElementById('giftAlert');
            if(giftAlert){
                giftAlert.style.display='none';
            }
            
            if(typeof fbq!=='undefined'){
                fbq('track','ViewContent',{
                    content_name:gameName,
                    content_category:'Casino Game',
                    content_type:'game',
                    content_ids:[gameCode],
                    provider:providerCode
                });
            }
        }else{
            if(data.message&&data.message.includes('IP não autorizado')){
                const checkIpUrl = window.location.origin+'/api/check-ip.php';
                showErrorModalWithButton(
                    'IP não autorizado',
                    'O IP do seu servidor não está autorizado na PlayFivers.\n\nClique no botão abaixo para descobrir seu IP e depois adicione na whitelist do painel da PlayFivers.',
                    'Descobrir Meu IP',
                    checkIpUrl
                );
            }else if(data.message&&(data.message.includes('422')||data.message.includes('saldo')||data.message.includes('Saldo')||data.message.includes('insuficiente'))){
                showErrorModal('Provedor em Manutenção','Este provedor está temporariamente indisponível.\n\nTente outro jogo ou volte mais tarde.');
            }else{
                showErrorModal('Erro ao Carregar',data.message||'Não foi possível carregar o jogo. Tente novamente.');
            }
            closeGame();
        }
    }catch(error){
        console.error('Erro ao lançar jogo:',error);
        showErrorModal('Erro de Conexão','Não foi possível conectar ao servidor.\n\nVerifique sua internet e tente novamente.');
        closeGame();
    }
}

function closeGame(){
    window.onbeforeunload = null;
    
    const modal=document.getElementById('gameModal');
    const iframe=document.getElementById('gameIframe');
    
    iframe.src='about:blank';
    modal.classList.remove('active');
    document.body.style.overflow='';
    
    setTimeout(() => {
        iframe.src='';
    }, 100);
    
    if(isLoggedIn){
        fetch('api/get-balance.php').then(r=>r.json()).then(d=>{
            if(d.success){
                userBalance=parseFloat(d.balance);
                if(typeof updateHeaderBalance==='function'){
                    updateHeaderBalance();
                }
            }
        }).catch(err=>console.error('Erro ao atualizar saldo:',err));
        
        if(typeof checkGiftAlert==='function'){
            checkGiftAlert();
        }
    }
}

document.addEventListener('DOMContentLoaded',function(){document.querySelectorAll('.game-card').forEach(card=>{card.addEventListener('click',function(e){if(!isLoggedIn){e.stopPropagation();e.preventDefault();console.log('Click interceptado - abrindo login');openModal('loginModal');return false}},true)})});

function searchGames(){const searchTerm=document.getElementById('searchInput').value.toLowerCase();const sections=document.querySelectorAll('.game-section');sections.forEach(section=>{const cards=section.querySelectorAll('.game-card');let hasVisible=false;cards.forEach(card=>{const gameName=card.querySelector('.game-name')?.textContent.toLowerCase()||'';const gameProvider=card.querySelector('.game-provider')?.textContent.toLowerCase()||'';const gameAlt=card.querySelector('img')?.alt.toLowerCase()||'';if(searchTerm===''||gameName.includes(searchTerm)||gameProvider.includes(searchTerm)||gameAlt.includes(searchTerm)){card.style.display='';hasVisible=true}else{card.style.display='none'}});section.style.display=hasVisible?'':'none'})}

document.addEventListener('keydown',function(e){if(e.key==='Escape')closeGame()});

function checkCasinoRollover(){if(!isLoggedIn)return;fetch('api/casino-rollover-check.php',{method:'POST'}).then(r=>r.json()).then(data=>{if(data.success){if(data.contribution){console.log('🎰 Rollover Cassino atualizado:',{aposta_detectada:'R$ '+data.bet_detected.toFixed(2),contribuicao:'R$ '+data.contribution.toFixed(2),falta:'R$ '+data.rollover_pending.toFixed(2)});if(typeof updateHeaderBalance==='function'){updateHeaderBalance()}if(data.completed){showErrorModal('Rollover Completo!','Parabéns! Você completou o rollover.\n\nVocê já pode fazer saques!')}}}}).catch(err=>console.error('Erro ao checar rollover:',err))}
if(isLoggedIn){setInterval(checkCasinoRollover,5000);checkCasinoRollover()}
</script>

<?php include 'tabbar.php'; ?>
</body>
</html>