<?php require 'config.php';
$ip = $_SERVER['REMOTE_ADDR'];
$endpoint = 'page.profile'; // ganti nama sesuai file
if (!checkRateLimitApi($pdo, $ip, $endpoint, 120, 60)) {
    http_response_code(429);
    die('<div style="text-align:center;padding:50px;"><h1>429 Too Many Requests</h1><p>Terlalu banyak permintaan. Silakan coba lagi setelah 1 menit.</p></div>');
} ?>
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=yes">
    <title>Profil Saya - FIFA World Cup 2026</title>
    <meta name="csrf-token" content="<?php echo $_SESSION['csrf_token']; ?>">
    <script src="https://cdn.tailwindcss.com"></script>
    <link
        href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800;900&family=Space+Grotesk:wght@300;400;500;600;700&display=swap"
        rel="stylesheet">
    <style type="text/tailwindcss">
        /* ========== CSS SAMA PERSEPERTI INDEX.PHP (LENGKAP) ========== */
        :root {
            --wc-green: #00df82;
            --wc-blue: #0052ff;
            --wc-red: #ff2d55;
            --wc-gold: #ffcc00;
            --wc-surface: #030610;
        }
        .bg-worldcup-green { background-color: var(--wc-green); }
        .bg-worldcup-blue { background-color: var(--wc-blue); }
        .bg-worldcup-red { background-color: var(--wc-red); }
        .text-worldcup-green { color: var(--wc-green); }
        .text-worldcup-blue { color: var(--wc-blue); }
        .text-worldcup-red { color: var(--wc-red); }
        .bg-worldcup-green\/5 { background-color: rgba(0,223,130,0.05); }
        .bg-worldcup-blue\/5 { background-color: rgba(0,82,255,0.05); }
        body {
            @apply bg-[#030610] text-slate-300 font-sans selection:bg-amber-500/30 selection:text-white overflow-x-hidden;
        }
        .bg-mesh {
            background: radial-gradient(circle at 0% 0%, rgba(0,223,130,0.05) 0%, transparent 50%),
                        radial-gradient(circle at 100% 0%, rgba(255,45,85,0.05) 0%, transparent 50%),
                        radial-gradient(circle at 100% 100%, rgba(0,82,255,0.05) 0%, transparent 50%),
                        radial-gradient(circle at 50% 50%, rgba(255,204,0,0.03) 0%, transparent 60%);
        }
        .bg-mesh::after {
            content: '';
            @apply absolute inset-0 opacity-[0.03] pointer-events-none;
            background-image: linear-gradient(rgba(255,255,255,0.1) 1px, transparent 1px),
                              linear-gradient(90deg, rgba(255,255,255,0.1) 1px, transparent 1px);
            background-size: 40px 40px;
        }
        .glass-card {
            @apply bg-white/[0.02] backdrop-blur-2xl border border-white/[0.05] shadow-[0_8px_32px_rgba(0,0,0,0.5)];
            transition: all 0.5s cubic-bezier(0.23,1,0.32,1);
        }
        .glass-card:hover {
            @apply bg-white/[0.04] border-white/10 shadow-[0_20px_50px_rgba(0,0,0,0.6)] -translate-y-1;
        }
        .nav-link {
            @apply relative py-2 px-4 transition-all duration-300 text-slate-500 font-bold uppercase tracking-widest text-[9px];
        }
        .nav-link::after {
            content: '';
            @apply absolute bottom-0 left-1/2 -translate-x-1/2 w-0 h-[2px] bg-amber-500 transition-all duration-300 rounded-full;
        }
        .nav-link:hover { @apply text-white/80 scale-105; }
        .nav-link.active { @apply text-amber-500; }
        .nav-link.active::after { @apply w-1/2 bg-amber-500; }
        @keyframes glow {
            0%,100% { opacity:0.2; transform:scale(1); }
            50% { opacity:0.4; transform:scale(1.1); }
        }
        ::-webkit-scrollbar { width:4px; }
        ::-webkit-scrollbar-track { background:transparent; }
        ::-webkit-scrollbar-thumb { @apply bg-white/10 rounded-full hover:bg-white/20; }
        .mobile-menu-overlay { transition: opacity 0.3s ease, visibility 0.3s ease; }
        .toast {
            @apply pointer-events-auto bg-black/80 backdrop-blur-xl border border-amber-500/30 rounded-2xl px-6 py-4 shadow-2xl transform transition-all duration-500;
            animation: slideUpFade 0.5s cubic-bezier(0.23,1,0.32,1) forwards;
        }
        @keyframes slideUpFade {
            from { opacity: 0; transform: translateY(30px); }
            to { opacity: 1; transform: translateY(0); }
        }
        .toast-exit {
            opacity: 0;
            transform: translateY(20px);
            transition: opacity 0.3s, transform 0.3s;
        }
        .avatar-clickable { cursor: pointer; }

        /* ===== DROPDOWN MENU ===== */
        .user-dropdown {
            position: relative;
            display: inline-block;
        }
        .dropdown-content {
            display: none;
            position: absolute;
            right: 0;
            top: 100%;
            background-color: #0f172a;
            min-width: 180px;
            box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.6);
            border-radius: 1rem;
            border: 1px solid rgba(255,255,255,0.1);
            z-index: 100;
            margin-top: 8px;
            backdrop-filter: blur(8px);
        }
        .dropdown-content a {
            color: white;
            padding: 12px 16px;
            text-decoration: none;
            display: block;
            font-size: 12px;
            font-weight: 600;
            transition: background 0.2s;
        }
        .dropdown-content a:hover {
            background-color: rgba(245,158,11,0.2);
            color: #f59e0b;
        }
        .user-dropdown:hover .dropdown-content {
            display: block;
        }
        /* Info user di samping avatar */
        .user-info-side {
            display: flex;
            flex-direction: column;
            align-items: flex-end;
            margin-right: 12px;
        }
        .user-info-side .username {
            font-size: 10px;
            font-weight: 800;
            color: white;
            text-transform: uppercase;
            letter-spacing: 0.05em;
        }
        .user-info-side .stats {
            display: flex;
            gap: 12px;
            font-size: 8px;
            font-weight: 700;
            margin-top: 2px;
        }
        .user-info-side .stats span {
            display: flex;
            align-items: center;
            gap: 4px;
        }

        /* ===== STYLE TAMBAHAN UNTUK BRACKET DLL (TIDAK DIGUNAKAN DI PROFIL, TETAP DISERTAKAN AGAR KONSISTEN) ===== */
        .bracket-container {
            overflow-x: auto;
            padding: 20px 0;
            position: relative;
        }
        .bracket {
            display: flex;
            flex-direction: row;
            justify-content: center;
            gap: 30px;
            min-width: max-content;
        }
        .bracket-column {
            display: flex;
            flex-direction: column;
            justify-content: space-around;
            position: relative;
        }
        .bracket-match {
            background: rgba(255,255,255,0.03);
            border: 1px solid rgba(255,255,255,0.1);
            border-radius: 12px;
            padding: 10px;
            margin: 12px 0;
            width: 200px;
            position: relative;
            transition: all 0.2s;
        }
        .bracket-column:has(.bracket-match:last-child) .bracket-match {
            width: 230px;
            background: rgba(255,215,0,0.08);
            border: 1px solid rgba(255,215,0,0.4);
            box-shadow: 0 0 15px rgba(255,215,0,0.2);
        }
        .bracket-match .teams {
            display: flex;
            justify-content: space-between;
            gap: 6px;
            font-size: 11px;
        }
        .bracket-match .team {
            flex: 1;
            text-align: center;
            padding: 4px;
            background: rgba(0,0,0,0.5);
            border-radius: 8px;
            white-space: nowrap;
            overflow-x: auto;
        }
        .bracket-match .vs {
            font-size: 9px;
            color: #f59e0b;
            align-self: center;
        }
        .bracket-match .match-date {
            font-size: 8px;
            text-align: center;
            margin-top: 6px;
            color: #94a3b8;
        }
        .bracket-match .score {
            font-size: 11px;
            text-align: center;
            margin-top: 4px;
            color: #fbbf24;
        }
        .bracket-column:not(:last-child)::after {
            content: '';
            position: absolute;
            right: -15px;
            top: 50%;
            width: 15px;
            height: 2px;
            background: rgba(255,255,255,0.3);
            transform: translateY(-50%);
        }
        .bracket-match:not(:last-child)::before {
            content: '';
            position: absolute;
            bottom: -12px;
            left: 50%;
            width: 2px;
            height: 12px;
            background: rgba(255,255,255,0.3);
        }
        @media (max-width: 768px) {
            .bracket { gap: 15px; }
            .bracket-match { width: 160px; padding: 6px; }
            .bracket-match .teams { font-size: 9px; }
            .bracket-column:has(.bracket-match:last-child) .bracket-match { width: 180px; }
        }

        /* ===== CAROUSEL (TIDAK DIPAKAI, TETAP DISERTAKAN) ===== */
        .carousel-container {
            position: relative;
            width: 100%;
            overflow: hidden;
            border-radius: 0 0 2rem 2rem;
            margin-top: -1rem;
            z-index: 5;
        }
        .carousel-slides {
            display: flex;
            transition: transform 0.5s ease-in-out;
        }
        .carousel-slide {
            flex: 0 0 100%;
            position: relative;
            background-size: cover;
            background-position: center;
            cursor: pointer;
            filter: brightness(1.05);
        }
        .carousel-slide {
            height: 520px;
        }
        @media (max-width: 1024px) {
            .carousel-slide { height: 420px; }
        }
        @media (max-width: 768px) {
            .carousel-slide { 
                height: auto;
                aspect-ratio: 16 / 9;
            }
            .carousel-btn { width: 32px; height: 32px; font-size: 1rem; }
            .carousel-caption h2 { font-size: 1.25rem; }
            .carousel-caption p { font-size: 0.7rem; }
        }
        .carousel-overlay {
            position: absolute;
            inset: 0;
            background: linear-gradient(135deg, rgba(0,0,0,0.3) 0%, rgba(0,0,0,0.1) 100%);
            display: flex;
            align-items: center;
            justify-content: center;
            text-align: center;
        }
        .carousel-caption {
            color: white;
            text-shadow: 0 2px 10px rgba(0,0,0,0.5);
            padding: 1rem;
        }
        .carousel-caption h2 {
            font-size: 2rem;
            font-weight: 800;
            letter-spacing: -0.02em;
            margin-bottom: 0.5rem;
        }
        .carousel-caption p {
            font-size: 0.875rem;
            opacity: 0.9;
        }
        .carousel-btn {
            position: absolute;
            top: 50%;
            transform: translateY(-50%);
            background: rgba(0,0,0,0.5);
            backdrop-filter: blur(4px);
            color: white;
            border: none;
            width: 40px;
            height: 40px;
            border-radius: 40px;
            cursor: pointer;
            z-index: 20;
            transition: all 0.3s;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 1.5rem;
        }
        .carousel-btn:hover {
            background: #f59e0b;
            color: black;
        }
        .btn-prev { left: 20px; }
        .btn-next { right: 20px; }
        .carousel-dots {
            position: absolute;
            bottom: 20px;
            left: 0;
            right: 0;
            display: flex;
            justify-content: center;
            gap: 10px;
            z-index: 20;
        }
        .dot {
            width: 10px;
            height: 10px;
            background: rgba(255,255,255,0.5);
            border-radius: 10px;
            cursor: pointer;
            transition: all 0.3s;
        }
        .dot.active {
            width: 24px;
            background: #f59e0b;
        }

        /* ===== MODAL & BADGE ===== */
        #auth-modal {
            z-index: 9999 !important;
        }
        #auth-modal.flex {
            display: flex !important;
        }
        body.modal-open {
            overflow: hidden !important;
        }
        #claim-daily-btn.not-claimed {
            position: relative;
            overflow: visible;
        }
        #claim-daily-btn.not-claimed::before {
            content: "!";
            position: absolute;
            top: -16px;
            right: -16px;
            background: #ef4444;
            color: white;
            font-weight: 900;
            font-size: 20px;
            width: 30px;
            height: 30px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            animation: blinkWarning 1s step-end infinite;
            box-shadow: 0 0 8px rgba(239,68,68,0.8);
            z-index: 10;
            border: 4px solid white;
        }
        @keyframes blinkWarning {
            0%, 100% { opacity: 1; transform: scale(1); }
            50% { opacity: 0.4; transform: scale(0.85); }
        }
        #avatar-btn {
            position: relative;
        }
        .avatar-indicator {
            position: absolute;
            top: 4px;
            right: 4px;
            width: 12px;
            height: 12px;
            background-color: #ef4444;
            border-radius: 50%;
            border: 2px solid #030610;
            animation: pulseRed 1s infinite;
            z-index: 15;
        }
        @keyframes pulseRed {
            0% { transform: scale(1); opacity: 1; }
            50% { transform: scale(1.2); opacity: 0.7; }
            100% { transform: scale(1); opacity: 1; }
        }
        .menu-indicator {
            position: absolute;
            top: -4px;
            right: -4px;
            width: 12px;
            height: 12px;
            background-color: #00df82;
            border-radius: 50%;
            border: 2px solid #030610;
            animation: pulseGreen 1s infinite;
            z-index: 15;
        }
        .claim-badge {
            background: linear-gradient(135deg, #00df82, #00b368);
            border-radius: 40px;
            padding: 2px 8px;
            display: flex;
            align-items: center;
            justify-content: center;
            box-shadow: 0 0 12px rgba(0, 223, 130, 0.6);
            animation: pulseGreen 1.2s infinite ease-in-out;
            transition: all 0.2s;
            white-space: nowrap;
        }
        .claim-badge:hover {
            transform: scale(1.05);
            background: linear-gradient(135deg, #00f090, #00c570);
        }
        .claim-badge-text {
            font-size: 6px;
            font-weight: 800;
            color: #030610;
            letter-spacing: 0.5px;
            text-transform: uppercase;
        }
        @keyframes pulseGreen {
            0% {
                transform: scale(0.95);
                box-shadow: 0 0 0 0 rgba(0, 223, 130, 0.7);
            }
            70% {
                transform: scale(1);
                box-shadow: 0 0 0 10px rgba(0, 223, 130, 0);
            }
            100% {
                transform: scale(0.95);
                box-shadow: 0 0 0 0 rgba(0, 223, 130, 0);
            }
        }
        /* Animasi untuk tombol promosi */
        @keyframes promoPulse {
            0% { transform: scale(1); box-shadow: 0 0 0 0 rgba(245,158,11,0.7); }
            70% { transform: scale(1.03); box-shadow: 0 0 0 10px rgba(245,158,11,0); }
            100% { transform: scale(1); box-shadow: 0 0 0 0 rgba(245,158,11,0); }
        }
        .promo-animate {
            animation: promoPulse 1.5s infinite ease-in-out;
        }
        /* Tambahan untuk detail prediksi */
        .pred-detail-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(100px,1fr));
            gap: 0.5rem;
            margin-top: 0.5rem;
            font-size: 0.7rem;
            color: #94a3b8;
        }
        .pred-detail-item {
            background: rgba(255,255,255,0.03);
            padding: 0.2rem 0.4rem;
            border-radius: 0.5rem;
            text-align: center;
        }
    </style>
</head>

<body class="min-h-screen relative">
    <!-- Background (sama seperti index) -->
    <div class="fixed inset-0 bg-mesh pointer-events-none opacity-50"></div>
    <div
        class="fixed top-[-10%] left-[-10%] w-[40%] h-[40%] bg-worldcup-green/5 rounded-full blur-[120px] animate-glow pointer-events-none">
    </div>
    <div class="fixed bottom-[-10%] right-[-10%] w-[50%] h-[50%] bg-worldcup-blue/5 rounded-full blur-[150px] animate-glow pointer-events-none"
        style="animation-delay: -4s"></div>
    <div
        class="fixed top-1/4 left-10 w-1 h-24 bg-gradient-to-b from-transparent via-amber-500/20 to-transparent blur-sm animate-pulse pointer-events-none">
    </div>
    <div class="fixed bottom-1/4 right-10 w-1 h-32 bg-gradient-to-b from-transparent via-worldcup-green/20 to-transparent blur-sm animate-pulse pointer-events-none"
        style="animation-delay: 2s"></div>
    <div
        class="fixed top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 w-[80vw] h-[80vh] border border-white/[0.02] rounded-full pointer-events-none">
    </div>
    <div
        class="fixed top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 w-[60vw] h-[60vh] border border-white/[0.015] rounded-full pointer-events-none">
    </div>

    <!-- Navbar (sama persis dengan index.php) -->
    <nav class="sticky top-0 z-50 px-4 pt-4">
        <div
            class="max-w-7xl mx-auto glass-card rounded-[40px] px-5 sm:px-10 h-24 flex items-center justify-between border-white/[0.03]">
            <div class="flex items-center gap-4 cursor-pointer group" onclick="window.location.href='index.php'">
                <div class="relative flex items-center gap-2">
                    <img src="fifa-world-cup-2026-logo-white.png" alt="FIFA World Cup 2026"
                        class="h-12 w-auto object-contain drop-shadow-lg">
                    <div class="flex flex-col">
                        <span class="text-xs font-black text-white tracking-[0.3em] uppercase leading-none">Piala
                            Dunia</span>
                        <span
                            class="text-lg font-display font-black text-amber-500 tracking-tighter leading-none">2026</span>
                    </div>
                </div>
            </div>
            <div class="hidden lg:flex items-center gap-2 bg-black/20 p-2 rounded-[24px] border border-white/5">
                <button onclick="window.location.href='promosi.php'"
                    class="promo-animate bg-amber-500 text-black px-4 py-2 rounded-full text-[9px] font-black uppercase tracking-widest hover:bg-amber-400 transition-all shadow-md">🎉
                    PROMOSI</button>
                <button onclick="window.location.href='index.php'" id="nav-standings" class="nav-link">Klasemen</button>
                <button onclick="window.location.href='index.php?view=schedule'" id="nav-schedule"
                    class="nav-link">Jadwal</button>
                <button onclick="window.location.href='predict.php'" id="nav-predict" class="nav-link">Prediksi</button>
                <button onclick="window.location.href='index.php?view=knockout'" id="nav-knockout"
                    class="nav-link">Penyisihan</button>
                <button onclick="window.location.href='index.php?view=teams'" id="nav-teams"
                    class="nav-link">Tim</button>
                <button onclick="window.location.href='index.php?view=leaderboard'" id="nav-leaderboard"
                    class="nav-link">Peringkat</button>
                <button onclick="window.location.href='profile.php'" id="nav-profile" class="nav-link">Profil</button>
                <?php if (isset($_SESSION['is_admin']) && $_SESSION['is_admin'] == 1): ?>
                    <a href="admin_panel.php" id="nav-admin" class="nav-link text-rose-500/70 hover:text-rose-500">Admin</a>
                <?php endif; ?>
            </div>
            <div class="flex items-center gap-4">
                <?php if (isset($_SESSION['username'])): ?>
                    <div class="user-dropdown">
                        <div class="flex items-center cursor-pointer">
                            <div class="user-info-side hidden sm:flex">
                                <div class="username"><?php echo htmlspecialchars($_SESSION['username']); ?></div>
                                <div class="stats">
                                    <span class="text-amber-500">🎫 <span id="ticket-count-side">0</span></span>
                                    <span class="text-worldcup-green">⭐ <span id="points-count-side">0</span></span>
                                </div>
                            </div>
                            <div class="relative">
                                <div id="avatar-btn" onclick="event.stopPropagation(); window.location.href='profile.php'"
                                    class="w-10 h-10 sm:w-12 sm:h-12 rounded-2xl bg-white/5 border border-white/10 flex items-center justify-center group overflow-hidden relative avatar-clickable">
                                    <div
                                        class="absolute inset-0 bg-amber-500 translate-y-full group-hover:translate-y-0 transition-transform duration-500">
                                    </div>
                                    <svg class="w-4 h-4 sm:w-5 sm:h-5 text-slate-400 group-hover:text-black relative z-10"
                                        fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                        <path d="M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z" />
                                    </svg>
                                </div>
                                <div id="claim-badge" class="claim-badge hidden cursor-pointer absolute -top-2 -right-2"
                                    onclick="event.stopPropagation(); window.location.href='profile.php'">
                                    <span class="claim-badge-text">KLAIM</span>
                                </div>
                            </div>
                        </div>
                    </div>
                <?php else: ?>
                    <button onclick="window.location.href='index.php?showAuth=1'"
                        class="bg-white text-black px-4 sm:px-6 py-2 sm:py-3 rounded-[20px] text-[9px] sm:text-[10px] font-black uppercase tracking-widest hover:bg-amber-500 hover:scale-105 transition-all shadow-[0_20px_40px_rgba(255,255,255,0.05)]">MASUK</button>
                <?php endif; ?>
                <button id="mobile-menu-btn"
                    class="lg:hidden p-2 rounded-xl bg-white/5 border border-white/10 text-white hover:bg-white/10 transition-all relative">
                    <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path d="M4 6h16M4 12h16M4 18h16" />
                    </svg>
                    <div class="menu-indicator"></div>
                </button>
            </div>
        </div>
        <div id="mobile-menu" class="fixed inset-0 z-50 lg:hidden mobile-menu-overlay invisible opacity-0">
            <div class="absolute inset-0 bg-black/80 backdrop-blur-md" onclick="toggleMobileMenu()"></div>
            <div
                class="absolute right-0 top-0 h-full w-64 glass-card rounded-l-[40px] p-6 transform translate-x-full transition-transform duration-300">
                <div class="flex justify-end mb-8">
                    <button onclick="toggleMobileMenu()" class="p-2 rounded-full bg-white/10 text-white"><svg
                            class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path d="M6 18L18 6M6 6l12 12" />
                        </svg></button>
                </div>
                <div class="flex flex-col gap-4">
                    <button onclick="window.location.href='promosi.php'; toggleMobileMenu();"
                        class="promo-animate text-left px-4 py-3 rounded-2xl bg-amber-500/20 border border-amber-500/50 text-amber-400 font-black transition-all flex items-center gap-2">🎉
                        Promosi</button>
                    <button onclick="window.location.href='index.php'; toggleMobileMenu();"
                        class="text-left px-4 py-3 rounded-2xl hover:bg-white/5 transition-all">Klasemen</button>
                    <button onclick="window.location.href='index.php?view=schedule'; toggleMobileMenu();"
                        class="text-left px-4 py-3 rounded-2xl hover:bg-white/5 transition-all">Jadwal</button>
                    <button onclick="window.location.href='predict.php'; toggleMobileMenu();"
                        class="text-left px-4 py-3 rounded-2xl hover:bg-white/5 transition-all">Prediksi</button>
                    <button onclick="window.location.href='index.php?view=knockout'; toggleMobileMenu();"
                        class="text-left px-4 py-3 rounded-2xl hover:bg-white/5 transition-all">Penyisihan</button>
                    <button onclick="window.location.href='index.php?view=teams'; toggleMobileMenu();"
                        class="text-left px-4 py-3 rounded-2xl hover:bg-white/5 transition-all">Tim</button>
                    <button onclick="window.location.href='index.php?view=leaderboard'; toggleMobileMenu();"
                        class="text-left px-4 py-3 rounded-2xl hover:bg-white/5 transition-all">Peringkat</button>
                    <button onclick="window.location.href='profile.php'; toggleMobileMenu();"
                        class="text-left px-4 py-3 rounded-2xl hover:bg-white/5 transition-all">👤 Profil</button>
                    <?php if (isset($_SESSION['is_admin']) && $_SESSION['is_admin'] == 1): ?>
                        <a href="admin_panel.php" onclick="toggleMobileMenu();"
                            class="text-left px-4 py-3 rounded-2xl hover:bg-white/5 transition-all text-rose-500">Admin</a>
                    <?php endif; ?>
                    <?php if (isset($_SESSION['username'])): ?>
                        <a href="auth.php?action=logout"
                            class="text-left px-4 py-3 rounded-2xl hover:bg-white/5 transition-all text-red-400">🚪
                            Logout</a>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </nav>

    <!-- KONTEN PROFIL -->
    <main class="max-w-7xl mx-auto px-4 sm:px-6 py-8 sm:py-12">
        <div class="flex flex-col lg:flex-row lg:items-end justify-between gap-6 border-b border-white/5 pb-8 mb-8">
            <div class="space-y-3">
                <h1
                    class="text-5xl sm:text-7xl md:text-8xl font-display font-black text-white tracking-tighter uppercase leading-[0.9]">
                    PROFIL <br /> <span class="text-amber-500 italic">PENGGUNA</span>
                </h1>
            </div>
        </div>

        <div class="max-w-3xl mx-auto w-full space-y-6">
            <!-- Kartu Informasi User -->
            <div class="glass-card rounded-[48px] p-8 space-y-6">
                <!-- Baris atas: avatar, username, role, dan tombol logout -->
                <div class="flex items-center justify-between">
                    <div class="flex items-center gap-4">
                        <div
                            class="w-16 h-16 rounded-3xl bg-gradient-to-br from-amber-500 to-amber-700 flex items-center justify-center shadow-xl">
                            <span class="text-3xl font-black text-white uppercase" id="profile-initial">-</span>
                        </div>
                        <div>
                            <h2 class="text-2xl font-black text-white" id="profile-username">-</h2>
                            <p class="text-[10px] text-slate-400 uppercase tracking-wider"><span
                                    id="profile-role">User</span> • Member since <span id="profile-joined">-</span></p>
                        </div>
                    </div>
                    <!-- Tombol Logout di kanan username -->
                    <button id="logout-btn"
                        onclick="if(confirm('Yakin ingin logout?')) window.location.href='auth.php?action=logout';"
                        class="bg-red-500/20 hover:bg-red-500/30 text-red-400 px-5 py-2 rounded-xl font-black uppercase tracking-wider text-xs transition-all flex items-center gap-2">
                        <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                                d="M17 16l4-4m0 0l-4-4m4 4H7m6 4v1a3 3 0 01-3 3H6a3 3 0 01-3-3V7a3 3 0 013-3h4a3 3 0 013 3v1" />
                        </svg>
                        LOGOUT
                    </button>
                </div>

                <div class="grid grid-cols-1 sm:grid-cols-3 gap-6 pt-4 border-t border-white/10">
                    <div class="bg-white/5 rounded-2xl p-5 text-center">
                        <div class="text-4xl font-black text-amber-500" id="profile-tickets">0</div>
                        <div class="text-[9px] font-black text-slate-400 uppercase tracking-wider mt-1">Tiket Tersedia
                        </div>
                    </div>
                    <div class="bg-white/5 rounded-2xl p-5 text-center">
                        <div class="text-4xl font-black text-amber-500" id="profile-points">0</div>
                        <div class="text-[9px] font-black text-slate-400 uppercase tracking-wider mt-1">Poin</div>
                    </div>
                    <div class="bg-white/5 rounded-2xl p-5 text-center">
                        <div class="text-sm font-mono text-white" id="profile-last-claim">Belum pernah klaim</div>
                        <div class="text-[9px] font-black text-slate-400 uppercase tracking-wider mt-1">Klaim Terakhir
                        </div>
                    </div>
                </div>
                <button id="claim-daily-btn"
                    class="w-full bg-amber-500 text-black py-5 rounded-2xl font-black uppercase tracking-[0.2em] text-sm hover:bg-amber-400 transition-all flex items-center justify-center gap-3">
                    <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z" />
                    </svg> KLAIM TIKET HARIAN
                </button>
                <p class="text-[9px] text-slate-500 text-center">Setiap hari Anda berhak mendapatkan 1 tiket gratis.
                    Klik tombol di atas untuk mengklaim.</p>
            </div>

            <!-- Task & Pencapaian -->
            <div class="glass-card rounded-[48px] p-8">
                <h3 class="text-lg font-black text-white uppercase tracking-tight mb-4">Task & Pencapaian</h3>
                <div class="space-y-3">
                    <div class="glass-card rounded-[48px] p-8 mt-6">
                        <h3 class="text-lg font-black text-white uppercase tracking-tight mb-4">🎟️ Klaim Tiket dengan
                            Kode</h3>
                        <div class="flex gap-3 flex-col sm:flex-row">
                            <input type="text" id="redeem-code-input" placeholder="Masukkan kode tiket"
                                class="flex-1 bg-white/5 border border-white/10 rounded-xl px-4 py-3 text-white text-sm focus:outline-none focus:border-amber-500">
                            <button id="redeem-code-btn"
                                class="bg-amber-500 text-black px-6 py-3 rounded-xl text-xs font-black uppercase tracking-wider whitespace-nowrap">Klaim</button>
                        </div>
                        <div id="redeem-message" class="mt-3 text-xs text-center"></div>
                    </div>
                    <div class="flex items-center justify-between p-3 bg-white/5 rounded-xl">
                        <div class="flex items-center gap-3"><svg class="w-5 h-5 text-amber-500" fill="none"
                                stroke="currentColor" viewBox="0 0 24 24">
                                <path d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z" />
                            </svg><span class="text-sm font-bold text-white">Login Harian</span></div>
                        <span class="text-xs text-amber-500 font-mono">+1 tiket/hari</span>
                    </div>
                    <div class="flex items-center justify-between p-3 bg-white/5 rounded-xl opacity-60">
                        <div class="flex items-center gap-3"><svg class="w-5 h-5 text-slate-500" fill="none"
                                stroke="currentColor" viewBox="0 0 24 24">
                                <path d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z" />
                            </svg><span class="text-sm font-bold text-white">Memprediksi 5 pertandingan</span></div>
                        <span class="text-xs text-slate-500">Segera</span>
                    </div>
                </div>
            </div>

            <!-- Tukar Poin -->
            <div class="glass-card rounded-[48px] p-8 mt-6">
                <h3 class="text-lg font-black text-white uppercase tracking-tight mb-4">🎁 Tukar Poin</h3>
                <div id="user-points-info" class="bg-white/5 rounded-2xl p-4 mb-6">
                    <div class="flex justify-between items-center"><span class="text-slate-400">Total Poin
                            Didapat:</span><span id="total-points-display"
                            class="text-2xl font-black text-amber-500">0</span></div>
                    <div class="flex justify-between items-center mt-2"><span class="text-slate-400">Poin Tersedia untuk
                            Ditukar:</span><span id="available-points-display"
                            class="text-2xl font-black text-worldcup-green">0</span></div>
                </div>
                <div id="rewards-container" class="grid grid-cols-1 sm:grid-cols-2 gap-4">
                    <div class="text-center text-slate-400 py-4">Memuat daftar hadiah...</div>
                </div>
            </div>

            <!-- Riwayat Prediksi Lengkap -->
            <div class="glass-card rounded-[48px] p-8">
                <h3 class="text-lg font-black text-white uppercase tracking-tight mb-6">📋 Riwayat Prediksi Saya</h3>
                <div id="prediction-history-container">
                    <div class="text-center text-slate-400 py-4">Memuat data...</div>
                </div>
            </div>
        </div>
    </main>

    <footer
        class="border-t border-white/10 mt-16 py-8 text-center text-slate-500 text-[9px] font-black uppercase tracking-wider">
        <p>FIFA World Cup 2026 © All Rights Reserved.</p>
    </footer>

    <div id="toast-container"
        class="fixed bottom-6 left-1/2 -translate-x-1/2 z-[100] w-auto max-w-[90vw] pointer-events-none"></div>

    <script>
        // ========== FUNGSI LENGKAP ==========
        let currentUser = null;
        function escapeHtml(str) { if (!str) return str; return str.replace(/[&<>]/g, m => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;' }[m])); }
        function toggleMobileMenu() { const menu = document.getElementById('mobile-menu'); const drawer = menu?.querySelector('.absolute.right-0'); if (!menu) return; if (menu.classList.contains('invisible')) { menu.classList.remove('invisible', 'opacity-0'); menu.classList.add('visible', 'opacity-100'); drawer?.classList.remove('translate-x-full'); } else { menu.classList.add('invisible', 'opacity-0'); menu.classList.remove('visible', 'opacity-100'); drawer?.classList.add('translate-x-full'); } }
        document.getElementById('mobile-menu-btn')?.addEventListener('click', toggleMobileMenu);
        function showNotification(message, isError = false, linkUrl = null, linkText = null) {
            const container = document.getElementById('toast-container'); if (!container) return;
            const toast = document.createElement('div'); toast.className = 'toast flex items-center gap-4';
            const icon = isError ? '❌' : '✅';
            toast.innerHTML = `<div class="flex items-center gap-3"><span>${icon}</span><span class="text-sm font-bold text-white">${message}</span></div>${linkUrl && linkText ? `<a href="${linkUrl}">${linkText}</a>` : ''}<button class="ml-4 text-slate-400 hover:text-white" onclick="this.parentElement.remove()">✕</button>`;
            container.appendChild(toast); setTimeout(() => { if (toast.parentElement) { toast.classList.add('toast-exit'); setTimeout(() => toast.remove(), 300); } }, 5000);
        }
        async function fetchUserInfo() {
            try { const res = await fetch('api.php?action=get_user_info'); if (res.ok) { currentUser = await res.json(); updateProfileUI(); } } catch (e) { }
        }
        function updateProfileUI() {
            if (!currentUser) return;
            document.getElementById('profile-username').innerText = currentUser.username;
            document.getElementById('profile-tickets').innerText = currentUser.tickets;
            document.getElementById('profile-points').innerText = currentUser.available_points || 0;
            document.getElementById('profile-role').innerText = currentUser.is_admin == 1 ? 'Administrator' : 'FIFA Fan';
            document.getElementById('profile-initial').innerText = currentUser.username.charAt(0).toUpperCase();
            if (currentUser.last_daily_claim) { const lastDate = new Date(currentUser.last_daily_claim).toLocaleDateString('id-ID', { day: 'numeric', month: 'long', year: 'numeric' }); document.getElementById('profile-last-claim').innerText = lastDate; } else { document.getElementById('profile-last-claim').innerText = 'Belum pernah klaim'; }
            if (currentUser.joined_date) { const joinDate = new Date(currentUser.joined_date).toLocaleDateString('id-ID', { day: 'numeric', month: 'long', year: 'numeric' }); document.getElementById('profile-joined').innerText = joinDate; }
            const claimBtn = document.getElementById('claim-daily-btn'); if (claimBtn) { const today = new Date().toLocaleDateString('en-CA'); const lastClaim = currentUser.last_daily_claim; const sudahKlaim = (lastClaim === today); if (sudahKlaim) { claimBtn.classList.remove('not-claimed'); claimBtn.disabled = true; claimBtn.innerHTML = '✅ SUDAH DIKLAIM'; claimBtn.classList.remove('bg-amber-500', 'hover:bg-amber-400'); claimBtn.classList.add('bg-gray-600', 'cursor-not-allowed', 'opacity-70'); } else { claimBtn.disabled = false; claimBtn.innerHTML = '<svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z"/></svg> KLAIM TIKET HARIAN'; claimBtn.classList.remove('bg-gray-600', 'cursor-not-allowed', 'opacity-70'); claimBtn.classList.add('bg-amber-500', 'hover:bg-amber-400'); claimBtn.classList.add('not-claimed'); } }
            const avatarBtn = document.getElementById('avatar-btn'); const today = new Date().toLocaleDateString('en-CA'); const lastClaim = currentUser.last_daily_claim; const sudahKlaimHariIni = (lastClaim === today); if (avatarBtn) { let indicator = avatarBtn.querySelector('.avatar-indicator'); if (!sudahKlaimHariIni) { if (!indicator) { const div = document.createElement('div'); div.className = 'avatar-indicator'; avatarBtn.appendChild(div); } } else { if (indicator) indicator.remove(); } }
            updateClaimBadge();
        }
        function updateClaimBadge() { const badge = document.getElementById('claim-badge'); if (!badge || !currentUser) return; const today = new Date().toLocaleDateString('en-CA'); const lastClaim = currentUser.last_daily_claim; const sudahKlaim = (lastClaim === today); if (!sudahKlaim) badge.classList.remove('hidden'); else badge.classList.add('hidden'); }
        async function claimDailyTicketManual() { if (!currentUser) { showNotification('Anda harus login terlebih dahulu.', true); return; } const btn = document.getElementById('claim-daily-btn'); const originalText = btn.innerHTML; btn.innerHTML = '<div class="animate-spin h-5 w-5 border-2 border-white border-t-transparent rounded-full mx-auto"></div>'; btn.disabled = true; try { const response = await fetch('api.php?action=claim_daily_ticket', { method: 'POST', headers: { 'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content } }); const data = await response.json(); if (data.status === 'success') { if (data.claimed) { showNotification(`🎉 Selamat! Anda mendapatkan +1 tiket. Total tiket: ${data.tickets}`); await fetchUserInfo(); updateClaimBadge(); } else { showNotification('Anda sudah mengklaim tiket hari ini. Coba lagi besok!'); } } else { showNotification(data.error || 'Gagal mengklaim tiket', true); } } catch (err) { showNotification('Terjadi kesalahan jaringan', true); } finally { btn.innerHTML = originalText; btn.disabled = false; } }
        async function loadRewards() {
            const container = document.getElementById('rewards-container');
            if (!container) return;
            try {
                const rewardsRes = await fetch('api.php?action=get_rewards');
                const rewards = await rewardsRes.json();
                const pointsRes = await fetch('api.php?action=get_user_points');
                const pointsData = await pointsRes.json();
                const availablePoints = pointsData.available_points || 0;
                document.getElementById('total-points-display').innerText = pointsData.total_points || 0;
                document.getElementById('available-points-display').innerText = availablePoints;
                if (!rewards.length) {
                    container.innerHTML = '<div class="text-center text-slate-400 py-4">Belum ada hadiah tersedia.</div>';
                    return;
                }
                let html = '';
                for (const reward of rewards) {
                    const isDisabled = (reward.stock <= 0) || (availablePoints < reward.points_required);
                    const imgHtml = reward.image_url ?
                        `<img src="${reward.image_url}" class="w-full h-40 object-cover rounded-xl mb-3">` :
                        `<div class="text-5xl mb-2">🎁</div>`;
                    html += `<div class="glass-card p-5 rounded-2xl flex flex-col items-center text-center">
                        ${imgHtml}
                        <h4 class="font-bold text-white">${escapeHtml(reward.name)}</h4>
                        <p class="text-[10px] text-slate-400 mt-1">${escapeHtml(reward.description || '')}</p>
                        <div class="mt-3 flex items-center gap-2">
                            <span class="text-amber-500 font-bold">${reward.points_required} Poin</span>
                            <span class="text-slate-400 text-xs">Stok: ${reward.stock}</span>
                        </div>
                        <button ${isDisabled ? 'disabled' : ''} onclick="redeemReward(${reward.id}, ${reward.points_required})" 
                            class="mt-3 px-4 py-2 rounded-xl text-xs font-black transition-all ${isDisabled ? 'bg-slate-600 cursor-not-allowed opacity-50' : 'bg-amber-500 text-black hover:bg-amber-400'}">
                            Tukar
                        </button>
                    </div>`;
                }
                container.innerHTML = html;
            } catch (err) {
                container.innerHTML = '<div class="text-center text-red-400 py-4">Gagal memuat daftar hadiah.</div>';
            }
        }
        async function redeemReward(rewardId, pointsRequired) { if (!confirm(`Tukar ${pointsRequired} poin untuk hadiah ini?`)) return; try { const formData = new FormData(); formData.append('reward_id', rewardId); const res = await fetch('api.php?action=redeem_points', { method: 'POST', body: formData, headers: { 'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content } }); const data = await res.json(); if (data.status === 'success') { showNotification(data.message); await loadRewards(); await fetchUserInfo(); } else { showNotification(data.error || 'Gagal menukar poin', true); } } catch (err) { showNotification('Terjadi kesalahan jaringan', true); } }

        // ========== FUNGSI LOAD PREDIKSI DENGAN DETAIL LENGKAP ==========
        async function loadPredictionHistory() {
            const container = document.getElementById('prediction-history-container');
            if (!container) return;
            try {
                const predRes = await fetch('api.php?action=get_my_predictions');
                const predData = await predRes.json();
                const [groupMatchesRes, knockoutMatchesRes] = await Promise.all([
                    fetch('api.php?action=get_group_matches'),
                    fetch('api.php?action=get_knockout')
                ]);
                const groupMatches = await groupMatchesRes.json();
                const knockoutMatches = await knockoutMatchesRes.json();

                let html = '';

                // BABAK GRUP
                if (predData.group && predData.group.length > 0) {
                    html += `<div class="mb-8"><h4 class="text-sm font-black text-amber-500 uppercase tracking-wider mb-4 flex items-center gap-2">🏆 Babak Grup <span class="text-[10px] text-slate-400">(${predData.group.length} prediksi)</span></h4><div class="space-y-4">`;
                    for (const pred of predData.group) {
                        const match = groupMatches.find(m => m.id == pred.match_id);
                        if (!match) continue;
                        const team1 = match.team1_name;
                        const team2 = match.team2_name;
                        const matchDate = match.match_date ? new Date(match.match_date).toLocaleString('id-ID') : 'TBD';

                        // Prediksi pemenang/hasil
                        let predWinnerText = '-';
                        if (pred.result_type) {
                            if (pred.result_type === 'home_win') predWinnerText = team1;
                            else if (pred.result_type === 'away_win') predWinnerText = team2;
                            else predWinnerText = 'Seri';
                        }
                        // Prediksi skor
                        const predScore = (pred.team1_score_pred !== null && pred.team2_score_pred !== null) ? `${pred.team1_score_pred} - ${pred.team2_score_pred}` : 'Belum';
                        // Prediksi lainnya
                        const totalGoals = pred.total_goals_pred !== null ? pred.total_goals_pred : '-';
                        const corners = pred.corners_pred !== null ? pred.corners_pred : '-';
                        const yellow = pred.yellow_cards_pred !== null ? pred.yellow_cards_pred : '-';
                        const red = pred.red_cards_pred !== null ? pred.red_cards_pred : '-';
                        const offside = pred.offsides_pred !== null ? pred.offsides_pred : '-';
                        // Poin
                        let pointsText = 'Belum ada poin';
                        let pointsColor = 'text-slate-500';
                        if (pred.points_awarded == 1) {
                            let pts = 0;
                            if (pred.team1_score_pred !== null && pred.team2_score_pred !== null) pts = 4;
                            else if (pred.result_type) pts = 2;
                            if (pred.total_goals_pred !== null) pts += 2;
                            if (pred.corners_pred !== null) pts += 7;
                            if (pred.yellow_cards_pred !== null) pts += 9;
                            if (pred.red_cards_pred !== null) pts += 9;
                            if (pred.offsides_pred !== null) pts += 11;
                            pointsText = `+${pts} poin (sudah dihitung)`;
                            pointsColor = 'text-worldcup-green';
                        } else if (pred.team1_score_pred !== null || pred.result_type || pred.total_goals_pred !== null) {
                            pointsText = 'Menunggu pertandingan selesai';
                            pointsColor = 'text-yellow-500';
                        }

                        html += `<div class="glass-card p-4 rounded-2xl">
                            <div class="flex flex-wrap justify-between items-start gap-2">
                                <div>
                                    <div class="font-bold text-white">${escapeHtml(team1)} vs ${escapeHtml(team2)}</div>
                                    <div class="text-[10px] text-slate-400">${matchDate}</div>
                                </div>
                                <div class="text-right">
                                    <div class="text-amber-500 text-xs font-black">🏆 Pemenang: ${predWinnerText}</div>
                                    <div class="text-amber-500 text-xs font-black">⚽ Skor: ${predScore}</div>
                                </div>
                            </div>
                            <div class="pred-detail-grid mt-2">
                                <div class="pred-detail-item">⚽ Total Gol: ${totalGoals}</div>
                                <div class="pred-detail-item">🚩 Pojok: ${corners}</div>
                                <div class="pred-detail-item">🟨 Kartu Kuning: ${yellow}</div>
                                <div class="pred-detail-item">🟥 Kartu Merah: ${red}</div>
                                <div class="pred-detail-item">🚩 Offside: ${offside}</div>
                            </div>
                            <div class="text-right text-[10px] font-bold ${pointsColor} mt-2">${pointsText}</div>
                        </div>`;
                    }
                    html += `</div></div>`;
                } else {
                    html += `<div class="mb-6 text-center text-slate-400 py-4">Belum ada prediksi babak grup.</div>`;
                }

                // BABAK KNOCKOUT
                if (predData.knockout && predData.knockout.length > 0) {
                    html += `<div class="mt-6"><h4 class="text-sm font-black text-amber-500 uppercase tracking-wider mb-4 flex items-center gap-2">🥇 Babak Knockout <span class="text-[10px] text-slate-400">(${predData.knockout.length} prediksi)</span></h4><div class="space-y-4">`;
                    for (const pred of predData.knockout) {
                        const match = knockoutMatches.find(m => m.id == pred.match_id);
                        if (!match) continue;
                        const team1 = match.team1_name || match.team1_code || '?';
                        const team2 = match.team2_name || match.team2_code || '?';
                        const matchDate = match.match_date ? new Date(match.match_date).toLocaleString('id-ID') : 'TBD';

                        let predWinnerText = '-';
                        if (pred.winner_id && pred.winner_id != 0) {
                            predWinnerText = (pred.winner_id == match.team1_id) ? team1 : team2;
                        }
                        const predScore = (pred.team1_score_pred !== null && pred.team2_score_pred !== null) ? `${pred.team1_score_pred} - ${pred.team2_score_pred}` : 'Belum';
                        const totalGoals = pred.total_goals_pred !== null ? pred.total_goals_pred : '-';
                        const corners = pred.corners_pred !== null ? pred.corners_pred : '-';
                        const yellow = pred.yellow_cards_pred !== null ? pred.yellow_cards_pred : '-';
                        const red = pred.red_cards_pred !== null ? pred.red_cards_pred : '-';
                        const offside = pred.offsides_pred !== null ? pred.offsides_pred : '-';

                        let pointsText = 'Belum ada poin';
                        let pointsColor = 'text-slate-500';
                        if (pred.points_awarded == 1) {
                            let pts = 0;
                            if (pred.team1_score_pred !== null && pred.team2_score_pred !== null) pts = 4;
                            else if (pred.winner_id && pred.winner_id != 0) pts = 2;
                            if (pred.total_goals_pred !== null) pts += 2;
                            if (pred.corners_pred !== null) pts += 7;
                            if (pred.yellow_cards_pred !== null) pts += 9;
                            if (pred.red_cards_pred !== null) pts += 9;
                            if (pred.offsides_pred !== null) pts += 11;
                            pointsText = `+${pts} poin (sudah dihitung)`;
                            pointsColor = 'text-worldcup-green';
                        } else if (pred.team1_score_pred !== null || pred.winner_id) {
                            pointsText = 'Menunggu pertandingan selesai';
                            pointsColor = 'text-yellow-500';
                        }

                        html += `<div class="glass-card p-4 rounded-2xl">
                            <div class="flex flex-wrap justify-between items-start gap-2">
                                <div>
                                    <div class="font-bold text-white">${escapeHtml(team1)} vs ${escapeHtml(team2)}</div>
                                    <div class="text-[10px] text-slate-400">${matchDate}</div>
                                </div>
                                <div class="text-right">
                                    <div class="text-amber-500 text-xs font-black">🏆 Pemenang: ${predWinnerText}</div>
                                    <div class="text-amber-500 text-xs font-black">⚽ Skor: ${predScore}</div>
                                </div>
                            </div>
                            <div class="pred-detail-grid mt-2">
                                <div class="pred-detail-item">⚽ Total Gol: ${totalGoals}</div>
                                <div class="pred-detail-item">🚩 Pojok: ${corners}</div>
                                <div class="pred-detail-item">🟨 Kartu Kuning: ${yellow}</div>
                                <div class="pred-detail-item">🟥 Kartu Merah: ${red}</div>
                                <div class="pred-detail-item">🚩 Offside: ${offside}</div>
                            </div>
                            <div class="text-right text-[10px] font-bold ${pointsColor} mt-2">${pointsText}</div>
                        </div>`;
                    }
                    html += `</div></div>`;
                } else if (predData.group && predData.group.length === 0) {
                    html += `<div class="text-center text-slate-400 py-4">Belum ada prediksi knockout.</div>`;
                }

                if (!predData.group.length && !predData.knockout.length) {
                    html = '<div class="text-center text-slate-400 py-4">Belum ada prediksi sama sekali. Ayo buat prediksi!</div>';
                }
                container.innerHTML = html;
            } catch (err) {
                console.error(err);
                container.innerHTML = '<div class="text-center text-red-400 py-4">Gagal memuat riwayat prediksi.</div>';
            }
        }

        const redeemBtn = document.getElementById('redeem-code-btn'); const redeemInput = document.getElementById('redeem-code-input'); const redeemMessage = document.getElementById('redeem-message'); if (redeemBtn) { redeemBtn.addEventListener('click', async () => { const code = redeemInput.value.trim(); if (!code) { redeemMessage.innerText = '❌ Masukkan kode tiket terlebih dahulu.'; redeemMessage.classList.add('text-red-400'); return; } redeemBtn.disabled = true; redeemBtn.innerText = 'Memproses...'; redeemMessage.innerText = ''; try { const formData = new FormData(); formData.append('code', code); const res = await fetch('api.php?action=redeem_ticket_code', { method: 'POST', body: formData, headers: { 'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content } }); const data = await res.json(); if (data.status === 'success') { redeemMessage.innerText = data.message || '✅ Tiket berhasil diklaim!'; redeemMessage.classList.remove('text-red-400'); redeemMessage.classList.add('text-worldcup-green'); redeemInput.value = ''; await fetchUserInfo(); loadRewards(); } else { redeemMessage.innerText = data.error || '❌ Gagal menukar kode.'; redeemMessage.classList.add('text-red-400'); } } catch (err) { redeemMessage.innerText = '❌ Terjadi kesalahan jaringan.'; redeemMessage.classList.add('text-red-400'); } finally { redeemBtn.disabled = false; redeemBtn.innerText = 'Klaim'; } }); }
        document.getElementById('claim-daily-btn')?.addEventListener('click', claimDailyTicketManual);
        (async () => { await fetchUserInfo(); loadRewards(); loadPredictionHistory(); })();
    </script>
</body>

</html>