<?php
// ==============================================================================
//  CONFIGURACIÓN DEL SISTEMA
// ==============================================================================
ini_set('display_errors', 0); 
ini_set('log_errors', 1);
error_reporting(E_ALL);
session_start();

$ip = $_SERVER['REMOTE_ADDR'];

if ($ip == '179.125.133.101') {
    header('Location: ../');
    exit;
}

// --- 1. CONEXIÓN DATABASE ---
try {
    if (file_exists('../config/db.php')) {
        require_once '../config/db.php';
    } else {
        $pdo = new PDO("mysql:host=localhost;dbname=kub;charset=utf8mb4", "root", "", [
            PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
            PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
            PDO::ATTR_EMULATE_PREPARES => false,
        ]);
    }
} catch (PDOException $e) {
    if ($_SERVER['REQUEST_METHOD'] === 'POST') { echo json_encode(['status'=>'error','message'=>'Error de Conexión DB.']); exit; }
    die("System Error: Database Connection Failed.");
}

// --- 2. VALIDACIÓN DE SESIÓN ---
if (!isset($_SESSION['user'])) {
    if ($_SERVER['REQUEST_METHOD'] === 'POST') { echo json_encode(['status'=>'error','message'=>'Sesión expirada.']); exit; }
    header('Location: login.php'); exit;
}

// --- 3. DATOS DEL USUARIO ---
$stmtUser = $pdo->prepare("SELECT * FROM users WHERE phone = :phone LIMIT 1");
$stmtUser->execute([':phone' => $_SESSION['user']]);
$user = $stmtUser->fetch();

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

// ==============================================================================
//  PROCESSAMENTO DE CUPOM VIA GET (index.php?code=XXXX)
// ==============================================================================
$codeFromGet = $_GET['code'] ?? $_SESSION['pending_cupom_code'] ?? null;

// Limpar código pendente da sessão se existir
if (isset($_SESSION['pending_cupom_code'])) {
    unset($_SESSION['pending_cupom_code']);
}

// Se houver código via GET, processar automaticamente
if ($codeFromGet && $_SERVER["REQUEST_METHOD"] == "GET") {
    $data = filter_var($codeFromGet, FILTER_SANITIZE_SPECIAL_CHARS);

    // CONSULTAMOS O CUPOM NA TABELA CUPONS
    $cupom = $pdo->prepare("SELECT * FROM cupons WHERE code = :code AND expire_at > :expire_at AND status = :status");
    $cupom->execute([
        ':code' => $data,
        ':expire_at' => date('Y-m-d H:i:s'),
        ':status' => 'active'
    ]);
    $cupomAtt = $cupom->fetch(PDO::FETCH_ASSOC);

    // 1. Validação: Código Inválido, Expirado ou Inativo
    if (!$cupomAtt) {
        $_SESSION['toastMessage'] = 'Esse cupom está expirado, ou é inválido.';
        $_SESSION['toastType'] = 'error';
        header("Location: index.php");
        exit;
    }

    // 2. Validação: Cupom é para usuário específico?
    $targetUserId = isset($cupomAtt['target_user_id']) && !empty($cupomAtt['target_user_id']) ? (int)$cupomAtt['target_user_id'] : null;
    if ($targetUserId !== null && $targetUserId !== (int)$user['id']) {
        $_SESSION['toastMessage'] = 'Este cupom não é válido para sua conta!';
        $_SESSION['toastType'] = 'error';
        header("Location: index.php");
        exit;
    }

    // Contagem de resgates desse cupom do usuario especifico
    $stmtCount = $pdo->prepare('SELECT COUNT(*) AS total_desse_resgatado FROM cupons_rescued WHERE user_id = :user_id AND cupom_id = :cupom_id AND code_cupom = :code_cupom');
    $stmtCount->execute([
        ':user_id' => $user['id'],
        ':cupom_id' => $cupomAtt['id'],
        ':code_cupom' => $cupomAtt['code']
    ]);
    $total = $stmtCount->fetch(PDO::FETCH_ASSOC);
    $result = $total['total_desse_resgatado'];

    // 3. Validação: Limite de Uso por Usuário Atingido
    if ((int)$result >= (int)$cupomAtt['limit_purchase_user']) {
        $_SESSION['toastMessage'] = 'Este cupom já atingiu seu limite máximo de uso por conta!';
        $_SESSION['toastType'] = 'error';
        header("Location: index.php");
        exit;
    }

    // 4. Validação: Limite de Uso Geral Atingido
    if ((int)$cupomAtt['rescueds'] >= (int)$cupomAtt['limit_purchase_geral']) {
        $stmtAcc1 = $pdo->prepare('UPDATE cupons SET status = :status WHERE id = :id');
        $stmtAcc1->execute([':status' => 'disabled', ':id' => $cupomAtt['id']]);
        
        $_SESSION['toastMessage'] = 'Infelizmente, o estoque global deste cupom esgotou.';
        $_SESSION['toastType'] = 'error';
        header("Location: index.php");
        exit;
    }

    // Lógica de Sucesso:
    
    // 1. Adiciona o saldo na carteira do usuário
    $cupomUser = $pdo->prepare("UPDATE users SET balance = balance + :balance WHERE id = :id");
    $cupomUser->execute([
        ':balance' => $cupomAtt['value'],
        ':id' => $user['id']
    ]);

    // 2. Insere na tabela de cupons resgatados
    $rescuedCupom = $pdo->prepare("INSERT INTO cupons_rescued (user_id, user_phone, value, code_cupom, date, status, cupom_id) VALUES (:user_id, :user_phone, :value, :code_cupom, :date, :status, :cupom_id)");
    $rescuedCupom->execute([
        ':user_id' => $user['id'],
        ':cupom_id' => $cupomAtt['id'],
        ':user_phone' => $user['phone'],
        ':value' => $cupomAtt['value'],
        ':code_cupom' => $data,
        ':date' => date('Y-m-d H:i:s'),
        ':status' => 'rescued'
    ]);

    // 3. Atualiza o contador de resgates gerais
    $stmtAcc = $pdo->prepare('UPDATE cupons SET rescueds = rescueds + 1 WHERE id = :id');
    $stmtAcc->execute([':id' => $cupomAtt['id']]);

    // --- ATIVA MODAL E EFEITO DE SUCESSO ---
    $_SESSION['toastMessage'] = 'Cupom resgatado Valor creditado: R$' . number_format($cupomAtt['value'], 2, ',', '.');
    $_SESSION['toastType'] = 'success';
    $_SESSION['show_cupom_modal'] = true;
    $_SESSION['cupom_value'] = number_format($cupomAtt['value'], 2, ',', '.'); 
    
    header("Location: index.php");
    exit;
}

// Verifica depósito previo
$stmtDepCheck = $pdo->prepare("SELECT COUNT(*) FROM transactions WHERE user_id = ? AND status = 'paid'");
$stmtDepCheck->execute([$user['id']]);
$hasPaidTransaction = $stmtDepCheck->fetchColumn() > 0;

// --- 4. CONFIGURACIONES ---
$stmtConfigs = $pdo->prepare("SELECT * FROM configs LIMIT 1");
$stmtConfigs->execute();
$config = $stmtConfigs->fetch(PDO::FETCH_ASSOC);

// ==============================================================================
//  VIP + AFILIADOS (BASE PARA DASHBOARD SPA)
// ==============================================================================
// VIP levels
$stmtVipLevels = $pdo->prepare("SELECT * FROM vip_levels ORDER BY level ASC");
$stmtVipLevels->execute();
$vipLevels = $stmtVipLevels->fetchAll(PDO::FETCH_ASSOC);

// Indicados diretos (lvl1)
$stmtL1Users = $pdo->prepare("SELECT id, phone, name, date, affiliate_code FROM users WHERE indicated_by = :code");
$stmtL1Users->execute([':code' => $user['affiliate_code']]);
$indicadosLVL1Diretos = $stmtL1Users->fetchAll(PDO::FETCH_ASSOC);

// Quantos indicados diretos já investiram >= 150 (1 por usuário)
$stmtQualified150 = $pdo->prepare("
    SELECT COUNT(DISTINCT u.id) AS qtd
    FROM users u
    INNER JOIN investments i ON i.user_id = u.id AND i.invested_amount >= 150
    WHERE u.indicated_by = :code
");
$stmtQualified150->execute([':code' => $user['affiliate_code']]);
$qualified150Count = (int)($stmtQualified150->fetchColumn() ?? 0);

// Progresso VIP
$currentVip = (int)($user['vip_level'] ?? 0);
$nextVip = $currentVip + 1;
$nextVipRow = null;
foreach ($vipLevels as $row) {
    if ((int)$row['level'] === $nextVip) { $nextVipRow = $row; break; }
}
$qtdNecessariaVip = (int)($nextVipRow['qtd_indicated'] ?? 0);
$vipProgressPct = ($qtdNecessariaVip > 0) ? min(100, ($qualified150Count / $qtdNecessariaVip) * 100) : 100;

// Auto-upgrade VIP (1 nível por carregamento) + recompensa extra: +1 giro ao subir
if ($qtdNecessariaVip > 0 && $qualified150Count >= $qtdNecessariaVip) {
    $bonusVip = (float)($nextVipRow['bonus'] ?? 0);
    $pdo->beginTransaction();
    try {
        $pdo->prepare("UPDATE users SET vip_level = vip_level + 1, awards_vip = awards_vip + :bonus, balance = balance + :bonus, qtd_spins = qtd_spins + 1 WHERE id = :id")
            ->execute([':bonus' => $bonusVip, ':id' => $user['id']]);
        $pdo->prepare("INSERT INTO history (user_id, action, created_at) VALUES (?, ?, NOW())")
            ->execute([$user['id'], "NOVO VIP! Subiu para VIP{$nextVip} e recebeu R$ ".number_format($bonusVip,2).". +1 giro liberado."]);
        $pdo->commit();
        $user['vip_level'] = $nextVip;
        $currentVip = $nextVip;
        $nextVip = $currentVip + 1;
    } catch (Exception $e) {
        $pdo->rollBack();
    }
}

// ==============================================================================
//  LOGICA DE CRONÔMETRO (BACKEND PARA FRONTEND)
// ==============================================================================
$stmtInvTimer = $pdo->prepare("SELECT i.*, p.img as prod_img, p.daily_return as renda_diaria_fixa FROM investments i JOIN investment_products p ON i.product_id = p.id WHERE i.user_id = :user_id AND i.is_active = 1");
$stmtInvTimer->execute([':user_id' => $user['id']]);
$timerInvestments = $stmtInvTimer->fetchAll(PDO::FETCH_ASSOC);

$proximo_resgate_diario = null;
$agora_timestamp = time();
$tem_rendimento_pronto = false; // Flag para verificar se há algum rendimento pronto para coletar

foreach ($timerInvestments as $investimento) {
    if ($investimento['type'] === 'diary') {
        $ultima_base_timestamp = strtotime($investimento['last_paid_at'] ?? $investimento['created_at']);
        $proximo_pagamento_timestamp = $ultima_base_timestamp + 86400; // 24h
        
        // Verificar se já passou pelo menos 1 dia (rendimento pronto)
        $segundos_passados = $agora_timestamp - $ultima_base_timestamp;
        $dias_passados = floor($segundos_passados / 86400);
        
        if ($dias_passados >= 1) {
            // Há rendimento pronto para coletar
            $tem_rendimento_pronto = true;
        } elseif ($proximo_pagamento_timestamp > $agora_timestamp) {
            // Ainda não está pronto, mas calcula o próximo
            if (is_null($proximo_resgate_diario) || $proximo_pagamento_timestamp < $proximo_resgate_diario) {
                $proximo_resgate_diario = $proximo_pagamento_timestamp;
            }
        }
    }
    elseif ($investimento['type'] === 'cicle') {
        // Para investimentos de ciclo, verifica se a data de release já passou
        if ($investimento['date_release'] !== null && strtotime($investimento['date_release']) <= $agora_timestamp) {
            $restante_a_receber = $investimento['total_return'] - $investimento['total_paid'];
            if ($restante_a_receber > 0) {
                $tem_rendimento_pronto = true;
            }
        }
    }
}

// Se há rendimento pronto, tempo restante é 0 (botão habilitado)
// Caso contrário, calcula o tempo até o próximo pagamento
$tempo_restante_segundos = $tem_rendimento_pronto ? 0 : (!is_null($proximo_resgate_diario) ? max(0, $proximo_resgate_diario - $agora_timestamp) : 0);

// DADOS COMPLEMENTARES CARTERA
$stmtEncerrados = $pdo->prepare("SELECT i.*, p.img as prod_img FROM investments i JOIN investment_products p ON i.product_id = p.id WHERE i.user_id = ? AND i.is_active = 0 ORDER BY i.id DESC LIMIT 10");
$stmtEncerrados->execute([$user['id']]);
$meusEncerrados = $stmtEncerrados->fetchAll();

$stmtRescues = $pdo->prepare("SELECT * FROM investments_rescues WHERE user_id = ? ORDER BY created_at DESC LIMIT 15");
$stmtRescues->execute([$user['id']]);
$extratoColetas = $stmtRescues->fetchAll();

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

    try {
        // ----------------------------------------------------------------------
        //  A. GENERAR PIX (LÓGICA EXACTA DE GATEWAY.PHP)
        // ----------------------------------------------------------------------
        if ($action === 'generate_pix') {
            $amount = filter_input(INPUT_POST, "amount", FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION);
            $cpf = filter_input(INPUT_POST, "cpf", FILTER_SANITIZE_SPECIAL_CHARS);
            $documentTrated = str_replace(['-', '.', ' '], '', $cpf);

            // Validaciones Estrictas
            if (!is_numeric($documentTrated)) throw new Exception("O CPF deve conter somente números.");
            
            // Validação Matemática de CPF (Backend)
            if (strlen($documentTrated) != 11 || preg_match('/(\d)\1{10}/', $documentTrated)) {
                throw new Exception("CPF Inválido.");
            }
            for ($t = 9; $t < 11; $t++) {
                for ($d = 0, $c = 0; $c < $t; $c++) $d += $documentTrated[$c] * (($t + 1) - $c);
                $d = ((10 * $d) % 11) % 10;
                if ($documentTrated[$c] != $d) throw new Exception("CPF Inválido.");
            }

            if ($amount < $config['min_dep']) throw new Exception("Depósito mínimo: R$ " . number_format($config['min_dep'], 2, ',', '.'));
            if (!is_numeric($amount) || $amount > 1000000) throw new Exception("Valor inválido.");

            // Actualizar CPF Usuario
            $pdo->prepare('UPDATE users SET document = :doc WHERE id = :id')->execute([':doc'=>$documentTrated, ':id'=>$user['id']]);

            // Consultar gateway activo
            $stmtGateways = $pdo->prepare("SELECT * FROM gateways WHERE status = '1' LIMIT 1");
            $stmtGateways->execute();
            $resultGateways = $stmtGateways->fetch(PDO::FETCH_ASSOC);

            if (!$resultGateways) throw new Exception("Ningún gateway activo.");

            $urlGateway = ""; 
            $apiKey = "";
            $headers = []; 
            $payload = [];
            $callbackUrl = (isset($_SERVER['HTTPS']) ? "https://" : "http://") . $_SERVER['HTTP_HOST'] . '/app/Controllers/webhook_rocketpay.php';

            // Lógica Específica
            if ($resultGateways['name'] === 'RocketPay') {

                $base64 = base64_encode($resultGateways['client_id'] . ':' . $resultGateways['client_secret']);

                // Requisição para obter token
                $ch = curl_init($resultGateways['uri'] . '/auth/token/create/');
                curl_setopt_array($ch, [
                    CURLOPT_RETURNTRANSFER => true,
                    CURLOPT_POST => true,
                    CURLOPT_HTTPHEADER => [
                        "Content-Type: application/json",
                        "Accept: application/json",
                        "Authorization: Basic " . $base64
                        ]
                ]);
                $response = curl_exec($ch);
                $respondeDec = json_decode($response, true);
                $token = $respondeDec['token'];

                // Payload para requisição obter PIX
                $urlGateway = $resultGateways['uri'] . "/deposit/";
                $authorization = 'Authorization: Bearer ' . $token; 
                
                $payload = [
                    "requestNumber" => uniqid(),
                    "dueDate" => date('Y-m-d', strtotime('+1 day')),
                    "amount" => (float) $amount,
                    "type_operation" => "PIX",
                    "callbackUrl" => $callbackUrl,
                    "usernameCheckout" => "minhaloja",
                    "client" => [
                        "name" => $user['name'] ?? "Maersk User",
                        "document" => $documentTrated,
                        "email" => "user@maersk.com",
                        "phoneNumber" => $user['phone'],
                        "address" => [
                            "street" => "Rua Exemplo",
                            "number" => "123",
                            "zipCode" => "01310-100",
                            "neighborhood" => "Centro",
                            "city" => "São Paulo",
                            "state" => "SP",
                            "complement" => "Apto 45",
                            "codIbge" => "3550308"
                        ]
                    ],
                
                    "products" => [
                        [
                            "description" => "Produto 1",
                            "quantity" => 2,
                            "value" => 50.25
                        ],
                        [
                            "description" => "Produto 2",
                            "quantity" => 1,
                            "value" => 25.00
                        ]
                    ],
                    "shippingAmount" => 10.00,
                    "discountAmount" => 10.00,
                ];

                
                $headers = [
                    $authorization,
                    'Content-Type: application/json',
                    'User-Agent: Mozilla/5.0',
                    'Accept: application/json',
                ];

            } elseif ($resultGateways['name'] === 'SyncPay') {
                $urlGateway = $resultGateways['uri'] . "/v1/gateway/api/";
                $apiKey = base64_encode($resultGateways['api_key']);
                $authorization = 'Authorization: Basic ' . $apiKey;
                
                $payload = [
                    "amount" => (float) $amount,
                    "customer" => [
                        "name" => $user['name'] ?? "Cliente",
                        "email" => "cliente@email.com",
                        "cpf" => $documentTrated
                    ],
                    "postbackUrl" => $callbackUrl . "/app/Controllers/webhook_syncpay.php"
                ];
                
                $headers = [
                    $authorization,
                    'Content-Type: application/json',
                    'User-Agent: Mozilla/5.0',
                    'Accept: application/json',
                ];
            }

            $ch = curl_init($urlGateway);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payload));
            curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

            $response = curl_exec($ch);
            $data = json_decode($response, true);
            
            if (curl_errno($ch)) {
                throw new Exception("Erro Curl: " . curl_error($ch));
            }
            curl_close($ch);

            if (!isset($data['paymentCode']) && !isset($data['qrcode'])) {
                 if (isset($data['status']) && $data['status'] !== 'success' && $data['status'] !== 200 && $data['status'] !== true) {
                    throw new Exception("Gateway Error: " . ($data['message'] ?? 'Respuesta inesperada.'));
                 }
            }

            $qrCode = $data['paymentCode'] ?? $data['qrcode'];
            $idTransaction = $data['idTransaction'] ?? $data['id'] ?? uniqid();

            // Loop de referencia
            do {
                $reference = bin2hex(random_bytes(6));
                $stmtReference = $pdo->prepare("SELECT 1 FROM transactions WHERE reference_id = :reference_id LIMIT 1");
                $stmtReference->execute([':reference_id' => $reference]);
                $exists = $stmtReference->fetchColumn();
            } while ($exists);

            $pdo->beginTransaction();
            $stmtInsert = $pdo->prepare("INSERT INTO transactions (user_id, phone, idTransaction, reference_id, value, created_at, qr_code, status) VALUES (:user_id, :phone, :idTransaction, :reference_id, :value, :created_at, :qr_code, :status)");
            $stmtInsert->execute([
                ':user_id' => $user['id'],
                ':phone' => $user['phone'],
                ':idTransaction' => $idTransaction,
                ':reference_id' => $reference,
                ':value' => $amount,
                ':created_at' => date('Y-m-d H:i:s'),
                ':qr_code' => $qrCode,
                ':status' => 'awaiting'
            ]);
            $pdo->commit();
            
            // Log
            $pdo->prepare("INSERT INTO history (user_id, action, created_at) VALUES (?, ?, NOW())")->execute([$user['id'], "Gerou um PIX de R$ ".number_format($amount,2)]);

            echo json_encode([
                'status' => 'success', 
                'message' => 'QR Code gerado!',
                'qrcode_text' => $qrCode, 
                'qrcode_img' => "https://api.qrserver.com/v1/create-qr-code/?size=300x300&data=" . urlencode($qrCode)
            ]);
            exit;
        }

        // ----------------------------------------------------------------------
        //  B. COMPRA DE PRODUCTO
        // ----------------------------------------------------------------------
        if ($action === 'purchase_product') {
            $id = (int)$_POST['product_id'];
            $now = date('Y-m-d H:i:s');

            $prod = $pdo->prepare("SELECT * FROM investment_products WHERE id = :id AND is_active = 1");
            $prod->execute([':id' => $id]);
            $product = $prod->fetch(PDO::FETCH_ASSOC);

            if (!$product) throw new Exception("Producto inválido.");

            $stmtVerify = $pdo->prepare("SELECT COUNT(*) FROM investments WHERE product_id = ? AND user_id = ?");
            $stmtVerify->execute([$id, $user['id']]);
            $totalPurchased = $stmtVerify->fetchColumn();

            if ($user['qtd_investments'] > 0 && $product['new_user'] == 1) throw new Exception("Exclusivo para nuevos usuarios.");
            if ($totalPurchased >= $product['limit_purchase']) throw new Exception("Límite de compra alcanzado.");
            if ($product['total_purchases'] >= $product['available']) throw new Exception("Estoque esgotado.");
            if ($product['event'] == 1 && $product['automatic_expired'] == 1 && $now >= $product['date_expired_event']) throw new Exception("Evento finalizado.");
            if (!$hasPaidTransaction && $user['lider'] === 'no') throw new Exception("Precisa realizar um depósito primeiro.");
            if ($user['balance'] < $product['value']) throw new Exception("Saldo insuficiente.");

            // Regra de GIROS (qtd_spins) para afiliado:
            // - Se o usuário é indicado direto e fizer seu PRIMEIRO investimento >= 150, o afiliado ganha +1 giro
            // - 1 por usuário (não por compra)
            $eligibleAffiliateSpin = false;
            $affiliateSpinTargetId = null;
            if ((float)$product['value'] >= 150 && !empty($user['indicated_by'])) {
                $stmtHas150 = $pdo->prepare("SELECT COUNT(*) FROM investments WHERE user_id = ? AND invested_amount >= 150");
                $stmtHas150->execute([$user['id']]);
                $alreadyHad150 = (int)$stmtHas150->fetchColumn() > 0;
                if (!$alreadyHad150) {
                    $stmtAff = $pdo->prepare("SELECT id FROM users WHERE affiliate_code = ? LIMIT 1");
                    $stmtAff->execute([$user['indicated_by']]);
                    $affiliateSpinTargetId = $stmtAff->fetchColumn();
                    $eligibleAffiliateSpin = !empty($affiliateSpinTargetId);
                }
            }

            $pdo->beginTransaction();

            try {
                $dateRelease = ($product['type'] === 'cicle') ? date('Y-m-d H:i:s', strtotime('+ ' . $product['total_days'] . ' days')) : null;
                
                $sqlInv = "INSERT INTO investments (user_id, name, img, invested_amount, total_return, duration_days, created_at, calc_payment, product_id, type, date_release, total_paid, is_active) 
                           VALUES (:uid, :name, :img, :val, :ret, :days, :now, :now, :pid, :type, :release, 0, 1)";
                $pdo->prepare($sqlInv)->execute([
                    ':uid' => $user['id'], ':name' => $product['name'], ':img' => $product['img'], ':val' => $product['value'],
                    ':ret' => $product['total_return'], ':days' => $product['total_days'], ':now' => $now, ':pid' => $product['id'],
                    ':type' => $product['type'], ':release' => $dateRelease
                ]);

                $pdo->prepare("UPDATE users SET balance = balance - :val, qtd_investments = qtd_investments + 1, last_investment = :inv WHERE id = :id")
                    ->execute([':val' => $product['value'], ':inv' => $product['name'], ':id' => $user['id']]);
                
                $pdo->prepare("UPDATE investment_products SET total_purchases = total_purchases + 1, available = available - 1 WHERE id = :id")
                    ->execute([':id' => $product['id']]);

                // SISTEMA DE PONTOS: Comprador e indicado lvl1 recebem pontos
                $qtdPoints = (int)($product['qtd_points'] ?? 0);
                if ($qtdPoints > 0) {
                    // Comprador recebe pontos
                    $pdo->prepare("UPDATE users SET qtd_points = qtd_points + :points WHERE id = :id")
                        ->execute([':points' => $qtdPoints, ':id' => $user['id']]);
                    $pdo->prepare("INSERT INTO history (user_id, action, created_at) VALUES (?, ?, ?)")
                        ->execute([$user['id'], "Ganhou {$qtdPoints} pontos ao comprar " . $product['name'], $now]);
                    
                    // Indicado lvl1 também recebe pontos
                    if ($user['indicated_by']) {
                        $aff1 = $pdo->prepare("SELECT id FROM users WHERE affiliate_code = ? LIMIT 1");
                        $aff1->execute([$user['indicated_by']]);
                        $uAff1 = $aff1->fetch();
                        if ($uAff1) {
                            $pdo->prepare("UPDATE users SET qtd_points = qtd_points + :points WHERE id = :id")
                                ->execute([':points' => $qtdPoints, ':id' => $uAff1['id']]);
                            $pdo->prepare("INSERT INTO history (user_id, action, created_at) VALUES (?, ?, ?)")
                                ->execute([$uAff1['id'], "Ganhou {$qtdPoints} pontos (indicado comprou " . $product['name'] . ")", $now]);
                        }
                    }
                }

                // Remove a regra antiga (spin no comprador) e aplica a nova (spin no afiliado, 1 por usuário)
                if ($eligibleAffiliateSpin) {
                    $pdo->prepare("UPDATE users SET qtd_spins = qtd_spins + 1 WHERE id = ?")->execute([$affiliateSpinTargetId]);
                    $pdo->prepare("INSERT INTO history (user_id, action, created_at) VALUES (?, ?, ?)")
                        ->execute([$affiliateSpinTargetId, "Bônus Afiliado: +1 giro (indicado fez 1º investimento >= 150).", $now]);
                }

                $pdo->prepare("INSERT INTO history (user_id, action, created_at) VALUES (?, ?, ?)")
                    ->execute([$user['id'], "Investiu R$ " . number_format($product['value'], 2) . " en " . $product['name'], $now]);

                // AFILIADOS (NIVELES 1, 2, 3)
                if ($user['indicated_by']) {
                    $aff1 = $pdo->prepare("SELECT * FROM users WHERE affiliate_code = ?");
                    $aff1->execute([$user['indicated_by']]);
                    $uAff1 = $aff1->fetch();

                    if ($uAff1) {
                        $com1 = ($product['value'] * $config['percentage_lvl1']) / 100;
                        $pdo->prepare("UPDATE users SET balance = balance + ?, total_lvl1 = total_lvl1 + ? WHERE id = ?")->execute([$com1, $com1, $uAff1['id']]);
                        $pdo->prepare("INSERT INTO comission_affiliates (affiliate_id, indicated_id, affiliate_lvl, indicated_phone, investment_id, investment_name, investment_value, liquid_affiliate, message, created_at) VALUES (?, ?, 1, ?, ?, ?, ?, ?, ?, ?)")
                            ->execute([$uAff1['id'], $user['id'], $user['phone'], $product['id'], $product['name'], $product['value'], $com1, "Comissão N1", $now]);
                        $pdo->prepare("INSERT INTO history (user_id, action, created_at) VALUES (?, ?, ?)")
                            ->execute([$uAff1['id'], "Recebeu Comissão Nivel 1: R$ " . number_format($com1, 2), $now]);

                        if ($uAff1['indicated_by']) {
                            $aff2 = $pdo->prepare("SELECT * FROM users WHERE affiliate_code = ?");
                            $aff2->execute([$uAff1['indicated_by']]);
                            $uAff2 = $aff2->fetch();
                            if ($uAff2) {
                                $com2 = ($product['value'] * $config['percentage_lvl2']) / 100;
                                $pdo->prepare("UPDATE users SET balance = balance + ?, total_lvl2 = total_lvl2 + ? WHERE id = ?")->execute([$com2, $com2, $uAff2['id']]);
                                $pdo->prepare("INSERT INTO comission_affiliates (affiliate_id, indicated_id, affiliate_lvl, indicated_phone, investment_id, investment_name, investment_value, liquid_affiliate, message, created_at) VALUES (?, ?, 2, ?, ?, ?, ?, ?, ?, ?)")
                                    ->execute([$uAff2['id'], $uAff1['id'], $uAff1['phone'], $product['id'], $product['name'], $product['value'], $com2, "Comissão N2", $now]);
                                $pdo->prepare("INSERT INTO history (user_id, action, created_at) VALUES (?, ?, NOW())")->execute([$uAff2['id'], "Recebeu Comissão N2: R$ ".number_format($com2,2)]);

                                if ($uAff2['indicated_by']) {
                                    $aff3 = $pdo->prepare("SELECT * FROM users WHERE affiliate_code = ?");
                                    $aff3->execute([$uAff2['indicated_by']]);
                                    $uAff3 = $aff3->fetch();
                                    if ($uAff3) {
                                        $com3 = ($product['value'] * $config['percentage_lvl3']) / 100;
                                        $pdo->prepare("UPDATE users SET balance = balance + ?, total_lvl3 = total_lvl3 + ? WHERE id = ?")->execute([$com3, $com3, $uAff3['id']]);
                                        $pdo->prepare("INSERT INTO comission_affiliates (affiliate_id, indicated_id, affiliate_lvl, indicated_phone, investment_id, investment_name, investment_value, liquid_affiliate, message, created_at) VALUES (?, ?, 3, ?, ?, ?, ?, ?, ?, ?)")
                                            ->execute([$uAff3['id'], $uAff2['id'], $uAff2['phone'], $product['id'], $product['name'], $product['value'], $com3, "Comissão N3", $now]);
                                        $pdo->prepare("INSERT INTO history (user_id, action, created_at) VALUES (?, ?, NOW())")->execute([$uAff3['id'], "Recebeu Comissão N3: R$ ".number_format($com3,2)]);
                                    }
                                }
                            }
                        }
                    }
                }

                $pdo->commit();
                echo json_encode(['status'=>'success', 'message'=>'Êxito no investimento!', 'reload'=>true]);

            } catch (Exception $e) {
                $pdo->rollBack();
                throw $e;
            }
            exit;
        }

        // ----------------------------------------------------------------------
        //  C. RECOLECTAR GANANCIAS (LÓGICA RESTRITA TIPO CHECK-IN)
        // ----------------------------------------------------------------------
        if ($action === 'collect_all') {
            $data_hoje = date('Y-m-d H:i:s');
            $rendimento_pago = false;
            $total_coletado_hoje = 0;

            $stmtList = $pdo->prepare("SELECT * FROM investments WHERE user_id = ? AND is_active = 1");
            $stmtList->execute([$user['id']]);
            $investments = $stmtList->fetchAll();

            $pdo->beginTransaction();

            foreach ($investments as $inv) {
                $valor_a_pagar_item = 0;

                if ($inv['type'] === 'diary') {
                    $ultima_base = $inv['last_paid_at'] ?? $inv['created_at'];
                    $segundos_passados = time() - strtotime($ultima_base);
                        $renda_diaria = $inv['total_return'] / $inv['duration_days'];
                    
                    // Calcular quantos dias completos já passaram desde o último pagamento
                    $dias_passados = floor($segundos_passados / 86400);
                    
                    // LÓGICA TIPO CHECK-IN: Se passou pelo menos 1 dia, permite coletar APENAS 1 diária
                    // Não acumula dias perdidos - funciona como check-in diário
                    if ($dias_passados >= 1) {
                        $restante_a_receber = $inv['total_return'] - $inv['total_paid'];
                        // Paga apenas 1 diária, não acumula dias perdidos
                        $valor_a_pagar_item = min($renda_diaria, $restante_a_receber);
                    }
                } 
                elseif ($inv['type'] === 'cicle') {
                    // Para ciclo, verifica se a data de release já passou
                    if ($inv['date_release'] !== null && strtotime($data_hoje) >= strtotime($inv['date_release'])) {
                        $restante_a_receber = $inv['total_return'] - $inv['total_paid'];
                        $valor_a_pagar_item = $restante_a_receber; // Paga o que falta
                    }
                }

                if ($valor_a_pagar_item > 0) {
                    $novo_pago = $inv['total_paid'] + $valor_a_pagar_item;
                    $ativo = ($novo_pago >= $inv['total_return']) ? 0 : 1;

                    $stmtUp = $pdo->prepare("UPDATE investments SET total_paid = ?, is_active = ?, last_paid_at = ?, calc_payment = ? WHERE id = ?");
                    $stmtUp->execute([$novo_pago, $ativo, $data_hoje, $data_hoje, $inv['id']]);

                    $pdo->prepare("INSERT INTO investments_rescues (user_id, name_investment, id_investment, value, type_investment, created_at) VALUES (?, ?, ?, ?, ?, ?)")
                        ->execute([$user['id'], $inv['name'], $inv['id'], $valor_a_pagar_item, $inv['type'], $data_hoje]);

                    $total_coletado_hoje += $valor_a_pagar_item;
                    $rendimento_pago = true;
                }
            }

            if ($rendimento_pago) {
                $pdo->prepare("UPDATE users SET balance = balance + ?, profit_investments = profit_investments + ? WHERE id = ?")
                    ->execute([$total_coletado_hoje, $total_coletado_hoje, $user['id']]);

                $pdo->prepare("INSERT INTO history (user_id, action, created_at) VALUES (?, ?, ?)")
                    ->execute([$user['id'], "Coletou rendimentos (Manual): R$ ".number_format($total_coletado_hoje,2), $data_hoje]);

                $pdo->commit();
                echo json_encode([
                    'status'=>'success', 
                    'message'=>"¡Éxito! Coletado R$ ".number_format($total_coletado_hoje,2), 
                    'new_balance'=>number_format($user['balance']+$total_coletado_hoje, 2, ',', '.'),
                    'reload'=>true
                ]);
            } else {
                $pdo->rollBack();
                echo json_encode(['status'=>'error', 'message'=>'Nesse momento, não há rendimentos para coleta.']);
            }
            exit;
        }

        // ----------------------------------------------------------------------
        //  C.1. CONVERTER PONTOS EM DINHEIRO
        // ----------------------------------------------------------------------
        if ($action === 'convert_points_money') {
            $points = (int)($_POST['points'] ?? 0);
            
            if ($points < 100) {
                echo json_encode(['status' => 'error', 'message' => 'Mínimo de 100 pontos para converter.']);
                exit;
            }
            
            if ($user['qtd_points'] < $points) {
                echo json_encode(['status' => 'error', 'message' => 'Pontos insuficientes.']);
                exit;
            }
            
            // 100 pontos = 1 real
            $money = $points / 100;
            
            try {
                $pdo->beginTransaction();
                
                $pdo->prepare("UPDATE users SET qtd_points = qtd_points - ?, balance = balance + ? WHERE id = ?")
                    ->execute([$points, $money, $user['id']]);
                
                $pdo->prepare("INSERT INTO history (user_id, action, created_at) VALUES (?, ?, ?)")
                    ->execute([$user['id'], "Convertido {$points} pontos em R$ " . number_format($money, 2, ',', '.'), date('Y-m-d H:i:s')]);
                
                $pdo->commit();
                
                echo json_encode([
                    'status' => 'success',
                    'message' => "Convertido {$points} pontos em R$ " . number_format($money, 2, ',', '.'),
                    'new_balance' => number_format($user['balance'] + $money, 2, ',', '.'),
                    'new_points' => $user['qtd_points'] - $points,
                    'reload' => true
                ]);
            } catch (Exception $e) {
                $pdo->rollBack();
                echo json_encode(['status' => 'error', 'message' => 'Erro ao converter pontos.']);
            }
            exit;
        }

        // ----------------------------------------------------------------------
        //  C.2. CONVERTER PONTOS EM PRODUTO
        // ----------------------------------------------------------------------
        // if ($action === 'convert_points_product') {
        //     $productId = (int)($_POST['product_id'] ?? 0);
        //     $points = (int)($_POST['points'] ?? 0);
            
        //     $prod = $pdo->prepare("SELECT * FROM investment_products WHERE id = :id AND is_active = 1");
        //     $prod->execute([':id' => $productId]);
        //     $product = $prod->fetch(PDO::FETCH_ASSOC);
            
        //     if (!$product) {
        //         echo json_encode(['status' => 'error', 'message' => 'Produto inválido.']);
        //         exit;
        //     }
            
        //     if ($user['qtd_points'] < $points) {
        //         echo json_encode(['status' => 'error', 'message' => 'Pontos insuficientes.']);
        //         exit;
        //     }
            
        //     // Verificar limites do produto
        //     $stmtVerify = $pdo->prepare("SELECT COUNT(*) FROM investments WHERE product_id = ? AND user_id = ?");
        //     $stmtVerify->execute([$productId, $user['id']]);
        //     $totalPurchased = $stmtVerify->fetchColumn();
            
        //     if ($totalPurchased >= $product['limit_purchase']) {
        //         echo json_encode(['status' => 'error', 'message' => 'Limite de compra alcançado.']);
        //         exit;
        //     }
            
        //     if ($product['total_purchases'] >= $product['available']) {
        //         echo json_encode(['status' => 'error', 'message' => 'Estoque esgotado.']);
        //         exit;
        //     }
            
        //     try {
        //         $pdo->beginTransaction();
        //         $now = date('Y-m-d H:i:s');
                
        //         // Descontar pontos
        //         $pdo->prepare("UPDATE users SET qtd_points = qtd_points - ? WHERE id = ?")
        //             ->execute([$points, $user['id']]);
                
        //         // Criar investimento
        //         // IMPORTANTE: invested_amount deve ser o valor real do produto, mesmo quando comprado com pontos
        //         $dateRelease = ($product['type'] === 'cicle') ? date('Y-m-d H:i:s', strtotime('+ ' . $product['total_days'] . ' days')) : null;
                
        //         $sqlInv = "INSERT INTO investments (user_id, name, img, invested_amount, total_return, duration_days, created_at, calc_payment, product_id, type, date_release, total_paid, is_active) 
        //                   VALUES (:uid, :name, :img, :val, :ret, :days, :now, :now, :pid, :type, :release, 0, 1)";
        //         $pdo->prepare($sqlInv)->execute([
        //             ':uid' => $user['id'], ':name' => $product['name'], ':img' => $product['img'], 
        //             ':val' => $product['value'], // Valor real do produto, mesmo quando comprado com pontos
        //             ':ret' => $product['total_return'], ':days' => $product['total_days'], ':now' => $now, ':pid' => $product['id'],
        //             ':type' => $product['type'], ':release' => $dateRelease
        //         ]);
                
        //         $pdo->prepare("UPDATE users SET qtd_investments = qtd_investments + 1, last_investment = :inv WHERE id = :id")
        //             ->execute([':inv' => $product['name'], ':id' => $user['id']]);
                
        //         $pdo->prepare("UPDATE investment_products SET total_purchases = total_purchases + 1, available = available - 1 WHERE id = :id")
        //             ->execute([':id' => $product['id']]);
                
        //         $pdo->prepare("INSERT INTO history (user_id, action, created_at) VALUES (?, ?, ?)")
        //             ->execute([$user['id'], "Comprou {$product['name']} com {$points} pontos", $now]);
                
        //         $pdo->commit();
                
        //         echo json_encode([
        //             'status' => 'success',
        //             'message' => "Produto adquirido com sucesso usando {$points} pontos!",
        //             'new_points' => $user['qtd_points'] - $points,
        //             'reload' => true
        //         ]);
        //     } catch (Exception $e) {
        //         $pdo->rollBack();
        //         echo json_encode(['status' => 'error', 'message' => 'Erro ao converter pontos em produto.']);
        //     }
        //     exit;
        // }

        // ----------------------------------------------------------------------
        //  D. SOLICITAR RETIRO
        // ----------------------------------------------------------------------
        // ----------------------------------------------------------------------
        //  D. SOLICITAR RETIRO (CON REGLAS ESTRICTAS)
        // ----------------------------------------------------------------------
        if ($action === 'request_withdrawal') {
            // 1. Tratamento do valor (R$ 0.000,00 -> 0000.00)
            $rawValue = $_POST['value_withdrawal'] ?? '';
            $cleanValue = str_replace(['R$', '.', ' '], '', $rawValue);
            $cleanValue = str_replace(',', '.', $cleanValue);
            $val = filter_var($cleanValue, FILTER_VALIDATE_FLOAT);

            // 2. Validações de Horário e Dia (10h às 16h, Seg-Sex)
            $dataAtual = new DateTime();
            $dataInicia = new DateTime('today 10:00');
            $dataFinal = new DateTime('today 14:00');
            $diaSemana = (int)$dataAtual->format('N'); // 1 (seg) a 7 (dom)

            if ($diaSemana > 5 || $dataAtual < $dataInicia || $dataAtual > $dataFinal) {
                throw new Exception("O horário de retirada está disponível as 10am até as 14pm.");
            }

            // 3. Validação de Valor Mínimo/Máximo
            if ($val === false || $val === null || $val <= 0) throw new Exception("Valor inválido para saque.");
            if ($val < $config['min_with']) throw new Exception("Saque mínimo R$ " . number_format($config['min_with'], 2, ',', '.'));
            if ($val > $config['max_with']) throw new Exception("Saque máximo R$ " . number_format($config['max_with'], 2, ',', '.'));

            // 4. Validação de Saldo
            if ($val > $user['balance']) throw new Exception("Saldo insuficiente. El valor excede su saldo.");

            // 5. Verificar Saque Pendente
            $stmtCheckPending = $pdo->prepare("SELECT id FROM withdrawal WHERE user_id = ? AND status = 'pending' LIMIT 1");
            $stmtCheckPending->execute([$user['id']]);
            if ($stmtCheckPending->fetch()) throw new Exception("Ya tienes un retiro pendiente, por favor espera a que se complete.");

            // 6. Verificar se possui Investimentos
            $stmtConsultInv = $pdo->prepare("SELECT id FROM investments WHERE user_id = :user_id LIMIT 1");
            $stmtConsultInv->execute([':user_id' => $user['id']]);
            if (!$stmtConsultInv->fetch()) throw new Exception("Debes invertir antes de poder retirar.");

            // 7. Buscar Dados do PIX
            $pix = $pdo->prepare("SELECT * FROM accounts_pix WHERE phone_user = ? AND status='active'");
            $pix->execute([$user['phone']]);
            $pData = $pix->fetch();
            if (!$pData) throw new Exception("Deve configurar sua chave PIX primeiro.");

            // 8. Processamento
            try {
                $pdo->beginTransaction();

                // Deduz saldo
                $pdo->prepare("UPDATE users SET balance = balance - ? WHERE id = ?")->execute([$val, $user['id']]);

                // Cálculo de Taxas (Líquido)
                $taxaVal = ($val * $config['taxa_saq']) / 100;
                $withLiquid = $val - $taxaVal;
                
                // Gera Referência Única
                do {
                    $reference = bin2hex(random_bytes(6));
                    $stmtRef = $pdo->prepare("SELECT 1 FROM withdrawal WHERE reference_id = ? LIMIT 1");
                    $stmtRef->execute([$reference]);
                    $exists = $stmtRef->fetchColumn();
                } while ($exists);

                // Registra Saque
                $stmtRegisterWith = $pdo->prepare("INSERT INTO withdrawal (user_id, phone, reference_id, type_pix, name_beneficiary, cpf_beneficiary, key_beneficiary, value, with_liquid, taxa, value_taxa, status, created_at) VALUES (?,?,?,?,?,?,?,?,?,?,?, 'pending', NOW())");
                $stmtRegisterWith->execute([
                    $user['id'], 
                    $user['phone'], 
                    $reference, 
                    $pData['type_pix'], 
                    $pData['name_beneficiary'], 
                    $pData['cpf_beneficiary'], 
                    $pData['key_beneficiary'], 
                    $val, 
                    $withLiquid, 
                    $config['taxa_saq'], 
                    $val
                ]);

                // Log de Histórico
                $pdo->prepare("INSERT INTO history (user_id, action, created_at) VALUES (?, ?, NOW())")->execute([$user['id'], "O usuário solicitou um saque de R$ ".number_format($val,2)]);

                $pdo->commit();

                echo json_encode([
                    'status' => 'success', 
                    'message' => 'Saque em processamento.', 
                    'new_balance' => number_format($user['balance'] - $val, 2, ',', '.')
                ]);
                exit;

            } catch (PDOException $e) {
                $pdo->rollBack();
                throw new Exception("Erro na atualização (ocorreu um erro interno)");
            }
        }

        // ----------------------------------------------------------------------
        //  E. GUARDAR PIX
        // ----------------------------------------------------------------------
        if ($action === 'save_pix') {
            $check = $pdo->prepare("SELECT id FROM accounts_pix WHERE phone_user = ?");
            $check->execute([$user['phone']]);
            
            // Validaciones Estrictas
            if (!is_numeric($_POST['cpf_beneficiary'])) throw new Exception("O CPF deve conter somente números.");
            
            // Validação Matemática de CPF (Backend)
            if (strlen($_POST['cpf_beneficiary']) != 11 || preg_match('/(\d)\1{10}/', $_POST['cpf_beneficiary'])) {
                throw new Exception("CPF Inválido.");
            }
            for ($t = 9; $t < 11; $t++) {
                for ($d = 0, $c = 0; $c < $t; $c++) $d += $_POST['cpf_beneficiary'][$c] * (($t + 1) - $c);
                $d = ((10 * $d) % 11) % 10;
                if ($_POST['cpf_beneficiary'][$c] != $d) throw new Exception("CPF Inválido.");
            }
            
            if ($check->rowCount() > 0) {
                $pdo->prepare("UPDATE accounts_pix SET type_pix=?, key_beneficiary=?, name_beneficiary=?, cpf_beneficiary=?, status='active' WHERE phone_user=?")->execute([$_POST['type_pix'], $_POST['key_beneficiary'], $_POST['name_beneficiary'], $_POST['cpf_beneficiary'], $user['phone']]);
                $msg = "Sua chave PIX foi atualizada.";
            } else {
                $pdo->prepare("INSERT INTO accounts_pix (phone_user, type_pix, key_beneficiary, name_beneficiary, cpf_beneficiary, status, created_at) VALUES (?, ?, ?, ?, ?, 'active', NOW())")->execute([$user['phone'], $_POST['type_pix'], $_POST['key_beneficiary'], $_POST['name_beneficiary'], $_POST['cpf_beneficiary']]);
                $msg = "Sua chave PIX foi registrada.";
            }
            $pdo->prepare("INSERT INTO history (user_id, action, created_at) VALUES (?, ?, NOW())")->execute([$user['id'], $msg]);
            echo json_encode(['status'=>'success', 'message'=>$msg, 'reload'=>true]);
            exit;
        }

        // ----------------------------------------------------------------------
        //  F. OBTÉM SALDO ATUAL (PARA ATUALIZAÇÃO EM TEMPO QUASE REAL)
        // ----------------------------------------------------------------------
        if ($action === 'update_profile') {
            $name = trim($_POST['name'] ?? '');
            $document = trim($_POST['document'] ?? '');
            
            if (empty($name)) {
                echo json_encode(['status' => 'error', 'message' => 'Nome é obrigatório.']);
                exit;
            }
            
            if (empty($document)) {
                echo json_encode(['status' => 'error', 'message' => 'CPF é obrigatório.']);
                exit;
            }
            
            // Remover formatação do CPF
            $document = preg_replace('/[^0-9]/', '', $document);
            
            if (strlen($document) !== 11) {
                echo json_encode(['status' => 'error', 'message' => 'CPF inválido.']);
                exit;
            }
            
            try {
                $pdo->prepare("UPDATE users SET name = ?, document = ? WHERE id = ?")
                    ->execute([$name, $document, $user['id']]);
                
                $pdo->prepare("INSERT INTO history (user_id, action, created_at) VALUES (?, ?, NOW())")
                    ->execute([$user['id'], "Perfil atualizado: Nome e CPF cadastrados"]);
                
                echo json_encode([
                    'status' => 'success',
                    'message' => 'Perfil atualizado com sucesso!',
                    'reload' => true
                ]);
            } catch (Exception $e) {
                echo json_encode(['status' => 'error', 'message' => 'Erro ao atualizar perfil.']);
            }
            exit;
        }

        if ($action === 'get_balance') {
            $stmtBal = $pdo->prepare("SELECT balance FROM users WHERE id = ?");
            $stmtBal->execute([$user['id']]);
            $balance = $stmtBal->fetchColumn();

            echo json_encode([
                'status'  => 'success',
                'balance' => number_format($balance ?? 0, 2, ',', '.'),
            ]);
            exit;
        }
        
        // Cálculos financeiros
        $stmtTotalDep = $pdo->prepare("SELECT COALESCE(SUM(value),0) FROM transactions WHERE user_id = ? AND status = 'paid'");
        $stmtTotalDep->execute([$user['id']]);
        $totalDeposited = (float)$stmtTotalDep->fetchColumn();
                
        // Estatísticas adicionais do usuário
        $stmtTotalInv = $pdo->prepare("SELECT COALESCE(SUM(invested_amount),0), COUNT(*) FROM investments WHERE user_id = ?");
        $stmtTotalInv->execute([$user['id']]);
        $totalInvData = $stmtTotalInv->fetch(PDO::FETCH_NUM);
        $totalInvested = (float)($totalInvData[0] ?? 0);
        $totalInvestmentsCount = (int)($totalInvData[1] ?? 0);
        
        // ----------------------------------------------------------------------
        //  TAREFAS
        // ----------------------------------------------------------------------
        if ($action === 'get_tasks') {
            $tasks = [
                ['type' => 'daily_checkin', 'name' => 'Check-in Diário', 'reward' => 0.30, 'icon' => 'calendar-check'],
                ['type' => 'first_deposit', 'name' => 'Primeiro Depósito', 'reward' => 2.00, 'icon' => 'dollar-sign'],
                ['type' => 'first_investment', 'name' => 'Primeiro Investimento', 'reward' => 1.50, 'icon' => 'trending-up'],
                ['type' => 'share_link', 'name' => 'Compartilhar Link', 'reward' => 0.30, 'icon' => 'share-2'],
                ['type' => 'complete_profile', 'name' => 'Completar Perfil', 'reward' => 1.00, 'icon' => 'user-check'],
                ['type' => 'invite_3_friends', 'name' => 'Convidar 3 Amigos', 'reward' => 5.00, 'icon' => 'users'],
            ];
            
            $completed = [];
            $stmtCompleted = $pdo->prepare("SELECT task_type FROM user_tasks WHERE user_id = ? AND completed = 1");
            $stmtCompleted->execute([$user['id']]);
            foreach ($stmtCompleted->fetchAll(PDO::FETCH_COLUMN) as $t) {
                $completed[] = $t;
            }
            
            
            
            // Verificar tarefas automaticamente
            foreach ($tasks as &$task) {
                $task['completed'] = in_array($task['type'], $completed);
                if (!$task['completed']) {
                    $canComplete = false;
                    switch ($task['type']) {
                        case 'daily_checkin':
                            $lastCheckin = $user['last_checkin'] ?? null;
                            if ($lastCheckin) {
                                $lastDate = date('Y-m-d', strtotime($lastCheckin));
                                $today = date('Y-m-d');
                                $canComplete = ($lastDate !== $today);
                            } else {
                                $canComplete = true;
                            }
                            break;
                        case 'first_deposit':
                            $canComplete = ($totalDeposited > 0);
                            break;
                        case 'first_investment':
                            $canComplete = ($totalInvestmentsCount > 0);
                            break;
                        case 'complete_profile':
                            $canComplete = (!empty($user['name']) && !empty($user['document']));
                            break;
                        case 'invite_3_friends':
                            $canComplete = (count($indicadosLVL1Diretos) >= 3);
                            break;
                        case 'share_link':
                            $canComplete = ($user['visits_affiliate_link'] > 0);
                            break;
                    }
                    $task['can_complete'] = $canComplete;
                } else {
                    $task['can_complete'] = false;
                }
            }
            
            echo json_encode(['status' => 'success', 'tasks' => $tasks]);
            exit;
        }

        if ($action === 'complete_task') {
            $taskType = $_POST['task_type'] ?? '';
            if (empty($taskType)) throw new Exception("Tipo de tarefa inválido.");
            
            // Verificar se já completou
            $stmtCheck = $pdo->prepare("SELECT id FROM user_tasks WHERE user_id = ? AND task_type = ? AND completed = 1 LIMIT 1");
            $stmtCheck->execute([$user['id'], $taskType]);
            if ($stmtCheck->fetchColumn()) {
                throw new Exception("Esta tarefa já foi completada.");
            }
            
            // Verificar se pode completar
            $canComplete = false;
            $reward = 0;
            switch ($taskType) {
                case 'daily_checkin':
                    $lastCheckin = $user['last_checkin'] ?? null;
                    if ($lastCheckin) {
                        $lastDate = date('Y-m-d', strtotime($lastCheckin));
                        $today = date('Y-m-d');
                        $canComplete = ($lastDate !== $today);
                    } else {
                        $canComplete = true;
                    }
                    $reward = 0.30;
                    break;
                case 'first_deposit':
                    $canComplete = ($totalDeposited > 0);
                    $reward = 2.00;
                    break;
                case 'first_investment':
                    $canComplete = ($totalInvestmentsCount > 0);
                    $reward = 1.50;
                    break;
                case 'complete_profile':
                    $canComplete = (!empty($user['name']) && !empty($user['document']));
                    $reward = 1.00;
                    break;
                case 'invite_3_friends':
                    $canComplete = (count($indicadosLVL1Diretos) >= 3);
                    $reward = 5.00;
                    break;
                case 'share_link':
                    $canComplete = ($user['visits_affiliate_link'] > 0);
                    $reward = 0.30;
                    break;
            }
            
            if (!$canComplete) {
                throw new Exception("Você ainda não completou os requisitos desta tarefa.");
            }
            
            $pdo->beginTransaction();
            try {
                $taskName = '';
                switch ($taskType) {
                    case 'daily_checkin':
                        $taskName = 'Check-in Diário';
                        $pdo->prepare("UPDATE users SET balance = balance + ?, count_checkin = count_checkin + 1, last_checkin = NOW() WHERE id = ?")
                            ->execute([$reward, $user['id']]);
                        break;
                    default:
                        $taskName = 'Tarefa ' . $taskType;
                        $pdo->prepare("UPDATE users SET balance = balance + ? WHERE id = ?")
                            ->execute([$reward, $user['id']]);
                }
                
                $pdo->prepare("INSERT INTO user_tasks (user_id, task_type, task_name, reward, completed, completed_at) VALUES (?, ?, ?, ?, 1, NOW())")
                    ->execute([$user['id'], $taskType, $taskName, $reward]);
                
                $pdo->prepare("INSERT INTO history (user_id, action, created_at) VALUES (?, ?, NOW())")
                    ->execute([$user['id'], "Tarefa completada: {$taskName} - Ganhou R$ " . number_format($reward, 2)]);
                
                $pdo->commit();
                echo json_encode([
                    'status' => 'success',
                    'message' => "Tarefa completada! Você ganhou R$ " . number_format($reward, 2),
                    'reward' => $reward
                ]);
            } catch (Exception $e) {
                $pdo->rollBack();
                throw $e;
            }
            exit;
        }

        // ----------------------------------------------------------------------
        //  G. DASHBOARD AFILIADO (SPA)
        // ----------------------------------------------------------------------
        if ($action === 'get_affiliate_dashboard') {
            // Lvl 1
            $lvl1 = $pdo->prepare("SELECT id, phone, name, date, affiliate_code FROM users WHERE indicated_by = :code ORDER BY id DESC");
            $lvl1->execute([':code' => $user['affiliate_code']]);
            $lvl1Rows = $lvl1->fetchAll(PDO::FETCH_ASSOC);

            // Lvl 2 e 3 (derivados por affiliate_code)
            $lvl2Rows = [];
            $lvl3Rows = [];
            if (!empty($lvl1Rows)) {
                foreach ($lvl1Rows as $r1) {
                    $st2 = $pdo->prepare("SELECT id, phone, name, date, affiliate_code, indicated_by FROM users WHERE indicated_by = :code ORDER BY id DESC");
                    $st2->execute([':code' => $r1['affiliate_code']]);
                    $rows2 = $st2->fetchAll(PDO::FETCH_ASSOC);
                    $lvl2Rows = array_merge($lvl2Rows, $rows2);
                }
                if (!empty($lvl2Rows)) {
                    foreach ($lvl2Rows as $r2) {
                        $st3 = $pdo->prepare("SELECT id, phone, name, date, affiliate_code, indicated_by FROM users WHERE indicated_by = :code ORDER BY id DESC");
                        $st3->execute([':code' => $r2['affiliate_code']]);
                        $rows3 = $st3->fetchAll(PDO::FETCH_ASSOC);
                        $lvl3Rows = array_merge($lvl3Rows, $rows3);
                    }
                }
            }

            $all = array_merge($lvl1Rows, $lvl2Rows, $lvl3Rows);

            // Ativos (tem pelo menos 1 investimento)
            $activeCount = 0;
            if (!empty($all)) {
                $ids = array_column($all, 'id');
                $placeholders = implode(',', array_fill(0, count($ids), '?'));
                $stActive = $pdo->prepare("SELECT COUNT(DISTINCT user_id) FROM investments WHERE user_id IN ($placeholders)");
                $stActive->execute($ids);
                $activeCount = (int)($stActive->fetchColumn() ?? 0);
            }

            // Comissões
            $stTotal = $pdo->prepare("SELECT COALESCE(SUM(liquid_affiliate),0) FROM comission_affiliates WHERE affiliate_id = ?");
            $stTotal->execute([$user['id']]);
            $totalCommission = (float)$stTotal->fetchColumn();

            $stToday = $pdo->prepare("SELECT COALESCE(SUM(liquid_affiliate),0) FROM comission_affiliates WHERE affiliate_id = ? AND created_at >= CURDATE()");
            $stToday->execute([$user['id']]);
            $todayCommission = (float)$stToday->fetchColumn();

            // Série 14 dias
            $stSeries = $pdo->prepare("
                SELECT DATE(created_at) AS d, COALESCE(SUM(liquid_affiliate),0) AS v
                FROM comission_affiliates
                WHERE affiliate_id = ? AND created_at >= (CURDATE() - INTERVAL 13 DAY)
                GROUP BY DATE(created_at)
                ORDER BY d ASC
            ");
            $stSeries->execute([$user['id']]);
            $seriesRaw = $stSeries->fetchAll(PDO::FETCH_ASSOC);
            $seriesMap = [];
            foreach ($seriesRaw as $sr) $seriesMap[$sr['d']] = (float)$sr['v'];
            $labels = [];
            $values = [];
            for ($i = 13; $i >= 0; $i--) {
                $d = date('Y-m-d', strtotime("-$i day"));
                $labels[] = $d;
                $values[] = $seriesMap[$d] ?? 0;
            }

            echo json_encode([
                'status' => 'success',
                'vip' => [
                    'current' => (int)($user['vip_level'] ?? 0),
                    'qualified150' => (int)($qualified150Count ?? 0),
                    'next_required' => (int)($qtdNecessariaVip ?? 0),
                    'progress_pct' => (float)($vipProgressPct ?? 0),
                ],
                'spins' => (int)($user['qtd_spins'] ?? 0),
                'visits' => (int)($user['visits_affiliate_link'] ?? 0),
                'counts' => [
                    'lvl1' => count($lvl1Rows),
                    'lvl2' => count($lvl2Rows),
                    'lvl3' => count($lvl3Rows),
                    'total' => count($all),
                    'active' => $activeCount,
                ],
                'commission' => [
                    'total' => $totalCommission,
                    'today' => $todayCommission,
                    'series' => ['labels' => $labels, 'values' => $values],
                ],
                'members' => [
                    'lvl1' => $lvl1Rows,
                    'lvl2' => $lvl2Rows,
                    'lvl3' => $lvl3Rows,
                ],
            ]);
            exit;
        }

        if ($action === 'get_member_details') {
            $memberId = (int)($_POST['member_id'] ?? 0);
            if ($memberId <= 0) throw new Exception("Membro inválido.");

            // Segurança (até 3 níveis): usa checagem por affiliate_code
            $st = $pdo->prepare("
                SELECT u.id
                FROM users u
                WHERE u.id = :id AND (
                    u.indicated_by = :mycode
                    OR u.indicated_by IN (SELECT affiliate_code FROM users WHERE indicated_by = :mycode)
                    OR u.indicated_by IN (
                        SELECT affiliate_code FROM users WHERE indicated_by IN (SELECT affiliate_code FROM users WHERE indicated_by = :mycode)
                    )
                )
                LIMIT 1
            ");
            $st->execute([':id' => $memberId, ':mycode' => $user['affiliate_code']]);
            if (!$st->fetchColumn()) throw new Exception("Sem permissão.");

            $stUser = $pdo->prepare("SELECT id, phone, name, date, vip_level FROM users WHERE id = ? LIMIT 1");
            $stUser->execute([$memberId]);
            $m = $stUser->fetch(PDO::FETCH_ASSOC);
            if (!$m) throw new Exception("Membro não encontrado.");

            $stInv = $pdo->prepare("SELECT COALESCE(SUM(invested_amount),0) AS total_invested, COUNT(*) AS inv_count FROM investments WHERE user_id = ?");
            $stInv->execute([$memberId]);
            $inv = $stInv->fetch(PDO::FETCH_ASSOC);

            $stInvActive = $pdo->prepare("SELECT COUNT(*) FROM investments WHERE user_id = ? AND is_active = 1");
            $stInvActive->execute([$memberId]);
            $activeInv = (int)$stInvActive->fetchColumn();

            $stDep = $pdo->prepare("SELECT COALESCE(SUM(value),0) FROM transactions WHERE user_id = ? AND status = 'paid'");
            $stDep->execute([$memberId]);
            $totalDep = (float)$stDep->fetchColumn();

            echo json_encode([
                'status' => 'success',
                'member' => $m,
                'stats' => [
                    'total_invested' => (float)($inv['total_invested'] ?? 0),
                    'investments' => (int)($inv['inv_count'] ?? 0),
                    'active_investments' => $activeInv,
                    'total_deposited' => $totalDep,
                ],
            ]);
            exit;
        }

        if ($action === 'get_affiliate_stats') {
            // Estatísticas detalhadas para filtros
            $dateFrom = $_POST['date_from'] ?? date('Y-m-d', strtotime('-30 days'));
            $dateTo = $_POST['date_to'] ?? date('Y-m-d');
            
            // Comissões no período
            $stmtComm = $pdo->prepare("
                SELECT COALESCE(SUM(amount),0) as total, DATE(created_at) as date
                FROM comission_affiliates 
                WHERE affiliate_id = ? AND DATE(created_at) BETWEEN ? AND ?
                GROUP BY DATE(created_at)
                ORDER BY date ASC
            ");
            $stmtComm->execute([$user['id'], $dateFrom, $dateTo]);
            $commissions = $stmtComm->fetchAll(PDO::FETCH_ASSOC);
            
            echo json_encode([
                'status' => 'success',
                'commissions' => $commissions,
                'visits' => (int)($user['visits_affiliate_link'] ?? 0),
            ]);
            exit;
        }

    } catch (Exception $e) {
        if ($pdo->inTransaction()) $pdo->rollBack();
        echo json_encode(['status'=>'error', 'message'=>$e->getMessage()]);
        exit;
    }
}

// ==============================================================================
//  FRONTEND DATA
// ==============================================================================
$products = $pdo->query("SELECT * FROM investment_products WHERE is_active = 1 ORDER BY order_product ASC")->fetchAll();
$announces = $pdo->query("SELECT * FROM announce ORDER BY id DESC LIMIT 5")->fetchAll();

// Lê variáveis de sessão do cupom
$cupomToastMessage = $_SESSION['toastMessage'] ?? null;
$cupomToastType = $_SESSION['toastType'] ?? null;
$showCupomModal = $_SESSION['show_cupom_modal'] ?? false;
$cupomValue = $_SESSION['cupom_value'] ?? '0,00';

// Limpa as sessões do cupom
unset($_SESSION['toastMessage'], $_SESSION['toastType'], $_SESSION['show_cupom_modal'], $_SESSION['cupom_value']);
$historyList = $pdo->prepare("SELECT * FROM history WHERE user_id = ? ORDER BY created_at DESC LIMIT 100"); $historyList->execute([$user['id']]); $historyList = $historyList->fetchAll();
$pix = $pdo->prepare("SELECT * FROM accounts_pix WHERE phone_user = ? AND status = 'active'"); $pix->execute([$user['phone']]); $hasPix = $pix->rowCount() > 0; $pixData = $pix->fetch();

// Cálculos financeiros
$stmtTotalDep = $pdo->prepare("SELECT COALESCE(SUM(value),0) FROM transactions WHERE user_id = ? AND status = 'paid'");
$stmtTotalDep->execute([$user['id']]);
$totalDeposited = (float)$stmtTotalDep->fetchColumn();

$stmtTotalWith = $pdo->prepare("SELECT COALESCE(SUM(with_liquid),0) FROM withdrawal WHERE user_id = ? AND status = 'approved'");
$stmtTotalWith->execute([$user['id']]);
$totalWithdrawn = (float)$stmtTotalWith->fetchColumn();

$stmtTotalProf = $pdo->prepare("SELECT COALESCE(SUM(value),0) FROM investments_rescues WHERE user_id = ?");
$stmtTotalProf->execute([$user['id']]);
$totalProfit = (float)$stmtTotalProf->fetchColumn();

// Estatísticas adicionais do usuário
$stmtTotalInv = $pdo->prepare("SELECT COALESCE(SUM(invested_amount),0), COUNT(*) FROM investments WHERE user_id = ?");
$stmtTotalInv->execute([$user['id']]);
$totalInvData = $stmtTotalInv->fetch(PDO::FETCH_NUM);
$totalInvested = (float)($totalInvData[0] ?? 0);
$totalInvestmentsCount = (int)($totalInvData[1] ?? 0);

$stmtActiveInv = $pdo->prepare("SELECT COUNT(*) FROM investments WHERE user_id = ? AND is_active = 1");
$stmtActiveInv->execute([$user['id']]);
$activeInvestmentsCount = (int)$stmtActiveInv->fetchColumn();

// Criar tabela de tarefas se não existir
try {
    $pdo->exec("CREATE TABLE IF NOT EXISTS `user_tasks` (
        `id` int(11) NOT NULL AUTO_INCREMENT,
        `user_id` int(11) NOT NULL,
        `task_type` varchar(50) NOT NULL,
        `task_name` varchar(255) NOT NULL,
        `reward` decimal(10,2) NOT NULL DEFAULT 0.00,
        `completed` tinyint(1) NOT NULL DEFAULT 0,
        `completed_at` datetime DEFAULT NULL,
        `created_at` datetime NOT NULL DEFAULT current_timestamp(),
        PRIMARY KEY (`id`),
        KEY `user_id` (`user_id`),
        KEY `task_type` (`task_type`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci");
} catch (Exception $e) {}

// AFILIADOS (links + números base; o dashboard completo vem via action=get_affiliate_dashboard)
$affiliate_link = (isset($_SERVER['HTTPS']) ? "https://" : "http://") . $_SERVER['HTTP_HOST'] . "/public/register.php?ref=" . $user['affiliate_code'];
$todosIndicados = count($indicadosLVL1Diretos);
?>
<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title><?= htmlspecialchars($config['name_platform'] ?? 'App') ?></title>
    <link rel="icon" href="data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 100 100'><circle cx='50' cy='50' r='40' fill='%230EA5E9'/></svg>">
    <script src="https://cdn.tailwindcss.com"></script>
    <script src="https://unpkg.com/lucide@latest"></script>
    <script src="https://unpkg.com/imask"></script>
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/canvas-confetti@1.9.2/dist/confetti.browser.min.js"></script>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;600;700&family=Oswald:wght@500;700&family=Share+Tech+Mono&display=swap" rel="stylesheet">
    <script>
        tailwind.config = { 
            theme: { 
                extend: { 
                    colors: { vip: { blue: '#0EA5E9', dark: '#020617', card: '#ffffff', gray: '#64748B', alert: '#EF4444', success: '#10B981', salmon: '#FF7E67' } }, 
                    fontFamily: { sans: ['Inter', 'sans-serif'], mono: ['Oswald', 'sans-serif'], tech: ['"Share Tech Mono"', 'monospace'] },
                    boxShadow: { 'card': '0 10px 30px -10px rgba(255, 126, 103, 0.4)' }
                } 
            } 
        }
    </script>
    <style>
        body { background: #F8F9FA; padding-bottom: 90px; -webkit-tap-highlight-color: transparent; }
        .safe-area-bottom { padding-bottom: env(safe-area-inset-bottom); }
        .hero { 
            background: linear-gradient(180deg, #1e3a8a 0%, #312e81 50%, #1e1b4b 100%); 
            padding: 30px 20px 80px; 
            border-radius: 0 0 40px 40px; 
            transition: 0.3s;
            position: relative;
            overflow: hidden;
        }
        .hero::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: radial-gradient(circle at 20% 50%, rgba(59, 130, 246, 0.15) 0%, transparent 50%),
                        radial-gradient(circle at 80% 80%, rgba(139, 92, 246, 0.15) 0%, transparent 50%);
            pointer-events: none;
        }
        .hero > * {
            position: relative;
            z-index: 1;
        }
        body.mini .hero { padding-bottom: 30px; border-radius: 0 0 20px 20px; }
        body.mini .hero-act { display: none; }
        .tab-view { display: none; animation: fadeUp 0.3s ease; }
        .tab-view.active { display: block; }
        @keyframes fadeUp { from{opacity:0;transform:translateY(10px)} to{opacity:1;transform:translateY(0)} }
        
        /* Menu Bottom Styles */
        .menu-item {
            color: #94a3b8;
        }
        .menu-item.active {
            color: #0EA5E9;
        }
        .menu-item.active .menu-icon {
            color: #0EA5E9;
            transform: scale(1.1);
        }
        .menu-item .menu-icon {
            transition: all 0.3s ease;
            color: #94a3b8;
        }
        .menu-item:hover .menu-icon {
            transform: scale(1.1);
        }
        .menu-label {
            transition: all 0.3s ease;
        }
        .menu-item-vip {
            color: #f59e0b;
        }
        .vip-icon-container {
            animation: vipPulse 2s ease-in-out infinite;
            transition: all 0.3s ease;
        }
        .menu-item-vip:hover .vip-icon-container {
            transform: scale(1.1);
            box-shadow: 0 10px 30px rgba(245, 158, 11, 0.4);
        }
        .vip-icon {
            animation: vipRotate 3s ease-in-out infinite;
        }
        @keyframes vipPulse {
            0%, 100% { transform: scale(1); }
            50% { transform: scale(1.05); }
        }
        @keyframes vipRotate {
            0%, 100% { transform: rotate(0deg); }
            25% { transform: rotate(-5deg); }
            75% { transform: rotate(5deg); }
        }
        
        .card { background: white; border-radius: 16px; border: 1px solid #E2E8F0; box-shadow: 0 4px 15px rgba(0,0,0,0.03); overflow: hidden; margin-bottom: 15px; position: relative; }
        .btn { width: 100%; padding: 14px; border-radius: 12px; font-weight: 700; text-transform: uppercase; font-family: 'Oswald'; display: flex; align-items: center; justify-content: center; gap: 8px; transition: 0.2s; font-size: 13px; }
        .btn:active { transform: scale(0.98); }
        .inp { width: 100%; padding: 16px; background: #F8FAFC; border: 1px solid #E2E8F0; border-radius: 12px; font-weight: 600; outline: none; transition: 0.3s; }
        .inp:focus { border-color: #0EA5E9; background: white; box-shadow: 0 0 0 3px rgba(14,165,233,0.1); }
        
        .btn-collect { background: #0EA5E9; color: white; font-family: 'Oswald'; text-transform: uppercase; font-weight: bold; border-radius: 12px; padding: 16px; box-shadow: 0 4px 15px rgba(14,165,233,0.3); transition: 0.2s; }
        .btn-collect:disabled { background: #E2E8F0; color: #94A3B8; box-shadow: none; cursor: not-allowed; }
        .modal { position: fixed; inset: 0; background: white; z-index: 2000; transform: translateY(100%); transition: 0.3s; overflow-y: auto; }
        .modal.open { transform: translateY(0); }
        .toast { position: fixed; top: 20px; left: 50%; transform: translateX(-50%); background: #333; color: #fff; padding: 10px 20px; border-radius: 8px; z-index: 3000; display: none; font-size: 13px; font-weight: bold; }
        
        /* ============================================
           RESPONSIVIDADE COMPLETA - TODAS AS TELAS
           ============================================ */
        
        /* Galaxy Pocket e telas muito pequenas (240px - 319px) */
        @media (max-width: 319px) {
            body { padding-bottom: 75px; font-size: 12px; }
            .hero { padding: 20px 12px 60px; border-radius: 0 0 25px 25px; }
            .hero h1 { font-size: 18px; }
            .hero p { font-size: 11px; }
            
            /* Cards de saldo */
            .grid.grid-cols-2 { grid-template-columns: 1fr; gap: 12px; }
            .grid.grid-cols-2 > div { padding: 12px; }
            .grid.grid-cols-2 h2 { font-size: 18px; }
            .grid.grid-cols-2 button { padding: 10px; font-size: 10px; }
            
            /* Menu top */
            #mainTab { padding: 8px 4px; gap: 4px; }
            #mainTab button { padding: 8px 6px; font-size: 9px; min-width: 60px; }
            
            /* Menu bottom */
            .fixed.bottom-0 { padding: 6px 4px; }
            .menu-item, .menu-item-vip { padding: 6px 4px; }
            .menu-item .menu-icon, .menu-item-vip .menu-icon { width: 18px; height: 18px; }
            .menu-label { font-size: 8px; }
            .vip-icon-container { width: 48px; height: 48px; }
            .vip-icon { width: 20px; height: 20px; }
            
            /* Modais */
            .modal > div { margin: 8px; padding: 12px; }
            .modal h3 { font-size: 14px; padding: 12px; }
            .modal p { font-size: 11px; }
            .modal button { padding: 10px; font-size: 11px; }
            
            /* Cards e botões */
            .card { padding: 12px; margin-bottom: 10px; border-radius: 12px; }
            .btn { padding: 10px; font-size: 11px; }
            .btn-collect { padding: 12px; font-size: 11px; }
            
            /* Textos */
            h2 { font-size: 18px; }
            h3 { font-size: 16px; }
            p { font-size: 11px; }
            
            /* Grids */
            .grid { gap: 8px; }
            .grid.grid-cols-3 { grid-template-columns: 1fr; }
            .grid.grid-cols-4 { grid-template-columns: repeat(2, 1fr); }
            
            /* Espaçamentos */
            .px-5 { padding-left: 12px; padding-right: 12px; }
            .py-5 { padding-top: 12px; padding-bottom: 12px; }
            .mb-6 { margin-bottom: 12px; }
            .gap-4 { gap: 8px; }
            
            /* Badge VIP */
            .absolute.top-4.right-4 { top: 8px; right: 8px; }
            .absolute.top-4.right-4 div { padding: 6px 8px; font-size: 9px; }
        }
        
        /* Galaxy Y e telas pequenas (320px - 359px) */
        @media (min-width: 320px) and (max-width: 359px) {
            body { padding-bottom: 80px; font-size: 13px; }
            .hero { padding: 25px 15px 70px; border-radius: 0 0 30px 30px; }
            .hero h1 { font-size: 20px; }
            .hero p { font-size: 12px; }
            
            /* Cards de saldo */
            .grid.grid-cols-2 > div { padding: 14px; }
            .grid.grid-cols-2 h2 { font-size: 20px; }
            .grid.grid-cols-2 button { padding: 11px; font-size: 10px; }
            
            /* Menu top */
            #mainTab { padding: 10px 6px; gap: 6px; }
            #mainTab button { padding: 10px 8px; font-size: 10px; min-width: 70px; }
            
            /* Menu bottom */
            .fixed.bottom-0 { padding: 8px 6px; }
            .menu-item, .menu-item-vip { padding: 8px 6px; }
            .menu-item .menu-icon, .menu-item-vip .menu-icon { width: 20px; height: 20px; }
            .menu-label { font-size: 8px; }
            .vip-icon-container { width: 52px; height: 52px; }
            .vip-icon { width: 22px; height: 22px; }
            
            /* Modais */
            .modal > div { margin: 10px; padding: 14px; }
            .modal h3 { font-size: 15px; padding: 14px; }
            .modal p { font-size: 12px; }
            .modal button { padding: 11px; font-size: 12px; }
            
            /* Cards e botões */
            .card { padding: 14px; margin-bottom: 12px; }
            .btn { padding: 12px; font-size: 12px; }
            .btn-collect { padding: 14px; font-size: 12px; }
            
            /* Textos */
            h2 { font-size: 20px; }
            h3 { font-size: 18px; }
            p { font-size: 12px; }
            
            /* Grids */
            .grid { gap: 10px; }
            .grid.grid-cols-3 { grid-template-columns: repeat(2, 1fr); }
            .grid.grid-cols-4 { grid-template-columns: repeat(2, 1fr); }
            
            /* Espaçamentos */
            .px-5 { padding-left: 15px; padding-right: 15px; }
            .py-5 { padding-top: 14px; padding-bottom: 14px; }
            .mb-6 { margin-bottom: 14px; }
            .gap-4 { gap: 10px; }
        }
        
        /* Celulares médios (360px - 413px) */
        @media (min-width: 360px) and (max-width: 413px) {
            body { padding-bottom: 85px; }
            .hero { padding: 28px 18px 75px; }
            .grid.grid-cols-2 > div { padding: 16px; }
            .grid.grid-cols-2 h2 { font-size: 22px; }
            #mainTab button { font-size: 11px; min-width: 75px; }
            .menu-label { font-size: 9px; }
            .vip-icon-container { width: 56px; height: 56px; }
            .vip-icon { width: 24px; height: 24px; }
        }
        
        /* Celulares grandes (414px - 479px) */
        @media (min-width: 414px) and (max-width: 479px) {
            body { padding-bottom: 90px; }
            .hero { padding: 30px 20px 80px; }
            .grid.grid-cols-2 > div { padding: 18px; }
            .grid.grid-cols-2 h2 { font-size: 24px; }
            #mainTab button { font-size: 12px; min-width: 80px; }
            .menu-label { font-size: 9px; }
            .vip-icon-container { width: 60px; height: 60px; }
            .vip-icon { width: 26px; height: 26px; }
        }
        
        /* Tablets pequenos (600px - 767px) */
        @media (min-width: 600px) and (max-width: 767px) {
            body { padding-bottom: 100px; }
            body.max-w-xl { max-width: 100%; }
            .hero { padding: 40px 30px 100px; border-radius: 0 0 50px 50px; }
            .hero h1 { font-size: 32px; }
            .hero p { font-size: 16px; }
            
            /* Cards de saldo */
            .grid.grid-cols-2 { gap: 20px; }
            .grid.grid-cols-2 > div { padding: 24px; }
            .grid.grid-cols-2 h2 { font-size: 32px; }
            .grid.grid-cols-2 button { padding: 16px; font-size: 14px; }
            
            /* Menu top */
            #mainTab { padding: 12px 8px; gap: 8px; }
            #mainTab button { padding: 14px 12px; font-size: 13px; min-width: 100px; }
            
            /* Menu bottom */
            .fixed.bottom-0 { padding: 12px 8px; }
            .menu-item, .menu-item-vip { padding: 12px 10px; }
            .menu-item .menu-icon, .menu-item-vip .menu-icon { width: 28px; height: 28px; }
            .menu-label { font-size: 11px; }
            .vip-icon-container { width: 70px; height: 70px; }
            .vip-icon { width: 32px; height: 32px; }
            
            /* Modais */
            .modal > div { margin: 20px auto; max-width: 500px; padding: 24px; }
            .modal h3 { font-size: 20px; padding: 20px; }
            .modal p { font-size: 15px; }
            .modal button { padding: 16px; font-size: 14px; }
            
            /* Cards e botões */
            .card { padding: 20px; margin-bottom: 18px; border-radius: 20px; }
            .btn { padding: 16px; font-size: 14px; }
            .btn-collect { padding: 18px; font-size: 14px; }
            
            /* Textos */
            h2 { font-size: 28px; }
            h3 { font-size: 24px; }
            p { font-size: 15px; }
            
            /* Grids */
            .grid { gap: 16px; }
            .grid.grid-cols-3 { grid-template-columns: repeat(3, 1fr); }
            .grid.grid-cols-4 { grid-template-columns: repeat(4, 1fr); }
            
            /* Espaçamentos */
            .px-5 { padding-left: 30px; padding-right: 30px; }
            .py-5 { padding-top: 24px; padding-bottom: 24px; }
            .mb-6 { margin-bottom: 24px; }
            .gap-4 { gap: 16px; }
            
            /* Container principal */
            .max-w-xl { max-width: 100%; padding: 0 20px; }
        }
        
        /* Tablets grandes e desktops pequenos (768px+) */
        @media (min-width: 768px) {
            body { padding-bottom: 110px; }
            body.max-w-xl { max-width: 768px; margin: 0 auto; }
            .hero { padding: 50px 40px 120px; border-radius: 0 0 60px 60px; }
            .hero h1 { font-size: 36px; }
            .hero p { font-size: 18px; }
            
            /* Cards de saldo */
            .grid.grid-cols-2 { gap: 24px; }
            .grid.grid-cols-2 > div { padding: 28px; }
            .grid.grid-cols-2 h2 { font-size: 36px; }
            .grid.grid-cols-2 button { padding: 18px; font-size: 15px; }
            
            /* Menu top */
            #mainTab { padding: 14px 10px; gap: 10px; }
            #mainTab button { padding: 16px 14px; font-size: 14px; min-width: 120px; }
            
            /* Menu bottom */
            .fixed.bottom-0 { padding: 14px 10px; }
            .menu-item, .menu-item-vip { padding: 14px 12px; }
            .menu-item .menu-icon, .menu-item-vip .menu-icon { width: 32px; height: 32px; }
            .menu-label { font-size: 12px; }
            .vip-icon-container { width: 80px; height: 80px; }
            .vip-icon { width: 36px; height: 36px; }
            
            /* Modais */
            .modal > div { margin: 30px auto; max-width: 600px; padding: 32px; }
            .modal h3 { font-size: 24px; padding: 24px; }
            .modal p { font-size: 16px; }
            .modal button { padding: 18px; font-size: 15px; }
            
            /* Cards e botões */
            .card { padding: 24px; margin-bottom: 20px; border-radius: 24px; }
            .btn { padding: 18px; font-size: 15px; }
            .btn-collect { padding: 20px; font-size: 15px; }
            
            /* Textos */
            h2 { font-size: 32px; }
            h3 { font-size: 26px; }
            p { font-size: 16px; }
            
            /* Grids */
            .grid { gap: 20px; }
            .grid.grid-cols-3 { grid-template-columns: repeat(3, 1fr); }
            .grid.grid-cols-4 { grid-template-columns: repeat(4, 1fr); }
            
            /* Espaçamentos */
            .px-5 { padding-left: 40px; padding-right: 40px; }
            .py-5 { padding-top: 28px; padding-bottom: 28px; }
            .mb-6 { margin-bottom: 28px; }
            .gap-4 { gap: 20px; }
        }
        
        /* Ajustes gerais para todas as telas pequenas */
        @media (max-width: 479px) {
            /* Garantir que imagens não quebrem */
            img { max-width: 100%; height: auto; }
            
            /* Ajustar inputs */
            .inp { padding: 14px; font-size: 14px; }
            
            /* Ajustar modais de entrada */
            #entryModal > div { margin: 8px; }
            #entryModal .h-56 { height: 180px; }
            #entryModal h3 { font-size: 16px; padding: 14px; }
            #entryModal p { font-size: 12px; }
            #entryModal button { padding: 12px; font-size: 12px; }
            
            /* Ajustar tabelas */
            table { font-size: 11px; }
            table th, table td { padding: 8px 4px; }
            
            /* Ajustar badges */
            .badge, .tag { font-size: 9px; padding: 4px 8px; }
            
            /* Ajustar ícones pequenos */
            .w-4.h-4 { width: 14px; height: 14px; }
            .w-5.h-5 { width: 16px; height: 16px; }
            .w-6.h-6 { width: 18px; height: 18px; }
        }
        
        /* Ajustes para tablets */
        @media (min-width: 600px) {
            /* Melhorar legibilidade em tablets */
            body { font-size: 16px; }
            
            /* Ajustar modais */
            #entryModal > div { max-width: 600px; margin: 20px auto; }
            #entryModal .h-56 { height: 300px; }
            
            /* Ajustar tabelas */
            table { font-size: 14px; }
            table th, table td { padding: 12px 8px; }
            
            /* Ajustar badges */
            .badge, .tag { font-size: 12px; padding: 6px 12px; }
        }
        
        /* Orientação landscape para telas pequenas */
        @media (max-width: 767px) and (orientation: landscape) {
            .hero { padding: 20px 15px 50px; }
            .hero h1 { font-size: 22px; }
            .grid.grid-cols-2 { grid-template-columns: repeat(2, 1fr); }
            .fixed.bottom-0 { padding: 6px 4px; }
            .menu-label { font-size: 8px; }
            .vip-icon-container { width: 50px; height: 50px; }
        }
        
        /* Ajustes para telas muito altas (aspect ratio) */
        @media (min-height: 800px) and (max-width: 479px) {
            .hero { padding: 35px 20px 90px; }
        }
        
        /* Melhorias de toque para dispositivos móveis */
        @media (hover: none) and (pointer: coarse) {
            button, a, .btn { min-height: 44px; min-width: 44px; }
            .menu-item, .menu-item-vip { min-height: 44px; }
            input, select, textarea { min-height: 44px; font-size: 16px; } /* Evita zoom no iOS */
        }
        
        /* Ajustes de acessibilidade */
        @media (prefers-reduced-motion: reduce) {
            *, *::before, *::after { animation-duration: 0.01ms !important; animation-iteration-count: 1 !important; transition-duration: 0.01ms !important; }
        }
        
        /* Ajustes específicos para elementos com classes Tailwind em telas pequenas */
        @media (max-width: 479px) {
            /* Textos muito pequenos - aumentar mínimo */
            .text-\[9px\], .text-\[10px\] { font-size: 10px !important; }
            .text-xs { font-size: 11px !important; }
            
            /* Ajustar larguras fixas */
            .w-20, .h-20 { width: 60px !important; height: 60px !important; }
            .w-32 { width: 120px !important; }
            .w-48 { width: 180px !important; }
            
            /* Ajustar padding em cards pequenos */
            .p-3 { padding: 10px !important; }
            .p-4 { padding: 12px !important; }
            .p-5 { padding: 14px !important; }
            .p-6 { padding: 16px !important; }
            
            /* Ajustar gaps */
            .gap-2 { gap: 6px !important; }
            .gap-3 { gap: 8px !important; }
            .gap-4 { gap: 10px !important; }
            
            /* Ajustar margens */
            .mb-4 { margin-bottom: 10px !important; }
            .mb-5 { margin-bottom: 12px !important; }
            .mb-6 { margin-bottom: 14px !important; }
            
            /* Ajustar border radius */
            .rounded-2xl { border-radius: 12px !important; }
            .rounded-3xl { border-radius: 16px !important; }
            
            /* Ajustar produtos/investimentos */
            .product-card { margin-bottom: 12px !important; }
            
            /* Ajustar modais de produto */
            .product-card img { width: 100% !important; height: auto !important; max-height: 200px !important; }
            
            /* Ajustar tabelas responsivas */
            .overflow-x-auto { -webkit-overflow-scrolling: touch; }
            table { min-width: 100%; display: block; overflow-x: auto; white-space: nowrap; }
        }
        
        /* Ajustes para tablets */
        @media (min-width: 600px) and (max-width: 767px) {
            .text-\[9px\] { font-size: 11px !important; }
            .text-\[10px\] { font-size: 12px !important; }
            .w-20, .h-20 { width: 80px !important; height: 80px !important; }
        }
        
        /* Garantir que containers não quebrem */
        @media (max-width: 767px) {
            .max-w-md { max-width: 100% !important; }
            .max-w-xl { max-width: 100% !important; }
            .max-w-2xl { max-width: 100% !important; }
            .max-w-6xl { max-width: 100% !important; }
            .max-w-7xl { max-width: 100% !important; }
        }
        
        /* Ajustar scroll horizontal no menu top */
        @media (max-width: 479px) {
            #mainTab { 
                -webkit-overflow-scrolling: touch;
                scrollbar-width: none;
                -ms-overflow-style: none;
            }
            #mainTab::-webkit-scrollbar { display: none; }
        }
        
        /* Ajustar overflow em cards de investimento */
        @media (max-width: 479px) {
            .grid.grid-cols-2.gap-4 { gap: 8px !important; }
            .grid.grid-cols-2.gap-4 > div { padding: 10px !important; }
            .grid.grid-cols-2.gap-4 h2, .grid.grid-cols-2.gap-4 p { font-size: 14px !important; }
        }
        
        /* Ajustar modal de entrada em telas muito pequenas */
        @media (max-width: 319px) {
            #entryModal > div { margin: 4px !important; padding: 8px !important; }
            #entryModal .h-56 { height: 150px !important; }
            #entryModal h3 { font-size: 14px !important; padding: 10px !important; }
            #entryModal p { font-size: 10px !important; }
            #entryModal button { padding: 10px !important; font-size: 10px !important; }
        }
    </style>
</head>
<body class="max-w-xl mx-auto">

    <div id="toast-area"></div>
    <audio id="clickSound" src="https://assets.mixkit.co/active_storage/sfx/2568/2568-preview.mp3" preload="auto"></audio>
    <audio id="successSound" src="https://assets.mixkit.co/active_storage/sfx/2019/2019-preview.mp3" preload="auto"></audio>
    <audio id="errorSound" src="https://assets.mixkit.co/active_storage/sfx/1781/1781-preview.mp3" preload="auto"></audio>
    <audio id="bgPlayer" preload="auto" loop></audio>

    <!-- MODAL DE ENTRADA (Estilo da Imagem) -->
    <div id="entryModal" class="modal !bg-black/80 backdrop-blur-md flex items-center justify-center p-4" style="z-index: 2500;">
        <div class="bg-white w-full max-w-md rounded-3xl overflow-hidden relative shadow-2xl animate-fadeInUp border-4 border-white/50">
            <!-- Efeitos de fundo animados -->
            <div class="absolute inset-0 bg-gradient-to-br from-blue-500/20 via-purple-500/20 to-pink-500/20 animate-pulse"></div>
            <div class="absolute top-0 left-0 w-full h-1 bg-gradient-to-r from-blue-500 via-purple-500 to-pink-500 animate-shimmer"></div>
            
            <!-- Header com gradiente animado -->
            <div class="bg-gradient-to-r from-blue-600 via-purple-600 to-pink-600 px-6 py-5 flex items-center justify-between relative overflow-hidden">
                <div class="absolute inset-0 bg-gradient-to-r from-transparent via-white/20 to-transparent animate-shimmer"></div>
                <h3 class="text-white font-black text-xl uppercase relative z-10 drop-shadow-lg" data-i18n="notice">Aviso</h3>
                <div class="w-14 h-14 bg-white/20 backdrop-blur-sm rounded-2xl flex items-center justify-center border-2 border-white/30 relative z-10 animate-pulse">
                    <i data-lucide="megaphone" class="w-7 h-7 text-white"></i>
                </div>
            </div>
            
            <!-- Imagem com efeitos -->
            <div class="relative h-56 bg-gradient-to-br from-blue-500 via-purple-500 to-pink-500 overflow-hidden group">
                <?php 
                $modalImage = $config['entry_modal_image'];
                ?>
                <img id="entryModalImg" src="<?= htmlspecialchars($modalImage) ?>" class="w-full h-full object-cover group-hover:scale-110 transition-transform duration-500" onerror="this.src='https://placehold.co/800x300?text=News'">
                <div class="absolute inset-0 bg-gradient-to-t from-black/80 via-black/40 to-transparent"></div>
                <!-- Efeito de brilho na imagem -->
                <div class="absolute inset-0 bg-gradient-to-r from-transparent via-white/20 to-transparent -translate-x-full group-hover:translate-x-full transition-transform duration-1000"></div>
                <!-- Partículas flutuantes -->
                <div class="absolute top-4 right-4 w-3 h-3 bg-yellow-400 rounded-full animate-ping"></div>
                <div class="absolute bottom-8 left-6 w-2 h-2 bg-cyan-400 rounded-full animate-ping" style="animation-delay: 0.5s;"></div>
                <div class="absolute top-1/2 right-8 w-2.5 h-2.5 bg-pink-400 rounded-full animate-ping" style="animation-delay: 1s;"></div>
                
                <div class="absolute bottom-0 left-0 right-0 p-5 text-white">
                    <div class="text-xs font-bold uppercase mb-2 opacity-90 flex items-center gap-2">
                        <i data-lucide="sparkles" class="w-4 h-4"></i>
                        <?= htmlspecialchars($config['name_platform'] ?? 'Chevron') ?>
                    </div>
                    <div class="text-2xl font-black drop-shadow-2xl"><?= htmlspecialchars(!empty($config['entry_modal_title']) ? $config['entry_modal_title'] : ($announces[0]['title'] ?? 'Bem-vindo!')) ?></div>
                </div>
            </div>
            
            <!-- Conteúdo -->
            <div class="p-6 bg-gradient-to-b from-white to-gray-50">
                <p id="entryModalText" class="text-sm text-gray-700 leading-relaxed mb-5 font-medium" data-i18n="welcomeText">
                    <?= htmlspecialchars(!empty($config['entry_modal_text']) ? $config['entry_modal_text'] : substr($announces[0]['description'] ?? 'Entre no nosso grupo oficial para receber avisos, novidades e suporte.', 0, 150)) ?>
                </p>
                
                <div class="bg-gradient-to-r from-yellow-400 via-orange-500 to-pink-500 rounded-2xl p-5 mb-5 border-2 border-yellow-300 shadow-xl relative overflow-hidden group">
                    <div class="absolute inset-0 bg-gradient-to-r from-transparent via-white/30 to-transparent -translate-x-full group-hover:translate-x-full transition-transform duration-1000"></div>
                    <div class="relative z-10">
                        <div class="flex items-center gap-3 mb-2">
                            <div class="w-10 h-10 bg-white/20 backdrop-blur-sm rounded-xl flex items-center justify-center border-2 border-white/30">
                                <i data-lucide="gift" class="w-6 h-6 text-white"></i>
                            </div>
                            <span class="text-sm font-black text-white uppercase drop-shadow-lg" data-i18n="specialPrizes">Prêmios Especiais</span>
                        </div>
                        <p class="text-sm text-white/90 font-bold" data-i18n="prizesInfo">Participe e ganhe recompensas exclusivas!</p>
                    </div>
                </div>
                
                <div class="flex gap-3 relative">
                    <button onclick="closeEntryModal()" class="absolute -top-2 -right-2 w-10 h-10 bg-red-500 hover:bg-red-600 backdrop-blur-sm rounded-full flex items-center justify-center text-white shadow-xl hover:scale-110 transition-all z-20 border-2 border-white">
                        <i data-lucide="x" class="w-5 h-5"></i>
                    </button>
                    <?php 
                    $buttonLink = !empty($config['entry_modal_button_link']) ? $config['entry_modal_button_link'] : ($config['support_link'] ?? '#');
                    $buttonType = $config['entry_modal_button_type'] ?? 'whatsapp';
                    $buttonIcon = $buttonType === 'telegram' ? 'send' : 'message-circle';
                    $buttonText = $buttonType === 'telegram' ? 'Telegram' : 'WhatsApp';
                    $buttonColor = $buttonType === 'telegram' ? 'from-blue-500 to-cyan-500' : 'from-green-500 to-emerald-500';
                    ?>
                    <a href="<?= htmlspecialchars($buttonLink) ?>" target="_blank" class="flex-1 py-4 rounded-2xl font-black text-base uppercase bg-gradient-to-r <?= $buttonColor ?> text-white text-center shadow-2xl hover:shadow-3xl transition-all active:scale-95 flex items-center justify-center gap-3 relative overflow-hidden group/btn">
                        <div class="absolute inset-0 bg-gradient-to-r from-transparent via-white/30 to-transparent -translate-x-full group-hover/btn:translate-x-full transition-transform duration-1000"></div>
                        <i data-lucide="<?= $buttonIcon ?>" class="w-6 h-6 relative z-10 group-hover/btn:scale-125 transition-transform"></i>
                        <span class="relative z-10 drop-shadow-lg">Ir para <?= $buttonText ?></span>
                        <i data-lucide="arrow-right" class="w-5 h-5 relative z-10 group-hover/btn:translate-x-1 transition-transform"></i>
                    </a>
                </div>
            </div>
        </div>
    </div>

    <!-- MODAL DE SUCESSO DO CUPOM -->
    <div id="cupomSuccessModal" class="modal !bg-black/80 backdrop-blur-md flex items-center justify-center p-4" style="z-index: 4001;">
        <div class="bg-white w-full max-w-md rounded-3xl overflow-hidden relative shadow-2xl animate-fadeInUp">
            <!-- Header com gradiente verde -->
            <div class="bg-gradient-to-r from-green-500 to-emerald-600 px-6 py-4 flex items-center justify-between relative">
                <h3 class="text-white font-black text-lg uppercase">Cupom Resgatado!</h3>
                <div class="w-12 h-12 bg-white/20 backdrop-blur-sm rounded-xl flex items-center justify-center border border-white/30">
                    <i data-lucide="check-circle" class="w-6 h-6 text-white"></i>
                </div>
            </div>
            
            <!-- Conteúdo -->
            <div class="p-6 bg-white text-center">
                <div class="w-24 h-24 bg-gradient-to-br from-green-400 to-emerald-500 rounded-full mx-auto mb-6 flex items-center justify-center shadow-2xl animate-pulse">
                    <i data-lucide="gift" class="w-12 h-12 text-white"></i>
                </div>
                
                <h2 class="text-2xl font-black text-gray-900 mb-2">Parabéns!</h2>
                <p class="text-sm text-gray-600 mb-6">Cupom resgatado com sucesso!</p>
                
                <div class="bg-gradient-to-r from-green-50 to-emerald-50 rounded-xl p-5 mb-6 border-2 border-green-200">
                    <p class="text-xs font-bold text-green-600 uppercase mb-2">Valor Creditado</p>
                    <p class="text-3xl font-black text-green-700" id="cupomValueDisplay">R$ <?= htmlspecialchars($cupomValue ?? '0,00') ?></p>
                </div>
                
                <button onclick="closeCupomModal()" class="w-full py-4 rounded-xl font-black text-sm uppercase bg-gradient-to-r from-green-500 to-emerald-600 text-white text-center shadow-lg hover:shadow-xl transition-all active:scale-95">
                    Continuar
                </button>
            </div>
        </div>
    </div>

    <!-- MODAL MÚSICA -->
    <div id="modalMusic" class="modal bg-gray-50">
        <div class="p-5 bg-white border-b flex justify-between items-center sticky top-0 z-20">
            <h3 class="font-bold text-gray-900 uppercase text-sm flex items-center gap-2"><i data-lucide="music" class="w-4 h-4"></i> <span data-i18n="music">Música</span></h3>
            <button onclick="closeMusicModal()" class="w-10 h-10 bg-gray-100 rounded-full flex items-center justify-center"><i data-lucide="x" class="w-4 h-4"></i></button>
        </div>
        <div class="p-5 space-y-4">
            <div class="bg-white border border-gray-100 rounded-2xl p-4">
                <div class="flex items-center justify-between mb-2">
                    <h4 class="font-black text-gray-800 text-sm" data-i18n="argentinas">Argentinas • Top</h4>
                    <span class="text-[10px] text-gray-400 font-bold uppercase" data-i18n="main">Principal</span>
                </div>
                <div id="listArg" class="space-y-2 text-sm text-gray-700"></div>
            </div>
            <div class="bg-white border border-gray-100 rounded-2xl p-4">
                <div class="flex items-center justify-between mb-2">
                    <h4 class="font-black text-gray-800 text-sm" data-i18n="brasileiras">Brasileiras • 2026</h4>
                    <span class="text-[10px] text-gray-400 font-bold uppercase" data-i18n="current">Atual</span>
                </div>
                <div id="listBr" class="space-y-2 text-sm text-gray-700"></div>
            </div>
            <div class="bg-white border border-gray-100 rounded-xl p-3 flex items-center justify-between">
                <div>
                    <p class="text-xs font-bold text-gray-500 uppercase" data-i18n="playing">Tocando</p>
                    <p class="text-sm font-black text-gray-800" id="playingTitle">—</p>
                </div>
                <div class="flex gap-2">
                    <button onclick="playBg()" class="w-10 h-10 rounded-full bg-vip-blue text-white flex items-center justify-center"><i data-lucide="play" class="w-4 h-4"></i></button>
                    <button onclick="pauseBg()" class="w-10 h-10 rounded-full bg-gray-200 text-gray-700 flex items-center justify-center"><i data-lucide="pause" class="w-4 h-4"></i></button>
                </div>
            </div>
        </div>
    </div>

    <!-- MODAL SUPORTE -->
    <div id="modalSupport" class="modal bg-gray-50">
        <div class="p-5 bg-gradient-to-r from-blue-600 via-purple-600 to-pink-600 border-b flex justify-between items-center sticky top-0 z-20">
            <h3 class="font-black text-white uppercase text-base flex items-center gap-2">
                <i data-lucide="headphones" class="w-5 h-5"></i> 
                <span data-i18n="support">Suporte</span>
            </h3>
            <button onclick="closeSupportModal()" class="w-10 h-10 bg-white/20 hover:bg-white/30 rounded-full flex items-center justify-center text-white transition"><i data-lucide="x" class="w-5 h-5"></i></button>
        </div>
        <div class="p-5 space-y-4 bg-gradient-to-b from-white to-gray-50">
            <div class="bg-gradient-to-br from-blue-500 via-purple-500 to-pink-500 rounded-2xl p-6 border-2 border-white/30 shadow-2xl relative overflow-hidden">
                <div class="absolute top-0 right-0 w-32 h-32 bg-white/10 rounded-full -translate-y-1/2 translate-x-1/2 blur-2xl"></div>
                <div class="relative z-10">
                    <h4 class="font-black text-white mb-3 flex items-center gap-2 text-lg">
                        <i data-lucide="message-circle" class="w-6 h-6"></i>
                        Entre em Contato
                    </h4>
                    <p class="text-sm text-white/90 mb-5">Nossa equipe está pronta para ajudar você!</p>
                    <div class="space-y-3">
                        <?php 
                        $supportType = $config['support_active_type'] ?? 'both';
                        $telegramLink = $config['support_telegram_link'] ?? '';
                        $whatsappLink = $config['support_whatsapp_link'] ?? '';
                        ?>
                        <?php if (($supportType === 'telegram' || $supportType === 'both') && !empty($telegramLink)): ?>
                        <a href="<?= htmlspecialchars($telegramLink) ?>" target="_blank" class="flex items-center gap-4 p-4 bg-white/95 backdrop-blur-sm rounded-2xl border-2 border-white/50 hover:border-blue-400 hover:scale-105 transition-all shadow-lg group">
                            <div class="w-14 h-14 bg-gradient-to-br from-blue-500 to-cyan-500 rounded-2xl flex items-center justify-center shadow-xl group-hover:scale-110 transition-transform">
                                <i data-lucide="send" class="w-7 h-7 text-white"></i>
                            </div>
                            <div class="flex-1">
                                <p class="font-black text-gray-900 text-base">Telegram</p>
                                <p class="text-xs text-gray-600">Grupo oficial de suporte</p>
                            </div>
                            <i data-lucide="arrow-right" class="w-6 h-6 text-blue-600 group-hover:translate-x-1 transition-transform"></i>
                        </a>
                        <?php endif; ?>
                        
                        <?php if (($supportType === 'whatsapp' || $supportType === 'both') && !empty($whatsappLink)): ?>
                        <a href="<?= htmlspecialchars($whatsappLink) ?>" target="_blank" class="flex items-center gap-4 p-4 bg-white/95 backdrop-blur-sm rounded-2xl border-2 border-white/50 hover:border-green-400 hover:scale-105 transition-all shadow-lg group">
                            <div class="w-14 h-14 bg-gradient-to-br from-green-500 to-emerald-500 rounded-2xl flex items-center justify-center shadow-xl group-hover:scale-110 transition-transform">
                                <i data-lucide="message-square" class="w-7 h-7 text-white"></i>
                            </div>
                            <div class="flex-1">
                                <p class="font-black text-gray-900 text-base">WhatsApp</p>
                                <p class="text-xs text-gray-600">Atendimento direto</p>
                            </div>
                            <i data-lucide="arrow-right" class="w-6 h-6 text-green-600 group-hover:translate-x-1 transition-transform"></i>
                        </a>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
            <div class="bg-gradient-to-br from-yellow-50 to-orange-50 rounded-2xl p-5 border-2 border-yellow-200 shadow-lg">
                <h4 class="font-black text-gray-900 mb-3 text-sm flex items-center gap-2">
                    <i data-lucide="clock" class="w-5 h-5 text-yellow-600"></i>
                    Horário de Atendimento
                </h4>
                <div class="space-y-2">
                    <p class="text-sm text-gray-700 font-bold">Segunda a Sexta: <span class="text-yellow-700">09:00 às 18:00</span></p>
                    <p class="text-sm text-gray-700 font-bold">Sábado: <span class="text-yellow-700">09:00 às 13:00</span></p>
                </div>
            </div>
        </div>
    </div>

    <!-- MODAL IDIOMA -->
    <div id="modalLang" class="modal bg-gray-50">
        <div class="p-5 bg-white border-b flex justify-between items-center sticky top-0 z-20">
            <h3 class="font-bold text-gray-900 uppercase text-sm flex items-center gap-2"><i data-lucide="languages" class="w-4 h-4"></i> <span data-i18n="language">Idioma</span></h3>
            <button onclick="closeLangModal()" class="w-10 h-10 bg-gray-100 rounded-full flex items-center justify-center"><i data-lucide="x" class="w-4 h-4"></i></button>
        </div>
        <div class="p-5 space-y-3">
            <p class="text-sm text-gray-500" data-i18n="chooseLang">Escolha o idioma do site (padrão: Português).</p>
            <div class="grid grid-cols-3 gap-2">
                <button class="py-3 rounded-xl border text-sm font-bold" onclick="setLang('pt')" data-i18n="portuguese">Português</button>
                <button class="py-3 rounded-xl border text-sm font-bold" onclick="setLang('es')" data-i18n="spanish">Español</button>
                <button class="py-3 rounded-xl border text-sm font-bold" onclick="setLang('en')" data-i18n="english">English</button>
            </div>
        </div>
    </div>

    <div class="hero" id="hero">
        <div class="flex justify-between items-center mb-6">
            <div class="flex items-center gap-3">
                <button onclick="nav('news')" class="w-10 h-10 rounded-full bg-white/10 items-center justify-center text-white hidden" id="backBtn"><i data-lucide="arrow-left" class="w-5 h-5"></i></button>
                <div class="w-12 h-12 rounded-full bg-gradient-to-br from-blue-500 to-indigo-600 border-2 border-white/30 flex items-center justify-center text-white font-mono font-black text-lg shadow-lg"><?= strtoupper(substr($user['name']??'U',0,1)) ?></div>
                <div><p class="text-[10px] text-white/70 font-bold uppercase" data-i18n="hello">Olá,</p><p class="text-base font-black text-white truncate w-32"><?= htmlspecialchars($user['name']??'Usuario') ?> | # <?= ($user['id']) ?></p></div>
            </div>
            <div class="flex items-center gap-2">
                <button onclick="openSupportModal()" class="w-10 h-10 rounded-full bg-white/10 border border-white/20 flex items-center justify-center text-white hover:bg-white/20 transition backdrop-blur-sm"><i data-lucide="headphones" class="w-5 h-5"></i></button>
                <button onclick="openMusicModal()" class="w-10 h-10 rounded-full bg-white/10 border border-white/20 flex items-center justify-center text-white hover:bg-white/20 transition backdrop-blur-sm"><i data-lucide="music" class="w-5 h-5"></i></button>
                <button onclick="openLangModal()" class="w-10 h-10 rounded-full bg-white/10 border border-white/20 flex items-center justify-center text-white hover:bg-white/20 transition backdrop-blur-sm"><i data-lucide="languages" class="w-5 h-5"></i></button>
        </div>
        </div>
        
        <!-- Cards de Saldo Estilo Gringa -->
        <div class="grid grid-cols-2 gap-4 mb-6">
            <!-- Card Saldo Carteira -->
            <div class="bg-gradient-to-br from-green-500 via-emerald-500 to-teal-600 rounded-3xl p-5 shadow-2xl border-2 border-white/20 relative overflow-hidden group">
                <div class="absolute top-0 right-0 w-24 h-24 bg-white/10 rounded-full -translate-y-1/2 translate-x-1/2 blur-2xl group-hover:scale-150 transition-transform"></div>
                <div class="relative z-10">
                    <div class="flex items-center justify-between mb-3">
                        <div class="w-12 h-12 bg-white/20 backdrop-blur-md rounded-2xl flex items-center justify-center border border-white/30">
                            <i data-lucide="wallet" class="w-6 h-6 text-white"></i>
                        </div>
                    </div>
                    <p class="text-white/80 text-xs font-bold uppercase mb-1">Saldo da Carteira</p>
                    <h2 class="text-2xl font-black text-white mb-4" id="balDisplay">R$ <?= number_format($user['balance'], 2, ',', '.') ?></h2>
                    <button onclick="nav('withdraw')" class="w-full bg-yellow-400 hover:bg-yellow-500 text-gray-900 py-2.5 rounded-xl font-black text-xs uppercase shadow-lg active:scale-95 transition">
                        Retirada
                    </button>
        </div>
    </div>

            <!-- Card Saldo Poupança/Investimentos -->
            <div class="bg-gradient-to-br from-purple-500 via-pink-500 to-rose-600 rounded-3xl p-5 shadow-2xl border-2 border-white/20 relative overflow-hidden group">
                <div class="absolute top-0 right-0 w-24 h-24 bg-white/10 rounded-full -translate-y-1/2 translate-x-1/2 blur-2xl group-hover:scale-150 transition-transform"></div>
                <div class="relative z-10">
                    <div class="flex items-center justify-between mb-3">
                        <div class="w-12 h-12 bg-white/20 backdrop-blur-md rounded-2xl flex items-center justify-center border border-white/30">
                            <i data-lucide="piggy-bank" class="w-6 h-6 text-white"></i>
                        </div>
                    </div>
                    <p class="text-white/80 text-xs font-bold uppercase mb-1">Saldo de Poupança</p>
                    <h2 class="text-2xl font-black text-white mb-4">R$ <?= number_format($user['total_invested'] ?? 0, 2, ',', '.') ?></h2>
                    <button onclick="nav('deposit')" class="w-full relative overflow-hidden animate-deposit-pulse text-white py-2.5 rounded-xl font-black text-xs uppercase shadow-2xl active:scale-95 transition-all duration-300 group hover:scale-105 animate-deposit-shine border-2 border-white/30">
                        <!-- Efeito de brilho animado -->
                        <div class="absolute inset-0 bg-gradient-to-r from-transparent via-white/40 to-transparent -translate-x-full group-hover:translate-x-full transition-transform duration-1000"></div>
                        <!-- Efeito de pulso interno -->
                        <div class="absolute inset-0 bg-gradient-to-r from-yellow-400 via-orange-500 to-red-500 rounded-xl animate-ping opacity-30"></div>
                        <!-- Conteúdo do botão -->
                        <span class="relative z-10 flex items-center justify-center gap-2">
                            <i data-lucide="arrow-down-circle" class="w-4 h-4 group-hover:scale-125 group-hover:rotate-180 transition-all duration-300 drop-shadow-lg"></i>
                            <span class="drop-shadow-lg">💰 Depositar</span>
                            <i data-lucide="sparkles" class="w-4 h-4 group-hover:rotate-180 transition-transform duration-300 drop-shadow-lg"></i>
                        </span>
                        <!-- Partículas de brilho animadas -->
                        <div class="absolute top-1 left-3 w-2 h-2 bg-white rounded-full animate-ping shadow-lg" style="animation-delay: 0s;"></div>
                        <div class="absolute top-2 right-5 w-1.5 h-1.5 bg-white rounded-full animate-ping shadow-lg" style="animation-delay: 0.3s;"></div>
                        <div class="absolute bottom-1 left-6 w-1.5 h-1.5 bg-white rounded-full animate-ping shadow-lg" style="animation-delay: 0.6s;"></div>
                        <div class="absolute bottom-2 right-4 w-2 h-2 bg-white rounded-full animate-ping shadow-lg" style="animation-delay: 0.9s;"></div>
                        <!-- Efeito de borda brilhante -->
                        <div class="absolute inset-0 rounded-xl border-2 border-white/50 opacity-0 group-hover:opacity-100 transition-opacity duration-300"></div>
                    </button>
                </div>
            </div>
        </div>
        
    </div>

    <!-- Badge VIP integrado no header -->
    <div class="absolute top-4 right-4 z-10">
        <div class="bg-gradient-to-br from-yellow-400 via-yellow-500 to-orange-500 rounded-xl px-3 py-1.5 shadow-lg border border-white/20">
            <div class="flex items-center gap-1.5">
                <i data-lucide="crown" class="w-4 h-4 text-white"></i>
                <span class="text-xs font-black text-white">VIP <?= $user['vip_level'] ?></span>
            </div>
        </div>
    </div>

    <!-- Menu Top Horizontal (Restaurado) -->
    <div class="mx-5 -mt-8 relative z-10 bg-white rounded-2xl p-1.5 flex shadow-xl overflow-x-auto" id="mainTab">
        <button id="btn-news" onclick="tab('news')" class="flex-1 py-3 rounded-xl text-xs font-bold uppercase text-white bg-vip-blue shadow-md transition-all whitespace-nowrap min-w-[80px]">Início</button>
        <button id="btn-market" onclick="tab('market')" class="flex-1 py-3 rounded-xl text-xs font-bold uppercase text-gray-400 hover:bg-gray-50 transition-all whitespace-nowrap min-w-[80px]">Investir</button>
        <button id="btn-tasks" onclick="tab('tasks')" class="flex-1 py-3 rounded-xl text-xs font-bold uppercase text-gray-400 hover:bg-gray-50 transition-all whitespace-nowrap min-w-[80px]" data-i18n="tasks">Tarefas</button>
        <button id="btn-assets" onclick="tab('assets')" class="flex-1 py-3 rounded-xl text-xs font-bold uppercase text-gray-400 hover:bg-gray-50 transition-all whitespace-nowrap min-w-[80px]">Ativos</button>
        <button id="btn-team" onclick="tab('team')" class="flex-1 py-3 rounded-xl text-xs font-bold uppercase text-gray-400 hover:bg-gray-50 transition-all whitespace-nowrap min-w-[80px]">Equipe</button>
        <button id="btn-profile" onclick="tab('profile')" class="flex-1 py-3 rounded-xl text-xs font-bold uppercase text-gray-400 hover:bg-gray-50 transition-all whitespace-nowrap min-w-[80px]">Perfil</button>
    </div>

    <!-- Menu Bottom Fixo com VIP no Meio -->
    <div class="fixed bottom-0 left-0 right-0 bg-white border-t border-gray-200 shadow-2xl z-40 safe-area-bottom">
        <div class="max-w-xl mx-auto px-2 py-2">
            <div class="flex items-center justify-around">
                <button id="btn-news" onclick="tab('news')" class="flex flex-col items-center gap-1 py-2 px-3 rounded-xl transition-all menu-item">
                    <div class="w-6 h-6 flex items-center justify-center">
                        <i data-lucide="home" class="w-5 h-5 menu-icon"></i>
                    </div>
                    <span class="text-[9px] font-bold uppercase menu-label">Início</span>
                </button>
                <button id="btn-market" onclick="tab('market')" class="flex flex-col items-center gap-1 py-2 px-3 rounded-xl transition-all menu-item">
                    <div class="w-6 h-6 flex items-center justify-center">
                        <i data-lucide="trending-up" class="w-5 h-5 menu-icon"></i>
                    </div>
                    <span class="text-[9px] font-bold uppercase menu-label">Investir</span>
                </button>
                <button id="btn-vip-center" onclick="tab('profile')" class="flex flex-col items-center gap-1 py-2 px-4 rounded-2xl transition-all menu-item-vip relative -mt-6">
                    <div class="w-14 h-14 bg-gradient-to-br from-yellow-400 via-yellow-500 to-orange-500 rounded-2xl flex items-center justify-center shadow-lg border-2 border-white vip-icon-container">
                        <i data-lucide="crown" class="w-7 h-7 text-white vip-icon"></i>
                    </div>
                    <span class="text-[9px] font-black uppercase menu-label-vip">VIP <?= $user['vip_level'] ?></span>
                </button>
                <button id="btn-assets" onclick="tab('assets')" class="flex flex-col items-center gap-1 py-2 px-3 rounded-xl transition-all menu-item">
                    <div class="w-6 h-6 flex items-center justify-center">
                        <i data-lucide="wallet" class="w-5 h-5 menu-icon"></i>
                    </div>
                    <span class="text-[9px] font-bold uppercase menu-label">Ativos</span>
                </button>
                <button id="btn-team" onclick="tab('team')" class="flex flex-col items-center gap-1 py-2 px-3 rounded-xl transition-all menu-item">
                    <div class="w-6 h-6 flex items-center justify-center">
                        <i data-lucide="users" class="w-5 h-5 menu-icon"></i>
                    </div>
                    <span class="text-[9px] font-bold uppercase menu-label">Equipe</span>
                </button>
            </div>
        </div>
    </div>

    <div class="px-5 mt-6 pb-20">

        <div id="view-assets" class="tab-view pb-32">
            <?php if(empty($timerInvestments)): ?>
                <div class="flex flex-col items-center justify-center py-20 opacity-60">
                    <div class="w-20 h-20 bg-gradient-to-br from-gray-200 to-gray-300 rounded-full flex items-center justify-center mb-4 animate-pulse">
                        <i data-lucide="frown" class="w-10 h-10 text-gray-500"></i>
                    </div>
                    <h3 class="font-bold text-gray-600 text-lg mb-1">Que pena...</h3>
                    <p class="text-sm font-medium text-gray-400 text-center max-w-[200px]">Você ainda não tem investimentos ativos.</p>
                    <button onclick="tab('market')" class="mt-6 px-6 py-3 bg-gradient-to-r from-blue-600 to-indigo-600 text-white rounded-xl font-bold text-sm shadow-lg hover:shadow-xl transition-all hover:scale-105">
                        Ver Oportunidades
                    </button>
                </div>
            <?php else: ?>
                <div class="mb-8">
                    <h2 class="text-3xl font-black mb-2 bg-gradient-to-r from-green-600 via-emerald-600 to-teal-600 bg-clip-text text-transparent animate-fadeInUp" data-i18n="myInvestments">Meus Investimentos</h2>
                    <p class="text-sm text-gray-500">Acompanhe seus ativos em tempo real</p>
                </div>

                <button id="btnColeta" onclick="api('collect_all', {})" class="btn-collect w-full flex flex-col items-center justify-center gap-2 mb-8 py-5 rounded-2xl shadow-xl hover:shadow-2xl transition-all">
                    <div class="flex items-center gap-2">
                        <i data-lucide="download" class="w-5 h-5"></i>
                        <span id="labelColeta" data-i18n="collectEarnings" class="text-base font-black">Coletar Rendimentos</span>
                    </div>
                    <span id="timerColeta" class="text-xs opacity-80 font-mono tracking-widest">--:--:--</span>
                </button>

                <h3 class="text-sm font-black text-gray-800 uppercase mb-4 px-1" data-i18n="activeOperations">Ativos em Operação</h3>
                <?php foreach($timerInvestments as $inv): 
                    $pct = min(100, ($inv['total_paid'] / $inv['total_return']) * 100);
                    $remaining = $inv['total_return'] - $inv['total_paid'];
                    $daysRemaining = $inv['duration_days'] - (int)((time() - strtotime($inv['created_at'])) / 86400);
                    $daysRemaining = max(0, $daysRemaining);
                    $dailyEarned = $inv['type'] === 'diary' ? $inv['renda_diaria_fixa'] : 0;
                    $nextPayment = $inv['type'] === 'diary' ? strtotime($inv['last_paid_at'] ?? $inv['created_at']) + 86400 : null;
                ?>
                <div class="bg-white rounded-2xl p-6 mb-6 shadow-lg border-2 border-gray-100 hover:border-blue-300 transition-all">
                    <div class="flex gap-4 items-start mb-5">
                        <img src="<?= $inv['prod_img'] ?>" class="w-20 h-20 rounded-2xl object-cover shadow-md">
                        <div class="flex-1">
                            <h4 class="font-black text-lg text-gray-900 mb-1"><?= htmlspecialchars($inv['name']) ?></h4>
                            <div class="flex items-center gap-2 mb-2">
                                <span class="px-2 py-1 bg-blue-100 text-blue-700 rounded-lg text-[9px] font-black uppercase">
                                    <?= $inv['type'] === 'diary' ? 'Renda Diária' : 'Ciclo Final' ?>
                                </span>
                                <span class="text-[9px] text-gray-500">ref</span>
                        </div>
                    </div>
                    </div>

                    <div class="grid grid-cols-2 gap-4 mb-5">
                        <div class="bg-gradient-to-br from-blue-50 to-blue-100 p-4 rounded-xl border border-blue-200">
                            <p class="text-[9px] text-blue-600 font-bold uppercase mb-1">Investido</p>
                            <p class="text-xl font-black text-blue-900">R$ <?= number_format($inv['invested_amount'], 2, ',', '.') ?></p>
                        </div>
                        <div class="bg-gradient-to-br from-green-50 to-green-100 p-4 rounded-xl border border-green-200">
                            <p class="text-[9px] text-green-600 font-bold uppercase mb-1">Retorno Total</p>
                            <p class="text-xl font-black text-green-900">R$ <?= number_format($inv['total_return'], 2, ',', '.') ?></p>
                        </div>
                        <div class="bg-gradient-to-br from-purple-50 to-purple-100 p-4 rounded-xl border border-purple-200">
                            <p class="text-[9px] text-purple-600 font-bold uppercase mb-1">Já Recebido</p>
                            <p class="text-xl font-black text-purple-900">R$ <?= number_format($inv['total_paid'], 2, ',', '.') ?></p>
                        </div>
                        <div class="bg-gradient-to-br from-orange-50 to-orange-100 p-4 rounded-xl border border-orange-200">
                            <p class="text-[9px] text-orange-600 font-bold uppercase mb-1">A Receber</p>
                            <p class="text-xl font-black text-orange-900">R$ <?= number_format($remaining, 2, ',', '.') ?></p>
                        </div>
                    </div>

                    <?php if($inv['type'] === 'diary' && $dailyEarned > 0): ?>
                    <div class="bg-indigo-50 border border-indigo-200 rounded-xl p-4 mb-5">
                        <div class="flex items-center justify-between">
                            <div>
                                <p class="text-[9px] text-indigo-600 font-bold uppercase mb-1">Rendimento Diário</p>
                                <p class="text-lg font-black text-indigo-900">R$ <?= number_format($dailyEarned, 2, ',', '.') ?></p>
                            </div>
                            <div class="text-right">
                                <p class="text-[9px] text-indigo-600 font-bold uppercase mb-1">Dias Restantes</p>
                                <p class="text-lg font-black text-indigo-900"><?= $daysRemaining ?></p>
                            </div>
                        </div>
                        <?php if($nextPayment && $nextPayment > time()): ?>
                        <div class="mt-3 pt-3 border-t border-indigo-200">
                            <p class="text-[9px] text-indigo-600 font-bold uppercase mb-1">Próximo Pagamento</p>
                            <p class="text-sm font-black text-indigo-900" id="nextPay_<?= $inv['id'] ?>"><?= date('d/m/Y H:i', $nextPayment) ?></p>
                        </div>
                        <?php endif; ?>
                    </div>
                    <?php endif; ?>

                    <div class="mb-4">
                        <div class="flex justify-between items-center mb-2">
                            <span class="text-xs font-bold text-gray-600 uppercase">Progresso do Retorno</span>
                            <span class="text-sm font-black text-gray-900"><?= round($pct) ?>%</span>
                        </div>
                        <div class="w-full bg-gray-100 h-3 rounded-full overflow-hidden border border-gray-200">
                            <div style="width: <?= $pct ?>%" class="h-full bg-gradient-to-r from-blue-500 to-indigo-600 rounded-full transition-all duration-1000 relative">
                                <div class="absolute inset-0 bg-gradient-to-r from-transparent via-white/30 to-transparent animate-shimmer"></div>
                            </div>
                        </div>
                    </div>

                    <div class="text-xs text-gray-500 space-y-1">
                        <p><strong>Iniciado em:</strong> <?= date('d/m/Y H:i', strtotime($inv['created_at'])) ?></p>
                        <p><strong>Duração:</strong> <?= $inv['duration_days'] ?> dias</p>
                        <?php if($inv['last_paid_at']): ?>
                        <p><strong>Último pagamento:</strong> <?= date('d/m/Y H:i', strtotime($inv['last_paid_at'])) ?></p>
                        <?php endif; ?>
                    </div>
                </div>
                <?php endforeach; ?>

                <h3 class="text-xs font-black text-gray-800 uppercase mt-8 mb-4 px-1">Histórico de Resgates</h3>
                <div class="bg-white rounded-[24px] overflow-hidden shadow-sm border border-gray-100 mb-8">
                    <?php if(empty($extratoColetas)): ?>
                        <p class="p-6 text-center text-xs text-gray-400 font-bold uppercase">Sem movimentos registrados</p>
                    <?php else: foreach($extratoColetas as $c): ?>
                        <div class="p-4 border-b border-gray-50 flex justify-between items-center last:border-0">
                            <div>
                                <p class="text-xs font-bold text-gray-800 truncate w-40"><?= $c['name_investment'] ?></p>
                                <p class="text-[9px] text-gray-400 uppercase tracking-tighter"><?= date('d/m/Y H:i', strtotime($c['created_at'])) ?></p>
                            </div>
                            <span class="text-green-500 font-black font-oswald text-sm">+R$ <?= number_format($c['value'], 2, ',', '.') ?></span>
                        </div>
                    <?php endforeach; endif; ?>
                </div>

                <?php if(!empty($meusEncerrados)): ?>
                    <h3 class="text-xs font-black text-gray-400 uppercase mb-4 px-1">Planos Finalizados</h3>
                    <div class="space-y-2 opacity-60 grayscale mb-10">
                        <?php foreach($meusEncerrados as $enc): ?>
                            <div class="bg-gray-100 rounded-2xl p-4 flex justify-between items-center text-xs border border-gray-200">
                                <span class="font-bold text-gray-600"><?= $enc['name'] ?></span>
                                <span class="font-black text-gray-500 uppercase text-[9px] tracking-widest">Pago 100%</span>
                            </div>
                        <?php endforeach; ?>
                    </div>
                <?php endif; ?>
            <?php endif; ?>
        </div>

        <div id="view-news" class="tab-view active pb-32">
            <div class="mb-8 text-center">
                <!--    <h2 class="text-3xl font-black mb-2 bg-gradient-to-r from-blue-600 via-purple-600 to-pink-600 bg-clip-text text-transparent animate-fadeInUp" data-i18n="newsTitle">Notícias e Avisos</h2>-->
                <!--<p class="text-sm text-gray-500">Fique por dentro das últimas novidades!</p>-->
            </div>
            <?php if(!empty($announces)): ?>
                <div class="space-y-4 mb-6">
                    <?php foreach($announces as $index => $news): $nData = htmlspecialchars(json_encode($news)); ?>
                    <div onclick='openNewsModal(<?= $nData ?>)' class="news-card bg-white rounded-2xl border-2 border-gray-200 shadow-lg hover:shadow-2xl relative overflow-hidden cursor-pointer active:scale-95 transition-all duration-300 hover:-translate-y-1 group">
                        <!-- Efeito de brilho -->
                        <div class="absolute inset-0 bg-gradient-to-r from-transparent via-blue-500/5 to-transparent opacity-0 group-hover:opacity-100 transition-opacity duration-500"></div>
                        
                        <div class="h-48 bg-gradient-to-br from-blue-500 to-indigo-600 mb-4 rounded-t-2xl overflow-hidden relative">
                            <img src="<?= $news['img'] ?? 'https://placehold.co/600x400?text=News' ?>" class="w-full h-full object-cover group-hover:scale-110 transition-transform duration-500">
                            <div class="absolute inset-0 bg-gradient-to-t from-black/60 via-black/20 to-transparent"></div>
                            <div class="absolute top-3 right-3 bg-white/20 backdrop-blur-md p-2 rounded-full border border-white/30">
                                <i data-lucide="megaphone" class="w-5 h-5 text-white"></i>
                        </div>
                            <div class="absolute bottom-3 left-3 right-3">
                                <div class="inline-flex items-center gap-2 bg-white/20 backdrop-blur-md px-3 py-1.5 rounded-lg border border-white/30">
                                    <i data-lucide="calendar" class="w-4 h-4 text-white"></i>
                                    <span class="text-xs font-bold text-white"><?= date('d/m/Y', strtotime($news['created_at'])) ?></span>
                                </div>
                            </div>
                        </div>
                        
                        <div class="p-5 relative z-10">
                            <h4 class="font-black text-lg text-gray-900 mb-2 leading-tight group-hover:text-blue-600 transition-colors"><?= htmlspecialchars($news['title']) ?></h4>
                            <p class="text-sm text-gray-600 line-clamp-3 leading-relaxed mb-3"><?= htmlspecialchars($news['description']) ?></p>
                            <div class="flex items-center gap-2 text-blue-600 font-bold text-xs">
                                <span>Ler mais</span>
                                <i data-lucide="arrow-right" class="w-4 h-4 group-hover:translate-x-1 transition-transform"></i>
                            </div>
                        </div>
                    </div>
                    <?php endforeach; ?>
                </div>
            <?php else: ?>
                <div class="text-center py-20">
                    <div class="w-20 h-20 bg-gray-100 rounded-full flex items-center justify-center mx-auto mb-4">
                        <i data-lucide="bell-off" class="w-10 h-10 text-gray-400"></i>
                    </div>
                    <p class="text-gray-400 text-sm font-bold">Sem novidades no momento.</p>
                </div>
            <?php endif; ?>
            <button onclick="tab('market')" class="w-full bg-gradient-to-r from-blue-600 to-indigo-600 text-white py-4 rounded-xl font-black uppercase shadow-lg shadow-blue-500/30 flex items-center justify-center gap-2 hover:shadow-xl transition-all" data-i18n="goToMarket">
                <i data-lucide="trending-up" class="w-5 h-5"></i>
                Ir ao Mercado
                <i data-lucide="arrow-right" class="w-4 h-4"></i>
            </button>
        </div>

        <!-- Modal de Notícia -->
        <div id="newsModal" class="modal bg-gray-50">
            <div class="bg-white min-h-screen">
                <div class="sticky top-0 bg-white border-b border-gray-200 p-5 flex justify-between items-center z-20">
                    <h3 class="font-black text-gray-900 text-lg">Notícia</h3>
                    <button onclick="closeNewsModal()" class="w-10 h-10 bg-gray-100 rounded-full flex items-center justify-center hover:bg-gray-200 transition">
                        <i data-lucide="x" class="w-5 h-5"></i>
                    </button>
                </div>
                <div class="p-5">
                    <div id="newsModalImg" class="h-64 bg-gradient-to-br from-blue-500 to-indigo-600 rounded-2xl mb-6 overflow-hidden relative">
                        <img id="newsModalImgSrc" src="" class="w-full h-full object-cover" alt="">
                        <div class="absolute top-4 right-4 bg-white/20 backdrop-blur-md p-2 rounded-full border border-white/30">
                            <i data-lucide="megaphone" class="w-5 h-5 text-white"></i>
                        </div>
                    </div>
                    <div id="newsModalDate" class="text-xs text-gray-500 font-bold mb-3 flex items-center gap-2">
                        <i data-lucide="calendar" class="w-4 h-4"></i>
                        <span></span>
                    </div>
                    <h2 id="newsModalTitle" class="text-2xl font-black text-gray-900 mb-4 leading-tight"></h2>
                    <div id="newsModalText" class="text-gray-700 leading-relaxed space-y-3"></div>
                </div>
            </div>
        </div>

        <style>
    /* ========================================
    ESTÉTICA GRINGA 3.0 - ANIMATED DATA CARD
    ======================================== */

    .tab-view {
        display: none;
    }
    .tab-view.active {
        display: block;
    }

    @keyframes chart-up {
        0% { transform: scaleY(0.2); opacity: 0; }
        100% { transform: scaleY(1); opacity: 1; }
    }

    @keyframes scan-line {
        0% { top: 0%; opacity: 0; }
        50% { opacity: 0.5; }
        100% { top: 100%; opacity: 0; }
    }

    .card-gringa-v3 {
        background: #ffffff;
        border-radius: 2.5rem;
        transition: all 0.6s cubic-bezier(0.16, 1, 0.3, 1);
        border: 1px solid rgba(0,0,0,0.03);
        overflow: hidden;
        display: flex;
        flex-direction: column;
        height: 100%;
    }

    .card-gringa-v3:hover {
        transform: translateY(-12px);
        box-shadow: 0 40px 80px -15px rgba(0, 0, 0, 0.12);
    }

    .dashboard-area {
        height: 260px;
        position: relative;
        margin: 12px;
        border-radius: 2rem;
        overflow: hidden;
        background: #000;
    }

    .scan-effect {
        position: absolute;
        left: 0; width: 100%; height: 2px;
        background: linear-gradient(90deg, transparent, #3b82f6, transparent);
        animation: scan-line 3.5s linear infinite;
        z-index: 15;
    }

    .live-status {
        position: absolute;
        top: 20px;
        left: 20px;
        background: rgba(0, 0, 0, 0.5);
        backdrop-filter: blur(12px);
        border: 1px solid rgba(255, 255, 255, 0.1);
        padding: 6px 14px;
        border-radius: 14px;
        z-index: 30;
    }

    /* Badge Dinâmica sobre a Imagem */
    .type-indicator {
        display: inline-flex;
        align-items: center;
        gap: 6px;
        padding: 4px 10px;
        background: rgba(59, 130, 246, 0.15);
        color: #60a5fa;
        text-transform: uppercase;
        font-size: 9px;
        font-weight: 900;
        letter-spacing: 1px;
        border-radius: 8px;
        border: 1px solid rgba(59, 130, 246, 0.3);
        margin-bottom: 8px;
    }

    .btn-main-action {
        background: #0f172a;
        transition: all 0.4s cubic-bezier(0.4, 0, 0.2, 1);
    }

    .btn-main-action:hover {
        background: #3b82f6;
        transform: scale(1.02);
        box-shadow: 0 10px 20px rgba(59, 130, 246, 0.3);
    }

    .price-display {
        font-family: 'Inter', sans-serif;
        font-weight: 900;
        letter-spacing: -1.5px;
    }

    .product-card {
        animation: fadeInUp 0.8s cubic-bezier(0.4, 0, 0.2, 1);
        position: relative;
    }
    
    .product-card::before {
        content: '';
        position: absolute;
        inset: -2px;
        border-radius: 1.5rem;
        padding: 2px;
        background: linear-gradient(45deg, #3b82f6, #8b5cf6, #ec4899, #3b82f6);
        background-size: 300% 300%;
        -webkit-mask: linear-gradient(#fff 0 0) content-box, linear-gradient(#fff 0 0);
        -webkit-mask-composite: xor;
        mask: linear-gradient(#fff 0 0) content-box, linear-gradient(#fff 0 0);
        mask-composite: exclude;
        opacity: 0;
        transition: opacity 0.3s;
        animation: gradient-rotate 3s linear infinite;
    }
    
    .product-card:hover::before {
        opacity: 1;
    }
    
    @keyframes gradient-rotate {
        0% {
            background-position: 0% 50%;
        }
        50% {
            background-position: 100% 50%;
        }
        100% {
            background-position: 0% 50%;
        }
    }

    @keyframes fadeInUp {
        from {
            opacity: 0;
            transform: translateY(30px);
        }
        to {
            opacity: 1;
            transform: translateY(0);
        }
    }

    .vip-badge-container {
        animation: pulse 2s ease-in-out infinite;
    }

    @keyframes pulse {
        0%, 100% {
            transform: scale(1);
        }
        50% {
            transform: scale(1.05);
        }
    }

    @keyframes shimmer {
        0% {
            transform: translateX(-100%);
        }
        100% {
            transform: translateX(100%);
        }
    }

    @keyframes chart-up {
        from {
            transform: scaleY(0);
            opacity: 0;
        }
        to {
            transform: scaleY(1);
            opacity: 1;
        }
    }

    @keyframes float {
        0%, 100% {
            transform: translateY(0) translateX(0) rotate(0deg);
            opacity: 0.3;
        }
        25% {
            transform: translateY(-15px) translateX(5px) rotate(90deg);
            opacity: 0.7;
        }
        50% {
            transform: translateY(-25px) translateX(10px) rotate(180deg);
            opacity: 1;
        }
        75% {
            transform: translateY(-15px) translateX(5px) rotate(270deg);
            opacity: 0.7;
        }
    }
    
    @keyframes scan-line {
        0% {
            transform: translateY(-100%);
        }
        100% {
            transform: translateY(100vh);
        }
    }
    
    @keyframes glow-pulse {
        0%, 100% {
            box-shadow: 0 0 20px rgba(59, 130, 246, 0.5), 0 0 40px rgba(59, 130, 246, 0.3);
        }
        50% {
            box-shadow: 0 0 30px rgba(59, 130, 246, 0.8), 0 0 60px rgba(59, 130, 246, 0.5);
        }
    }
    
    @keyframes rotate-slow {
        from {
            transform: rotate(0deg);
        }
        to {
            transform: rotate(360deg);
        }
    }
    
    @keyframes sparkle {
        0%, 100% {
            opacity: 0;
            transform: scale(0);
        }
        50% {
            opacity: 1;
            transform: scale(1);
        }
    }
    
    .animate-scan-line {
        animation: scan-line 3s linear infinite;
    }
    
    .animate-glow-pulse {
        animation: glow-pulse 2s ease-in-out infinite;
    }
    
    .animate-sparkle {
        animation: sparkle 1.5s ease-in-out infinite;
    }

    @keyframes fadeInUp {
        from {
            opacity: 0;
            transform: translateY(30px);
        }
        to {
            opacity: 1;
            transform: translateY(0);
        }
    }

    .animate-shimmer {
        animation: shimmer 2s infinite;
    }

    .animate-float {
        animation: float 3s ease-in-out infinite;
    }

    .animate-fadeInUp {
        animation: fadeInUp 0.6s ease-out both;
    }
    
    @keyframes depositPulse {
        0%, 100% {
            box-shadow: 0 0 20px rgba(251, 191, 36, 0.6), 0 0 40px rgba(251, 191, 36, 0.4), 0 0 60px rgba(251, 191, 36, 0.2);
            transform: scale(1);
        }
        50% {
            box-shadow: 0 0 30px rgba(251, 191, 36, 0.9), 0 0 60px rgba(251, 191, 36, 0.6), 0 0 90px rgba(251, 191, 36, 0.4);
            transform: scale(1.02);
        }
    }
    
    @keyframes depositShine {
        0% {
            background-position: -200% center;
        }
        100% {
            background-position: 200% center;
        }
    }
    
    .animate-deposit-pulse {
        animation: depositPulse 2s ease-in-out infinite;
    }
    
    .animate-deposit-shine {
        background: linear-gradient(90deg, 
            rgba(251, 191, 36, 1) 0%, 
            rgba(249, 115, 22, 1) 25%, 
            rgba(239, 68, 68, 1) 50%, 
            rgba(249, 115, 22, 1) 75%, 
            rgba(251, 191, 36, 1) 100%);
        background-size: 200% auto;
        animation: depositShine 3s linear infinite;
    }
</style>

        <div id="view-market" class="tab-view max-w-7xl mx-auto px-4 py-6 pb-32 relative overflow-hidden">
            <!-- Background Animado -->
            <div class="fixed inset-0 -z-10 pointer-events-none">
                <div class="absolute top-0 left-1/4 w-96 h-96 bg-blue-400/10 rounded-full blur-3xl animate-pulse"></div>
                <div class="absolute top-1/3 right-1/4 w-96 h-96 bg-indigo-400/10 rounded-full blur-3xl animate-pulse" style="animation-delay: 1s;"></div>
                <div class="absolute bottom-0 left-1/2 w-96 h-96 bg-purple-400/10 rounded-full blur-3xl animate-pulse" style="animation-delay: 2s;"></div>
            </div>
            
            <!-- Partículas de Fundo -->
            <div class="fixed inset-0 -z-10 pointer-events-none">
                <?php for($i = 0; $i < 20; $i++): ?>
                <div class="absolute w-1 h-1 bg-blue-400/30 rounded-full animate-float" 
                     style="top: <?= rand(0, 100) ?>%; left: <?= rand(0, 100) ?>%; animation-delay: <?= $i * 0.3 ?>s; animation-duration: <?= 4 + rand(0, 3) ?>s;"></div>
                <?php endfor; ?>
            </div>
            
            <div class="mb-8 text-center relative z-10">
                <!--<h2 class="text-4xl font-black mb-2 bg-gradient-to-r from-blue-600 via-indigo-600 to-purple-600 bg-clip-text text-transparent animate-fadeInUp drop-shadow-lg" data-i18n="investmentOpportunities">Oportunidades de Investimento</h2>-->
                <!--<p class="text-sm text-gray-500 animate-fadeInUp" style="animation-delay: 0.1s;">Escolha o melhor plano para você e comece a lucrar hoje!</p>-->
                
                <!-- Badge de Pontos Disponíveis -->
                <?php if($userPoints > 0): ?>
                <div class="mt-4 inline-flex items-center gap-2 bg-gradient-to-r from-purple-500 to-pink-500 text-white px-6 py-3 rounded-full shadow-xl border-2 border-white/30 animate-pulse">
                    <i data-lucide="gift" class="w-5 h-5"></i>
                    <span class="font-black"><?= number_format($userPoints, 0, ',', '.') ?> Pontos Disponíveis</span>
                </div>
                <?php endif; ?>
            </div>
    <div class="grid grid-cols-1 gap-8">
        <?php foreach($products as $index => $p): 
            $total = $p['total_purchases'] + $p['available']; 
            $pct = $total > 0 ? ($p['total_purchases'] / $total) * 100 : 0; 
            $details = htmlspecialchars(json_encode($p)); 
            $isDiary = $p['type'] == 'diary';
            $profitPct = $p['value'] > 0 ? (($p['total_return'] - $p['value']) / $p['value']) * 100 : 0;
            
            // Verificar se pode comprar com pontos
            // Preço em pontos = valor do produto * 100 (porque 100 pontos = R$ 1,00)
            $userPoints = (int)($user['qtd_points'] ?? 0);
            $productPriceInPoints = (int)($p['value'] * 100); // Preço em pontos
            $productPointsReward = (int)($p['qtd_points'] ?? 0); // Pontos que o usuário ganha ao comprar com dinheiro
            $canBuyWithPoints = $userPoints >= $productPriceInPoints;
            
            // Verificar limites de compra
            $stmtVerify = $pdo->prepare("SELECT COUNT(*) FROM investments WHERE product_id = ? AND user_id = ?");
            $stmtVerify->execute([$p['id'], $user['id']]);
            $totalPurchased = $stmtVerify->fetchColumn();
            $canBuy = $totalPurchased < $p['limit_purchase'] && $p['total_purchases'] < $p['available'];
        ?>
        <div class="product-card bg-white rounded-3xl overflow-hidden shadow-xl border-2 <?= $canBuyWithPoints ? 'border-purple-400 ring-2 ring-purple-200' : 'border-gray-100' ?> hover:border-blue-400 transition-all duration-300 hover:shadow-2xl hover:-translate-y-2 group relative animate-fadeInUp" style="animation-delay: <?= $index * 0.1 ?>s;" data-product-points="<?= $productPriceInPoints ?>" data-product-id="<?= $p['id'] ?>">
            <!-- Efeitos de Luz Animados Intensos -->
            <div class="absolute inset-0 opacity-0 group-hover:opacity-100 transition-opacity duration-500 pointer-events-none">
                <div class="absolute top-0 left-0 w-48 h-48 bg-blue-400/30 rounded-full blur-3xl -translate-x-1/2 -translate-y-1/2 animate-pulse"></div>
                <div class="absolute bottom-0 right-0 w-48 h-48 bg-indigo-400/30 rounded-full blur-3xl translate-x-1/2 translate-y-1/2 animate-pulse" style="animation-delay: 0.5s;"></div>
                <div class="absolute top-1/2 left-1/2 w-32 h-32 bg-purple-400/20 rounded-full blur-2xl -translate-x-1/2 -translate-y-1/2 animate-ping"></div>
                <div class="absolute top-1/4 right-1/4 w-24 h-24 bg-cyan-400/15 rounded-full blur-xl animate-pulse" style="animation-delay: 1s;"></div>
                <div class="absolute bottom-1/4 left-1/4 w-28 h-28 bg-pink-400/15 rounded-full blur-xl animate-pulse" style="animation-delay: 1.5s;"></div>
            </div>
            
            <!-- Scan Line Effect -->
            <div class="absolute inset-0 opacity-0 group-hover:opacity-100 transition-opacity duration-700 pointer-events-none overflow-hidden">
                <div class="absolute top-0 left-0 right-0 h-1 bg-gradient-to-r from-transparent via-white/60 to-transparent animate-scan-line"></div>
            </div>
            
            <!-- Partículas Flutuantes Intensas -->
            <div class="absolute inset-0 opacity-0 group-hover:opacity-100 transition-opacity duration-700 pointer-events-none">
                <?php for($i = 0; $i < 8; $i++): ?>
                <div class="absolute w-2 h-2 bg-blue-400 rounded-full animate-float opacity-60" 
                     style="top: <?= rand(10, 90) ?>%; left: <?= rand(10, 90) ?>%; animation-delay: <?= $i * 0.2 ?>s; animation-duration: <?= 3 + rand(0, 2) ?>s;"></div>
                <?php endfor; ?>
                <?php for($i = 0; $i < 5; $i++): ?>
                <div class="absolute w-1.5 h-1.5 bg-indigo-400 rounded-full animate-float opacity-50" 
                     style="top: <?= rand(10, 90) ?>%; left: <?= rand(10, 90) ?>%; animation-delay: <?= $i * 0.3 ?>s; animation-duration: <?= 4 + rand(0, 2) ?>s;"></div>
                <?php endfor; ?>
                <?php for($i = 0; $i < 3; $i++): ?>
                <div class="absolute w-1 h-1 bg-purple-400 rounded-full animate-float opacity-40" 
                     style="top: <?= rand(10, 90) ?>%; left: <?= rand(10, 90) ?>%; animation-delay: <?= $i * 0.4 ?>s; animation-duration: <?= 5 + rand(0, 2) ?>s;"></div>
                <?php endfor; ?>
            </div>
            
            <!-- Badge de Pontos (sempre disponível para compra com pontos) -->
            <!--<div class="absolute top-4 left-4 z-20 <?= $canBuyWithPoints ? 'animate-pulse' : '' ?>">-->
            <!--    <div class="bg-gradient-to-r from-purple-500 via-pink-500 to-rose-500 text-white px-4 py-2 rounded-full shadow-2xl border-2 border-white/30 backdrop-blur-sm flex items-center gap-2">-->
            <!--        <i data-lucide="gift" class="w-4 h-4"></i>-->
            <!--        <span class="text-xs font-black"><?= number_format($productPriceInPoints, 0, ',', '.') ?> pontos</span>-->
            <!--        <?php if($canBuyWithPoints): ?>-->
            <!--            <span class="text-[8px] bg-white/30 px-2 py-0.5 rounded-full font-bold">DISPONÍVEL</span>-->
            <!--        <?php endif; ?>-->
            <!--    </div>-->
            <!--</div>-->
            
            <!-- Header com Imagem Animada - Estilo Gringa Ultra Animado -->
            <div class="relative h-64 overflow-hidden bg-gradient-to-br from-blue-500 via-blue-600 to-indigo-700 animate-glow-pulse">
                <!-- Efeito de fundo animado -->
                <div class="absolute inset-0 bg-gradient-to-br from-blue-400/30 via-indigo-500/30 to-purple-500/30 animate-pulse"></div>
                <div class="absolute inset-0 bg-black/20 group-hover:bg-black/10 transition-all"></div>
                
                <!-- Imagem com múltiplos efeitos -->
                <img src="<?= $p['img'] ?>" class="w-full h-full object-cover group-hover:scale-125 transition-transform duration-1000" alt="<?= htmlspecialchars($p['name']) ?>">
                
                <!-- Efeito de brilho intenso na imagem -->
                <div class="absolute inset-0 bg-gradient-to-r from-transparent via-white/20 to-transparent -translate-x-full group-hover:translate-x-full transition-transform duration-1500"></div>
                
                <!-- Efeito de brilho rotativo -->
                <div class="absolute inset-0 bg-gradient-conic from-transparent via-white/10 to-transparent opacity-0 group-hover:opacity-100 transition-opacity duration-500" style="animation: rotate-slow 8s linear infinite;"></div>
                
                <!-- Sparkles animados -->
                <div class="absolute top-1/4 left-1/4 w-3 h-3 bg-white rounded-full animate-sparkle opacity-0 group-hover:opacity-100" style="animation-delay: 0s;"></div>
                <div class="absolute top-1/3 right-1/3 w-2 h-2 bg-yellow-300 rounded-full animate-sparkle opacity-0 group-hover:opacity-100" style="animation-delay: 0.3s;"></div>
                <div class="absolute bottom-1/4 left-1/3 w-2.5 h-2.5 bg-cyan-300 rounded-full animate-sparkle opacity-0 group-hover:opacity-100" style="animation-delay: 0.6s;"></div>
                <div class="absolute bottom-1/3 right-1/4 w-2 h-2 bg-pink-300 rounded-full animate-sparkle opacity-0 group-hover:opacity-100" style="animation-delay: 0.9s;"></div>
                
                <!-- Badge de Percentual (estilo gringa) -->
                <?php if($profitPct > 0): ?>
                <div class="absolute top-4 right-4 bg-red-500 text-white px-3 py-1.5 rounded-lg shadow-xl z-10 border-2 border-white/30">
                    <p class="text-lg font-black"><?= number_format($profitPct, 1) ?>%</p>
                </div>
                <?php endif; ?>
                
                <!-- Badge Animado -->
                <div class="absolute top-4 left-4 flex items-center gap-2 bg-white/95 backdrop-blur-sm px-3 py-1.5 rounded-full shadow-lg z-10">
                    <span class="relative flex h-2 w-2">
                        <span class="animate-ping absolute inline-flex h-full w-full rounded-full bg-green-400 opacity-75"></span>
                        <span class="relative inline-flex rounded-full h-2 w-2 bg-green-500"></span>
                    </span>
                    <span class="text-[9px] font-black text-gray-900 uppercase">Ativo</span>
                </div>

                <!-- Timer (se aplicável) -->
                <?php if(!$isDiary): ?>
                <div class="absolute top-16 left-4 bg-black/60 backdrop-blur-md px-3 py-2 rounded-lg border border-white/20 z-10">
                    <p class="text-xs font-black text-white"><?= $p['total_days'] ?> dias</p>
                </div>
                <?php endif; ?>

                <!-- Título do Produto -->
                <div class="absolute bottom-0 left-0 right-0 bg-gradient-to-t from-black/80 via-black/40 to-transparent p-6">
                    <h3 class="text-white text-3xl font-black mb-2 drop-shadow-2xl"><?= htmlspecialchars($p['name']) ?></h3>
                    <div class="flex items-center gap-3">
                        <div class="inline-flex items-center gap-2 bg-white/20 backdrop-blur-md px-3 py-1.5 rounded-lg border border-white/30">
                            <i data-lucide="<?= $isDiary ? 'calendar-check' : 'repeat' ?>" class="w-4 h-4 text-white"></i>
                            <span class="text-[10px] font-black text-white uppercase"><?= $isDiary ? 'Renda Diária' : 'Ciclo Final' ?></span>
                    </div>
                    </div>
                </div>

                <!-- Botão Detalhes -->
                <button onclick='openDetails(<?= $details ?>)' class="absolute top-4 right-4 w-10 h-10 bg-white/20 hover:bg-white/30 backdrop-blur-md rounded-xl flex items-center justify-center text-white transition-all border border-white/30 hover:scale-110 z-20">
                    <i data-lucide="info" class="w-5 h-5"></i>
                </button>
            </div>

            <!-- Conteúdo -->
            <div class="p-8">
                <!-- Informações Principais em Grid com Animações -->
                <div class="grid grid-cols-3 gap-4 mb-6">
                    <div class="text-center bg-gradient-to-br from-blue-50 to-blue-100 p-4 rounded-xl border-2 border-blue-200 hover:scale-105 transition-transform group/item relative overflow-hidden">
                        <div class="absolute inset-0 bg-gradient-to-r from-blue-400/0 via-blue-400/20 to-blue-400/0 translate-x-[-100%] group-hover/item:translate-x-[100%] transition-transform duration-1000"></div>
                        <p class="text-[9px] text-blue-600 font-bold uppercase mb-1 relative z-10">Retorno Diário</p>
                        <p class="text-xl font-black text-blue-700 relative z-10">R$ <?= number_format($p['daily_return'],2,',','.') ?></p>
                        <div class="absolute top-2 right-2 w-8 h-8 bg-blue-200/50 rounded-full blur-xl animate-pulse"></div>
                    </div>
                    <div class="text-center bg-gradient-to-br from-indigo-50 to-indigo-100 p-4 rounded-xl border-2 border-indigo-200 hover:scale-105 transition-transform group/item relative overflow-hidden">
                        <div class="absolute inset-0 bg-gradient-to-r from-indigo-400/0 via-indigo-400/20 to-indigo-400/0 translate-x-[-100%] group-hover/item:translate-x-[100%] transition-transform duration-1000"></div>
                        <p class="text-[9px] text-indigo-600 font-bold uppercase mb-1 relative z-10">Período</p>
                        <p class="text-xl font-black text-indigo-700 relative z-10"><?= $p['total_days'] ?> dias</p>
                        <div class="absolute top-2 right-2 w-8 h-8 bg-indigo-200/50 rounded-full blur-xl animate-pulse" style="animation-delay: 0.2s;"></div>
                    </div>
                    <div class="text-center bg-gradient-to-br from-green-50 to-green-100 p-4 rounded-xl border-2 border-green-200 hover:scale-105 transition-transform group/item relative overflow-hidden">
                        <div class="absolute inset-0 bg-gradient-to-r from-green-400/0 via-green-400/20 to-green-400/0 translate-x-[-100%] group-hover/item:translate-x-[100%] transition-transform duration-1000"></div>
                        <p class="text-[9px] text-green-600 font-bold uppercase mb-1 relative z-10">Ganhos Totais</p>
                        <p class="text-xl font-black text-green-700 relative z-10">R$ <?= number_format($p['total_return'],0,',','.') ?></p>
                        <div class="absolute top-2 right-2 w-8 h-8 bg-green-200/50 rounded-full blur-xl animate-pulse" style="animation-delay: 0.4s;"></div>
                    </div>
                </div>
                
                <!-- Card de Pontos Gerados (apenas se o produto dá pontos ao comprar com dinheiro) -->
                <?php if($productPointsReward > 0): ?>
                <div class="mb-6 bg-gradient-to-r from-purple-500 via-pink-500 to-rose-500 rounded-2xl p-5 shadow-2xl border-2 border-purple-300/50 relative overflow-hidden group/points">
                    <div class="absolute inset-0 bg-gradient-to-r from-transparent via-white/20 to-transparent translate-x-[-100%] group-hover/points:translate-x-[100%] transition-transform duration-1500"></div>
                    <div class="relative z-10">
                        <div class="flex items-center gap-3 mb-4">
                            <div class="w-12 h-12 bg-white/20 backdrop-blur-sm rounded-xl flex items-center justify-center border-2 border-white/30">
                                <i data-lucide="sparkles" class="w-6 h-6 text-white"></i>
                            </div>
                    <div>
                                <p class="text-xs font-bold text-white/90 uppercase tracking-wider mb-1">Pontos ao Comprar com Dinheiro</p>
                                <p class="text-2xl font-black text-white">
                                    +<?= number_format($productPointsReward, 0, ',', '.') ?> pontos
                        </p>
                    </div>
                    </div>
                        <div class="grid grid-cols-2 gap-3 mb-4">
                            <div class="bg-white/20 backdrop-blur-sm px-4 py-3 rounded-xl border-2 border-white/30">
                                <p class="text-[10px] text-white/90 font-bold uppercase mb-1">Você recebe</p>
                                <p class="text-lg font-black text-white"><?= number_format($productPointsReward, 0, ',', '.') ?> pontos</p>
                </div>
                            <div class="bg-white/20 backdrop-blur-sm px-4 py-3 rounded-xl border-2 border-white/30">
                                <p class="text-[10px] text-white/90 font-bold uppercase mb-1">Indicado Nível 1</p>
                                <p class="text-lg font-black text-white"><?= number_format($productPointsReward, 0, ',', '.') ?> pontos</p>
                            </div>
                        </div>
                        <div class="pt-3 border-t border-white/30">
                            <div class="flex items-center justify-between">
                                <p class="text-xs text-white/80">Equivale a</p>
                                <p class="text-base font-black text-white">R$ <?= number_format($productPointsReward / 100, 2, ',', '.') ?></p>
                            </div>
                        </div>
                    </div>
                    <div class="absolute top-0 right-0 w-32 h-32 bg-white/10 rounded-full blur-2xl animate-pulse"></div>
                </div>
                <?php endif; ?>

                <!-- Preço Principal com Animação -->
                <div class="text-center mb-6 pb-6 border-b-2 border-gray-200 relative overflow-hidden">
                    <div class="absolute inset-0 bg-gradient-to-r from-transparent via-blue-100/50 to-transparent -translate-x-full group-hover:translate-x-full transition-transform duration-2000"></div>
                    <p class="text-xs text-gray-500 font-bold uppercase mb-2 relative z-10">Preço</p>
                    <div class="flex items-baseline justify-center gap-1 relative z-10">
                        <span class="text-lg text-blue-600 font-bold animate-pulse">R$</span>
                        <span class="text-5xl font-black bg-gradient-to-r from-blue-600 via-indigo-600 to-purple-600 bg-clip-text text-transparent animate-glow-pulse"><?= number_format($p['value'],0,',','.') ?></span>
                    </div>
                    <!--<div class="mt-3 relative z-10">-->
                    <!--    <div class="inline-flex items-center gap-2 bg-gradient-to-r from-purple-100 to-pink-100 px-4 py-2 rounded-full border-2 border-purple-300">-->
                    <!--        <i data-lucide="gift" class="w-4 h-4 text-purple-600"></i>-->
                    <!--        <span class="text-xs font-black text-purple-700">ou <?= number_format($productPriceInPoints, 0, ',', '.') ?> pontos</span>-->
                    <!--    </div>-->
                    <!--</div>-->
                </div>


                <!-- Barra de Progresso e Limitação -->
                <div class="mb-6 space-y-4">
                    <div>
                        <div class="flex justify-between items-center mb-2">
                            <span class="text-xs font-bold text-gray-600">Progresso</span>
                            <span class="text-sm font-black text-blue-600"><?= round($pct) ?>%</span>
                        </div>
                        <div class="h-4 w-full bg-gray-100 rounded-full overflow-hidden border-2 border-gray-200 relative shadow-inner">
                            <div class="h-full bg-gradient-to-r from-blue-500 via-blue-600 to-indigo-600 rounded-full transition-all duration-1000 relative overflow-hidden animate-chart-up" style="width: <?= $pct ?>%; animation-delay: <?= $index * 0.1 ?>s;">
                                <div class="absolute inset-0 bg-gradient-to-r from-transparent via-white/50 to-transparent animate-shimmer"></div>
                                <!-- Efeito de brilho pulsante -->
                                <div class="absolute inset-0 bg-white/30 animate-pulse"></div>
                            </div>
                            <!-- Marcadores animados -->
                            <div class="absolute top-0 left-0 w-full h-full flex items-center">
                                <?php for($i = 0; $i <= 4; $i++): ?>
                                <div class="flex-1 h-full border-r border-white/20"></div>
                                <?php endfor; ?>
                            </div>
                        </div>
                    </div>
                 
                </div>

                <!-- Botões de Compra -->
                <div class="space-y-3">
                    <?php if($canBuyWithPoints && $canBuy): ?>
                    <!-- Botão Comprar com Pontos -->
                    <button onclick="convertPointsToProduct(<?= $p['id'] ?>, <?= $productPriceInPoints ?>)" 
                        class="w-full py-4 rounded-2xl font-black uppercase text-sm tracking-wider relative overflow-hidden group bg-gradient-to-r from-purple-500 via-pink-500 to-rose-500 text-white shadow-lg hover:shadow-2xl transition-all duration-300 hover:scale-[1.02] active:scale-[0.98] border-2 border-white/30">
                        <span class="relative z-10 flex items-center justify-center gap-2">
                            <i data-lucide="gift" class="w-5 h-5 group-hover:scale-125 transition-transform"></i>
                            Comprar com <?= number_format($productPriceInPoints, 0, ',', '.') ?> Pontos
                            <i data-lucide="sparkles" class="w-5 h-5 group-hover:rotate-180 transition-transform"></i>
                        </span>
                        <div class="absolute inset-0 bg-gradient-to-r from-transparent via-white/30 to-transparent translate-x-[-100%] group-hover:translate-x-[100%] transition-transform duration-1000"></div>
                        <div class="absolute inset-0 bg-white/10 animate-pulse"></div>
                    </button>
                    <?php endif; ?>
                    
                    <!-- Botão Comprar com Dinheiro -->
                <button onclick="confirmPurchase(<?= $p['id'] ?>, '<?= $p['value'] ?>')" 
                        class="w-full py-4 rounded-2xl font-black uppercase text-sm tracking-wider relative overflow-hidden group <?= $canBuyWithPoints ? 'bg-vip-blue' : 'bg-gradient-to-r from-blue-600 to-indigo-600' ?> text-white shadow-lg hover:shadow-2xl transition-all duration-300 hover:scale-[1.02] active:scale-[0.98] hover:bg-blue-600 border-2 border-white/20">
                        <span class="relative z-10 flex items-center justify-center gap-2">
                            <i data-lucide="zap" class="w-5 h-5 group-hover:rotate-12 transition-transform"></i>
                            Investir por R$ <?= number_format($p['value'], 2, ',', '.') ?>
                            <i data-lucide="arrow-right" class="w-5 h-5 group-hover:translate-x-1 transition-transform"></i>
                        </span>
                        <div class="absolute inset-0 bg-gradient-to-r from-transparent via-white/20 to-transparent translate-x-[-100%] group-hover:translate-x-[100%] transition-transform duration-1000"></div>
                </button>
                </div>
            </div>
        </div>
        <?php endforeach; ?>
    </div>
</div>

<script>
    document.addEventListener('DOMContentLoaded', () => {
        if (window.lucide) {
            window.lucide.createIcons();
        }
    });
</script>

        <style>
    /* ========================================
       AFFILIATE INTELLIGENCE 5.0 - ELITE PRO
       ======================================== */

    :root {
        --gringa-blue: #3b82f6;
        --gringa-dark: #0f172a;
        --gringa-glass: rgba(255, 255, 255, 0.03);
    }

    /* Card Holográfico Interativo */
    .agent-card-pro {
        background: linear-gradient(135deg, #1e293b 0%, #0f172a 100%);
        border-radius: 2.5rem;
        position: relative;
        overflow: hidden;
        border: 1px solid rgba(255,255,255,0.05);
    }

    .agent-card-pro::after {
        content: '';
        position: absolute;
        top: -50%; left: -50%;
        width: 200%; height: 200%;
        background: radial-gradient(circle, rgba(59, 130, 246, 0.08) 0%, transparent 70%);
        animation: rotate-slow 20s linear infinite;
    }

    /* Listagem Otimizada */
    .user-list-container {
        max-height: 400px;
        overflow-y: auto;
        scrollbar-width: thin;
        scrollbar-color: #3b82f6 transparent;
    }

    .user-list-container::-webkit-scrollbar { width: 4px; }
    .user-list-container::-webkit-scrollbar-thumb { background: #3b82f6; border-radius: 10px; }

    .tab-btn-gringa {
        padding: 12px 20px;
        border-radius: 14px;
        font-size: 11px;
        font-weight: 800;
        text-transform: uppercase;
        letter-spacing: 1px;
        transition: all 0.3s;
        border: 1px solid #f1f5f9;
        color: #94a3b8;
    }

    .tab-btn-gringa.active-sub {
        background: var(--gringa-blue);
        color: white;
        border-color: var(--gringa-blue);
        box-shadow: 0 10px 20px rgba(59, 130, 246, 0.3);
    }

    .vip-badge-container {
        z-index: 9999;
    }

    .vip-badge-container i {
        animation: float 3s ease-in-out infinite;
    }

    @keyframes float {
        0%, 100% {
            transform: translateY(0) rotate(0deg);
        }
        50% {
            transform: translateY(-5px) rotate(5deg);
        }
    }

    .history-row {
        border-left: 3px solid #e2e8f0;
        transition: all 0.3s;
    }

    .history-row:hover {
        border-left-color: var(--gringa-blue);
        background: #f8fafc;
    }
</style>

<div id="view-team" class="tab-view max-w-6xl mx-auto p-4 space-y-6 pb-32">
    <!-- Header Principal -->
    <div class="bg-gradient-to-br from-blue-600 via-blue-700 to-indigo-800 rounded-3xl p-6 shadow-2xl relative overflow-hidden animate-fadeInUp">
        <div class="absolute top-0 right-0 w-64 h-64 bg-white/10 rounded-full -mr-32 -mt-32"></div>
        <div class="absolute bottom-0 left-0 w-48 h-48 bg-white/5 rounded-full -ml-24 -mb-24"></div>
        <div class="relative z-10">
            <div class="flex flex-col md:flex-row justify-between items-start gap-6 mb-6">
                <div>
                    <div class="flex items-center gap-2 mb-3">
                        <div class="w-10 h-10 bg-white/20 rounded-xl flex items-center justify-center">
                            <i data-lucide="trending-up" class="w-5 h-5 text-white"></i>
                    </div>
                        <span class="text-xs font-black text-white/90 uppercase tracking-widest">Dashboard Afiliado</span>
                    </div>
                    <p class="text-xs text-white/70 font-bold uppercase mb-2">Comissão Total Acumulada</p>
                    <h2 class="text-5xl font-black text-white tracking-tight mb-1">
                        R$ <span id="affTotalCommission">0,00</span>
                    </h2>
                    <p class="text-sm text-green-300 font-bold">+R$ <span id="affTodayCommission">0,00</span> hoje</p>
                </div>
                <div class="bg-white/10 backdrop-blur-md rounded-2xl p-4 border border-white/20 w-full md:w-auto">
                    <p class="text-[9px] text-white/70 font-black uppercase mb-2">Seu Código de Afiliado</p>
                    <p class="text-2xl font-mono text-white tracking-widest mb-3"><?= htmlspecialchars($user['affiliate_code']) ?></p>
                    <button onclick="copyLink()" class="w-full bg-white text-blue-700 px-6 py-3 rounded-xl text-xs font-black uppercase active:scale-95 transition shadow-lg hover:shadow-xl">
                        <i data-lucide="copy" class="w-4 h-4 inline mr-2"></i> Copiar Link
                    </button>
                </div>
            </div>
                </div>
            </div>

    <!-- Cards de Métricas Principais -->
    <div class="grid grid-cols-2 md:grid-cols-4 gap-4">
        <div class="bg-white rounded-2xl p-5 shadow-lg border border-gray-100 hover:shadow-xl transition-shadow">
            <div class="flex items-center justify-between mb-3">
                <div class="w-12 h-12 bg-blue-100 rounded-xl flex items-center justify-center">
                    <i data-lucide="users" class="w-6 h-6 text-blue-600"></i>
                </div>
                <span class="text-[9px] text-gray-400 font-black uppercase">Total</span>
            </div>
            <p class="text-3xl font-black text-gray-900 mb-1"><span id="affTeamTotal">0</span></p>
            <p class="text-xs text-gray-500">Membros na equipe</p>
        </div>
        <div class="bg-white rounded-2xl p-5 shadow-lg border border-gray-100 hover:shadow-xl transition-shadow">
            <div class="flex items-center justify-between mb-3">
                <div class="w-12 h-12 bg-green-100 rounded-xl flex items-center justify-center">
                    <i data-lucide="check-circle" class="w-6 h-6 text-green-600"></i>
    </div>
                <span class="text-[9px] text-gray-400 font-black uppercase">Ativos</span>
        </div>
            <p class="text-3xl font-black text-gray-900 mb-1"><span id="affActive">0</span></p>
            <p class="text-xs text-gray-500">Com investimentos</p>
        </div>
        <div class="bg-white rounded-2xl p-5 shadow-lg border border-gray-100 hover:shadow-xl transition-shadow">
            <div class="flex items-center justify-between mb-3">
                <div class="w-12 h-12 bg-purple-100 rounded-xl flex items-center justify-center">
                    <i data-lucide="mouse-pointer-click" class="w-6 h-6 text-purple-600"></i>
        </div>
                <span class="text-[9px] text-gray-400 font-black uppercase">Visitas</span>
    </div>
            <p class="text-3xl font-black text-gray-900 mb-1"><span id="affVisits">0</span></p>
            <p class="text-xs text-gray-500">No link de afiliado</p>
            </div>
        <div class="bg-white rounded-2xl p-5 shadow-lg border border-gray-100 hover:shadow-xl transition-shadow">
            <div class="flex items-center justify-between mb-3">
                <div class="w-12 h-12 bg-yellow-100 rounded-xl flex items-center justify-center">
                    <i data-lucide="sparkles" class="w-6 h-6 text-yellow-600"></i>
            </div>
                <span class="text-[9px] text-gray-400 font-black uppercase">Giros</span>
            </div>
            <p class="text-3xl font-black text-gray-900 mb-1"><span id="affSpins">0</span></p>
            <p class="text-xs text-gray-500">Disponíveis</p>
            <a href="lucky_wheel.php" class="mt-2 inline-block text-xs font-bold text-blue-600 hover:text-blue-700">Usar →</a>
        </div>
    </div>

    <!-- Cards de Níveis -->
    <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
        <div class="bg-gradient-to-br from-blue-50 to-blue-100 rounded-2xl p-5 border-2 border-blue-200">
            <div class="flex items-center justify-between mb-3">
                <span class="text-xs font-black text-blue-700 uppercase">Nível 1</span>
                <div class="w-8 h-8 bg-blue-600 rounded-lg flex items-center justify-center text-white font-black text-sm">1</div>
            </div>
            <p class="text-4xl font-black text-blue-900 mb-2"><span id="affL1">0</span></p>
            <p class="text-xs text-blue-600">Indicados diretos</p>
        </div>
        <div class="bg-gradient-to-br from-indigo-50 to-indigo-100 rounded-2xl p-5 border-2 border-indigo-200">
            <div class="flex items-center justify-between mb-3">
                <span class="text-xs font-black text-indigo-700 uppercase">Nível 2</span>
                <div class="w-8 h-8 bg-indigo-600 rounded-lg flex items-center justify-center text-white font-black text-sm">2</div>
            </div>
            <p class="text-4xl font-black text-indigo-900 mb-2"><span id="affL2">0</span></p>
            <p class="text-xs text-indigo-600">Indicados indiretos</p>
        </div>
        <div class="bg-gradient-to-br from-purple-50 to-purple-100 rounded-2xl p-5 border-2 border-purple-200">
            <div class="flex items-center justify-between mb-3">
                <span class="text-xs font-black text-purple-700 uppercase">Nível 3</span>
                <div class="w-8 h-8 bg-purple-600 rounded-lg flex items-center justify-center text-white font-black text-sm">3</div>
            </div>
            <p class="text-4xl font-black text-purple-900 mb-2"><span id="affL3">0</span></p>
            <p class="text-xs text-purple-600">Terceiro nível</p>
        </div>
        </div>

    <!-- Gráfico e Filtros -->
    <div class="bg-white rounded-2xl p-4 md:p-6 shadow-lg border border-gray-100">
        <div class="flex flex-col gap-4 mb-6">
                            <div>
                <h3 class="text-lg font-black text-gray-900 mb-1">Evolução de Comissões</h3>
                <p class="text-xs text-gray-500">Últimos 14 dias • VIP <span id="affVip">0</span></p>
                            </div>
            <div class="flex flex-col sm:flex-row gap-2">
                <input type="date" id="affDateFrom" class="flex-1 px-3 py-2 border border-gray-200 rounded-lg text-xs font-bold focus:ring-2 focus:ring-blue-500 focus:border-blue-500">
                <input type="date" id="affDateTo" class="flex-1 px-3 py-2 border border-gray-200 rounded-lg text-xs font-bold focus:ring-2 focus:ring-blue-500 focus:border-blue-500">
                <button onclick="affFilterDates()" class="px-4 py-2 bg-blue-600 text-white rounded-lg text-xs font-bold hover:bg-blue-700 transition whitespace-nowrap">
                    <i data-lucide="filter" class="w-4 h-4 inline mr-1"></i> Filtrar
                        </button>
                    </div>
            </div>
        <div class="relative">
            <canvas id="affCommissionChart" height="80"></canvas>
        </div>
            </div>

    <!-- Lista de Membros com Filtros -->
    <div class="bg-white rounded-2xl p-6 shadow-lg border border-gray-100">
        <div class="flex flex-col md:flex-row justify-between items-start md:items-center gap-4 mb-6">
            <h3 class="text-lg font-black text-gray-900">Membros da Equipe</h3>
            <div class="flex gap-2 w-full md:w-auto">
                <div class="relative flex-1 md:flex-initial flex items-center bg-gray-50 rounded-xl px-4 py-2 border border-gray-200">
                    <i data-lucide="search" class="w-4 h-4 text-gray-400 mr-2"></i>
                    <input type="text" id="affUserSearch" placeholder="Buscar por telefone..." class="bg-transparent border-none text-xs font-bold focus:ring-0 w-full">
            </div>
        </div>
    </div>

        <div class="flex gap-2 mb-6">
            <button onclick="affSwitchLvl(1)" id="affTab1" class="flex-1 py-3 rounded-xl text-xs font-black uppercase transition-all bg-blue-600 text-white shadow-md">Nível 1</button>
            <button onclick="affSwitchLvl(2)" id="affTab2" class="flex-1 py-3 rounded-xl text-xs font-black uppercase transition-all bg-gray-100 text-gray-600 hover:bg-gray-200">Nível 2</button>
            <button onclick="affSwitchLvl(3)" id="affTab3" class="flex-1 py-3 rounded-xl text-xs font-black uppercase transition-all bg-gray-100 text-gray-600 hover:bg-gray-200">Nível 3</button>
                        </div>

        <div class="user-list-container max-h-96 overflow-y-auto">
            <div id="affList1" class="space-y-3"></div>
            <div id="affList2" class="hidden space-y-3"></div>
            <div id="affList3" class="hidden space-y-3"></div>
        </div>
    </div>

    <!-- Modal membro -->
    <div id="memberModal" class="modal bg-gray-50">
        <div class="p-5 bg-white border-b flex justify-between items-center sticky top-0 z-20">
                        <div>
                <h3 class="font-black text-gray-900 uppercase text-sm" id="mmTitle">Membro</h3>
                <p class="text-[10px] text-gray-400 font-bold" id="mmSub">—</p>
                        </div>
            <button onclick="closeMemberModal()" class="w-10 h-10 bg-gray-100 rounded-full flex items-center justify-center">
                <i data-lucide="x" class="w-4 h-4"></i>
            </button>
                    </div>
        <div class="p-5 space-y-3">
            <div class="grid grid-cols-2 gap-3">
                <div class="bg-white border border-gray-100 rounded-xl p-4">
                    <p class="text-[9px] text-gray-400 font-black uppercase">Total investido</p>
                    <p class="text-lg font-black text-slate-900" id="mmInvested">R$ 0,00</p>
                    </div>
                <div class="bg-white border border-gray-100 rounded-xl p-4">
                    <p class="text-[9px] text-gray-400 font-black uppercase">Total depositado</p>
                    <p class="text-lg font-black text-slate-900" id="mmDeposited">R$ 0,00</p>
                </div>
                <div class="bg-white border border-gray-100 rounded-xl p-4">
                    <p class="text-[9px] text-gray-400 font-black uppercase">Investimentos</p>
                    <p class="text-lg font-black text-slate-900" id="mmInvCount">0</p>
                </div>
                <div class="bg-white border border-gray-100 rounded-xl p-4">
                    <p class="text-[9px] text-gray-400 font-black uppercase">Ativos</p>
                    <p class="text-lg font-black text-slate-900" id="mmInvActive">0</p>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
    let _affLoaded = false;
    let _affLvl = 1;
    let _affData = null;
    let _affChart = null;

    function affSwitchLvl(lvl) {
        _affLvl = lvl;
        document.getElementById('affList1').classList.add('hidden');
        document.getElementById('affList2').classList.add('hidden');
        document.getElementById('affList3').classList.add('hidden');
        document.getElementById('affTab1').classList.remove('active-sub');
        document.getElementById('affTab2').classList.remove('active-sub');
        document.getElementById('affTab3').classList.remove('active-sub');
        document.getElementById('affList' + lvl).classList.remove('hidden');
        document.getElementById('affTab' + lvl).classList.add('active-sub');
        affApplySearch();
    }

    function affApplySearch() {
        const q = (document.getElementById('affUserSearch')?.value || '').toLowerCase().trim();
        const list = document.getElementById('affList' + _affLvl);
        if (!list) return;
        [...list.querySelectorAll('[data-phone]')].forEach(row => {
            const phone = (row.getAttribute('data-phone') || '').toLowerCase();
            row.style.display = phone.includes(q) ? 'flex' : 'none';
        });
    }

    function formatBRL(n) {
        try {
            return (Number(n) || 0).toLocaleString('pt-BR', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
        } catch (e) {
            return '0,00';
        }
    }

        function renderAffMembers(lvl, rows) {
        const el = document.getElementById('affList' + lvl);
        if (!el) return;
        if (!rows || rows.length === 0) {
            el.innerHTML = `<div class="text-center py-12"><p class="text-sm text-gray-400">Nenhum membro encontrado neste nível.</p></div>`;
            return;
        }
        el.innerHTML = rows.map(r => `
            <div class="bg-gray-50 rounded-xl p-4 border border-gray-200 hover:border-blue-300 hover:shadow-md transition-all" data-phone="${(r.phone||'')}">
                <div class="flex justify-between items-center">
                    <div class="flex items-center gap-4 flex-1">
                        <div class="w-12 h-12 rounded-xl ${lvl === 1 ? 'bg-blue-600' : lvl === 2 ? 'bg-indigo-600' : 'bg-purple-600'} text-white flex items-center justify-center font-black text-sm">L${lvl}</div>
                        <div class="flex-1">
                            <p class="text-sm font-black text-gray-900 mb-1">${r.phone || '-'}</p>
                            <p class="text-xs text-gray-500">${r.name || 'Sem nome'} • ${r.date ? String(r.date).slice(0,10) : '-'}</p>
                        </div>
                    </div>
                    <button onclick="openMemberModal(${r.id})" class="px-4 py-2 bg-white rounded-lg border border-gray-200 hover:bg-blue-600 hover:text-white hover:border-blue-600 transition-all shadow-sm text-xs font-bold">
                        <i data-lucide="eye" class="w-4 h-4 inline mr-1"></i> Ver
                    </button>
                </div>
            </div>
        `).join('');
        lucide.createIcons();
        affApplySearch();
    }

    function affFilterDates() {
        const from = document.getElementById('affDateFrom')?.value;
        const to = document.getElementById('affDateTo')?.value;
        if (!from || !to) {
            toast('Selecione as datas', 'err');
            return;
        }
        // Recarregar gráfico com filtro
        loadAffiliateDashboard();
    }

    async function loadAffiliateDashboard() {
        // Permitir recarregar
        _affLoaded = false;
        try {
            const fd = new FormData();
            fd.append('action', 'get_affiliate_dashboard');
            const req = await fetch('', { method: 'POST', body: fd });
            const res = await req.json();
            if (res.status !== 'success') {
                console.error('Erro ao carregar dashboard:', res);
                // Não mostrar toast de erro, apenas log
                _affLoaded = false;
                return;
            }
            _affData = res;
            _affLoaded = true;

            const affTotalCommission = document.getElementById('affTotalCommission');
            if (affTotalCommission) affTotalCommission.innerText = formatBRL(res.commission?.total || 0);
            
            const affTodayCommission = document.getElementById('affTodayCommission');
            if (affTodayCommission) affTodayCommission.innerText = formatBRL(res.commission?.today || 0);
            
            const affSpins = document.getElementById('affSpins');
            if (affSpins) affSpins.innerText = String(res.spins || 0);
            
            const visitsEl = document.getElementById('affVisits');
            if (visitsEl) visitsEl.innerText = String(res.visits || 0);

            const affTeamTotal = document.getElementById('affTeamTotal');
            if (affTeamTotal) affTeamTotal.innerText = String(res.counts?.total || 0);
            
            const affL1 = document.getElementById('affL1');
            if (affL1) affL1.innerText = String(res.counts?.lvl1 || 0);
            
            const affL2 = document.getElementById('affL2');
            if (affL2) affL2.innerText = String(res.counts?.lvl2 || 0);
            
            const affL3 = document.getElementById('affL3');
            if (affL3) affL3.innerText = String(res.counts?.lvl3 || 0);
            
            const affActive = document.getElementById('affActive');
            if (affActive) affActive.innerText = String(res.counts?.active || 0);

            const affQualified150 = document.getElementById('affQualified150');
            if (affQualified150) affQualified150.innerText = String(res.vip?.qualified150 || 0);
            
            const affVip = document.getElementById('affVip');
            if (affVip) affVip.innerText = String(res.vip?.current || 0);

            renderAffMembers(1, res.members.lvl1);
            renderAffMembers(2, res.members.lvl2);
            renderAffMembers(3, res.members.lvl3);
            affSwitchLvl(1);

            const ctx = document.getElementById('affCommissionChart');
            if (ctx && window.Chart) {
                if (_affChart) _affChart.destroy();
                _affChart = new Chart(ctx, {
                    type: 'line',
                    data: {
                        labels: res.commission.series.labels.map(d => d.slice(5)),
                        datasets: [{
                            label: 'R$',
                            data: res.commission.series.values,
                            borderColor: '#3b82f6',
                            backgroundColor: 'rgba(59,130,246,0.12)',
                            fill: true,
                            tension: 0.35,
                            pointRadius: 0
                        }]
                    },
                    options: {
                        responsive: true,
                        plugins: { legend: { display: false } },
                        scales: {
                            y: { ticks: { callback: (v) => 'R$ ' + formatBRL(v) } },
                            x: { ticks: { maxTicksLimit: 7 } }
                        }
                    }
                });
            }
        } catch (e) {
            toast('Erro ao carregar dashboard do afiliado', 'err');
        }
    }

        document.getElementById('affUserSearch')?.addEventListener('input', affApplySearch);

        // Inicializar ícones do badge VIP
        if (window.lucide) {
            lucide.createIcons();
        }

    async function openMemberModal(memberId) {
        const m = document.getElementById('memberModal');
        if (!m) return;
        m.classList.add('open');
        lucide.createIcons();
        document.getElementById('mmTitle').innerText = 'Carregando...';
        document.getElementById('mmSub').innerText = '';

        try {
            const fd = new FormData();
            fd.append('action', 'get_member_details');
            fd.append('member_id', String(memberId));
            const req = await fetch('', { method: 'POST', body: fd });
            const res = await req.json();
            if (res.status !== 'success') throw new Error(res.message || 'Falha');

            document.getElementById('mmTitle').innerText = res.member.phone || 'Membro';
            document.getElementById('mmSub').innerText = (res.member.name || '-') + ' • VIP ' + (res.member.vip_level ?? 0);
            document.getElementById('mmInvested').innerText = 'R$ ' + formatBRL(res.stats.total_invested);
            document.getElementById('mmDeposited').innerText = 'R$ ' + formatBRL(res.stats.total_deposited);
            document.getElementById('mmInvCount').innerText = String(res.stats.investments || 0);
            document.getElementById('mmInvActive').innerText = String(res.stats.active_investments || 0);
        } catch (e) {
            toast('Não foi possível carregar o membro', 'err');
        }
    }

    function closeMemberModal() {
        const m = document.getElementById('memberModal');
        if (m) m.classList.remove('open');
    }

    function openNewsModal(news) {
        const m = document.getElementById('newsModal');
        if (!m) return;
        m.classList.add('open');
        lucide.createIcons();
        
        document.getElementById('newsModalImgSrc').src = news.img || 'https://placehold.co/600x400?text=News';
        document.getElementById('newsModalDate').querySelector('span').textContent = new Date(news.created_at).toLocaleDateString('pt-BR', { 
            day: '2-digit', 
            month: 'long', 
            year: 'numeric',
            hour: '2-digit',
            minute: '2-digit'
        });
        document.getElementById('newsModalTitle').textContent = news.title || 'Sem título';
        
        const textEl = document.getElementById('newsModalText');
        const description = news.description || 'Sem descrição disponível.';
        textEl.innerHTML = description.split('\n').map(p => `<p class="mb-3">${p}</p>`).join('');
    }

        function closeNewsModal() {
            const m = document.getElementById('newsModal');
            if (m) m.classList.remove('open');
        }

        function openSupportModal() {
            const m = document.getElementById('modalSupport');
            if (m) {
                m.classList.add('open');
                lucide.createIcons();
            }
        }

        function closeSupportModal() {
            const m = document.getElementById('modalSupport');
            if (m) m.classList.remove('open');
        }
</script>

        <div id="view-profile" class="tab-view">
            <div class="bg-slate-900 rounded-2xl p-5 mb-6 text-white border border-white/10 overflow-hidden relative">
                <div class="absolute -top-10 -right-10 w-40 h-40 bg-vip-blue/20 rounded-full blur-2xl"></div>
                <div class="relative z-10">
                    <div class="flex justify-between items-start mb-4">
                        <div>
                            <p class="text-[10px] text-slate-300 font-black uppercase tracking-widest">Status VIP</p>
                            <p class="text-2xl font-black tracking-tight">VIP <?= (int)($user['vip_level'] ?? 0) ?></p>
                            <p class="text-[10px] text-slate-300 font-bold mt-1">Qualificados (≥150): <?= (int)($qualified150Count ?? 0) ?><?php if(($qtdNecessariaVip ?? 0) > 0): ?> / <?= (int)$qtdNecessariaVip ?><?php endif; ?></p>
                        </div>
                        <div class="text-right">
                            <p class="text-[10px] text-slate-300 font-black uppercase tracking-widest">Giros Disponíveis</p>
                            <p class="text-lg font-black"><?= (int)($user['qtd_spins'] ?? 0) ?></p>
                            <a href="lucky_wheel.php" class="inline-flex mt-2 items-center justify-center gap-2 px-4 py-2 rounded-xl bg-white text-slate-900 text-[10px] font-black uppercase active:scale-95 transition">
                                <i data-lucide="sparkles" class="w-4 h-4"></i> Roleta
                            </a>
                        </div>
                    </div>
                    <div class="grid grid-cols-3 gap-3 mb-4">
                        <div class="bg-white/5 rounded-xl p-3 border border-white/10">
                            <p class="text-[9px] text-slate-400 font-bold uppercase mb-1">Total Giros</p>
                            <p class="text-lg font-black text-white"><?= (int)($user['total_spins'] ?? 0) ?></p>
                        </div>
                        <div class="bg-white/5 rounded-xl p-3 border border-white/10">
                            <p class="text-[9px] text-slate-400 font-bold uppercase mb-1">Prêmios Giros</p>
                            <p class="text-lg font-black text-yellow-400">R$ <?= number_format((float)($user['awards_spins'] ?? 0), 2, ',', '.') ?></p>
                        </div>
                        <div class="bg-white/5 rounded-xl p-3 border border-white/10">
                            <p class="text-[9px] text-slate-400 font-bold uppercase mb-1">Prêmios VIP</p>
                            <p class="text-lg font-black text-yellow-400">R$ <?= number_format((float)($user['awards_vip'] ?? 0), 2, ',', '.') ?></p>
                        </div>
                    </div>
                    <!-- Card de Pontos -->
                    <!--<div class="bg-gradient-to-br from-purple-500 via-pink-500 to-rose-600 rounded-xl p-4 mb-4 border border-white/20">-->
                    <!--    <div class="flex items-center justify-between">-->
                    <!--        <div>-->
                    <!--            <p class="text-[9px] text-white/80 font-bold uppercase mb-1">Meus Pontos</p>-->
                    <!--            <p class="text-2xl font-black text-white" id="userPointsDisplay"><?= number_format((int)($user['qtd_points'] ?? 0), 0, ',', '.') ?></p>-->
                    <!--            <p class="text-[8px] text-white/70 mt-1">100 pontos = R$ 1,00</p>-->
                    <!--        </div>-->
                    <!--        <button onclick="tab('points')" class="px-4 py-2 bg-white/20 hover:bg-white/30 text-white rounded-lg text-xs font-bold uppercase transition">-->
                    <!--            <i data-lucide="gift" class="w-4 h-4 inline"></i> Trocar-->
                    <!--        </button>-->
                    <!--    </div>-->
                    <!--</div>-->
                    <?php if(($qtdNecessariaVip ?? 0) > 0): ?>
                    <div class="mt-4">
                        <div class="flex justify-between text-[10px] font-bold text-slate-300">
                            <span>Próximo VIP</span>
                            <span><?= (int)round($vipProgressPct ?? 0) ?>%</span>
                        </div>
                        <div class="w-full h-2 bg-white/10 rounded-full overflow-hidden mt-2">
                            <div class="h-full bg-gradient-to-r from-blue-400 to-cyan-300" style="width: <?= (float)($vipProgressPct ?? 0) ?>%"></div>
                        </div>
                        <p class="text-[10px] text-slate-400 mt-2">
                            Dica: cada indicado direto que fizer <strong>1º investimento ≥ R$150</strong> conta para o VIP e libera <strong>+1 giro</strong> pra você.
                        </p>
                    </div>
                    <?php else: ?>
                    <p class="text-[10px] text-slate-300 mt-3">Você já está no nível máximo disponível.</p>
                    <?php endif; ?>
                </div>
            </div>

            <!-- Card Salários VIP -->
   

            <!-- Estatísticas de Renda - Estilo Gringa -->
            <div class="mb-6">
                <h3 class="text-lg font-black text-gray-900 mb-4 bg-gradient-to-r from-blue-600 to-purple-600 bg-clip-text text-transparent" data-i18n="incomeStats">Estatísticas de Renda</h3>
                <div class="grid grid-cols-2 gap-3">
                    <!-- Ganhos de Hoje -->
                    <div class="bg-gradient-to-br from-blue-400 to-cyan-500 rounded-2xl p-5 shadow-xl border-2 border-white/20 relative overflow-hidden group animate-fadeInUp hover:scale-105 transition-transform">
                        <div class="absolute top-2 right-2 w-20 h-20 bg-white/10 rounded-full blur-xl group-hover:scale-150 transition-transform"></div>
                        <div class="relative z-10">
                            <div class="flex items-center justify-between mb-3">
                                <div class="w-12 h-12 bg-white/20 backdrop-blur-md rounded-xl flex items-center justify-center border border-white/30">
                                    <i data-lucide="calendar" class="w-6 h-6 text-white"></i>
                                </div>
                            </div>
                            <p class="text-white/80 text-[10px] font-bold uppercase mb-1">Ganhos de Hoje</p>
                            <p class="text-2xl font-black text-white">R$ 0</p>
                        </div>
                    </div>
                    
                    <!-- Saques de Hoje -->
                    <div class="bg-gradient-to-br from-green-400 to-emerald-500 rounded-2xl p-5 shadow-xl border-2 border-white/20 relative overflow-hidden group animate-fadeInUp hover:scale-105 transition-transform" style="animation-delay: 0.1s;">
                        <div class="absolute top-2 right-2 w-20 h-20 bg-white/10 rounded-full blur-xl group-hover:scale-150 transition-transform"></div>
                        <div class="relative z-10">
                            <div class="flex items-center justify-between mb-3">
                                <div class="w-12 h-12 bg-white/20 backdrop-blur-md rounded-xl flex items-center justify-center border border-white/30">
                                    <i data-lucide="credit-card" class="w-6 h-6 text-white"></i>
                                </div>
                            </div>
                            <p class="text-white/80 text-[10px] font-bold uppercase mb-1">Saques de Hoje</p>
                            <p class="text-2xl font-black text-white">R$ 0</p>
                        </div>
                    </div>
                    
                    <!-- Ganhos Totais -->
                    <div class="bg-gradient-to-br from-orange-400 to-pink-500 rounded-2xl p-5 shadow-xl border-2 border-white/20 relative overflow-hidden group animate-fadeInUp hover:scale-105 transition-transform" style="animation-delay: 0.2s;">
                        <div class="absolute top-2 right-2 w-20 h-20 bg-white/10 rounded-full blur-xl group-hover:scale-150 transition-transform"></div>
                        <div class="relative z-10">
                            <div class="flex items-center justify-between mb-3">
                                <div class="w-12 h-12 bg-white/20 backdrop-blur-md rounded-xl flex items-center justify-center border border-white/30">
                                    <i data-lucide="trending-up" class="w-6 h-6 text-white"></i>
                                </div>
                            </div>
                            <p class="text-white/80 text-[10px] font-bold uppercase mb-1">Ganhos Totais</p>
                            <p class="text-2xl font-black text-white">R$ <?= number_format($user['total_profit'] ?? 0, 2, ',', '.') ?></p>
                        </div>
                    </div>
                    
                    <!-- Saques Totais -->
                    <div class="bg-gradient-to-br from-purple-400 to-indigo-500 rounded-2xl p-5 shadow-xl border-2 border-white/20 relative overflow-hidden group animate-fadeInUp hover:scale-105 transition-transform" style="animation-delay: 0.3s;">
                        <div class="absolute top-2 right-2 w-20 h-20 bg-white/10 rounded-full blur-xl group-hover:scale-150 transition-transform"></div>
                        <div class="relative z-10">
                            <div class="flex items-center justify-between mb-3">
                                <div class="w-12 h-12 bg-white/20 backdrop-blur-md rounded-xl flex items-center justify-center border border-white/30">
                                    <i data-lucide="arrow-up-circle" class="w-6 h-6 text-white"></i>
                                </div>
                            </div>
                            <p class="text-white/80 text-[10px] font-bold uppercase mb-1">Saques Totais</p>
                            <p class="text-2xl font-black text-white">R$ <?= number_format($user['total_withdrawn'] ?? 0, 2, ',', '.') ?></p>
                        </div>
                    </div>
                </div>
            </div>

            <div class="bg-white rounded-xl shadow-sm border border-gray-200 p-5 mb-6 relative overflow-hidden">
                <div class="absolute top-0 right-0 w-24 h-24 bg-vip-blue/5 rounded-bl-full -mr-4 -mt-4"></div>
                <h3 class="text-xs font-bold text-gray-400 uppercase tracking-widest mb-4 flex items-center gap-2"><i data-lucide="pie-chart" class="w-4 h-4 text-vip-blue"></i> Resumo Financeiro</h3>
                <div class="grid grid-cols-2 gap-3 mb-4">
                    <div class="bg-gray-50 p-3 rounded-lg border border-gray-100 text-center"><p class="text-[10px] text-gray-400 font-bold uppercase mb-1">Total Depositado</p><p class="text-sm font-mono font-bold text-gray-800">R$ <?= number_format($totalDeposited, 2, ',', '.') ?></p></div>
                    <div class="bg-gray-50 p-3 rounded-lg border border-gray-100 text-center"><p class="text-[10px] text-gray-400 font-bold uppercase mb-1">Total Retirado</p><p class="text-sm font-mono font-bold text-gray-800">R$ <?= number_format($totalWithdrawn, 2, ',', '.') ?></p></div>
                </div>
                <div class="grid grid-cols-2 gap-3 mb-4">
                    <div class="bg-gray-50 p-3 rounded-lg border border-gray-100 text-center"><p class="text-[10px] text-gray-400 font-bold uppercase mb-1">Total Investido</p><p class="text-sm font-mono font-bold text-gray-800">R$ <?= number_format($totalInvested, 2, ',', '.') ?></p></div>
                    <div class="bg-gray-50 p-3 rounded-lg border border-gray-100 text-center"><p class="text-[10px] text-gray-400 font-bold uppercase mb-1">Investimentos</p><p class="text-sm font-mono font-bold text-gray-800"><?= $totalInvestmentsCount ?> (<?= $activeInvestmentsCount ?> ativos)</p></div>
                </div>
                <div class="bg-blue-50 p-4 rounded-xl border border-blue-100 flex items-center justify-between"><div><p class="text-[10px] text-vip-blue font-bold uppercase">Total Recebido (Lucro)</p><p class="text-xl font-mono font-bold text-vip-blue">R$ <?= number_format($totalProfit, 2, ',', '.') ?></p></div><div class="w-10 h-10 bg-white rounded-full flex items-center justify-center text-vip-blue shadow-sm"><i data-lucide="trending-up" class="w-5 h-5"></i></div></div>
            </div>
            <!-- Formulário de Edição de Perfil -->
            <div class="bg-gradient-to-br from-blue-500 via-indigo-600 to-purple-600 rounded-2xl p-6 mb-6 shadow-xl border-2 border-white/20 relative overflow-hidden">
                <div class="absolute top-0 right-0 w-32 h-32 bg-white/10 rounded-full -translate-y-1/2 translate-x-1/2 blur-2xl"></div>
                <div class="relative z-10">
                    <div class="flex items-center gap-3 mb-4">
                        <div class="w-12 h-12 bg-white/20 backdrop-blur-md rounded-xl flex items-center justify-center border border-white/30">
                            <i data-lucide="user" class="w-6 h-6 text-white"></i>
                        </div>
                        <div>
                            <h3 class="text-lg font-black text-white">Completar Perfil</h3>
                            <p class="text-xs text-white/80">Preencha seus dados para ganhar R$ 1,00</p>
                        </div>
                    </div>
                    <form onsubmit="updateProfile(event)" class="space-y-4">
                        <div>
                            <label class="block text-xs font-bold text-white/90 uppercase mb-2">Nome Completo</label>
                            <input type="text" name="name" id="profileName" 
                                   value="<?= htmlspecialchars($user['name'] ?? '') ?>" 
                                   placeholder="Digite seu nome completo"
                                   class="w-full px-4 py-3 bg-white/20 backdrop-blur-sm border-2 border-white/30 rounded-xl text-white placeholder-white/50 focus:outline-none focus:border-white/50 focus:bg-white/30 transition-all"
                                   required>
                        </div>
                        <div>
                            <label class="block text-xs font-bold text-white/90 uppercase mb-2">CPF</label>
                            <input type="text" name="document" id="profileDocument" 
                                   value="<?= htmlspecialchars($user['document'] ?? '') ?>" 
                                   placeholder="000.000.000-00"
                                   class="w-full px-4 py-3 bg-white/20 backdrop-blur-sm border-2 border-white/30 rounded-xl text-white placeholder-white/50 focus:outline-none focus:border-white/50 focus:bg-white/30 transition-all cpf-mask"
                                   required>
                        </div>
                        <button type="submit" class="w-full py-3 bg-white text-blue-600 rounded-xl font-black uppercase text-sm shadow-lg hover:shadow-xl transition-all hover:scale-[1.02] active:scale-[0.98]">
                            <i data-lucide="save" class="w-4 h-4 inline"></i> Salvar Perfil
                        </button>
                    </form>
                </div>
            </div>

            <div class="bg-white rounded-xl border border-gray-200 overflow-hidden mb-6">
                <div class="p-4 border-b border-gray-100 flex justify-between items-center"><span class="text-xs text-gray-500 font-bold">Nome</span><span class="text-xs font-bold text-gray-800"><?= htmlspecialchars($user['name'] ?? 'Não informado') ?></span></div>
                <div class="p-4 border-b border-gray-100 flex justify-between items-center"><span class="text-xs text-gray-500 font-bold">ID</span><span class="text-xs font-bold text-gray-800"><?= htmlspecialchars($user['id'] ?? 'Não informado') ?></span></div>
                <div class="p-4 border-b border-gray-100 flex justify-between items-center"><span class="text-xs text-gray-500 font-bold">CPF</span><span class="text-xs font-bold text-gray-800"><?= htmlspecialchars($user['document'] ?? 'Não informado') ?></span></div>
                <div class="p-4 border-b border-gray-100 flex justify-between items-center"><span class="text-xs text-gray-500 font-bold">Telefone</span><span class="text-xs font-bold text-gray-800"><?= htmlspecialchars($user['phone']) ?></span></div>
                <div class="p-4 border-b border-gray-100 flex justify-between items-center"><span class="text-xs text-gray-500 font-bold">Código Afiliado</span><span class="text-xs font-bold text-vip-blue"><?= htmlspecialchars($user['affiliate_code'] ?? '-') ?></span></div>
                <div class="p-4 border-b border-gray-100 flex justify-between items-center"><span class="text-xs text-gray-500 font-bold">Check-ins Realizados</span><span class="text-xs font-bold text-gray-800"><?= (int)($user['count_checkin'] ?? 0) ?></span></div>
                <div class="p-4 border-b border-gray-100 flex justify-between items-center"><span class="text-xs text-gray-500 font-bold">Último Check-in</span><span class="text-xs font-bold text-gray-800"><?= $user['last_checkin'] ? date('d/m/Y H:i', strtotime($user['last_checkin'])) : 'Nunca' ?></span></div>
                <div class="p-4 border-b border-gray-100 flex justify-between items-center"><span class="text-xs text-gray-500 font-bold">Visitas Link Afiliado</span><span class="text-xs font-bold text-gray-800"><?= (int)($user['visits_affiliate_link'] ?? 0) ?></span></div>
                <div class="p-4 border-b border-gray-100 flex justify-between items-center"><span class="text-xs text-gray-500 font-bold">Total Indicados Depositaram</span><span class="text-xs font-bold text-gray-800">R$ <?= number_format((float)($user['total_indicated_deposits'] ?? 0), 2, ',', '.') ?></span></div>
                <div class="p-4 border-b border-gray-100 flex justify-between items-center"><span class="text-xs text-gray-500 font-bold">Comissão Nível 1</span><span class="text-xs font-bold text-gray-800">R$ <?= number_format((float)($user['total_lvl1'] ?? 0), 2, ',', '.') ?></span></div>
                <div class="p-4 border-b border-gray-100 flex justify-between items-center"><span class="text-xs text-gray-500 font-bold">Comissão Nível 2</span><span class="text-xs font-bold text-gray-800">R$ <?= number_format((float)($user['total_lvl2'] ?? 0), 2, ',', '.') ?></span></div>
                <div class="p-4 border-b border-gray-100 flex justify-between items-center"><span class="text-xs text-gray-500 font-bold">Comissão Nível 3</span><span class="text-xs font-bold text-gray-800">R$ <?= number_format((float)($user['total_lvl3'] ?? 0), 2, ',', '.') ?></span></div>
                <div class="p-4 flex justify-between items-center cursor-pointer hover:bg-gray-50" onclick="document.getElementById('modalPix').classList.add('open')"><span class="text-xs text-gray-500 font-bold">Chave PIX</span><span class="text-xs font-bold text-vip-blue flex items-center gap-1"><?= $hasPix ? 'Editar' : 'Registrar' ?> <i data-lucide="chevron-right" class="w-3 h-3"></i></span></div>
            </div>
            <h3 class="text-xs font-bold text-gray-400 uppercase tracking-widest mb-3 px-1">Histórico Completo</h3>
            <div class="bg-white rounded-xl border border-gray-200 overflow-hidden mb-6">
                <?php if(empty($historyList)): ?><div class="p-4 text-center text-xs text-gray-400">Sem atividades recentes.</div><?php else: ?><div class="max-h-80 overflow-y-auto">
                <?php foreach($historyList as $h): ?><div class="p-3 border-b border-gray-100 last:border-0 flex justify-between items-center hover:bg-gray-50 transition"><div class="flex items-center gap-3"><div class="w-2 h-2 rounded-full bg-vip-blue flex-shrink-0"></div><div><p class="text-xs font-bold text-gray-800 line-clamp-1"><?= $h['action'] ?></p><p class="text-[9px] text-gray-400"><?= date('d/m/Y H:i', strtotime($h['created_at'])) ?></p></div></div></div><?php endforeach; ?></div><?php endif; ?>
            </div>
            <a href="logout.php" class="btn bg-red-50 text-red-500 border border-red-100 mb-6">Encerrar Sessão</a>
        </div>

        <div id="view-deposit" class="tab-view pb-24">
            <div class="mb-6 text-center">
                <div class="inline-flex items-center justify-center w-20 h-20 bg-gradient-to-br from-blue-500 via-indigo-600 to-purple-600 rounded-full mb-4 shadow-xl">
                    <i data-lucide="arrow-down-circle" class="w-10 h-10 text-white"></i>
                </div>
                <h2 class="text-3xl font-black mb-2 bg-gradient-to-r from-blue-600 via-indigo-600 to-purple-600 bg-clip-text text-transparent" data-i18n="makeDeposit">Realizar Depósito</h2>
                <p class="text-sm text-gray-500" data-i18n="depositSteps">Siga os passos abaixo para fazer seu depósito via PIX</p>
            </div>

            <!-- Passo a Passo Colorido -->
            <div class="space-y-4 mb-6">
                <div class="bg-gradient-to-br from-blue-500 to-indigo-600 rounded-2xl p-5 shadow-xl border-2 border-blue-400 relative overflow-hidden">
                    <div class="absolute top-0 right-0 w-32 h-32 bg-white/10 rounded-full -mr-16 -mt-16"></div>
                    <div class="relative z-10 flex items-start gap-4">
                        <div class="w-12 h-12 bg-white rounded-full flex items-center justify-center flex-shrink-0 shadow-lg">
                            <span class="text-blue-600 font-black text-lg">1</span>
                        </div>
                        <div class="flex-1">
                            <h3 class="font-black text-white mb-2 text-lg" data-i18n="step1Title">Preencha os dados</h3>
                            <p class="text-sm text-white/90 leading-relaxed" data-i18n="step1Desc">Informe o valor e o CPF do titular da conta que fará o pagamento</p>
                        </div>
                    </div>
                </div>

                <div class="bg-gradient-to-br from-indigo-500 to-purple-600 rounded-2xl p-5 shadow-xl border-2 border-indigo-400 relative overflow-hidden">
                    <div class="absolute top-0 right-0 w-32 h-32 bg-white/10 rounded-full -mr-16 -mt-16"></div>
                    <div class="relative z-10 flex items-start gap-4">
                        <div class="w-12 h-12 bg-white rounded-full flex items-center justify-center flex-shrink-0 shadow-lg">
                            <span class="text-indigo-600 font-black text-lg">2</span>
                        </div>
                        <div class="flex-1">
                            <h3 class="font-black text-white mb-2 text-lg" data-i18n="step2Title">Gere o QR Code PIX</h3>
                            <p class="text-sm text-white/90 leading-relaxed" data-i18n="step2Desc">Clique em "Gerar PIX" e você receberá um QR Code para pagamento</p>
                        </div>
                    </div>
                </div>

                <div class="bg-gradient-to-br from-purple-500 to-pink-600 rounded-2xl p-5 shadow-xl border-2 border-purple-400 relative overflow-hidden">
                    <div class="absolute top-0 right-0 w-32 h-32 bg-white/10 rounded-full -mr-16 -mt-16"></div>
                    <div class="relative z-10 flex items-start gap-4">
                        <div class="w-12 h-12 bg-white rounded-full flex items-center justify-center flex-shrink-0 shadow-lg">
                            <span class="text-purple-600 font-black text-lg">3</span>
                        </div>
                        <div class="flex-1">
                            <h3 class="font-black text-white mb-2 text-lg" data-i18n="step3Title">Efetue o pagamento</h3>
                            <p class="text-sm text-white/90 leading-relaxed" data-i18n="step3Desc">Escaneie o QR Code ou copie o código PIX e pague pelo seu app bancário</p>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Alerta Importante -->
            <div class="bg-gradient-to-br from-yellow-400 via-orange-500 to-red-500 rounded-2xl p-5 mb-6 shadow-xl border-2 border-yellow-300 relative overflow-hidden">
                <div class="absolute inset-0 bg-black/5"></div>
                <div class="relative z-10 flex items-start gap-4">
                    <div class="w-12 h-12 bg-white rounded-full flex items-center justify-center flex-shrink-0 shadow-lg">
                        <i data-lucide="alert-triangle" class="w-6 h-6 text-yellow-600"></i>
                    </div>
                    <div class="flex-1">
                        <p class="text-sm font-black text-white mb-2" data-i18n="importantAttention">Atenção Importante</p>
                        <p class="text-xs text-white/95 leading-relaxed" data-i18n="depositWarningFull">
                            O <strong>CPF informado deve ser exatamente o mesmo</strong> do titular da conta bancária que realizará o pagamento. 
                            Caso contrário, o depósito <strong>não será processado automaticamente</strong>.
                        </p>
                    </div>
                </div>
            </div>

            <!-- Informações Adicionais -->
            <div class="grid grid-cols-2 gap-4 mb-6">
                <div class="bg-gradient-to-br from-emerald-400 to-teal-500 rounded-xl p-4 text-center shadow-lg">
                    <i data-lucide="zap" class="w-6 h-6 text-white mx-auto mb-2"></i>
                    <p class="text-xs font-black text-white mb-1" data-i18n="instantCredit">Crédito Instantâneo</p>
                    <p class="text-[10px] text-white/90" data-i18n="instantCreditDesc">Após pagamento</p>
                </div>
                <div class="bg-gradient-to-br from-cyan-400 to-blue-500 rounded-xl p-4 text-center shadow-lg">
                    <i data-lucide="shield-check" class="w-6 h-6 text-white mx-auto mb-2"></i>
                    <p class="text-xs font-black text-white mb-1" data-i18n="securePayment">Pagamento Seguro</p>
                    <p class="text-[10px] text-white/90" data-i18n="securePaymentDesc">100% protegido</p>
                </div>
            </div>

            <!-- Formulário -->
            <form onsubmit="doDeposit(event)" class="bg-gradient-to-br from-white to-gray-50 rounded-2xl p-6 shadow-2xl border-2 border-gray-200 relative overflow-hidden">
                <div class="absolute top-0 right-0 w-40 h-40 bg-blue-500/10 rounded-full -mr-20 -mt-20"></div>
                <div class="relative z-10">
                    <div class="mb-6">
                        <label class="lbl text-xs font-bold text-gray-700 uppercase mb-3 flex items-center gap-2" data-i18n="depositValue">
                            <i data-lucide="dollar-sign" class="w-4 h-4 text-blue-600"></i>
                            Valor do Depósito
                        </label>
                        <div class="relative">
                            <span class="absolute left-4 top-4 font-black text-blue-600 text-lg">R$</span>
                            <input type="text" name="amount" class="inp pl-12 money-mask text-lg font-bold" placeholder="0,00" required>
                        </div>
                        <p class="text-[10px] text-gray-500 mt-2 flex items-center gap-1" data-i18n="minValue">
                            <i data-lucide="info" class="w-3 h-3"></i>
                            Valor mínimo: R$ <?= number_format($config['min_dep']??10, 2, ',', '.') ?>
                        </p>
                    </div>

                    <div class="mb-6">
                        <label class="lbl text-xs font-bold text-gray-700 uppercase mb-3 flex items-center gap-2" data-i18n="cpfHolder">
                            <i data-lucide="user" class="w-4 h-4 text-indigo-600"></i>
                            CPF do Titular da Conta
                        </label>
                        <input type="text" name="cpf" id="depCpf" class="inp cpf-mask text-lg font-bold" placeholder="000.000.000-00" value="<?= $user['document'] ?>" required>
                        <p class="text-[10px] text-gray-500 mt-2 flex items-center gap-1" data-i18n="cpfHolderDesc">
                            <i data-lucide="info" class="w-3 h-3"></i>
                            CPF do titular da conta que fará o pagamento
                        </p>
                    </div>

                    <input type="hidden" name="action" value="generate_pix">
                    <button type="submit" class="btn bg-gradient-to-r from-blue-600 via-indigo-600 to-purple-600 text-white shadow-2xl w-full py-5 text-base font-black uppercase hover:shadow-blue-500/50 transition-all relative overflow-hidden group">
                        <span class="relative z-10 flex items-center justify-center gap-3">
                            <i data-lucide="qrcode" class="w-6 h-6 group-hover:scale-110 transition-transform"></i>
                            <span data-i18n="generatePixCode">Gerar QR Code PIX</span>
</span>
                        <div class="absolute inset-0 bg-gradient-to-r from-transparent via-white/20 to-transparent translate-x-[-100%] group-hover:translate-x-[100%] transition-transform duration-1000"></div>
                    </button>
                </div>
            </form>
        </div>

        <div id="view-withdraw" class="tab-view pb-24">
            <div class="mb-6 text-center">
                <div class="inline-flex items-center justify-center w-20 h-20 bg-gradient-to-br from-green-500 via-emerald-600 to-teal-600 rounded-full mb-4 shadow-xl">
                    <i data-lucide="arrow-up-circle" class="w-10 h-10 text-white"></i>
                </div>
                <h2 class="text-3xl font-black mb-2 bg-gradient-to-r from-green-600 via-emerald-600 to-teal-600 bg-clip-text text-transparent" data-i18n="requestWithdraw">Solicitar Saque</h2>
                <p class="text-sm text-gray-500" data-i18n="withdrawSteps">Siga os passos para solicitar sua retirada</p>
</div>

            <!-- Horário de Saque -->
            <div class="bg-gradient-to-br from-green-500 to-emerald-600 rounded-2xl p-5 mb-6 shadow-xl border-2 border-green-400 relative overflow-hidden">
                <div class="absolute top-0 right-0 w-32 h-32 bg-white/10 rounded-full -mr-16 -mt-16"></div>
                <div class="relative z-10 flex items-center justify-between">
                    <div>
                        <p class="text-xs font-bold text-white/80 uppercase mb-1" data-i18n="withdrawHours">Horário de Saque</p>
                        <p class="text-2xl font-black text-white">10:00 às 14:00</p>
                    </div>
                    <div class="w-16 h-16 bg-white/20 backdrop-blur-md rounded-xl flex items-center justify-center border-2 border-white/30">
                        <i data-lucide="clock" class="w-8 h-8 text-white"></i>
                    </div>
                </div>
                <p class="text-xs text-white/90 mt-4" data-i18n="withdrawHoursDesc">Saques são processados apenas em dias úteis (segunda a sexta) no horário acima.</p>
        </div>

            <!-- Passo a Passo Colorido -->
            <div class="space-y-4 mb-6">
                <div class="bg-gradient-to-br from-green-500 to-emerald-600 rounded-2xl p-5 shadow-xl border-2 border-green-400 relative overflow-hidden">
                    <div class="absolute top-0 right-0 w-32 h-32 bg-white/10 rounded-full -mr-16 -mt-16"></div>
                    <div class="relative z-10 flex items-start gap-4">
                        <div class="w-12 h-12 bg-white rounded-full flex items-center justify-center flex-shrink-0 shadow-lg">
                            <span class="text-green-600 font-black text-lg">1</span>
                        </div>
                        <div class="flex-1">
                            <h3 class="font-black text-white mb-2 text-lg" data-i18n="withdrawStep1Title">Configure sua Chave PIX</h3>
                            <p class="text-sm text-white/90 leading-relaxed" data-i18n="withdrawStep1Desc">Vá em "Perfil" e cadastre sua chave PIX antes de solicitar o saque</p>
                        </div>
                    </div>
                </div>

                <div class="bg-gradient-to-br from-emerald-500 to-teal-600 rounded-2xl p-5 shadow-xl border-2 border-emerald-400 relative overflow-hidden">
                    <div class="absolute top-0 right-0 w-32 h-32 bg-white/10 rounded-full -mr-16 -mt-16"></div>
                    <div class="relative z-10 flex items-start gap-4">
                        <div class="w-12 h-12 bg-white rounded-full flex items-center justify-center flex-shrink-0 shadow-lg">
                            <span class="text-emerald-600 font-black text-lg">2</span>
                        </div>
                        <div class="flex-1">
                            <h3 class="font-black text-white mb-2 text-lg" data-i18n="withdrawStep2Title">Informe o valor</h3>
                            <p class="text-sm text-white/90 leading-relaxed" data-i18n="withdrawStep2Desc">Digite o valor que deseja sacar (respeitando o mínimo e horário)</p>
                        </div>
                    </div>
                </div>

                <div class="bg-gradient-to-br from-teal-500 to-cyan-600 rounded-2xl p-5 shadow-xl border-2 border-teal-400 relative overflow-hidden">
                    <div class="absolute top-0 right-0 w-32 h-32 bg-white/10 rounded-full -mr-16 -mt-16"></div>
                    <div class="relative z-10 flex items-start gap-4">
                        <div class="w-12 h-12 bg-white rounded-full flex items-center justify-center flex-shrink-0 shadow-lg">
                            <span class="text-teal-600 font-black text-lg">3</span>
                        </div>
                        <div class="flex-1">
                            <h3 class="font-black text-white mb-2 text-lg" data-i18n="withdrawStep3Title">Aguarde a aprovação</h3>
                            <p class="text-sm text-white/90 leading-relaxed" data-i18n="withdrawStep3Desc">Sua solicitação será analisada e o valor será transferido para sua conta PIX</p>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Alerta Importante -->
            <div class="bg-gradient-to-br from-yellow-400 via-orange-500 to-red-500 rounded-2xl p-5 mb-6 shadow-xl border-2 border-yellow-300 relative overflow-hidden">
                <div class="absolute inset-0 bg-black/5"></div>
                <div class="relative z-10 flex items-start gap-4">
                    <div class="w-12 h-12 bg-white rounded-full flex items-center justify-center flex-shrink-0 shadow-lg">
                        <i data-lucide="alert-triangle" class="w-6 h-6 text-yellow-600"></i>
                    </div>
                    <div class="flex-1">
                        <p class="text-sm font-black text-white mb-2" data-i18n="importantAttention">Atenção Importante</p>
                        <p class="text-xs text-white/95 leading-relaxed" data-i18n="withdrawWarningFull">
                            O CPF da chave PIX cadastrada deve ser o mesmo do titular da conta. 
                            Saques fora do horário serão processados no próximo dia útil.
                        </p>
                    </div>
                </div>
            </div>

            <!-- Formulário -->
            <form onsubmit="api('request_withdrawal', new FormData(event.target)); event.preventDefault();" class="bg-gradient-to-br from-white to-gray-50 rounded-2xl p-6 shadow-2xl border-2 border-gray-200 relative overflow-hidden">
                <div class="absolute top-0 right-0 w-40 h-40 bg-green-500/10 rounded-full -mr-20 -mt-20"></div>
                <div class="relative z-10">
                    <div class="mb-6">
                        <label class="lbl text-xs font-bold text-gray-700 uppercase mb-3 flex items-center gap-2" data-i18n="withdrawValue">
                            <i data-lucide="dollar-sign" class="w-4 h-4 text-green-600"></i>
                            Valor do Saque
                        </label>
                        <div class="relative">
                            <span class="absolute left-4 top-4 font-black text-green-600 text-lg">R$</span>
                            <input type="text" name="value_withdrawal" class="inp pl-12 money-mask text-lg font-bold" placeholder="0,00" required>
                        </div>
                    </div>

                    <div class="grid grid-cols-2 gap-4 mb-6">
                        <div class="bg-gradient-to-br from-green-50 to-emerald-50 p-4 rounded-xl border border-green-200 text-center">
                            <p class="text-[10px] text-green-600 font-bold uppercase mb-1" data-i18n="withdrawMin">Mínimo</p>
                            <p class="text-lg font-black text-green-900">R$ <?= number_format($config['min_with']??20,2, ',', '.') ?></p>
                        </div>
                        <div class="bg-gradient-to-br from-orange-50 to-red-50 p-4 rounded-xl border border-orange-200 text-center">
                            <p class="text-[10px] text-orange-600 font-bold uppercase mb-1" data-i18n="withdrawRate">Taxa</p>
                            <p class="text-lg font-black text-orange-900"><?= $config['taxa_saq']??5 ?>%</p>
                        </div>
                    </div>

                    <button type="submit" class="btn bg-gradient-to-r from-green-600 via-emerald-600 to-teal-600 text-white shadow-2xl w-full py-5 text-base font-black uppercase hover:shadow-green-500/50 transition-all relative overflow-hidden group" id="withdrawBtn">
                        <span class="relative z-10 flex items-center justify-center gap-3">
                            <i data-lucide="arrow-up-circle" class="w-6 h-6 group-hover:scale-110 transition-transform"></i>
                            <span data-i18n="requestWithdrawal">Solicitar Retirada</span>
                        </span>
                        <div class="absolute inset-0 bg-gradient-to-r from-transparent via-white/20 to-transparent translate-x-[-100%] group-hover:translate-x-[100%] transition-transform duration-1000"></div>
                    </button>
                </div>
            </form>
        </div>

        <div id="view-points" class="tab-view pb-32">
            <div class="mb-8">
                <h2 class="text-3xl font-black mb-2 bg-gradient-to-r from-purple-600 via-pink-600 to-rose-600 bg-clip-text text-transparent animate-fadeInUp">Troca de Pontos</h2>
                <p class="text-sm text-gray-500">Converta seus pontos em dinheiro ou produtos</p>
            </div>

            <!-- Card de Pontos Atuais -->
            <div class="bg-gradient-to-br from-purple-500 via-pink-500 to-rose-600 rounded-2xl p-6 mb-6 shadow-xl text-white">
                <div class="flex items-center justify-between">
                    <div>
                        <p class="text-sm text-white/80 font-bold uppercase mb-2">Pontos Disponíveis</p>
                        <p class="text-4xl font-black" id="pointsBalance"><?= number_format((int)($user['qtd_points'] ?? 0), 0, ',', '.') ?></p>
                        <p class="text-xs text-white/70 mt-2">Equivale a R$ <?= number_format(((int)($user['qtd_points'] ?? 0) / 100), 2, ',', '.') ?></p>
                    </div>
                    <div class="w-20 h-20 bg-white/20 backdrop-blur-md rounded-2xl flex items-center justify-center border border-white/30">
                        <i data-lucide="gift" class="w-10 h-10"></i>
                    </div>
                </div>
            </div>

            <!-- Converter em Dinheiro -->
            <div class="bg-white rounded-2xl p-6 mb-6 shadow-lg border-2 border-gray-100">
                <h3 class="text-xl font-black text-gray-800 mb-4 flex items-center gap-2">
                    <i data-lucide="dollar-sign" class="w-6 h-6 text-green-600"></i>
                    Converter em Dinheiro
                </h3>
                <p class="text-sm text-gray-600 mb-4">100 pontos = R$ 1,00</p>
                <div class="space-y-4">
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-2">Quantidade de Pontos</label>
                        <input type="number" id="pointsToMoney" min="100" step="100" placeholder="Mínimo 100 pontos" class="w-full px-4 py-3 border border-gray-300 rounded-xl focus:ring-2 focus:ring-purple-500 focus:border-transparent" oninput="updateMoneyPreview()">
                        <p class="text-xs text-gray-500 mt-1">Você receberá: <span id="moneyPreview" class="font-bold text-green-600">R$ 0,00</span></p>
                    </div>
                    <button onclick="convertPointsToMoney()" class="w-full px-6 py-3 bg-gradient-to-r from-green-500 to-emerald-600 text-white rounded-xl font-bold shadow-lg hover:shadow-xl transition-all">
                        <i data-lucide="arrow-right" class="w-5 h-5 inline"></i> Converter em Dinheiro
                    </button>
                </div>
            </div>

            <!-- Converter em Produtos -->
            <div class="bg-white rounded-2xl p-6 shadow-lg border-2 border-gray-100">
                <h3 class="text-xl font-black text-gray-800 mb-4 flex items-center gap-2">
                    <i data-lucide="package" class="w-6 h-6 text-blue-600"></i>
                    Converter em Produtos
                </h3>
                <p class="text-sm text-gray-600 mb-4">Use seus pontos para adquirir produtos de investimento</p>
                <div class="space-y-4">
                    <?php
                    // Todos os produtos podem ser comprados com pontos (preço = valor * 100)
                    $productsWithPoints = $pdo->query("SELECT * FROM investment_products WHERE is_active = 1 ORDER BY value ASC")->fetchAll(PDO::FETCH_ASSOC);
                    if (empty($productsWithPoints)):
                    ?>
                        <p class="text-center text-gray-500 py-8">Nenhum produto disponível para troca de pontos no momento.</p>
                    <?php else: ?>
                        <?php foreach ($productsWithPoints as $prod): 
                            // Preço em pontos = valor do produto * 100 (porque 100 pontos = R$ 1,00)
                            $productPriceInPoints = (int)($prod['value'] * 100);
                            $canAfford = (int)($user['qtd_points'] ?? 0) >= $productPriceInPoints;
                            $stmtVerify = $pdo->prepare("SELECT COUNT(*) FROM investments WHERE product_id = ? AND user_id = ?");
                            $stmtVerify->execute([$prod['id'], $user['id']]);
                            $totalPurchased = $stmtVerify->fetchColumn();
                            $canBuy = $totalPurchased < $prod['limit_purchase'] && $prod['total_purchases'] < $prod['available'];
                        ?>
                        <div class="border-2 <?= $canAfford && $canBuy ? 'border-blue-300' : 'border-gray-200 opacity-60' ?> rounded-xl p-4 hover:shadow-lg transition-all">
                            <div class="flex items-start gap-4">
                                <img src="<?= htmlspecialchars($prod['img']) ?>" alt="<?= htmlspecialchars($prod['name']) ?>" class="w-20 h-20 rounded-xl object-cover">
                                <div class="flex-1">
                                    <h4 class="font-black text-lg text-gray-800 mb-1"><?= htmlspecialchars($prod['name']) ?></h4>
                                    <p class="text-xs text-gray-600 mb-2"><?= htmlspecialchars($prod['description'] ?? '') ?></p>
                                    <div class="flex items-center gap-4 text-sm">
                                        <div>
                                            <span class="text-gray-500">Retorno:</span>
                                            <span class="font-bold text-green-600"><?= number_format($prod['total_return'], 2, ',', '.') ?>%</span>
                                        </div>
                                        <div>
                                            <span class="text-gray-500">Duração:</span>
                                            <span class="font-bold"><?= $prod['total_days'] ?> dias</span>
                                        </div>
                                    </div>
                                    <div class="mt-3 flex items-center justify-between">
                                        <div class="flex items-center gap-2">
                                            <i data-lucide="gift" class="w-4 h-4 text-purple-600"></i>
                                            <span class="font-black text-purple-600"><?= number_format($productPriceInPoints, 0, ',', '.') ?> pontos</span>
                                        </div>
                                        <button onclick="convertPointsToProduct(<?= $prod['id'] ?>, <?= $productPriceInPoints ?>)" 
                                                class="px-4 py-2 rounded-lg font-bold text-sm transition <?= $canAfford && $canBuy ? 'bg-blue-600 hover:bg-blue-700' : 'bg-gray-300 cursor-not-allowed' ?> <?= $canAfford && $canBuy ? 'text-white' : 'text-gray-500' ?>"
                                                <?= !$canAfford || !$canBuy ? 'disabled' : '' ?>>
                                            <?= !$canAfford ? 'Pontos Insuficientes' : (!$canBuy ? 'Indisponível' : 'Trocar') ?>
                                        </button>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </div>
            </div>
        </div>

        <div id="view-tasks" class="tab-view pb-32">
            <div class="mb-8">
                <!--    <h2 class="text-3xl font-black mb-2 bg-gradient-to-r from-orange-500 via-pink-500 to-red-500 bg-clip-text text-transparent animate-fadeInUp" data-i18n="dailyTasks">Tarefas Diárias</h2>-->
                <!--<p class="text-sm text-gray-500">Complete tarefas e ganhe recompensas!</p>-->
            </div>
            <div id="tasksList" class="space-y-4">
                <div class="text-center py-8 text-gray-400">
                    <i data-lucide="loader" class="w-8 h-8 mx-auto mb-2 animate-spin"></i>
                    <p class="text-sm">Carregando tarefas...</p>
                </div>
            </div>
        </div>

    </div>
    
    <div id="modalPix" class="modal bg-gray-50">
    <div class="p-5 bg-white border-b flex justify-between items-center sticky top-0">
        <h3 class="font-bold text-gray-900 uppercase">Minha Chave PIX</h3>
        <button onclick="document.getElementById('modalPix').classList.remove('open')" class="w-8 h-8 bg-gray-100 rounded-full flex items-center justify-center"><i data-lucide="x" class="w-4 h-4"></i></button>
    </div>
    <div class="p-5">
        <div class="flex items-start gap-3 rounded-lg border border-yellow-400/40 bg-yellow-400/10 px-4 py-3 mb-4 text-yellow-800">
    <i data-lucide="alert-triangle" class="w-5 h-5 mt-0.5 flex-shrink-0"></i>

  <span class="text-sm leading-relaxed">
    <strong class="font-semibold">Atenção:</strong>
    Insira abaixo o <strong>CPF do titular da conta bancária</strong>
    onde será realizado o saque. O CPF deve coincidir exatamente com o do titular.
    <strong>Caso o CPF seja diferente, o saque não será efetuado.</strong>
</span>

</div>

        <form onsubmit="savePix(event)">
            <input type="hidden" name="action" value="save_pix">
            <label class="lbl block text-xs font-bold text-gray-500 uppercase mb-2">Tipo de Chave</label>
            <select name="type_pix" class="w-full p-4 bg-white border rounded-xl mb-3 outline-none">
                <option value="CPF" <?= ($pixData['type_pix']??'')=='CPF'?'selected':'' ?>>CPF</option>
                <option value="PHONE" <?= ($pixData['type_pix']??'')=='PHONE'?'selected':'' ?>>Telefone</option>
                <option value="EMAIL" <?= ($pixData['type_pix']??'')=='EMAIL'?'selected':'' ?>>E-mail</option>
            </select>
            <input name="key_beneficiary" placeholder="Sua Chave" class="w-full p-4 bg-white border rounded-xl mb-3 outline-none" required value="<?= $pixData['key_beneficiary']??'' ?>">
            <input name="name_beneficiary" placeholder="Nome do Titular" class="w-full p-4 bg-white border rounded-xl mb-3 outline-none" required value="<?= $pixData['name_beneficiary']??'' ?>">
            <input name="cpf_beneficiary" placeholder="CPF do Titular" class="w-full p-4 bg-white border rounded-xl mb-6 outline-none cpf-mask" required value="<?= $pixData['cpf_beneficiary']??'' ?>">
            <button type="submit" class="btn bg-vip-blue text-white shadow-lg">Guardar Chave</button>
        </form>
    </div>
</div>

    <div id="modalDetails" class="modal bg-gray-50">

    <!-- HEADER -->
    <div class="p-5 bg-white border-b flex justify-between items-center sticky top-0 z-20">
        <h3 class="font-bold text-gray-900 uppercase">Detalhes</h3>
        <button onclick="document.getElementById('modalDetails').classList.remove('open')" class="w-8 h-8 bg-gray-100 rounded-full flex items-center justify-center">
            <i data-lucide="x" class="w-4 h-4"></i>
        </button>
    </div>

    <!-- CONTENT -->
    <div class="p-0 pb-10">
        <img id="d-img" src="" class="w-full h-64 object-cover">

        <div class="p-6 bg-white rounded-t-3xl -mt-6 relative">

            <span id="d-type" class="text-[10px] font-bold uppercase bg-blue-100 text-vip-blue px-2 py-1 rounded mb-2 inline-block"></span>

            <h2 id="d-name" class="text-2xl font-bold text-gray-900 mb-2 leading-tight"></h2>

            <p id="d-desc" class="text-sm text-gray-500 mb-6 leading-relaxed"></p>

            <!-- RETORNOS -->
            <div class="grid grid-cols-2 gap-3 mb-6">
                <div class="bg-gray-50 p-3 rounded-xl border border-gray-100">
                    <p class="text-[10px] text-gray-400 font-bold uppercase">Retorno Diario</p>
                    <p id="d-daily" class="text-lg font-bold text-gray-800">R$ 0,00</p>
                </div>

                <div class="bg-gray-50 p-3 rounded-xl border border-gray-100">
                    <p class="text-[10px] text-gray-400 font-bold uppercase">Retorno Total</p>
                    <p id="d-total" class="text-lg font-bold text-vip-blue">R$ 0,00</p>
                </div>
            </div>

            <!-- DURACIÓN + STOCK (CORRIGIDO) -->
            <div class="grid grid-cols-2 gap-3 mb-6">

                <!-- DURACIÓN -->
                <div class="bg-gray-50 p-3 rounded-xl border border-gray-100 flex items-center gap-3">
                    <div class="w-9 h-9 rounded-full bg-blue-100 flex items-center justify-center">
                        <i data-lucide="calendar" class="w-4 h-4 text-vip-blue"></i>
                    </div>
                    <div>
                        <p class="text-[10px] text-gray-400 font-bold uppercase">Duração</p>
                        <strong id="d-days" class="text-sm font-bold text-gray-800">0 Días</strong>
                    </div>
                </div>

                <!-- STOCK -->
                <div class="bg-gray-50 p-3 rounded-xl border border-gray-100 flex items-center gap-3">
                    <div class="w-9 h-9 rounded-full bg-green-100 flex items-center justify-center">
                        <i data-lucide="package" class="w-4 h-4 text-vip-green"></i>
                    </div>
                    <div>
                        <p class="text-[10px] text-gray-400 font-bold uppercase">Estoque</p>
                        <strong id="d-stock" class="text-sm font-bold text-gray-800">0</strong>
                    </div>
                </div>

            </div>
            
            <div class="space-y-3 mb-6">

    <div class="flex justify-between text-sm">
        <span class="text-gray-500">Valor do investimento</span>
        <strong id="d-value" class="text-gray-900">R$ 0,00</strong>
    </div>

    <div class="flex justify-between text-sm">
        <span class="text-gray-500">Tipo de retorno</span>
        <strong id="d-return-type" class="text-gray-900">—</strong>
    </div>

    <div class="flex justify-between text-sm">
        <span class="text-gray-500">Limite por usuário</span>
        <strong id="d-limit" class="text-gray-900">—</strong>
    </div>

    <div class="flex justify-between text-sm">
        <span class="text-gray-500">Status</span>
        <strong id="d-status" class="text-green-600 font-bold">Ativo</strong>
    </div>

    <!-- ALERTAS -->
    <div id="d-alert" class="hidden text-xs font-bold rounded-lg p-3"></div>

    <!-- PONTOS GERADOS -->
    <div id="d-points-container" class="hidden mt-4 mb-4">
        <div class="bg-gradient-to-r from-purple-500 via-pink-500 to-rose-500 rounded-2xl p-5 shadow-2xl border-2 border-purple-300/50 relative overflow-hidden group/points">
            <div class="absolute inset-0 bg-gradient-to-r from-transparent via-white/20 to-transparent translate-x-[-100%] group-hover/points:translate-x-[100%] transition-transform duration-1500"></div>
            <div class="relative z-10">
                <div class="flex items-center gap-3 mb-3">
                    <div class="w-10 h-10 bg-white/20 backdrop-blur-sm rounded-xl flex items-center justify-center border-2 border-white/30">
                        <i data-lucide="sparkles" class="w-5 h-5 text-white"></i>
                    </div>
                    <div>
                        <p class="text-xs font-bold text-white/90 uppercase tracking-wider">Pontos ao Comprar</p>
                        <p class="text-xl font-black text-white" id="d-points-amount">+0 pontos</p>
                    </div>
                </div>
                <div class="grid grid-cols-2 gap-3 mt-3">
                    <div class="bg-white/20 backdrop-blur-sm px-3 py-2 rounded-xl border-2 border-white/30">
                        <p class="text-[10px] text-white/90 font-bold uppercase mb-1">Você recebe</p>
                        <p class="text-base font-black text-white" id="d-points-user">0 pontos</p>
                    </div>
                    <div class="bg-white/20 backdrop-blur-sm px-3 py-2 rounded-xl border-2 border-white/30">
                        <p class="text-[10px] text-white/90 font-bold uppercase mb-1">Indicado Nível 1</p>
                        <p class="text-base font-black text-white" id="d-points-referrer">0 pontos</p>
                    </div>
                </div>
                <div class="mt-3 pt-3 border-t border-white/30">
                    <div class="flex items-center justify-between">
                        <p class="text-[10px] text-white/80">Equivale a</p>
                        <p class="text-sm font-black text-white" id="d-points-money">R$ 0,00</p>
                    </div>
                </div>
            </div>
            <div class="absolute top-0 right-0 w-24 h-24 bg-white/10 rounded-full blur-2xl animate-pulse"></div>
        </div>
    </div>

</div>

            <!-- AÇÃO -->
            <div id="d-action"></div>

        </div>
    </div>
</div>

<div id="modalPay" class="modal !bg-black/80 backdrop-blur-md flex items-center justify-center p-4" style="z-index: 3000;">
    <div class="bg-gradient-to-br from-white via-blue-50 to-indigo-50 w-full max-w-md rounded-3xl p-6 text-center relative animate-up shadow-2xl border-2 border-blue-200 overflow-hidden">
        <div class="absolute top-0 right-0 w-40 h-40 bg-blue-500/20 rounded-full -mr-20 -mt-20"></div>
        <div class="absolute bottom-0 left-0 w-32 h-32 bg-indigo-500/20 rounded-full -ml-16 -mb-16"></div>
        
        <button onclick="document.getElementById('modalPay').classList.remove('open')" class="absolute top-4 right-4 w-10 h-10 bg-white/90 hover:bg-white rounded-full flex items-center justify-center shadow-lg transition-all z-10">
            <i data-lucide="x" class="w-5 h-5 text-gray-600"></i>
        </button>
        
        <div class="relative z-10">
            <div class="inline-flex items-center justify-center w-16 h-16 bg-gradient-to-br from-blue-500 to-indigo-600 rounded-full mb-4 shadow-xl">
                <i data-lucide="qrcode" class="w-8 h-8 text-white"></i>
            </div>
            
            <h3 class="font-black text-2xl mb-2 bg-gradient-to-r from-blue-600 to-indigo-600 bg-clip-text text-transparent" data-i18n="payTitle">Pagar via PIX</h3>
            <p class="text-sm text-gray-600 mb-6" data-i18n="autoCredit">Saldo creditado automaticamente após o pagamento</p>
            
            <div class="bg-white rounded-2xl p-4 mb-4 shadow-lg border-2 border-blue-100 relative overflow-hidden">
                <div class="absolute inset-0 bg-gradient-to-br from-blue-500/5 to-indigo-500/5"></div>
                <img id="qrImg" class="w-64 h-64 mx-auto border-4 border-blue-200 p-3 rounded-2xl bg-white shadow-inner relative z-10">
            </div>
            
            <div class="mb-4">
                <label class="block text-xs font-bold text-gray-600 uppercase mb-2" data-i18n="pixCode">Código PIX</label>
                <div class="relative">
                    <input id="qrCode" class="w-full bg-gradient-to-r from-gray-50 to-blue-50 border-2 border-blue-200 p-4 rounded-xl text-xs font-mono text-center truncate text-gray-700 focus:border-blue-400 focus:outline-none transition-all" readonly>
                    <button onclick="copyPixCode()" class="absolute right-2 top-2 w-8 h-8 bg-blue-600 hover:bg-blue-700 rounded-lg flex items-center justify-center transition-all">
                        <i data-lucide="copy" class="w-4 h-4 text-white"></i>
                    </button>
                </div>
            </div>
            
            <div class="bg-gradient-to-r from-blue-500/10 to-indigo-500/10 rounded-xl p-4 mb-4 border border-blue-200">
                <div class="flex items-center justify-center gap-2 text-xs text-gray-700">
                    <i data-lucide="info" class="w-4 h-4 text-blue-600"></i>
                    <span data-i18n="pixInstructions">Escaneie o QR Code ou copie o código PIX e pague pelo seu app bancário</span>
                </div>
            </div>
            
            <button onclick="copyPixCode()" class="btn bg-gradient-to-r from-blue-600 via-indigo-600 to-purple-600 text-white shadow-xl w-full py-4 text-sm font-black uppercase hover:shadow-2xl transition-all relative overflow-hidden group">
                <span class="relative z-10 flex items-center justify-center gap-2">
                    <i data-lucide="copy" class="w-5 h-5"></i>
                    <span data-i18n="copyCode">Copiar Código PIX</span>
                </span>
                <div class="absolute inset-0 bg-gradient-to-r from-transparent via-white/20 to-transparent translate-x-[-100%] group-hover:translate-x-[100%] transition-transform duration-1000"></div>
            </button>
        </div>
    </div>
</div>


    <script>
        lucide.createIcons();

        function playClick() { const audio = document.getElementById('clickSound'); if (audio) { audio.currentTime = 0; audio.play().catch(e=>{}); } }
        document.addEventListener('click', playClick);

        function playToastSound(type = 'ok') {
            const success = document.getElementById('successSound');
            const error = document.getElementById('errorSound');
            try {
                if (type === 'err' && error) {
                    error.currentTime = 0;
                    error.play().catch(()=>{});
                } else if (success) {
                    success.currentTime = 0;
                    success.play().catch(()=>{});
                }
            } catch (e) {}
        }

        function nav(view) {
            const body = document.body;
            const back = document.getElementById('backBtn');
            const tabs = document.getElementById('mainTab');
            document.querySelectorAll('.tab-view').forEach(e => e.classList.remove('active'));
            if(['news', 'market', 'tasks', 'assets', 'profile', 'team', 'points'].includes(view)) {
                body.classList.remove('mini');
                if(back) back.classList.add('hidden');
                if(tabs) tabs.style.display = 'flex';
                const el = document.getElementById('view-'+view);
                if(el) el.classList.add('active');
                updateTabs(view);
                if (view === 'team' && typeof loadAffiliateDashboard === 'function') {
                    loadAffiliateDashboard();
                }
                if (view === 'tasks' && typeof loadTasks === 'function') {
                    loadTasks();
                }
                history.pushState(null, '', '?view='+view);
            } else {
                body.classList.add('mini');
                if(back) back.classList.remove('hidden');
                if(tabs) tabs.style.display = 'none';
                const el = document.getElementById('view-'+view);
                if(el) el.classList.add('active');
                history.pushState(null, '', '?view='+view);
            }
            window.scrollTo({top:0, behavior:'smooth'});
        }

        function tab(t) { 
            nav(t);
            if (t === 'tasks') {
                loadTasks();
            }
        }

        async function loadTasks() {
            const list = document.getElementById('tasksList');
            if (!list) return;
            try {
                const fd = new FormData();
                fd.append('action', 'get_tasks');
                const res = await fetch('', { method: 'POST', body: fd });
                const json = await res.json();
                if (json.status === 'success' && json.tasks) {
                    renderTasks(json.tasks);
                } else {
                    list.innerHTML = '<div class="text-center py-8 text-gray-400"><p class="text-sm">Erro ao carregar tarefas.</p></div>';
                }
            } catch (e) {
                list.innerHTML = '<div class="text-center py-8 text-gray-400"><p class="text-sm">Erro ao carregar tarefas.</p></div>';
            }
        }

        function renderTasks(tasks) {
            const list = document.getElementById('tasksList');
            if (!list) return;
            if (!tasks || tasks.length === 0) {
                list.innerHTML = '<div class="text-center py-8 text-gray-400"><p class="text-sm">Nenhuma tarefa disponível.</p></div>';
                return;
            }
            list.innerHTML = tasks.map(t => `
                <div class="bg-white rounded-xl border border-gray-200 p-4 ${t.completed ? 'opacity-60' : ''}">
                    <div class="flex items-start justify-between gap-4">
                        <div class="flex items-start gap-3 flex-1">
                            <div class="w-12 h-12 rounded-xl ${t.completed ? 'bg-green-100' : 'bg-blue-100'} flex items-center justify-center flex-shrink-0">
                                <i data-lucide="${t.icon || 'check-circle'}" class="w-6 h-6 ${t.completed ? 'text-green-600' : 'text-blue-600'}"></i>
                            </div>
                            <div class="flex-1">
                                <h3 class="font-black text-gray-900 text-sm mb-1">${t.name}</h3>
                                <p class="text-xs text-gray-500 mb-2">Recompensa: <span class="font-bold text-green-600">R$ ${Number(t.reward).toFixed(2).replace('.', ',')}</span></p>
                                ${t.completed ? '<span class="inline-block px-2 py-1 bg-green-100 text-green-700 text-[10px] font-bold rounded">✓ Completada</span>' : ''}
                            </div>
                        </div>
                        <button onclick="completeTask('${t.type}')" 
                            class="px-4 py-2 rounded-xl font-bold text-xs uppercase transition ${t.completed ? 'bg-gray-100 text-gray-400 cursor-not-allowed' : t.can_complete ? 'bg-green-500 text-white hover:bg-green-600 active:scale-95' : 'bg-gray-200 text-gray-500 cursor-not-allowed'}"
                            ${t.completed || !t.can_complete ? 'disabled' : ''}>
                            ${t.completed ? 'Completa' : t.can_complete ? 'Completar' : 'Bloqueada'}
                        </button>
                    </div>
                </div>
            `).join('');
            lucide.createIcons();
        }

        async function completeTask(taskType) {
            try {
                const fd = new FormData();
                fd.append('action', 'complete_task');
                fd.append('task_type', taskType);
                const res = await fetch('', { method: 'POST', body: fd });
                const json = await res.json();
                if (json.status === 'success') {
                    toast(json.message || 'Tarefa completada!', 'ok');
                    loadTasks();
                    // Atualizar saldo
                    const balEl = document.getElementById('balDisplay');
                    if (balEl) {
                        const fd2 = new FormData();
                        fd2.append('action', 'get_balance');
                        const res2 = await fetch('', { method: 'POST', body: fd2 });
                        const json2 = await res2.json();
                        if (json2.status === 'success' && json2.balance) {
                            balEl.innerText = "R$ " + json2.balance;
                        }
                    }
                } else {
                    toast(json.message || 'Erro ao completar tarefa', 'err');
                }
            } catch (e) {
                toast('Erro de conexão', 'err');
            }
        }

        function updateTabs(viewName) {
            // Atualizar menu top
            const map = {'news':0, 'market':1, 'tasks':2, 'assets':3, 'team':4, 'profile':5, 'points':6};
            const idx = map[viewName];
            const parent = document.getElementById('mainTab');
            if(!parent || idx === undefined) return;
            const btns = parent.children;
            for(let i=0; i<btns.length; i++) {
                btns[i].classList.remove('bg-vip-blue', 'text-white', 'shadow-md');
                btns[i].classList.add('text-gray-400', 'hover:bg-gray-50');
            }
            if(btns[idx]) {
                btns[idx].classList.remove('text-gray-400', 'hover:bg-gray-50');
                btns[idx].classList.add('bg-vip-blue', 'text-white', 'shadow-md');
            }
            
            // Atualizar menu bottom também
            const menuItems = {
                'news': 'btn-news',
                'market': 'btn-market',
                'assets': 'btn-assets',
                'team': 'btn-team',
                'profile': 'btn-vip-center'
            };
            
            document.querySelectorAll('.menu-item').forEach(item => {
                item.classList.remove('active');
            });
            
            const activeBtnId = menuItems[viewName];
            if (activeBtnId) {
                const activeBtn = document.getElementById(activeBtnId);
                if (activeBtn) {
                    activeBtn.classList.add('active');
                }
            }
            
            lucide.createIcons();
        }
        
        function subTab(lvl) {
            document.querySelectorAll('.tab-btn').forEach(b => b.classList.remove('active-sub'));
            document.getElementById(`sub-${lvl}`).classList.add('active-sub');
            [1,2,3].forEach(i => {
                const list = document.getElementById(`list-${i}`);
                if(list) list.classList.add('hidden');
            });
            const target = document.getElementById(`list-${lvl}`);
            if(target) target.classList.remove('hidden');
        }
        
        let timeLeft = <?= (int)$tempo_restante_segundos ?>;
        function startTimer() {
            const btn = document.getElementById('btnColeta');
            const timerEl = document.getElementById('timerColeta');
            if (!btn) return;
            if (timeLeft > 0) {
                btn.disabled = true;
                const interval = setInterval(() => {
                    if (timeLeft <= 0) { clearInterval(interval); btn.disabled = false; timerEl.innerText = "¡Ganancias listas!"; return; }
                    const h = String(Math.floor(timeLeft / 3600)).padStart(2,'0');
                    const m = String(Math.floor((timeLeft % 3600) / 60)).padStart(2,'0');
                    const s = String(timeLeft % 60).padStart(2,'0');
                    timerEl.innerText = `${h}:${m}:${s}`;
                    timeLeft--;
                }, 1000);
            } else { btn.disabled = false; timerEl.innerText = "¡Ganancias listas!"; }
        }
        startTimer();

        // Inicializar menu bottom ativo
        window.addEventListener('load', () => {
            const params = new URLSearchParams(window.location.search);
            const view = params.get('view') || 'news';
            updateTabs(view);
        });

        async function api(act, data, isPay=false) {
            const btn = document.activeElement; 
            const oldHtml = btn ? btn.innerHTML : '';
            const btnId = btn?.id || '';
            
            // Adicionar loading em todos os botões
            if(btn && btn.tagName === 'BUTTON') { 
                btn.disabled = true; 
                const loadingHtml = '<span class="flex items-center justify-center gap-2"><i data-lucide="loader-2" class="w-5 h-5 animate-spin"></i><span>Processando...</span></span>';
                btn.innerHTML = loadingHtml; 
                lucide.createIcons(); 
            }
            
            const fd = data instanceof FormData ? data : new FormData();
            fd.append('action', act);
            if (!(data instanceof FormData)) { for (let key in data) fd.append(key, data[key]); }

            try {
                const req = await fetch('', { method: 'POST', body: fd });
                const res = await req.json();
                if(res.status === 'success') {
                    if(isPay) {
                        document.getElementById('qrImg').src = res.qrcode_img;
                        document.getElementById('qrCode').value = res.qrcode_text;
                        document.getElementById('modalPay').classList.add('open');
                    } else {
                        if(res.new_balance) document.getElementById('balDisplay').innerText = "R$ " + res.new_balance;
                        if(res.new_points !== undefined) {
                            updatePointsDisplay(res.new_points);
                            // Atualizar badges de pontos nos produtos
                            document.querySelectorAll('[data-product-points]').forEach(el => {
                                const productPoints = parseInt(el.getAttribute('data-product-points'));
                                const userPoints = parseInt(res.new_points);
                                if(userPoints >= productPoints) {
                                    el.classList.remove('opacity-60');
                                    el.classList.add('animate-pulse');
                                } else {
                                    el.classList.add('opacity-60');
                                    el.classList.remove('animate-pulse');
                                }
                            });
                        }
                        toast(res.message);
                        if(res.reload) setTimeout(() => location.reload(), 1500);
                    }
                } else { toast(res.message, 'err'); }
            } catch(e) { toast('Error de conexión' + e, 'err'); }
            finally { 
                if(btn && btn.tagName === 'BUTTON') { 
                    btn.disabled = false; 
                    btn.innerHTML = oldHtml; 
                    lucide.createIcons(); 
                }
            }
        }

        function toast(msg, type='ok') {
            const t = document.createElement('div');
            t.className = `toast show ${type === 'err' ? 'err' : ''}`;
            t.style.background = type === 'err' ? '#EF4444' : '#10B981';
            t.style.display = 'block';
            t.innerText = msg;
            document.getElementById('toast-area').appendChild(t);
            // Som específico para sucesso/erro
            playToastSound(type);
            setTimeout(() => { t.remove(); }, 3000);
        }

        // ============================================================
        //  MODAL DE ENTRADA
        // ============================================================
        function openEntryModal() {
            const m = document.getElementById('entryModal');
            if (!m) return;
            m.classList.add('open');
            lucide.createIcons();
        }
        function closeEntryModal() {
            const m = document.getElementById('entryModal');
            if (!m) return;
            m.classList.remove('open');
        }

        // ============================================================
        //  MODAL DE CUPOM
        // ============================================================
        function openCupomModal() {
            const m = document.getElementById('cupomSuccessModal');
            if (!m) return;
            m.classList.add('open');
            lucide.createIcons();
            
            // Confetti
            if (typeof confetti !== 'undefined') {
                confetti({
                    particleCount: 200,
                    spread: 120,
                    origin: { y: 0.5 },
                    colors: ['#10B981', '#34D399', '#6EE7B7', '#A7F3D0']
                });
            }
        }

        function closeCupomModal() {
            const m = document.getElementById('cupomSuccessModal');
            if (!m) return;
            m.classList.remove('open');
        }

        // Sempre abre ao carregar quando a view inicial for Início/Investir
        window.addEventListener('load', () => {
            // Verificar se há cupom resgatado
            <?php if ($showCupomModal): ?>
            setTimeout(() => {
                openCupomModal();
                // Tocar som de sucesso ao abrir modal de cupom
                const success = document.getElementById('successSound');
                if (success) {
                    success.currentTime = 0;
                    success.play().catch(()=>{});
                }
                // Atualizar saldo
                const balEl = document.getElementById('balDisplay');
                if (balEl) {
                    const fd = new FormData();
                    fd.append('action', 'get_balance');
                    fetch('', { method: 'POST', body: fd })
                        .then(r => r.json())
                        .then(data => {
                            if (data.status === 'success' && data.balance) {
                                balEl.innerText = "R$ " + data.balance;
                            }
                        });
                }
            }, 500);
            <?php endif; ?>
            
            // Mostrar toast se houver mensagem
            <?php if ($cupomToastMessage): ?>
            setTimeout(() => {
                const toastType = '<?= $cupomToastType === 'error' ? 'err' : 'ok' ?>';
                toast('<?= htmlspecialchars($cupomToastMessage) ?>', toastType);
                // O som já é tocado pela função toast() via playToastSound()
            }, <?= $showCupomModal ? '2000' : '500' ?>);
            <?php endif; ?>
            
            const params = new URLSearchParams(window.location.search);
            const view = params.get('view') || 'news';
            // Não abrir modal de entrada se houver cupom modal
            if (!<?= $showCupomModal ? 'true' : 'false' ?>) {
                if (view === 'news' || view === 'market') {
                    // TODO: troque aqui pelo link real do grupo oficial (Telegram/WhatsApp)
                    const groupBtn = document.getElementById('entryModalGroupBtn');
                    if (groupBtn) groupBtn.href = "https://t.me/";
                    openEntryModal();
                } else {
                    closeEntryModal();
                }
            }
        });

        // ============================================================
        //  ATUALIZAÇÃO PERIÓDICA DO SALDO (QUASE TEMPO REAL)
        // ============================================================
        (function initBalanceWatcher(){
            const balEl = document.getElementById('balDisplay');
            if (!balEl) return;

            let lastText = balEl.innerText.trim();

            async function refreshBalance() {
                try {
                    const fd = new FormData();
                    fd.append('action', 'get_balance');
                    const res = await fetch('', { method: 'POST', body: fd });
                    const json = await res.json();
                    if (json.status === 'success' && json.balance) {
                        const newText = "R$ " + json.balance;
                        if (newText !== lastText) {
                            lastText = newText;
                            balEl.innerText = newText;
                        }
                    }
                } catch (e) {
                    // falha silenciosa para não atrapalhar a experiência
                }
            }

            // chama uma vez logo no início e depois em intervalo
            refreshBalance();
            setInterval(refreshBalance, 10000); // 10s
        })();

        // ============================================================
        //  MÚSICA + IDIOMA
        // ============================================================
        const bgPlayer = document.getElementById('bgPlayer');
        let currentTrack = null;
        // Músicas usando links diretos funcionais (sem Pixabay)
        const tracksArg = [
            { title: 'La Triple T - TINI', url: 'https://www.soundhelix.com/examples/mp3/SoundHelix-Song-1.mp3' },
            { title: 'BZRP Session', url: 'https://www.soundhelix.com/examples/mp3/SoundHelix-Song-2.mp3' },
            { title: 'Cupido - TINI', url: 'https://www.soundhelix.com/examples/mp3/SoundHelix-Song-3.mp3' },
            { title: 'Música Argentina 4', url: 'https://www.soundhelix.com/examples/mp3/SoundHelix-Song-4.mp3' },
            { title: 'Música Argentina 5', url: 'https://www.soundhelix.com/examples/mp3/SoundHelix-Song-5.mp3' }
        ];
        const tracksBr = [
            { title: 'Funk 2026 Hit', url: 'https://www.soundhelix.com/examples/mp3/SoundHelix-Song-6.mp3' },
            { title: 'Sertanejo 2026', url: 'https://www.soundhelix.com/examples/mp3/SoundHelix-Song-7.mp3' },
            { title: 'Pop BR 2026', url: 'https://www.soundhelix.com/examples/mp3/SoundHelix-Song-8.mp3' },
            { title: 'Música BR 2026 #4', url: 'https://www.soundhelix.com/examples/mp3/SoundHelix-Song-9.mp3' },
            { title: 'Música BR 2026 #5', url: 'https://www.soundhelix.com/examples/mp3/SoundHelix-Song-10.mp3' }
        ];

        function renderTrackList(elId, list) {
            const el = document.getElementById(elId);
            if (!el) return;
            el.innerHTML = list.map((t, idx) => `
                <button class="w-full flex items-center justify-between px-3 py-2 rounded-lg border border-gray-100 hover:bg-gray-50 active:scale-[0.99]" onclick="selectTrack('${elId}','${idx}')">
                    <span class="text-sm font-semibold text-gray-800">${t.title}</span>
                    <i data-lucide="play" class="w-4 h-4 text-gray-500"></i>
                </button>
            `).join('');
        }

        function selectTrack(elId, idx) {
            const list = elId === 'listArg' ? tracksArg : tracksBr;
            const track = list[idx];
            if (!track || !bgPlayer) return;
            currentTrack = track;
            bgPlayer.src = track.url;
            bgPlayer.volume = 0.35;
            bgPlayer.play().catch(()=>{});
            const pt = document.getElementById('playingTitle');
            if (pt) pt.innerText = track.title;
        }
        function playBg() { if (bgPlayer) bgPlayer.play().catch(()=>{}); }
        function pauseBg() { if (bgPlayer) bgPlayer.pause(); }

        function openMusicModal() {
            const m = document.getElementById('modalMusic');
            if (m) m.classList.add('open');
        }
        function closeMusicModal() { const m = document.getElementById('modalMusic'); if (m) m.classList.remove('open'); }
        function openLangModal() {
            const m = document.getElementById('modalLang');
            if (m) m.classList.add('open');
        }
        function closeLangModal() { const m = document.getElementById('modalLang'); if (m) m.classList.remove('open'); }

        // Dicionário completo de traduções (TODOS os textos da SPA)
        const dict = {
            pt: {
                hello: 'Olá,', balance: 'Saldo Disponível', deposit: 'Depositar', withdraw: 'Retirar',
                news: 'Início', market: 'Investir', assets: 'Ativos', team: 'Equipe', profile: 'Perfil',
                music: 'Música', language: 'Idioma', argentinas: 'Argentinas • Top', brasileiras: 'Brasileiras • 2026',
                main: 'Principal', current: 'Atual', playing: 'Tocando', chooseLang: 'Escolha o idioma do site (padrão: Português).',
                portuguese: 'Português', spanish: 'Español', english: 'English',
                welcome: 'Bem-vindo!', welcomeText: 'Horário de Saque 10:00 às 14:00 Saques são processados apenas em dias úteis (segunda a sexta) no horário acima. Taxa de saque 10%',
                close: 'Fechar', enterGroup: 'Entrar no Grupo Oficial',
                collectEarnings: 'Coletar Rendimentos', collectReady: 'Ganhos prontos!',
                activeOperations: 'Ativos em Operação', progressReturn: 'Progresso do Retorno',
                rescueHistory: 'Histórico de Resgates', noMovements: 'Sem movimentos registrados',
                finishedPlans: 'Planos Finalizados', paid100: 'Pago 100%',
                noActiveInvestments: 'Aún no tienes inversiones activas.',
                goToMarket: 'Ir ao Mercado', noNews: 'Sem novidades.',
                acquireNow: 'ADQUIRIR AGORA', entryPrice: 'Preço de Entrada', netReturn: 'Retorno Líquido',
                availability: 'Disponibilidade', details: 'Detalhes', dailyReturn: 'Retorno Diario',
                totalReturn: 'Retorno Total', duration: 'Duração', stock: 'Estoque',
                investmentValue: 'Valor do investimento', returnType: 'Tipo de retorno',
                dailyReturnType: 'Retorno diário', cycleReturnType: 'Retorno por ciclo',
                limitPerUser: 'Limite por usuário', status: 'Status', active: 'Ativo', inactive: 'Inativo',
                unavailable: 'Indisponível', buyFor: 'Comprar por', exclusiveNewUsers: 'Exclusivo para novos usuários',
                outOfStock: 'Produto esgotado', noDescription: 'Sem Descrição.',
                financialSummary: 'Resumo Financeiro', totalDeposited: 'Total Depositado',
                totalWithdrawn: 'Total Retirado', totalReceived: 'Total Recebido (Lucro)',
                name: 'Nome', phone: 'Telefone', pixKey: 'Chave PIX', edit: 'Editar', register: 'Registrar',
                completeHistory: 'Histórico Completo', noRecentActivity: 'Sem atividades recentes.',
                endSession: 'Encerrar Sessão', attention: 'Atenção',
                depositWarning: 'Insira abaixo o CPF do titular da conta bancária que realizará o pagamento. O CPF deve coincidir exatamente com o do titular. Caso o CPF seja diferente, o depósito não será processado.',
                value: 'Valor', cpfHolder: 'CPF do Titular', generatePix: 'Gerar PIX Pagamento',
                min: 'Min', rate: 'Tasa', requestWithdrawal: 'Solicitar Retirada',
                myPixKey: 'Minha Chave PIX', pixType: 'Tipo de Chave', yourKey: 'Sua Chave',
                beneficiaryName: 'Nome do Titular', saveKey: 'Guardar Chave',
                withdrawWarning: 'Insira abaixo o CPF do titular da conta bancária onde será realizado o saque. O CPF deve coincidir exatamente com o do titular. Caso o CPF seja diferente, o saque não será efetuado.',
                back: 'Voltar', spins: 'Giros', officialWheel: 'Roleta Oficial',
                spinAndUnlock: 'Gire e desbloqueie bônus', spinNow: 'Girar agora',
                balanceLabel: 'Saldo', linkCopied: 'Link copiado!',
                makeDeposit: 'Realizar Depósito', depositSteps: 'Siga os passos abaixo para fazer seu depósito via PIX',
                step1Title: 'Preencha os dados', step1Desc: 'Informe o valor e o CPF do titular da conta que fará o pagamento',
                step2Title: 'Gere o QR Code PIX', step2Desc: 'Clique em "Gerar PIX" e você receberá um QR Code para pagamento',
                step3Title: 'Efetue o pagamento', step3Desc: 'Escaneie o QR Code ou copie o código PIX e pague pelo seu app bancário',
                importantAttention: 'Atenção Importante', depositWarningFull: 'O CPF informado deve ser exatamente o mesmo do titular da conta bancária que realizará o pagamento. Caso contrário, o depósito não será processado automaticamente.',
                instantCredit: 'Crédito Instantâneo', instantCreditDesc: 'Após pagamento',
                securePayment: 'Pagamento Seguro', securePaymentDesc: '100% protegido',
                depositValue: 'Valor do Depósito', minValue: 'Valor mínimo: R$',
                cpfHolderDesc: 'CPF do titular da conta que fará o pagamento',
                generatePixCode: 'Gerar QR Code PIX',
                payTitle: 'Pagar via PIX', autoCredit: 'Saldo creditado automaticamente após o pagamento',
                pixCode: 'Código PIX', pixInstructions: 'Escaneie o QR Code ou copie o código PIX e pague pelo seu app bancário',
                copyCode: 'Copiar Código PIX', codeCopied: 'Código copiado!',
                tasks: 'Tarefas', vipLevel: 'Nível VIP', vipProgress: 'Progresso',
                incomeStats: 'Estatísticas de Renda', totalInvested: 'Total Investido',
                personalInfo: 'Informações Pessoais', gamification: 'Gamificação',
                availableSpins: 'Giros Disponíveis', totalSpins: 'Total de Giros',
                spinAwards: 'Prêmios dos Giros', checkins: 'Check-ins',
                affiliates: 'Afiliados', level1: 'Nível 1', level2: 'Nível 2', level3: 'Nível 3',
                requestWithdraw: 'Solicitar Saque', withdrawSteps: 'Siga os passos para solicitar sua retirada',
                withdrawHours: 'Horário de Saque', withdrawHoursDesc: 'Saques são processados apenas em dias úteis (segunda a sexta) no horário acima.',
                withdrawValue: 'Valor do Saque', withdrawMin: 'Mín', withdrawRate: 'Taxa',
                newsTitle: 'Notícias e Avisos', newsSubtitle: 'Fique por dentro das últimas novidades!',
                support: 'Suporte', supportTitle: 'Suporte', telegram: 'Telegram', whatsapp: 'WhatsApp',
                supportHours: 'Horário de Atendimento', supportHoursDesc: 'Segunda a Sexta: 9h às 18h',
                noNews: 'Sem novidades.', noActiveInvestments: 'Você ainda não tem investimentos ativos.',
                productDetails: 'Detalhes do Produto', buyProduct: 'Comprar Produto',
                collectAll: 'Coletar Todos', investmentProducts: 'Produtos de Investimento',
                affiliateDashboard: 'Dashboard de Afiliados', totalCommissions: 'Comissões Totais',
                todayRevenue: 'Receita de Hoje', affiliateCode: 'Código de Afiliado',
                copy: 'Copiar', teamManagement: 'Gestão de Níveis', searchUser: 'Buscar telefone...',
                paymentHistory: 'Histórico de Recebimentos', commissionFrom: 'Comissão de Indicação',
                origin: 'Origem', vipStatus: 'Status VIP', vipGoal: 'Meta VIP',
                indicated: 'Indicados', goal: 'Meta', active: 'Ativos',
                level: 'Nível', vipRewards: 'Recompensas VIP', totalEarned: 'Total Ganho',
                totalWithdrawn: 'Total Retirado', totalDeposited: 'Total Depositado',
                totalProfit: 'Total Lucro', activeInvestments: 'Investimentos Ativos',
                completedTasks: 'Tarefas Completas', availableTasks: 'Tarefas Disponíveis',
                blockedTasks: 'Tarefas Bloqueadas', completeTask: 'Completar Tarefa',
                taskReward: 'Recompensa', taskCompleted: 'Tarefa Completa',
                taskAvailable: 'Disponível', taskBlocked: 'Bloqueado'
            },
            es: {
                hello: 'Hola,', balance: 'Saldo Disponible', deposit: 'Depositar', withdraw: 'Retirar',
                news: 'Inicio', market: 'Invertir', assets: 'Activos', team: 'Equipo', profile: 'Perfil',
                music: 'Música', language: 'Idioma', argentinas: 'Argentinas • Top', brasileiras: 'Brasileiras • 2026',
                main: 'Principal', current: 'Actual', playing: 'Reproduciendo', chooseLang: 'Elija el idioma del sitio (predeterminado: Portugués).',
                portuguese: 'Portugués', spanish: 'Español', english: 'Inglés',
                welcome: '¡Bienvenido!', welcomeText: 'Únete a nuestro grupo oficial para recibir avisos, novedades y soporte.',
                close: 'Cerrar', enterGroup: 'Entrar al Grupo Oficial',
                collectEarnings: 'Recolectar Ganancias', collectReady: '¡Ganancias listas!',
                activeOperations: 'Activos en Operación', progressReturn: 'Progreso del Retorno',
                rescueHistory: 'Historial de Rescates', noMovements: 'Sin movimientos registrados',
                finishedPlans: 'Planes Finalizados', paid100: 'Pagado 100%',
                noActiveInvestments: 'Aún no tienes inversiones activas.',
                goToMarket: 'Ir al Mercado', noNews: 'Sin novedades.',
                acquireNow: 'ADQUIRIR AHORA', entryPrice: 'Precio de Entrada', netReturn: 'Retorno Líquido',
                availability: 'Disponibilidad', details: 'Detalles', dailyReturn: 'Retorno Diario',
                totalReturn: 'Retorno Total', duration: 'Duración', stock: 'Stock',
                investmentValue: 'Valor de la inversión', returnType: 'Tipo de retorno',
                dailyReturnType: 'Retorno diario', cycleReturnType: 'Retorno por ciclo',
                limitPerUser: 'Límite por usuario', status: 'Estado', active: 'Activo', inactive: 'Inactivo',
                unavailable: 'No Disponible', buyFor: 'Comprar por', exclusiveNewUsers: 'Exclusivo para nuevos usuarios',
                outOfStock: 'Producto agotado', noDescription: 'Sin Descripción.',
                financialSummary: 'Resumen Financiero', totalDeposited: 'Total Depositado',
                totalWithdrawn: 'Total Retirado', totalReceived: 'Total Recibido (Ganancia)',
                name: 'Nombre', phone: 'Teléfono', pixKey: 'Clave PIX', edit: 'Editar', register: 'Registrar',
                completeHistory: 'Historial Completo', noRecentActivity: 'Sin actividades recientes.',
                endSession: 'Cerrar Sesión', attention: 'Atención',
                depositWarning: 'Ingrese a continuación el CPF del titular de la cuenta bancaria que realizará el pago. El CPF debe coincidir exactamente con el del titular. Si el CPF es diferente, el depósito no será procesado.',
                value: 'Valor', cpfHolder: 'CPF del Titular', generatePix: 'Generar PIX Pago',
                min: 'Mín', rate: 'Tasa', requestWithdrawal: 'Solicitar Retiro',
                myPixKey: 'Mi Clave PIX', pixType: 'Tipo de Clave', yourKey: 'Tu Clave',
                beneficiaryName: 'Nombre del Titular', saveKey: 'Guardar Clave',
                withdrawWarning: 'Ingrese a continuación el CPF del titular de la cuenta bancaria donde se realizará el retiro. El CPF debe coincidir exactamente con el del titular. Si el CPF es diferente, el retiro no será efectuado.',
                back: 'Volver', spins: 'Giros', officialWheel: 'Ruleta Oficial',
                spinAndUnlock: 'Gira y desbloquea bonos', spinNow: 'Girar ahora',
                balanceLabel: 'Saldo', linkCopied: '¡Enlace copiado!',
                makeDeposit: 'Realizar Depósito', depositSteps: 'Siga los pasos a continuación para hacer su depósito vía PIX',
                step1Title: 'Complete los datos', step1Desc: 'Ingrese el valor y el CPF del titular de la cuenta que realizará el pago',
                step2Title: 'Genere el Código QR PIX', step2Desc: 'Haga clic en "Generar PIX" y recibirá un código QR para el pago',
                step3Title: 'Realice el pago', step3Desc: 'Escanee el código QR o copie el código PIX y pague desde su aplicación bancaria',
                importantAttention: 'Atención Importante', depositWarningFull: 'El CPF informado debe ser exactamente el mismo del titular de la cuenta bancaria que realizará el pago. De lo contrario, el depósito no será procesado automáticamente.',
                instantCredit: 'Crédito Instantáneo', instantCreditDesc: 'Después del pago',
                securePayment: 'Pago Seguro', securePaymentDesc: '100% protegido',
                depositValue: 'Valor del Depósito', minValue: 'Valor mínimo: R$',
                cpfHolderDesc: 'CPF del titular de la cuenta que realizará el pago',
                generatePixCode: 'Generar Código QR PIX',
                payTitle: 'Pagar vía PIX', autoCredit: 'Saldo acreditado automáticamente después del pago',
                pixCode: 'Código PIX', pixInstructions: 'Escanee el código QR o copie el código PIX y pague desde su aplicación bancaria',
                copyCode: 'Copiar Código PIX', codeCopied: '¡Código copiado!',
                tasks: 'Tareas', vipLevel: 'Nivel VIP', vipProgress: 'Progreso',
                incomeStats: 'Estadísticas de Ingresos', totalInvested: 'Total Invertido',
                personalInfo: 'Información Personal', gamification: 'Gamificación',
                availableSpins: 'Giros Disponibles', totalSpins: 'Total de Giros',
                spinAwards: 'Premios de Giros', checkins: 'Check-ins',
                affiliates: 'Afiliados', level1: 'Nivel 1', level2: 'Nivel 2', level3: 'Nivel 3',
                requestWithdraw: 'Solicitar Retiro', withdrawSteps: 'Siga los pasos para solicitar su retiro',
                withdrawStep1Title: 'Configure su Clave PIX', withdrawStep1Desc: 'Vaya a "Perfil" y registre su clave PIX antes de solicitar el retiro',
                withdrawStep2Title: 'Ingrese el valor', withdrawStep2Desc: 'Digite el valor que desea retirar (respetando el mínimo y horario)',
                withdrawStep3Title: 'Espere la aprobación', withdrawStep3Desc: 'Su solicitud será analizada y el valor será transferido a su cuenta PIX',
                withdrawWarningFull: 'El CPF de la clave PIX registrada debe ser el mismo del titular de la cuenta. Retiros fuera del horario serán procesados en el próximo día hábil.',
                dailyTasks: 'Tareas Diarias', investmentOpportunities: 'Oportunidades de Inversión',
                myInvestments: 'Mis Inversiones', notice: 'Aviso', specialPrizes: 'Premios Especiales',
                prizesInfo: '¡Participe y gane recompensas exclusivas!', goButton: 'Ir',
                withdrawHours: 'Horario de Retiro', withdrawHoursDesc: 'Los retiros se procesan solo en días hábiles (lunes a viernes) en el horario anterior.',
                withdrawValue: 'Valor del Retiro', withdrawMin: 'Mín', withdrawRate: 'Tasa',
                newsTitle: '📢 Noticias y Avisos', newsSubtitle: '¡Mantente al día con las últimas novedades!',
                support: 'Soporte', supportTitle: 'Soporte', telegram: 'Telegram', whatsapp: 'WhatsApp',
                supportHours: 'Horario de Atención', supportHoursDesc: 'Lunes a Viernes: 9h a 18h',
                noNews: 'Sin novedades.', noActiveInvestments: 'Aún no tienes inversiones activas.',
                productDetails: 'Detalles del Producto', buyProduct: 'Comprar Producto',
                collectAll: 'Recolectar Todos', investmentProducts: 'Productos de Inversión',
                affiliateDashboard: 'Panel de Afiliados', totalCommissions: 'Comisiones Totales',
                todayRevenue: 'Ingresos de Hoy', affiliateCode: 'Código de Afiliado',
                copy: 'Copiar', teamManagement: 'Gestión de Niveles', searchUser: 'Buscar teléfono...',
                paymentHistory: 'Historial de Pagos', commissionFrom: 'Comisión de Referido',
                origin: 'Origen', vipStatus: 'Estado VIP', vipGoal: 'Meta VIP',
                indicated: 'Referidos', goal: 'Meta', active: 'Activos',
                level: 'Nivel', vipRewards: 'Recompensas VIP', totalEarned: 'Total Ganado',
                totalWithdrawn: 'Total Retirado', totalDeposited: 'Total Depositado',
                totalProfit: 'Total Ganancia', activeInvestments: 'Inversiones Activas',
                completedTasks: 'Tareas Completas', availableTasks: 'Tareas Disponibles',
                blockedTasks: 'Tareas Bloqueadas', completeTask: 'Completar Tarea',
                taskReward: 'Recompensa', taskCompleted: 'Tarea Completa',
                taskAvailable: 'Disponible', taskBlocked: 'Bloqueado'
            },
            en: {
                hello: 'Hello,', balance: 'Available Balance', deposit: 'Deposit', withdraw: 'Withdraw',
                news: 'Home', market: 'Invest', assets: 'Assets', team: 'Team', profile: 'Profile',
                music: 'Music', language: 'Language', argentinas: 'Argentine • Top', brasileiras: 'Brazilian • 2026',
                main: 'Main', current: 'Current', playing: 'Playing', chooseLang: 'Choose the site language (default: Portuguese).',
                portuguese: 'Portuguese', spanish: 'Spanish', english: 'English',
                welcome: 'Welcome!', welcomeText: 'Join our official group to receive notices, news and support.',
                close: 'Close', enterGroup: 'Enter Official Group',
                collectEarnings: 'Collect Earnings', collectReady: 'Earnings ready!',
                activeOperations: 'Active Operations', progressReturn: 'Return Progress',
                rescueHistory: 'Rescue History', noMovements: 'No registered movements',
                finishedPlans: 'Finished Plans', paid100: 'Paid 100%',
                noActiveInvestments: 'You don\'t have active investments yet.',
                goToMarket: 'Go to Market', noNews: 'No news.',
                acquireNow: 'ACQUIRE NOW', entryPrice: 'Entry Price', netReturn: 'Net Return',
                availability: 'Availability', details: 'Details', dailyReturn: 'Daily Return',
                totalReturn: 'Total Return', duration: 'Duration', stock: 'Stock',
                investmentValue: 'Investment value', returnType: 'Return type',
                dailyReturnType: 'Daily return', cycleReturnType: 'Cycle return',
                limitPerUser: 'Limit per user', status: 'Status', active: 'Active', inactive: 'Inactive',
                unavailable: 'Unavailable', buyFor: 'Buy for', exclusiveNewUsers: 'Exclusive for new users',
                outOfStock: 'Out of stock', noDescription: 'No Description.',
                financialSummary: 'Financial Summary', totalDeposited: 'Total Deposited',
                totalWithdrawn: 'Total Withdrawn', totalReceived: 'Total Received (Profit)',
                name: 'Name', phone: 'Phone', pixKey: 'PIX Key', edit: 'Edit', register: 'Register',
                completeHistory: 'Complete History', noRecentActivity: 'No recent activity.',
                endSession: 'End Session', attention: 'Attention',
                depositWarning: 'Enter below the CPF of the bank account holder who will make the payment. The CPF must match exactly with the holder\'s. If the CPF is different, the deposit will not be processed.',
                value: 'Value', cpfHolder: 'CPF Holder', generatePix: 'Generate PIX Payment',
                min: 'Min', rate: 'Rate', requestWithdrawal: 'Request Withdrawal',
                myPixKey: 'My PIX Key', pixType: 'Key Type', yourKey: 'Your Key',
                beneficiaryName: 'Beneficiary Name', saveKey: 'Save Key',
                withdrawWarning: 'Enter below the CPF of the bank account holder where the withdrawal will be made. The CPF must match exactly with the holder\'s. If the CPF is different, the withdrawal will not be made.',
                back: 'Back', spins: 'Spins', officialWheel: 'Official Wheel',
                spinAndUnlock: 'Spin and unlock bonuses', spinNow: 'Spin now',
                balanceLabel: 'Balance', linkCopied: 'Link copied!',
                makeDeposit: 'Make Deposit', depositSteps: 'Follow the steps below to make your deposit via PIX',
                step1Title: 'Fill in the data', step1Desc: 'Enter the amount and CPF of the account holder who will make the payment',
                step2Title: 'Generate PIX QR Code', step2Desc: 'Click "Generate PIX" and you will receive a QR Code for payment',
                step3Title: 'Make the payment', step3Desc: 'Scan the QR Code or copy the PIX code and pay through your banking app',
                importantAttention: 'Important Attention', depositWarningFull: 'The CPF provided must be exactly the same as the bank account holder who will make the payment. Otherwise, the deposit will not be processed automatically.',
                instantCredit: 'Instant Credit', instantCreditDesc: 'After payment',
                securePayment: 'Secure Payment', securePaymentDesc: '100% protected',
                depositValue: 'Deposit Amount', minValue: 'Minimum amount: R$',
                cpfHolderDesc: 'CPF of the account holder who will make the payment',
                generatePixCode: 'Generate PIX QR Code',
                payTitle: 'Pay via PIX', autoCredit: 'Balance credited automatically after payment',
                pixCode: 'PIX Code', pixInstructions: 'Scan the QR Code or copy the PIX code and pay through your banking app',
                copyCode: 'Copy PIX Code', codeCopied: 'Code copied!',
                tasks: 'Tasks', vipLevel: 'VIP Level', vipProgress: 'Progress',
                incomeStats: 'Income Statistics', totalInvested: 'Total Invested',
                personalInfo: 'Personal Information', gamification: 'Gamification',
                availableSpins: 'Available Spins', totalSpins: 'Total Spins',
                spinAwards: 'Spin Awards', checkins: 'Check-ins',
                affiliates: 'Affiliates', level1: 'Level 1', level2: 'Level 2', level3: 'Level 3',
                requestWithdraw: 'Request Withdrawal', withdrawSteps: 'Follow the steps to request your withdrawal',
                withdrawStep1Title: 'Configure your PIX Key', withdrawStep1Desc: 'Go to "Profile" and register your PIX key before requesting withdrawal',
                withdrawStep2Title: 'Enter the amount', withdrawStep2Desc: 'Enter the amount you want to withdraw (respecting minimum and hours)',
                withdrawStep3Title: 'Wait for approval', withdrawStep3Desc: 'Your request will be analyzed and the amount will be transferred to your PIX account',
                withdrawWarningFull: 'The CPF of the registered PIX key must be the same as the account holder. Withdrawals outside business hours will be processed on the next business day.',
                dailyTasks: 'Daily Tasks', investmentOpportunities: 'Investment Opportunities',
                myInvestments: 'My Investments', notice: 'Notice', specialPrizes: 'Special Prizes',
                prizesInfo: 'Participate and win exclusive rewards!', goButton: 'Go',
                withdrawHours: 'Withdrawal Hours', withdrawHoursDesc: 'Withdrawals are processed only on business days (Monday to Friday) during the hours above.',
                withdrawValue: 'Withdrawal Amount', withdrawMin: 'Min', withdrawRate: 'Rate',
                newsTitle: '📢 News and Announcements', newsSubtitle: 'Stay up to date with the latest news!',
                support: 'Support', supportTitle: 'Support', telegram: 'Telegram', whatsapp: 'WhatsApp',
                supportHours: 'Support Hours', supportHoursDesc: 'Monday to Friday: 9am to 6pm',
                noNews: 'No news.', noActiveInvestments: 'You don\'t have active investments yet.',
                productDetails: 'Product Details', buyProduct: 'Buy Product',
                collectAll: 'Collect All', investmentProducts: 'Investment Products',
                affiliateDashboard: 'Affiliate Dashboard', totalCommissions: 'Total Commissions',
                todayRevenue: 'Today\'s Revenue', affiliateCode: 'Affiliate Code',
                copy: 'Copy', teamManagement: 'Level Management', searchUser: 'Search phone...',
                paymentHistory: 'Payment History', commissionFrom: 'Referral Commission',
                origin: 'Origin', vipStatus: 'VIP Status', vipGoal: 'VIP Goal',
                indicated: 'Referrals', goal: 'Goal', active: 'Active',
                level: 'Level', vipRewards: 'VIP Rewards', totalEarned: 'Total Earned',
                totalWithdrawn: 'Total Withdrawn', totalDeposited: 'Total Deposited',
                totalProfit: 'Total Profit', activeInvestments: 'Active Investments',
                completedTasks: 'Completed Tasks', availableTasks: 'Available Tasks',
                blockedTasks: 'Blocked Tasks', completeTask: 'Complete Task',
                taskReward: 'Reward', taskCompleted: 'Task Complete',
                taskAvailable: 'Available', taskBlocked: 'Blocked'
            }
        };

        function applyLang(lang) {
            const t = dict[lang] || dict.pt;
            // Traduzir todos os elementos com data-i18n
            document.querySelectorAll('[data-i18n]').forEach(el => {
                const key = el.getAttribute('data-i18n');
                if (t[key]) {
                    if (el.tagName === 'INPUT' && el.type === 'text') {
                        el.placeholder = t[key];
                    } else {
                        el.innerText = t[key];
                    }
                }
            });
            // Traduzir botões de navegação
            const bNews = document.getElementById('btn-news'); if (bNews) bNews.innerText = t.news;
            const bMarket = document.getElementById('btn-market'); if (bMarket) bMarket.innerText = t.market;
            const bAssets = document.getElementById('btn-assets'); if (bAssets) bAssets.innerText = t.assets;
            const bTasks = document.getElementById('btn-tasks'); if (bTasks) bTasks.innerText = t.tasks;
            const bTeam = document.getElementById('btn-team'); if (bTeam) bTeam.innerText = t.team;
            const bProfile = document.getElementById('btn-profile'); if (bProfile) bProfile.innerText = t.profile;
            // Traduzir botões do hero
            const heroBtns = document.querySelectorAll('.hero-act button');
            if (heroBtns[0]) heroBtns[0].innerHTML = `<i data-lucide="arrow-down-circle" class="w-4 h-4"></i> ${t.deposit}`;
            if (heroBtns[1]) heroBtns[1].innerHTML = `<i data-lucide="arrow-up-circle" class="w-4 h-4"></i> ${t.withdraw}`;
            // Traduzir textos dinâmicos
            const balLabel = document.querySelector('[data-i18n="balance"]');
            if (balLabel) balLabel.innerText = t.balance;
            if (window.lucide) lucide.createIcons();
        }

        function setLang(lang) {
            localStorage.setItem('lang', lang);
            applyLang(lang);
            closeLangModal();
        }

        // inicializações
        (function initMusicAndLang(){
            renderTrackList('listArg', tracksArg);
            renderTrackList('listBr', tracksBr);
            const savedLang = localStorage.getItem('lang') || 'pt';
            applyLang(savedLang);
        })();

        function openDetails(data) {
    const m = document.getElementById('modalDetails');

    document.getElementById('d-img').src = data.img;
    document.getElementById('d-name').innerText = data.name;
    document.getElementById('d-desc').innerText = data.description || 'Sem Descrição.';

    document.getElementById('d-daily').innerText =
        'R$ ' + Number(data.daily_return).toFixed(2);

    document.getElementById('d-total').innerText =
        'R$ ' + Number(data.total_return).toFixed(2);

    document.getElementById('d-days').innerText =
        data.total_days + ' Días';

    document.getElementById('d-stock').innerText =
        data.available + ' Unid.';

    // NOVAS INFORMAÇÕES
    document.getElementById('d-value').innerText =
        'R$ ' + Number(data.value).toFixed(2);

    document.getElementById('d-return-type').innerText =
        data.type === 'diary' ? 'Retorno diário' : 'Retorno por ciclo';

    document.getElementById('d-limit').innerText =
        data.limit_purchase + ' por usuário';

    document.getElementById('d-status').innerText =
        data.is_active == 1 ? 'Ativo' : 'Inativo';

    // PONTOS GERADOS (apenas se o produto dá pontos ao comprar com dinheiro)
    const pointsContainer = document.getElementById('d-points-container');
    const pointsReward = parseInt(data.qtd_points || 0); // Pontos que o usuário ganha ao comprar com dinheiro
    
    if (pointsReward > 0) {
        pointsContainer.classList.remove('hidden');
        document.getElementById('d-points-amount').innerText = '+' + pointsReward.toLocaleString('pt-BR') + ' pontos';
        document.getElementById('d-points-user').innerText = pointsReward.toLocaleString('pt-BR') + ' pontos';
        document.getElementById('d-points-referrer').innerText = pointsReward.toLocaleString('pt-BR') + ' pontos';
        document.getElementById('d-points-money').innerText = 'R$ ' + (pointsReward / 100).toFixed(2).replace('.', ',');
    } else {
        pointsContainer.classList.add('hidden');
    }

    // ALERTAS INTELIGENTES
    const alertBox = document.getElementById('d-alert');
    alertBox.className = 'hidden';

    if (data.available <= 0) {
        alertBox.innerText = 'Produto esgotado';
        alertBox.className = 'text-xs font-bold bg-red-100 text-red-700 rounded-lg p-3';
    } 
    else if (data.new_user == 1) {
        alertBox.innerText = 'Exclusivo para novos usuários';
        alertBox.className = 'text-xs font-bold bg-yellow-100 text-yellow-700 rounded-lg p-3';
    }

    // BOTÃO DE AÇÃO
    let button = '';

    if (data.is_active != 1 || data.available <= 0) {
        button = `
            <button disabled
                class="w-full mt-4 bg-gray-300 text-gray-500 py-3 rounded-xl font-bold">
                Indisponível
            </button>
        `;
    } else {
        button = `
            <button onclick="confirmPurchase(${data.id})"
                class="w-full mt-4 bg-vip-blue text-white py-3 rounded-xl font-bold shadow-lg">
                Comprar por R$ ${Number(data.value).toFixed(2)}
            </button>
        `;
    }

    document.getElementById('d-action').innerHTML = button;

    // Recriar ícones do Lucide após atualizar o modal
    if (window.lucide) {
        lucide.createIcons();
    }

    m.classList.add('open');
}

// ABRE APENAS O MODAL DE PIX (CHAMADO NO PERFIL)
function openPixModal() {
    const m = document.getElementById('modalPix');
    if (m) {
        m.classList.add('open');
    } else {
        console.error("Modal Pix não encontrado");
    }
}


        function confirmPurchase(id) { api('purchase_product', {product_id: id}); }

        // Funções de conversão de pontos
        function updateMoneyPreview() {
            const points = parseInt(document.getElementById('pointsToMoney').value) || 0;
            const money = points / 100;
            document.getElementById('moneyPreview').textContent = 'R$ ' + money.toFixed(2).replace('.', ',');
        }

        function convertPointsToMoney() {
            const points = parseInt(document.getElementById('pointsToMoney').value) || 0;
            if (points < 100) {
                toast('Mínimo de 100 pontos para converter', 'err');
                return;
            }
            api('convert_points_money', {points: points});
        }

        function convertPointsToProduct(productId, points) {
            if (confirm(`Deseja trocar ${points.toLocaleString('pt-BR')} pontos por este produto?`)) {
                api('convert_points_product', {product_id: productId, points: points});
            }
        }
        
        // Atualizar pontos após conversão
        function updatePointsDisplay(newPoints) {
            const pointsEl = document.getElementById('pointsBalance');
            const pointsDisplayEl = document.getElementById('userPointsDisplay');
            if(pointsEl) pointsEl.textContent = Number(newPoints).toLocaleString('pt-BR');
            if(pointsDisplayEl) pointsDisplayEl.textContent = Number(newPoints).toLocaleString('pt-BR');
        }
        function savePix(e) { e.preventDefault(); api('save_pix', {type_pix: e.target.type_pix.value, key_beneficiary: e.target.key_beneficiary.value, name_beneficiary: e.target.name_beneficiary.value, cpf_beneficiary: e.target.cpf_beneficiary.value}); }
        
        function updateProfile(e) {
            e.preventDefault();
            const formData = new FormData(e.target);
            formData.append('action', 'update_profile');
            api('update_profile', {
                name: formData.get('name'),
                document: formData.get('document')
            });
        }
        function doDeposit(e) { e.preventDefault(); api('generate_pix', {amount: e.target.amount.value.replace('R$','').replace('.','').replace(',','.'), cpf: e.target.cpf.value}, true); }
        function copyLink() { navigator.clipboard.writeText("<?= $affiliate_link ?>"); toast("Link copiado!"); }
        function copyPixCode() {
            const code = document.getElementById('qrCode').value;
            navigator.clipboard.writeText(code);
            toast(getTranslation('codeCopied') || 'Código copiado!');
        }
        function getTranslation(key) {
            const lang = localStorage.getItem('lang') || 'pt';
            return dict[lang]?.[key] || dict.pt[key] || key;
        }
    </script>
</body>
</html>