<?php
require 'config.php';
$action = $_GET['action'] ?? '';
$ip = $_SERVER['REMOTE_ADDR'];
$endpoint = 'page.predict'; // 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>');
}
// Redirect jika belum login
if (!isset($_SESSION['user_id'])) {
    header('Location: index.php');
    exit;
}

// Ambil data user untuk cek tiket
$stmt = $pdo->prepare("SELECT tickets, username, points FROM users WHERE id = ?");
$stmt->execute([$_SESSION['user_id']]);
$user = $stmt->fetch();
$tickets = $user['tickets'];
$username = $user['username'];
$points = $user['points'];
?>
<!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>FIFA World Cup 2026 - Prediksi</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>
        /* ========== SEMUA STYLE SAMA SEPERTI SEBELUMNYA ========== */
        :root {
            --wc-green: #00df82;
            --wc-blue: #0052ff;
            --wc-red: #ff2d55;
            --wc-gold: #ffcc00;
            --wc-surface: #030610;
        }

        body {
            background: #030610;
            font-family: 'Inter', sans-serif;
        }

        .glass-card {
            background: rgba(255, 255, 255, 0.02);
            backdrop-filter: blur(12px);
            border: 1px solid rgba(255, 255, 255, 0.05);
            border-radius: 2rem;
            transition: all 0.3s;
        }

        .glass-card:hover {
            background: rgba(255, 255, 255, 0.04);
            border-color: rgba(255, 255, 255, 0.1);
        }

        .btn-predict {
            background: linear-gradient(135deg, #f59e0b, #d97706);
            color: black;
            font-weight: 800;
            transition: all 0.2s;
        }

        .btn-predict:hover {
            transform: scale(1.02);
            box-shadow: 0 10px 25px -5px rgba(245, 158, 11, 0.5);
        }

        .btn-disabled {
            background: #334155;
            cursor: not-allowed;
            opacity: 0.6;
        }

        .match-card {
            transition: all 0.2s;
        }

        .match-card:hover {
            transform: translateY(-2px);
            border-color: #f59e0b;
        }

        .toast {
            position: fixed;
            bottom: 20px;
            left: 50%;
            transform: translateX(-50%);
            background: #1e293b;
            backdrop-filter: blur(12px);
            border: 1px solid #f59e0b;
            border-radius: 2rem;
            padding: 0.75rem 1.5rem;
            color: white;
            z-index: 1000;
            font-weight: bold;
            animation: slideUp 0.3s ease;
            display: flex;
            align-items: center;
            gap: 12px;
            flex-wrap: wrap;
            justify-content: center;
            text-align: center;
        }

        .toast a {
            background: #f59e0b;
            color: black;
            padding: 4px 12px;
            border-radius: 30px;
            font-size: 12px;
            font-weight: bold;
            text-decoration: none;
            margin-left: 8px;
        }

        .toast a:hover {
            background: #d97706;
        }

        @keyframes slideUp {
            from {
                opacity: 0;
                transform: translateX(-50%) translateY(20px);
            }

            to {
                opacity: 1;
                transform: translateX(-50%) translateY(0);
            }
        }

        .score-input {
            background: rgba(0, 0, 0, 0.6);
            border: 1px solid #334155;
            border-radius: 0.75rem;
            padding: 0.5rem;
            text-align: center;
            color: white;
            width: 70px;
        }

        .score-input:focus {
            outline: none;
            border-color: #f59e0b;
        }

        .stat-select {
            background: rgba(0, 0, 0, 0.6);
            border: 1px solid #334155;
            border-radius: 0.75rem;
            padding: 0.5rem;
            text-align: center;
            color: white;
            width: 80px;
            cursor: pointer;
        }

        .tab-active {
            background: #f59e0b;
            color: black;
        }

        .tab-inactive {
            background: rgba(255, 255, 255, 0.05);
            color: #94a3b8;
        }

        .predict-select {
            background: #1e293b;
            border: 1px solid #f59e0b;
            border-radius: 0.75rem;
            padding: 0.4rem 0.8rem;
            color: white;
            font-size: 0.75rem;
            cursor: pointer;
        }

        .predict-select option {
            background: #0f172a;
        }

        .predicted-badge {
            background: rgba(0, 223, 130, 0.2);
            border: 1px solid #00df82;
            color: #00df82;
            font-size: 9px;
            padding: 2px 6px;
            border-radius: 20px;
            white-space: nowrap;
        }

        .match-header {
            display: grid;
            grid-template-columns: 1fr auto 1fr;
            align-items: center;
            gap: 1rem;
        }

        .team-home,
        .team-away {
            display: flex;
            flex-direction: column;
            align-items: center;
            gap: 0.5rem;
        }

        .team-home {
            text-align: center;
        }

        .team-away {
            text-align: center;
        }

        .vs-div {
            text-align: center;
        }

        @media (max-width: 640px) {
            .match-header {
                gap: 0.5rem;
            }

            .team-home img,
            .team-away img {
                width: 2rem;
                height: 1.5rem;
            }

            .team-home span,
            .team-away span {
                font-size: 0.75rem;
            }

            .vs-div .text-2xl {
                font-size: 1.25rem;
            }
        }

        .match-separator {
            width: 70%;
            margin: 2rem auto;
            border: 0;
            height: 1px;
            background: linear-gradient(90deg, transparent, rgba(245, 158, 11, 0.5), rgba(0, 223, 130, 0.5), rgba(245, 158, 11, 0.5), transparent);
            border-radius: 2px;
        }

        .match-separator:hover {
            background: linear-gradient(90deg, transparent, #f59e0b, #00df82, #f59e0b, transparent);
            height: 2px;
            transition: all 0.3s ease;
        }

        .custom-select {
            position: relative;
            width: 100%;
            max-width: 220px;
        }

        .select-trigger {
            background: #1e293b;
            border: 1px solid #f59e0b;
            border-radius: 0.75rem;
            padding: 0.4rem 0.8rem;
            color: white;
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: space-between;
            font-size: 0.75rem;
        }

        .select-trigger .selected-content {
            display: flex;
            align-items: center;
            gap: 8px;
            flex: 1;
        }

        .select-trigger img {
            width: 24px;
            height: 18px;
            object-fit: cover;
            border-radius: 4px;
        }

        .select-options {
            position: absolute;
            top: 100%;
            left: 0;
            right: 0;
            background: #0f172a;
            border: 1px solid #f59e0b;
            border-radius: 0.75rem;
            z-index: 100;
            display: none;
            margin-top: 4px;
            max-height: 200px;
            overflow-y: auto;
        }

        .select-options.show {
            display: block;
        }

        .select-option {
            padding: 0.5rem;
            display: flex;
            align-items: center;
            gap: 8px;
            cursor: pointer;
            transition: background 0.2s;
            font-size: 0.75rem;
        }

        .select-option:hover {
            background: #f59e0b20;
        }

        .select-option img {
            width: 24px;
            height: 18px;
            object-fit: cover;
            border-radius: 4px;
        }

        .confirm-modal {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.8);
            backdrop-filter: blur(8px);
            z-index: 2000;
            display: none;
            align-items: center;
            justify-content: center;
            opacity: 0;
            transition: opacity 0.3s ease;
        }

        .confirm-modal.show {
            display: flex;
            opacity: 1;
        }

        .confirm-card {
            max-width: 380px;
            width: 90%;
            background: #0f172a;
            border: 1px solid rgba(245, 158, 11, 0.3);
            border-radius: 2rem;
            padding: 1.5rem;
            text-align: center;
            box-shadow: 0 20px 35px -10px black;
            transform: scale(0.9);
            transition: transform 0.2s ease;
        }

        .confirm-modal.show .confirm-card {
            transform: scale(1);
        }

        .confirm-icon {
            font-size: 3rem;
            margin-bottom: 0.5rem;
        }

        .confirm-title {
            font-size: 1.25rem;
            font-weight: 800;
            color: #f59e0b;
            margin-bottom: 0.75rem;
        }

        .confirm-message {
            font-size: 0.9rem;
            color: #cbd5e1;
            margin-bottom: 1.5rem;
        }

        .confirm-buttons {
            display: flex;
            gap: 1rem;
            justify-content: center;
        }

        .confirm-btn {
            padding: 0.5rem 1.5rem;
            border-radius: 2rem;
            font-weight: 700;
            font-size: 0.8rem;
            cursor: pointer;
            transition: all 0.2s;
            border: none;
        }

        .confirm-btn.yes {
            background: #f59e0b;
            color: black;
        }

        .confirm-btn.yes:hover {
            background: #d97706;
            transform: scale(1.02);
        }

        .confirm-btn.no {
            background: rgba(255, 255, 255, 0.1);
            color: white;
            border: 1px solid rgba(255, 255, 255, 0.2);
        }

        .confirm-btn.no:hover {
            background: rgba(255, 255, 255, 0.2);
        }

        /* ===== STYLE UNTUK USER INFO DI NAVBAR (DESKTOP & MOBILE) ===== */
        .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;
        }

        /* Ukuran lebih kecil untuk mobile agar tidak terlalu padat */
        @media (max-width: 550px) {
            .user-info-side .username {
                font-size: 8px;
            }

            .user-info-side .stats {
                gap: 6px;
                font-size: 7px;
            }

            .user-info-side {
                margin-right: 6px;
            }
        }

        .avatar-clickable {
            cursor: pointer;
        }

        /* Style untuk info user di mobile menu drawer */
        .mobile-user-info {
            display: flex;
            align-items: center;
            gap: 12px;
            padding: 12px 16px;
            background: rgba(255, 255, 255, 0.05);
            border-radius: 1rem;
            margin-bottom: 20px;
            border: 1px solid rgba(255, 255, 255, 0.1);
        }

        .mobile-user-avatar {
            width: 40px;
            height: 40px;
            background: rgba(255, 255, 255, 0.1);
            border-radius: 1rem;
            display: flex;
            align-items: center;
            justify-content: center;
        }

        .mobile-user-details {
            flex: 1;
        }

        .mobile-user-name {
            font-size: 12px;
            font-weight: 800;
            color: white;
        }

        .mobile-user-stats {
            display: flex;
            gap: 16px;
            font-size: 10px;
            margin-top: 4px;
        }

        /* Animasi 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;
        }

        .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;
        }

        @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);
            }
        }

        .mobile-menu-overlay {
            transition: opacity 0.3s ease, visibility 0.3s ease;
        }

        /* Navbar link style */
        .nav-link {
            position: relative;
            padding: 0.5rem 1rem;
            transition: all 0.3s;
            color: #64748b;
            font-weight: 800;
            text-transform: uppercase;
            letter-spacing: 0.1em;
            font-size: 9px;
        }

        .nav-link::after {
            content: '';
            position: absolute;
            bottom: 0;
            left: 50%;
            transform: translateX(-50%);
            width: 0;
            height: 2px;
            background-color: #f59e0b;
            transition: all 0.3s;
            border-radius: 9999px;
        }

        .nav-link:hover {
            color: rgba(255, 255, 255, 0.8);
            transform: scale(1.05);
        }

        .nav-link.active {
            color: #f59e0b;
        }

        .nav-link.active::after {
            width: 50%;
            background-color: #f59e0b;
        }

        /* ========== RESPONSIVE FIX UNTUK MOBILE ========== */
        @media (max-width: 550px) {
            .match-card .grid-cols-\[120px_1fr_auto\] {
                grid-template-columns: 80px minmax(90px, 1fr) auto !important;
                gap: 6px !important;
            }

            .score-input {
                width: 55px;
                font-size: 12px;
                padding: 0.3rem;
            }

            .stat-select {
                width: 65px;
                font-size: 12px;
                padding: 0.3rem;
            }

            .custom-select .select-trigger {
                font-size: 10px;
                padding: 0.25rem 0.5rem;
            }

            .predicted-badge {
                font-size: 8px;
                white-space: normal;
                text-align: center;
                line-height: 1.2;
            }

            .save-winner-btn,
            .save-score-btn,
            .save-total-goals-btn,
            .save-corners-btn,
            .save-yellow-btn,
            .save-red-btn,
            .save-offside-btn,
            .save-ko-winner-btn,
            .save-ko-score-btn,
            .save-ko-total-goals-btn,
            .save-ko-corners-btn,
            .save-ko-yellow-btn,
            .save-ko-red-btn,
            .save-ko-offside-btn {
                font-size: 9px;
                padding: 2px 8px;
                white-space: nowrap;
            }

            .match-card .text-right {
                display: flex;
                justify-content: flex-end;
                align-items: center;
            }

            .team-home span,
            .team-away span {
                font-size: 11px;
                max-width: 80px;
                word-break: break-word;
            }

            .glass-card {
                padding: 1rem !important;
            }
        }

        /* Styling dropdown pilih tanggal */
        #date-select {
            background: transparent;
            border: none;
            color: #f59e0b;
            font-weight: bold;
            font-size: 0.9rem;
            cursor: pointer;
            outline: none;
            padding: 0.25rem 0.5rem;
            border-radius: 2rem;
            transition: all 0.2s;
        }

        #date-select:hover {
            background: rgba(255, 255, 255, 0.1);
            color: white;
        }

        #date-select option {
            background: #0f172a;
            color: white;
            font-weight: normal;
        }

        /* ========== TAMBAHAN CSS UNTUK BACKGROUND BARU (SAMA SEPERTI INDEX) ========== */
        @keyframes pulseSpotlight {
            0% {
                opacity: 0.1;
                transform: scale(1);
            }

            100% {
                opacity: 0.25;
                transform: scale(1.05);
            }
        }

        @keyframes floatBall1 {
            0% {
                transform: translateY(0) rotate(0deg) scale(0.95);
            }

            50% {
                transform: translateY(-25px) rotate(180deg) scale(1.05);
            }

            100% {
                transform: translateY(0) rotate(360deg) scale(0.95);
            }
        }

        @keyframes floatBall2 {
            0% {
                transform: translateY(0) rotate(360deg) scale(1);
            }

            50% {
                transform: translateY(30px) rotate(180deg) scale(0.9);
            }

            100% {
                transform: translateY(0) rotate(0deg) scale(1);
            }
        }

        @keyframes pingStar {
            0% {
                opacity: 0.4;
                transform: scale(1);
            }

            70% {
                opacity: 0;
                transform: scale(3);
            }

            100% {
                opacity: 0;
                transform: scale(3);
            }
        }

        .bg-stadium-spotlight {
            animation: pulseSpotlight 6s infinite alternate;
        }

        .float-ball-1 {
            animation: floatBall1 12s infinite ease-in-out;
        }

        .float-ball-2 {
            animation: floatBall2 16s infinite ease-in-out;
        }

        .ping-star {
            animation: pingStar 2s infinite cubic-bezier(0.4, 0, 0.6, 1);
        }
    </style>
</head>

<body class="min-h-screen bg-[#030610] text-white">

    <!-- ========== BACKGROUND BARU (Stadium, Grid, Floating Balls) - SAMA SEPERTI INDEX ========== -->
    <div class="fixed inset-0 overflow-hidden pointer-events-none z-0">
        <!-- Global Stadium Mesh Spots (Spotlights) -->
        <div
            class="absolute top-[-10%] left-[-10%] w-[50%] h-[50%] bg-[#00df82] rounded-full blur-[140px] opacity-15 bg-stadium-spotlight">
        </div>
        <div class="absolute bottom-[-10%] right-[-10%] w-[60%] h-[60%] bg-[#0052ff] rounded-full blur-[160px] opacity-15 bg-stadium-spotlight"
            style="animation-delay: -2s; animation-direction: alternate-reverse;"></div>
        <div class="absolute top-[30%] right-[10%] w-[40%] h-[40%] bg-[#ff2d55] rounded-full blur-[150px] opacity-[0.08] bg-stadium-spotlight"
            style="animation-duration: 8s; animation-delay: -4s;"></div>
        <div class="absolute bottom-[20%] left-[5%] w-[45%] h-[45%] bg-[#ffcc00] rounded-full blur-[130px] opacity-[0.06] bg-stadium-spotlight"
            style="animation-duration: 10s; animation-direction: alternate-reverse;"></div>

        <!-- Tactical Stadium Grid Overlay -->
        <div class="absolute inset-0 opacity-[0.035]"
            style="background-image: linear-gradient(to right, rgba(255,255,255,0.15) 1px, transparent 1px), linear-gradient(to bottom, rgba(255,255,255,0.15) 1px, transparent 1px); background-size: 45px 45px;">
        </div>

        <!-- Stadium Field Lines (Pitch markings) -->
        <div class="absolute inset-x-0 top-1/2 -translate-y-1/2 flex justify-center items-center opacity-[0.03]">
            <div class="w-[400px] h-[400px] border-4 border-white rounded-full flex justify-center items-center">
                <div class="w-[12px] h-[12px] bg-white rounded-full"></div>
            </div>
            <div class="absolute left-0 right-0 h-[4px] bg-white"></div>
            <div class="absolute top-0 w-[80%] h-[200px] border-b-4 border-x-4 border-white opacity-50 rounded-b-xl">
            </div>
            <div class="absolute bottom-0 w-[80%] h-[200px] border-t-4 border-x-4 border-white opacity-50 rounded-t-xl">
            </div>
        </div>

        <!-- Elegant Glowing Floating Laser Lights -->
        <div
            class="absolute top-1/4 left-10 w-1 h-32 bg-gradient-to-b from-transparent via-amber-500/20 to-transparent blur-sm animate-pulse">
        </div>
        <div class="absolute bottom-1/4 right-10 w-1 h-40 bg-gradient-to-b from-transparent via-[#00df82]/20 to-transparent blur-sm animate-pulse"
            style="animation-delay: 2.5s;"></div>

        <!-- Fluid Floating Soccer-Ball Geometric Particles -->
        <div class="absolute bottom-16 left-[8%] w-16 h-16 opacity-[0.2] float-ball-1">
            <svg viewBox="0 0 100 100" fill="none" xmlns="http://www.w3.org/2000/svg"
                class="text-[#00df82] stroke-current stroke-2 w-full h-full">
                <circle cx="50" cy="50" r="45" />
                <path d="M50 5 L35 30 L15 35 L5 50 L15 65 L35 70 L50 95 L65 70 L85 65 L95 50 L85 35 L65 30 Z" />
                <path d="M50 30 L40 45 L50 58 L60 45 Z" />
                <path d="M35 30 L40 45" />
                <path d="M65 30 L60 45" />
                <path d="M15 35 L40 45" />
                <path d="M85 35 L60 45" />
                <path d="M15 65 L50 58" />
                <path d="M85 65 L50 58" />
            </svg>
        </div>
        <div class="absolute top-20 right-[10%] w-24 h-24 opacity-[0.15] float-ball-2">
            <svg viewBox="0 0 100 100" fill="none" xmlns="http://www.w3.org/2000/svg"
                class="text-[#ffcc00] stroke-current stroke-2 w-full h-full">
                <ellipse cx="50" cy="50" rx="45" ry="30" />
                <ellipse cx="50" cy="50" rx="35" ry="20" />
                <line x1="50" y1="5" x2="50" y2="20" />
                <line x1="50" y1="80" x2="50" y2="95" />
                <line x1="5" y1="50" x2="15" y2="50" />
                <line x1="85" y1="50" x2="95" y2="50" />
                <path d="M15 35 L35 50" />
                <path d="M85 35 L65 50" />
                <path d="M15 65 L35 50" />
                <path d="M85 65 L65 50" />
            </svg>
        </div>

        <!-- Brand Stars (Kelap-kelip) -->
        <div class="absolute top-[15%] left-[45%] w-[3px] h-[3px] bg-white rounded-full opacity-40 ping-star"></div>
        <div class="absolute bottom-[35%] right-[30%] w-[4px] h-[4px] bg-[#00df82] rounded-full opacity-50 animate-ping"
            style="animation-duration: 3s;"></div>
        <div class="absolute top-[60%] left-[20%] w-[3px] h-[3px] bg-[#ff2d55] rounded-full opacity-30 animate-pulse">
        </div>
    </div>

    <!-- Navbar lengkap seperti di index.php dan leaderboard.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 active">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='leaderboard.php'" 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" 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 relative">
                        <div class="flex items-center cursor-pointer">
                            <!-- TAMPILAN USER INFO DI DESKTOP & MOBILE (flex, tidak disembunyikan) -->
                            <div class="user-info-side flex">
                                <div class="username"><?php echo htmlspecialchars($username); ?></div>
                                <div class="stats">
                                    <span class="text-amber-500">🎫 <span
                                            id="ticket-count-side"><?php echo $tickets; ?></span></span>
                                    <span class="text-worldcup-green">⭐ <span
                                            id="points-count-side"><?php echo $points; ?></span></span>
                                </div>
                            </div>
                            <div class="relative">
                                <div onclick="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 stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                                            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="window.location.href='profile.php'">
                                    <span class="claim-badge-text">KLAIM</span>
                                </div>
                            </div>
                        </div>
                    </div>
                <?php else: ?>
                    <button onclick="toggleAuthModal()"
                        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>

        <!-- Mobile Menu Drawer -->
        <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='leaderboard.php'; 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; ?>
                    <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>
                </div>
            </div>
        </div>
    </nav>

    <main class="max-w-6xl mx-auto px-4 py-8 relative z-10">
        <div class="text-center mb-8">
            <h1 class="text-4xl md:text-6xl font-black uppercase tracking-tighter">Buat Prediksi</h1>
            <p class="text-slate-400 text-sm mt-2">Gunakan tiket Anda untuk memprediksi detail pertandingan</p>
        </div>

        <!-- Dropdown Pilih Tanggal (2 hari terdekat) -->
        <div class="flex justify-center mb-6">
            <div class="glass-card px-6 py-3 rounded-full text-sm font-bold text-amber-500 flex items-center gap-3">
                <span>📅 Pilih Tanggal</span>
                <select id="date-select" class="bg-transparent text-white font-bold focus:outline-none cursor-pointer">
                    <option value="">Memuat...</option>
                </select>
            </div>
        </div>

        <div class="flex justify-center gap-4 mb-8">
            <button id="tab-group" class="tab-active px-6 py-2 rounded-full text-sm font-black transition">🏆 Babak
                Grup</button>
            <button id="tab-ko" class="tab-inactive px-6 py-2 rounded-full text-sm font-black transition">🥇 Babak
                Penyisihan</button>
        </div>

        <div id="group-container" class="space-y-6">
            <div class="text-center py-10 text-slate-500">Memuat pertandingan grup...</div>
        </div>

        <div id="ko-container" class="hidden space-y-6">
            <div class="text-center py-10 text-slate-500">Memuat pertandingan penyisihan...</div>
        </div>
    </main>

    <footer
        class="border-t border-white/10 mt-12 py-8 text-center text-slate-500 text-[9px] font-black uppercase tracking-wider relative z-10">
        <p>FIFA World Cup 2026 © All Rights Reserved. Promo hanya berlaku sesuai syarat dan ketentuan.</p>
    </footer>

    <div id="toast-message" class="toast hidden"></div>
    <div id="confirmModal" class="confirm-modal">
        <div class="confirm-card">
            <div class="confirm-icon">⚠️</div>
            <div class="confirm-title">Konfirmasi Prediksi</div>
            <div class="confirm-message" id="confirmMessage">Apakah Anda yakin ingin memasang prediksi ini?</div>
            <div class="confirm-buttons">
                <button class="confirm-btn yes" id="confirmYes">Ya, Pasang</button>
                <button class="confirm-btn no" id="confirmNo">Batal</button>
            </div>
        </div>
    </div>

    <script>
        let csrfToken = document.querySelector('meta[name="csrf-token"]').content;
        let currentUserTickets = <?php echo $tickets; ?>;
        let currentUserPoints = <?php echo $points; ?>;

        let allGroupMatches = [];
        let allKnockoutMatches = [];
        let matchesByDate = {};
        let sortedDates = [];
        let currentActiveDate = null;
        let currentTab = 'group';
        let myPredictions = { group: [], knockout: [] };
        let pendingSaveCallback = null;

        // === Fungsi untuk mobile menu ===
        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);

        // === Fungsi lainnya (sama seperti sebelumnya) ===
        async function fetchMyPredictions() {
            try {
                const res = await fetch('api.php?action=get_my_predictions');
                if (!res.ok) throw new Error(`HTTP ${res.status}`);
                const data = await res.json();
                myPredictions = {
                    group: Array.isArray(data.group) ? data.group : [],
                    knockout: Array.isArray(data.knockout) ? data.knockout : []
                };
            } catch (err) {
                console.error(err);
                myPredictions = { group: [], knockout: [] };
                showToast('Gagal memuat data prediksi Anda, tetapi Anda tetap dapat melihat jadwal.', true);
            }
        }

        function formatDateYMD(dateStr) {
            if (!dateStr) return null;
            return dateStr.substring(0, 10);
        }

        function showToast(message, isError = false, linkUrl = null, linkText = null) {
            let toast = document.getElementById('toast-message');
            toast.innerHTML = '';
            const textSpan = document.createElement('span');
            textSpan.innerText = message;
            toast.appendChild(textSpan);
            if (linkUrl && linkText) {
                const link = document.createElement('a');
                link.href = linkUrl;
                link.innerText = linkText;
                link.target = '_self';
                toast.appendChild(link);
            }
            toast.classList.remove('hidden', 'bg-green-600', 'bg-red-600');
            if (isError) {
                toast.classList.add('bg-red-600/90', 'border-red-500');
            } else {
                toast.classList.add('bg-green-600/90', 'border-green-500');
            }
            setTimeout(() => {
                toast.classList.add('hidden');
            }, 5000);
        }

        function escapeHtml(str) {
            if (!str) return str;
            return str.replace(/[&<>]/g, m => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;' }[m]));
        }

        function generateOptions(max, selected = null) {
            let options = '';
            for (let i = 0; i <= max; i++) {
                options += `<option value="${i}" ${selected == i ? 'selected' : ''}>${i}</option>`;
            }
            return options;
        }

        function showConfirm(message, onConfirm) {
            const modal = document.getElementById('confirmModal');
            document.getElementById('confirmMessage').innerText = message;
            pendingSaveCallback = onConfirm;
            modal.classList.add('show');
        }

        document.getElementById('confirmYes').onclick = () => {
            document.getElementById('confirmModal').classList.remove('show');
            if (pendingSaveCallback) pendingSaveCallback();
            pendingSaveCallback = null;
        };
        document.getElementById('confirmNo').onclick = () => {
            document.getElementById('confirmModal').classList.remove('show');
            pendingSaveCallback = null;
        };
        document.getElementById('confirmModal').addEventListener('click', (e) => {
            if (e.target === document.getElementById('confirmModal')) {
                document.getElementById('confirmModal').classList.remove('show');
                pendingSaveCallback = null;
            }
        });

        async function fetchUserInfo() {
            try {
                const res = await fetch('api.php?action=get_user_info');
                if (res.ok) {
                    const userData = await res.json();
                    currentUserTickets = userData.tickets;
                    currentUserPoints = userData.available_points || 0;
                    document.getElementById('ticket-count-side').innerText = currentUserTickets;
                    document.getElementById('points-count-side').innerText = currentUserPoints;
                    document.getElementById('mobile-top-ticket').innerText = currentUserTickets;
                    document.getElementById('mobile-top-points').innerText = currentUserPoints;
                    document.getElementById('mobile-ticket-count').innerText = currentUserTickets;
                    document.getElementById('mobile-points-count').innerText = currentUserPoints;
                    // Update claim badge
                    const badge = document.getElementById('claim-badge');
                    if (badge && userData.last_daily_claim) {
                        const today = new Date().toLocaleDateString('en-CA');
                        if (userData.last_daily_claim !== today) badge.classList.remove('hidden');
                        else badge.classList.add('hidden');
                    }
                }
            } catch (e) { console.error(e); }
        }

        async function savePrediction(matchId, isKnockout, data) {
            const formData = new FormData();
            formData.append('match_id', matchId);
            formData.append('is_knockout', isKnockout ? '1' : '0');
            if (data.resultType) formData.append('result_type', data.resultType);
            if (data.winnerId !== undefined) formData.append('winner_id', data.winnerId);
            if (data.homeScore !== undefined) formData.append('team1_score_pred', data.homeScore);
            if (data.awayScore !== undefined) formData.append('team2_score_pred', data.awayScore);
            if (data.totalGoals !== undefined) formData.append('total_goals_pred', data.totalGoals);
            if (data.corners !== undefined) formData.append('corners_pred', data.corners);
            if (data.yellowCards !== undefined) formData.append('yellow_cards_pred', data.yellowCards);
            if (data.redCards !== undefined) formData.append('red_cards_pred', data.redCards);
            if (data.offsides !== undefined) formData.append('offsides_pred', data.offsides);

            try {
                const res = await fetch('api.php?action=predict', {
                    method: 'POST',
                    body: formData,
                    headers: { 'X-CSRF-TOKEN': csrfToken }
                });
                const result = await res.json();
                if (result.status === 'success') {
                    showToast('Prediksi terpasang!');
                    await fetchMyPredictions();
                    await loadAllMatchesAndRender();
                    await fetchUserInfo();
                } else {
                    let errorMsg = result.error || 'Gagal memasang prediksi';
                    if (errorMsg.toLowerCase().includes('tiket tidak cukup')) {
                        showToast(errorMsg + '  Lakukan deposit terlebih dahulu.', true, 'profile.php', 'Ambil Tiket');
                    } else if (errorMsg.toLowerCase().includes('ditutup 30 menit')) {
                        showToast(errorMsg, true);
                    } else if (errorMsg.toLowerCase().includes('sudah dimulai')) {
                        showToast(errorMsg, true);
                    } else {
                        showToast(errorMsg, true);
                    }
                }
            } catch (err) {
                console.error(err);
                showToast('Terjadi kesalahan jaringan', true);
            }
        }

        function initCustomSelect(container, selectedValue) {
            const trigger = container.querySelector('.select-trigger');
            const optionsDiv = container.querySelector('.select-options');
            const selectedContent = container.querySelector('.selected-content');

            trigger.addEventListener('click', (e) => {
                e.stopPropagation();
                document.querySelectorAll('.select-options').forEach(div => {
                    if (div !== optionsDiv) div.classList.remove('show');
                });
                optionsDiv.classList.toggle('show');
            });

            container.querySelectorAll('.select-option').forEach(opt => {
                opt.addEventListener('click', (e) => {
                    e.stopPropagation();
                    const value = opt.getAttribute('data-value');
                    const cloned = opt.cloneNode(true);
                    cloned.classList.remove('select-option');
                    selectedContent.innerHTML = '';
                    selectedContent.appendChild(cloned);
                    optionsDiv.classList.remove('show');
                    container.setAttribute('data-selected', value);
                });
            });

            if (selectedValue) {
                const targetOption = Array.from(container.querySelectorAll('.select-option')).find(opt => opt.getAttribute('data-value') === selectedValue);
                if (targetOption) {
                    const cloned = targetOption.cloneNode(true);
                    cloned.classList.remove('select-option');
                    selectedContent.innerHTML = '';
                    selectedContent.appendChild(cloned);
                    container.setAttribute('data-selected', selectedValue);
                }
            }
        }

        document.addEventListener('click', () => {
            document.querySelectorAll('.select-options').forEach(opt => opt.classList.remove('show'));
        });

        // === Render functions (sama seperti sebelumnya) ===
        function renderGroupMatchesForDate(date) {
            const container = document.getElementById('group-container');
            const matches = matchesByDate[date]?.group || [];
            if (matches.length === 0) {
                container.innerHTML = '<div class="text-center py-10 text-slate-500">Tidak ada pertandingan grup pada tanggal ini.</div>';
                return;
            }
            let html = '';
            for (let i = 0; i < matches.length; i++) {
                const match = matches[i];
                const matchDate = new Date(match.match_date);
                const now = new Date();
                const isLocked = !isNaN(matchDate) ? (matchDate - now) < 30 * 60 * 1000 : false;
                const existingPred = myPredictions.group.find(p => p.match_id == match.id);
                const hasWinnerPred = existingPred && existingPred.result_type !== null;
                const hasScorePred = existingPred && existingPred.team1_score_pred !== null && existingPred.team2_score_pred !== null;
                const hasTotalGoalsPred = existingPred && existingPred.total_goals_pred !== null;
                const hasCornersPred = existingPred && existingPred.corners_pred !== null;
                const hasYellowPred = existingPred && existingPred.yellow_cards_pred !== null;
                const hasRedPred = existingPred && existingPred.red_cards_pred !== null;
                const hasOffsidePred = existingPred && existingPred.offsides_pred !== null;

                const winnerValue = existingPred?.result_type ?? '';
                const homeScoreValue = existingPred?.team1_score_pred ?? '';
                const awayScoreValue = existingPred?.team2_score_pred ?? '';
                const totalGoalsValue = existingPred?.total_goals_pred ?? '';
                const cornersValue = existingPred?.corners_pred ?? '';
                const yellowValue = existingPred?.yellow_cards_pred ?? '';
                const redValue = existingPred?.red_cards_pred ?? '';
                const offsideValue = existingPred?.offsides_pred ?? '';

                const displayDate = !isNaN(matchDate) ? matchDate.toLocaleString('id-ID') : 'TBD';
                const homeFlag = match.team1_flag || '';
                const awayFlag = match.team2_flag || '';

                html += `
                    <div class="glass-card p-6 rounded-3xl match-card max-w-4xl mx-auto" data-match-id="${match.id}" data-team1-id="${match.team1_id}" data-team2-id="${match.team2_id}" data-is-knockout="0">
                        <div class="match-header">
                            <div class="team-home">
                                <img src="${homeFlag}" class="w-12 h-8 object-cover rounded-md shadow">
                                <span class="font-bold text-white">${escapeHtml(match.team1_name)}</span>
                            </div>
                            <div class="vs-div">
                                <div class="text-2xl font-black text-amber-500">VS</div>
                                <div class="text-[10px] text-slate-400">${displayDate}</div>
                            </div>
                            <div class="team-away">
                                <img src="${awayFlag}" class="w-12 h-8 object-cover rounded-md shadow">
                                <span class="font-bold text-white">${escapeHtml(match.team2_name)}</span>
                            </div>
                        </div>
                        <div class="mt-4 border-t border-white/10 pt-4 space-y-3">
                            <!-- Baris Pemenang -->
                            <div class="grid grid-cols-[120px_1fr_auto] items-center gap-2">
                                <div class="text-xs font-bold text-amber-500">🏆 Pemenang</div>
                                <div class="custom-select winner-custom" data-selected="${winnerValue}">
                                    <div class="select-trigger">
                                        <div class="selected-content"><span>-- Pilih --</span></div>
                                        <span class="arrow">▼</span>
                                    </div>
                                    <div class="select-options">
                                        <div class="select-option" data-value="home_win"><img src="${homeFlag}" onerror="this.style.display='none'"><span> ${escapeHtml(match.team1_name)}</span></div>
                                        <div class="select-option" data-value="draw"><span>🤝 Seri</span></div>
                                        <div class="select-option" data-value="away_win"><img src="${awayFlag}" onerror="this.style.display='none'"><span> ${escapeHtml(match.team2_name)}</span></div>
                                    </div>
                                </div>
                                <div class="text-right">
                                    ${!hasWinnerPred ? `<button class="save-winner-btn bg-amber-500/20 hover:bg-amber-500/30 text-amber-400 px-3 py-1 rounded-full text-xs font-black whitespace-nowrap">Pasang</button>` : `<span class="predicted-badge whitespace-nowrap">✔ Terpasang</span>`}
                                </div>
                            </div>
                            <!-- Baris Skor Akhir -->
                            <div class="grid grid-cols-[120px_1fr_auto] items-center gap-2">
                                <div class="text-xs font-bold text-amber-500">⚽ Skor Akhir</div>
                                <div class="flex gap-2 items-center">
                                    <input type="number" placeholder="Home" class="score-input score-home w-16 text-center" min="0" max="30" value="${homeScoreValue}" ${hasScorePred ? 'disabled' : ''}>
                                    <span class="text-amber-500">-</span>
                                    <input type="number" placeholder="Away" class="score-input score-away w-16 text-center" min="0" max="30" value="${awayScoreValue}" ${hasScorePred ? 'disabled' : ''}>
                                </div>
                                <div class="text-right">
                                    ${!hasScorePred ? `<button class="save-score-btn bg-amber-500/20 hover:bg-amber-500/30 text-amber-400 px-3 py-1 rounded-full text-xs font-black whitespace-nowrap">Pasang</button>` : `<span class="predicted-badge whitespace-nowrap">✔ Terpasang</span>`}
                                </div>
                            </div>
                            <!-- Statistik lainnya -->
                            <div class="grid grid-cols-[120px_1fr_auto] items-center gap-2">
                                <div class="text-xs font-bold text-amber-500">⚽ Total Gol</div>
                                <select class="stat-select total-goals-select w-24" ${hasTotalGoalsPred ? 'disabled' : ''}>${generateOptions(50, totalGoalsValue)}</select>
                                <div class="text-right">${!hasTotalGoalsPred ? `<button class="save-total-goals-btn bg-amber-500/20 hover:bg-amber-500/30 text-amber-400 px-3 py-1 rounded-full text-xs font-black whitespace-nowrap">Pasang</button>` : `<span class="predicted-badge whitespace-nowrap">✔ Terpasang</span>`}</div>
                            </div>
                            <div class="grid grid-cols-[120px_1fr_auto] items-center gap-2">
                                <div class="text-xs font-bold text-amber-500">🚩 Tendangan Pojok</div>
                                <select class="stat-select corners-select w-24" ${hasCornersPred ? 'disabled' : ''}>${generateOptions(50, cornersValue)}</select>
                                <div class="text-right">${!hasCornersPred ? `<button class="save-corners-btn bg-amber-500/20 hover:bg-amber-500/30 text-amber-400 px-3 py-1 rounded-full text-xs font-black whitespace-nowrap">Pasang</button>` : `<span class="predicted-badge whitespace-nowrap">✔ Terpasang</span>`}</div>
                            </div>
                            <div class="grid grid-cols-[120px_1fr_auto] items-center gap-2">
                                <div class="text-xs font-bold text-amber-500">🟨 Kartu Kuning</div>
                                <select class="stat-select yellow-select w-24" ${hasYellowPred ? 'disabled' : ''}>${generateOptions(40, yellowValue)}</select>
                                <div class="text-right">${!hasYellowPred ? `<button class="save-yellow-btn bg-amber-500/20 hover:bg-amber-500/30 text-amber-400 px-3 py-1 rounded-full text-xs font-black whitespace-nowrap">Pasang</button>` : `<span class="predicted-badge whitespace-nowrap">✔ Terpasang</span>`}</div>
                            </div>
                            <div class="grid grid-cols-[120px_1fr_auto] items-center gap-2">
                                <div class="text-xs font-bold text-amber-500">🟥 Kartu Merah</div>
                                <select class="stat-select red-select w-24" ${hasRedPred ? 'disabled' : ''}>${generateOptions(20, redValue)}</select>
                                <div class="text-right">${!hasRedPred ? `<button class="save-red-btn bg-amber-500/20 hover:bg-amber-500/30 text-amber-400 px-3 py-1 rounded-full text-xs font-black whitespace-nowrap">Pasang</button>` : `<span class="predicted-badge whitespace-nowrap">✔ Terpasang</span>`}</div>
                            </div>
                            <div class="grid grid-cols-[120px_1fr_auto] items-center gap-2">
                                <div class="text-xs font-bold text-amber-500">🚩 Offside</div>
                                <select class="stat-select offside-select w-24" ${hasOffsidePred ? 'disabled' : ''}>${generateOptions(50, offsideValue)}</select>
                                <div class="text-right">${!hasOffsidePred ? `<button class="save-offside-btn bg-amber-500/20 hover:bg-amber-500/30 text-amber-400 px-3 py-1 rounded-full text-xs font-black whitespace-nowrap">Pasang</button>` : `<span class="predicted-badge whitespace-nowrap">✔ Terpasang</span>`}</div>
                            </div>
                            ${isLocked ? '<div class="text-red-400 text-xs mt-2 text-center">⚠️ Prediksi ditutup 30 menit sebelum pertandingan.</div>' : ''}
                        </div>
                    </div>
                `;
                if (i < matches.length - 1) html += `<hr class="match-separator">`;
            }
            container.innerHTML = html;
            document.querySelectorAll('#group-container .custom-select').forEach(customSelect => {
                const selectedVal = customSelect.getAttribute('data-selected') || '';
                initCustomSelect(customSelect, selectedVal);
            });
            attachGroupEventListeners();
        }

        function renderKnockoutMatchesForDate(date) {
            const container = document.getElementById('ko-container');
            const matches = matchesByDate[date]?.knockout || [];
            if (matches.length === 0) {
                container.innerHTML = '<div class="text-center py-10 text-slate-500">Tidak ada pertandingan knockout pada tanggal ini.</div>';
                return;
            }
            let html = '';
            for (let i = 0; i < matches.length; i++) {
                const match = matches[i];
                const matchDate = new Date(match.match_date);
                const now = new Date();
                const isLocked = !isNaN(matchDate) ? (matchDate - now) < 30 * 60 * 1000 : false;
                const team1Name = match.team1_name || match.team1_code || '?';
                const team2Name = match.team2_name || match.team2_code || '?';
                const existingPred = myPredictions.knockout.find(p => p.match_id == match.id);
                const hasWinnerPred = existingPred && existingPred.winner_id !== null && existingPred.winner_id != 0;
                const hasScorePred = existingPred && existingPred.team1_score_pred !== null && existingPred.team2_score_pred !== null;
                const hasTotalGoalsPred = existingPred && existingPred.total_goals_pred !== null;
                const hasCornersPred = existingPred && existingPred.corners_pred !== null;
                const hasYellowPred = existingPred && existingPred.yellow_cards_pred !== null;
                const hasRedPred = existingPred && existingPred.red_cards_pred !== null;
                const hasOffsidePred = existingPred && existingPred.offsides_pred !== null;

                let winnerValue = '';
                if (existingPred && existingPred.winner_id) {
                    if (existingPred.winner_id == match.team1_id) winnerValue = 'team1';
                    else if (existingPred.winner_id == match.team2_id) winnerValue = 'team2';
                }
                const homeScoreValue = existingPred?.team1_score_pred ?? '';
                const awayScoreValue = existingPred?.team2_score_pred ?? '';
                const totalGoalsValue = existingPred?.total_goals_pred ?? '';
                const cornersValue = existingPred?.corners_pred ?? '';
                const yellowValue = existingPred?.yellow_cards_pred ?? '';
                const redValue = existingPred?.red_cards_pred ?? '';
                const offsideValue = existingPred?.offsides_pred ?? '';

                const displayDate = !isNaN(matchDate) ? matchDate.toLocaleString('id-ID') : 'TBD';
                const homeFlag = match.team1_flag || '';
                const awayFlag = match.team2_flag || '';

                html += `
                    <div class="glass-card p-6 rounded-3xl match-card max-w-4xl mx-auto" data-match-id="${match.id}" data-team1-id="${match.team1_id}" data-team2-id="${match.team2_id}" data-is-knockout="1">
                        <div class="match-header">
                            <div class="team-home">
                                <img src="${homeFlag}" class="w-12 h-8 object-cover rounded-md shadow" onerror="this.style.display='none'">
                                <span class="font-bold text-white">${escapeHtml(team1Name)}</span>
                            </div>
                            <div class="vs-div">
                                <div class="text-2xl font-black text-amber-500">VS</div>
                                <div class="text-[10px] text-slate-400">${displayDate}</div>
                            </div>
                            <div class="team-away">
                                <img src="${awayFlag}" class="w-12 h-8 object-cover rounded-md shadow" onerror="this.style.display='none'">
                                <span class="font-bold text-white">${escapeHtml(team2Name)}</span>
                            </div>
                        </div>
                        <div class="mt-4 border-t border-white/10 pt-4 space-y-3">
                            <!-- Baris Pemenang -->
                            <div class="grid grid-cols-[120px_1fr_auto] items-center gap-2">
                                <div class="text-xs font-bold text-amber-500">🏆 Pemenang</div>
                                <div class="custom-select winner-custom" data-selected="${winnerValue}">
                                    <div class="select-trigger">
                                        <div class="selected-content"><span>-- Pilih --</span></div>
                                        <span class="arrow">▼</span>
                                    </div>
                                    <div class="select-options">
                                        <div class="select-option" data-value="team1"><img src="${homeFlag}" onerror="this.style.display='none'"><span>${escapeHtml(team1Name)}</span></div>
                                        <div class="select-option" data-value="team2"><img src="${awayFlag}" onerror="this.style.display='none'"><span>${escapeHtml(team2Name)}</span></div>
                                    </div>
                                </div>
                                <div class="text-right">
                                    ${!hasWinnerPred ? `<button class="save-ko-winner-btn bg-amber-500/20 hover:bg-amber-500/30 text-amber-400 px-3 py-1 rounded-full text-xs font-black whitespace-nowrap">Pasang</button>` : `<span class="predicted-badge whitespace-nowrap">✔ Terpasang</span>`}
                                </div>
                            </div>
                            <!-- Baris Skor Akhir -->
                            <div class="grid grid-cols-[120px_1fr_auto] items-center gap-2">
                                <div class="text-xs font-bold text-amber-500">⚽ Skor Akhir</div>
                                <div class="flex gap-2 items-center">
                                    <input type="number" placeholder="Home" class="score-input ko-score-home w-16 text-center" min="0" max="30" value="${homeScoreValue}" ${hasScorePred ? 'disabled' : ''}>
                                    <span class="text-amber-500">-</span>
                                    <input type="number" placeholder="Away" class="score-input ko-score-away w-16 text-center" min="0" max="30" value="${awayScoreValue}" ${hasScorePred ? 'disabled' : ''}>
                                </div>
                                <div class="text-right">
                                    ${!hasScorePred ? `<button class="save-ko-score-btn bg-amber-500/20 hover:bg-amber-500/30 text-amber-400 px-3 py-1 rounded-full text-xs font-black whitespace-nowrap">Pasang</button>` : `<span class="predicted-badge whitespace-nowrap">✔ Terpasang</span>`}
                                </div>
                            </div>
                            <!-- Statistik lainnya -->
                            <div class="grid grid-cols-[120px_1fr_auto] items-center gap-2">
                                <div class="text-xs font-bold text-amber-500">⚽ Total Gol</div>
                                <select class="stat-select ko-total-goals-select w-24" ${hasTotalGoalsPred ? 'disabled' : ''}>${generateOptions(50, totalGoalsValue)}</select>
                                <div class="text-right">${!hasTotalGoalsPred ? `<button class="save-ko-total-goals-btn bg-amber-500/20 hover:bg-amber-500/30 text-amber-400 px-3 py-1 rounded-full text-xs font-black whitespace-nowrap">Pasang</button>` : `<span class="predicted-badge whitespace-nowrap">✔ Terpasang</span>`}</div>
                            </div>
                            <div class="grid grid-cols-[120px_1fr_auto] items-center gap-2">
                                <div class="text-xs font-bold text-amber-500">🚩 Tendangan Pojok</div>
                                <select class="stat-select ko-corners-select w-24" ${hasCornersPred ? 'disabled' : ''}>${generateOptions(50, cornersValue)}</select>
                                <div class="text-right">${!hasCornersPred ? `<button class="save-ko-corners-btn bg-amber-500/20 hover:bg-amber-500/30 text-amber-400 px-3 py-1 rounded-full text-xs font-black whitespace-nowrap">Pasang</button>` : `<span class="predicted-badge whitespace-nowrap">✔ Terpasang</span>`}</div>
                            </div>
                            <div class="grid grid-cols-[120px_1fr_auto] items-center gap-2">
                                <div class="text-xs font-bold text-amber-500">🟨 Kartu Kuning</div>
                                <select class="stat-select ko-yellow-select w-24" ${hasYellowPred ? 'disabled' : ''}>${generateOptions(40, yellowValue)}</select>
                                <div class="text-right">${!hasYellowPred ? `<button class="save-ko-yellow-btn bg-amber-500/20 hover:bg-amber-500/30 text-amber-400 px-3 py-1 rounded-full text-xs font-black whitespace-nowrap">Pasang</button>` : `<span class="predicted-badge whitespace-nowrap">✔ Terpasang</span>`}</div>
                            </div>
                            <div class="grid grid-cols-[120px_1fr_auto] items-center gap-2">
                                <div class="text-xs font-bold text-amber-500">🟥 Kartu Merah</div>
                                <select class="stat-select ko-red-select w-24" ${hasRedPred ? 'disabled' : ''}>${generateOptions(20, redValue)}</select>
                                <div class="text-right">${!hasRedPred ? `<button class="save-ko-red-btn bg-amber-500/20 hover:bg-amber-500/30 text-amber-400 px-3 py-1 rounded-full text-xs font-black whitespace-nowrap">Pasang</button>` : `<span class="predicted-badge whitespace-nowrap">✔ Terpasang</span>`}</div>
                            </div>
                            <div class="grid grid-cols-[120px_1fr_auto] items-center gap-2">
                                <div class="text-xs font-bold text-amber-500">🚩 Offside</div>
                                <select class="stat-select ko-offside-select w-24" ${hasOffsidePred ? 'disabled' : ''}>${generateOptions(50, offsideValue)}</select>
                                <div class="text-right">${!hasOffsidePred ? `<button class="save-ko-offside-btn bg-amber-500/20 hover:bg-amber-500/30 text-amber-400 px-3 py-1 rounded-full text-xs font-black whitespace-nowrap">Pasang</button>` : `<span class="predicted-badge whitespace-nowrap">✔ Terpasang</span>`}</div>
                            </div>
                            ${isLocked ? '<div class="text-red-400 text-xs mt-2 text-center">⚠️ Prediksi ditutup 30 menit sebelum pertandingan.</div>' : ''}
                        </div>
                    </div>
                `;
                if (i < matches.length - 1) html += `<hr class="match-separator">`;
            }
            container.innerHTML = html;
            document.querySelectorAll('#ko-container .custom-select').forEach(customSelect => {
                const selectedVal = customSelect.getAttribute('data-selected') || '';
                initCustomSelect(customSelect, selectedVal);
            });
            attachKoEventListeners();
        }

        function attachGroupEventListeners() {
            document.querySelectorAll('#group-container .save-winner-btn').forEach(btn => {
                btn.onclick = () => {
                    const card = btn.closest('.match-card');
                    const customSelect = card.querySelector('.custom-select');
                    const selectedValue = customSelect.getAttribute('data-selected');
                    if (!selectedValue) { showToast('Pilih pemenang terlebih dahulu', true); return; }
                    const matchId = card.dataset.matchId;
                    let resultType = selectedValue;
                    let winnerId = null;
                    if (resultType === 'home_win') winnerId = card.dataset.team1Id;
                    else if (resultType === 'away_win') winnerId = card.dataset.team2Id;
                    const selectedText = customSelect.querySelector('.selected-content span')?.innerText || '';
                    showConfirm(`Yakin ingin memasang prediksi PEMENANG (${selectedText})?`, async () => {
                        await savePrediction(matchId, false, { resultType, winnerId });
                    });
                };
            });
            document.querySelectorAll('#group-container .save-score-btn').forEach(btn => {
                btn.onclick = () => {
                    const card = btn.closest('.match-card');
                    const matchId = card.dataset.matchId;
                    const homeScore = card.querySelector('.score-home').value;
                    const awayScore = card.querySelector('.score-away').value;
                    if (homeScore === '' || awayScore === '') { showToast('Masukkan skor untuk kedua tim', true); return; }
                    showConfirm(`Yakin ingin memasang prediksi SKOR (${homeScore} - ${awayScore})?`, async () => {
                        await savePrediction(matchId, false, { homeScore: parseInt(homeScore), awayScore: parseInt(awayScore) });
                    });
                };
            });
            document.querySelectorAll('#group-container .save-total-goals-btn').forEach(btn => {
                btn.onclick = () => {
                    const card = btn.closest('.match-card');
                    const matchId = card.dataset.matchId;
                    const totalGoals = card.querySelector('.total-goals-select').value;
                    if (totalGoals === '') return;
                    showConfirm(`Yakin ingin memasang prediksi TOTAL GOL (${totalGoals})?`, async () => {
                        await savePrediction(matchId, false, { totalGoals: parseInt(totalGoals) });
                    });
                };
            });
            document.querySelectorAll('#group-container .save-corners-btn').forEach(btn => {
                btn.onclick = () => {
                    const card = btn.closest('.match-card');
                    const matchId = card.dataset.matchId;
                    const corners = card.querySelector('.corners-select').value;
                    if (corners === '') return;
                    showConfirm(`Yakin ingin memasang prediksi TENDANGAN POJOK (${corners})?`, async () => {
                        await savePrediction(matchId, false, { corners: parseInt(corners) });
                    });
                };
            });
            document.querySelectorAll('#group-container .save-yellow-btn').forEach(btn => {
                btn.onclick = () => {
                    const card = btn.closest('.match-card');
                    const matchId = card.dataset.matchId;
                    const yellow = card.querySelector('.yellow-select').value;
                    if (yellow === '') return;
                    showConfirm(`Yakin ingin memasang prediksi KARTU KUNING (${yellow})?`, async () => {
                        await savePrediction(matchId, false, { yellowCards: parseInt(yellow) });
                    });
                };
            });
            document.querySelectorAll('#group-container .save-red-btn').forEach(btn => {
                btn.onclick = () => {
                    const card = btn.closest('.match-card');
                    const matchId = card.dataset.matchId;
                    const red = card.querySelector('.red-select').value;
                    if (red === '') return;
                    showConfirm(`Yakin ingin memasang prediksi KARTU MERAH (${red})?`, async () => {
                        await savePrediction(matchId, false, { redCards: parseInt(red) });
                    });
                };
            });
            document.querySelectorAll('#group-container .save-offside-btn').forEach(btn => {
                btn.onclick = () => {
                    const card = btn.closest('.match-card');
                    const matchId = card.dataset.matchId;
                    const offside = card.querySelector('.offside-select').value;
                    if (offside === '') return;
                    showConfirm(`Yakin ingin memasang prediksi OFFSIDE (${offside})?`, async () => {
                        await savePrediction(matchId, false, { offsides: parseInt(offside) });
                    });
                };
            });
        }

        function attachKoEventListeners() {
            document.querySelectorAll('#ko-container .save-ko-winner-btn').forEach(btn => {
                btn.onclick = () => {
                    const card = btn.closest('.match-card');
                    const customSelect = card.querySelector('.custom-select');
                    const selectedValue = customSelect.getAttribute('data-selected');
                    if (!selectedValue) { showToast('Pilih pemenang terlebih dahulu', true); return; }
                    const matchId = card.dataset.matchId;
                    let winnerId = selectedValue === 'team1' ? card.dataset.team1Id : card.dataset.team2Id;
                    if (!winnerId || winnerId == 0) { showToast('Tim belum ditentukan', true); return; }
                    const selectedText = customSelect.querySelector('.selected-content span')?.innerText || '';
                    showConfirm(`Yakin ingin memasang prediksi PEMENANG (${selectedText})?`, async () => {
                        await savePrediction(matchId, true, { winnerId });
                    });
                };
            });
            document.querySelectorAll('#ko-container .save-ko-score-btn').forEach(btn => {
                btn.onclick = () => {
                    const card = btn.closest('.match-card');
                    const matchId = card.dataset.matchId;
                    const homeScore = card.querySelector('.ko-score-home').value;
                    const awayScore = card.querySelector('.ko-score-away').value;
                    if (homeScore === '' || awayScore === '') { showToast('Masukkan skor untuk kedua tim', true); return; }
                    showConfirm(`Yakin ingin memasang prediksi SKOR (${homeScore} - ${awayScore})?`, async () => {
                        await savePrediction(matchId, true, { homeScore: parseInt(homeScore), awayScore: parseInt(awayScore) });
                    });
                };
            });
            document.querySelectorAll('#ko-container .save-ko-total-goals-btn').forEach(btn => {
                btn.onclick = () => {
                    const card = btn.closest('.match-card');
                    const matchId = card.dataset.matchId;
                    const totalGoals = card.querySelector('.ko-total-goals-select').value;
                    if (totalGoals === '') return;
                    showConfirm(`Yakin ingin memasang prediksi TOTAL GOL (${totalGoals})?`, async () => {
                        await savePrediction(matchId, true, { totalGoals: parseInt(totalGoals) });
                    });
                };
            });
            document.querySelectorAll('#ko-container .save-ko-corners-btn').forEach(btn => {
                btn.onclick = () => {
                    const card = btn.closest('.match-card');
                    const matchId = card.dataset.matchId;
                    const corners = card.querySelector('.ko-corners-select').value;
                    if (corners === '') return;
                    showConfirm(`Yakin ingin memasang prediksi TENDANGAN POJOK (${corners})?`, async () => {
                        await savePrediction(matchId, true, { corners: parseInt(corners) });
                    });
                };
            });
            document.querySelectorAll('#ko-container .save-ko-yellow-btn').forEach(btn => {
                btn.onclick = () => {
                    const card = btn.closest('.match-card');
                    const matchId = card.dataset.matchId;
                    const yellow = card.querySelector('.ko-yellow-select').value;
                    if (yellow === '') return;
                    showConfirm(`Yakin ingin memasang prediksi KARTU KUNING (${yellow})?`, async () => {
                        await savePrediction(matchId, true, { yellowCards: parseInt(yellow) });
                    });
                };
            });
            document.querySelectorAll('#ko-container .save-ko-red-btn').forEach(btn => {
                btn.onclick = () => {
                    const card = btn.closest('.match-card');
                    const matchId = card.dataset.matchId;
                    const red = card.querySelector('.ko-red-select').value;
                    if (red === '') return;
                    showConfirm(`Yakin ingin memasang prediksi KARTU MERAH (${red})?`, async () => {
                        await savePrediction(matchId, true, { redCards: parseInt(red) });
                    });
                };
            });
            document.querySelectorAll('#ko-container .save-ko-offside-btn').forEach(btn => {
                btn.onclick = () => {
                    const card = btn.closest('.match-card');
                    const matchId = card.dataset.matchId;
                    const offside = card.querySelector('.ko-offside-select').value;
                    if (offside === '') return;
                    showConfirm(`Yakin ingin memasang prediksi OFFSIDE (${offside})?`, async () => {
                        await savePrediction(matchId, true, { offsides: parseInt(offside) });
                    });
                };
            });
        }

        function populateDateSelect() {
            const dateSelect = document.getElementById('date-select');
            if (!dateSelect) return;
            dateSelect.innerHTML = '';
            if (sortedDates.length === 0) {
                dateSelect.innerHTML = '<option value="">Tidak ada jadwal</option>';
                return;
            }
            const today = new Date().toISOString().split('T')[0];
            let datesToShow = sortedDates;
            if (sortedDates.length > 2) {
                const futureDates = sortedDates.filter(d => d >= today);
                if (futureDates.length >= 2) {
                    datesToShow = futureDates.slice(0, 2);
                } else {
                    datesToShow = sortedDates.slice(0, 2);
                }
            }
            for (const date of datesToShow) {
                const option = document.createElement('option');
                option.value = date;
                const displayDate = new Date(date).toLocaleDateString('id-ID', { weekday: 'long', day: 'numeric', month: 'long', year: 'numeric' });
                option.textContent = displayDate;
                dateSelect.appendChild(option);
            }
            if (currentActiveDate && datesToShow.includes(currentActiveDate)) {
                dateSelect.value = currentActiveDate;
            } else if (datesToShow.length > 0) {
                dateSelect.value = datesToShow[0];
                currentActiveDate = datesToShow[0];
            }
        }

        async function loadAllMatchesAndRender() {
            try {
                await fetchMyPredictions();
                await fetchUserInfo();
                const [groupRes, knockoutRes] = await Promise.all([
                    fetch('api.php?action=get_group_matches'),
                    fetch('api.php?action=get_knockout')
                ]);
                if (!groupRes.ok || !knockoutRes.ok) throw new Error('Gagal mengambil data pertandingan');
                const groupMatches = await groupRes.json();
                const knockoutMatches = await knockoutRes.json();
                if (!Array.isArray(groupMatches) || !Array.isArray(knockoutMatches)) throw new Error('Data pertandingan tidak valid');
                allGroupMatches = groupMatches;
                allKnockoutMatches = knockoutMatches;
                matchesByDate = {};
                const addMatch = (match, type) => {
                    if (!match || !match.match_date) return;
                    const date = formatDateYMD(match.match_date);
                    if (!date) return;
                    if (!matchesByDate[date]) matchesByDate[date] = { group: [], knockout: [] };
                    matchesByDate[date][type].push(match);
                };
                groupMatches.forEach(m => { if (m.is_finished == 0 && m.match_date) addMatch(m, 'group'); });
                knockoutMatches.forEach(m => { if (m.is_finished == 0 && m.match_date && m.team1_id != null && m.team2_id != null) addMatch(m, 'knockout'); });
                sortedDates = Object.keys(matchesByDate).sort();
                populateDateSelect();
                const dateSelect = document.getElementById('date-select');
                if (dateSelect && dateSelect.options.length > 0 && !currentActiveDate) {
                    currentActiveDate = dateSelect.value;
                }
                if (currentActiveDate) {
                    if (currentTab === 'group') renderGroupMatchesForDate(currentActiveDate);
                    else renderKnockoutMatchesForDate(currentActiveDate);
                } else {
                    document.getElementById('group-container').innerHTML = '<div class="text-center py-10 text-slate-500">Belum ada jadwal pertandingan.</div>';
                    document.getElementById('ko-container').innerHTML = '<div class="text-center py-10 text-slate-500">Belum ada jadwal pertandingan.</div>';
                }
            } catch (err) {
                console.error(err);
                showToast('Gagal memuat data: ' + (err.message || 'Terjadi kesalahan'), true);
                document.getElementById('group-container').innerHTML = '<div class="text-center py-10 text-red-400">Gagal memuat data pertandingan. Silakan refresh halaman.</div>';
                document.getElementById('ko-container').innerHTML = '<div class="text-center py-10 text-red-400">Gagal memuat data pertandingan. Silakan refresh halaman.</div>';
            }
        }

        document.getElementById('date-select')?.addEventListener('change', (e) => {
            const selectedDate = e.target.value;
            if (!selectedDate) return;
            currentActiveDate = selectedDate;
            if (currentTab === 'group') renderGroupMatchesForDate(currentActiveDate);
            else renderKnockoutMatchesForDate(currentActiveDate);
        });

        document.getElementById('tab-group').addEventListener('click', () => {
            currentTab = 'group';
            document.getElementById('group-container').classList.remove('hidden');
            document.getElementById('ko-container').classList.add('hidden');
            document.getElementById('tab-group').classList.add('tab-active');
            document.getElementById('tab-group').classList.remove('tab-inactive');
            document.getElementById('tab-ko').classList.add('tab-inactive');
            document.getElementById('tab-ko').classList.remove('tab-active');
            if (currentActiveDate) renderGroupMatchesForDate(currentActiveDate);
        });
        document.getElementById('tab-ko').addEventListener('click', () => {
            currentTab = 'ko';
            document.getElementById('ko-container').classList.remove('hidden');
            document.getElementById('group-container').classList.add('hidden');
            document.getElementById('tab-ko').classList.add('tab-active');
            document.getElementById('tab-ko').classList.remove('tab-inactive');
            document.getElementById('tab-group').classList.add('tab-inactive');
            document.getElementById('tab-group').classList.remove('tab-active');
            if (currentActiveDate) renderKnockoutMatchesForDate(currentActiveDate);
        });

        loadAllMatchesAndRender();
    </script>
</body>

</html>