<?php
require_once '../app/Controllers/sessions.php';
require_once '../app/Controllers/security_access.php';
require_once '../app/models/user.php';
require_once '../app/Controllers/checkInController.php';
require '../app/Controllers/layouts.php';

$toastMessage = $_SESSION['toastMessage'] ?? null;
$toastType = $_SESSION['toastType'] ?? null;
unset($_SESSION['toastMessage'], $_SESSION['toastType']);

// --- LÓGICA DE DADOS (Preservada) ---
// Define variáveis com fallback
$totalLiquid = $totalLiquid ?? '0.00';
$totalIndicatedsUser = $totalIndicatedsUser ?? 0;
$totalGeral = $totalGeral ?? 0;
$dividendos_hoje = $dividendos_hoje ?? '0.00';
$contagemAtivos = $contagemAtivos ?? 0;

// Consultas de Receita Hoje
if (isset($user['id'])) {
    $stmtReceitaHoje = $pdo->prepare('SELECT SUM(liquid_affiliate) AS receita_hoje FROM comission_affiliates WHERE affiliate_id = :affiliate_id AND created_at LIKE :created_at');
    $stmtReceitaHoje->execute([
        ':affiliate_id' => $user['id'],
        ':created_at' => '%' . date('Y-m-d') . '%',
    ]);
    $receitaDeHoje = $stmtReceitaHoje->fetch(PDO::FETCH_ASSOC);
    $resultadoReceitaDeHoje = $receitaDeHoje['receita_hoje'] ?? 0;
} else {
    $resultadoReceitaDeHoje = 0;
}

// Inicialização de Arrays
$indicadosLVL1Diretos = $indicadosLVL1Diretos ?? [];
$somaLvl2 = $somaLvl2 ?? [];
$somaLvl3 = $somaLvl3 ?? [];
$todosIndicados = array_merge($indicadosLVL1Diretos, $somaLvl2, $somaLvl3);

// Contagens
$lvl1_count = count($indicadosLVL1Diretos);
$lvl2_count = count($somaLvl2);
$lvl3_count = count($somaLvl3);

// Link de Afiliado
$affiliate_code = $user['affiliate_code'] ?? '';
$base_url = $_SERVER['HTTP_HOST'] . '/public/register.php';
$affiliate_link = "http://" . $base_url . '?ref=' . $affiliate_code;

// Mensagens de compartilhamento
$share_message_raw = "Estou recebendo muito dinheiro investindo nessa plataforma! ";
$share_message_url = urlencode($share_message_raw);
$whatsapp_link = 'https://api.whatsapp.com/send?text=' . $share_message_url . urlencode($affiliate_link);
$telegram_link = 'https://t.me/share/url?url=' . urlencode($affiliate_link) . '&text=' . $share_message_url;
$facebook_link = 'https://www.facebook.com/sharer/sharer.php?u=' . urlencode($affiliate_link) . '&quote=' . $share_message_url;
?>

<?php if ($stmtThemesPlatformResult['theme_actual'] === 'brasileira') : ?>
  <script>window.location.href = '?theme=gringa2';</script>
<?php elseif ($stmtThemesPlatformResult['theme_actual'] === 'gringa') : ?>
   <script>window.location.href = '?theme=gringa2';</script>
<?php elseif ($stmtThemesPlatformResult['theme_actual'] === 'gringa2' || true) : ?>
  <!DOCTYPE html>
  <html lang="pt-BR">

  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Minha Equipe 团队 - <?= htmlspecialchars($stmtConfigsPlatformResult["name_platform"]) ?></title>

    <script src="https://cdn.tailwindcss.com"></script>
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Oswald:wght@400;500;700&family=Inter:wght@300;400;600;700;800&family=Share+Tech+Mono&display=swap" rel="stylesheet">
    
    <script src="https://unpkg.com/lucide@latest"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.6.0/css/all.min.css">

    <script>
      tailwind.config = {
        theme: {
          extend: {
            colors: {
              vip: {
                bg: '#F8F9FA',      // Fundo claro
                card: '#FFFFFF',    // Card branco
                text: '#333333',    // Texto escuro
                border: '#E5E7EB',  // Borda cinza claro
                salmon: '#FF7E67',  // Cor Principal (Salmão)
                salmonlight: '#FFA090',
                red: '#E53935',
                green: '#43A047',
                blue: '#2980B9'
              }
            },
            fontFamily: {
              sans: ['Inter', 'sans-serif'],
              mono: ['Oswald', 'sans-serif'],
              tech: ['"Share Tech Mono"', 'monospace']
            },
            boxShadow: {
              'soft': '0 4px 20px rgba(0, 0, 0, 0.05)',
              'glow-salmon': '0 0 15px rgba(255, 126, 103, 0.4)',
              'card-float': '0 15px 35px -5px rgba(255, 126, 103, 0.5)'
            }
          }
        }
      };
    </script>

    <style>
      body {
        background-color: #F8F9FA;
        /* Grade cinza sutil */
        background-image: 
            linear-gradient(#E5E7EB 1px, transparent 1px),
            linear-gradient(90deg, #E5E7EB 1px, transparent 1px);
        background-size: 40px 40px;
        color: #333;
        -webkit-font-smoothing: antialiased;
        padding-bottom: 100px;
      }

      /* Header */
      .vip-header {
        padding: 20px;
        background: rgba(255, 255, 255, 0.95);
        border-bottom: 1px solid #E5E7EB;
        display: flex; justify-content: space-between; align-items: center;
        position: sticky; top: 0; z-index: 50; backdrop-filter: blur(10px);
        box-shadow: 0 2px 10px rgba(0,0,0,0.03);
      }

      /* --- CARTÃO "AGENT ELITE" (SALMÃO) --- */
      .agent-card-container {
        perspective: 1000px;
        margin: 20px 20px 10px 20px;
      }

      .agent-card {
        background: linear-gradient(135deg, #FF7E67 0%, #FF6B50 100%);
        border-radius: 16px;
        padding: 24px;
        position: relative;
        overflow: hidden;
        box-shadow: var(--card-float);
        min-height: 210px;
        display: flex; flex-direction: column; justify-content: space-between;
        color: white;
      }

      .agent-card::after {
        content: ''; position: absolute; top: -50%; right: -50%; width: 100%; height: 100%;
        background: radial-gradient(circle, rgba(255,255,255,0.2) 0%, transparent 60%);
        pointer-events: none;
      }
      
      .chip-icon {
        width: 45px; height: 32px;
        background: rgba(255,255,255,0.2);
        border-radius: 6px; border: 1px solid rgba(255,255,255,0.3);
        position: relative;
      }

      .card-brand {
        font-family: 'Oswald', sans-serif; font-weight: bold; color: #fff; font-style: italic;
        text-shadow: 0 0 10px rgba(0,0,0,0.1);
        display: flex; align-items: center; gap: 6px;
        font-size: 14px; letter-spacing: 1px;
      }

      .commission-display {
        margin-top: 15px; margin-bottom: 15px; relative; z-index: 2;
      }
      .commission-label { font-size: 9px; color: rgba(255,255,255,0.8); text-transform: uppercase; letter-spacing: 2px; margin-bottom: 4px; }
      .commission-value {
        font-family: 'Share Tech Mono', monospace; font-size: 36px; color: #FFF;
        text-shadow: 0 2px 5px rgba(0,0,0,0.1); letter-spacing: 1px; font-weight: bold;
      }

      .card-footer {
        display: flex; justify-content: space-between; align-items: end; relative; z-index: 2;
      }
      .code-label { font-size: 8px; color: rgba(255,255,255,0.8); text-transform: uppercase; margin-bottom: 2px; }
      .code-val { font-family: 'Share Tech Mono', monospace; color: #fff; font-size: 16px; letter-spacing: 3px; }

      /* --- MÉTRICAS DETALHADAS --- */
      .metrics-grid {
        display: grid; grid-template-columns: repeat(3, 1fr); gap: 10px;
        padding: 0 20px; margin-bottom: 30px;
      }
      
      .metric-card {
        background: #FFF; border: 1px solid #E5E7EB; border-radius: 12px;
        padding: 12px; text-align: center; position: relative; overflow: hidden;
        transition: transform 0.2s; box-shadow: 0 4px 10px rgba(0,0,0,0.03);
      }
      .metric-card:active { transform: scale(0.98); }
      
      .metric-val { font-family: 'Share Tech Mono', monospace; font-size: 18px; color: #333; font-weight: bold; }
      .metric-label { font-size: 9px; color: #9CA3AF; text-transform: uppercase; margin-top: 4px; font-weight: bold; letter-spacing: 0.5px; }
      
      .text-green { color: #43A047; }
      .text-salmon { color: #FF7E67; }

      /* --- VIP LOUNGE AREA --- */
      .vip-lounge {
        margin: 0 20px 30px 20px;
        padding: 20px;
        background: #FFF;
        border: 1px solid #E5E7EB;
        border-radius: 12px;
        position: relative;
        overflow: hidden;
        box-shadow: 0 4px 15px rgba(0,0,0,0.03);
      }
      
      .vip-header-title {
        font-family: 'Oswald', sans-serif;
        color: #FF7E67;
        text-transform: uppercase;
        font-size: 14px;
        letter-spacing: 1px;
        margin-bottom: 15px;
        display: flex; align-items: center; gap: 8px;
        font-weight: bold;
      }

      .vip-progress-container {
        display: flex; align-items: center; gap: 15px; margin-bottom: 15px;
      }

      .current-vip-badge {
        width: 60px; height: 60px;
        background: #FFF;
        border: 2px solid #FF7E67;
        border-radius: 50%;
        display: flex; align-items: center; justify-content: center;
        flex-shrink: 0;
        box-shadow: 0 0 15px rgba(255, 126, 103, 0.2);
        position: relative;
      }
      .current-vip-badge img { width: 35px; height: 35px; object-fit: contain; }
      
      .progress-info { flex: 1; }
      
      .progress-bar-bg {
        width: 100%; height: 6px; background: #F3F4F6; border-radius: 3px;
        margin-top: 8px; overflow: hidden; position: relative;
      }
      .progress-bar-fill {
        height: 100%; background: linear-gradient(90deg, #FF7E67, #FFA090);
        border-radius: 3px; box-shadow: 0 0 10px rgba(255, 126, 103, 0.3);
        transition: width 1s ease-out;
      }

      /* Scroll Horizontal de VIPs */
      .vip-tier-scroll {
        display: flex; gap: 10px; overflow-x: auto; padding-bottom: 10px;
        scrollbar-width: none; /* Firefox */
      }
      .vip-tier-scroll::-webkit-scrollbar { display: none; }

      .vip-tier-card {
        min-width: 90px;
        background: #F9FAFB;
        border: 1px solid #E5E7EB;
        border-radius: 8px;
        padding: 10px;
        display: flex; flex-direction: column; align-items: center;
        opacity: 0.6;
        transition: all 0.3s;
      }
      .vip-tier-card.active-tier {
        border-color: #FF7E67;
        background: #FFF;
        opacity: 1;
        box-shadow: 0 4px 15px rgba(255, 126, 103, 0.15);
        transform: scale(1.05);
      }
      .vip-tier-card img { width: 30px; height: 30px; margin-bottom: 5px; }
      .vip-tier-name { font-size: 10px; font-weight: bold; color: #333; }
      .vip-tier-card.active-tier .vip-tier-name { color: #FF7E67; }
      .vip-tier-req { font-size: 8px; color: #9CA3AF; margin-top: 2px; }

      /* --- INVITE SECTION --- */
      .invite-section { margin: 0 20px 30px 20px; }
      
      .invite-title {
         font-size: 10px; color: #6B7280; font-weight: bold; uppercase; letter-spacing: 2px; margin-bottom: 8px;
      }

      .invite-input-box {
        background: #FFF; border: 1px solid #E5E7EB;
        display: flex; align-items: center; padding: 4px; border-radius: 8px;
        margin-bottom: 10px;
        box-shadow: 0 2px 5px rgba(0,0,0,0.02);
      }
      
      .invite-url {
        background: transparent; border: none; color: #333; font-family: 'Share Tech Mono', monospace;
        font-size: 11px; flex: 1; padding: 12px; outline: none;
      }
      
      .btn-copy {
        background: #FFF; color: #FF7E67; font-family: 'Oswald', sans-serif;
        font-size: 10px; padding: 10px 18px; border-radius: 6px; border: 1px solid #FF7E67;
        text-transform: uppercase; transition: all 0.2s; font-weight: bold;
      }
      .btn-copy:active { background: #FF7E67; color: #FFF; }

      .social-grid { display: grid; grid-template-columns: repeat(3, 1fr); gap: 10px; }
      
      .social-btn {
        background: #FFF; border: 1px solid #E5E7EB; padding: 12px;
        display: flex; flex-direction: column; align-items: center; gap: 6px;
        border-radius: 8px; transition: all 0.2s; cursor: pointer;
        box-shadow: 0 2px 5px rgba(0,0,0,0.02);
      }
      .social-btn:hover { border-color: #FF7E67; transform: translateY(-2px); }
      .social-icon { font-size: 20px; }
      .social-name { font-size: 9px; color: #6B7280; text-transform: uppercase; font-weight: bold; }

      /* --- LISTA DE MEMBROS --- */
      .members-container { padding: 0 20px 80px 20px; }
      
      .tab-header {
        display: flex; border-bottom: 1px solid #E5E7EB; margin-bottom: 20px;
      }
      
      .tab-btn {
        flex: 1; background: transparent; border: none; color: #9CA3AF;
        padding: 12px; font-family: 'Oswald', sans-serif; font-size: 12px;
        text-transform: uppercase; letter-spacing: 1px; cursor: pointer;
        position: relative; transition: color 0.3s; font-weight: bold;
      }
      
      .tab-btn.active { color: #FF7E67; }
      .tab-btn.active::after {
        content: ''; position: absolute; bottom: -1px; left: 0; width: 100%;
        height: 2px; background: #FF7E67; box-shadow: 0 0 10px rgba(255, 126, 103, 0.4);
      }

      .member-item {
        display: flex; justify-content: space-between; align-items: center;
        background: #FFF;
        border-left: 2px solid #E5E7EB;
        padding: 15px; margin-bottom: 8px;
        transition: border-color 0.2s;
        border-radius: 0 8px 8px 0;
        box-shadow: 0 2px 5px rgba(0,0,0,0.02);
      }
      .member-item:hover { border-left-color: #FF7E67; }
      
      .member-avatar-box {
        width: 32px; height: 32px; background: #F3F4F6; border: 1px solid #E5E7EB;
        border-radius: 6px; display: flex; align-items: center; justify-content: center;
        font-family: 'Oswald', sans-serif; font-weight: bold; color: #6B7280; font-size: 10px;
      }
      
      .member-info h4 { font-size: 12px; color: #333; font-weight: bold; margin-bottom: 2px; font-family: 'Inter', sans-serif; }
      .member-info p { font-size: 9px; color: #9CA3AF; font-family: 'Share Tech Mono', monospace; }
      
      .member-profit { font-family: 'Share Tech Mono', monospace; color: #43A047; font-size: 12px; font-weight: bold; }

      /* Toast Light */
      .toast-custom {
        background: #FFF; border: 1px solid #E5E7EB; border-left: 3px solid #FF7E67;
        color: #333; padding: 12px 20px; box-shadow: 0 10px 40px rgba(0,0,0,0.1);
        display: flex; align-items: center; gap: 10px;
        animation: slideInTop 0.4s forwards;
      }
      @keyframes slideInTop { from { transform: translateY(-100%); opacity: 0; } to { transform: translateY(0); opacity: 1; } }
    </style>
  </head>

  <body>

    <div id="toast-container" class="fixed top-4 left-0 right-0 z-[100] flex justify-center pointer-events-none"></div>

    <div class="max-w-[480px] mx-auto min-h-screen relative border-x border-gray-100 shadow-xl">

      <div class="vip-header">
        <a href="index.php" class="text-gray-400 hover:text-vip-salmon transition">
            <i data-lucide="arrow-left" class="w-6 h-6"></i>
        </a>
        <h1 class="text-lg font-bold text-vip-salmon font-mono tracking-widest uppercase">
            Minha Equipe 团队
        </h1>
        <div class="w-6"></div> 
      </div>

      <div class="agent-card-container">
         <div class="agent-card">
            <div class="card-header">
               <div class="chip-icon"></div>
               <div class="card-brand mt-4">
                  <i class="fa-solid fa-layer-group text-white"></i>
                  <span>AGENTE DE ELITE 精英代理</span>
               </div>
            </div>

            <div class="commission-display">
               <p class="commission-label">Comissão Total 累计佣金</p>
               <p class="commission-value">R$ <?= number_format($totalLiquid, 2, ',', '.') ?></p>
            </div>

            <div class="card-footer">
               <div>
                  <p class="code-label">ID do Agente 代理ID</p>
                  <p class="code-val"><?= htmlspecialchars($affiliate_code) ?></p>
               </div>
               <div class="text-right">
                  <p class="code-label">Lucro Hoje 今日收益</p>
                  <p class="text-sm font-bold text-white font-mono">+<?= number_format($resultadoReceitaDeHoje, 2, ',', '.') ?></p>
               </div>
            </div>
         </div>
      </div>

      <div class="metrics-grid">
         <div class="metric-card">
            <p class="metric-val"><?= count($todosIndicados) ?></p>
            <p class="metric-label">Membros 成员总数</p>
         </div>
         <div class="metric-card">
            <p class="metric-val text-green"><?= htmlspecialchars($contagemAtivos) ?></p>
            <p class="metric-label">Ativos 活跃用户</p>
         </div>
         <div class="metric-card">
            <p class="metric-val text-salmon text-[12px] pt-1">R$ <?= number_format($user['total_lvl1'] + $user['total_lvl2'] + $user['total_lvl3'], 2, ',', '.') ?></p>
            <p class="metric-label">Receita Equipe 团队收入</p>
         </div>
      </div>

      <div class="vip-lounge">
         <div class="vip-header-title">
            <i class="fa-solid fa-crown text-vip-salmon"></i> Status VIP & Progresso 会员等级
         </div>

         <?php
            // Lógica VIP Preservada
            $currentLvl = (int)($user['vip_level'] ?? 0);
            $nextLvl = $currentLvl + 1;
            
            // Dados atuais
            $qtdAtual = $located150Contagem ?? 0;
            // Busca dados do próximo nível
            $qtdNecessaria = 10; // Default
            $nextBonus = 0;
            
            foreach($resultVips as $v) {
                if($v['level'] == $nextLvl) {
                    $qtdNecessaria = (int)$v['qtd_indicated'];
                    $nextBonus = $v['bonus_fake'];
                    break;
                }
            }
            if($qtdNecessaria == 0) $qtdNecessaria = 1;

            $percent = min(100, ($qtdAtual / $qtdNecessaria) * 100);
            
            // Imagem do nível atual
            $currentImg = 'uploads/default.png'; 
            foreach($resultVips as $v) {
                if($v['level'] == $currentLvl) {
                    $currentImg = 'uploads/' . $v['img'] . '.png';
                    break;
                }
            }
            if($currentLvl == 0 && isset($resultVips[0])) {
                 $currentImg = 'uploads/' . $resultVips[0]['img'] . '.png';
            }
         ?>

         <?php if ($currentLvl >= 10) : ?>
             <div class="text-center py-4">
                 <div class="inline-block p-4 rounded-full border-2 border-vip-salmon bg-vip-salmon/10 mb-2">
                     <i class="fa-solid fa-trophy text-3xl text-vip-salmon"></i>
                 </div>
                 <h2 class="text-vip-salmon font-bold uppercase tracking-widest">Nível Máximo Elite 最高等级</h2>
                 <p class="text-xs text-gray-500">Você está no topo da cadeia.</p>
             </div>
         <?php else: ?>
             <div class="vip-progress-container">
                 <div class="current-vip-badge">
                     <img src="<?= htmlspecialchars($currentImg) ?>" onerror="this.src='https://cdn-icons-png.flaticon.com/512/6941/6941697.png'">
                 </div>
                 <div class="progress-info">
                     <div class="flex justify-between items-end mb-1">
                         <span class="text-xs font-bold text-gray-700 uppercase">Próximo: VIP<?= $nextLvl ?></span>
                         <span class="text-[9px] text-vip-salmon font-mono font-bold"><?= $qtdAtual ?>/<?= $qtdNecessaria ?> Refs</span>
                     </div>
                     <div class="progress-bar-bg">
                         <div class="progress-bar-fill" style="width: <?= $percent ?>%"></div>
                     </div>
                     <p class="text-[9px] text-gray-400 mt-1 text-right">Bônus Desbloqueio 解锁奖金: R$ <?= number_format($nextBonus, 2, ',', '.') ?></p>
                 </div>
             </div>
         <?php endif; ?>

         <div class="vip-tier-scroll">
             <?php foreach ($resultVips as $vip): 
                 $isActive = ($vip['level'] == $currentLvl);
                 $isUnlocked = ($vip['level'] <= $currentLvl);
                 $cardClass = $isActive ? 'active-tier' : '';
                 $iconOpacity = $isUnlocked ? 'opacity-100' : 'opacity-40 grayscale';
             ?>
             <div class="vip-tier-card <?= $cardClass ?>">
                 <img src="uploads/<?= htmlspecialchars($vip['img']) ?>.png" class="<?= $iconOpacity ?>" onerror="this.src='https://cdn-icons-png.flaticon.com/512/6941/6941697.png'">
                 <span class="vip-tier-name">VIP<?= $vip['level'] ?></span>
                 <span class="vip-tier-req"><?= $vip['qtd_indicated'] ?> Refs</span>
             </div>
             <?php endforeach; ?>
         </div>
      </div>

      <div class="invite-section">
         <h3 class="invite-title">Link de Convite 邀请链接</h3>
         
         <div class="invite-input-box">
            <input type="text" id="affiliate-link" value="<?= $affiliate_link ?>" readonly class="invite-url">
            <button onclick="copyLink()" class="btn-copy">
               COPIAR 复制
            </button>
         </div>

         <div class="social-grid">
            <div onclick="shareSocial('whatsapp')" class="social-btn">
               <i class="fa-brands fa-whatsapp social-icon text-vip-green"></i>
               <span class="social-name">Whatsapp</span>
            </div>
            <div onclick="shareSocial('telegram')" class="social-btn">
               <i class="fa-brands fa-telegram social-icon text-vip-blue"></i>
               <span class="social-name">Telegram</span>
            </div>
            <div onclick="shareSocial('facebook')" class="social-btn">
               <i class="fa-brands fa-facebook social-icon text-blue-600"></i>
               <span class="social-name">Facebook</span>
            </div>
         </div>
      </div>

      <div class="members-container">
         <div class="tab-header">
            <button onclick="switchTab(1)" id="tab-1" class="tab-btn active">NÍVEL 1 (<?= $lvl1_count ?>)</button>
            <button onclick="switchTab(2)" id="tab-2" class="tab-btn">NÍVEL 2 (<?= $lvl2_count ?>)</button>
            <button onclick="switchTab(3)" id="tab-3" class="tab-btn">NÍVEL 3 (<?= $lvl3_count ?>)</button>
         </div>

         <div id="list-lvl-1">
            <?php if(empty($indicadosLVL1Diretos)): ?>
               <p class="text-center text-[10px] text-gray-400 py-8 font-mono border border-dashed border-gray-200">SEM DADOS / 暂无数据</p>
            <?php else: ?>
               <?php foreach($indicadosLVL1Diretos as $m): ?>
                  <div class="member-item">
                     <div class="flex items-center gap-3">
                        <div class="member-avatar-box border-vip-red/30 text-vip-red">L1</div>
                        <div class="member-info">
                           <h4><?= htmlspecialchars($m['phone']) ?></h4>
                           <p><?= htmlspecialchars($m['date'] ?? '-') ?></p>
                        </div>
                     </div>
                     <span class="member-profit">+R$ <?= htmlspecialchars($m['profit_investments'] ?? '0.00') ?></span>
                  </div>
               <?php endforeach; ?>
            <?php endif; ?>
         </div>

         <div id="list-lvl-2" class="hidden">
            <?php if(empty($somaLvl2)): ?>
               <p class="text-center text-[10px] text-gray-400 py-8 font-mono border border-dashed border-gray-200">SEM DADOS / 暂无数据</p>
            <?php else: ?>
               <?php foreach($somaLvl2 as $m): ?>
                  <div class="member-item">
                     <div class="flex items-center gap-3">
                        <div class="member-avatar-box border-orange-500/30 text-orange-500">L2</div>
                        <div class="member-info">
                           <h4><?= htmlspecialchars($m['phone']) ?></h4>
                           <p><?= htmlspecialchars($m['date'] ?? '-') ?></p>
                        </div>
                     </div>
                     <span class="member-profit">+R$ <?= htmlspecialchars($m['profit_investments'] ?? '0.00') ?></span>
                  </div>
               <?php endforeach; ?>
            <?php endif; ?>
         </div>

         <div id="list-lvl-3" class="hidden">
            <?php if(empty($somaLvl3)): ?>
               <p class="text-center text-[10px] text-gray-400 py-8 font-mono border border-dashed border-gray-200">SEM DADOS / 暂无数据</p>
            <?php else: ?>
               <?php foreach($somaLvl3 as $m): ?>
                  <div class="member-item">
                     <div class="flex items-center gap-3">
                        <div class="member-avatar-box border-blue-500/30 text-blue-500">L3</div>
                        <div class="member-info">
                           <h4><?= htmlspecialchars($m['phone']) ?></h4>
                           <p><?= htmlspecialchars($m['date'] ?? '-') ?></p>
                        </div>
                     </div>
                     <span class="member-profit">+R$ <?= htmlspecialchars($m['profit_investments'] ?? '0.00') ?></span>
                  </div>
               <?php endforeach; ?>
            <?php endif; ?>
         </div>
      </div>

      <?php include 'partials/menu-bottom.php'; ?>

    </div>

    <script>
      lucide.createIcons();

      // Switch Tabs
      function switchTab(lvl) {
         document.querySelectorAll('.tab-btn').forEach(el => el.classList.remove('active'));
         document.getElementById('tab-' + lvl).classList.add('active');

         document.getElementById('list-lvl-1').classList.add('hidden');
         document.getElementById('list-lvl-2').classList.add('hidden');
         document.getElementById('list-lvl-3').classList.add('hidden');
         document.getElementById('list-lvl-' + lvl).classList.remove('hidden');
      }

      // Toast Light Style
      function showToast(msg) {
         const container = document.getElementById('toast-container');
         const toast = document.createElement('div');
         
         toast.className = 'toast-custom pointer-events-auto';
         toast.innerHTML = `
            <i data-lucide="check-circle" class="w-4 h-4 text-vip-green"></i>
            <span class="font-mono text-xs uppercase tracking-wide font-bold">${msg}</span>
         `;
         
         container.appendChild(toast);
         lucide.createIcons();

         setTimeout(() => {
            toast.style.opacity = '0';
            toast.style.transform = 'translateY(-20px)';
            toast.style.transition = 'all 0.3s';
            setTimeout(() => toast.remove(), 400);
         }, 3000);
      }

      // Copy Function
      async function copyLink() {
         const input = document.getElementById('affiliate-link');
         try {
            await navigator.clipboard.writeText(input.value);
            showToast('Link copiado! 链接已复制');
         } catch (err) {
            input.select();
            document.execCommand('copy');
            showToast('Link copiado! 链接已复制');
         }
      }

      // Social Share
      function shareSocial(network) {
         const url = encodeURIComponent(document.getElementById('affiliate-link').value);
         const text = encodeURIComponent("Junte-se à minha rede VIP e lucre! 🚀");
         let shareUrl = '';

         if(network === 'whatsapp') shareUrl = `https://api.whatsapp.com/send?text=${text}%20${url}`;
         else if(network === 'telegram') shareUrl = `https://t.me/share/url?url=${url}&text=${text}`;
         else if(network === 'facebook') shareUrl = `https://www.facebook.com/sharer/sharer.php?u=${url}`;

         window.open(shareUrl, '_blank');
      }

      <?php if ($toastMessage) : ?>
         window.addEventListener('load', () => showToast('<?= htmlspecialchars($toastMessage) ?>'));
      <?php endif; ?>
    </script>
  </body>
  </html>
<?php endif; ?>