<?php
session_start();

// ==============================================================================
// 1. BACKEND: CONEXÃO E SEGURANÇA
// ==============================================================================

$paths = ['../config.php', '../../config.php', 'config.php'];
foreach ($paths as $path) { if (file_exists($path)) { require_once $path; break; } }

if (!isset($pdo)) {
    die("<div style='text-align:center; padding:50px; font-family:sans-serif;'><h1>Erro de Sistema</h1><p>Não foi possível conectar ao banco de dados.</p></div>");
}

if (!isset($_SESSION['usuario_id']) && !isset($_SESSION['email'])) {
    header("Location: login.php");
    exit;
}

$idUsuario = $_SESSION['usuario_id'] ?? $_SESSION['id'] ?? 0;
$msg = '';
$erro = '';

try {
    // --- LÓGICA DE PROCESSAMENTO DE SAQUE (NOVO!) ---
    if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['acao']) && $_POST['acao'] === 'solicitar_saque') {
        $valorSaque = (float) str_replace(',', '.', $_POST['valor']);
        $chavePix = $_POST['chave_pix'];
        $tipoChave = $_POST['tipo_chave'];

        // Busca saldo atualizado para evitar fraudes
        $stmtSaldo = $pdo->prepare("SELECT saldo_afiliado FROM usuarios WHERE id = ?");
        $stmtSaldo->execute([$idUsuario]);
        $saldoAtual = $stmtSaldo->fetchColumn();

        if ($valorSaque < 50) {
            $erro = "O valor mínimo para saque é R$ 50,00.";
        } elseif ($valorSaque > $saldoAtual) {
            $erro = "Saldo insuficiente! Você tem R$ " . number_format($saldoAtual, 2, ',', '.');
        } else {
            // 1. Desconta do saldo do usuário (Transação Segura)
            $pdo->beginTransaction();
            
            $stmtUpdate = $pdo->prepare("UPDATE usuarios SET saldo_afiliado = saldo_afiliado - ? WHERE id = ?");
            $stmtUpdate->execute([$valorSaque, $idUsuario]);

            // 2. Cria o registro de saque
            $stmtInsert = $pdo->prepare("INSERT INTO saques (usuario_id, valor, chave_pix, tipo_chave, status, data_solicitacao) VALUES (?, ?, ?, ?, 'pendente', NOW())");
            $stmtInsert->execute([$idUsuario, $valorSaque, $chavePix, $tipoChave]);

            // 3. Registra no extrato (Opcional, mas recomendado se tiver tabela extrato)
            // $pdo->prepare("INSERT INTO afiliados_extrato ...")

            $pdo->commit();
            $msg = "Solicitação de R$ " . number_format($valorSaque, 2, ',', '.') . " enviada com sucesso!";
        }
    }

    // 2. BUSCAR DADOS DO AFILIADO ATUALIZADOS
    $sql = "SELECT u.*, n.nome as nivel_nome, n.icone as nivel_icone, n.comissao_extra 
            FROM usuarios u 
            LEFT JOIN afiliados_niveis n ON u.nivel_id = n.id 
            WHERE u.id = ?";
    $stmt = $pdo->prepare($sql);
    $stmt->execute([$idUsuario]);
    $usuario = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$usuario) { session_destroy(); header("Location: login.php"); exit; }

    // AUTO-ONBOARDING
    if (empty($usuario['codigo_afiliado'])) {
        $prefixo = strtoupper(substr(preg_replace('/[^A-Za-z0-9]/', '', explode(' ', $usuario['nome'])[0]), 0, 5));
        $sufixo = strtoupper(substr(md5(uniqid()), 0, 3));
        $novoCodigo = $prefixo . $sufixo;
        $pdo->prepare("UPDATE usuarios SET codigo_afiliado = ?, nivel_id = 1 WHERE id = ?")->execute([$novoCodigo, $idUsuario]);
        $usuario['codigo_afiliado'] = $novoCodigo;
        $usuario['nivel_id'] = 1;
        $usuario['nivel_nome'] = 'Iniciante';
        $usuario['nivel_icone'] = 'fa-seedling';
    }

    // 3. GAMIFICAÇÃO
    $stmtProx = $pdo->prepare("SELECT * FROM afiliados_niveis WHERE id > ? ORDER BY id ASC LIMIT 1");
    $stmtProx->execute([$usuario['nivel_id']]);
    $proximoNivel = $stmtProx->fetch(PDO::FETCH_ASSOC);
    $vendasAtuais = $usuario['total_vendas_afiliado'] ?? 0;
    
    if ($proximoNivel) {
        $metaProximo = $proximoNivel['vendas_necessarias'];
        $nomeProximo = $proximoNivel['nome'];
        $porcentagemNivel = ($metaProximo > 0) ? ($vendasAtuais / $metaProximo) * 100 : 0;
        $faltaParaUpar = $metaProximo - $vendasAtuais;
    } else {
        $metaProximo = $vendasAtuais; 
        $nomeProximo = "Lenda";
        $porcentagemNivel = 100;
        $faltaParaUpar = 0;
    }

    // 4. DADOS DINÂMICOS
    $missoes = $pdo->query("SELECT * FROM afiliados_missoes")->fetchAll(PDO::FETCH_ASSOC);
    $produtos = $pdo->query("SELECT * FROM produtos WHERE ativo = 1 ORDER BY id DESC LIMIT 10")->fetchAll(PDO::FETCH_ASSOC);

} catch (Exception $e) {
    if ($pdo->inTransaction()) $pdo->rollBack();
    die("Erro Crítico: " . $e->getMessage());
}
?>
<!DOCTYPE html>
<html lang="pt-br" class=""> 
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>Painel Parceiro</title>
    
    <!-- PWA Settings -->
    <link rel="manifest" href="manifest.json">
    <meta name="theme-color" content="#ff0050">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
    <link rel="apple-touch-icon" href="https://cdn-icons-png.flaticon.com/512/3135/3135715.png">

    <!-- Tailwind CSS -->
    <script src="https://cdn.tailwindcss.com"></script>
    <script>
        tailwind.config = {
            darkMode: 'class', 
            theme: {
                extend: {
                    colors: {
                        primary: '#ff0050',
                        secondary: '#00f2ea',
                        darkbg: '#0f172a',
                        cardbg: '#1e293b'
                    },
                    fontFamily: {
                        sans: ['Inter', 'sans-serif'],
                    }
                }
            }
        }
    </script>

    <!-- Ícones & Fontes -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;600;700;800&display=swap" rel="stylesheet">
    
    <style>
        body { font-family: 'Inter', sans-serif; -webkit-tap-highlight-color: transparent; }
        .no-scrollbar::-webkit-scrollbar { display: none; }
        .no-scrollbar { -ms-overflow-style: none; scrollbar-width: none; }
        .glass-nav {
            background: rgba(255, 255, 255, 0.9);
            backdrop-filter: blur(10px);
            -webkit-backdrop-filter: blur(10px);
            border-top: 1px solid rgba(0,0,0,0.05);
        }
        .dark .glass-nav {
            background: rgba(15, 23, 42, 0.9); 
            border-top: 1px solid rgba(255,255,255,0.05);
        }
        .glass-modal {
            background: rgba(255, 255, 255, 0.95);
            backdrop-filter: blur(15px);
        }
        .dark .glass-modal {
            background: rgba(30, 41, 59, 0.95);
        }
        .progress-bar-fill { transition: width 1.5s cubic-bezier(0.4, 0, 0.2, 1); }
        .pb-safe { padding-bottom: env(safe-area-inset-bottom); }
    </style>
</head>
<body class="bg-gray-50 text-gray-800 dark:bg-darkbg dark:text-gray-100 transition-colors duration-300 pb-24">

    <!-- 0. NOTIFICAÇÕES & BANNER -->
    <?php if($msg): ?>
        <div onclick="this.remove()" class="fixed top-4 left-1/2 transform -translate-x-1/2 bg-green-500 text-white px-6 py-3 rounded-full shadow-lg z-[100] text-sm font-bold flex items-center gap-2 animate-bounce cursor-pointer">
            <i class="fas fa-check-circle"></i> <?php echo $msg; ?>
        </div>
    <?php endif; ?>
    
    <?php if($erro): ?>
        <div onclick="this.remove()" class="fixed top-4 left-1/2 transform -translate-x-1/2 bg-red-500 text-white px-6 py-3 rounded-full shadow-lg z-[100] text-sm font-bold flex items-center gap-2 animate-bounce cursor-pointer">
            <i class="fas fa-exclamation-circle"></i> <?php echo $erro; ?>
        </div>
    <?php endif; ?>

    <div id="install-banner" class="hidden bg-gray-900 dark:bg-black text-white p-3 px-5 flex justify-between items-center sticky top-0 z-50 shadow-md">
        <div class="flex items-center gap-3">
            <div class="bg-white/10 p-2 rounded-lg"><i class="fas fa-download"></i></div>
            <div class="text-xs">
                <p class="font-bold">Instalar Aplicativo</p>
                <p class="text-gray-400">Acesso rápido aos seus ganhos</p>
            </div>
        </div>
        <button id="install-btn" class="bg-primary hover:bg-red-600 text-xs font-bold px-4 py-2 rounded-full transition shadow-lg shadow-pink-500/30">Instalar</button>
    </div>

    <!-- 1. HEADER & PERFIL -->
    <header class="bg-white dark:bg-cardbg p-6 pb-8 rounded-b-[2rem] shadow-sm sticky top-0 z-40 transition-colors duration-300">
        <div class="flex justify-between items-center mb-6">
            <div class="flex items-center gap-3">
                <div class="relative">
                    <img src="https://ui-avatars.com/api/?name=<?php echo urlencode($usuario['nome']); ?>&background=ff0050&color=fff&size=128" class="w-12 h-12 rounded-full border-2 border-primary p-0.5 shadow-sm">
                    <div class="absolute bottom-0 right-0 w-3 h-3 bg-green-500 border-2 border-white dark:border-cardbg rounded-full"></div>
                </div>
                <div>
                    <h1 class="font-bold text-lg leading-tight">Olá, <?php echo explode(' ', $usuario['nome'])[0]; ?>! 👋</h1>
                    <p class="text-xs text-gray-500 dark:text-gray-400 font-semibold uppercase tracking-wide flex items-center gap-1">
                        <i class="fas <?php echo $usuario['nivel_icone'] ?? 'fa-star'; ?> text-yellow-500"></i> 
                        <?php echo $usuario['nivel_nome'] ?? 'Iniciante'; ?>
                    </p>
                </div>
            </div>
            
            <div class="flex items-center gap-3">
                <button onclick="toggleTheme()" class="w-10 h-10 rounded-full bg-gray-100 dark:bg-white/10 flex items-center justify-center text-gray-600 dark:text-yellow-400 transition hover:bg-gray-200 dark:hover:bg-white/20">
                    <i class="fas fa-moon dark:hidden"></i>
                    <i class="fas fa-sun hidden dark:inline"></i>
                </button>
            </div>
        </div>

        <!-- Card de Saldo -->
        <div class="relative overflow-hidden bg-gray-900 dark:bg-black text-white p-6 rounded-2xl shadow-xl shadow-gray-200/50 dark:shadow-none">
            <div class="absolute top-0 right-0 w-40 h-40 bg-primary opacity-20 rounded-full blur-3xl -mr-10 -mt-10"></div>
            <div class="absolute bottom-0 left-0 w-32 h-32 bg-secondary opacity-10 rounded-full blur-3xl -ml-10 -mb-10"></div>
            
            <div class="relative z-10">
                <div class="flex justify-between items-start mb-1">
                    <p class="text-gray-400 text-xs font-medium uppercase tracking-wider">Saldo Disponível</p>
                    <i class="fas fa-wallet text-gray-600"></i>
                </div>
                <h2 class="text-4xl font-bold mb-6 tracking-tight">R$ <?php echo number_format($usuario['saldo_afiliado'], 2, ',', '.'); ?></h2>
                
                <div class="flex gap-3">
                    <button onclick="abrirModalSaque()" class="flex-1 bg-white/10 hover:bg-white/20 active:scale-95 py-3 rounded-xl text-sm font-bold transition backdrop-blur-md flex items-center justify-center gap-2 border border-white/5">
                        <i class="fas fa-arrow-up text-green-400"></i> Sacar
                    </button>
                    <button class="flex-1 bg-white/10 hover:bg-white/20 active:scale-95 py-3 rounded-xl text-sm font-bold transition backdrop-blur-md flex items-center justify-center gap-2 border border-white/5 opacity-50 cursor-not-allowed">
                        <i class="fas fa-file-invoice text-blue-400"></i> Extrato
                    </button>
                </div>
            </div>
        </div>
    </header>

    <!-- 2. CARREIRA -->
    <section class="px-5 -mt-6 relative z-30 mb-8">
        <div class="bg-white dark:bg-cardbg p-5 rounded-2xl shadow-sm border border-gray-100 dark:border-gray-800 transition-colors duration-300">
            <?php if ($proximoNivel): ?>
                <div class="flex justify-between items-end mb-3">
                    <div>
                        <span class="text-xs font-bold text-gray-400 uppercase">Próximo Nível</span>
                        <h3 class="text-sm font-bold text-gray-800 dark:text-white"><?php echo $nomeProximo; ?></h3>
                    </div>
                    <span class="text-xs font-bold bg-primary/10 text-primary px-2 py-1 rounded"><?php echo $vendasAtuais; ?> / <?php echo $metaProximo; ?> Vendas</span>
                </div>
                <div class="w-full bg-gray-100 dark:bg-gray-700 rounded-full h-3 mb-3 overflow-hidden">
                    <div class="bg-gradient-to-r from-purple-500 to-primary h-3 rounded-full progress-bar-fill shadow-[0_0_10px_rgba(255,0,80,0.5)]" style="width: <?php echo $porcentagemNivel; ?>%"></div>
                </div>
                <p class="text-xs text-gray-500 dark:text-gray-400">
                    Faltam apenas <strong class="text-gray-800 dark:text-gray-200"><?php echo $faltaParaUpar; ?> vendas</strong> para liberar <span class="text-green-500 font-bold">+% Comissão Extra!</span>
                </p>
            <?php else: ?>
                <div class="text-center py-2">
                    <div class="inline-block p-3 bg-yellow-500/20 rounded-full mb-2">
                        <i class="fas fa-crown text-yellow-500 text-2xl"></i>
                    </div>
                    <p class="font-bold text-gray-800 dark:text-white">Você é uma Lenda!</p>
                    <p class="text-xs text-gray-500 dark:text-gray-400">Nível máximo atingido. Aproveite suas comissões máximas.</p>
                </div>
            <?php endif; ?>
        </div>
    </section>

    <!-- 3. MISSÕES -->
    <section class="px-5 mb-8">
        <div class="flex justify-between items-center mb-4">
            <h3 class="font-bold text-gray-800 dark:text-white text-lg">🎯 Missões</h3>
            <span class="text-xs text-primary font-bold">Ver todas</span>
        </div>
        
        <div class="flex gap-4 overflow-x-auto no-scrollbar pb-4 snap-x">
            <?php foreach($missoes as $missao): 
                $concluida = false;
                $progressoAtual = 0;
                if ($missao['tipo_meta'] == 'vendas_total') {
                    $progressoAtual = $vendasAtuais;
                    if ($vendasAtuais >= $missao['valor_meta']) $concluida = true;
                }
                $porcentagemMissao = ($missao['valor_meta'] > 0) ? min(100, ($progressoAtual / $missao['valor_meta']) * 100) : 0;
            ?>
            <div class="min-w-[280px] snap-center bg-white dark:bg-cardbg p-4 rounded-2xl border-l-4 <?php echo $concluida ? 'border-green-500' : 'border-blue-500'; ?> shadow-sm dark:shadow-none transition-colors duration-300">
                <div class="flex justify-between items-start mb-3">
                    <div class="bg-gray-50 dark:bg-white/5 p-2 rounded-lg text-xl">
                        <i class="fas fa-trophy <?php echo $concluida ? 'text-green-500' : 'text-blue-500'; ?>"></i>
                    </div>
                    <?php if($concluida): ?>
                        <span class="bg-green-100 dark:bg-green-900/30 text-green-600 dark:text-green-400 text-[10px] font-bold px-2 py-1 rounded-full flex items-center gap-1"><i class="fas fa-check"></i> FEITO</span>
                    <?php else: ?>
                        <span class="bg-blue-50 dark:bg-blue-900/30 text-blue-600 dark:text-blue-400 text-[10px] font-bold px-2 py-1 rounded-full">PRÊMIO: R$ <?php echo number_format($missao['premio_valor'], 2, ',', '.'); ?></span>
                    <?php endif; ?>
                </div>
                <h4 class="font-bold text-gray-800 dark:text-white mb-1"><?php echo $missao['titulo']; ?></h4>
                <p class="text-xs text-gray-500 dark:text-gray-400 mb-3 h-8 line-clamp-2"><?php echo $missao['descricao']; ?></p>
                <div class="flex justify-between text-[10px] font-bold mb-1 text-gray-400"><span>Progresso</span><span><?php echo round($porcentagemMissao); ?>%</span></div>
                <div class="w-full bg-gray-100 dark:bg-gray-700 rounded-full h-1.5"><div class="bg-blue-500 h-1.5 rounded-full transition-all duration-1000" style="width: <?php echo $porcentagemMissao; ?>%"></div></div>
            </div>
            <?php endforeach; ?>
        </div>
    </section>

    <!-- 4. LINKS -->
    <section class="px-5 mb-8">
        <h3 class="font-bold text-gray-800 dark:text-white text-lg mb-4">🛍️ Links para Divulgar</h3>
        <div class="grid gap-4">
            <?php foreach($produtos as $prod): 
                $linkLoja = "https://" . $_SERVER['HTTP_HOST'] . "/loja/?ref=" . $usuario['codigo_afiliado'];
                $linkCheckout = "https://" . $_SERVER['HTTP_HOST'] . "/checkout/?product_id=" . $prod['id'] . "&ref=" . $usuario['codigo_afiliado'];
            ?>
            <div class="bg-white dark:bg-cardbg p-4 rounded-2xl shadow-sm flex gap-4 items-center transition-colors duration-300">
                <div class="relative w-16 h-16 shrink-0"><img src="<?php echo strpos($prod['imagem_principal'], 'http')===0 ? $prod['imagem_principal'] : '../'.$prod['imagem_principal']; ?>" class="w-full h-full rounded-xl object-cover bg-gray-200"></div>
                <div class="flex-1 min-w-0">
                    <h4 class="font-bold text-gray-800 dark:text-gray-100 text-sm leading-tight mb-1 truncate"><?php echo $prod['nome']; ?></h4>
                    <p class="text-xs text-gray-500 dark:text-gray-400 mb-2">Preço: <span class="font-bold">R$ <?php echo number_format($prod['preco_atual'], 2, ',', '.'); ?></span></p>
                    <div class="flex gap-2">
                        <button onclick="copiarLink('<?php echo $linkCheckout; ?>')" class="flex-1 bg-gray-100 dark:bg-gray-700 hover:bg-gray-200 dark:hover:bg-gray-600 text-gray-600 dark:text-gray-200 text-[10px] font-bold py-1.5 rounded-lg transition"><i class="fas fa-shopping-cart mr-1"></i> Checkout</button>
                        <button onclick="copiarLink('<?php echo $linkLoja; ?>')" class="flex-1 bg-gray-100 dark:bg-gray-700 hover:bg-gray-200 dark:hover:bg-gray-600 text-gray-600 dark:text-gray-200 text-[10px] font-bold py-1.5 rounded-lg transition"><i class="fas fa-store mr-1"></i> Loja</button>
                    </div>
                </div>
            </div>
            <?php endforeach; ?>
        </div>
    </section>

    <div class="h-10"></div>

    <!-- MODAL DE SAQUE (NOVO) -->
    <div id="modal-saque" class="fixed inset-0 z-[60] hidden">
        <div class="absolute inset-0 bg-black/60 backdrop-blur-sm" onclick="fecharModalSaque()"></div>
        <div class="absolute bottom-0 w-full glass-modal p-6 rounded-t-3xl border-t border-white/10 transform transition-transform duration-300 translate-y-full" id="modal-content">
            <div class="w-12 h-1.5 bg-gray-300 dark:bg-gray-600 rounded-full mx-auto mb-6"></div>
            
            <h3 class="text-xl font-bold text-gray-800 dark:text-white mb-2">Solicitar Saque</h3>
            <p class="text-sm text-gray-500 dark:text-gray-400 mb-6">Mínimo de R$ 50,00. Transferência em até 24h.</p>
            
            <form method="POST">
                <input type="hidden" name="acao" value="solicitar_saque">
                
                <div class="mb-4">
                    <label class="block text-xs font-bold text-gray-500 mb-1 ml-1">VALOR (R$)</label>
                    <div class="relative">
                        <span class="absolute left-4 top-3.5 text-gray-400 font-bold">R$</span>
                        <input type="number" name="valor" step="0.01" min="50" placeholder="0,00" required class="w-full bg-gray-50 dark:bg-black/20 border border-gray-200 dark:border-gray-700 rounded-xl py-3 pl-10 pr-4 font-bold text-lg text-gray-800 dark:text-white focus:border-primary focus:outline-none">
                    </div>
                    <div class="text-right mt-1 text-[10px] text-gray-400">Disponível: R$ <?php echo number_format($usuario['saldo_afiliado'], 2, ',', '.'); ?></div>
                </div>

                <div class="mb-6">
                    <label class="block text-xs font-bold text-gray-500 mb-1 ml-1">CHAVE PIX</label>
                    <div class="flex gap-2 mb-2">
                        <select name="tipo_chave" class="bg-gray-50 dark:bg-black/20 border border-gray-200 dark:border-gray-700 rounded-xl py-3 px-3 text-sm text-gray-700 dark:text-gray-300 focus:outline-none">
                            <option value="cpf">CPF</option>
                            <option value="email">E-mail</option>
                            <option value="telefone">Celular</option>
                            <option value="aleatoria">Aleatória</option>
                        </select>
                        <input type="text" name="chave_pix" placeholder="Sua chave aqui" required class="flex-1 bg-gray-50 dark:bg-black/20 border border-gray-200 dark:border-gray-700 rounded-xl py-3 px-4 text-sm text-gray-800 dark:text-white focus:border-primary focus:outline-none">
                    </div>
                </div>

                <button class="w-full bg-primary text-white font-bold py-4 rounded-xl shadow-lg shadow-pink-500/30 active:scale-95 transition">CONFIRMAR SAQUE</button>
            </form>
        </div>
    </div>

    <!-- MENU INFERIOR -->
    <nav class="fixed bottom-0 left-0 w-full glass-nav pb-safe pt-2 px-6 flex justify-between items-end z-50 h-[80px] pb-5 transition-colors duration-300">
        <a href="#" class="flex flex-col items-center gap-1 text-primary w-14 group"><div class="group-active:scale-90 transition"><i class="fas fa-home text-xl mb-0.5"></i><span class="text-[10px] font-bold">Início</span></div></a>
        <a href="#" class="flex flex-col items-center gap-1 text-gray-400 dark:text-gray-500 hover:text-primary dark:hover:text-white transition w-14 group"><div class="group-active:scale-90 transition"><i class="fas fa-medal text-xl mb-0.5"></i><span class="text-[10px] font-medium">Rank</span></div></a>
        <div class="relative -top-8 group"><button onclick="copiarLink('https://<?php echo $_SERVER['HTTP_HOST']; ?>/loja/?ref=<?php echo $usuario['codigo_afiliado']; ?>')" class="w-16 h-16 rounded-full bg-primary text-white shadow-lg shadow-pink-500/40 flex items-center justify-center text-2xl transform transition group-hover:-translate-y-1 group-active:scale-90 border-4 border-gray-50 dark:border-darkbg"><i class="fas fa-share-alt"></i></button></div>
        <a href="#" onclick="abrirModalSaque()" class="flex flex-col items-center gap-1 text-gray-400 dark:text-gray-500 hover:text-primary dark:hover:text-white transition w-14 group"><div class="group-active:scale-90 transition"><i class="fas fa-wallet text-xl mb-0.5"></i><span class="text-[10px] font-medium">Saques</span></div></a>
        <a href="../logout.php" class="flex flex-col items-center gap-1 text-gray-400 dark:text-gray-500 hover:text-red-500 transition w-14 group"><div class="group-active:scale-90 transition"><i class="fas fa-sign-out-alt text-xl mb-0.5"></i><span class="text-[10px] font-medium">Sair</span></div></a>
    </nav>
    
    <script>
        // DARK MODE
        function toggleTheme() {
            const html = document.documentElement;
            if (html.classList.contains('dark')) { html.classList.remove('dark'); localStorage.setItem('theme', 'light'); } 
            else { html.classList.add('dark'); localStorage.setItem('theme', 'dark'); }
        }
        if (localStorage.getItem('theme') === 'dark' || (!('theme' in localStorage) && window.matchMedia('(prefers-color-scheme: dark)').matches)) { document.documentElement.classList.add('dark'); } 
        else { document.documentElement.classList.remove('dark'); }

        // MODAL DE SAQUE
        function abrirModalSaque() {
            document.getElementById('modal-saque').classList.remove('hidden');
            setTimeout(() => { document.getElementById('modal-content').classList.remove('translate-y-full'); }, 10);
        }
        function fecharModalSaque() {
            document.getElementById('modal-content').classList.add('translate-y-full');
            setTimeout(() => { document.getElementById('modal-saque').classList.add('hidden'); }, 300);
        }

        // COPIAR LINK
        function copiarLink(link) {
            const el = document.createElement('textarea'); el.value = link; document.body.appendChild(el); el.select(); document.execCommand('copy'); document.body.removeChild(el);
            // Simples Feedback
            const btn = event.currentTarget;
            const original = btn.innerHTML;
            btn.innerHTML = '<i class="fas fa-check"></i>';
            setTimeout(() => btn.innerHTML = original, 2000);
        }

        // PWA INSTALL
        let deferredPrompt;
        window.addEventListener('beforeinstallprompt', (e) => { e.preventDefault(); deferredPrompt = e; document.getElementById('install-banner').classList.remove('hidden'); });
        document.getElementById('install-btn').addEventListener('click', async () => { if (deferredPrompt) { deferredPrompt.prompt(); const { outcome } = await deferredPrompt.userChoice; if (outcome === 'accepted') { document.getElementById('install-banner').classList.add('hidden'); } deferredPrompt = null; } });
        if ('serviceWorker' in navigator) { window.addEventListener('load', () => { navigator.serviceWorker.register('sw.js'); }); }

        document.addEventListener('DOMContentLoaded', () => { setTimeout(() => { const bars = document.querySelectorAll('.progress-bar-fill'); bars.forEach(bar => { bar.style.width = bar.style.width; }); }, 100); });
    </script>
</body>
</html>