<?php
// loteria.php
session_start();
$page_title = "Pokemon Relics - Loteria";

require 'includes/conexao.php';
require 'includes/header.php';
require 'includes/gacha_engine.php';

// VERIFICAÇÃO DE LOGIN
if (!isset($_SESSION['account_id'])) {
    echo "
    <div class='container my-5 text-center' style='padding-top: 100px;'>
        <div class='card bg-dark text-white border-secondary p-5 shadow-lg'>
            <i class='fas fa-lock fa-4x text-warning mb-3'></i>
            <h2>Acesso Restrito</h2>
            <p class='text-white-50'>Você precisa estar logado para acessar a Loteria e tentar a sorte.</p>
            <a href='login.php' class='btn btn-primary fw-bold mt-2'><i class='fas fa-sign-in-alt me-2'></i>Fazer Login</a>
        </div>
    </div>";
    include 'includes/footer.php';
    exit;
}

$accountID = $_SESSION['account_id'];

// --- CONFIGURAÇÃO DE PAGINAÇÃO ---
$limit = 8; // Itens por página
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$offset = ($page - 1) * $limit;

// --- CARREGAR DADOS ---
$configStmt = $pdo->query("SELECT * FROM gacha_config WHERE id = 1");
$config = $configStmt->fetch(PDO::FETCH_ASSOC);
if (!$config) { die("<div class='container text-white pt-5'>Erro: Configuração da Loteria não encontrada.</div>"); }

$currentSeasonID = $config['current_season_id'];
$seasonStmt = $pdo->prepare("SELECT name FROM gacha_seasons WHERE id = ?");
$seasonStmt->execute([$currentSeasonID]);
$seasonData = $seasonStmt->fetch();
$seasonName = $seasonData['name'] ?? 'Temporada Padrão';

// Itens para o Guia
$allItems = $pdo->query("SELECT id, item_name, item_id, count, image_url, probability, rarity, description FROM gacha_items ORDER BY rarity DESC, probability DESC")->fetchAll(PDO::FETCH_ASSOC);
$itemMap = array_column($allItems, 'image_url', 'item_id');

// Personagens
$chars = $pdo->prepare("SELECT id, name, level FROM players WHERE account_id = ? ORDER BY level DESC");
$chars->execute([$accountID]);
$myChars = $chars->fetchAll(PDO::FETCH_ASSOC);

// PPS
$stmt = $pdo->prepare("SELECT post_points FROM accounts WHERE id = ?");
$stmt->execute([$accountID]);
$myPoints = $stmt->fetchColumn();

// --- FUNÇÃO PARA PEGAR CORES (DEVE ESTAR EM gacha_engine.php ou similar, mas é simulada aqui para o HTML)
if (!function_exists('getRarityColor')) {
    function getRarityColor($rarity) {
        switch ($rarity) {
            case 'Mitica': return ['#ef4444', 'bg-danger'];
            case 'Lendaria': return ['#eab308', 'bg-warning text-dark'];
            case 'Epica': return ['#a855f7', 'bg-purple']; // Usando bg-purple para Epica
            case 'Rara': return ['#3b82f6', 'bg-primary'];
            case 'Incomum': return ['#22c55e', 'bg-success'];
            default: return ['#475569', 'bg-secondary'];
        }
    }
}

// --- HISTÓRICO DE GANHOS DO JOGADOR (PAGINADO) ---
$sqlHistory = "
    SELECT
        h.item_name,
        h.rarity,
        h.drop_time,
        h.delivery_status,
        h.item_id,
        h.item_count
    FROM gacha_history h
    WHERE h.account_id = ?
    ORDER BY h.drop_time DESC
    LIMIT $limit OFFSET $offset";
$historyStmt = $pdo->prepare($sqlHistory);
$historyStmt->execute([$accountID]);
$history = $historyStmt->fetchAll(PDO::FETCH_ASSOC);

// Contagem total para paginação do histórico
$totalHistoryStmt = $pdo->prepare("SELECT COUNT(*) FROM gacha_history WHERE account_id = ?");
$totalHistoryStmt->execute([$accountID]);
$totalHistory = $totalHistoryStmt->fetchColumn();
$totalPages = ceil($totalHistory / $limit);

// Ranking (MANTIDO)
$sqlRank = "SELECT player_name, COUNT(*) as total_wins,
             SUM(CASE WHEN rarity = 'Mitica' THEN 1 ELSE 0 END) as miticas,
             SUM(CASE WHEN rarity = 'Lendaria' THEN 1 ELSE 0 END) as lendarias
             FROM gacha_history
             WHERE season_id = ? AND rarity IN ('Epica', 'Lendaria', 'Mitica')
             GROUP BY player_name
             ORDER BY total_wins DESC, miticas DESC LIMIT 10";
$rankStmt = $pdo->prepare($sqlRank);
$rankStmt->execute([$currentSeasonID]);
$ranking = $rankStmt->fetchAll(PDO::FETCH_ASSOC);
?>

<style>
    /* --- DESIGN DARK BLUE LOTERIA --- */
    .gacha-hero {
        background: linear-gradient(180deg, #0f172a 0%, #1e293b 100%);
        padding: 50px 0;
        border-bottom: 1px solid rgba(255,255,255,0.05);
        /* Ajuste para respeitar o header */
        margin-top: 0; 
        padding-top: 80px; 
        box-shadow: 0 10px 30px -10px rgba(0,0,0,0.5);
    }
    
    /* Z-INDEX para o Dropdown do Header (Corrigir corte) */
    .dropdown-menu {
        z-index: 1050 !important; 
    }

    .gacha-card {
        background: #1e293b;
        border: 1px solid rgba(255,255,255,0.1);
        border-radius: 16px;
        padding: 25px;
        box-shadow: 0 10px 30px rgba(0,0,0,0.3);
        height: 100%;
    }

    .season-tag {
        background: rgba(245, 158, 11, 0.15);
        color: #fbbf24;
        border: 1px solid rgba(245, 158, 11, 0.3);
        padding: 6px 16px;
        border-radius: 30px;
        font-weight: 700;
        font-size: 0.9rem;
        letter-spacing: 1px;
        text-transform: uppercase;
        display: inline-flex;
        align-items: center;
    }

    /* Roleta */
    .wheel-container {
        position: relative;
        width: 100%;
        height: 150px;
        background: #0f172a;
        border: 3px solid #3b82f6;
        border-radius: 14px;
        overflow: hidden;
        box-shadow: inset 0 0 40px rgba(0,0,0,0.9), 0 0 20px rgba(59, 130, 246, 0.2);
        margin-bottom: 30px;
    }
    
    .wheel-pointer {
        position: absolute;
        top: 0; left: 50%;
        transform: translateX(-50%);
        width: 4px; height: 100%;
        background: #ef4444;
        z-index: 10;
        box-shadow: 0 0 15px #ef4444;
    }
    
    .wheel-strip {
        display: flex;
        height: 100%;
        width: max-content;
        will-change: transform;
    }
    
    .wheel-item {
        width: 120px;
        height: 100%;
        border-right: 1px solid rgba(255,255,255,0.05);
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        background: linear-gradient(180deg, #1e293b 0%, #0f172a 100%);
        padding: 12px;
        position: relative;
    }
    .wheel-item img { width: 60px; height: 60px; object-fit: contain; margin-bottom: 10px; filter: drop-shadow(0 4px 6px rgba(0,0,0,0.4)); transition: transform 0.2s; }
    .wheel-item:hover img { transform: scale(1.1); }
    .wheel-item span { font-size: 0.75rem; color: #fff; text-align: center; line-height: 1.2; font-weight: 600; text-shadow: 0 1px 2px rgba(0,0,0,0.5); }
    
    /* Botões de Giro */
    .btn-spin {
        border: none;
        color: white;
        font-weight: 800;
        text-transform: uppercase;
        padding: 18px;
        border-radius: 14px;
        transition: all 0.2s;
        width: 100%;
        position: relative;
        overflow: hidden;
        text-shadow: 0 1px 2px rgba(0,0,0,0.3);
    }
    .btn-spin:hover { transform: translateY(-3px); filter: brightness(1.1); }
    .btn-spin:active { transform: scale(0.98) translateY(0); }
    .btn-spin small { font-weight: 500; opacity: 0.9; font-size: 0.8rem; display: block; margin-top: 4px; color: #fff; }
    
    .btn-1x { background: linear-gradient(135deg, #3b82f6, #1d4ed8); box-shadow: 0 6px 0 #1e40af; }
    .btn-5x { background: linear-gradient(135deg, #8b5cf6, #6d28d9); box-shadow: 0 6px 0 #5b21b6; }
    .btn-10x { background: linear-gradient(135deg, #f59e0b, #b45309); box-shadow: 0 6px 0 #92400e; }

    /* Loot Display */
    .loot-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(100px, 1fr)); gap: 15px; margin-top: 25px; }
    .loot-box {
        background: #0f172a;
        border: 2px solid rgba(255,255,255,0.1);
        border-radius: 12px;
        padding: 15px 10px;
        text-align: center;
        animation: popUp 0.5s cubic-bezier(0.34, 1.56, 0.64, 1);
        box-shadow: 0 5px 15px rgba(0,0,0,0.2);
        transition: transform 0.2s;
    }
    .loot-box:hover { transform: translateY(-5px); }
    @keyframes popUp { from { transform: scale(0.5); opacity: 0; } to { transform: scale(1); opacity: 1; } }

    /* Inputs */
    .form-select-dark {
        background-color: #0f172a;
        border: 2px solid rgba(255,255,255,0.15);
        color: white;
        font-weight: 500;
        border-radius: 10px;
    }
    .form-select-dark:focus { background-color: #0f172a; color: white; border-color: #3b82f6; box-shadow: 0 0 0 4px rgba(59, 130, 246, 0.2); }

    /* Modal de Regras/Histórico (Fundo Escuro) */
    .modal-dark .modal-content { 
        background-color: #1e293b !important; 
        border: 1px solid rgba(255,255,255,0.1); 
        color: #ffffff !important; 
    }
    /* Garante que o corpo do modal, mesmo com scroll, tenha fundo escuro */
    .modal-dark .modal-body {
        background-color: #1e293b !important; 
        color: #ffffff !important;
    }
    .modal-dark .modal-header, .modal-dark .modal-footer { 
        border-color: rgba(255,255,255,0.1); 
        color: #ffffff !important;
    }
    .modal-dark .modal-title, .modal-dark .modal-body h4 {
        color: #ffffff !important;
    }
    .modal-dark .modal-body p, 
    .modal-dark .modal-body ul li, 
    .modal-dark .modal-body .text-white-50 {
        color: rgba(255, 255, 255, 0.8) !important; 
    }
    .modal-dark .btn-close { filter: invert(1); }
    
    /* Novo estilo para o modal de prêmios */
    .prize-item-thumb { width: 40px; height: 40px; object-fit: contain; margin-right: 15px; }
    .bg-purple { background-color: #a855f7 !important; }
    
    /* CORREÇÃO VISUAL GERAL */
    .gacha-card { color: #ffffff !important; }
    .text-white-50, .text-light-50 { color: rgba(255, 255, 255, 0.7) !important; }
    
    /* Histórico de Itens */
    .history-item {
        border-bottom: 1px dashed rgba(255, 255, 255, 0.1);
        padding-bottom: 10px;
        margin-bottom: 10px;
        display: flex;
        align-items: center;
    }
    .history-item:last-child { border-bottom: none; }
    .history-item img { width: 30px; height: 30px; object-fit: contain; margin-right: 10px; }
    .delivery-badge { font-size: 0.7rem; padding: 4px 8px; }
    
    /* Paginação Customizada */
    .pagination-dark .page-item .page-link {
        background-color: #0f172a;
        color: #fff;
        border: 1px solid rgba(255,255,255,0.1);
    }
    .pagination-dark .page-item.active .page-link {
        background-color: #3b82f6;
        border-color: #3b82f6;
        color: #fff;
    }
    .pagination-dark .page-item .page-link:hover {
        background-color: #1e293b;
        color: #fff;
    }
</style>

<div class="gacha-hero text-center">
    <div class="container">
        <span class="season-tag mb-4"><i class="fas fa-calendar-alt me-2"></i> <?php echo htmlspecialchars($seasonName); ?></span>
        <h1 class="display-4 fw-bold text-white mb-3" style="font-family: 'Rajdhani', sans-serif; letter-spacing: 2px;">SISTEMA DE LOTERIA</h1>
        <p class="text-white-50 fs-5 mb-5 max-w-600 mx-auto">Gire a roleta e conte com a sorte para obter itens raros, lendários e místicos!</p>
        
        <div class="d-inline-flex flex-wrap justify-content-center align-items-center gap-3 bg-dark bg-opacity-50 px-4 py-3 rounded-pill border border-primary border-opacity-25 shadow-sm">
            <div class="d-flex align-items-center me-3">
                <span class="text-white-50 me-2">Seus PPS:</span>
                <span class="text-warning fw-bold fs-4" id="displayPoints">
                    <i class="fas fa-coins me-1"></i><?php echo number_format($myPoints, 0, ',', '.'); ?>
                </span>
            </div>
            <a href="donate.php" class="btn btn-success rounded-pill fw-bold px-4 hover-lift shadow-sm">
                <i class="fas fa-plus-circle me-2"></i>Comprar PPS
            </a>
            <button class="btn btn-outline-light rounded-pill px-4 hover-lift" data-bs-toggle="modal" data-bs-target="#rulesModal">
                <i class="fas fa-book-open me-2"></i>Guia & Regras
            </button>
        </div>
    </div>
</div>

<div class="container my-5 pb-5">
    <div class="row g-5">
        
        <div class="col-lg-4 order-lg-0">
             <div class="gacha-card mb-4">
                 <h4 class="fw-bold text-white border-bottom border-secondary pb-3 mb-4 d-flex align-items-center">
                     <i class="fas fa-trophy text-warning me-3 fa-lg"></i> Top Sortudos (Temporada Atual)
                 </h4>
                 
                 <?php if(empty($ranking)): ?>
                     <div class="text-center py-3">
                         <i class="fas fa-ghost fa-2x text-white-50 mb-3"></i>
                         <p class="text-white-50 fw-bold small m-0">Nenhum ganhador de item raro registrado ainda.</p>
                     </div>
                 <?php else: ?>
                     <div class="d-flex flex-column gap-3">
                     <?php $pos = 1; foreach($ranking as $r): ?>
                         <?php 
                             $rankBg = 'bg-dark'; $rankBorder = 'border-secondary'; $medal = '';
                             if($pos === 1) { $rankBg = 'bg-warning bg-opacity-10'; $rankBorder = 'border-warning'; $medal = '🥇'; }
                             elseif($pos === 2) { $rankBg = 'bg-secondary bg-opacity-10'; $rankBorder = 'border-secondary'; $medal = '🥈'; }
                             elseif($pos === 3) { $rankBg = 'bg-danger bg-opacity-10'; $rankBorder = 'border-danger'; $medal = '🥉'; }
                         ?>
                         <div class="d-flex align-items-center p-3 rounded border <?php echo $rankBg . ' ' . $rankBorder; ?> shadow-sm transition-hover">
                             <div class="fw-bold d-flex align-items-center justify-content-center me-3 fs-4" style="width: 40px;">
                                 <?php echo $medal ?: "#$pos"; ?>
                             </div>
                             <div class="flex-grow-1 overflow-hidden">
                                 <div class="text-white fw-bold text-truncate"><?php echo htmlspecialchars($r['player_name']); ?></div>
                                 <div class="text-white-50 small"><i class="fas fa-gift me-1"></i><?php echo $r['total_wins']; ?> Prêmios Raros</div>
                             </div>
                             <div class="text-end d-flex flex-column gap-1">
                                 <?php if($r['miticas']>0): ?>
                                     <span class="badge bg-danger shadow-sm" title="Itens Míticos"><i class="fas fa-dragon me-1"></i><?php echo $r['miticas']; ?></span>
                                 <?php endif; ?>
                                 <?php if($r['lendarias']>0): ?>
                                     <span class="badge bg-warning text-dark shadow-sm" title="Itens Lendários"><i class="fas fa-crown me-1"></i><?php echo $r['lendarias']; ?></span>
                                 <?php endif; ?>
                             </div>
                         </div>
                     <?php $pos++; endforeach; ?>
                     </div>
                 <?php endif; ?>
             </div>

             <div class="gacha-card d-grid">
                 <button class="btn btn-info fw-bold py-3 hover-lift" data-bs-toggle="modal" data-bs-target="#historyModal">
                     <i class="fas fa-history me-2"></i> Meu Histórico de Sorteios
                 </button>
             </div>
        </div>


        <div class="col-lg-8 order-lg-1">
            <div class="gacha-card">
                
                <div class="mb-4">
                    <label class="text-white fw-bold mb-2 text-uppercase small"><i class="fas fa-user-tag me-2 text-primary"></i>Receber itens no personagem:</label>
                    <?php if(empty($myChars)): ?>
                        <div class="alert alert-warning border-0 d-flex align-items-center">
                            <i class="fas fa-exclamation-triangle me-3 fa-2x"></i>
                            <div><strong>Atenção!</strong> Crie um personagem no jogo primeiro.</div>
                        </div>
                    <?php else: ?>
                    <select id="selectedChar" class="form-select form-select-dark py-3 px-4 fs-5 shadow-sm">
                        <?php foreach($myChars as $char): ?>
                            <option value="<?php echo $char['id']; ?>"><?php echo htmlspecialchars($char['name']); ?> (Lvl <?php echo $char['level']; ?>)</option>
                        <?php endforeach; ?>
                    </select>
                    <?php endif; ?>
                </div>

                <div class="text-center mb-3">
                    <span id="spinStatusText" class="fw-bold text-warning opacity-0 fs-5" style="letter-spacing: 1.5px; text-shadow: 0 0 10px rgba(245, 158, 11, 0.5);">
                        <i class="fas fa-sync fa-spin me-2"></i>PREPARANDO GIRO...
                    </span>
                </div>

                <div class="wheel-container">
                    <div class="wheel-pointer"></div>
                    <div class="wheel-strip" id="wheelStrip">
                        <div class="d-flex w-100 h-100 align-items-center justify-content-center text-white">
                            <div class="text-center">
                                <i class="fas fa-arrow-up fa-3x mb-3 text-primary opacity-50 animate-bounce"></i>
                                <h4 class="fw-bold">Sua sorte começa aqui!</h4>
                                <p class="text-white-50 m-0">Selecione uma opção abaixo para girar.</p>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="row g-3" id="controls">
                    <div class="col-md-4">
                        <button onclick="spin(1, <?php echo $config['opt1_cost']; ?>)" class="btn-spin btn-1x" <?php echo empty($myChars) ? 'disabled' : ''; ?>>
                            <i class="fas fa-dice-one fa-2x mb-2 d-block"></i>
                            <?php echo $config['opt1_amount']; ?> Giro(s)
                            <small><i class="fas fa-coins me-1"></i><?php echo number_format($config['opt1_cost'], 0, ',', '.'); ?> pts</small>
                        </button>
                    </div>
                    <div class="col-md-4">
                        <button onclick="spin(2, <?php echo $config['opt2_cost']; ?>)" class="btn-spin btn-5x" <?php echo empty($myChars) ? 'disabled' : ''; ?>>
                             <i class="fas fa-dice-five fa-2x mb-2 d-block"></i>
                            <?php echo $config['opt2_amount']; ?> Giros
                            <small><i class="fas fa-coins me-1"></i><?php echo number_format($config['opt2_cost'], 0, ',', '.'); ?> pts</small>
                        </button>
                    </div>
                    <div class="col-md-4">
                        <button onclick="spin(3, <?php echo $config['opt3_cost']; ?>)" class="btn-spin btn-10x" <?php echo empty($myChars) ? 'disabled' : ''; ?>>
                             <i class="fas fa-dice d-block fa-2x mb-2"></i>
                            <?php echo $config['opt3_amount']; ?> Giros
                            <small><i class="fas fa-coins me-1"></i><?php echo number_format($config['opt3_cost'], 0, ',', '.'); ?> pts</small>
                        </button>
                    </div>
                </div>

                <div id="msgArea" class="mt-4"></div>
                <div id="lootArea" class="loot-grid"></div>

            </div>
        </div>

    </div>
</div>

<div class="modal fade" id="rulesModal" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered modal-lg">
        <div class="modal-content modal-dark">
            <div class="modal-header">
                <h5 class="modal-title"><i class="fas fa-book-open me-2 text-primary"></i> Guia Completo da Loteria</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                
                <h4 class="text-white fw-bold mb-3 border-bottom border-secondary pb-2"><i class="fas fa-lightbulb me-2 text-warning"></i> Como Funciona o Jogo?</h4>
                <p class="text-white-50">A Loteria (Gacha) é um sistema de sorteio onde você usa PPS (Pontos de Postagem/Doação) para tentar ganhar itens raros, exclusivos ou místicos.</p>
                <ul class="text-white-50 small">
                    <li><i class="fas fa-check text-success me-1"></i> O giro é baseado na probabilidade de cada item (veja a tabela abaixo).</li>
                    <li><i class="fas fa-check text-success me-1"></i> Todos os itens ganhos são automaticamente registrados e enviados para o **personagem selecionado** na tela principal.</li>
                    <li><i class="fas fa-check text-success me-1"></i> A chance de obter itens mais raros é sempre muito baixa, mas é garantida pela porcentagem exibida.</li>
                </ul>
                
                <h4 class="text-warning fw-bold mb-3 mt-4 border-bottom border-secondary pb-2"><i class="fas fa-percentage me-2"></i> Prêmios Disponíveis (Chance por Giro)</h4>
                
                <div class="row row-cols-1 row-cols-sm-2 row-cols-md-3 row-cols-lg-4 g-3">
                    <?php 
                    $currentRarity = '';
                    foreach($allItems as $item): 
                        list($hex, $class) = getRarityColor($item['rarity']);
                    ?>
                    <div class="col">
                        <div class="p-2 border rounded shadow-sm d-flex flex-column align-items-center text-center h-100" style="border-color: <?php echo $hex; ?> !important; background-color: #0f172a;">
                             <img src="<?php echo htmlspecialchars($item['image_url']); ?>" class="prize-item-thumb" onerror="this.src='images/default_item.png'" style="width: 50px; height: 50px; margin-bottom: 5px;">
                            
                            <div class="text-white fw-bold small text-truncate w-100" title="<?php echo htmlspecialchars($item['item_name']); ?> (x<?php echo $item['count']; ?>)"><?php echo htmlspecialchars($item['item_name']); ?> (x<?php echo $item['count']; ?>)</div>
                            
                            <span class="badge <?php echo $class; ?> fw-bold my-1" style="font-size:0.6rem;"><?php echo htmlspecialchars($item['rarity']); ?></span>
                            
                            <div class="text-warning small mt-auto" 
                                data-bs-toggle="tooltip" 
                                data-bs-placement="bottom" 
                                title="<?php echo htmlspecialchars($item['description'] ?? 'Sem descrição.'); ?>">
                                Chance: <strong class="text-white"><?php echo number_format((float)$item['probability'], 4) . '%'; ?></strong>
                            </div>
                        </div>
                    </div>
                    <?php endforeach; ?>
                </div>
            </div>
        </div>
    </div>
</div>

<div class="modal fade" id="historyModal" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered modal-lg">
        <div class="modal-content modal-dark">
            <div class="modal-header">
                <h5 class="modal-title"><i class="fas fa-history me-2 text-info"></i> Meu Histórico de Sorteios</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <?php if(empty($history)): ?>
                    <div class="text-center py-5">
                        <i class="fas fa-box-open fa-3x text-white-50 mb-3"></i>
                        <p class="text-white-50 fw-bold m-0">Nenhum item sorteado ainda.</p>
                    </div>
                <?php else: ?>
                    <div class="d-flex flex-column">
                        <?php foreach($history as $h): ?>
                            <?php
                                list($hex, $class) = getRarityColor($h['rarity']);
                                $image_url = $itemMap[$h['item_id']] ?? 'images/default_item.png';
                                $delivery_icon = '';
                                $delivery_text = '';
                                $delivery_class = '';
                                
                                switch ($h['delivery_status']) {
                                    case 'Delivered':
                                        $delivery_icon = '<i class="fas fa-check-circle me-1"></i>';
                                        $delivery_text = 'Entregue';
                                        $delivery_class = 'bg-success';
                                        break;
                                    case 'Pending':
                                        $delivery_icon = '<i class="fas fa-clock me-1"></i>';
                                        $delivery_text = 'Pendente';
                                        $delivery_class = 'bg-warning text-dark';
                                        break;
                                    case 'Failed':
                                        $delivery_icon = '<i class="fas fa-exclamation-triangle me-1"></i>';
                                        $delivery_text = 'Falha';
                                        $delivery_class = 'bg-danger';
                                        break;
                                    default:
                                        $delivery_icon = '<i class="fas fa-question-circle me-1"></i>';
                                        $delivery_text = 'Desconhecido';
                                        $delivery_class = 'bg-secondary';
                                }

                                $drop_time = date('d/m H:i', strtotime($h['drop_time']));
                            ?>
                            <div class="history-item">
                                <img src="<?php echo htmlspecialchars($image_url); ?>" onerror="this.src='images/default_item.png'">
                                <div class="flex-grow-1">
                                    <div class="fw-bold text-white small" title="<?php echo htmlspecialchars($h['item_name']); ?>"><?php echo htmlspecialchars($h['item_name']); ?> (x<?php echo $h['item_count']; ?>)</div>
                                    <span class="badge <?php echo $class; ?> fw-bold" style="font-size:0.6rem;"><?php echo $h['rarity']; ?></span>
                                    <span class="text-white-50 small ms-2" title="Data do Sorteio"><i class="fas fa-calendar-day me-1"></i><?php echo $drop_time; ?></span>
                                </div>
                                <span class="badge delivery-badge <?php echo $delivery_class; ?>" title="Status de Entrega"><?php echo $delivery_icon . $delivery_text; ?></span>
                            </div>
                        <?php endforeach; ?>
                    </div>
                    
                    <?php if ($totalPages > 1): ?>
                    <nav class="mt-3">
                        <ul class="pagination pagination-sm justify-content-center pagination-dark">
                            <?php if ($page > 1): ?>
                                <li class="page-item"><a class="page-link" href="?page=<?php echo $page - 1; ?>"><i class="fas fa-angle-left"></i></a></li>
                            <?php endif; ?>
                            
                            <?php 
                            $start = max(1, $page - 1);
                            $end = min($totalPages, $page + 1);
                            
                            if ($page == 1) $end = min($totalPages, 3);
                            if ($page == $totalPages) $start = max(1, $totalPages - 2);

                            for ($i = $start; $i <= $end; $i++): ?>
                                <li class="page-item <?php echo ($i == $page) ? 'active' : ''; ?>">
                                    <a class="page-link" href="?page=<?php echo $i; ?>"><?php echo $i; ?></a>
                                </li>
                            <?php endfor; ?>
                            
                            <?php if ($page < $totalPages): ?>
                                <li class="page-item"><a class="page-link" href="?page=<?php echo $page + 1; ?>"><i class="fas fa-angle-right"></i></a></li>
                            <?php endif; ?>
                        </ul>
                    </nav>
                    <?php endif; ?>
                <?php endif; ?>
            </div>
        </div>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script>
    // Inicializa Tooltips do Bootstrap (para os modais)
    document.addEventListener('DOMContentLoaded', function () {
        var tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'));
        var tooltipList = tooltipTriggerList.map(function (tooltipTriggerEl) {
            return new bootstrap.Tooltip(tooltipTriggerEl)
        });
    });

    const allItems = <?php echo json_encode($allItems); ?>;
    const wheelStrip = document.getElementById('wheelStrip');
    const msgArea = document.getElementById('msgArea');
    const lootArea = document.getElementById('lootArea');
    const statusText = document.getElementById('spinStatusText');
    const displayPoints = document.getElementById('displayPoints');
    const selectedCharSelect = document.getElementById('selectedChar');

    // optionIndex: 1, 2 ou 3 (Botões da esquerda para direita)
    function spin(optionIndex, cost) {
        if (!selectedCharSelect) {
             msgArea.innerHTML = `<div class="alert alert-warning bg-warning text-dark border-0 fw-bold"><i class="fas fa-exclamation-triangle me-2"></i>Você precisa criar um personagem primeiro!</div></div>`;
             return;
        }
        const charId = selectedCharSelect.value;
        const currentPointsStr = displayPoints.innerText.replace(/[^\d]/g, '');
        const currentPoints = parseInt(currentPointsStr);

        if(isNaN(currentPoints) || currentPoints < cost) { 
            msgArea.innerHTML = `
                <div class="alert alert-danger bg-danger bg-opacity-25 text-danger border-danger d-flex align-items-center">
                    <i class="fas fa-times-circle me-3 fa-2x"></i>
                    <div>
                        <strong>Saldo insuficiente!</strong>
                        <br>Você precisa de mais PPS. <a href="donate.php" class="alert-link fw-bold">Clique aqui para comprar.</a>
                    </div>
                </div>`; 
            return; 
        }

        toggleUI(true);
        lootArea.innerHTML = ''; 
        msgArea.innerHTML = '';
        statusText.classList.remove('opacity-0');
        statusText.innerHTML = '<i class="fas fa-circle-notch fa-spin me-2"></i>CONECTANDO AO SERVIDOR...';

        fetch('api/gacha_spin.php', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ option_index: optionIndex, char_id: charId })
        })
        .then(res => res.json())
        .then(data => {
            if(data.success) {
                displayPoints.innerHTML = '<i class="fas fa-coins me-1"></i>' + new Intl.NumberFormat('pt-BR').format(data.new_points);
                runSpinSequence(data.results);
            } else {
                msgArea.innerHTML = `<div class="alert alert-danger bg-danger bg-opacity-25 text-danger border-danger fw-bold"><i class="fas fa-exclamation-circle me-2"></i>${data.error}</div>`;
                toggleUI(false);
                statusText.classList.add('opacity-0');
            }
        })
        .catch(err => {
            console.error(err);
            msgArea.innerHTML = `<div class="alert alert-danger bg-danger bg-opacity-25 text-danger border-danger fw-bold"><i class="fas fa-wifi me-2"></i>Erro de conexão. Verifique sua internet e tente novamente.</div>`;
            toggleUI(false);
            statusText.classList.add('opacity-0');
        });
    }

    async function runSpinSequence(prizes) {
        for (let i = 0; i < prizes.length; i++) {
            const prize = prizes[i];
            const remaining = prizes.length - (i + 1);
            
            statusText.innerHTML = `<i class="fas fa-sync fa-spin me-2"></i>SORTEANDO ITEM ${i+1} DE ${prizes.length}...`;
            
            await animateWheel(prize);
            
            addLootItem(prize);
            
            if(remaining > 0) await new Promise(r => setTimeout(r, 400));
        }
        
        statusText.innerHTML = '<span class="text-success fw-bold"><i class="fas fa-check-circle me-2"></i>GIROS CONCLUÍDOS! PARABÉNS!</span>';
        toggleUI(false);
    }

    function animateWheel(targetItem) {
        return new Promise(resolve => {
            // 1. Reset e setup
            wheelStrip.style.transition = 'none';
            wheelStrip.style.transform = 'translateX(0px)';
            
            let html = '';
            const totalSlots = 35; 
            const winnerIndex = 30; 
            const slotWidth = 120; 

            if (allItems.length === 0) {
                 wheelStrip.innerHTML = '<div class="d-flex w-100 h-100 align-items-center justify-content-center text-danger fw-bold">Erro: Nenhum item configurado.</div>';
                 resolve(false);
                 return;
            }
            
            for(let i=0; i < totalSlots; i++) {
                let item = (i === winnerIndex) ? targetItem : allItems[Math.floor(Math.random() * allItems.length)];
                
                let borderC = '#475569';
                if(item.rarity === 'Incomum') borderC = '#22c55e';
                if(item.rarity === 'Rara') borderC = '#3b82f6';
                if(item.rarity === 'Epica') borderC = '#a855f7';
                if(item.rarity === 'Lendaria') borderC = '#eab308';
                if(item.rarity === 'Mitica') borderC = '#ef4444';
                
                html += `
                <div class="wheel-item" style="width: ${slotWidth}px; border-bottom: 4px solid ${borderC}">
                    <img src="${item.image_url}" onerror="this.src='images/default_item.png'" alt="${item.item_name}">
                    <span class="text-truncate w-100 px-1" title="${item.item_name}">${item.item_name}</span>
                </div>`;
            }
            wheelStrip.innerHTML = html;

            void wheelStrip.offsetWidth; 

            // 3. Calcular a posição de parada
            const containerWidth = document.querySelector('.wheel-container').offsetWidth;
            const center = (containerWidth / 2) - (slotWidth / 2);
            const targetPos = -((winnerIndex * slotWidth)) + center;
            const randomOffset = Math.floor(Math.random() * (slotWidth * 0.6)) - (slotWidth * 0.3); 

            // 4. Iniciar Animação
            setTimeout(() => {
                wheelStrip.style.transition = 'transform 4s cubic-bezier(0.1, 0.8, 0.1, 1)'; 
                wheelStrip.style.transform = `translateX(${targetPos + randomOffset}px)`;
            }, 50);

            // 5. Finalizar após a animação (4 segundos)
            setTimeout(() => {
                resolve(true);
            }, 4100); 
        });
    }

    function addLootItem(item) {
        const div = document.createElement('div');
        div.className = 'loot-box';
        
        let borderC = item.color_hex || '#475569'; 
        let badgeClass = item.color_class || 'bg-secondary';
        
        // Simulação de cor de borda
        if(item.rarity === 'Incomum') borderC = '#22c55e';
        if(item.rarity === 'Rara') borderC = '#3b82f6';
        if(item.rarity === 'Epica') borderC = '#a855f7';
        if(item.rarity === 'Lendaria') borderC = '#eab308';
        if(item.rarity === 'Mitica') borderC = '#ef4444';

        // Simulação da classe de cor para o badge
        if(item.rarity === 'Incomum') badgeClass = 'bg-success';
        if(item.rarity === 'Rara') badgeClass = 'bg-primary';
        if(item.rarity === 'Epica') badgeClass = 'bg-purple';
        if(item.rarity === 'Lendaria') badgeClass = 'bg-warning text-dark';
        if(item.rarity === 'Mitica') badgeClass = 'bg-danger';

        div.style.borderColor = borderC;
        div.style.boxShadow = `0 0 15px ${borderC}40`; // Sombra mais sutil

        div.innerHTML = `
            <img src="${item.image_url}" onerror="this.src='images/default_item.png'" style="width:50px; height:50px; object-fit:contain; margin-bottom:8px;" class="animate-bounce-in" data-bs-toggle="tooltip" data-bs-placement="top" title="${item.item_name} (x${item.count}) - ${item.description || 'Sem descrição'}">
            <div class="text-white fw-bold text-truncate mb-2" style="font-size:0.75rem;" title="${item.item_name}">${item.item_name}</div>
            <span class="badge ${badgeClass} fw-bold" style="font-size:0.65rem; letter-spacing: 0.5px;">${item.rarity.toUpperCase()}</span>
        `;
        lootArea.prepend(div); 
        
        // CORREÇÃO: Remove o forçar scroll para baixo
        // lootArea.scrollIntoView({ behavior: 'smooth', block: 'start', inline: 'center' }); 
        
        new bootstrap.Tooltip(div.querySelector('img'));
    }

    function toggleUI(disabled) {
        document.querySelectorAll('.btn-spin').forEach(b => {
            b.disabled = disabled;
            if(disabled) b.classList.add('opacity-50', 'cursor-not-allowed');
            else b.classList.remove('opacity-50', 'cursor-not-allowed');
        });
        if (selectedCharSelect) {
            selectedCharSelect.disabled = disabled;
            if(disabled) selectedCharSelect.classList.add('opacity-50', 'cursor-not-allowed');
            else selectedCharSelect.classList.remove('opacity-50', 'cursor-not-allowed');
        }
    }

    const style = document.createElement('style');
    style.textContent = `
        .animate-bounce { animation: bounce 2s infinite; }
        @keyframes bounce { 0%, 20%, 50%, 80%, 100% { transform: translateY(0); } 40% { transform: translateY(-10px); } 60% { transform: translateY(-5px); } }
        .animate-bounce-in { animation: bounceIn 0.6s; }
        @keyframes bounceIn { 0% { opacity: 0; transform: scale(0.3); } 50% { opacity: 1; transform: scale(1.05); } 70% { transform: scale(0.9); } 100% { transform: scale(1); } }
        .bg-purple { background-color: #a855f7 !important; }
        .text-purple { color: #a855f7 !important; }
        .hover-lift { transition: transform 0.2s; }
        .hover-lift:hover { transform: translateY(-3px); }
        .transition-hover { transition: all 0.2s ease; }
        .transition-hover:hover { transform: translateY(-2px); box-shadow: 0 .5rem 1rem rgba(0,0,0,.15)!important; }
    `;
    document.head.appendChild(style);
</script>

<?php include 'includes/footer.php'; ?>