<?php require 'config.php'; ?>
<!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</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 LENGKAP (sama seperti sebelumnya) ========== */
        :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 LAINNYA (SAMA SEPERTI ASLI) ===== */
        .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-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: contain;
            background-repeat: no-repeat;
            background-position: center;
            background-color: #030610;
            cursor: pointer;
            filter: brightness(1.05);
            height: auto;
            aspect-ratio: 16 / 9;
        }
        @media (min-width: 1024px) {
            .carousel-slide {
                aspect-ratio: 21 / 9;
            }
        }
        @media (max-width: 768px) {
            .carousel-slide {
                aspect-ratio: 16 / 9;
            }
            .carousel-container {
                background-color: #030610;
            }
            .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;
        }
        #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);
            }
        }
        @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;
        }
        @keyframes liveBlink {
            0% {
                opacity: 0.7;
                text-shadow: 0 0 2px rgba(239, 68, 68, 0.5);
            }
            50% {
                opacity: 1;
                text-shadow: 0 0 8px #ef4444, 0 0 4px #ef4444;
                color: #ff6b6b;
            }
            100% {
                opacity: 0.7;
                text-shadow: 0 0 2px rgba(239, 68, 68, 0.5);
            }
        }
        .live-text {
            animation: liveBlink 1s ease-in-out infinite;
            font-weight: 800;
            letter-spacing: 1px;
        }
        @keyframes livePulse {
            0% {
                transform: scale(1);
                background-color: #ef4444;
                box-shadow: 0 0 0 0 rgba(239, 68, 68, 0.7);
            }
            50% {
                transform: scale(1.2);
                background-color: #ff6b6b;
                box-shadow: 0 0 0 6px rgba(239, 68, 68, 0);
            }
            100% {
                transform: scale(1);
                background-color: #ef4444;
                box-shadow: 0 0 0 0 rgba(239, 68, 68, 0);
            }
        }
        .live-dot {
            animation: livePulse 1.2s infinite;
        }
        @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);
        }
        .popup-modal {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.85);
            backdrop-filter: blur(10px);
            display: none;
            justify-content: center;
            align-items: center;
            z-index: 10000;
            opacity: 0;
            transition: opacity 0.3s ease;
        }
        .popup-modal.show {
            display: flex;
            opacity: 1;
        }
        .popup-content {
            position: relative;
            max-width: 90%;
            max-height: 90%;
            background: linear-gradient(145deg, #0f172a, #0a0f1c);
            border-radius: 2rem;
            border: 1px solid rgba(245, 158, 11, 0.4);
            box-shadow: 0 25px 40px rgba(0,0,0,0.5), 0 0 0 1px rgba(245, 158, 11, 0.1);
            padding: 1rem;
            animation: zoomIn 0.4s cubic-bezier(0.23, 1, 0.32, 1);
        }
        @keyframes zoomIn {
            from { transform: scale(0.9); opacity: 0; }
            to { transform: scale(1); opacity: 1; }
        }
        .popup-content img {
            max-width: 100%;
            max-height: 70vh;
            border-radius: 1.5rem;
            display: block;
            margin: 0 auto;
        }
        .close-popup {
            position: absolute;
            top: -12px;
            right: -12px;
            width: 32px;
            height: 32px;
            background: #f59e0b;
            color: #030610;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            font-weight: 900;
            font-size: 18px;
            cursor: pointer;
            transition: all 0.2s;
            border: 2px solid #fff;
            box-shadow: 0 2px 8px rgba(0,0,0,0.3);
        }
        .close-popup:hover {
            background: #d97706;
            transform: scale(1.05);
        }
        @media (max-width: 640px) {
            .popup-content { padding: 0.75rem; }
            .close-popup { top: -8px; right: -8px; width: 28px; height: 28px; font-size: 16px; }
        }
        #players-modal .glass-card {
            max-width: 95vw;
            width: 100%;
            margin: 0 auto;
        }
        @media (max-width: 640px) {
            #players-modal .p-6 {
                padding: 1rem;
            }
            #players-modal .grid-cols-1 {
                gap: 0.5rem;
            }
            #players-modal .bg-white\/5.rounded-xl {
                padding: 0.5rem;
            }
            #players-modal .text-sm.font-bold {
                font-size: 0.7rem;
            }
            #players-modal .text-\[9px\] {
                font-size: 0.65rem;
            }
        }
    </style>
</head>

<body class="min-h-screen relative">
    <!-- ========== BACKGROUND BARU (Stadium, Grid, Floating Balls) ========== -->
    <div class="fixed inset-0 overflow-hidden pointer-events-none z-0">
        <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>
        <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>
        <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>
        <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>
        <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>
        <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>

    <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>

    <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="showView('standings')">
                <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='userguide.php'"
                    class="promo-animate bg-green-500 text-black px-4 py-2 rounded-full text-[9px] font-black uppercase tracking-widest hover:bg-amber-400 transition-all shadow-md">
                    User Guide
                </button>
                <button onclick="showView('standings')" id="nav-standings" class="nav-link active">Klasemen</button>
                <button onclick="showView('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="showView('knockout')" id="nav-knockout" class="nav-link">Penyisihan</button>
                <button onclick="showView('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" 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 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="event.stopPropagation(); 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 stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                            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 stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                                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='userguide.php'; toggleMobileMenu();"
                        class="promo-animate text-left px-4 py-3 rounded-2xl bg-green-500/20 border border-green-500/50 text-green-400 font-black transition-all flex items-center gap-2">
                        User Guide
                    </button>
                    <button onclick="showView('standings'); toggleMobileMenu();"
                        class="text-left px-4 py-3 rounded-2xl hover:bg-white/5 transition-all">Klasemen</button>
                    <button onclick="showView('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="showView('knockout'); toggleMobileMenu();"
                        class="text-left px-4 py-3 rounded-2xl hover:bg-white/5 transition-all">Penyisihan</button>
                    <button onclick="showView('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; ?>
                    <?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>

    <!-- Banner Carousel -->
    <div class="carousel-container">
        <div class="carousel-slides" id="carouselSlides">
            <div class="carousel-slide" style="background-image: url('https://i.postimg.cc/dVCfP4BM/m-C.jpg');"
                data-url="https//mc-sakti.xyz">
                <div class="carousel-overlay">
                    <div class="carousel-caption">
                        <h2></h2>
                        <p></p>
                    </div>
                </div>
            </div>
            <div class="carousel-slide" style="background-image: url('https://i.postimg.cc/0QzWnnbx/Bannerdepan.jpg');"
                data-url="">
                <div class="carousel-overlay">
                    <div class="carousel-caption">
                        <h2></h2>
                        <p></p>
                    </div>
                </div>
            </div>
            <div class="carousel-slide" style="background-image: url('images/carousel/banner3.jpg');"
                data-url="https://cutt.ly/moneysitesakti123">
                <div class="carousel-overlay">
                    <div class="carousel-caption">
                        <h2></h2>
                        <p></p>
                    </div>
                </div>
            </div>
        </div>
        <button class="carousel-btn btn-prev" id="prevBtn">❮</button>
        <button class="carousel-btn btn-next" id="nextBtn">❯</button>
        <div class="carousel-dots" id="carouselDots"></div>
    </div>

    <main id="main-content" class="max-w-7xl mx-auto px-4 sm:px-6 py-8 sm:py-12 flex-1 w-full relative z-10">
        <!-- Standings -->
        <div id="view-standings" class="view space-y-12 sm:space-y-16">
            <div class="flex flex-col lg:flex-row lg:items-end justify-between gap-6 border-b border-white/5 pb-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] drop-shadow-2xl">
                        KLASEMEN <br /> <span class="text-amber-500 italic">PIALA DUNIA 2026</span></h1>
                </div>
            </div>
            <div id="standings-grid"
                class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 2xl:grid-cols-4 gap-6 md:gap-8"></div>
            <div
                class="mt-8 p-3 sm:p-4 bg-white/5 rounded-2xl flex flex-wrap items-center justify-center gap-3 sm:gap-6 text-[9px] sm:text-xs text-center">
                <div class="flex items-center gap-1.5 sm:gap-2">
                    <div class="w-2 h-2 sm:w-3 sm:h-3 rounded-full bg-worldcup-green shadow-md"></div>
                    <span class="text-white font-bold">Peringkat 1 & 2</span>
                    <span class="text-slate-400">→ Lolos ke Knockout Stage (32 Besar)</span>
                </div>
                <div class="flex items-center gap-1.5 sm:gap-2">
                    <div class="w-2 h-2 sm:w-3 sm:h-3 rounded-full bg-yellow-500 shadow-md"></div>
                    <span class="text-white font-bold">8 Peringkat 3 terbaik</span>
                    <span class="text-slate-400">→ Lolos ke Knockout Stage (32 Besar)</span>
                </div>
            </div>
        </div>

        <!-- Schedule -->
        <div id="view-schedule" class="view hidden space-y-8 sm:space-y-12">
            <div class="flex flex-col lg:flex-row lg:items-end justify-between gap-4 border-b border-white/5 pb-6">
                <div class="space-y-2">
                    <h1
                        class="text-4xl sm:text-6xl md:text-7xl font-display font-black text-white tracking-tighter uppercase leading-[0.9]">
                        JADWAL <br /> <span class="text-amber-500 italic">PERTANDINGAN</span></h1>
                </div>
                <p
                    class="max-w-md text-slate-400 text-xs sm:text-sm leading-relaxed font-medium uppercase tracking-tight opacity-70">
                    Pilih tanggal untuk melihat jadwal pertandingan.</p>
            </div>
            <div
                class="sticky top-24 z-20 glass-card p-4 rounded-2xl flex flex-wrap items-center justify-between gap-3">
                <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 stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                            d="M8 7V3m8 4V3m-9 8h10M5 21h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z" />
                    </svg><span class="text-xs font-black text-white uppercase tracking-wider">Pilih Tanggal</span>
                </div>
                <select id="schedule-date-select"
                    class="bg-black/40 border border-white/10 rounded-xl px-4 py-2 text-white text-sm focus:outline-none focus:border-amber-500">
                    <option value="">-- Memuat tanggal --</option>
                </select>
            </div>
            <div id="schedule-container" class="grid gap-5 max-w-4xl mx-auto w-full"></div>
        </div>

        <!-- Knockout -->
        <div id="view-knockout" class="view hidden space-y-12 sm:space-y-20">
            <div class="flex flex-col items-center text-center space-y-4">
                <div class="flex items-center gap-3"><span class="w-12 h-[1px] bg-amber-500"></span><span
                        class="text-[10px] font-black text-amber-500 uppercase tracking-[0.6em]">piala dunia
                        2026</span><span class="w-12 h-[1px] bg-amber-500"></span></div>
                <h2
                    class="text-6xl sm:text-8xl md:text-9xl font-display font-black text-white tracking-tighter uppercase leading-[0.85] drop-shadow-2xl">
                    Babak <span class="text-amber-500 italic">Penyisihan</span></h2>
                <p class="max-w-2xl text-slate-500 text-xs font-black uppercase tracking-[0.4em] opacity-80">Round of 32
                    to Final.</p>
            </div>
            <div id="knockout-container" class="flex overflow-x-auto pb-8 gap-6 snap-x scrollbar-none px-2"></div>
        </div>

        <!-- Teams -->
        <div id="view-teams" class="view hidden space-y-12 sm:space-y-16">
            <?php if (!isset($_SESSION['user_id'])): ?>
                <div class="text-center py-20 sm:py-32 space-y-8 glass-card rounded-[48px] border-amber-500/10">
                    <div class="relative w-24 h-24 mx-auto">
                        <div class="absolute inset-0 bg-amber-500 blur-3xl opacity-20 animate-pulse"></div>
                        <div
                            class="relative w-24 h-24 bg-white/5 rounded-[28px] flex items-center justify-center border border-white/10">
                            <svg class="w-10 h-10 text-amber-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                                    d="M12 15v2m-6 4h12a2 2 0 002-2v-6a2 2 0 00-2-2H6a2 2 0 00-2 2v6a2 2 0 002 2zm10-10V7a4 4 0 00-8 0v4h8z" />
                            </svg>
                        </div>
                    </div>
                    <div class="space-y-3">
                        <h2 class="text-4xl sm:text-5xl font-display font-black uppercase tracking-tighter text-white">
                            Access <span class="text-amber-500">Restricted</span></h2>
                        <p class="text-slate-500 text-[10px] font-black uppercase tracking-[0.6em] max-w-sm mx-auto">Login
                            to view teams.</p>
                    </div>
                    <button onclick="toggleAuthModal()"
                        class="bg-white text-black px-10 py-4 rounded-2xl text-[10px] font-black uppercase tracking-[0.2em] hover:bg-amber-500 transition-all">Daftar
                        / Login</button>
                </div>
            <?php else: ?>
                <div class="relative p-8 sm:p-16 rounded-[48px] border border-white/5 overflow-hidden">
                    <div class="absolute inset-0 bg-[#050a1a]"></div>
                    <div class="absolute top-0 right-0 p-6 opacity-10"><svg class="w-32 h-32 text-white" fill="currentColor"
                            viewBox="0 0 24 24">
                            <path
                                d="M12 21.35l-1.45-1.32C5.4 15.36 2 12.28 2 8.5 2 5.42 4.42 3 7.5 3c1.74 0 3.41.81 4.5 2.09C13.09 3.81 14.76 3 16.5 3 19.58 3 22 5.42 22 8.5c0 3.78-3.4 6.86-8.55 11.54L12 21.35z" />
                        </svg></div>
                    <div class="relative z-10 space-y-6">
                        <h4
                            class="text-4xl sm:text-6xl md:text-7xl font-display font-black text-white leading-[1.1] tracking-tighter uppercase">
                            Tim <span class="text-amber-500 italic">Peserta</span></h4>
                        <div class="flex flex-col md:flex-row md:items-center gap-6 pt-2">
                            <p
                                class="text-xs font-medium text-slate-400 max-w-lg uppercase tracking-[0.2em] leading-relaxed">
                                Daftar seluruh peserta Piala Dunia 2026.</p>
                        </div>
                    </div>
                </div>
                <div id="teams-grid" class="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-6 gap-4 sm:gap-6">
                </div>
            <?php endif; ?>
        </div>

        <style>
            .menu-card {
                background: rgba(255, 255, 255, 0.03);
                backdrop-filter: blur(8px);
                border: 1px solid rgba(255, 255, 255, 0.08);
                border-radius: 2rem;
                padding: 8px 16px;
                transition: all 0.3s ease;
                cursor: pointer;
                min-width: 85px;
                text-align: center;
                position: relative;
                overflow: hidden;
            }

            .menu-card:hover {
                background: rgba(255, 255, 255, 0.08);
                border-color: rgba(255, 255, 255, 0.2);
                transform: translateY(-3px);
            }

            .promosi-card {
                animation: goldGlow 3s infinite ease-in-out;
            }

            .prediksi-card {
                animation: redGlow 3s infinite ease-in-out;
            }

            .chat-card {
                animation: blueGlow 3s infinite ease-in-out;
            }

            @keyframes goldGlow {
                0% {
                    box-shadow: 0 0 3px rgba(245, 158, 11, 0.3), 0 0 5px rgba(245, 158, 11, 0.1);
                    border-color: rgba(245, 158, 11, 0.3);
                }

                50% {
                    box-shadow: 0 0 12px rgba(245, 158, 11, 0.7), 0 0 18px rgba(245, 158, 11, 0.4);
                    border-color: rgba(245, 158, 11, 0.7);
                }

                100% {
                    box-shadow: 0 0 3px rgba(245, 158, 11, 0.3), 0 0 5px rgba(245, 158, 11, 0.1);
                    border-color: rgba(245, 158, 11, 0.3);
                }
            }

            @keyframes redGlow {
                0% {
                    box-shadow: 0 0 3px rgba(239, 68, 68, 0.3), 0 0 5px rgba(239, 68, 68, 0.1);
                    border-color: rgba(239, 68, 68, 0.3);
                }

                50% {
                    box-shadow: 0 0 12px rgba(239, 68, 68, 0.7), 0 0 18px rgba(239, 68, 68, 0.4);
                    border-color: rgba(239, 68, 68, 0.7);
                }

                100% {
                    box-shadow: 0 0 3px rgba(239, 68, 68, 0.3), 0 0 5px rgba(239, 68, 68, 0.1);
                    border-color: rgba(239, 68, 68, 0.3);
                }
            }

            @keyframes blueGlow {
                0% {
                    box-shadow: 0 0 3px rgba(59, 130, 246, 0.3), 0 0 5px rgba(59, 130, 246, 0.1);
                    border-color: rgba(59, 130, 246, 0.3);
                }

                50% {
                    box-shadow: 0 0 12px rgba(59, 130, 246, 0.7), 0 0 18px rgba(59, 130, 246, 0.4);
                    border-color: rgba(59, 130, 246, 0.7);
                }

                100% {
                    box-shadow: 0 0 3px rgba(59, 130, 246, 0.3), 0 0 5px rgba(59, 130, 246, 0.1);
                    border-color: rgba(59, 130, 246, 0.3);
                }
            }

            .promosi-card:hover {
                animation: none;
                box-shadow: 0 0 20px rgba(245, 158, 11, 0.8), 0 0 30px rgba(245, 158, 11, 0.5);
                border-color: #f59e0b;
            }

            .prediksi-card:hover {
                animation: none;
                box-shadow: 0 0 20px rgba(239, 68, 68, 0.8), 0 0 30px rgba(239, 68, 68, 0.5);
                border-color: #ef4444;
            }

            .chat-card:hover {
                animation: none;
                box-shadow: 0 0 20px rgba(59, 130, 246, 0.8), 0 0 30px rgba(59, 130, 246, 0.5);
                border-color: #3b82f6;
            }

            .bottom-nav-item {
                display: flex;
                flex-direction: column;
                align-items: center;
                gap: 4px;
                text-decoration: none;
                font-weight: 900;
            }

            .bottom-nav-item .nav-icon {
                width: 24px;
                height: 24px;
                stroke-width: 1.8;
                transition: all 0.3s cubic-bezier(0.2, 0.9, 0.4, 1.1);
                will-change: transform;
                animation: iconBreathing 3s ease-in-out infinite;
                filter: drop-shadow(0 0 2px rgba(0, 0, 0, 0.3));
            }

            .menu-card:hover .nav-icon {
                transform: scale(1.15) rotate(5deg);
                animation: none;
            }

            @keyframes iconBreathing {
                0% {
                    transform: scale(1);
                }

                50% {
                    transform: scale(1.08);
                }

                100% {
                    transform: scale(1);
                }
            }

            .bottom-nav-item .nav-label {
                font-size: 10px;
                font-weight: 900;
                letter-spacing: 0.05em;
                text-transform: uppercase;
                color: white;
                transition: all 0.2s;
            }

            .menu-card:hover .nav-label {
                letter-spacing: 0.1em;
                text-shadow: 0 0 4px rgba(255, 255, 255, 0.5);
            }

            .nav-promosi .nav-icon {
                stroke: #f59e0b;
            }

            .nav-prediksi .nav-icon {
                stroke: #ef4444;
            }

            .nav-chat .nav-icon {
                stroke: #3b82f6;
            }

            .promosi-card:hover .nav-icon {
                filter: drop-shadow(0 0 6px #f59e0b);
            }

            .prediksi-card:hover .nav-icon {
                filter: drop-shadow(0 0 6px #ef4444);
            }

            .chat-card:hover .nav-icon {
                filter: drop-shadow(0 0 6px #3b82f6);
            }

            @media (min-width: 640px) {
                .bottom-nav-item .nav-icon {
                    width: 20px;
                    height: 20px;
                    animation-duration: 4s;
                }

                .bottom-nav-item .nav-label {
                    font-size: 9px;
                }

                .menu-card {
                    padding: 6px 20px;
                    min-width: 100px;
                }
            }

            @media (max-width: 480px) {
                .menu-card {
                    padding: 6px 10px;
                    min-width: 70px;
                }
            }
        </style>

        <div class="sticky bottom-0 z-40 px-2 sm:px-4 pb-2 sm:pb-4 pt-1 sm:pt-2">
            <div
                class="max-w-7xl mx-auto glass-card rounded-[40px] px-3 sm:px-5 py-1.5 sm:py-2 flex items-center justify-between border-white/[0.05] backdrop-blur-2xl shadow-lg">
                <div class="flex items-center justify-around w-full gap-2 sm:gap-4">
                    <div class="cursor-pointer transition-all duration-300 hover:-translate-y-1"
                        onclick="window.location.href='promosi.php'">
                        <div class="flex flex-col items-center gap-1">
                            <svg class="w-5 h-5 sm:w-6 sm:h-6 stroke-slate-400 hover:stroke-amber-400 transition-all duration-300"
                                fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                                    d="M12 8v13m0-13V6a2 2 0 112 2h-2zm0 0V5.5A2.5 2.5 0 109.5 8H12zm-7 4h14M5 12a2 2 0 110-4h14a2 2 0 110 4M5 12v4a2 2 0 002 2h10a2 2 0 002-2v-4" />
                            </svg>
                            <span
                                class="text-[8px] sm:text-[9px] font-black uppercase tracking-wider text-slate-400 transition-colors">Promosi</span>
                        </div>
                    </div>
                    <div class="cursor-pointer transition-all duration-300 hover:-translate-y-1"
                        onclick="window.location.href='predict.php'">
                        <div class="flex flex-col items-center gap-1">
                            <svg class="w-5 h-5 sm:w-6 sm:h-6 stroke-slate-400 hover:stroke-amber-400 transition-all duration-300"
                                fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                                    d="M9 19v-6a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2a2 2 0 002-2zm0 0V9a2 2 0 012-2h2a2 2 0 012 2v10m-6 0a2 2 0 002 2h2a2 2 0 002-2m0 0V5a2 2 0 012-2h2a2 2 0 012 2v14a2 2 0 01-2 2h-2a2 2 0 01-2-2z" />
                            </svg>
                            <span
                                class="text-[8px] sm:text-[9px] font-black uppercase tracking-wider text-slate-400 transition-colors">Prediksi</span>
                        </div>
                    </div>
                    <div class="cursor-pointer transition-all duration-300 hover:-translate-y-1"
                        onclick="window.open('https://cutt.ly/livechatsakti123', '_blank')">
                        <div class="flex flex-col items-center gap-1">
                            <svg class="w-5 h-5 sm:w-6 sm:h-6 stroke-slate-400 hover:stroke-amber-400 transition-all duration-300"
                                fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                                    d="M8 12h.01M12 12h.01M16 12h.01M21 12c0 4.418-4.03 8-9 8a9.863 9.863 0 01-4.255-.949L3 20l1.395-3.72C3.512 15.042 3 13.574 3 12c0-4.418 4.03-8 9-8s9 3.582 9 8z" />
                            </svg>
                            <span
                                class="text-[8px] sm:text-[9px] font-black uppercase tracking-wider text-slate-400 transition-colors">LIVE
                                CHAT</span>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <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>

        <!-- Auth Modal -->
        <div id="auth-modal"
            class="fixed inset-0 z-[100] hidden items-center justify-center p-6 bg-[#030610]/80 backdrop-blur-2xl transition-opacity duration-500">
            <div
                class="relative w-full max-w-xl glass-card rounded-[48px] border-white/5 p-8 sm:p-12 shadow-2xl overflow-hidden">
                <div class="absolute -top-24 -right-24 w-64 h-64 bg-amber-500/10 blur-[100px] rounded-full"></div>
                <div class="relative z-10 space-y-8">
                    <div class="space-y-3">
                        <div class="flex items-center gap-3"><span class="w-8 h-[1px] bg-amber-500"></span><span
                                class="text-[10px] font-black text-amber-500 uppercase tracking-[0.4em]">Secure
                                Access</span></div>
                        <h3 id="auth-title"
                            class="text-5xl font-display font-black text-white tracking-tighter uppercase leading-[0.9]">
                            MASUK <br /> <span class="text-amber-500 italic">PORTAL</span></h3>
                    </div>
                    <form id="auth-form" class="space-y-6">
                        <div class="space-y-3">
                            <!-- Username -->
                            <input type="text" name="username" placeholder="Username (min 3 chars)" required
                                minlength="3"
                                class="w-full bg-white/[0.02] border border-white/10 rounded-2xl py-5 px-6 text-white outline-none focus:border-amber-500/50">
                            <!-- Note untuk Username (hanya tampil saat daftar) -->
                            <p id="note-username" class="text-[8px] text-slate-400 mt-1 hidden">
                                ⭐ * Username sesuai dengan yang di web (minimal 3 karakter, huruf/angka, tanpa spasi)
                            </p>

                            <!-- Password -->
                            <input type="password" name="password" placeholder="Password (min 6 chars)" required
                                minlength="6"
                                class="w-full bg-white/[0.02] border border-white/10 rounded-2xl py-5 px-6 text-white outline-none focus:border-amber-500/50">

                            <!-- Field Nomor HP (awal tersembunyi) -->
                            <div id="phone-field" class="hidden">
                                <input type="tel" name="phone_number"
                                    placeholder="Nomor HP Aktif (contoh: 08123456789 atau +628123456789)"
                                    class="w-full bg-white/[0.02] border border-white/10 rounded-2xl py-5 px-6 text-white outline-none focus:border-amber-500/50">
                                <!-- Note untuk Nomor HP -->
                                <p id="note-phone" class="text-[8px] text-slate-400 mt-1">
                                    * Username dan Nomor HP aktif sesuai dengan yang di SAKTI123
                                </p>
                            </div>
                        </div>

                        <div id="auth-error" class="text-red-500 text-xs text-center hidden"></div>

                        <button type="submit"
                            class="w-full bg-amber-500 text-black py-5 rounded-2xl font-black uppercase tracking-[0.2em] text-xs hover:bg-amber-400 transition-all"
                            id="auth-submit-btn">MASUK</button>

                        <div class="text-center pt-4 border-t border-white/5">
                            <p id="toggle-auth-mode"
                                class="text-[10px] font-black uppercase tracking-[0.4em] text-slate-400 cursor-pointer hover:text-amber-500 transition-colors">
                                Belum punya akun? Daftar
                            </p>
                            <button type="button" onclick="toggleAuthModal()"
                                class="mt-4 text-[9px] font-bold uppercase tracking-widest text-red-500/40 hover:text-red-500 transition-colors">Tutup</button>
                        </div>
                    </form>
                </div>
            </div>
        </div>

        <!-- Modal Detail Match (untuk prediksi) -->
        <div id="detail-match-modal"
            class="fixed inset-0 z-[200] hidden items-center justify-center p-4 bg-black/80 backdrop-blur-xl transition-all duration-300">
            <div class="relative w-full max-w-2xl glass-card rounded-3xl border border-amber-500/30 overflow-hidden">
                <div class="absolute top-0 right-0 p-4"><button onclick="closeDetailModal()"
                        class="text-slate-400 hover:text-white"><svg class="w-6 h-6" fill="none" stroke="currentColor"
                            viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                                d="M6 18L18 6M6 6l12 12" />
                        </svg></button></div>
                <div class="p-6 sm:p-8 space-y-6">
                    <div class="text-center space-y-2">
                        <div class="text-[10px] font-black text-amber-500 uppercase tracking-[0.4em]">DETAIL
                            PERTANDINGAN
                        </div>
                        <h3 id="modal-match-title" class="text-2xl font-black text-white">- vs -</h3>
                        <p id="modal-match-info" class="text-xs text-slate-400"></p>
                    </div>
                    <div id="modal-prediction-status" class="text-center text-sm text-red-400 hidden"></div>
                    <div class="border-b border-white/10 pb-4">
                        <div class="text-xs font-black text-amber-500 uppercase tracking-wider mb-3">Tim yang lolos ke
                            babak
                            selanjutnya</div>
                        <div class="grid grid-cols-3 gap-3 text-center" id="modal-result-buttons"></div><button
                            id="save-winner-btn"
                            class="w-full mt-3 bg-amber-500/20 hover:bg-amber-500/30 text-amber-400 py-2 rounded-xl font-black uppercase tracking-[0.1em] text-xs">SIMPAN
                            PREDIKSI PEMENANG</button>
                    </div>
                    <div>
                        <div class="text-xs font-black text-amber-500 uppercase tracking-wider mb-3">Prediksi Skor 2 x
                            45
                        </div>
                        <div class="grid grid-cols-2 gap-4">
                            <div><label class="text-xs text-slate-400">Skor Tim 1</label><input type="number"
                                    id="modal-score-home" min="0" step="1"
                                    class="w-full bg-white/5 border border-white/10 rounded-2xl py-3 px-4 text-white text-center text-xl font-mono outline-none focus:border-amber-500"
                                    placeholder="0"></div>
                            <div><label class="text-xs text-slate-400">Skor Tim 2</label><input type="number"
                                    id="modal-score-away" min="0" step="1"
                                    class="w-full bg-white/5 border border-white/10 rounded-2xl py-3 px-4 text-white text-center text-xl font-mono outline-none focus:border-amber-500"
                                    placeholder="0"></div>
                        </div>
                        <p class="text-[8px] text-slate-500 text-center mt-1 italic">* Skor akhir setelah extra
                            time/penalti
                            (jika imbang, pilih pemenang di atas)</p><button id="save-score-btn"
                            class="w-full mt-2 bg-amber-500/20 hover:bg-amber-500/30 text-amber-400 py-2 rounded-xl font-black uppercase tracking-[0.1em] text-xs">SIMPAN
                            PREDIKSI SKOR</button>
                    </div>
                    <p class="text-[9px] text-slate-500 text-center pt-2">* Tiket hanya dikenakan sekali per prediksi
                        (pemenang atau skor). Prediksi tidak dapat diubah setelah disimpan.</p>
                </div>
            </div>
        </div>

        <!-- MODAL DETAIL MATCH (INFORMASI LENGKAP, TANPA PREDIKSI) -->
        <div id="match-detail-modal"
            class="fixed inset-0 z-[250] hidden items-center justify-center p-4 bg-black/80 backdrop-blur-xl transition-all duration-300">
            <div class="relative w-full max-w-2xl glass-card rounded-3xl border border-amber-500/30 overflow-hidden">
                <div class="absolute top-0 right-0 p-4"><button onclick="closeMatchDetailModal()"
                        class="text-slate-400 hover:text-white"><svg class="w-6 h-6" fill="none" stroke="currentColor"
                            viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                                d="M6 18L18 6M6 6l12 12" />
                        </svg></button></div>
                <div class="p-6 sm:p-8 space-y-6">
                    <div class="text-center space-y-2">
                        <div class="text-[10px] font-black text-amber-500 uppercase tracking-[0.4em]">DETAIL
                            PERTANDINGAN
                        </div>
                        <h3 id="detail-match-title" class="text-2xl font-black text-white">- vs -</h3>
                        <p id="detail-match-info" class="text-xs text-slate-400"></p>
                    </div>
                    <div class="grid grid-cols-2 gap-8 border-y border-white/10 py-6">
                        <div class="text-center"><img id="detail-team1-flag" src=""
                                class="w-16 h-12 object-cover rounded-lg mx-auto mb-2">
                            <div class="text-xl font-bold text-white" id="detail-team1-name"></div>
                            <div class="text-3xl font-black text-amber-500 mt-2" id="detail-team1-score">-</div>
                        </div>
                        <div class="text-center"><img id="detail-team2-flag" src=""
                                class="w-16 h-12 object-cover rounded-lg mx-auto mb-2">
                            <div class="text-xl font-bold text-white" id="detail-team2-name"></div>
                            <div class="text-3xl font-black text-amber-500 mt-2" id="detail-team2-score">-</div>
                        </div>
                    </div>
                    <div class="text-center text-sm text-slate-400"><span id="detail-match-status"></span></div>
                    <div class="text-center text-xs text-slate-500"><span id="detail-match-group"></span></div>
                    <button onclick="closeMatchDetailModal()"
                        class="w-full bg-white/10 hover:bg-white/20 text-white py-3 rounded-xl font-black uppercase tracking-wider text-sm">Tutup</button>
                </div>
            </div>
        </div>

        <!-- Group Detail Modal -->
        <div id="group-detail-modal"
            class="fixed inset-0 z-[200] hidden items-center justify-center p-4 bg-black/80 backdrop-blur-xl transition-all duration-300">
            <div class="relative w-full max-w-4xl glass-card rounded-3xl border border-amber-500/30 overflow-hidden">
                <div class="absolute top-0 right-0 p-4"><button onclick="closeGroupDetailModal()"
                        class="text-slate-400 hover:text-white"><svg class="w-6 h-6" fill="none" stroke="currentColor"
                            viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                                d="M6 18L18 6M6 6l12 12" />
                        </svg></button></div>
                <div class="p-6 sm:p-8 space-y-6">
                    <div class="text-center space-y-2">
                        <div class="text-[10px] font-black text-amber-500 uppercase tracking-[0.4em]">Detail Grup</div>
                        <h3 id="group-modal-title" class="text-3xl font-black text-white">Grup A</h3>
                    </div>
                    <div id="group-matches-container" class="overflow-x-auto">
                        <div class="text-center text-slate-400 py-8">Memuat data...</div>
                    </div>
                </div>
            </div>
        </div>

        <!-- POP-UP PROMO -->
        <div id="promoPopup" class="popup-modal">
            <div class="popup-content">
                <div class="close-popup" id="closePopupBtn">&times;</div>
                <img src="https://i.postimg.cc/fWj5YLwf/POP-UP-PIALA-DUNIA-(1).gif" alt="Promo Piala Dunia 2026">
            </div>
        </div>

        <!-- Modal Daftar Pemain (Z-INDEX DIPERBAIKI) -->
        <div id="players-modal"
            class="fixed inset-0 z-[9999] hidden items-center justify-center p-4 bg-black/80 backdrop-blur-xl transition-all duration-300"
            data-close-on-outside="true">
            <div
                class="relative w-full max-w-2xl glass-card rounded-3xl border border-amber-500/30 overflow-hidden max-h-[90vh] flex flex-col">
                <div class="absolute top-0 right-0 p-4"><button onclick="closePlayersModal()"
                        class="text-slate-400 hover:text-white"><svg class="w-6 h-6" fill="none" stroke="currentColor"
                            viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                                d="M6 18L18 6M6 6l12 12" />
                        </svg></button></div>
                <div class="p-6 sm:p-8 overflow-y-auto">
                    <div class="text-center space-y-2 mb-6">
                        <div class="text-[10px] font-black text-amber-500 uppercase tracking-[0.4em]">Skuad Tim</div>
                        <h3 id="players-modal-title" class="text-2xl font-black text-white">-</h3>
                    </div>
                    <div id="players-list-container" class="space-y-6">
                        <div class="text-center text-slate-400 py-8">Memuat data pemain...</div>
                    </div>
                </div>
            </div>
        </div>

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

        <script>
            // ========== FUNGSI YANG DIPERLUKAN UNTUK INDEX ==========
            let currentAuthMode = 'login';
            let currentUser = null;
            let currentIsKnockout = false;
            let currentMatchId = null;
            let currentTeam1Id = null;
            let currentTeam2Id = null;

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

            function closeAllModals() {
                const modalIds = ['detail-match-modal', 'match-detail-modal', 'group-detail-modal', 'players-modal', 'auth-modal'];
                modalIds.forEach(id => {
                    const modal = document.getElementById(id);
                    if (modal) {
                        modal.classList.add('hidden');
                        modal.classList.remove('flex');
                    }
                });
            }

            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, type = 'success') {
                const container = document.getElementById('toast-container');
                if (!container) return;
                const toast = document.createElement('div');
                toast.className = 'toast flex items-center gap-4';
                const icon = type === 'success'
                    ? '<svg class="w-5 h-5 text-amber-500" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7"></path></svg>'
                    : '<svg class="w-5 h-5 text-red-500" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"></path></svg>';
                toast.innerHTML = `<div class="flex items-center gap-3">${icon}<span class="text-sm font-bold text-white">${message}</span></div><button class="ml-4 text-slate-400 hover:text-white transition-colors" onclick="this.parentElement.remove()">✕</button>`;
                container.appendChild(toast);
                setTimeout(() => {
                    if (toast.parentElement) {
                        toast.classList.add('toast-exit');
                        setTimeout(() => toast.remove(), 300);
                    }
                }, 4000);
            }

            function formatDate(dateStr) {
                if (!dateStr) return 'TO BE DETERMINED';
                try {
                    const date = new Date(dateStr);
                    if (isNaN(date.getTime())) return dateStr;
                    return date.toLocaleDateString('en-GB', { day: '2-digit', month: 'short', hour: '2-digit', minute: '2-digit', hour12: false }).toUpperCase();
                } catch (e) { return dateStr; }
            }

            async function fetchUserInfo() {
                try {
                    const res = await fetch('api.php?action=get_user_info');
                    if (res.ok) {
                        currentUser = await res.json();
                        const ticketSide = document.getElementById('ticket-count-side');
                        const pointsSide = document.getElementById('points-count-side');
                        if (ticketSide) ticketSide.innerText = currentUser.tickets;
                        if (pointsSide) pointsSide.innerText = currentUser.available_points || 0;
                        updateClaimBadge();
                    }
                } catch (e) { }
            }

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

            setTimeout(() => {
                if (currentUser) updateClaimBadge();
            }, 500);

            function showView(viewId) {
                closeAllModals();
                const views = document.querySelectorAll('.view');
                const navButtons = document.querySelectorAll('.nav-link, .nav-link-mobile');
                navButtons.forEach(btn => {
                    btn.classList.remove('active');
                    if (btn.id === 'nav-' + viewId) btn.classList.add('active');
                });
                views.forEach(v => {
                    if (!v.classList.contains('hidden')) {
                        v.style.opacity = '0';
                        v.style.transform = 'translateY(-20px)';
                        setTimeout(() => v.classList.add('hidden'), 400);
                    }
                });
                setTimeout(() => {
                    const targetView = document.getElementById('view-' + viewId);
                    if (targetView) {
                        targetView.classList.remove('hidden');
                        void targetView.offsetWidth;
                        targetView.style.opacity = '1';
                        targetView.style.transform = 'translateY(0)';
                        targetView.style.transition = 'all 0.6s cubic-bezier(0.23,1,0.32,1)';
                    }
                }, 450);
                if (viewId === 'standings') loadStandings();
                if (viewId === 'schedule') loadSchedule();
                if (viewId === 'knockout') loadKnockout();
                if (viewId === 'teams') loadTeams();
                window.scrollTo({ top: 0, behavior: 'smooth' });
            }

            async function loadStandings() {
                const res = await fetch('api.php?action=get_standings');
                const data = await res.json();
                const grid = document.getElementById('standings-grid');
                if (!grid) return;
                const matchesRes = await fetch('api.php?action=get_group_matches');
                const allMatches = await matchesRes.json();
                const now = new Date();
                const groupsWithLiveMatches = new Set();
                allMatches.forEach(match => {
                    if (match.match_date && match.is_finished == 0) {
                        const matchDateTime = new Date(match.match_date);
                        if (!isNaN(matchDateTime) && matchDateTime <= now) {
                            groupsWithLiveMatches.add(match.group_id);
                        }
                    }
                });
                grid.innerHTML = data.map(g => {
                    const isLive = groupsWithLiveMatches.has(g.id);
                    const statusColor = isLive ? 'bg-red-500' : 'bg-yellow-500';
                    const statusText = isLive ? 'LIVE' : 'Coming Soon';
                    const textColor = isLive ? 'text-red-500 live-text' : 'text-yellow-500';
                    return `<div class="glass-card rounded-[32px] sm:rounded-[48px] p-6 sm:p-8 hover:border-amber-500/30 group relative overflow-hidden cursor-pointer" data-group-id="${g.id}" data-group-name="${g.name}" onclick="showGroupDetail(${g.id}, '${g.name}')">
                    <div class="absolute top-0 right-0 p-4 opacity-[0.03] group-hover:opacity-[0.08] transition-all duration-1000"><span class="text-7xl font-display font-black">${g.name}</span></div>
                    <div class="relative z-10">
                        <div class="flex flex-wrap items-center justify-between gap-3 mb-6">
                            <div class="space-y-1"><div class="flex items-center gap-2"><span class="w-4 h-[1px] bg-amber-500/40"></span><span class="text-[8px] font-black text-amber-500 uppercase tracking-[0.4em]"></span></div><h3 class="text-2xl font-display font-black text-white tracking-tighter uppercase leading-none">Grup ${g.name}</h3></div>
                            <div class="flex items-center gap-2 flex-shrink-0"><span class="text-[9px] font-black uppercase tracking-wider whitespace-nowrap ${textColor}">${statusText}</span><div class="w-8 h-8 sm:w-10 sm:h-10 rounded-2xl bg-white/5 border border-white/10 flex items-center justify-center"><div class="w-2 h-2 rounded-full ${statusColor} ${isLive ? 'live-dot' : 'animate-pulse'}"></div></div></div>
                        </div>
                        <div class="overflow-x-auto"><table class="w-full text-[10px] sm:text-xs"><thead><tr class="border-b border-white/10 text-slate-500 font-black uppercase tracking-wider"><th class="text-left py-2 pl-2">Tim</th><th class="text-center px-1">MP</th><th class="text-center px-1">W</th><th class="text-center px-1">D</th><th class="text-center px-1">L</th><th class="text-center px-1">GF</th><th class="text-center px-1">GA</th><th class="text-center px-1">GD</th><th class="text-center px-1">Pts</th></tr></thead><tbody>${g.teams.map((t, idx) => {
                        const gd = t.goals_for - t.goals_against;
                        let circleColor = '';
                        if (idx < 2) circleColor = 'bg-worldcup-green';
                        else if (idx === 2) circleColor = 'bg-yellow-500';
                        return `<tr class="border-b border-white/5 hover:bg-white/5"><td class="py-2 pl-2"><div class="flex items-center gap-2"><div class="relative"><img src="${t.flag_url}" class="w-6 h-4 object-cover rounded shadow">${circleColor ? `<div class="absolute -top-1 -right-1 w-2 h-2 ${circleColor} rounded-full border border-[#030610]"></div>` : ''}</div><span class="font-bold text-slate-200 truncate max-w-[100px]">${escapeHtml(t.name)}</span></div></td><td class="text-center font-mono">${t.played}</td><td class="text-center font-mono text-worldcup-green">${t.won}</td><td class="text-center font-mono text-amber-500">${t.drawn}</td><td class="text-center font-mono text-worldcup-red">${t.lost}</td><td class="text-center font-mono">${t.goals_for}</td><td class="text-center font-mono">${t.goals_against}</td><td class="text-center font-mono ${gd >= 0 ? 'text-worldcup-green' : 'text-worldcup-red'}">${gd > 0 ? '+' : ''}${gd}</td><td class="text-center font-black ${idx < 2 ? 'text-amber-500' : 'text-white'}">${t.points}${t.points === null ? 0 : ''}</td></tr>`;
                    }).join('')}</tbody></table></div>
                    </div>
                </div>`;
                }).join('');
            }

            async function loadSchedule() {
                if (!currentUser) await fetchUserInfo();
                const res = await fetch('api.php?action=get_group_matches');
                let data = await res.json();
                data = data.filter(m => m.match_date);
                const allDates = [...new Set(data.map(m => m.match_date.substring(0, 10)))].sort();
                const dateSelect = document.getElementById('schedule-date-select');
                if (!dateSelect) return;
                if (allDates.length === 0) {
                    dateSelect.innerHTML = '<option value="">Tidak ada jadwal</option>';
                    document.getElementById('schedule-container').innerHTML = '<div class="text-center py-10 text-slate-500">Belum ada jadwal pertandingan.</div>';
                    return;
                }
                let options = '<option value="">-- Pilih Tanggal --</option>';
                allDates.forEach(date => {
                    const formatted = new Date(date).toLocaleDateString('id-ID', { weekday: 'long', day: 'numeric', month: 'long', year: 'numeric' });
                    options += `<option value="${date}">${formatted}</option>`;
                });
                dateSelect.innerHTML = options;
                async function renderMatchesForDate(selectedDate) {
                    const container = document.getElementById('schedule-container');
                    if (!selectedDate) {
                        container.innerHTML = '<div class="text-center py-10 text-slate-500">Silakan pilih tanggal untuk melihat jadwal.</div>';
                        return;
                    }
                    const matches = data.filter(m => m.match_date.substring(0, 10) === selectedDate);
                    if (matches.length === 0) {
                        container.innerHTML = '<div class="text-center py-10 text-slate-500">Tidak ada pertandingan pada tanggal ini.</div>';
                        return;
                    }
                    let html = '';
                    for (const m of matches) {
                        const matchDateTime = new Date(m.match_date);
                        const time = matchDateTime.toLocaleTimeString('id-ID', { hour: '2-digit', minute: '2-digit', hour12: false });
                        html += `<div class="glass-card p-5 rounded-3xl flex flex-col gap-3 group hover:border-amber-500/20 relative overflow-hidden">
                        <div class="flex items-center justify-between">
                            <div class="flex flex-col items-start gap-1 w-2/5"><span class="text-[8px] font-black text-slate-500 uppercase tracking-wider">HOME</span><div class="flex items-center gap-2 w-full"><div class="w-12 h-8 rounded-lg overflow-hidden bg-white/5 flex-shrink-0"><img src="${m.team1_flag}" class="w-full h-full object-cover" loading="lazy"></div><span class="text-xs font-bold text-white truncate">${escapeHtml(m.team1_name)}</span></div></div>
                            <div class="text-center min-w-[70px]">${m.is_finished == 1 ? `<div class="bg-black/50 px-3 py-1 rounded-full"><span class="text-xl font-black text-white">${m.team1_score}</span><span class="text-xs text-slate-400 mx-1">-</span><span class="text-xl font-black text-white">${m.team2_score}</span></div>` : `<span class="text-2xl font-black text-amber-500">VS</span>`}</div>
                            <div class="flex flex-col items-end gap-1 w-2/5"><span class="text-[8px] font-black text-slate-500 uppercase tracking-wider">AWAY</span><div class="flex items-center gap-2 justify-end w-full"><span class="text-xs font-bold text-white truncate text-right">${escapeHtml(m.team2_name)}</span><div class="w-12 h-8 rounded-lg overflow-hidden bg-white/5 flex-shrink-0"><img src="${m.team2_flag}" class="w-full h-full object-cover" loading="lazy"></div></div></div>
                        </div>
                        <div class="flex items-center justify-between text-[10px] text-slate-400 pt-1 border-t border-white/10">
                            <div class="flex items-center gap-1"><svg class="w-3 h-3" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z"/></svg><span class="font-mono">${time} WIB</span></div>
                            <div class="bg-white/5 px-2 py-0.5 rounded-full text-[9px] font-bold">Grup ${escapeHtml(m.group_name)}</div>
                        </div>
                        <div class="flex gap-2 mt-2">
                            <button class="detail-match-btn bg-white/10 hover:bg-white/20 text-white px-3 py-1 rounded-full text-[9px] font-black uppercase tracking-wider"
                                data-id="${m.id}"
                                data-team1="${escapeHtml(m.team1_name).replace(/'/g, "\\'")}"
                                data-team2="${escapeHtml(m.team2_name).replace(/'/g, "\\'")}"
                                data-date="${m.match_date}"
                                data-team1-id="${m.team1_id}"
                                data-team2-id="${m.team2_id}"
                                data-group="${escapeHtml(m.group_name)}"
                                data-score1="${m.team1_score}"
                                data-score2="${m.team2_score}"
                                data-finished="${m.is_finished}"
                                data-flag1="${m.team1_flag}"
                                data-flag2="${m.team2_flag}">
                                📋 Detail
                            </button>
                            <a href="predict.php?match_id=${m.id}&type=group" 
                               class="bg-amber-500/20 hover:bg-amber-500/30 text-amber-400 px-3 py-1 rounded-full text-[9px] font-black uppercase tracking-wider inline-block text-center">
                                🎯 Prediksi
                            </a>
                        </div>
                    </div>`;
                    }
                    container.innerHTML = html;
                }
                dateSelect.onchange = () => { renderMatchesForDate(dateSelect.value); };
                if (allDates.length > 0) {
                    dateSelect.value = allDates[0];
                    renderMatchesForDate(allDates[0]);
                }
            }

            document.getElementById('schedule-container')?.addEventListener('click', function (e) {
                const detailBtn = e.target.closest('.detail-match-btn');
                if (detailBtn) {
                    const id = detailBtn.dataset.id;
                    const team1 = detailBtn.dataset.team1;
                    const team2 = detailBtn.dataset.team2;
                    const date = detailBtn.dataset.date;
                    const team1Id = detailBtn.dataset.team1Id;
                    const team2Id = detailBtn.dataset.team2Id;
                    const group = detailBtn.dataset.group;
                    const score1 = detailBtn.dataset.score1;
                    const score2 = detailBtn.dataset.score2;
                    const finished = detailBtn.dataset.finished;
                    const flag1 = detailBtn.dataset.flag1;
                    const flag2 = detailBtn.dataset.flag2;
                    openMatchDetailModal(id, team1, team2, date, team1Id, team2Id, group, score1, score2, finished, flag1, flag2);
                }
            });

            function openMatchDetailModal(matchId, team1Name, team2Name, matchDate, team1Id, team2Id, groupName, team1Score, team2Score, isFinished, team1Flag, team2Flag) {
                document.getElementById('detail-match-title').innerHTML = `${escapeHtml(team1Name)} <span class="text-amber-500">VS</span> ${escapeHtml(team2Name)}`;
                const formattedDate = new Date(matchDate).toLocaleString('id-ID', { weekday: 'long', day: 'numeric', month: 'long', year: 'numeric', hour: '2-digit', minute: '2-digit' });
                document.getElementById('detail-match-info').innerHTML = formattedDate;
                document.getElementById('detail-team1-name').innerText = team1Name;
                document.getElementById('detail-team2-name').innerText = team2Name;
                document.getElementById('detail-team1-flag').src = team1Flag;
                document.getElementById('detail-team2-flag').src = team2Flag;
                if (isFinished == 1) {
                    document.getElementById('detail-team1-score').innerText = team1Score;
                    document.getElementById('detail-team2-score').innerText = team2Score;
                    document.getElementById('detail-match-status').innerHTML = '<span class="text-worldcup-green">✔ Pertandingan telah selesai</span>';
                } else {
                    document.getElementById('detail-team1-score').innerText = '?';
                    document.getElementById('detail-team2-score').innerText = '?';
                    document.getElementById('detail-match-status').innerHTML = '<span class="text-yellow-500">⏳ Pertandingan belum dimulai</span>';
                }
                document.getElementById('detail-match-group').innerHTML = `Grup ${escapeHtml(groupName)}`;
                document.getElementById('match-detail-modal').classList.remove('hidden');
                document.getElementById('match-detail-modal').classList.add('flex');
            }

            function closeMatchDetailModal() {
                document.getElementById('match-detail-modal').classList.add('hidden');
                document.getElementById('match-detail-modal').classList.remove('flex');
            }

            async function loadKnockout() {
                if (!currentUser) await fetchUserInfo();
                const res = await fetch('api.php?action=get_knockout');
                const matches = await res.json();
                let myPredictions = { group: [], knockout: [] };
                if (currentUser) myPredictions = await (await fetch('api.php?action=get_my_predictions')).json();
                const matchMap = {};
                matches.forEach(m => { matchMap[m.id] = m; });
                const leftR32Ids = [74, 77, 73, 75, 83, 84, 81, 82];
                const rightR32Ids = [76, 78, 79, 80, 86, 88, 85, 87];
                const leftR16Ids = [89, 90, 93, 94];
                const rightR16Ids = [91, 92, 95, 96];
                const leftQFIds = [97, 98];
                const rightQFIds = [99, 100];
                const sfLeftId = 101;
                const sfRightId = 102;
                const finalId = 104;
                const thirdId = 103;
                const getMatch = (id) => matchMap[id] || null;
                const leftR32 = leftR32Ids.map(id => getMatch(id)).filter(m => m);
                const rightR32 = rightR32Ids.map(id => getMatch(id)).filter(m => m);
                const leftR16 = leftR16Ids.map(id => getMatch(id)).filter(m => m);
                const rightR16 = rightR16Ids.map(id => getMatch(id)).filter(m => m);
                const leftQF = leftQFIds.map(id => getMatch(id)).filter(m => m);
                const rightQF = rightQFIds.map(id => getMatch(id)).filter(m => m);
                const sfLeft = getMatch(sfLeftId);
                const sfRight = getMatch(sfRightId);
                const finalMatch = getMatch(finalId);
                const thirdMatch = getMatch(thirdId);
                const leftCols = [leftR32, leftR16, leftQF, sfLeft ? [sfLeft] : []];
                const rightCols = [rightR32, rightR16, rightQF, sfRight ? [sfRight] : []];
                const finalCol = [finalMatch, thirdMatch].filter(m => m);
                function renderMatch(match) {
                    if (!match) return '';
                    const team1Display = match.team1_name || match.team1_code || '?';
                    const team2Display = match.team2_name || match.team2_code || '?';
                    const team1Flag = match.team1_flag || '';
                    const team2Flag = match.team2_flag || '';
                    const pred = myPredictions.knockout.find(p => p.match_id == match.id);
                    const winnerId = pred?.winner_id;
                    const isFinished = match.is_finished == 1;
                    let scoreHtml = '';
                    if (isFinished) {
                        let normal1 = (match.team1_score_normal !== null) ? match.team1_score_normal : match.team1_score;
                        let normal2 = (match.team2_score_normal !== null) ? match.team2_score_normal : match.team2_score;
                        let final1 = match.team1_score;
                        let final2 = match.team2_score;
                        let extension = match.match_extension || 'none';
                        let isDrawNormal = (normal1 === normal2);
                        if (!isDrawNormal) {
                            scoreHtml = `<div class="score">${normal1} - ${normal2}</div>`;
                        } else {
                            let extraInfo = '';
                            if (extension === 'et') extraInfo = ` (${normal1} - ${normal2} ET)`;
                            else if (extension === 'pen') extraInfo = ` (${normal1} - ${normal2} pen)`;
                            else extraInfo = ` (${normal1} - ${normal2})`;
                            scoreHtml = `<div class="score">${final1} - ${final2}${extraInfo}</div>`;
                        }
                    }
                    const flagImg = (flagUrl) => flagUrl ? `<img src="${flagUrl}" class="w-5 h-3 inline-block mr-1 rounded shadow" onerror="this.style.display='none'">` : '';
                    return `<div class="bracket-match cursor-pointer" data-id="${match.id}" onclick="openKnockoutDetailModal(${match.id}, '${escapeHtml(team1Display)}', '${escapeHtml(team2Display)}', '${match.match_date}', ${match.team1_id || 0}, ${match.team2_id || 0})">
                    <div class="teams"><div class="team ${winnerId == match.team1_id ? 'bg-amber-500/30' : ''}">${flagImg(team1Flag)} ${escapeHtml(team1Display)}</div><div class="vs">VS</div><div class="team ${winnerId == match.team2_id ? 'bg-amber-500/30' : ''}">${flagImg(team2Flag)} ${escapeHtml(team2Display)}</div></div>
                    ${scoreHtml}<div class="match-date">${formatDate(match.match_date)}</div>
                </div>`;
                }
                let bracketHtml = `<div class="bracket-container"><div class="bracket">`;
                leftCols.forEach(col => { bracketHtml += `<div class="bracket-column" style="gap: ${col.length > 0 ? (col.length > 4 ? '20px' : '30px') : '20px'};">${col.map(m => renderMatch(m)).join('')}</div>`; });
                bracketHtml += `<div class="bracket-column final-column">${finalCol.map(m => renderMatch(m)).join('')}</div>`;
                rightCols.reverse().forEach(col => { bracketHtml += `<div class="bracket-column" style="gap: ${col.length > 0 ? (col.length > 4 ? '20px' : '30px') : '20px'};">${col.map(m => renderMatch(m)).join('')}</div>`; });
                bracketHtml += `</div></div>`;
                document.getElementById('knockout-container').innerHTML = bracketHtml;
            }

            function openKnockoutDetailModal(matchId, team1Name, team2Name, matchDate, team1Id, team2Id) {
                if (!currentUser) { showNotification('Silakan login terlebih dahulu', 'error'); return; }
                currentIsKnockout = true;
                currentMatchId = matchId;
                currentTeam1Id = team1Id;
                currentTeam2Id = team2Id;
                document.getElementById('modal-match-title').innerHTML = `${escapeHtml(team1Name)} <span class="text-amber-500">VS</span> ${escapeHtml(team2Name)}`;
                const formattedDate = new Date(matchDate).toLocaleString('id-ID', { weekday: 'long', day: 'numeric', month: 'long', year: 'numeric', hour: '2-digit', minute: '2-digit' });
                document.getElementById('modal-match-info').innerHTML = formattedDate;
                const btnContainer = document.getElementById('modal-result-buttons');
                btnContainer.innerHTML = `<button data-winner-id="${team1Id}" class="py-3 rounded-xl bg-white/5 text-slate-400 hover:bg-white/10 transition text-sm font-black uppercase">${escapeHtml(team1Name)}</button><button data-winner-id="${team2Id}" class="py-3 rounded-xl bg-white/5 text-slate-400 hover:bg-white/10 transition text-sm font-black uppercase">${escapeHtml(team2Name)}</button>`;
                btnContainer.classList.remove('grid-cols-3');
                btnContainer.classList.add('grid-cols-2');
                btnContainer.querySelectorAll('button').forEach(btn => {
                    btn.addEventListener('click', function () {
                        btnContainer.querySelectorAll('button').forEach(b => { b.classList.remove('bg-amber-500', 'text-black'); b.classList.add('bg-white/5', 'text-slate-400'); });
                        this.classList.remove('bg-white/5', 'text-slate-400');
                        this.classList.add('bg-amber-500', 'text-black');
                    });
                });
                const statusDiv = document.getElementById('modal-prediction-status');
                const winnerBtn = document.getElementById('save-winner-btn');
                const scoreHome = document.getElementById('modal-score-home');
                const scoreAway = document.getElementById('modal-score-away');
                const saveScoreBtn = document.getElementById('save-score-btn');
                winnerBtn.disabled = false;
                winnerBtn.classList.remove('opacity-50', 'cursor-not-allowed');
                scoreHome.disabled = false;
                scoreHome.classList.remove('opacity-50', 'cursor-not-allowed');
                scoreAway.disabled = false;
                scoreAway.classList.remove('opacity-50', 'cursor-not-allowed');
                saveScoreBtn.disabled = false;
                saveScoreBtn.classList.remove('opacity-50', 'cursor-not-allowed');
                scoreHome.value = '';
                scoreAway.value = '';
                if (statusDiv) statusDiv.classList.add('hidden');
                fetch('api.php?action=get_my_predictions').then(res => res.json()).then(data => {
                    const existing = data.knockout.find(p => p.match_id == matchId);
                    if (existing) {
                        if (existing.winner_id !== null && existing.winner_id !== undefined && existing.winner_id != 0) {
                            btnContainer.querySelectorAll('button').forEach(btn => { if (btn.getAttribute('data-winner-id') == existing.winner_id) { btn.classList.remove('bg-white/5', 'text-slate-400'); btn.classList.add('bg-amber-500', 'text-black'); } });
                            winnerBtn.disabled = true;
                            winnerBtn.classList.add('opacity-50', 'cursor-not-allowed');
                        }
                        if (existing.team1_score_pred !== null && existing.team2_score_pred !== null) {
                            scoreHome.disabled = true;
                            scoreHome.classList.add('opacity-50', 'cursor-not-allowed');
                            scoreAway.disabled = true;
                            scoreAway.classList.add('opacity-50', 'cursor-not-allowed');
                            saveScoreBtn.disabled = true;
                            saveScoreBtn.classList.add('opacity-50', 'cursor-not-allowed');
                            scoreHome.value = existing.team1_score_pred;
                            scoreAway.value = existing.team2_score_pred;
                        }
                        if (existing.winner_id !== null && existing.winner_id != 0 && (existing.team1_score_pred !== null && existing.team2_score_pred !== null)) {
                            statusDiv.classList.remove('hidden');
                            statusDiv.innerText = '⚠️ Anda sudah memprediksi keduanya. Prediksi tidak dapat diubah.';
                        } else if (existing.winner_id !== null && existing.winner_id != 0 && (existing.team1_score_pred === null || existing.team2_score_pred === null)) {
                            statusDiv.classList.remove('hidden');
                            statusDiv.innerText = '✅ Anda sudah memprediksi pemenang. Anda masih bisa memprediksi skor.';
                        } else if ((existing.winner_id === null || existing.winner_id === 0) && (existing.team1_score_pred !== null && existing.team2_score_pred !== null)) {
                            statusDiv.classList.remove('hidden');
                            statusDiv.innerText = '✅ Anda sudah memprediksi skor. Anda masih bisa memprediksi pemenang.';
                        }
                    }
                });
                document.getElementById('detail-match-modal').classList.remove('hidden');
                document.getElementById('detail-match-modal').classList.add('flex');
            }

            async function loadTeams() {
                const [teamsRes] = await Promise.all([fetch('api.php?action=get_teams')]);
                const teams = await teamsRes.json();
                const grid = document.getElementById('teams-grid');
                if (!grid) return;
                grid.innerHTML = teams.map(t => `<div class="glass-card p-6 rounded-3xl flex flex-col items-center gap-3 transition-all cursor-pointer team-card" data-team-id="${t.id}" data-team-name="${escapeHtml(t.name)}"><div class="w-16 h-12 rounded-xl overflow-hidden shadow-lg"><img src="${t.flag_url}" class="w-full h-full object-cover"></div><span class="text-[10px] font-black text-white uppercase tracking-wider">${escapeHtml(t.name)}</span></div>`).join('');
                document.querySelectorAll('.team-card').forEach(card => {
                    card.addEventListener('click', (e) => {
                        const teamId = card.getAttribute('data-team-id');
                        const teamName = card.getAttribute('data-team-name');
                        showPlayersModal(teamId, teamName);
                    });
                });
            }

            async function showPlayersModal(teamId, teamName) {
                closeAllModals();
                const modal = document.getElementById('players-modal');
                const title = document.getElementById('players-modal-title');
                const container = document.getElementById('players-list-container');
                title.innerText = teamName;
                container.innerHTML = '<div class="text-center py-8"><div class="inline-block animate-spin rounded-full h-8 w-8 border-b-2 border-amber-500"></div></div>';
                modal.classList.remove('hidden');
                modal.classList.add('flex');
                try {
                    const res = await fetch(`api.php?action=get_players&team_id=${teamId}`);
                    if (!res.ok) throw new Error('Gagal memuat pemain');
                    const data = await res.json();
                    const players = data.players;
                    const coach = data.coach || 'Belum ditentukan';
                    if (!players || players.length === 0) {
                        container.innerHTML = `<div class="text-center py-8 text-slate-400"><div class="mb-2 text-amber-500">Pelatih: ${escapeHtml(coach)}</div>Belum ada data pemain untuk tim ini.</div>`;
                        return;
                    }
                    const grouped = { goalkeeper: [], defender: [], midfielder: [], forward: [] };
                    players.forEach(p => { grouped[p.position].push(p); });
                    const positionLabels = { goalkeeper: '🧤 Penjaga Gawang', defender: '🛡️ Bek', midfielder: '⚙️ Gelandang', forward: '⚽ Penyerang' };
                    let html = `<div class="mb-6 text-center border-b border-white/10 pb-4"><div class="text-xs font-black text-amber-500 uppercase tracking-wider">Pelatih Kepala</div><div class="text-xl font-bold text-white">${escapeHtml(coach)}</div></div>`;
                    for (const [pos, label] of Object.entries(positionLabels)) {
                        if (grouped[pos].length > 0) {
                            html += `<div class="mb-4"><h4 class="text-sm font-black text-amber-500 uppercase tracking-wider mb-2">${label}</h4><div class="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-2 md:gap-3">`;
                            grouped[pos].forEach(player => {
                                html += `<div class="bg-white/5 rounded-xl p-2 text-center hover:bg-white/10 transition-all hover:scale-[1.02]"><div class="text-sm font-bold text-white truncate">${escapeHtml(player.name)}</div><div class="text-[9px] text-slate-400">#${player.jersey_number || '-'}</div></div>`;
                            });
                            html += `</div></div>`;
                        }
                    }
                    container.innerHTML = html;
                } catch (err) {
                    console.error(err);
                    container.innerHTML = '<div class="text-center py-8 text-red-400">Gagal memuat data pemain.</div>';
                }
            }

            function closePlayersModal() {
                const modal = document.getElementById('players-modal');
                modal.classList.add('hidden');
                modal.classList.remove('flex');
            }

            function toggleAuthModal() {
                const modal = document.getElementById('auth-modal');
                modal.classList.toggle('hidden');
                modal.classList.toggle('flex');
                if (modal.classList.contains('flex')) {
                    document.body.classList.add('modal-open');
                } else {
                    document.body.classList.remove('modal-open');
                }
            }

            function toggleAuthMode() {
                currentAuthMode = currentAuthMode === 'login' ? 'register' : 'login';
                const title = document.getElementById('auth-title');
                const phoneField = document.getElementById('phone-field');
                const submitBtn = document.getElementById('auth-submit-btn');
                const toggleText = document.getElementById('toggle-auth-mode');
                if (currentAuthMode === 'login') {
                    title.innerHTML = 'MASUK <br/>AKUN';
                    phoneField.classList.add('hidden');
                    submitBtn.innerText = 'MASUK';
                    toggleText.innerHTML = 'Belum punya akun? Daftar';
                } else {
                    title.innerHTML = 'DAFTAR <br/>BARU';
                    phoneField.classList.remove('hidden');
                    submitBtn.innerText = 'DAFTAR';
                    toggleText.innerHTML = 'Sudah punya akun? Login';
                }
            }

            function closeGroupDetailModal() {
                document.getElementById('group-detail-modal').classList.add('hidden');
                document.getElementById('group-detail-modal').classList.remove('flex');
            }

            async function showGroupDetail(groupId, groupName) {
                const modal = document.getElementById('group-detail-modal');
                document.getElementById('group-modal-title').innerText = `Grup ${groupName}`;
                modal.classList.remove('hidden');
                modal.classList.add('flex');
                const container = document.getElementById('group-matches-container');
                container.innerHTML = '<div class="text-center py-8"><div class="inline-block animate-spin rounded-full h-8 w-8 border-b-2 border-amber-500"></div></div>';
                try {
                    const res = await fetch('api.php?action=get_group_matches');
                    const allMatches = await res.json();
                    const groupMatches = allMatches.filter(m => m.group_id == groupId);
                    if (groupMatches.length === 0) {
                        container.innerHTML = '<div class="text-center py-8 text-slate-400">Belum ada jadwal untuk grup ini.</div>';
                        return;
                    }
                    let html = `<div class="overflow-x-auto"><table class="w-full text-sm border-collapse"><thead class="border-b border-white/10"><tr class="text-[10px] font-black text-amber-500 uppercase tracking-wider"><th class="py-3 text-left">TIM 1</th><th class="py-3 text-center">SKOR</th><th class="py-3 text-left">TIM 2</th><th class="py-3 text-center">TANGGAL</th></tr></thead><tbody>`;
                    for (const m of groupMatches) {
                        let dateStr = 'TBD';
                        if (m.match_date) {
                            const date = new Date(m.match_date);
                            if (!isNaN(date.getTime())) {
                                const day = date.getDate();
                                const month = date.toLocaleString('id-ID', { month: 'short' }).replace('.', '');
                                const hour = date.getHours().toString().padStart(2, '0');
                                const minute = date.getMinutes().toString().padStart(2, '0');
                                dateStr = `${day} ${month}, ${hour}.${minute}`;
                            } else { dateStr = m.match_date; }
                        }
                        const isFinished = m.is_finished == 1;
                        const scoreDisplay = isFinished ? `${m.team1_score} - ${m.team2_score}` : 'vs';
                        html += `<tr class="border-b border-white/5 hover:bg-white/5"><td class="py-3"><div class="flex items-center gap-2"><img src="${m.team1_flag}" class="w-6 h-4 object-cover rounded" onerror="this.style.display='none'"><span>${escapeHtml(m.team1_name)}</span></div></td><td class="py-3 text-center font-mono font-bold text-base whitespace-nowrap">${scoreDisplay}</td><td class="py-3"><div class="flex items-center gap-2"><img src="${m.team2_flag}" class="w-6 h-4 object-cover rounded" onerror="this.style.display='none'"><span>${escapeHtml(m.team2_name)}</span></div></td><td class="py-3 text-center text-xs whitespace-nowrap">${dateStr}</td></tr>`;
                    }
                    html += `</tbody></table><div class="mt-6 text-center"><a href="predict.php" class="inline-block bg-amber-500 text-black px-6 py-3 rounded-xl font-black uppercase tracking-wider text-sm hover:bg-amber-400 transition-all">🎯 Prediksi Sekarang</a></div>`;
                    container.innerHTML = html;
                } catch (err) {
                    container.innerHTML = '<div class="text-center py-8 text-red-400">Gagal memuat data pertandingan.</div>';
                }
            }

            function openDetailModal(matchId, team1Name, team2Name, matchDate, team1Id, team2Id) {
                if (!currentUser) { showNotification('Silakan login terlebih dahulu', 'error'); return; }
                currentIsKnockout = false;
                currentMatchId = matchId;
                currentTeam1Id = team1Id;
                currentTeam2Id = team2Id;
                document.getElementById('modal-match-title').innerHTML = `${escapeHtml(team1Name)} <span class="text-amber-500">VS</span> ${escapeHtml(team2Name)}`;
                const formattedDate = new Date(matchDate).toLocaleString('id-ID', { weekday: 'long', day: 'numeric', month: 'long', year: 'numeric', hour: '2-digit', minute: '2-digit' });
                document.getElementById('modal-match-info').innerHTML = formattedDate;
                const btnContainer = document.getElementById('modal-result-buttons');
                btnContainer.innerHTML = `<button data-value="home_win" class="py-3 rounded-xl bg-white/5 text-slate-400 hover:bg-white/10 transition text-sm font-black uppercase">HOME WIN</button><button data-value="draw" class="py-3 rounded-xl bg-white/5 text-slate-400 hover:bg-white/10 transition text-sm font-black uppercase">DRAW</button><button data-value="away_win" class="py-3 rounded-xl bg-white/5 text-slate-400 hover:bg-white/10 transition text-sm font-black uppercase">AWAY WIN</button>`;
                btnContainer.classList.add('grid-cols-3');
                btnContainer.querySelectorAll('button').forEach(btn => {
                    btn.addEventListener('click', function () {
                        btnContainer.querySelectorAll('button').forEach(b => { b.classList.remove('bg-amber-500', 'text-black'); b.classList.add('bg-white/5', 'text-slate-400'); });
                        this.classList.remove('bg-white/5', 'text-slate-400');
                        this.classList.add('bg-amber-500', 'text-black');
                    });
                });
                const statusDiv = document.getElementById('modal-prediction-status');
                const winnerBtn = document.getElementById('save-winner-btn');
                const scoreHome = document.getElementById('modal-score-home');
                const scoreAway = document.getElementById('modal-score-away');
                const saveScoreBtn = document.getElementById('save-score-btn');
                winnerBtn.disabled = false;
                winnerBtn.classList.remove('opacity-50', 'cursor-not-allowed');
                scoreHome.disabled = false;
                scoreHome.classList.remove('opacity-50', 'cursor-not-allowed');
                scoreAway.disabled = false;
                scoreAway.classList.remove('opacity-50', 'cursor-not-allowed');
                saveScoreBtn.disabled = false;
                saveScoreBtn.classList.remove('opacity-50', 'cursor-not-allowed');
                scoreHome.value = '';
                scoreAway.value = '';
                if (statusDiv) statusDiv.classList.add('hidden');
                fetch('api.php?action=get_my_predictions').then(res => res.json()).then(data => {
                    const existing = data.group.find(p => p.match_id == matchId);
                    if (existing) {
                        if (existing.result_type) {
                            btnContainer.querySelectorAll('button').forEach(btn => { if (btn.getAttribute('data-value') === existing.result_type) { btn.classList.remove('bg-white/5', 'text-slate-400'); btn.classList.add('bg-amber-500', 'text-black'); } });
                            winnerBtn.disabled = true;
                            winnerBtn.classList.add('opacity-50', 'cursor-not-allowed');
                        }
                        if (existing.team1_score_pred !== null && existing.team2_score_pred !== null) {
                            scoreHome.disabled = true;
                            scoreHome.classList.add('opacity-50', 'cursor-not-allowed');
                            scoreAway.disabled = true;
                            scoreAway.classList.add('opacity-50', 'cursor-not-allowed');
                            saveScoreBtn.disabled = true;
                            saveScoreBtn.classList.add('opacity-50', 'cursor-not-allowed');
                            scoreHome.value = existing.team1_score_pred;
                            scoreAway.value = existing.team2_score_pred;
                        }
                        if (existing.result_type && (existing.team1_score_pred !== null && existing.team2_score_pred !== null)) {
                            statusDiv.classList.remove('hidden');
                            statusDiv.innerText = '⚠️ Anda sudah memprediksi keduanya. Prediksi tidak dapat diubah.';
                        } else if (existing.result_type && (existing.team1_score_pred === null || existing.team2_score_pred === null)) {
                            statusDiv.classList.remove('hidden');
                            statusDiv.innerText = '✅ Anda sudah memprediksi pemenang. Anda masih bisa memprediksi skor.';
                        } else if ((!existing.result_type) && (existing.team1_score_pred !== null && existing.team2_score_pred !== null)) {
                            statusDiv.classList.remove('hidden');
                            statusDiv.innerText = '✅ Anda sudah memprediksi skor. Anda masih bisa memprediksi pemenang.';
                        }
                    }
                });
                document.getElementById('detail-match-modal').classList.remove('hidden');
                document.getElementById('detail-match-modal').classList.add('flex');
            }

            function closeDetailModal() {
                document.getElementById('detail-match-modal').classList.add('hidden');
                document.getElementById('detail-match-modal').classList.remove('flex');
            }

            async function saveWinnerPrediction() {
                if (!currentMatchId) return;
                let winnerId = null;
                let resultType = null;
                if (currentIsKnockout) {
                    const selectedBtn = document.querySelector('#modal-result-buttons button.bg-amber-500');
                    if (!selectedBtn) { showNotification('Pilih pemenang terlebih dahulu', 'error'); return; }
                    winnerId = parseInt(selectedBtn.getAttribute('data-winner-id'));
                } else {
                    const selectedBtn = document.querySelector('#modal-result-buttons button.bg-amber-500');
                    if (!selectedBtn) { showNotification('Pilih pemenang terlebih dahulu', 'error'); return; }
                    resultType = selectedBtn.getAttribute('data-value');
                }
                const formData = new FormData();
                formData.append('match_id', currentMatchId);
                if (resultType) formData.append('result_type', resultType);
                if (winnerId !== null) formData.append('winner_id', winnerId);
                formData.append('is_knockout', currentIsKnockout ? '1' : '0');
                try {
                    const res = await fetch('api.php?action=predict', { 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('Prediksi pemenang tersimpan!', 'success');
                        closeDetailModal();
                        await fetchUserInfo();
                        if (currentIsKnockout) loadKnockout(); else loadSchedule();
                    } else {
                        showNotification(data.error || 'Gagal menyimpan prediksi', 'error');
                    }
                } catch (err) { showNotification('Terjadi kesalahan', 'error'); }
            }

            async function saveScorePrediction() {
                if (!currentMatchId) return;
                const homeScore = parseInt(document.getElementById('modal-score-home').value);
                const awayScore = parseInt(document.getElementById('modal-score-away').value);
                if (isNaN(homeScore) || isNaN(awayScore)) { showNotification('Masukkan skor yang valid (angka)', 'error'); return; }
                if (homeScore < 0 || awayScore < 0) { showNotification('Skor tidak boleh negatif', 'error'); return; }
                const formData = new FormData();
                formData.append('match_id', currentMatchId);
                formData.append('team1_score_pred', homeScore);
                formData.append('team2_score_pred', awayScore);
                formData.append('is_knockout', currentIsKnockout ? '1' : '0');
                try {
                    const res = await fetch('api.php?action=predict', { 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('Prediksi skor tersimpan!', 'success');
                        closeDetailModal();
                        await fetchUserInfo();
                        if (currentIsKnockout) loadKnockout(); else loadSchedule();
                    } else {
                        showNotification(data.error || 'Gagal menyimpan prediksi skor', 'error');
                    }
                } catch (err) { showNotification('Terjadi kesalahan', 'error'); }
            }

            document.getElementById('save-winner-btn').addEventListener('click', saveWinnerPrediction);
            document.getElementById('save-score-btn').addEventListener('click', saveScorePrediction);

            (function () {
                function initCarousel() {
                    const slidesContainer = document.getElementById('carouselSlides');
                    if (!slidesContainer) return;
                    const slides = document.querySelectorAll('.carousel-slide');
                    const prevBtn = document.getElementById('prevBtn');
                    const nextBtn = document.getElementById('nextBtn');
                    const dotsContainer = document.getElementById('carouselDots');
                    let currentIndex = 0;
                    let slideInterval;
                    const totalSlides = slides.length;
                    function createDots() { if (!dotsContainer) return; dotsContainer.innerHTML = ''; for (let i = 0; i < totalSlides; i++) { const dot = document.createElement('div'); dot.classList.add('dot'); if (i === currentIndex) dot.classList.add('active'); dot.addEventListener('click', () => goToSlide(i)); dotsContainer.appendChild(dot); } }
                    function goToSlide(index) { if (index < 0) index = totalSlides - 1; if (index >= totalSlides) index = 0; currentIndex = index; slidesContainer.style.transform = `translateX(-${currentIndex * 100}%)`; document.querySelectorAll('.dot').forEach((dot, i) => { dot.classList.toggle('active', i === currentIndex); }); }
                    function nextSlide() { goToSlide(currentIndex + 1); }
                    function prevSlide() { goToSlide(currentIndex - 1); }
                    function startAutoSlide() { if (slideInterval) clearInterval(slideInterval); slideInterval = setInterval(nextSlide, 5000); }
                    function stopAutoSlide() { if (slideInterval) clearInterval(slideInterval); }
                    if (prevBtn) prevBtn.addEventListener('click', () => { prevSlide(); stopAutoSlide(); startAutoSlide(); });
                    if (nextBtn) nextBtn.addEventListener('click', () => { nextSlide(); stopAutoSlide(); startAutoSlide(); });
                    const carouselContainer = document.querySelector('.carousel-container');
                    if (carouselContainer) { carouselContainer.addEventListener('mouseenter', stopAutoSlide); carouselContainer.addEventListener('mouseleave', startAutoSlide); }
                    slides.forEach(slide => { const url = slide.getAttribute('data-url'); if (url && url.trim() !== '') { slide.addEventListener('click', (e) => { window.location.href = url; }); } });
                    createDots();
                    goToSlide(0);
                    startAutoSlide();
                }
                if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', initCarousel); } else { initCarousel(); }
            })();

            function validatePhoneNumber(phone) { if (!phone) return false; phone = phone.replace(/\s/g, ''); const regex = /^(?:\+62|62|0)[0-9]{9,13}$/; return regex.test(phone); }

            document.getElementById('auth-form')?.addEventListener('submit', async (e) => {
                e.preventDefault();
                const formData = new FormData(e.target);
                const action = currentAuthMode === 'login' ? 'login' : 'register';
                const errorDiv = document.getElementById('auth-error');
                errorDiv.classList.add('hidden');
                errorDiv.innerText = '';
                if (action === 'register') {
                    const phoneNumber = formData.get('phone_number');
                    if (!phoneNumber || !validatePhoneNumber(phoneNumber)) { errorDiv.innerText = 'Format nomor HP tidak valid. Gunakan 08xxxxxxxxxx atau +628xxxxxxxxxx'; errorDiv.classList.remove('hidden'); return; }
                }
                const username = formData.get('username');
                const password = formData.get('password');
                if (username.length < 3) { errorDiv.innerText = 'Username minimal 3 karakter'; errorDiv.classList.remove('hidden'); return; }
                if (password.length < 6) { errorDiv.innerText = 'Password minimal 6 karakter'; errorDiv.classList.remove('hidden'); return; }
                try {
                    const res = await fetch(`auth.php?action=${action}`, { method: 'POST', body: formData, headers: { 'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content } });
                    const data = await res.json();
                    if (res.ok && data.status === 'success') {
                        if (action === 'login') { showNotification('Login berhasil! Mengalihkan...', 'success'); setTimeout(() => window.location.reload(), 1000); }
                        else { showNotification('Pendaftaran berhasil! Silakan login.', 'success'); toggleAuthMode(); document.getElementById('auth-form').reset(); const phoneField = document.getElementById('phone-field'); if (phoneField) phoneField.querySelector('input').value = ''; toggleAuthModal(); }
                    } else { errorDiv.innerText = data.error || 'Terjadi kesalahan. Silakan coba lagi.'; errorDiv.classList.remove('hidden'); }
                } catch (err) { errorDiv.innerText = 'Gagal terhubung ke server. Periksa koneksi Anda.'; errorDiv.classList.remove('hidden'); }
            });

            document.addEventListener('DOMContentLoaded', function () {
                const popup = document.getElementById('promoPopup');
                const closeBtn = document.getElementById('closePopupBtn');
                if (!sessionStorage.getItem('promoShown')) {
                    setTimeout(() => {
                        popup.classList.add('show');
                    }, 500);
                    sessionStorage.setItem('promoShown', 'true');
                }
                function closePopup() { popup.classList.remove('show'); }
                if (closeBtn) closeBtn.addEventListener('click', closePopup);
                popup.addEventListener('click', function (e) { if (e.target === popup) closePopup(); });
            });

            // TUTUP MODAL PEMAIN SAAT KLIK DI BACKDROP (z-index sudah tinggi)
            const playersModalElem = document.getElementById('players-modal');
            if (playersModalElem) {
                playersModalElem.addEventListener('click', function (e) {
                    if (e.target === playersModalElem) {
                        closePlayersModal();
                    }
                });
            }

            document.getElementById('toggle-auth-mode')?.addEventListener('click', toggleAuthMode);

            (async () => { await fetchUserInfo(); showView('standings'); })();
        </script>
</body>

</html>