
<!DOCTYPE html>
<html lang="vi" class="dark">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>CodeVortex - Chợ Source Code & Sàn Cá Cược Trải Nghiệm</title>
    <!-- Tailwind CSS -->
    <script src="https://cdn.tailwindcss.com"></script>
    <script>
        tailwind.config = {
            darkMode: 'class',
            theme: {
                extend: {
                    colors: {
                        brand: {
                            50: '#eef2ff',
                            100: '#e0e7ff',
                            500: '#6366f1',
                            600: '#4f46e5',
                            700: '#4338ca',
                            900: '#312e81',
                        },
                        darkbg: '#090d16',
                        darkcard: '#111827',
                    },
                    fontFamily: {
                        sans: ['Inter', 'sans-serif'],
                    }
                }
            }
        }
    </script>
    <!-- Google Fonts & FontAwesome Icons -->
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800&family=JetBrains+Mono:wght@400;700&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    
    <style>
        body {
            font-family: 'Inter', sans-serif;
            background-color: #090d16;
            color: #f3f4f6;
            overflow-x: hidden;
        }
        .font-mono-custom {
            font-family: 'JetBrains Mono', monospace;
        }
        /* Custom Scrollbar */
        ::-webkit-scrollbar {
            width: 8px;
        }
        ::-webkit-scrollbar-track {
            background: #090d16;
        }
        ::-webkit-scrollbar-thumb {
            background: #1f2937;
            border-radius: 4px;
        }
        ::-webkit-scrollbar-thumb:hover {
            background: #4f46e5;
        }
        /* Glassmorphism Backgrounds */
        .glass {
            background: rgba(17, 24, 39, 0.7);
            backdrop-filter: blur(12px);
            -webkit-backdrop-filter: blur(12px);
            border: 1px solid rgba(255, 255, 255, 0.08);
        }
        /* Glowing effects */
        .glow-purple {
            box-shadow: 0 0 40px -5px rgba(168, 85, 247, 0.4);
        }
        .glow-indigo {
            box-shadow: 0 0 50px -10px rgba(99, 102, 241, 0.5);
        }
        .glow-red {
            box-shadow: 0 0 40px -5px rgba(239, 68, 68, 0.4);
        }
        .glow-green {
            box-shadow: 0 0 40px -5px rgba(16, 185, 129, 0.4);
        }
    </style>
</head>
<body class="min-h-screen flex flex-col selection:bg-brand-500 selection:text-white">

    <!-- Ambient Glow Background Elements -->
    <div class="absolute top-0 left-1/4 w-96 h-96 bg-brand-600/20 rounded-full blur-[120px] pointer-events-none"></div>
    <div class="absolute top-1/3 right-1/4 w-[400px] h-[400px] bg-purple-600/15 rounded-full blur-[150px] pointer-events-none"></div>
    <div class="absolute bottom-10 left-1/3 w-80 h-80 bg-blue-600/10 rounded-full blur-[100px] pointer-events-none"></div>

    <!-- HEADER / NAVIGATION -->
    <header class="sticky top-0 z-40 w-full glass border-b border-white/5 transition-all duration-300">
        <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 h-20 flex items-center justify-between">
            <!-- Logo -->
            <a href="#" onclick="showPage('home')" class="flex items-center space-x-3 group">
                <div class="w-10 h-10 rounded-xl bg-gradient-to-tr from-brand-600 to-purple-600 flex items-center justify-center text-white font-bold text-xl shadow-lg shadow-brand-500/30 group-hover:scale-105 transition-transform">
                    <i class="fa-solid fa-cubes"></i>
                </div>
                <span class="text-2xl font-extrabold tracking-wider bg-gradient-to-r from-white via-indigo-200 to-indigo-400 bg-clip-text text-transparent">
                    CODE<span class="text-brand-500">VORTEX</span>
                </span>
            </a>

            <!-- Navigation Links -->
            <nav class="hidden lg:flex items-center space-x-8 text-sm font-medium">
                <a href="#" onclick="showPage('home')" class="text-gray-300 hover:text-white transition-colors">Trang Chủ</a>
                <a href="#marketplace" onclick="showPage('home')" class="text-gray-300 hover:text-white transition-colors">Source Code</a>
                <a href="#" onclick="openBetModal()" class="text-emerald-400 hover:text-emerald-300 transition-colors flex items-center space-x-1.5 font-bold">
                    <i class="fa-solid fa-chart-line animate-pulse"></i>
                    <span>Cá Cược Siêu Hũ (Crash)</span>
                </a>
                <a href="#" id="nav-admin-link" onclick="showPage('admin')" class="hidden text-rose-400 hover:text-rose-300 transition-colors flex items-center space-x-1">
                    <i class="fa-solid fa-user-shield"></i>
                    <span>Trang Admin</span>
                </a>
            </nav>

            <!-- Search Bar (Desktop) -->
            <div class="hidden md:flex flex-1 max-w-xs mx-4">
                <div class="relative w-full">
                    <input type="text" id="global-search" oninput="searchProducts()" placeholder="Tìm kiếm source code..." class="w-full bg-white/5 border border-white/10 rounded-full py-2 pl-10 pr-4 text-xs text-gray-200 placeholder-gray-400 focus:outline-none focus:border-brand-500 transition-all">
                    <div class="absolute inset-y-0 left-0 pl-3.5 flex items-center pointer-events-none">
                        <i class="fa-solid fa-magnifying-glass text-gray-400 text-xs"></i>
                    </div>
                </div>
            </div>

            <!-- Navigation Actions -->
            <div class="flex items-center space-x-3">
                <!-- Bet Game Shortcut (Mobile) -->
                <button onclick="openBetModal()" class="lg:hidden p-2.5 rounded-full bg-emerald-500/10 border border-emerald-500/20 text-emerald-400 hover:bg-emerald-500/20 transition-all">
                    <i class="fa-solid fa-chart-line animate-pulse"></i>
                </button>

                <!-- Cart Icon -->
                <button onclick="toggleCartModal()" class="relative p-2.5 rounded-full bg-white/5 border border-white/5 text-gray-300 hover:text-white hover:bg-white/10 transition-all">
                    <i class="fa-solid fa-cart-shopping text-base"></i>
                    <span id="cart-badge" class="absolute -top-1 -right-1 w-5 h-5 rounded-full bg-red-500 text-white text-[10px] font-bold flex items-center justify-center hidden">0</span>
                </button>

                <!-- Auth Section -->
                <div id="auth-section-guest" class="flex items-center space-x-1">
                    <button onclick="openAuthModal('login')" class="text-xs sm:text-sm font-semibold text-gray-300 hover:text-white transition-colors px-3 py-2">Đăng Nhập</button>
                    <button onclick="openAuthModal('register')" class="text-xs sm:text-sm font-semibold text-white bg-gradient-to-r from-brand-600 to-purple-600 hover:from-brand-700 hover:to-purple-700 px-4 py-2 rounded-full shadow-lg transition-all">Đăng Ký</button>
                </div>

                <div id="auth-section-user" class="hidden items-center space-x-3">
                    <!-- Balance -->
                    <div class="hidden sm:flex flex-col items-end text-[11px]">
                        <span class="text-gray-400">Số dư:</span>
                        <span id="user-balance" class="font-bold text-emerald-400 text-sm">0đ</span>
                    </div>
                    <!-- User Dropdown -->
                    <div class="relative">
                        <button onclick="toggleUserDropdown()" class="flex items-center space-x-2 focus:outline-none">
                            <img id="user-avatar" src="https://api.dicebear.com/7.x/adventurer/svg?seed=Felix" alt="Avatar" class="w-9 h-9 rounded-xl bg-indigo-900 border border-brand-500/30">
                            <i class="fa-solid fa-chevron-down text-gray-400 text-[10px]"></i>
                        </button>
                        <!-- Dropdown panel -->
                        <div id="user-dropdown" class="hidden absolute right-0 mt-3 w-56 glass rounded-2xl p-2 shadow-xl border border-white/10 z-50">
                            <div class="px-4 py-3 border-b border-white/5 mb-1">
                                <p class="text-sm font-bold text-white flex items-center gap-1" id="dropdown-username">Thành viên VIP</p>
                                <p class="text-xs text-gray-400 truncate" id="dropdown-email">user@codevortex.com</p>
                            </div>
                            <!-- Admin Switch inside dropdown if admin role -->
                            <a href="#" id="dropdown-admin-btn" onclick="showPage('admin')" class="hidden flex items-center space-x-3 px-3 py-2.5 rounded-xl text-rose-400 hover:bg-rose-500/10 transition-all text-sm">
                                <i class="fa-solid fa-user-shield w-5"></i>
                                <span>Trang Quản Trị (Admin)</span>
                            </a>
                            <a href="#" onclick="showPage('dashboard')" class="flex items-center space-x-3 px-3 py-2.5 rounded-xl text-gray-300 hover:text-white hover:bg-white/5 transition-all text-sm">
                                <i class="fa-solid fa-layer-group w-5 text-brand-400"></i>
                                <span>Kho Của Tôi</span>
                            </a>
                            <a href="#" onclick="openDepositModal()" class="flex items-center space-x-3 px-3 py-2.5 rounded-xl text-gray-300 hover:text-white hover:bg-white/5 transition-all text-sm">
                                <i class="fa-solid fa-wallet w-5 text-emerald-400"></i>
                                <span>Nạp Ví Tài Khoản</span>
                            </a>
                            <button onclick="logout()" class="w-full flex items-center space-x-3 px-3 py-2.5 rounded-xl text-red-400 hover:text-red-300 hover:bg-red-500/5 transition-all text-sm text-left">
                                <i class="fa-solid fa-right-from-bracket w-5"></i>
                                <span>Đăng Xuất</span>
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </header>

    <!-- MOBILE NAVIGATION LINKS -->
    <div class="lg:hidden flex items-center justify-around bg-darkbg border-b border-white/5 py-2.5 px-4 text-xs">
        <a href="#" onclick="showPage('home')" class="text-gray-300 hover:text-white flex flex-col items-center gap-1">
            <i class="fa-solid fa-house text-sm"></i>
            <span>Trang Chủ</span>
        </a>
        <a href="#marketplace" onclick="showPage('home')" class="text-gray-300 hover:text-white flex flex-col items-center gap-1">
            <i class="fa-solid fa-box-archive text-sm"></i>
            <span>Sản Phẩm</span>
        </a>
        <a href="#" onclick="openBetModal()" class="text-emerald-400 hover:text-emerald-300 flex flex-col items-center gap-1 font-bold">
            <i class="fa-solid fa-chart-line text-sm"></i>
            <span>Đặt Cược</span>
        </a>
        <a href="#" id="nav-admin-link-mobile" onclick="showPage('admin')" class="hidden text-rose-400 hover:text-rose-300 flex flex-col items-center gap-1">
            <i class="fa-solid fa-user-shield text-sm"></i>
            <span>Admin</span>
        </a>
    </div>

    <!-- MAIN CONTAINER -->
    <main class="flex-1 w-full max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8 relative z-10">

        <!-- ================= PAGE 1: HOME PAGE ================= -->
        <div id="page-home" class="space-y-16">
            
            <!-- HERO BANNER -->
            <section class="relative rounded-3xl overflow-hidden glass border border-white/10 p-8 sm:p-12 md:p-16 flex flex-col md:flex-row items-center justify-between gap-12 glow-indigo">
                <div class="absolute -top-40 -right-40 w-96 h-96 bg-indigo-600/20 rounded-full blur-[100px] pointer-events-none"></div>
                
                <div class="flex-1 space-y-6 text-center md:text-left">
                    <div class="inline-flex items-center space-x-2 bg-brand-500/10 border border-brand-500/30 px-3.5 py-1.5 rounded-full text-brand-400 text-xs sm:text-sm font-semibold tracking-wide">
                        <i class="fa-solid fa-bolt-lightning"></i>
                        <span>Chào Mừng Tới Kỷ Nguyên Mã Nguồn Mới</span>
                    </div>
                    <h1 class="text-4xl sm:text-5xl lg:text-6xl font-extrabold tracking-tight leading-tight">
                        Kiến Tạo Dự Án <br>
                        <span class="bg-gradient-to-r from-brand-400 via-indigo-300 to-purple-400 bg-clip-text text-transparent">Chỉ Trong Vài Giây</span>
                    </h1>
                    <p class="text-gray-400 text-base sm:text-lg max-w-xl">
                        Khám phá kho Source Code đỉnh cao, tối ưu sạch sẽ, sẵn sàng triển khai. Phù hợp cho lập trình viên, startup và doanh nghiệp lớn.
                    </p>
                    <div class="flex flex-col sm:flex-row items-center justify-center md:justify-start gap-4">
                        <a href="#marketplace" class="w-full sm:w-auto px-8 py-4 bg-gradient-to-r from-brand-600 to-purple-600 hover:from-brand-700 hover:to-purple-700 text-white font-bold rounded-2xl shadow-xl shadow-brand-500/25 hover:shadow-brand-500/35 transition-all text-center">
                            Khám Phá Ngay
                        </a>
                        <button onclick="openBetModal()" class="w-full sm:w-auto px-8 py-4 bg-emerald-500/10 border border-emerald-500/30 hover:bg-emerald-500/20 text-emerald-400 font-semibold rounded-2xl transition-all text-center flex items-center justify-center gap-2">
                            <i class="fa-solid fa-chart-line text-lg animate-pulse"></i>
                            <span>Cá Cược Nhân Ví (Crash)</span>
                        </button>
                    </div>
                </div>

                <!-- Animated Tech Illustration -->
                <div class="flex-1 relative max-w-md w-full aspect-square hidden md:block">
                    <div class="absolute inset-0 bg-gradient-to-tr from-brand-500/20 to-purple-500/20 rounded-3xl border border-white/10 flex items-center justify-center p-8">
                        <div class="grid grid-cols-3 gap-6 relative z-10 w-full max-w-xs">
                            <div class="bg-darkbg/80 border border-white/10 p-4 rounded-2xl flex flex-col items-center justify-center shadow-lg">
                                <i class="fa-brands fa-react text-blue-400 text-3xl mb-2"></i>
                                <span class="text-xs font-semibold text-gray-300">ReactJS</span>
                            </div>
                            <div class="bg-darkbg/80 border border-white/10 p-4 rounded-2xl flex flex-col items-center justify-center shadow-lg transform translate-y-4">
                                <i class="fa-brands fa-node-js text-emerald-400 text-3xl mb-2"></i>
                                <span class="text-xs font-semibold text-gray-300">NodeJS</span>
                            </div>
                            <div class="bg-darkbg/80 border border-white/10 p-4 rounded-2xl flex flex-col items-center justify-center shadow-lg">
                                <i class="fa-brands fa-python text-yellow-400 text-3xl mb-2"></i>
                                <span class="text-xs font-semibold text-gray-300">Python</span>
                            </div>
                            <div class="bg-darkbg/80 border border-white/10 p-4 rounded-2xl flex flex-col items-center justify-center shadow-lg">
                                <i class="fa-brands fa-vuejs text-teal-400 text-3xl mb-2"></i>
                                <span class="text-xs font-semibold text-gray-300">VueJS</span>
                            </div>
                            <div class="bg-darkbg/80 border border-white/10 p-4 rounded-2xl flex flex-col items-center justify-center shadow-lg transform translate-y-4">
                                <i class="fa-brands fa-laravel text-red-500 text-3xl mb-2"></i>
                                <span class="text-xs font-semibold text-gray-300">Laravel</span>
                            </div>
                            <div class="bg-darkbg/80 border border-white/10 p-4 rounded-2xl flex flex-col items-center justify-center shadow-lg">
                                <i class="fa-brands fa-docker text-sky-400 text-3xl mb-2"></i>
                                <span class="text-xs font-semibold text-gray-300">Docker</span>
                            </div>
                        </div>
                    </div>
                </div>
            </section>

            <!-- STATS SECTION -->
            <section class="grid grid-cols-2 md:grid-cols-4 gap-6">
                <div class="glass border border-white/5 p-6 rounded-2xl text-center">
                    <p class="text-4xl font-extrabold text-brand-400" id="stats-total-products">6+</p>
                    <p class="text-xs text-gray-400 mt-2 font-medium uppercase tracking-wider">Source Code Cao Cấp</p>
                </div>
                <div class="glass border border-white/5 p-6 rounded-2xl text-center">
                    <p class="text-4xl font-extrabold text-purple-400">15,000+</p>
                    <p class="text-xs text-gray-400 mt-2 font-medium uppercase tracking-wider">Khách Hàng Đã Tin Dùng</p>
                </div>
                <div class="glass border border-white/5 p-6 rounded-2xl text-center">
                    <p class="text-4xl font-extrabold text-emerald-400">99.8%</p>
                    <p class="text-xs text-gray-400 mt-2 font-medium uppercase tracking-wider">Tỉ Lệ Đánh Giá 5 Sao</p>
                </div>
                <div class="glass border border-white/5 p-6 rounded-2xl text-center">
                    <p class="text-4xl font-extrabold text-blue-400">24/7</p>
                    <p class="text-xs text-gray-400 mt-2 font-medium uppercase tracking-wider">Hỗ Trợ Triển Khai Kỹ Thuật</p>
                </div>
            </section>

            <!-- CATEGORY FILTER / MARKETPLACE -->
            <section id="marketplace" class="space-y-8 scroll-mt-24">
                <div class="flex flex-col md:flex-row items-start md:items-end justify-between gap-6">
                    <div>
                        <h2 class="text-3xl font-extrabold text-white tracking-tight">Thư Viện Sản Phẩm</h2>
                        <p class="text-gray-400 mt-2 text-sm sm:text-base">Các mã nguồn chất lượng cao, luôn cập nhật các phiên bản mới nhất.</p>
                    </div>
                    
                    <!-- Category Filters -->
                    <div class="flex flex-wrap gap-2 w-full md:w-auto">
                        <button onclick="filterCategory('all')" id="filter-all" class="filter-btn px-4 py-2 text-xs font-semibold rounded-xl bg-brand-600 text-white transition-all shadow-lg shadow-brand-500/20">Tất Cả</button>
                        <button onclick="filterCategory('web')" id="filter-web" class="filter-btn px-4 py-2 text-xs font-semibold rounded-xl bg-white/5 border border-white/5 text-gray-400 hover:text-white hover:bg-white/10 transition-all">Web Apps</button>
                        <button onclick="filterCategory('app')" id="filter-app" class="filter-btn px-4 py-2 text-xs font-semibold rounded-xl bg-white/5 border border-white/5 text-gray-400 hover:text-white hover:bg-white/10 transition-all">Mobile Apps</button>
                        <button onclick="filterCategory('game')" id="filter-game" class="filter-btn px-4 py-2 text-xs font-semibold rounded-xl bg-white/5 border border-white/5 text-gray-400 hover:text-white hover:bg-white/10 transition-all">Game Sources</button>
                        <button onclick="filterCategory('tool')" id="filter-tool" class="filter-btn px-4 py-2 text-xs font-semibold rounded-xl bg-white/5 border border-white/5 text-gray-400 hover:text-white hover:bg-white/10 transition-all">Tools & AI</button>
                    </div>
                </div>

                <!-- Products Grid -->
                <div id="products-grid" class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-8">
                    <!-- Cards will be populated dynamically by Javascript -->
                </div>
            </section>
        </div>


        <!-- ================= PAGE 2: PRODUCT DETAIL PAGE ================= -->
        <div id="page-detail" class="hidden space-y-12">
            <!-- Breadcrumbs -->
            <nav class="flex text-sm text-gray-400 space-x-2">
                <button onclick="showPage('home')" class="hover:text-white">Trang chủ</button>
                <span>/</span>
                <span id="detail-breadcrumb-category" class="capitalize">Sản phẩm</span>
                <span>/</span>
                <span id="detail-breadcrumb-title" class="text-white font-medium">Chi tiết</span>
            </nav>

            <!-- Main Content Area -->
            <div class="grid grid-cols-1 lg:grid-cols-3 gap-12">
                <!-- Left Details Area -->
                <div class="lg:col-span-2 space-y-8">
                    <div class="relative w-full aspect-video rounded-3xl overflow-hidden glass border border-white/10">
                        <img id="detail-img" src="" alt="Source code banner" class="w-full h-full object-cover">
                        <div class="absolute bottom-6 left-6 px-4 py-2 bg-darkbg/90 backdrop-blur-md rounded-2xl border border-white/10 text-xs font-bold text-brand-400 flex items-center space-x-2">
                            <i class="fa-solid fa-layer-group"></i>
                            <span id="detail-tech">Technology</span>
                        </div>
                    </div>

                    <div class="flex border-b border-white/5 space-x-6">
                        <button class="border-b-2 border-brand-500 pb-4 text-sm font-semibold text-white">Mô Tả Chi Tiết</button>
                        <button class="pb-4 text-sm font-medium text-gray-400 hover:text-white transition-colors">Hướng Dẫn Cài Đặt</button>
                    </div>

                    <div class="space-y-6 text-gray-300 leading-relaxed">
                        <p id="detail-desc" class="text-lg text-gray-400"></p>
                        <div class="space-y-4">
                            <h3 class="text-xl font-bold text-white">Tính năng nổi bật</h3>
                            <ul class="grid grid-cols-1 sm:grid-cols-2 gap-3 text-sm">
                                <li class="flex items-center space-x-2.5">
                                    <i class="fa-solid fa-circle-check text-emerald-400"></i>
                                    <span>Giao diện chuẩn Responsive (Mobile / Desktop)</span>
                                </li>
                                <li class="flex items-center space-x-2.5">
                                    <i class="fa-solid fa-circle-check text-emerald-400"></i>
                                    <span>Tối ưu hóa tốc độ tải cực nhanh</span>
                                </li>
                                <li class="flex items-center space-x-2.5">
                                    <i class="fa-solid fa-circle-check text-emerald-400"></i>
                                    <span>Cài đặt, triển khai siêu nhanh gọn</span>
                                </li>
                                <li class="flex items-center space-x-2.5">
                                    <i class="fa-solid fa-circle-check text-emerald-400"></i>
                                    <span>Miễn phí nâng cấp trọn đời (Update OTA)</span>
                                </li>
                            </ul>
                        </div>
                    </div>
                </div>

                <!-- Right Checkout Card -->
                <div class="space-y-6">
                    <div class="glass border border-white/10 p-8 rounded-3xl sticky top-28 glow-indigo">
                        <div class="inline-flex px-3 py-1 bg-brand-500/15 text-brand-400 text-xs font-semibold rounded-lg mb-4 uppercase tracking-wider" id="detail-badge-cat">Web</div>
                        <h2 class="text-2xl font-bold text-white mb-2" id="detail-title">Tên Source Code</h2>
                        
                        <div class="flex items-center space-x-4 text-xs text-gray-400 mb-6">
                            <span class="flex items-center space-x-1">
                                <i class="fa-solid fa-star text-yellow-400"></i>
                                <span class="font-bold text-white">4.9</span>
                                <span>(32 đánh giá)</span>
                            </span>
                            <span>|</span>
                            <span class="flex items-center space-x-1">
                                <i class="fa-solid fa-cloud-arrow-down"></i>
                                <span class="font-bold text-white" id="detail-downloads">120</span>
                                <span>lượt mua</span>
                            </span>
                        </div>

                        <div class="bg-white/5 border border-white/5 rounded-2xl p-4 mb-6">
                            <p class="text-xs text-gray-400 mb-1">Mức giá ưu đãi hiện tại:</p>
                            <div class="flex items-baseline space-x-3">
                                <span class="text-3xl font-extrabold text-brand-400" id="detail-price">0đ</span>
                                <span class="text-sm text-gray-500 line-through" id="detail-oldprice">0đ</span>
                            </div>
                        </div>

                        <div class="space-y-3">
                            <button id="btn-buy-now" class="w-full py-4 bg-gradient-to-r from-brand-600 to-purple-600 hover:from-brand-700 hover:to-purple-700 text-white font-bold rounded-xl shadow-lg transition-all flex items-center justify-center space-x-2">
                                <i class="fa-solid fa-credit-card"></i>
                                <span>MUA NGAY SẢN PHẨM</span>
                            </button>
                            <button id="btn-add-cart" class="w-full py-4 bg-white/5 border border-white/10 hover:bg-white/10 text-white font-semibold rounded-xl transition-all flex items-center justify-center space-x-2">
                                <i class="fa-solid fa-cart-plus"></i>
                                <span>Thêm Vào Giỏ Hàng</span>
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        </div>


        <!-- ================= PAGE 3: USER DASHBOARD ================= -->
        <div id="page-dashboard" class="hidden space-y-12">
            <div class="flex flex-col md:flex-row items-center justify-between gap-6 glass border border-white/10 p-8 rounded-3xl glow-purple">
                <div class="flex items-center space-x-4">
                    <img id="dash-avatar" src="https://api.dicebear.com/7.x/adventurer/svg?seed=Felix" alt="Dashboard Avatar" class="w-16 h-16 rounded-2xl border border-brand-500/40 bg-indigo-900">
                    <div>
                        <h2 class="text-2xl font-bold text-white flex items-center gap-2">
                            <span id="dash-username">Thành viên VIP</span>
                            <span class="text-xs bg-brand-500/20 text-brand-400 border border-brand-500/30 px-2 py-0.5 rounded">Khách Hàng Thân Thiết</span>
                        </h2>
                        <p class="text-sm text-gray-400" id="dash-email">user@codevortex.com</p>
                    </div>
                </div>

                <div class="flex items-center gap-4 w-full md:w-auto justify-end">
                    <div class="bg-white/5 border border-white/5 px-6 py-4 rounded-2xl text-right">
                        <p class="text-xs text-gray-400 mb-0.5">Số Dư Hiện Tại</p>
                        <p class="text-xl font-extrabold text-emerald-400" id="dash-balance">0đ</p>
                    </div>
                    <button onclick="openDepositModal()" class="px-6 py-4 bg-emerald-500 hover:bg-emerald-600 text-white font-bold rounded-2xl transition-all">
                        Nạp Tiền
                    </button>
                </div>
            </div>

            <div class="space-y-6">
                <h3 class="text-2xl font-bold text-white">Kho Source Code Đã Sở Hữu</h3>
                <div id="purchased-items-grid" class="grid grid-cols-1 md:grid-cols-2 gap-6">
                    <!-- Dynamic Items loaded here -->
                </div>
            </div>
        </div>


        <!-- ================= PAGE 4: ADMIN DASHBOARD ================= -->
        <div id="page-admin" class="hidden space-y-8">
            <div class="flex items-center justify-between border-b border-white/10 pb-4">
                <div>
                    <h2 class="text-3xl font-extrabold text-rose-400 tracking-tight flex items-center gap-2">
                        <i class="fa-solid fa-user-shield"></i>
                        <span>Quản Lý Hệ Thống CodeVortex</span>
                    </h2>
                    <p class="text-sm text-gray-400 mt-1">Giao diện quản trị, thêm mới và quản lý mã nguồn trên toàn bộ trang web.</p>
                </div>
                <button onclick="showPage('home')" class="px-4 py-2 text-xs font-semibold rounded-xl bg-white/5 hover:bg-white/10 text-white border border-white/10 transition-all">
                    Quay về Trang Chủ
                </button>
            </div>

            <div class="grid grid-cols-1 lg:grid-cols-3 gap-8">
                <!-- Add New Product Form -->
                <div class="lg:col-span-1 glass border border-white/10 rounded-3xl p-6 space-y-6 relative overflow-hidden">
                    <div class="absolute -top-20 -left-20 w-40 h-40 bg-rose-500/10 rounded-full blur-2xl pointer-events-none"></div>
                    <h3 class="text-xl font-bold text-white flex items-center gap-2">
                        <i class="fa-solid fa-circle-plus text-rose-400"></i>
                        <span>Đăng Code Mới</span>
                    </h3>
                    
                    <form id="admin-add-product-form" onsubmit="handleAdminAddProduct(event)" class="space-y-4 text-xs sm:text-sm">
                        <div class="space-y-1.5">
                            <label class="font-semibold text-gray-300">Tên Source Code</label>
                            <input type="text" id="admin-title" required placeholder="Nhập tên source code..." class="w-full bg-white/5 border border-white/10 rounded-xl py-2.5 px-3 text-white focus:outline-none focus:border-rose-500">
                        </div>

                        <div class="grid grid-cols-2 gap-4">
                            <div class="space-y-1.5">
                                <label class="font-semibold text-gray-300">Danh Mục</label>
                                <select id="admin-category" class="w-full bg-white/5 border border-white/10 rounded-xl py-2.5 px-3 text-white focus:outline-none focus:border-rose-500">
                                    <option value="web" class="bg-darkcard text-white">Web Apps</option>
                                    <option value="app" class="bg-darkcard text-white">Mobile Apps</option>
                                    <option value="game" class="bg-darkcard text-white">Game Sources</option>
                                    <option value="tool" class="bg-darkcard text-white">Tools & AI</option>
                                </select>
                            </div>
                            <div class="space-y-1.5">
                                <label class="font-semibold text-gray-300">Công Nghệ</label>
                                <input type="text" id="admin-tech" required placeholder="ReactJS, Python..." class="w-full bg-white/5 border border-white/10 rounded-xl py-2.5 px-3 text-white focus:outline-none focus:border-rose-500">
                            </div>
                        </div>

                        <div class="grid grid-cols-2 gap-4">
                            <div class="space-y-1.5">
                                <label class="font-semibold text-gray-300">Giá Bán (VNĐ)</label>
                                <input type="number" id="admin-price" required min="0" placeholder="299000" class="w-full bg-white/5 border border-white/10 rounded-xl py-2.5 px-3 text-white focus:outline-none focus:border-rose-500">
                            </div>
                            <div class="space-y-1.5">
                                <label class="font-semibold text-gray-300">Giá Cũ (Gốc)</label>
                                <input type="number" id="admin-oldprice" required min="0" placeholder="590000" class="w-full bg-white/5 border border-white/10 rounded-xl py-2.5 px-3 text-white focus:outline-none focus:border-rose-500">
                            </div>
                        </div>

                        <div class="space-y-1.5">
                            <label class="font-semibold text-gray-300">Tên Tệp Tin Giả Định</label>
                            <input type="text" id="admin-sourcefile" required placeholder="source_code_clean.zip" class="w-full bg-white/5 border border-white/10 rounded-xl py-2.5 px-3 text-white focus:outline-none focus:border-rose-500">
                        </div>

                        <div class="space-y-1.5">
                            <label class="font-semibold text-gray-300">Liên Kết Hình Ảnh (URL)</label>
                            <input type="url" id="admin-image" required placeholder="https://images.unsplash.com/..." class="w-full bg-white/5 border border-white/10 rounded-xl py-2.5 px-3 text-white focus:outline-none focus:border-rose-500">
                        </div>

                        <div class="space-y-1.5">
                            <label class="font-semibold text-gray-300">Mô Tả Sản Phẩm</label>
                            <textarea id="admin-desc" required rows="4" placeholder="Mô tả cấu trúc thư mục, hướng dẫn..." class="w-full bg-white/5 border border-white/10 rounded-xl py-2.5 px-3 text-white focus:outline-none focus:border-rose-500 resize-none"></textarea>
                        </div>

                        <button type="submit" class="w-full py-3 bg-gradient-to-r from-rose-500 to-pink-600 hover:from-rose-600 hover:to-pink-700 text-white font-bold rounded-xl shadow-lg shadow-rose-500/20 transition-all">
                            XÁC NHẬN ĐĂNG SẢN PHẨM
                        </button>
                    </form>
                </div>

                <!-- Product List & Management Actions -->
                <div class="lg:col-span-2 glass border border-white/10 rounded-3xl p-6 space-y-6">
                    <div class="flex items-center justify-between">
                        <h3 class="text-xl font-bold text-white flex items-center gap-2">
                            <i class="fa-solid fa-list-check text-rose-400"></i>
                            <span>Danh Sách Mã Nguồn Hệ Thống</span>
                        </h3>
                        <span class="text-xs bg-rose-500/10 border border-rose-500/20 text-rose-400 px-3 py-1 rounded-full font-medium" id="admin-product-count">0 Sản phẩm</span>
                    </div>

                    <!-- Table -->
                    <div class="overflow-x-auto w-full">
                        <table class="w-full text-left border-collapse text-xs sm:text-sm">
                            <thead>
                                <tr class="border-b border-white/10 text-gray-400 font-semibold">
                                    <th class="pb-3 pr-2">Sản phẩm</th>
                                    <th class="pb-3 px-2">Danh mục</th>
                                    <th class="pb-3 px-2">Giá thành</th>
                                    <th class="pb-3 pl-2 text-right">Hành động</th>
                                </tr>
                            </thead>
                            <tbody id="admin-products-table-body" class="divide-y divide-white/5">
                                <!-- Dynamic admin product rows -->
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>

    </main>

    <!-- FOOTER -->
    <footer class="w-full glass border-t border-white/5 mt-20 relative z-10">
        <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-12 space-y-8">
            <div class="grid grid-cols-1 md:grid-cols-4 gap-8">
                <!-- Branding and info -->
                <div class="md:col-span-2 space-y-4">
                    <span class="text-2xl font-extrabold bg-gradient-to-r from-white via-indigo-200 to-indigo-400 bg-clip-text text-transparent">CODE<span class="text-brand-500">VORTEX</span></span>
                    <p class="text-gray-400 text-sm max-w-sm">Chợ chia sẻ tài nguyên và mã nguồn đỉnh cao. Khởi tạo mọi ý tưởng của bạn với bộ code chuẩn, sạch và độ ổn định cao nhất.</p>
                </div>
                <!-- Nav Links -->
                <div>
                    <h4 class="text-white font-bold mb-4">Danh Mục Hot</h4>
                    <ul class="space-y-2 text-sm text-gray-400">
                        <li><a href="#" class="hover:text-white transition-colors">Thiết Kế Web Thương Mại</a></li>
                        <li><a href="#" class="hover:text-white transition-colors">Ứng Dụng Đa Nền Tảng</a></li>
                        <li><a href="#" class="hover:text-white transition-colors">Tools AI Automation</a></li>
                    </ul>
                </div>
                <!-- Contact info -->
                <div>
                    <h4 class="text-white font-bold mb-4">Hỗ Trợ Kỹ Thuật</h4>
                    <ul class="space-y-2 text-sm text-gray-400">
                        <li><span>Hotline: 1900 xxxx (8h - 22h)</span></li>
                        <li><span>Telegram: @codevortex_support</span></li>
                        <li><span>Email: admin@codevortex.com</span></li>
                    </ul>
                </div>
            </div>
            
            <div class="pt-8 border-t border-white/5 flex flex-col md:flex-row items-center justify-between gap-4 text-xs text-gray-400">
                <p>&copy; 2026 CodeVortex. All Rights Reserved.</p>
                <div class="flex space-x-6">
                    <a href="#" class="hover:text-white transition-colors">Điều Khoản Sử Dụng</a>
                    <a href="#" class="hover:text-white transition-colors">Chính Sách Hoàn Tiền</a>
                </div>
            </div>
        </div>
    </footer>


    <!-- ================= MODALS SYSTEM ================= -->

    <!-- 1. AUTHENTICATION MODAL -->
    <div id="auth-modal" class="hidden fixed inset-0 z-50 flex items-center justify-center p-4 bg-darkbg/80 backdrop-blur-md">
        <div class="w-full max-w-md glass border border-white/10 rounded-3xl p-8 shadow-2xl relative glow-purple">
            <button onclick="closeAuthModal()" class="absolute top-5 right-5 text-gray-400 hover:text-white transition-colors">
                <i class="fa-solid fa-xmark text-lg"></i>
            </button>

            <!-- Dynamic Tab Header -->
            <div class="flex justify-center border-b border-white/5 pb-4 mb-6 space-x-6">
                <button id="tab-login" onclick="switchAuthTab('login')" class="text-xl font-bold pb-2 border-b-2 border-brand-500 text-white transition-all">Đăng Nhập</button>
                <button id="tab-register" onclick="switchAuthTab('register')" class="text-xl font-bold pb-2 text-gray-400 hover:text-white transition-all">Đăng Ký</button>
            </div>

            <!-- Hint Information -->
            <div class="bg-indigo-500/10 border border-indigo-500/20 rounded-xl p-3 text-xs text-indigo-300 mb-4 text-center">
                <i class="fa-solid fa-circle-info mr-1"></i> Gợi ý: Đăng nhập với tài khoản <strong class="text-white">admin</strong> mật khẩu <strong class="text-white">admin123</strong> để có quyền Admin!
            </div>

            <!-- Login Form -->
            <form id="form-login" onsubmit="handleLoginSubmit(event)" class="space-y-5">
                <div class="space-y-2">
                    <label class="text-xs font-semibold text-gray-300">Tên tài khoản hoặc Email</label>
                    <div class="relative">
                        <input type="text" id="login-username" required placeholder="Nhập tài khoản 'admin'..." class="w-full bg-white/5 border border-white/10 rounded-xl py-3 pl-11 pr-4 text-sm text-white placeholder-gray-500 focus:outline-none focus:border-brand-500">
                        <div class="absolute inset-y-0 left-0 pl-4 flex items-center pointer-events-none text-gray-400">
                            <i class="fa-solid fa-user"></i>
                        </div>
                    </div>
                </div>

                <div class="space-y-2">
                    <label class="text-xs font-semibold text-gray-300">Mật khẩu</label>
                    <div class="relative">
                        <input type="password" id="login-password" required placeholder="Nhập mật khẩu 'admin123'..." class="w-full bg-white/5 border border-white/10 rounded-xl py-3 pl-11 pr-4 text-sm text-white placeholder-gray-500 focus:outline-none focus:border-brand-500">
                        <div class="absolute inset-y-0 left-0 pl-4 flex items-center pointer-events-none text-gray-400">
                            <i class="fa-solid fa-lock"></i>
                        </div>
                    </div>
                </div>

                <button type="submit" class="w-full py-3.5 bg-gradient-to-r from-brand-600 to-purple-600 hover:from-brand-700 hover:to-purple-700 text-white font-bold rounded-xl shadow-lg transition-all">ĐĂNG NHẬP NGAY</button>
            </form>

            <!-- Register Form -->
            <form id="form-register" onsubmit="handleRegisterSubmit(event)" class="hidden space-y-4">
                <div class="space-y-1.5">
                    <label class="text-xs font-semibold text-gray-300">Tên hiển thị</label>
                    <div class="relative">
                        <input type="text" id="reg-name" required placeholder="Nguyễn Văn A" class="w-full bg-white/5 border border-white/10 rounded-xl py-3 pl-11 pr-4 text-sm text-white placeholder-gray-500 focus:outline-none focus:border-brand-500">
                        <div class="absolute inset-y-0 left-0 pl-4 flex items-center pointer-events-none text-gray-400">
                            <i class="fa-solid fa-address-card"></i>
                        </div>
                    </div>
                </div>

                <div class="space-y-1.5">
                    <label class="text-xs font-semibold text-gray-300">Tên đăng nhập (Username)</label>
                    <div class="relative">
                        <input type="text" id="reg-username" required placeholder="user123" class="w-full bg-white/5 border border-white/10 rounded-xl py-3 pl-11 pr-4 text-sm text-white placeholder-gray-500 focus:outline-none focus:border-brand-500">
                        <div class="absolute inset-y-0 left-0 pl-4 flex items-center pointer-events-none text-gray-400">
                            <i class="fa-solid fa-user"></i>
                        </div>
                    </div>
                </div>

                <div class="space-y-1.5">
                    <label class="text-xs font-semibold text-gray-300">Địa chỉ Email</label>
                    <div class="relative">
                        <input type="email" id="reg-email" required placeholder="contact@domain.com" class="w-full bg-white/5 border border-white/10 rounded-xl py-3 pl-11 pr-4 text-sm text-white placeholder-gray-500 focus:outline-none focus:border-brand-500">
                        <div class="absolute inset-y-0 left-0 pl-4 flex items-center pointer-events-none text-gray-400">
                            <i class="fa-solid fa-envelope"></i>
                        </div>
                    </div>
                </div>

                <div class="space-y-1.5">
                    <label class="text-xs font-semibold text-gray-300">Mật khẩu</label>
                    <div class="relative">
                        <input type="password" id="reg-password" required placeholder="Tối thiểu 6 kí tự..." class="w-full bg-white/5 border border-white/10 rounded-xl py-3 pl-11 pr-4 text-sm text-white placeholder-gray-500 focus:outline-none focus:border-brand-500">
                        <div class="absolute inset-y-0 left-0 pl-4 flex items-center pointer-events-none text-gray-400">
                            <i class="fa-solid fa-lock"></i>
                        </div>
                    </div>
                </div>

                <button type="submit" class="w-full py-3.5 bg-gradient-to-r from-brand-600 to-purple-600 hover:from-brand-700 hover:to-purple-700 text-white font-bold rounded-xl shadow-lg transition-all mt-2">XÁC NHẬN ĐĂNG KÝ TÀI KHOẢN</button>
            </form>
        </div>
    </div>

    <!-- 2. DEPOSIT / TOP UP MODAL -->
    <div id="deposit-modal" class="hidden fixed inset-0 z-50 flex items-center justify-center p-4 bg-darkbg/80 backdrop-blur-md">
        <div class="w-full max-w-lg glass border border-white/10 rounded-3xl p-8 shadow-2xl relative glow-indigo">
            <button onclick="closeDepositModal()" class="absolute top-5 right-5 text-gray-400 hover:text-white transition-colors">
                <i class="fa-solid fa-xmark text-lg"></i>
            </button>

            <h3 class="text-2xl font-bold text-white mb-2">Nạp Tiền Vào Ví</h3>
            <p class="text-sm text-gray-400 mb-6">Tiền nạp có thể dùng để mua source code hoặc đặt cược cá cược ở Minigame!</p>

            <div class="space-y-6">
                <div class="bg-white/5 border border-white/10 rounded-2xl p-5 space-y-4">
                    <div class="flex items-center justify-between">
                        <div class="flex items-center space-x-3">
                            <div class="w-10 h-10 rounded-xl bg-indigo-500/10 flex items-center justify-center text-indigo-400">
                                <i class="fa-solid fa-building-columns"></i>
                            </div>
                            <div>
                                <h4 class="font-bold text-white text-sm">Chuyển khoản Ngân hàng tự động</h4>
                                <p class="text-xs text-gray-400">Duyệt nhanh trong vòng 1-3 phút</p>
                            </div>
                        </div>
                        <span class="px-2 py-0.5 bg-emerald-500/20 text-emerald-400 text-[10px] font-semibold rounded">Khuyên dùng</span>
                    </div>

                    <div class="flex flex-col sm:flex-row items-center gap-6 pt-2">
                        <div class="w-36 h-36 bg-white p-2 rounded-xl flex flex-col items-center justify-center shadow-lg relative">
                            <div class="w-full h-full bg-cover bg-center" style="background-image: url('https://api.qrserver.com/v1/create-qr-code/?size=150x150&data=VCB-1014859345-CodeVortex');"></div>
                        </div>

                        <div class="flex-1 space-y-2 text-xs sm:text-sm">
                            <div class="flex justify-between border-b border-white/5 pb-2">
                                <span class="text-gray-400">Ngân hàng:</span>
                                <span class="font-bold text-white">Vietcombank (VCB)</span>
                            </div>
                            <div class="flex justify-between border-b border-white/5 pb-2">
                                <span class="text-gray-400">Số tài khoản:</span>
                                <span class="font-mono font-bold text-brand-400 cursor-pointer hover:underline" onclick="copyText('1014859345')">1014859345 <i class="fa-regular fa-copy ml-1"></i></span>
                            </div>
                            <div class="flex justify-between border-b border-white/5 pb-2">
                                <span class="text-gray-400">Chủ tài khoản:</span>
                                <span class="font-bold text-white">NGUYEN VAN A</span>
                            </div>
                            <div class="flex justify-between border-b border-white/5 pb-2">
                                <span class="text-gray-400">Nội dung CK:</span>
                                <span id="deposit-memo" class="font-mono font-bold text-yellow-400 cursor-pointer hover:underline" onclick="copyText(document.getElementById('deposit-memo').innerText)">CODEVORTEX USER <i class="fa-regular fa-copy ml-1"></i></span>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Simulation Quick Deposit tool -->
                <div class="space-y-2">
                    <label class="text-xs font-semibold text-gray-300">Nhập số tiền nạp nhanh (Giả lập hệ thống):</label>
                    <div class="flex gap-2">
                        <input type="number" id="test-deposit-amount" value="500000" min="20000" class="flex-1 bg-white/5 border border-white/10 rounded-xl px-4 text-sm text-white focus:outline-none focus:border-brand-500">
                        <button onclick="simulateDeposit()" class="px-5 py-3 bg-emerald-500 hover:bg-emerald-600 text-white font-bold text-xs rounded-xl transition-all shadow-md">
                            Nạp Thử Ngay
                        </button>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- 3. SHOPPING CART MODAL -->
    <div id="cart-modal" class="hidden fixed inset-0 z-50 flex justify-end bg-darkbg/80 backdrop-blur-sm">
        <div class="w-full max-w-md h-full glass border-l border-white/10 p-6 shadow-2xl flex flex-col justify-between">
            <div>
                <div class="flex items-center justify-between border-b border-white/5 pb-4 mb-6">
                    <h3 class="text-xl font-bold text-white flex items-center space-x-2">
                        <i class="fa-solid fa-basket-shopping text-brand-400"></i>
                        <span>Giỏ Hàng Của Bạn</span>
                    </h3>
                    <button onclick="toggleCartModal()" class="text-gray-400 hover:text-white transition-colors">
                        <i class="fa-solid fa-xmark text-lg"></i>
                    </button>
                </div>

                <div id="cart-items-container" class="space-y-4 max-h-[60vh] overflow-y-auto pr-2">
                    <!-- Dynamic Items rendered here -->
                </div>
            </div>

            <div class="border-t border-white/10 pt-6 space-y-4">
                <div class="flex justify-between items-center text-sm">
                    <span class="text-gray-400">Tạm tính:</span>
                    <span id="cart-subtotal" class="font-bold text-white">0đ</span>
                </div>
                <div class="flex justify-between items-center text-base">
                    <span class="text-gray-400">Tổng thanh toán:</span>
                    <span id="cart-total" class="text-2xl font-extrabold text-brand-400">0đ</span>
                </div>

                <button onclick="checkoutCart()" class="w-full py-4 bg-gradient-to-r from-brand-600 to-purple-600 hover:from-brand-700 hover:to-purple-700 text-white font-bold rounded-xl shadow-lg transition-all flex items-center justify-center space-x-2">
                    <i class="fa-solid fa-wallet"></i>
                    <span>THANH TOÁN GIỎ HÀNG</span>
                </button>
            </div>
        </div>
    </div>

    <!-- 4. CRASH BETTING MINIGAME MODAL (New Feature replacing Lucky Wheel) -->
    <div id="bet-modal" class="hidden fixed inset-0 z-50 flex items-center justify-center p-4 bg-darkbg/90 backdrop-blur-md">
        <div class="w-full max-w-xl glass border border-white/10 rounded-3xl p-6 sm:p-8 shadow-2xl relative glow-green flex flex-col">
            <button onclick="closeBetModal()" class="absolute top-5 right-5 text-gray-400 hover:text-white transition-colors">
                <i class="fa-solid fa-xmark text-lg"></i>
            </button>

            <!-- Title Header -->
            <div class="text-center space-y-2 mb-6">
                <h3 class="text-2xl sm:text-3xl font-extrabold text-transparent bg-clip-text bg-gradient-to-r from-emerald-400 via-teal-300 to-indigo-400">
                    SÀN CRASH BET COIN
                </h3>
                <p class="text-xs sm:text-sm text-gray-400">Cá cược nến tăng trưởng. Chốt lời nhân tài sản trước khi nến sập (Crash)!</p>
            </div>

            <!-- Game Interface Screen -->
            <div class="grid grid-cols-1 md:grid-cols-3 gap-6">
                <!-- Betting Control (Left side) -->
                <div class="md:col-span-1 space-y-4">
                    <div class="bg-white/5 border border-white/10 rounded-2xl p-4 space-y-3">
                        <p class="text-xs font-semibold text-gray-400 uppercase tracking-wider">Bảng Đặt Cược</p>
                        
                        <!-- Bet Amount Input -->
                        <div class="space-y-1">
                            <label class="text-[10px] font-bold text-gray-300">Tiền cược (VNĐ)</label>
                            <input type="number" id="crash-bet-amount" value="50000" min="1000" step="1000" class="w-full bg-darkbg border border-white/10 rounded-xl py-2 px-3 text-sm text-white font-mono-custom focus:outline-none focus:border-emerald-500">
                        </div>

                        <!-- Shortcut Bet buttons -->
                        <div class="grid grid-cols-2 gap-1.5 text-[10px] font-bold">
                            <button onclick="setCrashBetShortcut('half')" class="py-1 bg-white/5 hover:bg-white/10 border border-white/5 rounded-lg text-gray-300">1/2 Cược</button>
                            <button onclick="setCrashBetShortcut('double')" class="py-1 bg-white/5 hover:bg-white/10 border border-white/5 rounded-lg text-gray-300">X2 Cược</button>
                            <button onclick="setCrashBetShortcut('all')" class="col-span-2 py-1 bg-emerald-500/10 hover:bg-emerald-500/20 border border-emerald-500/20 rounded-lg text-emerald-400">Tất tay (All-in)</button>
                        </div>
                    </div>

                    <!-- Main action button -->
                    <div class="space-y-2">
                        <!-- Bet / Cashout Button State -->
                        <button id="crash-main-btn" onclick="handleCrashButtonClick()" class="w-full py-4 bg-emerald-500 hover:bg-emerald-600 text-white font-bold rounded-2xl shadow-lg shadow-emerald-500/20 transition-all text-sm flex flex-col items-center justify-center">
                            <span id="crash-btn-primary-text">BẮT ĐẦU CƯỢC</span>
                            <span id="crash-btn-secondary-text" class="text-[10px] text-emerald-100 font-normal">Đặt tiền và khởi chạy nến</span>
                        </button>
                    </div>
                </div>

                <!-- Simulation Graphic Monitor (Right side - 2 columns) -->
                <div class="md:col-span-2 flex flex-col justify-between space-y-4">
                    <!-- Graph Screen Box -->
                    <div class="relative bg-black/50 border border-white/10 rounded-3xl h-60 overflow-hidden flex items-center justify-center p-4">
                        <!-- Grid Background effect -->
                        <div class="absolute inset-0 bg-[linear-gradient(rgba(255,255,255,0.02)_1px,transparent_1px),linear-gradient(90deg,rgba(255,255,255,0.02)_1px,transparent_1px)] bg-[size:20px_20px]"></div>
                        
                        <!-- Floating status indicator -->
                        <div class="absolute top-4 left-4 flex gap-1.5">
                            <span id="crash-badge-status" class="px-2.5 py-0.5 bg-gray-500/20 text-gray-400 text-[10px] font-bold rounded-full uppercase">Đang chờ</span>
                        </div>

                        <!-- Real-time Multiplier value display -->
                        <div class="text-center z-10 space-y-1">
                            <p id="crash-multiplier" class="text-5xl sm:text-6xl font-extrabold tracking-tight font-mono-custom text-gray-300">1.00x</p>
                            <p id="crash-game-info" class="text-[10px] font-semibold text-gray-500 tracking-widest uppercase">Chuẩn bị cược</p>
                        </div>

                        <!-- Custom canvas for live chart drawing -->
                        <canvas id="crash-chart" class="absolute bottom-0 left-0 w-full h-full opacity-40 pointer-events-none"></canvas>
                    </div>

                    <!-- Statistics / Game history -->
                    <div class="bg-white/5 border border-white/10 rounded-2xl p-4 flex items-center justify-between">
                        <div class="text-xs space-y-1">
                            <p class="text-gray-400">Lịch sử sập (Mới nhất):</p>
                            <div id="crash-history" class="flex gap-1.5 overflow-x-auto py-1">
                                <span class="px-2 py-0.5 bg-red-500/10 text-red-400 font-mono-custom rounded text-[10px]">1.23x</span>
                                <span class="px-2 py-0.5 bg-emerald-500/10 text-emerald-400 font-mono-custom rounded text-[10px]">4.50x</span>
                                <span class="px-2 py-0.5 bg-red-500/10 text-red-400 font-mono-custom rounded text-[10px]">1.02x</span>
                                <span class="px-2 py-0.5 bg-emerald-500/10 text-emerald-400 font-mono-custom rounded text-[10px]">2.11x</span>
                                <span class="px-2 py-0.5 bg-emerald-500/10 text-emerald-400 font-mono-custom rounded text-[10px]">15.40x</span>
                            </div>
                        </div>
                        <div class="text-right text-[10px] text-gray-500">
                            <p>Hệ thống cá cược</p>
                            <p class="font-bold text-gray-400">Khởi chạy tức thì</p>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Notification Toast System -->
    <div id="toast-container" class="fixed bottom-5 right-5 z-50 space-y-3 max-w-sm pointer-events-none"></div>

    <!-- ================= JAVASCRIPT SYSTEM LOGIC ================= -->
    <script>
        // --- 1. MOCK DATA BASE ---
        const DEFAULT_PRODUCTS = [
            {
                id: "sc-web-01",
                category: "web",
                tech: "ReactJS + TailwindCSS",
                title: "Mã nguồn Website Landing Page NFT cao cấp thế hệ 3",
                desc: "Một mẫu giao diện ví nghệ thuật kỹ thuật số đỉnh cao, ứng dụng ReactJS, tối ưu SEO, hỗ trợ tích hợp Web3 và hiệu ứng chuyển động mượt mà bằng Framer Motion.",
                price: 299000,
                oldPrice: 590000,
                img: "https://images.unsplash.com/photo-1620641788421-7a1c342ea42e?auto=format&fit=crop&q=80&w=600",
                downloads: 248,
                demoUrl: "#",
                sourceFile: "nft_landing_react.zip"
            },
            {
                id: "sc-web-02",
                category: "web",
                tech: "VueJS + ExpressJS",
                title: "Hệ thống quản lý Admin Dashboard CMS SaaS cao cấp",
                desc: "Hệ thống quản lý đa phân quyền, giao diện bóng bẩy, biểu đồ doanh thu trực quan, API Node.js kết nối sẵn CSDL MongoDB.",
                price: 599000,
                oldPrice: 1200000,
                img: "https://images.unsplash.com/photo-1551288049-bebda4e38f71?auto=format&fit=crop&q=80&w=600",
                downloads: 184,
                demoUrl: "#",
                sourceFile: "vue_dashboard_system.zip"
            },
            {
                id: "sc-app-01",
                category: "app",
                tech: "Flutter + Firebase",
                title: "Source code Ứng dụng E-Commerce Bán Hàng Hoàn Chỉnh",
                desc: "App bán hàng di động hoàn chỉnh cho cả iOS & Android, thanh toán ví điện tử tích hợp, thông báo đẩy đẩy đơn hàng thời gian thực.",
                price: 999000,
                oldPrice: 2000000,
                img: "https://images.unsplash.com/photo-1512941937669-90a1b58e7e9c?auto=format&fit=crop&q=80&w=600",
                downloads: 95,
                demoUrl: "#",
                sourceFile: "flutter_shop_firebase.zip"
            },
            {
                id: "sc-game-01",
                category: "game",
                tech: "Unity 3D + C#",
                title: "Source Game RPG Phiêu Lưu Thế Giới Mở Multiplayer",
                desc: "Dự án game RPG thế giới mở 3D chất lượng cao được thiết kế trên công cụ Unity, đầy đủ hệ thống chiến đấu, trang bị và nhiệm vụ.",
                price: 1499000,
                oldPrice: 3500000,
                img: "https://images.unsplash.com/photo-1538481199705-c710c4e965fc?auto=format&fit=crop&q=80&w=600",
                downloads: 57,
                demoUrl: "#",
                sourceFile: "unity_rpg_multiplayer.zip"
            },
            {
                id: "sc-tool-01",
                category: "tool",
                tech: "Python + OpenAI API",
                title: "Tool AI Tự Động Viết Bài & SEO Copywriting Siêu Hạng",
                desc: "Ứng dụng Python hỗ trợ tự động tìm kiếm từ khóa, tạo dàn bài và viết bài chuẩn SEO dựa trên kết nối API ChatGPT, có UI thân thiện.",
                price: 450000,
                oldPrice: 900000,
                img: "https://images.unsplash.com/photo-1677442136019-21780efad99a?auto=format&fit=crop&q=80&w=600",
                downloads: 310,
                demoUrl: "#",
                sourceFile: "seo_ai_writing_tool.zip"
            },
            {
                id: "sc-web-03",
                category: "web",
                tech: "Next.js + Tailwind",
                title: "Source Code Portfolio Lập Trình Viên Độc Đáo 3D",
                desc: "Showcase năng lực và dự án của cá nhân một cách chuyên nghiệp với thiết kế lơ lửng 3D, tích hợp sẵn Form liên hệ và blog cá nhân.",
                price: 199000,
                oldPrice: 400000,
                img: "https://images.unsplash.com/photo-1507238691740-187a5b1d37b8?auto=format&fit=crop&q=80&w=600",
                downloads: 412,
                demoUrl: "#",
                sourceFile: "nextjs_portfolio_3d.zip"
            }
        ];

        // --- 2. GLOBAL STATE ---
        let PRODUCTS = [];
        let currentUser = null;
        let cart = [];
        let currentActiveCategory = 'all';

        // --- 3. PAGE ROUTER SYSTEM ---
        function showPage(pageId) {
            document.getElementById('page-home').classList.add('hidden');
            document.getElementById('page-detail').classList.add('hidden');
            document.getElementById('page-dashboard').classList.add('hidden');
            document.getElementById('page-admin').classList.add('hidden');

            document.getElementById(`page-${pageId}`).classList.remove('hidden');
            window.scrollTo({ top: 0, behavior: 'smooth' });

            if (pageId === 'dashboard') {
                renderDashboard();
            } else if (pageId === 'admin') {
                renderAdminProductTable();
            }
        }

        // --- 4. INITIALIZATION ---
        window.addEventListener('DOMContentLoaded', () => {
            const savedProducts = localStorage.getItem('codevortex_products');
            if (savedProducts) {
                PRODUCTS = JSON.parse(savedProducts);
            } else {
                PRODUCTS = [...DEFAULT_PRODUCTS];
                localStorage.setItem('codevortex_products', JSON.stringify(PRODUCTS));
            }

            const savedUser = localStorage.getItem('codevortex_user');
            if (savedUser) {
                currentUser = JSON.parse(savedUser);
                updateAuthUI();
            }

            renderProducts();
            updateCartBadge();
            updateStatsCounter();
            initCrashCanvas();
        });

        function updateStatsCounter() {
            const countElement = document.getElementById('stats-total-products');
            if (countElement) {
                countElement.innerText = PRODUCTS.length + "+";
            }
        }

        // --- 5. RENDER PRODUCTS HOME ---
        function renderProducts(filteredProducts = PRODUCTS) {
            const container = document.getElementById('products-grid');
            container.innerHTML = '';

            if (filteredProducts.length === 0) {
                container.innerHTML = `
                    <div class="col-span-full py-16 text-center text-gray-500 space-y-4">
                        <i class="fa-solid fa-hourglass-empty text-5xl"></i>
                        <p class="text-lg">Không tìm thấy sản phẩm mã nguồn nào phù hợp.</p>
                    </div>
                `;
                return;
            }

            filteredProducts.forEach(prod => {
                const isPurchased = currentUser && currentUser.purchasedCode && currentUser.purchasedCode.includes(prod.id);
                
                const card = document.createElement('div');
                card.className = "group glass border border-white/5 rounded-3xl overflow-hidden hover:border-brand-500/50 transition-all duration-300 flex flex-col justify-between";
                card.innerHTML = `
                    <div>
                        <div class="relative overflow-hidden aspect-video bg-indigo-950/20">
                            <img src="${prod.img}" alt="${prod.title}" class="w-full h-full object-cover group-hover:scale-105 transition-transform duration-500">
                            <div class="absolute inset-0 bg-gradient-to-t from-darkbg to-transparent opacity-80"></div>
                            <div class="absolute bottom-4 left-4 px-3 py-1 bg-darkbg/80 backdrop-blur-md rounded-xl border border-white/5 text-xs font-semibold text-brand-400">
                                ${prod.tech}
                            </div>
                        </div>

                        <div class="p-6 space-y-3">
                            <span class="text-xs font-bold text-gray-500 uppercase tracking-widest">${prod.category}</span>
                            <h3 class="text-lg font-bold text-white line-clamp-2 group-hover:text-brand-400 transition-colors cursor-pointer" onclick="openProductDetail('${prod.id}')">
                                ${prod.title}
                            </h3>
                            <p class="text-gray-400 text-xs sm:text-sm line-clamp-2 leading-relaxed">
                                ${prod.desc}
                            </p>
                        </div>
                    </div>

                    <div class="px-6 pb-6 pt-3 border-t border-white/5 space-y-4">
                        <div class="flex items-center justify-between">
                            <div class="flex flex-col">
                                <span class="text-2xl font-extrabold text-brand-400">${prod.price.toLocaleString('vi-VN')}đ</span>
                                <span class="text-xs text-gray-500 line-through">${prod.oldPrice.toLocaleString('vi-VN')}đ</span>
                            </div>
                            <div class="text-right text-xs text-gray-400">
                                <span class="block"><i class="fa-solid fa-cloud-arrow-down mr-1"></i> ${prod.downloads || 120} lượt</span>
                            </div>
                        </div>

                        <div class="grid grid-cols-2 gap-3">
                            <button onclick="openProductDetail('${prod.id}')" class="w-full py-2.5 bg-white/5 hover:bg-white/10 text-white text-xs font-bold rounded-xl transition-all border border-white/5">
                                Xem Chi Tiết
                            </button>
                            ${isPurchased ? `
                                <button onclick="showPage('dashboard')" class="w-full py-2.5 bg-emerald-500/10 text-emerald-400 text-xs font-bold rounded-xl transition-all border border-emerald-500/20">
                                    <i class="fa-solid fa-cloud-arrow-down mr-1"></i> Tải Ngay
                                </button>
                            ` : `
                                <button onclick="addToCart('${prod.id}')" class="w-full py-2.5 bg-gradient-to-r from-brand-600 to-purple-600 hover:from-brand-700 hover:to-purple-700 text-white text-xs font-bold rounded-xl shadow-md transition-all">
                                    <i class="fa-solid fa-cart-plus mr-1"></i> Mua Ngay
                                </button>
                            `}
                        </div>
                    </div>
                `;
                container.appendChild(card);
            });
        }

        // --- 6. CATEGORY FILTERING ---
        function filterCategory(cat) {
            currentActiveCategory = cat;
            
            document.querySelectorAll('.filter-btn').forEach(btn => {
                btn.className = "filter-btn px-4 py-2 text-xs font-semibold rounded-xl bg-white/5 border border-white/5 text-gray-400 hover:text-white hover:bg-white/10 transition-all";
            });

            const activeBtn = document.getElementById(`filter-${cat}`);
            if (activeBtn) {
                activeBtn.className = "filter-btn px-4 py-2 text-xs font-semibold rounded-xl bg-brand-600 text-white transition-all shadow-lg shadow-brand-500/20";
            }

            if (cat === 'all') {
                renderProducts(PRODUCTS);
            } else {
                const filtered = PRODUCTS.filter(p => p.category === cat);
                renderProducts(filtered);
            }
        }

        // --- 7. SEARCH PROCESS ---
        function searchProducts() {
            const query = document.getElementById('global-search').value.toLowerCase().trim();
            executeSearch(query);
        }

        function executeSearch(query) {
            if (!query) {
                filterCategory(currentActiveCategory);
                return;
            }

            const searched = PRODUCTS.filter(p => 
                p.title.toLowerCase().includes(query) || 
                p.desc.toLowerCase().includes(query) || 
                p.tech.toLowerCase().includes(query)
            );
            renderProducts(searched);
        }

        // --- 8. PRODUCT DETAIL ROUTING ---
        function openProductDetail(prodId) {
            const prod = PRODUCTS.find(p => p.id === prodId);
            if (!prod) return;

            document.getElementById('detail-breadcrumb-category').innerText = prod.category;
            document.getElementById('detail-breadcrumb-title').innerText = prod.title;
            document.getElementById('detail-img').src = prod.img;
            document.getElementById('detail-tech').innerText = prod.tech;
            document.getElementById('detail-title').innerText = prod.title;
            document.getElementById('detail-desc').innerText = prod.desc;
            document.getElementById('detail-badge-cat').innerText = prod.category;
            document.getElementById('detail-downloads').innerText = prod.downloads || 120;
            document.getElementById('detail-price').innerText = prod.price.toLocaleString('vi-VN') + "đ";
            document.getElementById('detail-oldprice').innerText = prod.oldPrice.toLocaleString('vi-VN') + "đ";

            const isPurchased = currentUser && currentUser.purchasedCode && currentUser.purchasedCode.includes(prod.id);
            const btnBuyNow = document.getElementById('btn-buy-now');
            const btnAddCart = document.getElementById('btn-add-cart');

            if (isPurchased) {
                btnBuyNow.innerHTML = `<i class="fa-solid fa-cloud-arrow-down"></i> <span>TẢI XUỐNG SOURCE CODE</span>`;
                btnBuyNow.onclick = () => showPage('dashboard');
                btnAddCart.style.display = 'none';
            } else {
                btnBuyNow.innerHTML = `<i class="fa-solid fa-credit-card"></i> <span>MUA NGAY SẢN PHẨM</span>`;
                btnBuyNow.onclick = () => {
                    addToCart(prod.id);
                    toggleCartModal();
                };
                btnAddCart.style.display = 'flex';
                btnAddCart.onclick = () => addToCart(prod.id);
            }

            showPage('detail');
        }

        // --- 9. SHOPPING CART LOGIC ---
        function toggleCartModal() {
            const cartPanel = document.getElementById('cart-modal');
            cartPanel.classList.toggle('hidden');
            if (!cartPanel.classList.contains('hidden')) {
                renderCart();
            }
        }

        function addToCart(prodId) {
            const prod = PRODUCTS.find(p => p.id === prodId);
            if (!prod) return;

            if (currentUser && currentUser.purchasedCode && currentUser.purchasedCode.includes(prodId)) {
                showToast("Sản phẩm này đã được sở hữu, hãy vào kho cá nhân!", "info");
                return;
            }

            if (cart.includes(prodId)) {
                showToast("Sản phẩm đã nằm trong giỏ hàng!", "warning");
                return;
            }

            cart.push(prodId);
            updateCartBadge();
            showToast(`Đã thêm: ${prod.title.substring(0, 20)}...`, "success");
        }

        function removeFromCart(prodId) {
            cart = cart.filter(id => id !== prodId);
            updateCartBadge();
            renderCart();
            showToast("Đã xóa khỏi giỏ hàng", "info");
        }

        function updateCartBadge() {
            const badge = document.getElementById('cart-badge');
            if (cart.length > 0) {
                badge.innerText = cart.length;
                badge.classList.remove('hidden');
            } else {
                badge.classList.add('hidden');
            }
        }

        function renderCart() {
            const container = document.getElementById('cart-items-container');
            const subtotalText = document.getElementById('cart-subtotal');
            const totalText = document.getElementById('cart-total');

            container.innerHTML = '';
            let total = 0;

            if (cart.length === 0) {
                container.innerHTML = `
                    <div class="py-12 text-center text-gray-500 space-y-3">
                        <i class="fa-solid fa-cart-shopping text-4xl text-gray-600"></i>
                        <p class="text-sm">Giỏ hàng của bạn đang trống.</p>
                    </div>
                `;
                subtotalText.innerText = '0đ';
                totalText.innerText = '0đ';
                return;
            }

            cart.forEach(id => {
                const prod = PRODUCTS.find(p => p.id === id);
                if (prod) {
                    total += prod.price;
                    const item = document.createElement('div');
                    item.className = "flex items-center space-x-4 bg-white/5 border border-white/5 p-3 rounded-2xl relative group";
                    item.innerHTML = `
                        <img src="${prod.img}" alt="${prod.title}" class="w-16 h-16 rounded-xl object-cover">
                        <div class="flex-1 min-w-0">
                            <h4 class="text-xs font-bold text-white truncate">${prod.title}</h4>
                            <p class="text-[10px] text-gray-400 capitalize">${prod.category} • ${prod.tech}</p>
                            <span class="text-sm font-extrabold text-brand-400 block mt-1">${prod.price.toLocaleString('vi-VN')}đ</span>
                        </div>
                        <button onclick="removeFromCart('${prod.id}')" class="p-1.5 rounded-lg bg-red-500/10 text-red-400 hover:bg-red-500 hover:text-white transition-all text-xs">
                            <i class="fa-regular fa-trash-can"></i>
                        </button>
                    `;
                    container.appendChild(item);
                }
            });

            subtotalText.innerText = total.toLocaleString('vi-VN') + "đ";
            totalText.innerText = total.toLocaleString('vi-VN') + "đ";
        }

        function checkoutCart() {
            if (!currentUser) {
                toggleCartModal();
                openAuthModal('login');
                showToast("Vui lòng đăng nhập trước khi thanh toán!", "warning");
                return;
            }

            if (cart.length === 0) {
                showToast("Giỏ hàng của bạn đang trống!", "warning");
                return;
            }

            let total = 0;
            cart.forEach(id => {
                const p = PRODUCTS.find(prod => prod.id === id);
                if (p) total += p.price;
            });

            if (currentUser.balance < total) {
                toggleCartModal();
                openDepositModal();
                showToast("Số dư ví không đủ! Hãy nạp ví để mua code.", "warning");
                return;
            }

            currentUser.balance -= total;
            if (!currentUser.purchasedCode) {
                currentUser.purchasedCode = [];
            }

            cart.forEach(id => {
                if (!currentUser.purchasedCode.includes(id)) {
                    currentUser.purchasedCode.push(id);
                }
            });

            cart = [];
            updateCartBadge();
            saveUserToStorage();
            updateAuthUI();
            toggleCartModal();

            showToast("🎉 Thanh toán thành công! Source code đã được chuyển vào Kho của bạn.", "success");
            showPage('dashboard');
        }


        // --- 10. AUTHENTICATION & USERS FLOW ---
        function openAuthModal(mode) {
            document.getElementById('auth-modal').classList.remove('hidden');
            switchAuthTab(mode);
        }

        function closeAuthModal() {
            document.getElementById('auth-modal').classList.add('hidden');
        }

        function switchAuthTab(mode) {
            const tabLogin = document.getElementById('tab-login');
            const tabRegister = document.getElementById('tab-register');
            const formLogin = document.getElementById('form-login');
            const formRegister = document.getElementById('form-register');

            if (mode === 'login') {
                tabLogin.className = "text-xl font-bold pb-2 border-b-2 border-brand-500 text-white transition-all";
                tabRegister.className = "text-xl font-bold pb-2 text-gray-400 hover:text-white transition-all";
                formLogin.classList.remove('hidden');
                formRegister.classList.add('hidden');
            } else {
                tabRegister.className = "text-xl font-bold pb-2 border-b-2 border-brand-500 text-white transition-all";
                tabLogin.className = "text-xl font-bold pb-2 text-gray-400 hover:text-white transition-all";
                formRegister.classList.remove('hidden');
                formLogin.classList.add('hidden');
            }
        }

        function handleLoginSubmit(e) {
            e.preventDefault();
            const usernameInput = document.getElementById('login-username').value.trim();
            const passwordInput = document.getElementById('login-password').value;

            if (passwordInput.length < 6) {
                showToast("Mật khẩu phải chứa tối thiểu từ 6 ký tự!", "error");
                return;
            }

            const isAdmin = (usernameInput.toLowerCase() === 'admin' && passwordInput === 'admin123');

            currentUser = {
                username: usernameInput,
                name: isAdmin ? "Administrator" : "Thành viên Premium",
                email: usernameInput.includes('@') ? usernameInput : `${usernameInput}@codevortex.com`,
                balance: isAdmin ? 999999999 : 500000, 
                purchasedCode: ["sc-web-03"],
                role: isAdmin ? 'admin' : 'member'
            };

            saveUserToStorage();
            updateAuthUI();
            closeAuthModal();
            
            if (isAdmin) {
                showToast("Xin chào Quản Trị Viên! Hệ thống đã kích hoạt phân quyền Admin.", "success");
            } else {
                showToast(`Chào mừng ${currentUser.username} quay trở lại! Bạn được tặng 500K để cá cược và mua sắm.`, "success");
            }

            renderProducts(); 
        }

        function handleRegisterSubmit(e) {
            e.preventDefault();
            const name = document.getElementById('reg-name').value;
            const username = document.getElementById('reg-username').value;
            const email = document.getElementById('reg-email').value;
            const password = document.getElementById('reg-password').value;

            if (password.length < 6) {
                showToast("Mật khẩu phải từ 6 kí tự trở lên!", "error");
                return;
            }

            currentUser = {
                username: username,
                name: name,
                email: email,
                balance: 300000, 
                purchasedCode: [],
                role: 'member'
            };

            saveUserToStorage();
            updateAuthUI();
            closeAuthModal();
            showToast(`Đăng ký tài khoản thành công! Tặng thử nghiệm 300.000đ vào ví của bạn.`, "success");
            renderProducts(); 
        }

        function logout() {
            currentUser = null;
            localStorage.removeItem('codevortex_user');
            document.getElementById('user-dropdown').classList.add('hidden');
            
            document.getElementById('nav-admin-link').classList.add('hidden');
            document.getElementById('nav-admin-link-mobile').classList.add('hidden');

            updateAuthUI();
            showPage('home');
            renderProducts();
            showToast("Bạn đã đăng xuất khỏi hệ thống.", "info");
        }

        function updateAuthUI() {
            const guestSection = document.getElementById('auth-section-guest');
            const userSection = document.getElementById('auth-section-user');
            const dropdownAdminBtn = document.getElementById('dropdown-admin-btn');
            const navAdminLink = document.getElementById('nav-admin-link');
            const navAdminLinkMobile = document.getElementById('nav-admin-link-mobile');

            if (currentUser) {
                guestSection.classList.add('hidden');
                userSection.classList.remove('hidden');
                
                document.getElementById('user-balance').innerText = currentUser.balance.toLocaleString('vi-VN') + "đ";
                document.getElementById('dropdown-username').innerText = currentUser.name;
                document.getElementById('dropdown-email').innerText = currentUser.email;
                document.getElementById('user-avatar').src = `https://api.dicebear.com/7.x/adventurer/svg?seed=${currentUser.username}`;
                
                document.getElementById('dash-balance').innerText = currentUser.balance.toLocaleString('vi-VN') + "đ";
                document.getElementById('dash-username').innerText = currentUser.name;
                document.getElementById('dash-email').innerText = currentUser.email;
                document.getElementById('dash-avatar').src = `https://api.dicebear.com/7.x/adventurer/svg?seed=${currentUser.username}`;

                document.getElementById('deposit-memo').innerText = `CODEVORTEX ${currentUser.username.toUpperCase()}`;

                if (currentUser.role === 'admin') {
                    dropdownAdminBtn.classList.remove('hidden');
                    navAdminLink.classList.remove('hidden');
                    navAdminLinkMobile.classList.remove('hidden');
                } else {
                    dropdownAdminBtn.classList.add('hidden');
                    navAdminLink.classList.add('hidden');
                    navAdminLinkMobile.classList.add('hidden');
                }
            } else {
                guestSection.classList.remove('hidden');
                userSection.classList.add('hidden');
                dropdownAdminBtn.classList.add('hidden');
                navAdminLink.classList.add('hidden');
                navAdminLinkMobile.classList.add('hidden');
            }
        }

        function saveUserToStorage() {
            localStorage.setItem('codevortex_user', JSON.stringify(currentUser));
        }

        function toggleUserDropdown() {
            const d = document.getElementById('user-dropdown');
            d.classList.toggle('hidden');
        }

        window.addEventListener('click', function(e) {
            const userSection = document.getElementById('auth-section-user');
            if (userSection && !userSection.contains(e.target)) {
                document.getElementById('user-dropdown').classList.add('hidden');
            }
        });


        // --- 11. DEPOSIT SIMULATOR ---
        function openDepositModal() {
            if (!currentUser) {
                openAuthModal('login');
                showToast("Bạn cần đăng nhập để nạp tiền!", "warning");
                return;
            }
            document.getElementById('deposit-modal').classList.remove('hidden');
        }

        function closeDepositModal() {
            document.getElementById('deposit-modal').classList.add('hidden');
        }

        function simulateDeposit() {
            const amt = parseInt(document.getElementById('test-deposit-amount').value);
            if (isNaN(amt) || amt < 20000) {
                showToast("Số tiền nạp tối thiểu là 20.000đ", "warning");
                return;
            }

            currentUser.balance += amt;
            saveUserToStorage();
            updateAuthUI();
            closeDepositModal();

            showToast(`💸 Đã giả lập nạp thành công: +${amt.toLocaleString('vi-VN')}đ vào ví tài khoản`, "success");
        }


        // --- 12. USER PURCHASED LIBRARY ---
        function renderDashboard() {
            const container = document.getElementById('purchased-items-grid');
            container.innerHTML = '';

            if (!currentUser || !currentUser.purchasedCode || currentUser.purchasedCode.length === 0) {
                container.innerHTML = `
                    <div class="col-span-full py-16 text-center text-gray-500 space-y-4 bg-white/5 border border-dashed border-white/10 rounded-2xl">
                        <i class="fa-solid fa-folder-open text-5xl"></i>
                        <p class="text-sm">Bạn chưa sở hữu mã nguồn nào. Hãy tiến hành thanh toán sản phẩm muốn học!</p>
                        <button onclick="showPage('home')" class="px-5 py-2.5 bg-brand-600 hover:bg-brand-700 text-xs font-bold text-white rounded-xl transition-all">
                            Dạo Chợ Source Code
                        </button>
                    </div>
                `;
                return;
            }

            currentUser.purchasedCode.forEach(id => {
                const prod = PRODUCTS.find(p => p.id === id);
                if (prod) {
                    const card = document.createElement('div');
                    card.className = "glass border border-white/10 p-6 rounded-2xl flex flex-col md:flex-row items-center justify-between gap-6 hover:border-brand-500/30 transition-all";
                    card.innerHTML = `
                        <div class="flex items-center space-x-4">
                            <img src="${prod.img}" alt="${prod.title}" class="w-16 h-16 rounded-xl object-cover border border-white/10">
                            <div>
                                <h4 class="font-bold text-white text-base line-clamp-1">${prod.title}</h4>
                                <p class="text-xs text-gray-400 mt-1">Định dạng file: <span class="font-mono text-brand-400">${prod.sourceFile}</span></p>
                                <span class="inline-block mt-2 text-[10px] bg-emerald-500/10 border border-emerald-500/20 text-emerald-400 font-semibold px-2 py-0.5 rounded">Hỗ trợ trọn đời</span>
                            </div>
                        </div>
                        <div class="flex flex-col sm:flex-row gap-3 w-full md:w-auto">
                            <button onclick="triggerDownload('${prod.sourceFile}', '${prod.title}')" class="px-5 py-3 bg-brand-600 hover:bg-brand-700 text-white font-bold text-xs rounded-xl shadow-md transition-all flex items-center justify-center space-x-2">
                                <i class="fa-solid fa-circle-down"></i>
                                <span>Tải Bản Đầy Đủ</span>
                            </button>
                        </div>
                    `;
                    container.appendChild(card);
                }
            });
        }

        function triggerDownload(fileName, title) {
            showToast(`Bắt đầu tải file: ${fileName}...`, "info");
            
            setTimeout(() => {
                const dummyContent = `=== CODEVORTEX MOCK SOURCE DOWNLOAD ===\nProject: ${title}\nSource file placeholder.`;
                const blob = new Blob([dummyContent], { type: "text/plain" });
                const link = document.createElement("a");
                link.href = URL.createObjectURL(blob);
                link.download = fileName;
                document.body.appendChild(link);
                link.click();
                document.body.removeChild(link);
                showToast(`Đã tải thành công: ${fileName}!`, "success");
            }, 1000);
        }


        // --- 13. ADMIN ACTIONS & PRODUCT MANAGEMENT ---
        function renderAdminProductTable() {
            const tableBody = document.getElementById('admin-products-table-body');
            const countLabel = document.getElementById('admin-product-count');
            
            tableBody.innerHTML = '';
            countLabel.innerText = `${PRODUCTS.length} Sản phẩm`;

            PRODUCTS.forEach((prod, idx) => {
                const row = document.createElement('tr');
                row.className = "hover:bg-white/5 transition-all text-xs sm:text-sm";
                row.innerHTML = `
                    <td class="py-4 pr-2 font-semibold text-white flex items-center gap-3">
                        <img src="${prod.img}" alt="${prod.title}" class="w-10 h-10 rounded-lg object-cover">
                        <div class="max-w-[200px] sm:max-w-xs truncate">
                            <span class="block text-xs text-gray-400">${prod.tech}</span>
                            <span class="truncate block font-bold">${prod.title}</span>
                        </div>
                    </td>
                    <td class="py-4 px-2 capitalize text-gray-300 font-medium">${prod.category}</td>
                    <td class="py-4 px-2 text-brand-400 font-bold">${prod.price.toLocaleString('vi-VN')}đ</td>
                    <td class="py-4 pl-2 text-right">
                        <button onclick="adminDeleteProduct('${prod.id}')" class="px-2.5 py-1.5 rounded-lg bg-red-500/15 text-red-400 hover:bg-red-500 hover:text-white transition-all">
                            <i class="fa-regular fa-trash-can"></i>
                        </button>
                    </td>
                `;
                tableBody.appendChild(row);
            });
        }

        function handleAdminAddProduct(e) {
            e.preventDefault();

            const title = document.getElementById('admin-title').value;
            const category = document.getElementById('admin-category').value;
            const tech = document.getElementById('admin-tech').value;
            const price = parseInt(document.getElementById('admin-price').value);
            const oldPrice = parseInt(document.getElementById('admin-oldprice').value);
            const sourceFile = document.getElementById('admin-sourcefile').value;
            const img = document.getElementById('admin-image').value;
            const desc = document.getElementById('admin-desc').value;

            const newProduct = {
                id: `sc-custom-${Date.now()}`,
                category,
                tech,
                title,
                desc,
                price,
                oldPrice,
                img,
                downloads: 0,
                sourceFile
            };

            PRODUCTS.unshift(newProduct);
            localStorage.setItem('codevortex_products', JSON.stringify(PRODUCTS));

            renderProducts();
            renderAdminProductTable();
            updateStatsCounter();

            document.getElementById('admin-add-product-form').reset();
            showToast("Đã thêm thành công và xuất bản mã nguồn mới lên hệ thống!", "success");
        }

        function adminDeleteProduct(prodId) {
            PRODUCTS = PRODUCTS.filter(p => p.id !== prodId);
            localStorage.setItem('codevortex_products', JSON.stringify(PRODUCTS));

            renderProducts();
            renderAdminProductTable();
            updateStatsCounter();
            showToast("Đã xóa mã nguồn ra khỏi kho hệ thống thành công.", "info");
        }


        // --- 14. CRASH BETTING MINIGAME LOGIC (Highly Engaging Simulator) ---
        let crashState = "waiting"; // waiting, running, crashed, cashed_out
        let crashCurrentBet = 0;
        let crashMultiplier = 1.00;
        let crashPoint = 1.00;
        let crashInterval = null;
        let crashCanvas, crashCtx;
        let crashChartHistoryPoints = [];

        function openBetModal() {
            document.getElementById('bet-modal').classList.remove('hidden');
            resizeCrashCanvas();
            drawStaticChartGrid();
        }

        function closeBetModal() {
            if (crashState === "running") {
                showToast("Bạn đang trong ván cược, hãy chờ đợi kết quả hoặc rút tiền!", "warning");
                return;
            }
            document.getElementById('bet-modal').classList.add('hidden');
        }

        function initCrashCanvas() {
            crashCanvas = document.getElementById('crash-chart');
            crashCtx = crashCanvas.getContext('2d');
            window.addEventListener('resize', resizeCrashCanvas);
        }

        function resizeCrashCanvas() {
            if (!crashCanvas) return;
            crashCanvas.width = crashCanvas.parentElement.clientWidth;
            crashCanvas.height = crashCanvas.parentElement.clientHeight;
            drawStaticChartGrid();
        }

        function drawStaticChartGrid() {
            if (!crashCtx) return;
            const w = crashCanvas.width;
            const h = crashCanvas.height;
            crashCtx.clearRect(0, 0, w, h);
            
            // Draw axis line base
            crashCtx.strokeStyle = "rgba(255, 255, 255, 0.1)";
            crashCtx.lineWidth = 1;
            crashCtx.beginPath();
            crashCtx.moveTo(0, h - 30);
            crashCtx.lineTo(w, h - 30);
            crashCtx.stroke();
        }

        function setCrashBetShortcut(mode) {
            const betInput = document.getElementById('crash-bet-amount');
            let currentVal = parseInt(betInput.value) || 10000;
            
            if (!currentUser) {
                showToast("Vui lòng đăng nhập trước!", "warning");
                return;
            }

            if (mode === 'half') {
                betInput.value = Math.max(1000, Math.floor(currentVal / 2));
            } else if (mode === 'double') {
                betInput.value = Math.min(currentUser.balance, currentVal * 2);
            } else if (mode === 'all') {
                betInput.value = currentUser.balance;
            }
        }

        function handleCrashButtonClick() {
            if (!currentUser) {
                closeBetModal();
                openAuthModal('login');
                showToast("Bạn cần đăng nhập để tham gia cá cược!", "warning");
                return;
            }

            if (crashState === "waiting") {
                startCrashGame();
            } else if (crashState === "running") {
                cashOutCrashGame();
            }
        }

        function startCrashGame() {
            const betInput = document.getElementById('crash-bet-amount');
            const betAmount = parseInt(betInput.value);

            if (isNaN(betAmount) || betAmount < 1000) {
                showToast("Tiền cược tối thiểu là 1.000 VNĐ", "warning");
                return;
            }

            if (currentUser.balance < betAmount) {
                showToast("Số dư tài khoản không đủ để đặt cược!", "error");
                return;
            }

            // Deduct balance and commit bet
            currentUser.balance -= betAmount;
            crashCurrentBet = betAmount;
            updateAuthUI();
            saveUserToStorage();

            // Set state to running
            crashState = "running";
            crashMultiplier = 1.00;
            
            // Random crash algorithm
            // House edge model: 10% instant crash at 1.00, else logarithmically distributed crash value
            const randomChance = Math.random();
            if (randomChance < 0.08) {
                crashPoint = 1.00; // Instacrash
            } else {
                // Generates high spikes sometimes, mostly sập around 1.1x to 4x
                crashPoint = Math.max(1.01, parseFloat((1.01 + Math.pow(Math.random(), -2) * 0.01).toFixed(2)));
                if (crashPoint > 100) crashPoint = parseFloat((30 + Math.random() * 50).toFixed(2)); // Cap max
            }

            // Update Bet UI Elements
            const mainBtn = document.getElementById('crash-main-btn');
            const primaryTxt = document.getElementById('crash-btn-primary-text');
            const secondaryTxt = document.getElementById('crash-btn-secondary-text');
            const statusBadge = document.getElementById('crash-badge-status');
            const multDisplay = document.getElementById('crash-multiplier');
            const gameInfo = document.getElementById('crash-game-info');

            mainBtn.className = "w-full py-4 bg-amber-500 hover:bg-amber-600 text-white font-bold rounded-2xl shadow-lg shadow-amber-500/20 transition-all text-sm flex flex-col items-center justify-center";
            primaryTxt.innerText = "CHỐT LỜI (CASH OUT)";
            secondaryTxt.innerText = `Rút: ${(crashCurrentBet).toLocaleString('vi-VN')}đ`;
            statusBadge.innerText = "Đang chạy";
            statusBadge.className = "px-2.5 py-0.5 bg-emerald-500/20 text-emerald-400 text-[10px] font-bold rounded-full uppercase animate-pulse";
            gameInfo.innerText = "Nến đang tăng...";
            multDisplay.className = "text-5xl sm:text-6xl font-extrabold tracking-tight font-mono-custom text-emerald-400";

            crashChartHistoryPoints = [{x: 0, y: 1.00}];

            // Real-time ticking cycle loop
            let elapsed = 0;
            crashInterval = setInterval(() => {
                elapsed += 60;
                
                // Exponential acceleration climb formula
                crashMultiplier = parseFloat((1.00 + Math.pow(elapsed / 2500, 2)).toFixed(2));
                
                // Redraw multiplier text
                multDisplay.innerText = `${crashMultiplier.toFixed(2)}x`;
                secondaryTxt.innerText = `Rút: ${Math.floor(crashCurrentBet * crashMultiplier).toLocaleString('vi-VN')}đ`;

                // Append and render live nến curves
                crashChartHistoryPoints.push({
                    x: elapsed,
                    y: crashMultiplier
                });
                drawCrashLiveChart();

                // Check crash point limit reached
                if (crashMultiplier >= crashPoint) {
                    triggerCrash();
                }
            }, 60);
        }

        function drawCrashLiveChart() {
            if (!crashCtx || crashChartHistoryPoints.length === 0) return;
            const w = crashCanvas.width;
            const h = crashCanvas.height;
            crashCtx.clearRect(0, 0, w, h);
            
            drawStaticChartGrid();

            crashCtx.strokeStyle = "rgba(16, 185, 129, 0.7)";
            crashCtx.lineWidth = 4;
            crashCtx.beginPath();

            const maxTime = Math.max(2000, crashChartHistoryPoints[crashChartHistoryPoints.length - 1].x);
            const maxMult = Math.max(2.0, crashChartHistoryPoints[crashChartHistoryPoints.length - 1].y);

            crashChartHistoryPoints.forEach((pt, idx) => {
                const screenX = (pt.x / maxTime) * (w - 40) + 10;
                const screenY = h - 30 - ((pt.y - 1) / (maxMult - 0.8)) * (h - 80);
                
                if (idx === 0) {
                    crashCtx.moveTo(screenX, screenY);
                } else {
                    crashCtx.lineTo(screenX, screenY);
                }
            });

            crashCtx.stroke();

            // Gradient filling under line
            crashCtx.fillStyle = "rgba(16, 185, 129, 0.08)";
            const finalX = (crashChartHistoryPoints[crashChartHistoryPoints.length - 1].x / maxTime) * (w - 40) + 10;
            crashCtx.lineTo(finalX, h - 30);
            crashCtx.lineTo(10, h - 30);
            crashCtx.closePath();
            crashCtx.fill();
        }

        function triggerCrash() {
            clearInterval(crashInterval);
            crashState = "crashed";

            // Update screen state
            const mainBtn = document.getElementById('crash-main-btn');
            const primaryTxt = document.getElementById('crash-btn-primary-text');
            const secondaryTxt = document.getElementById('crash-btn-secondary-text');
            const statusBadge = document.getElementById('crash-badge-status');
            const multDisplay = document.getElementById('crash-multiplier');
            const gameInfo = document.getElementById('crash-game-info');

            mainBtn.className = "w-full py-4 bg-red-500/25 text-red-400 border border-red-500/30 font-bold rounded-2xl transition-all text-sm flex flex-col items-center justify-center cursor-not-allowed";
            primaryTxt.innerText = "ĐÃ SẬP (CRASHED)";
            secondaryTxt.innerText = "Mất tiền cược";
            statusBadge.innerText = "Sập";
            statusBadge.className = "px-2.5 py-0.5 bg-red-500/20 text-red-400 text-[10px] font-bold rounded-full uppercase";
            gameInfo.innerText = "Cá cược thất bại!";
            multDisplay.className = "text-5xl sm:text-6xl font-extrabold tracking-tight font-mono-custom text-red-500 animate-bounce";
            multDisplay.innerText = `${crashMultiplier.toFixed(2)}x`;

            // Draw crashed line style
            if (crashCtx) {
                crashCtx.strokeStyle = "rgba(239, 68, 68, 0.8)";
                crashCtx.lineWidth = 4;
                crashCtx.stroke();
            }

            appendCrashHistory(crashMultiplier);
            showToast(`💥 Sập nến tại ${crashMultiplier.toFixed(2)}x! Bạn mất: -${crashCurrentBet.toLocaleString('vi-VN')}đ.`, "error");

            // Reset back to normal after delay
            setTimeout(() => {
                resetCrashSystemToWaiting();
            }, 3000);
        }

        function cashOutCrashGame() {
            clearInterval(crashInterval);
            crashState = "cashed_out";

            const winningAmount = Math.floor(crashCurrentBet * crashMultiplier);
            currentUser.balance += winningAmount;
            
            // UI Update
            updateAuthUI();
            saveUserToStorage();

            const mainBtn = document.getElementById('crash-main-btn');
            const primaryTxt = document.getElementById('crash-btn-primary-text');
            const secondaryTxt = document.getElementById('crash-btn-secondary-text');
            const statusBadge = document.getElementById('crash-badge-status');
            const gameInfo = document.getElementById('crash-game-info');

            mainBtn.className = "w-full py-4 bg-emerald-500/20 text-emerald-400 border border-emerald-500/30 font-bold rounded-2xl transition-all text-sm flex flex-col items-center justify-center cursor-not-allowed";
            primaryTxt.innerText = "THẮNG LỚN (SUCCESS)";
            secondaryTxt.innerText = `Cộng ví: +${winningAmount.toLocaleString('vi-VN')}đ`;
            statusBadge.innerText = "Đã chốt lời";
            statusBadge.className = "px-2.5 py-0.5 bg-emerald-500/20 text-emerald-400 text-[10px] font-bold rounded-full uppercase";
            gameInfo.innerText = "Chốt tiền thành công!";

            showToast(`🎉 Tuyệt đỉnh! Chốt lời thành công tại ${crashMultiplier.toFixed(2)}x. Nhận về: +${winningAmount.toLocaleString('vi-VN')}đ!`, "success");

            // Continue showing multiplier climb without crash influence till real crash point
            let futureElapsed = crashChartHistoryPoints[crashChartHistoryPoints.length - 1].x;
            const shadowInterval = setInterval(() => {
                futureElapsed += 60;
                const shadowMult = parseFloat((1.00 + Math.pow(futureElapsed / 2500, 2)).toFixed(2));
                
                document.getElementById('crash-multiplier').innerText = `${shadowMult.toFixed(2)}x`;
                crashChartHistoryPoints.push({ x: futureElapsed, y: shadowMult });
                drawCrashLiveChart();

                if (shadowMult >= crashPoint) {
                    clearInterval(shadowInterval);
                    appendCrashHistory(shadowMult);
                    
                    document.getElementById('crash-multiplier').className = "text-5xl sm:text-6xl font-extrabold tracking-tight font-mono-custom text-red-500";
                    document.getElementById('crash-multiplier').innerText = `${shadowMult.toFixed(2)}x`;
                    document.getElementById('crash-game-info').innerText = "Cơn lốc đã sập!";

                    setTimeout(() => {
                        resetCrashSystemToWaiting();
                    }, 2500);
                }
            }, 60);
        }

        function resetCrashSystemToWaiting() {
            crashState = "waiting";
            crashCurrentBet = 0;

            const mainBtn = document.getElementById('crash-main-btn');
            const primaryTxt = document.getElementById('crash-btn-primary-text');
            const secondaryTxt = document.getElementById('crash-btn-secondary-text');
            const statusBadge = document.getElementById('crash-badge-status');
            const multDisplay = document.getElementById('crash-multiplier');
            const gameInfo = document.getElementById('crash-game-info');

            mainBtn.className = "w-full py-4 bg-emerald-500 hover:bg-emerald-600 text-white font-bold rounded-2xl shadow-lg shadow-emerald-500/20 transition-all text-sm flex flex-col items-center justify-center";
            primaryTxt.innerText = "BẮT ĐẦU CƯỢC";
            secondaryTxt.innerText = "Đặt tiền và khởi chạy nến";
            statusBadge.innerText = "Đang chờ";
            statusBadge.className = "px-2.5 py-0.5 bg-gray-500/20 text-gray-400 text-[10px] font-bold rounded-full uppercase";
            gameInfo.innerText = "Chuẩn bị cược";
            multDisplay.className = "text-5xl sm:text-6xl font-extrabold tracking-tight font-mono-custom text-gray-300";
            multDisplay.innerText = "1.00x";

            drawStaticChartGrid();
        }

        function appendCrashHistory(mult) {
            const historyBox = document.getElementById('crash-history');
            const colorClass = mult >= 2.0 ? "bg-emerald-500/10 text-emerald-400" : "bg-red-500/10 text-red-400";
            const badge = `<span class="px-2 py-0.5 ${colorClass} font-mono-custom rounded text-[10px] shrink-0">${mult.toFixed(2)}x</span>`;
            historyBox.insertAdjacentHTML('afterbegin', badge);

            // Cap child nodes limit to 6 elements
            if (historyBox.children.length > 6) {
                historyBox.lastElementChild.remove();
            }
        }


        // --- 15. SYSTEM TOAST UTILITY ---
        function showToast(message, type = "info") {
            const container = document.getElementById('toast-container');
            const toast = document.createElement('div');
            toast.className = "transform translate-y-5 opacity-0 transition-all duration-300 pointer-events-auto flex items-center space-x-3 glass border border-white/10 p-4 rounded-2xl shadow-xl w-80";
            
            let icon = '<i class="fa-solid fa-circle-info text-blue-400"></i>';
            if (type === "success") icon = '<i class="fa-solid fa-circle-check text-emerald-400"></i>';
            if (type === "warning") icon = '<i class="fa-solid fa-circle-exclamation text-yellow-400"></i>';
            if (type === "error") icon = '<i class="fa-solid fa-triangle-exclamation text-red-400"></i>';

            toast.innerHTML = `
                <div class="text-lg">${icon}</div>
                <div class="flex-1 text-xs sm:text-sm font-medium text-gray-200">${message}</div>
            `;

            container.appendChild(toast);

            setTimeout(() => {
                toast.classList.remove('translate-y-5', 'opacity-0');
            }, 50);

            setTimeout(() => {
                toast.classList.add('opacity-0', 'scale-95');
                setTimeout(() => {
                    toast.remove();
                }, 300);
            }, 4000);
        }

        // --- 16. UTILITY CLIPBOARD COPY ---
        function copyText(text) {
            const dummy = document.createElement("textarea");
            document.body.appendChild(dummy);
            dummy.value = text;
            dummy.select();
            document.execCommand("copy");
            document.body.removeChild(dummy);
            showToast(`Đã sao chép: ${text}`, "success");
        }
    </script>
</body>
</html>

```
