<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate">
    <meta http-equiv="Pragma" content="no-cache">
    <meta http-equiv="Expires" content="0">
    <title>CAIBench Attack/Defense CTF</title>
    <link rel="icon" type="image/svg+xml" href="/static/LOGO-alias-white-nav.svg">
    <style>
        :root {
            /* Dark mode (default) */
            --bg-primary: #0a0a0a;
            --bg-secondary: rgba(24, 24, 27, 0.8);
            --bg-tertiary: rgba(39, 39, 42, 0.6);
            --bg-card-gradient-start: #18181b;
            --bg-card-gradient-end: #27272a;
            --text-primary: #e4e4e7;
            --text-secondary: #a1a1aa;
            --text-tertiary: #71717a;
            --border-primary: rgba(63, 63, 70, 0.4);
            --border-secondary: rgba(63, 63, 70, 0.6);
            --accent-primary: #14b8a6;
            --accent-secondary: #10b981;
            --bg-gradient-1: rgba(20, 184, 166, 0.1);
            --bg-gradient-2: rgba(59, 130, 246, 0.05);
            --shadow-primary: rgba(0, 0, 0, 0.4);
            --shadow-secondary: rgba(0, 0, 0, 0.3);
            --log-bg: rgba(10, 10, 10, 0.5);
        }

        [data-theme="light"] {
            /* Light mode */
            --bg-primary: #fafafa;
            --bg-secondary: rgba(255, 255, 255, 0.9);
            --bg-tertiary: rgba(243, 244, 246, 0.8);
            --bg-card-gradient-start: #ffffff;
            --bg-card-gradient-end: #f9fafb;
            --text-primary: #18181b;
            --text-secondary: #52525b;
            --text-tertiary: #71717a;
            --border-primary: rgba(228, 228, 231, 0.8);
            --border-secondary: rgba(212, 212, 216, 0.8);
            --accent-primary: #14b8a6;
            --accent-secondary: #10b981;
            --bg-gradient-1: rgba(20, 184, 166, 0.05);
            --bg-gradient-2: rgba(59, 130, 246, 0.03);
            --shadow-primary: rgba(0, 0, 0, 0.1);
            --shadow-secondary: rgba(0, 0, 0, 0.05);
            --log-bg: rgba(249, 250, 251, 0.8);
        }

        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
            background: var(--bg-primary);
            background-image: radial-gradient(circle at 20% 50%, var(--bg-gradient-1) 0%, transparent 50%),
                              radial-gradient(circle at 80% 80%, var(--bg-gradient-2) 0%, transparent 50%);
            min-height: 100vh;
            padding: 20px;
            color: var(--text-primary);
            transition: background 0.3s ease, color 0.3s ease;
        }

        .container {
            max-width: 1400px;
            margin: 0 auto;
        }

        .header {
            background: linear-gradient(135deg, var(--bg-card-gradient-start) 0%, var(--bg-card-gradient-end) 100%);
            border: 1px solid var(--border-primary);
            border-radius: 12px;
            padding: 24px;
            margin-bottom: 20px;
            box-shadow: 0 10px 40px var(--shadow-primary);
            backdrop-filter: blur(10px);
        }

        .header h1 {
            color: var(--accent-primary);
            margin: 0;
            font-size: 2em;
            font-weight: 700;
            display: inline-block;
        }

        .header-title {
            display: flex;
            align-items: center;
            justify-content: space-between;
            margin-bottom: 20px;
        }

        .title-left {
            display: flex;
            align-items: center;
            gap: 20px;
        }

        .logo {
            height: 40px;
            width: auto;
            filter: drop-shadow(0 2px 4px rgba(0, 0, 0, 0.3));
        }

        .by-alias {
            display: flex;
            align-items: center;
            gap: 8px;
            color: var(--text-tertiary);
            font-size: 0.85em;
            font-style: italic;
            position: relative;
            top: 25px;
        }

        .by-alias a {
            display: inline-flex;
            align-items: center;
            transition: opacity 0.3s ease;
        }

        .by-alias a:hover {
            opacity: 0.8;
        }

        [data-theme="light"] .alias-text-logo {
            height: 24px;
            width: auto;
            filter: brightness(0) opacity(0.6);
        }

        [data-theme="light"] .by-alias a:hover .alias-text-logo {
            filter: brightness(0) opacity(0.8);
        }

        .alias-text-logo {
            height: 24px;
            width: auto;
            filter: brightness(0) invert(1) opacity(0.6);
        }

        .by-alias a:hover .alias-text-logo {
            filter: brightness(0) invert(1) opacity(0.8);
        }

        .game-info {
            display: flex;
            gap: 30px;
            flex-wrap: wrap;
        }

        .info-item {
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .info-label {
            font-weight: 600;
            color: var(--text-tertiary);
            text-transform: uppercase;
            font-size: 0.75em;
            letter-spacing: 0.05em;
        }

        .info-value {
            color: var(--text-primary);
            font-size: 1.1em;
            font-weight: 500;
        }

        .status-indicator {
            width: 12px;
            height: 12px;
            border-radius: 50%;
            display: inline-block;
            margin-right: 5px;
        }

        .status-running {
            background: #10b981;
            animation: pulse 2s infinite;
            box-shadow: 0 0 20px rgba(16, 185, 129, 0.5);
        }

        .status-stopped {
            background: #ef4444;
            box-shadow: 0 0 10px rgba(239, 68, 68, 0.3);
        }

        @keyframes pulse {
            0% {
                box-shadow: 0 0 0 0 rgba(16, 185, 129, 0.7);
            }
            70% {
                box-shadow: 0 0 0 10px rgba(16, 185, 129, 0);
            }
            100% {
                box-shadow: 0 0 0 0 rgba(16, 185, 129, 0);
            }
        }

        .main-content {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 20px;
            margin-bottom: 20px;
        }

        /* Battle View Layout */
        .battle-view {
            display: flex;
            gap: 20px;
            margin-bottom: 20px;
            align-items: stretch;
            flex-wrap: wrap;
        }

        /* Special layout for 2 teams */
        .battle-view.two-teams {
            display: grid;
            grid-template-columns: 1fr 1fr 1fr;
            gap: 20px;
            align-items: start;
        }

        .battle-view.two-teams .team-column {
            max-width: none;
        }

        .battle-view.two-teams .center-checks {
            background: var(--bg-secondary);
            border: 1px solid var(--border-primary);
            border-radius: 12px;
            padding: 24px;
            box-shadow: 0 10px 40px var(--shadow-secondary);
            backdrop-filter: blur(10px);
            display: flex;
            flex-direction: column;
        }

        .battle-view.two-teams .center-checks h2 {
            color: var(--text-primary);
            margin-bottom: 20px;
            padding-bottom: 12px;
            border-bottom: 1px solid var(--border-secondary);
            font-weight: 600;
            font-size: 1.25em;
            flex-shrink: 0;
        }

        /* Make check-history fill the available space in 2-team layout */
        .battle-view.two-teams .center-checks .check-history {
            max-height: none;
            flex: 1;
            overflow-y: auto;
            min-height: 0;
        }

        /* Bottom grid for 2 teams */
        .bottom-grid {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 20px;
            margin-bottom: 20px;
        }

        .bottom-grid.two-teams {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 20px;
            margin-bottom: 20px;
        }

        .bottom-grid.two-teams .captures-card {
            grid-column: 1;
        }

        .bottom-grid.two-teams .submit-card {
            grid-column: 2;
        }

        /* When not 2-team layout, stack vertically */
        .bottom-grid:not(.two-teams) {
            grid-template-columns: 1fr;
        }

        @media (max-width: 1024px) {
            .battle-view.two-teams {
                grid-template-columns: 1fr;
            }

            .bottom-grid.two-teams {
                grid-template-columns: 1fr;
            }

            .bottom-grid.two-teams .submit-card {
                grid-column: 1;
            }
        }

        .team-column {
            flex: 1 1 300px;
            min-width: 300px;
            max-width: 450px;
            background: linear-gradient(145deg, var(--bg-card-gradient-start) 0%, var(--bg-card-gradient-end) 100%);
            border: 2px solid var(--border-primary);
            border-radius: 16px;
            padding: 24px;
            box-shadow: 0 20px 60px var(--shadow-primary),
                        0 10px 30px var(--shadow-secondary),
                        inset 0 1px 0 rgba(255, 255, 255, 0.1);
            backdrop-filter: blur(20px);
            position: relative;
            transition: transform 0.3s ease, box-shadow 0.3s ease;
        }

        .team-column:hover {
            transform: translateY(-4px);
            box-shadow: 0 24px 70px var(--shadow-primary),
                        0 12px 35px var(--shadow-secondary),
                        inset 0 1px 0 rgba(255, 255, 255, 0.15);
        }

        .team-column.team-1 {
            border-left: 5px solid #3b82f6;
            box-shadow: 0 20px 60px var(--shadow-primary),
                        0 10px 30px var(--shadow-secondary),
                        inset 0 1px 0 rgba(255, 255, 255, 0.1),
                        -4px 0 20px rgba(59, 130, 246, 0.3);
        }

        .team-column.team-2 {
            border-left: 5px solid #ef4444;
            box-shadow: 0 20px 60px var(--shadow-primary),
                        0 10px 30px var(--shadow-secondary),
                        inset 0 1px 0 rgba(255, 255, 255, 0.1),
                        -4px 0 20px rgba(239, 68, 68, 0.3);
        }

        .team-column.team-3 {
            border-left: 5px solid #10b981;
            box-shadow: 0 20px 60px var(--shadow-primary),
                        0 10px 30px var(--shadow-secondary),
                        inset 0 1px 0 rgba(255, 255, 255, 0.1),
                        -4px 0 20px rgba(16, 185, 129, 0.3);
        }

        .team-column.team-4 {
            border-left: 5px solid #f59e0b;
            box-shadow: 0 20px 60px var(--shadow-primary),
                        0 10px 30px var(--shadow-secondary),
                        inset 0 1px 0 rgba(255, 255, 255, 0.1),
                        -4px 0 20px rgba(245, 158, 11, 0.3);
        }

        .team-column.team-5 {
            border-left: 5px solid #8b5cf6;
            box-shadow: 0 20px 60px var(--shadow-primary),
                        0 10px 30px var(--shadow-secondary),
                        inset 0 1px 0 rgba(255, 255, 255, 0.1),
                        -4px 0 20px rgba(139, 92, 246, 0.3);
        }

        .team-column.team-6 {
            border-left: 5px solid #ec4899;
            box-shadow: 0 20px 60px var(--shadow-primary),
                        0 10px 30px var(--shadow-secondary),
                        inset 0 1px 0 rgba(255, 255, 255, 0.1),
                        -4px 0 20px rgba(236, 72, 153, 0.3);
        }

        .team-column.team-7 {
            border-left: 5px solid #06b6d4;
            box-shadow: 0 20px 60px var(--shadow-primary),
                        0 10px 30px var(--shadow-secondary),
                        inset 0 1px 0 rgba(255, 255, 255, 0.1),
                        -4px 0 20px rgba(6, 182, 212, 0.3);
        }

        .team-column.team-8 {
            border-left: 5px solid #84cc16;
            box-shadow: 0 20px 60px var(--shadow-primary),
                        0 10px 30px var(--shadow-secondary),
                        inset 0 1px 0 rgba(255, 255, 255, 0.1),
                        -4px 0 20px rgba(132, 204, 22, 0.3);
        }

        .team-column.team-9 {
            border-left: 5px solid #f97316;
            box-shadow: 0 20px 60px var(--shadow-primary),
                        0 10px 30px var(--shadow-secondary),
                        inset 0 1px 0 rgba(255, 255, 255, 0.1),
                        -4px 0 20px rgba(249, 115, 22, 0.3);
        }

        .team-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
            padding-bottom: 15px;
            border-bottom: 2px solid var(--border-secondary);
        }

        .team-name {
            font-size: 1.6em;
            font-weight: 800;
            color: var(--text-primary);
            letter-spacing: -0.02em;
            text-shadow: 0 2px 4px rgba(0, 0, 0, 0.3);
            background: linear-gradient(135deg, var(--text-primary) 0%, var(--text-secondary) 100%);
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
            background-clip: text;
        }

        .team-model {
            font-size: 0.75em;
            font-weight: 600;
            color: var(--text-secondary);
            margin-top: 4px;
            padding: 4px 10px;
            background: var(--bg-tertiary);
            border: 1px solid var(--border-secondary);
            border-radius: 6px;
            display: inline-block;
            font-family: 'SF Mono', 'Monaco', 'Courier New', monospace;
            letter-spacing: 0.02em;
        }

        .team-score {
            font-size: 2.5em;
            font-weight: 900;
            color: var(--accent-primary);
            letter-spacing: -0.03em;
            font-family: 'SF Mono', 'Monaco', 'Courier New', monospace;
        }

        body.dark-mode .team-score {
            text-shadow: 0 0 20px rgba(20, 184, 166, 0.4),
                         0 2px 8px rgba(0, 0, 0, 0.5);
        }

        .machines-list {
            display: flex;
            flex-direction: column;
            gap: 15px;
        }

        .machine-card {
            background: var(--bg-tertiary);
            border: 1px solid var(--border-secondary);
            border-radius: 12px;
            padding: 18px;
            transition: all 0.2s ease;
            position: relative;
        }

        body.dark-mode .machine-card {
            background: linear-gradient(135deg, var(--bg-tertiary) 0%, rgba(39, 39, 42, 0.4) 100%);
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15),
                        inset 0 1px 0 rgba(255, 255, 255, 0.05);
            overflow: hidden;
        }

        body.dark-mode .machine-card::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            height: 2px;
            background: linear-gradient(90deg, transparent, var(--accent-primary), transparent);
            opacity: 0;
            transition: opacity 0.3s ease;
        }

        .machine-card:hover {
            border-color: rgba(20, 184, 166, 0.3);
        }

        body.dark-mode .machine-card:hover {
            transform: translateY(-3px) scale(1.01);
            box-shadow: 0 8px 24px rgba(0, 0, 0, 0.25),
                        0 4px 12px rgba(20, 184, 166, 0.15),
                        inset 0 1px 0 rgba(255, 255, 255, 0.08);
        }

        body.dark-mode .machine-card:hover::before {
            opacity: 1;
        }

        .machine-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 10px;
        }

        .machine-name {
            font-size: 1.15em;
            font-weight: 700;
            color: var(--text-primary);
            text-transform: uppercase;
            letter-spacing: 0.05em;
            display: flex;
            align-items: center;
            gap: 8px;
        }

        .machine-ip {
            font-family: 'SF Mono', 'Monaco', 'Courier New', monospace;
            font-size: 0.95em;
            color: var(--text-secondary);
            padding: 4px 8px;
            background: rgba(20, 184, 166, 0.05);
            border-radius: 6px;
            display: inline-block;
            border: 1px solid rgba(20, 184, 166, 0.1);
        }

        .machine-score-breakdown {
            display: flex;
            justify-content: space-between;
            align-items: center;
            gap: 6px;
            flex-wrap: wrap;
            margin-top: 8px;
            padding-top: 8px;
            border-top: 1px solid var(--border-primary);
        }

        .machine-score-item {
            font-size: 0.75em;
            padding: 2px 6px;
            border-radius: 4px;
            font-weight: 500;
        }

        .machine-score-item.defense {
            background: rgba(16, 185, 129, 0.15);
            color: #10b981;
        }

        .machine-score-item.attack {
            background: rgba(239, 68, 68, 0.15);
            color: #ef4444;
        }

        .machine-score-item.penalty {
            background: rgba(251, 191, 36, 0.15);
            color: #fbbf24;
        }

        .cai-server-link {
            display: inline-flex;
            align-items: center;
            justify-content: center;
            gap: 6px;
            padding: 8px 14px;
            background: linear-gradient(135deg, #14b8a6 0%, #0d9488 100%);
            border: none;
            border-radius: 8px;
            color: #ffffff;
            text-decoration: none;
            font-size: 0.9em;
            font-weight: 700;
            transition: all 0.2s ease;
            white-space: nowrap;
            box-shadow: 0 2px 6px rgba(20, 184, 166, 0.3);
        }

        .cai-server-link:hover {
            background: linear-gradient(135deg, #0d9488 0%, #0f766e 100%);
            transform: translateY(-1px);
            box-shadow: 0 3px 8px rgba(20, 184, 166, 0.4);
        }

        .cai-server-link.failed {
            background: linear-gradient(135deg, #ef4444 0%, #dc2626 100%);
            color: #ffffff;
            cursor: not-allowed;
        }

        .cai-server-link.failed:hover {
            transform: none;
        }

        .cai-logo {
            width: 14px;
            height: 14px;
            color: #ffffff;
        }

        .cai-logo-img {
            width: 18px;
            height: 18px;
            object-fit: contain;
        }

        .cai-icon {
            font-size: 0.95em;
        }

        .cai-model-info {
            padding: 4px 10px;
            background: rgba(20, 184, 166, 0.08);
            border: 1px solid rgba(20, 184, 166, 0.2);
            border-radius: 6px;
            font-size: 0.85em;
            text-align: right;
            color: var(--text-primary);
            font-family: 'Monaco', 'Courier New', monospace;
            white-space: nowrap;
            margin-left: auto;
        }

        .flag-indicators {
            display: flex;
            gap: 10px;
            margin-top: 10px;
            padding-top: 10px;
            border-top: 1px solid var(--border-primary);
            justify-content: center;
        }

        .flag-icon {
            display: flex;
            align-items: center;
            gap: 4px;
            font-size: 0.85em;
            padding: 4px 8px;
            border-radius: 6px;
            transition: all 0.3s ease;
        }

        .flag-icon.safe {
            background: rgba(113, 113, 122, 0.2);
            color: #71717a;
        }

        .flag-icon.captured {
            background: rgba(239, 68, 68, 0.2);
            color: #ef4444;
            border: 1px solid rgba(239, 68, 68, 0.4);
            animation: flagPulse 2s ease-in-out infinite;
        }

        .flag-icon.secured {
            background: rgba(16, 185, 129, 0.2);
            color: #10b981;
            border: 1px solid rgba(16, 185, 129, 0.4);
        }

        @keyframes flagPulse {
            0%, 100% {
                box-shadow: 0 0 5px rgba(239, 68, 68, 0.3);
            }
            50% {
                box-shadow: 0 0 15px rgba(239, 68, 68, 0.6);
            }
        }

        .flag-capture-count {
            background: rgba(239, 68, 68, 0.3);
            color: #ef4444;
            font-weight: 700;
            padding: 2px 6px;
            border-radius: 50%;
            font-size: 0.75em;
            min-width: 18px;
            text-align: center;
        }

        .machine-status-badge {
            display: inline-flex;
            align-items: center;
            padding: 6px 14px;
            border-radius: 20px;
            font-size: 0.8em;
            font-weight: 700;
            text-transform: uppercase;
            letter-spacing: 0.05em;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
            transition: all 0.2s ease;
        }

        .machine-status-badge.OK {
            background: linear-gradient(135deg, rgba(16, 185, 129, 0.25) 0%, rgba(16, 185, 129, 0.15) 100%);
            color: #10b981;
            border: 1.5px solid rgba(16, 185, 129, 0.5);
            box-shadow: 0 2px 8px rgba(16, 185, 129, 0.2),
                        0 0 15px rgba(16, 185, 129, 0.15);
        }

        .machine-status-badge.DOWN {
            background: linear-gradient(135deg, rgba(239, 68, 68, 0.25) 0%, rgba(239, 68, 68, 0.15) 100%);
            color: #ef4444;
            border: 1.5px solid rgba(239, 68, 68, 0.5);
            box-shadow: 0 2px 8px rgba(239, 68, 68, 0.2),
                        0 0 15px rgba(239, 68, 68, 0.15);
            animation: badgePulse 2s ease-in-out infinite;
        }

        .machine-status-badge.MUMBLE {
            background: linear-gradient(135deg, rgba(251, 146, 60, 0.25) 0%, rgba(251, 146, 60, 0.15) 100%);
            color: #fb923c;
            border: 1.5px solid rgba(251, 146, 60, 0.5);
            box-shadow: 0 2px 8px rgba(251, 146, 60, 0.2),
                        0 0 15px rgba(251, 146, 60, 0.15);
        }

        .machine-status-badge.CORRUPT {
            background: linear-gradient(135deg, rgba(251, 191, 36, 0.25) 0%, rgba(251, 191, 36, 0.15) 100%);
            color: #fbbf24;
            border: 1.5px solid rgba(251, 191, 36, 0.5);
            box-shadow: 0 2px 8px rgba(251, 191, 36, 0.2),
                        0 0 15px rgba(251, 191, 36, 0.15);
        }

        .machine-status-badge.ERROR {
            background: linear-gradient(135deg, rgba(156, 163, 175, 0.25) 0%, rgba(156, 163, 175, 0.15) 100%);
            color: #9ca3af;
            border: 1.5px solid rgba(156, 163, 175, 0.5);
            box-shadow: 0 2px 8px rgba(156, 163, 175, 0.2);
        }

        @keyframes badgePulse {
            0%, 100% {
                box-shadow: 0 2px 8px rgba(239, 68, 68, 0.2),
                            0 0 15px rgba(239, 68, 68, 0.15);
            }
            50% {
                box-shadow: 0 2px 12px rgba(239, 68, 68, 0.3),
                            0 0 25px rgba(239, 68, 68, 0.25);
            }
        }

        .center-column {
            flex: 0 0 400px;
            display: flex;
            flex-direction: column;
            gap: 20px;
        }

        @media (max-width: 1024px) {
            .main-content {
                grid-template-columns: 1fr;
            }

            .battle-view {
                flex-direction: column;
            }

            .center-column {
                flex: 1;
            }
        }

        .card {
            background: var(--bg-secondary);
            border: 1px solid var(--border-primary);
            border-radius: 12px;
            padding: 24px;
            box-shadow: 0 10px 40px var(--shadow-secondary);
            backdrop-filter: blur(10px);
        }

        .card h2 {
            color: var(--text-primary);
            margin-bottom: 20px;
            padding-bottom: 12px;
            border-bottom: 1px solid var(--border-secondary);
            font-weight: 600;
            font-size: 1.25em;
        }

        .scoreboard {
            grid-column: 1;
        }

        .scoreboard table {
            width: 100%;
            border-collapse: collapse;
        }

        .scoreboard th {
            background: var(--bg-tertiary);
            padding: 12px;
            text-align: left;
            color: var(--text-secondary);
            font-weight: 600;
            font-size: 0.85em;
            text-transform: uppercase;
            letter-spacing: 0.05em;
        }

        .scoreboard td {
            padding: 12px;
            border-bottom: 1px solid var(--border-primary);
            color: var(--text-primary);
        }

        .scoreboard tr:hover {
            background: var(--bg-tertiary);
            opacity: 0.5;
        }

        .rank-1 {
            background: linear-gradient(90deg, rgba(255, 215, 0, 0.2) 0%, rgba(255, 237, 78, 0.1) 100%);
            color: #fbbf24;
            font-weight: bold;
            border-left: 3px solid #fbbf24;
        }

        .rank-2 {
            background: linear-gradient(90deg, rgba(192, 192, 192, 0.15) 0%, rgba(232, 232, 232, 0.05) 100%);
            color: #d4d4d8;
            border-left: 3px solid #a1a1aa;
        }

        .rank-3 {
            background: linear-gradient(90deg, rgba(205, 127, 50, 0.15) 0%, rgba(229, 168, 92, 0.05) 100%);
            color: #f59e0b;
            border-left: 3px solid #d97706;
        }

        .service-status {
            display: inline-block;
            padding: 2px 8px;
            border-radius: 12px;
            font-size: 0.85em;
            font-weight: 500;
        }

        .service-up {
            background: rgba(16, 185, 129, 0.2);
            color: #10b981;
            border: 1px solid rgba(16, 185, 129, 0.3);
        }

        .service-down {
            background: rgba(239, 68, 68, 0.2);
            color: #ef4444;
            border: 1px solid rgba(239, 68, 68, 0.3);
        }

        .service-mumble {
            background: rgba(251, 146, 60, 0.2);
            color: #fb923c;
            border: 1px solid rgba(251, 146, 60, 0.3);
        }

        .service-corrupt {
            background: rgba(251, 191, 36, 0.2);
            color: #fbbf24;
            border: 1px solid rgba(251, 191, 36, 0.3);
        }

        .checks {
            grid-column: 2;
        }

        .check-history {
            max-height: 250px;
            overflow-y: auto;
            padding-right: 5px;
        }

        .check-history::-webkit-scrollbar {
            width: 8px;
        }

        .check-history::-webkit-scrollbar-track {
            background: rgba(39, 39, 42, 0.5);
            border-radius: 4px;
        }

        .check-history::-webkit-scrollbar-thumb {
            background: rgba(113, 113, 122, 0.5);
            border-radius: 4px;
        }

        .check-history::-webkit-scrollbar-thumb:hover {
            background: rgba(113, 113, 122, 0.7);
        }

        @keyframes fadeIn {
            from {
                opacity: 0;
            }
            to {
                opacity: 1;
            }
        }

        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }

        .loading-spinner {
            display: inline-block;
            width: 14px;
            height: 14px;
            border: 2px solid rgba(20, 184, 166, 0.2);
            border-top: 2px solid #14b8a6;
            border-radius: 50%;
            animation: spin 1s linear infinite;
            margin-left: 8px;
        }

        .check-entry {
            padding: 12px;
            margin-bottom: 12px;
            background: var(--bg-tertiary);
            border-radius: 8px;
            border-left: 3px solid #6366f1;
            border: 1px solid var(--border-primary);
        }

        .check-timestamp {
            color: var(--text-tertiary);
            font-size: 0.85em;
            margin-bottom: 8px;
            font-weight: 500;
        }

        .check-results {
            display: flex;
            gap: 15px;
            flex-wrap: wrap;
        }

        .check-item {
            font-size: 0.9em;
        }

        .check-ok {
            color: #059669;
        }

        .check-warning {
            color: #f59e0b;
        }

        .check-fail {
            color: #dc2626;
        }

        .controls {
            background: var(--bg-secondary);
            border: 1px solid var(--border-primary);
            border-radius: 12px;
            padding: 24px;
            box-shadow: 0 10px 40px var(--shadow-secondary);
            backdrop-filter: blur(10px);
            margin-bottom: 20px;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .controls-center {
            display: flex;
            align-items: center;
            gap: 20px;
        }

        .control-buttons {
            display: flex;
            gap: 10px;
        }


        /* Theme Toggle Styles */
        .theme-toggle {
            position: relative;
            width: 60px;
            height: 30px;
            border-radius: 15px;
            background: var(--bg-tertiary);
            border: 1px solid var(--border-primary);
            cursor: pointer;
            transition: background 0.3s ease;
            display: flex;
            align-items: center;
            padding: 0 5px;
        }

        .theme-toggle:hover {
            background: var(--border-secondary);
        }

        .theme-toggle-slider {
            position: absolute;
            width: 22px;
            height: 22px;
            border-radius: 50%;
            background: var(--text-primary);
            transition: transform 0.3s ease;
            display: flex;
            align-items: center;
            justify-content: center;
            left: 4px;
        }

        .theme-toggle.light .theme-toggle-slider {
            transform: translateX(30px);
        }

        .theme-icon {
            width: 14px;
            height: 14px;
            fill: var(--bg-primary);
        }

        .theme-toggle-icons {
            width: 100%;
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 0 6px;
            pointer-events: none;
        }

        .theme-toggle-icons svg {
            width: 14px;
            height: 14px;
            fill: var(--text-secondary);
            transition: opacity 0.3s ease;
        }

        .theme-toggle.light .moon-icon {
            opacity: 0.3;
        }

        .theme-toggle:not(.light) .sun-icon {
            opacity: 0.3;
        }

        .btn {
            padding: 12px 24px;
            border: none;
            border-radius: 8px;
            font-size: 0.95em;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s;
            text-transform: uppercase;
            letter-spacing: 0.05em;
            box-shadow: 0 4px 15px rgba(0, 0, 0, 0.2);
        }

        .btn-start {
            background: linear-gradient(135deg, #10b981 0%, #14b8a6 100%);
            color: white;
            transition: all 0.3s ease;
        }

        .btn-start:hover:not(:disabled) {
            background: linear-gradient(135deg, #059669 0%, #0d9488 100%);
            box-shadow: 0 6px 20px rgba(16, 185, 129, 0.4);
            transform: translateY(-2px);
        }

        .btn-start.confirm {
            background: white;
            color: #10b981;
            border: 2px solid #10b981;
        }

        .btn-start.confirm:hover:not(:disabled) {
            background: rgba(16, 185, 129, 0.1);
            transform: translateY(-2px);
        }

        .btn-stop {
            background: linear-gradient(135deg, #ef4444 0%, #f87171 100%);
            color: white;
            transition: all 0.3s ease;
        }

        .btn-stop:hover:not(:disabled) {
            background: linear-gradient(135deg, #dc2626 0%, #ef4444 100%);
            box-shadow: 0 6px 20px rgba(239, 68, 68, 0.4);
            transform: translateY(-2px);
        }

        .btn-stop.confirm {
            background: white;
            color: #ef4444;
            border: 2px solid #ef4444;
        }

        .btn-stop.confirm:hover:not(:disabled) {
            background: rgba(239, 68, 68, 0.1);
            transform: translateY(-2px);
        }

        .btn:disabled {
            opacity: 0.5;
            cursor: not-allowed;
            transform: none !important;
        }

        .btn-reset-machine {
            width: 100%;
            padding: 8px 16px;
            border: 1px solid rgba(249, 115, 22, 0.3);
            border-radius: 6px;
            font-size: 0.85em;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.2s ease;
            background: linear-gradient(135deg, rgba(249, 115, 22, 0.1) 0%, rgba(251, 146, 60, 0.1) 100%);
            color: #f97316;
            text-transform: none;
        }

        .btn-reset-machine:hover {
            background: linear-gradient(135deg, rgba(249, 115, 22, 0.2) 0%, rgba(251, 146, 60, 0.2) 100%);
            border-color: rgba(249, 115, 22, 0.5);
            transform: translateY(-1px);
            box-shadow: 0 2px 8px rgba(249, 115, 22, 0.2);
        }

        .btn-reset-machine:active {
            transform: translateY(0);
        }

        body.dark-mode .btn-reset-machine {
            background: linear-gradient(135deg, rgba(249, 115, 22, 0.15) 0%, rgba(251, 146, 60, 0.15) 100%);
            border-color: rgba(249, 115, 22, 0.4);
            color: #fb923c;
        }

        body.dark-mode .btn-reset-machine:hover {
            background: linear-gradient(135deg, rgba(249, 115, 22, 0.25) 0%, rgba(251, 146, 60, 0.25) 100%);
            border-color: rgba(249, 115, 22, 0.6);
        }

        .flag-form {
            display: flex;
            gap: 10px;
            margin-top: 15px;
        }

        .flag-form input {
            flex: 1;
            padding: 12px;
            background: var(--bg-tertiary);
            border: 1px solid var(--border-secondary);
            border-radius: 8px;
            font-size: 1em;
            color: var(--text-primary);
        }

        .flag-form input:focus {
            outline: none;
            border-color: var(--accent-primary);
            box-shadow: 0 0 0 3px rgba(20, 184, 166, 0.1);
        }

        .flag-form select {
            padding: 12px;
            background: var(--bg-tertiary);
            border: 1px solid var(--border-secondary);
            border-radius: 8px;
            font-size: 1em;
            color: var(--text-primary);
        }

        .flag-form select:focus {
            outline: none;
            border-color: var(--accent-primary);
            box-shadow: 0 0 0 3px rgba(20, 184, 166, 0.1);
        }

        .alert {
            padding: 10px 15px;
            border-radius: 6px;
            margin-top: 10px;
            display: none;
        }

        .alert-success {
            background: rgba(16, 185, 129, 0.1);
            color: #10b981;
            border: 1px solid rgba(16, 185, 129, 0.3);
        }

        .alert-error {
            background: rgba(239, 68, 68, 0.1);
            color: #ef4444;
            border: 1px solid rgba(239, 68, 68, 0.3);
        }

        .timer {
            font-size: 1.2em;
            font-weight: bold;
            color: #14b8a6;
            font-family: 'Monaco', 'Courier New', monospace;
        }

        /* Logs Styles */
        .logs-container {
            max-height: 400px;
            display: flex;
            flex-direction: column;
        }

        .log-filters {
            display: flex;
            gap: 15px;
            margin-bottom: 15px;
            padding-bottom: 15px;
            border-bottom: 1px solid rgba(63, 63, 70, 0.4);
            align-items: center;
        }

        .log-filter {
            display: flex;
            align-items: center;
            gap: 8px;
            cursor: pointer;
        }

        .log-filter input[type="checkbox"] {
            width: 16px;
            height: 16px;
            accent-color: #14b8a6;
        }

        .log-level-badge {
            padding: 4px 8px;
            border-radius: 4px;
            font-size: 0.75em;
            font-weight: 600;
            text-transform: uppercase;
            letter-spacing: 0.05em;
        }

        .log-info {
            background: rgba(59, 130, 246, 0.2);
            color: #3b82f6;
            border: 1px solid rgba(59, 130, 246, 0.3);
        }

        .log-warning {
            background: rgba(251, 191, 36, 0.2);
            color: #fbbf24;
            border: 1px solid rgba(251, 191, 36, 0.3);
        }

        .log-error {
            background: rgba(239, 68, 68, 0.2);
            color: #ef4444;
            border: 1px solid rgba(239, 68, 68, 0.3);
        }

        .log-debug {
            background: rgba(156, 163, 175, 0.2);
            color: #9ca3af;
            border: 1px solid rgba(156, 163, 175, 0.3);
        }

        .logs-output {
            flex: 1;
            overflow-y: auto;
            font-family: 'Monaco', 'Courier New', monospace;
            font-size: 0.85em;
            background: var(--log-bg);
            border-radius: 8px;
            padding: 12px;
            border: 1px solid var(--border-primary);
        }

        .logs-output::-webkit-scrollbar {
            width: 8px;
        }

        .logs-output::-webkit-scrollbar-track {
            background: rgba(39, 39, 42, 0.5);
            border-radius: 4px;
        }

        .logs-output::-webkit-scrollbar-thumb {
            background: rgba(113, 113, 122, 0.5);
            border-radius: 4px;
        }

        .logs-output::-webkit-scrollbar-thumb:hover {
            background: rgba(113, 113, 122, 0.7);
        }

        .log-entry {
            padding: 6px 0;
            border-bottom: 1px solid rgba(63, 63, 70, 0.2);
            display: flex;
            align-items: flex-start;
            gap: 12px;
        }

        .log-entry:last-child {
            border-bottom: none;
        }

        .log-timestamp {
            color: #71717a;
            min-width: 180px;
        }

        .log-message {
            flex: 1;
            word-break: break-word;
        }

        .log-entry.info .log-level-badge {
            background: rgba(59, 130, 246, 0.2);
            color: #3b82f6;
        }

        .log-entry.warning .log-level-badge {
            background: rgba(251, 191, 36, 0.2);
            color: #fbbf24;
        }

        .log-entry.error .log-level-badge {
            background: rgba(239, 68, 68, 0.2);
            color: #ef4444;
        }

        .log-entry.debug .log-level-badge {
            background: rgba(156, 163, 175, 0.2);
            color: #9ca3af;
        }

        .btn-clear-logs {
            padding: 6px 12px;
            background: rgba(63, 63, 70, 0.4);
            border: 1px solid rgba(113, 113, 122, 0.3);
            border-radius: 6px;
            color: #a1a1aa;
            font-size: 0.85em;
            cursor: pointer;
            transition: all 0.2s;
            margin-left: auto;
        }

        .btn-clear-logs:hover {
            background: rgba(113, 113, 122, 0.4);
            color: #e4e4e7;
        }

        .log-entry.hidden {
            display: none;
        }

        /* Score breakdown styles */
        .score-breakdown {
            display: flex;
            flex-direction: column;
            gap: 2px;
            font-size: 0.75em;
        }

        .score-total {
            font-size: 1.2em;
            font-weight: bold;
            margin-bottom: 4px;
        }

        .score-details {
            display: flex;
            gap: 8px;
            flex-wrap: wrap;
        }

        .score-component {
            display: flex;
            align-items: center;
            gap: 3px;
            padding: 2px 6px;
            border-radius: 4px;
            background: rgba(0, 0, 0, 0.1);
        }

        .score-attack {
            background: rgba(239, 68, 68, 0.15);
            color: #ef4444;
        }

        .score-defense {
            background: rgba(16, 185, 129, 0.15);
            color: #10b981;
        }

        .score-penalty {
            background: rgba(251, 191, 36, 0.15);
            color: #fbbf24;
        }

        [data-theme="light"] .score-component {
            background: rgba(0, 0, 0, 0.05);
        }

        [data-theme="light"] .score-attack {
            background: rgba(239, 68, 68, 0.1);
        }

        [data-theme="light"] .score-defense {
            background: rgba(16, 185, 129, 0.1);
        }

        [data-theme="light"] .score-penalty {
            background: rgba(251, 191, 36, 0.1);
        }

    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <div class="header-title">
                <div class="title-left">
                    <img src="/static/LOGO-alias-white-nav.svg" alt="Alias Robotics" class="logo" id="main-logo">
                    <h1>CAIBench Attack/Defense CTF</h1>
                </div>
                <span class="by-alias">
                    by <a href="https://aliasrobotics.com" target="_blank" rel="noopener noreferrer">
                        <img src="/static/aliascrop.svg" alt="Alias Robotics" class="alias-text-logo">
                    </a>
                </span>
            </div>
            <div class="game-info">
                <div class="info-item">
                    <span class="info-label">Service:</span>
                    <span id="service-type" class="info-value" style="text-transform: uppercase; font-weight: bold; color: #14b8a6;">Loading...</span>
                </div>
                <div class="info-item">
                    <span class="info-label">Status:</span>
                    <span class="info-value">
                        <span id="status-indicator" class="status-indicator status-stopped"></span>
                        <span id="game-status">Stopped</span>
                    </span>
                </div>
                <div class="info-item">
                    <span class="info-label">Round:</span>
                    <span id="round-number" class="info-value">0</span>
                </div>
                <div class="info-item">
                    <span class="info-label">Time:</span>
                    <span id="game-timer" class="info-value timer">00:00:00</span>
                </div>
            </div>
        </div>

        <div id="status-banner" style="display: none; padding: 12px; margin-bottom: 20px; background: rgba(251, 191, 36, 0.1); border: 1px solid rgba(251, 191, 36, 0.3); border-radius: 8px; text-align: center; color: #fbbf24;">
            <span id="banner-text">Initializing game...</span>
            <span class="loading-spinner"></span>
        </div>

        <div class="controls">
            <h2>Game Controls</h2>
            <div class="controls-center">
                <!-- Theme Toggle -->
                <div class="theme-toggle" id="theme-toggle" onclick="toggleTheme()">
                    <div class="theme-toggle-icons">
                        <svg class="moon-icon" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">
                            <path d="M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z"></path>
                        </svg>
                        <svg class="sun-icon" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">
                            <circle cx="12" cy="12" r="5"></circle>
                            <line x1="12" y1="1" x2="12" y2="3"></line>
                            <line x1="12" y1="21" x2="12" y2="23"></line>
                            <line x1="4.22" y1="4.22" x2="5.64" y2="5.64"></line>
                            <line x1="18.36" y1="18.36" x2="19.78" y2="19.78"></line>
                            <line x1="1" y1="12" x2="3" y2="12"></line>
                            <line x1="21" y1="12" x2="23" y2="12"></line>
                            <line x1="4.22" y1="19.78" x2="5.64" y2="18.36"></line>
                            <line x1="18.36" y1="5.64" x2="19.78" y2="4.22"></line>
                        </svg>
                    </div>
                    <div class="theme-toggle-slider">
                        <svg class="theme-icon" id="active-theme-icon" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">
                            <!-- Will be filled dynamically -->
                        </svg>
                    </div>
                </div>
            </div>
            <div class="control-buttons">
                <button id="btn-start" class="btn btn-start" onclick="startGame()">Start Game</button>
                <button id="btn-stop" class="btn btn-stop" onclick="stopGame()" disabled>Stop Game</button>
            </div>
        </div>

        <!-- Battle View with Team Columns -->
        <div class="battle-view" id="battle-view">
            <!-- Teams will be dynamically populated here -->
            <div style="text-align: center; color: #71717a; flex: 1; padding: 40px;">
                No teams available. Start the game to begin.
            </div>
        </div>

        <!-- Recent Checks (standalone when not 2-team layout) -->
        <div class="card checks" id="checks-card-standalone" style="margin-bottom: 20px;">
            <h2>📊 Recent Checks</h2>
            <div class="check-history" id="check-history">
                <div style="text-align: center; color: #71717a;">No checks performed yet</div>
            </div>
        </div>

        <!-- Bottom Grid for Captures and Submit Flag -->
        <div class="bottom-grid" id="bottom-grid">
            <div class="card captures-card">
                <h2>🚩 Flag Captures</h2>
                <div class="check-history" id="captures-history">
                    <div style="text-align: center; color: #71717a;">No flags captured yet</div>
                </div>
            </div>

            <div class="card submit-card">
                <h2>🚩 Submit Flag</h2>
                <form class="flag-form" onsubmit="submitFlag(event)">
                    <select id="team-select" required>
                        <option value="">Select Your Team</option>
                    </select>
                    <input type="text" id="flag-input" placeholder="CAI_CTF{...}" required>
                    <button type="submit" class="btn btn-start">Submit</button>
                </form>
                <div id="flag-alert" class="alert"></div>
            </div>
        </div>

        <!-- System Logs -->
        <div class="card" style="margin-top: 20px;">
            <h2>📋 System Logs</h2>
            <div class="logs-container" id="logs-container">
                <div class="log-filters">
                    <label class="log-filter">
                        <input type="checkbox" id="filter-info" checked>
                        <span class="log-level-badge log-info">INFO</span>
                    </label>
                    <label class="log-filter">
                        <input type="checkbox" id="filter-warning" checked>
                        <span class="log-level-badge log-warning">WARNING</span>
                    </label>
                    <label class="log-filter">
                        <input type="checkbox" id="filter-error" checked>
                        <span class="log-level-badge log-error">ERROR</span>
                    </label>
                    <label class="log-filter">
                        <input type="checkbox" id="filter-debug">
                        <span class="log-level-badge log-debug">DEBUG</span>
                    </label>
                    <button class="btn-clear-logs" onclick="clearLogs()">Clear</button>
                </div>
                <div class="logs-output" id="logs-output">
                    <div style="text-align: center; color: #71717a;">No logs available</div>
                </div>
            </div>
        </div>

        <!-- API Documentation -->
        <div class="card" style="margin-top: 20px;">
            <h2>📚 API Documentation</h2>
            <div style="padding: 10px 0;">
                <h3 style="color: #a1a1aa; font-size: 1.1em; margin-bottom: 10px;">For Attackers:</h3>
                <p id="api-attackers" style="font-family: monospace; background: rgba(39, 39, 42, 0.5); padding: 12px; border-radius: 8px; margin-bottom: 15px; border: 1px solid rgba(63, 63, 70, 0.4); color: #e4e4e7;">
                    <strong>Submit Flag:</strong> PUT <span class="api-url">http://127.0.0.1:12345</span>/api/submit_flag<br>
                    <strong>Body:</strong> {"team_id": &lt;your_team_number&gt;, "flag": "&lt;captured_flag&gt;"}<br>
                    <strong>Content-Type:</strong> application/json<br>
                    <strong>Note:</strong> team_id is your team number (1 for Team 1, 2 for Team 2, etc.)<br><br>
                    <strong>Example (Team 1 submitting a flag):</strong><br>
                    curl -X PUT <span class="api-url">http://127.0.0.1:12345</span>/api/submit_flag \<br>
                    &nbsp;&nbsp;-H "Content-Type: application/json" \<br>
                    &nbsp;&nbsp;-d '{"team_id": 1, "flag": "CAI_CTF{example_flag}"}'
                </p>

                <h3 style="color: #a1a1aa; font-size: 1.1em; margin-bottom: 10px;">For Defenders:</h3>
                <p id="api-defenders" style="font-family: monospace; background: rgba(39, 39, 42, 0.5); padding: 12px; border-radius: 8px; margin-bottom: 15px; border: 1px solid rgba(63, 63, 70, 0.4); color: #e4e4e7;">
                    <strong>Check Status:</strong> GET <span class="api-url">http://127.0.0.1:12345</span>/api/status<br>
                    <strong>Returns:</strong> Game state, team scores, and service status<br>
                    <strong>Your Team:</strong> Check the "teams" array for your team_id and status
                </p>

                <h3 style="color: #a1a1aa; font-size: 1.1em; margin-bottom: 10px;">Game Server:</h3>
                <p id="api-server" style="font-family: monospace; background: rgba(39, 39, 42, 0.5); padding: 12px; border-radius: 8px; border: 1px solid rgba(63, 63, 70, 0.4); color: #e4e4e7;">
                    <strong>Base URL:</strong> <span class="api-url">http://127.0.0.1:12345</span><br>
                    <strong>Network:</strong> devcontainer_cainet (192.168.3.0/24)<br>
                    <strong>IP Pattern:</strong> 192.168.3.{team}{machine} (Grid allocation)<br>
                    <strong>Examples:</strong> Team 1 Machine 1 = .11, Team 2 Machine 1 = .21
                </p>
            </div>
        </div>
    </div>

    <script>
        let gameStatus = null;
        let startTime = null;
        let timerInterval = null;
        let logsData = [];
        let serverIp = '127.0.0.1';  // Default fallback
        let serverPort = 12345;

        // Theme management
        function initTheme() {
            const savedTheme = localStorage.getItem('theme');
            const systemPrefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches;

            // Default to dark mode if no preference saved, or use system preference
            const theme = savedTheme || (systemPrefersDark ? 'dark' : 'light');

            if (theme === 'light') {
                document.documentElement.setAttribute('data-theme', 'light');
                document.getElementById('theme-toggle').classList.add('light');
                updateThemeIcon('light');
            } else {
                document.documentElement.removeAttribute('data-theme');
                document.getElementById('theme-toggle').classList.remove('light');
                updateThemeIcon('dark');
            }
        }

        function updateThemeIcon(theme) {
            const icon = document.getElementById('active-theme-icon');
            const mainLogo = document.getElementById('main-logo');

            if (theme === 'light') {
                icon.innerHTML = '<circle cx="12" cy="12" r="5"></circle><line x1="12" y1="1" x2="12" y2="3"></line><line x1="12" y1="21" x2="12" y2="23"></line><line x1="4.22" y1="4.22" x2="5.64" y2="5.64"></line><line x1="18.36" y1="18.36" x2="19.78" y2="19.78"></line><line x1="1" y1="12" x2="3" y2="12"></line><line x1="21" y1="12" x2="23" y2="12"></line><line x1="4.22" y1="19.78" x2="5.64" y2="18.36"></line><line x1="18.36" y1="5.64" x2="19.78" y2="4.22"></line>';
                // Switch to light theme logo
                mainLogo.src = '/static/alias.png';
            } else {
                icon.innerHTML = '<path d="M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z"></path>';
                // Switch to dark theme logo
                mainLogo.src = '/static/LOGO-alias-white-nav.svg';
            }
        }

        function toggleTheme() {
            const toggle = document.getElementById('theme-toggle');
            const currentTheme = document.documentElement.getAttribute('data-theme');

            if (currentTheme === 'light') {
                document.documentElement.removeAttribute('data-theme');
                toggle.classList.remove('light');
                localStorage.setItem('theme', 'dark');
                updateThemeIcon('dark');
            } else {
                document.documentElement.setAttribute('data-theme', 'light');
                toggle.classList.add('light');
                localStorage.setItem('theme', 'light');
                updateThemeIcon('light');
            }
        }

        // Update status every 2 seconds
        setInterval(updateStatus, 2000);
        updateStatus();

        // Update logs every 3 seconds
        setInterval(updateLogs, 3000);
        updateLogs();

        async function updateStatus() {
            try {
                const response = await fetch('/api/status');
                const data = await response.json();
                gameStatus = data;

                // Update game status
                const statusIndicator = document.getElementById('status-indicator');
                const gameStatusText = document.getElementById('game-status');
                const btnStart = document.getElementById('btn-start');
                const btnStop = document.getElementById('btn-stop');

                // Check for game winner
                if (data.game_winner) {
                    statusIndicator.className = 'status-indicator status-stopped';
                    gameStatusText.innerHTML = `🏆 WON BY TEAM ${data.game_winner}`;
                    btnStart.disabled = true;
                    btnStop.disabled = true;
                    stopTimer();

                    // Show winner in status banner instead of popup
                    if (!window.winnerShown) {
                        window.winnerShown = true;
                        const banner = document.getElementById('status-banner');
                        const bannerText = document.getElementById('banner-text');
                        banner.style.background = 'linear-gradient(135deg, rgba(251, 191, 36, 0.2) 0%, rgba(251, 146, 60, 0.2) 100%)';
                        banner.style.border = '2px solid #fbbf24';
                        bannerText.innerHTML = `🏆 GAME OVER! Team ${data.game_winner} wins the game!`;
                        banner.style.display = 'block';
                    }
                } else if (data.game_running) {
                    statusIndicator.className = 'status-indicator status-running';
                    gameStatusText.textContent = 'Running';
                    btnStart.disabled = true;
                    btnStop.disabled = false;

                    if (!startTime && data.start_time) {
                        startTime = new Date(data.start_time);
                        startTimer();
                    }
                } else {
                    statusIndicator.className = 'status-indicator status-stopped';
                    gameStatusText.textContent = 'Stopped';
                    btnStart.disabled = false;
                    btnStop.disabled = true;
                    stopTimer();

                    // Reset winner state and hide banner when game is stopped
                    window.winnerShown = false;
                    const banner = document.getElementById('status-banner');
                    if (banner.style.display !== 'none' && banner.innerHTML.includes('GAME OVER')) {
                        banner.style.display = 'none';
                    }
                }

                // Update round number
                document.getElementById('round-number').textContent = data.round || 0;

                // Update server IP and port
                if (data.server_ip) {
                    serverIp = data.server_ip;
                }
                if (data.server_port) {
                    serverPort = data.server_port;
                }

                // Update service name if available
                if (data.service_name) {
                    document.getElementById('service-type').textContent = data.service_name.toUpperCase();
                    // Update page title
                    document.title = `CAIBench A/D CTF - ${data.service_name.toUpperCase()}`;
                }

                // Update API documentation with dynamic IP
                updateApiDocumentation();

                // Update battle view
                updateBattleView(data.teams);

                // Update team selector
                updateTeamSelector(data.teams);

                // Update check history
                updateCheckHistory();

                // Update captures
                updateCaptures();

            } catch (error) {
                console.error('Failed to fetch status:', error);
            }
        }


        function updateBattleView(teams) {
            const battleView = document.getElementById('battle-view');
            const checksStandalone = document.getElementById('checks-card-standalone');
            const bottomGrid = document.getElementById('bottom-grid');

            if (!teams || teams.length === 0) {
                battleView.innerHTML = '<div style="text-align: center; color: #71717a; flex: 1; padding: 40px;">No teams available. Start the game to begin.</div>';
                battleView.classList.remove('two-teams');
                checksStandalone.style.display = 'block';
                bottomGrid.classList.remove('two-teams');
                return;
            }

            // Special layout for 2 teams
            const isTwoTeams = teams.length === 2;
            if (isTwoTeams) {
                battleView.classList.add('two-teams');
                checksStandalone.style.display = 'none';
                bottomGrid.classList.add('two-teams');
            } else {
                battleView.classList.remove('two-teams');
                checksStandalone.style.display = 'block';
                bottomGrid.classList.remove('two-teams');
            }

            // Create team columns
            const teamColumns = teams.map((team, index) => {
                const breakdown = team.score_breakdown || {
                    attack_points: 0,
                    defense_points: 0,
                    penalty_points: 0
                };

                // Build machines list
                let machinesHTML = '';
                if (team.machines && team.machines.length > 0) {
                    machinesHTML = team.machines.map(machine => {
                        const status = machine.service_status || 'UNKNOWN';
                        const scoreBreakdown = machine.score_breakdown || {
                            defense_points: 0,
                            attack_points: 0,
                            penalty_points: 0
                        };

                        // Build machine score breakdown
                        let machineScoreHTML = '';
                        const scoreItems = [];
                        if (scoreBreakdown.defense_points > 0) {
                            scoreItems.push(`<span class="machine-score-item defense">🛡️ +${scoreBreakdown.defense_points}</span>`);
                        }
                        if (scoreBreakdown.attack_points > 0) {
                            scoreItems.push(`<span class="machine-score-item attack">🚩 +${scoreBreakdown.attack_points}</span>`);
                        }
                        if (scoreBreakdown.penalty_points < 0) {
                            scoreItems.push(`<span class="machine-score-item penalty">⚠️ ${scoreBreakdown.penalty_points}</span>`);
                        }

                        // Get model info (distributed mode)
                        // TODO: Add centralized mode support - show team-level model info
                        let modelInfoHTML = '';
                        if (machine.cai_server && machine.cai_server.status === 'running') {
                            const caiModel = machine.cai_server.model || 'unknown';
                            modelInfoHTML = `
                                <div class="cai-model-info">
                                    <span style="opacity: 0.6; font-size: 0.9em;">Model:</span> <span style="font-weight: 600;">${caiModel}</span>
                                </div>
                            `;
                        }

                        if (scoreItems.length > 0 || modelInfoHTML) {
                            const scoreItemsHTML = scoreItems.length > 0 ? `<div style="display: flex; gap: 6px; flex-wrap: wrap;">${scoreItems.join('')}</div>` : '';
                            machineScoreHTML = `
                                <div class="machine-score-breakdown">
                                    ${scoreItemsHTML}
                                    ${modelInfoHTML}
                                </div>
                            `;
                        }

                        // Build flag status indicators
                        const flagStatus = machine.flag_status || {};
                        const userFlagLost = flagStatus.user_flag_lost || 0;
                        const rootFlagLost = flagStatus.root_flag_lost || 0;
                        const userFlagsCaptured = flagStatus.user_flags_captured || 0;
                        const rootFlagsCaptured = flagStatus.root_flags_captured || 0;

                        let flagIndicatorsHTML = '';
                        const flagIndicators = [];

                        // User flag indicator (victim perspective - flag lost)
                        if (userFlagLost > 0) {
                            flagIndicators.push(`
                                <div class="flag-icon captured" title="User flag captured by enemies ${userFlagLost} time(s)">
                                    🏳️ User
                                    <span class="flag-capture-count">${userFlagLost}</span>
                                </div>
                            `);
                        } else {
                            flagIndicators.push(`
                                <div class="flag-icon safe" title="User flag safe">
                                    🏳️ User
                                </div>
                            `);
                        }

                        // Root flag indicator (victim perspective - flag lost)
                        if (rootFlagLost > 0) {
                            flagIndicators.push(`
                                <div class="flag-icon captured" title="Root flag captured by enemies ${rootFlagLost} time(s)">
                                    👑 Root
                                    <span class="flag-capture-count">${rootFlagLost}</span>
                                </div>
                            `);
                        } else {
                            flagIndicators.push(`
                                <div class="flag-icon safe" title="Root flag safe">
                                    👑 Root
                                </div>
                            `);
                        }

                        // Attack success indicators (attacker perspective - flags captured from others)
                        if (userFlagsCaptured > 0) {
                            flagIndicators.push(`
                                <div class="flag-icon secured" title="User flags captured from enemies">
                                    ⚔️ +${userFlagsCaptured} User
                                </div>
                            `);
                        }

                        if (rootFlagsCaptured > 0) {
                            flagIndicators.push(`
                                <div class="flag-icon secured" title="Root flags captured from enemies">
                                    ⚔️ +${rootFlagsCaptured} Root
                                </div>
                            `);
                        }

                        if (flagIndicators.length > 0) {
                            flagIndicatorsHTML = `
                                <div class="flag-indicators">
                                    ${flagIndicators.join('')}
                                </div>
                            `;
                        }

                        // CAI server link (distributed mode - per machine)
                        // TODO: Add centralized mode support - show team-level CAI server link
                        let caiServerHTML = '';
                        if (machine.cai_server) {
                            const caiStatus = machine.cai_server.status || 'unknown';
                            const caiUrl = machine.cai_server.url;
                            const caiPort = machine.cai_server.port;
                            const caiModel = machine.cai_server.model || 'unknown';

                            if (caiStatus === 'running' && caiUrl) {
                                caiServerHTML = `
                                    <a href="${caiUrl}" target="_blank" class="cai-server-link" title="Open CAI Agent Interface - Port ${caiPort}">
                                        <img src="/static/alias.png" class="cai-logo-img" alt="Alias">
                                        <span style="font-weight: 700;">CAI</span>
                                    </a>
                                `;
                            } else if (caiStatus === 'failed') {
                                caiServerHTML = `
                                    <div class="cai-server-link failed" title="CAI server failed to start">
                                        <span class="cai-icon">⚠️</span>
                                        <span>CAI Server Failed</span>
                                    </div>
                                `;
                            }
                        }

                        return `
                            <div class="machine-card">
                                <div class="machine-header">
                                    <div class="machine-name">🖥️ ${machine.name}</div>
                                    <div class="machine-status-badge ${status}">${status}</div>
                                </div>
                                <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 10px;">
                                    <div class="machine-ip">${machine.ip}</div>
                                    ${caiServerHTML}
                                </div>
                                ${machineScoreHTML}
                                ${flagIndicatorsHTML}
                                <div style="margin-top: 12px;">
                                    <button class="btn-reset-machine" onclick="resetMachine(${team.id}, '${machine.name}')" title="Reset machine to fresh state (keeps password and flags)">
                                        🔄 Reset Machine
                                    </button>
                                </div>
                            </div>
                        `;
                    }).join('');
                } else {
                    machinesHTML = '<div style="color: #71717a; text-align: center; padding: 20px;">No machines</div>';
                }

                // Score breakdown display
                const scoreBreakdownHTML = `
                    <div class="score-details" style="margin-top: 10px;">
                        ${breakdown.attack_points > 0 ? `<span class="score-component score-attack">🚩 +${breakdown.attack_points}</span>` : ''}
                        ${breakdown.defense_points > 0 ? `<span class="score-component score-defense">🛡️ +${breakdown.defense_points}</span>` : ''}
                        ${breakdown.penalty_points < 0 ? `<span class="score-component score-penalty">⚠️ ${breakdown.penalty_points}</span>` : ''}
                    </div>
                `;

                // Format score with + or - sign
                const scoreSign = team.score >= 0 ? '+' : '';
                const formattedScore = `${scoreSign}${team.score}`;

                // Model badge (only show in centralized mode)
                const modelBadgeHTML = team.agent_mode === 'centralized' && team.model
                    ? `<div class="team-model">🤖 ${team.model}</div>`
                    : '';

                return `
                    <div class="team-column team-${team.id}">
                        <div class="team-header">
                            <div>
                                <div class="team-name">${team.name}</div>
                                ${modelBadgeHTML}
                                ${scoreBreakdownHTML}
                            </div>
                            <div class="team-score">${formattedScore}</div>
                        </div>
                        <div class="machines-list">
                            ${machinesHTML}
                        </div>
                    </div>
                `;
            });

            // For 2 teams, insert checks in the middle
            if (isTwoTeams) {
                // Build the middle checks column
                const checksColumn = `
                    <div class="center-checks">
                        <h2>📊 Recent Checks</h2>
                        <div class="check-history" id="check-history-center">
                            <div style="text-align: center; color: #71717a;">No checks performed yet</div>
                        </div>
                    </div>
                `;

                // Insert checks between team 1 and team 2
                battleView.innerHTML = teamColumns[0] + checksColumn + teamColumns[1];

                // Sync heights after DOM is updated
                setTimeout(() => syncTwoTeamHeights(), 0);
            } else {
                battleView.innerHTML = teamColumns.join('');
            }
        }

        function syncTwoTeamHeights() {
            const battleView = document.getElementById('battle-view');
            if (!battleView.classList.contains('two-teams')) return;

            const teamColumns = battleView.querySelectorAll('.team-column');
            const centerChecks = battleView.querySelector('.center-checks');

            if (teamColumns.length !== 2 || !centerChecks) return;

            // Get the maximum height of the team columns
            const maxHeight = Math.max(teamColumns[0].offsetHeight, teamColumns[1].offsetHeight);

            // Set the center checks to match that height
            centerChecks.style.height = maxHeight + 'px';
        }

        function updateTeamSelector(teams) {
            const select = document.getElementById('team-select');
            const currentValue = select.value;

            if (teams && teams.length > 0) {
                select.innerHTML = '<option value="">Select Your Team</option>' +
                    teams.map(team => `<option value="${team.id}">${team.name}</option>`).join('');

                // Restore previous selection if it exists
                if (currentValue) {
                    select.value = currentValue;
                }
            }
        }

        async function updateCheckHistory() {
            try {
                const response = await fetch('/api/history');
                const history = await response.json();

                const container = document.getElementById('check-history');
                const containerCenter = document.getElementById('check-history-center');

                const emptyHTML = '<div style="text-align: center; color: #71717a;">No checks performed yet</div>';

                if (!history || history.length === 0) {
                    if (container) container.innerHTML = emptyHTML;
                    if (containerCenter) containerCenter.innerHTML = emptyHTML;
                    return;
                }

                const historyHTML = history.reverse().map(round => {
                    const timestamp = new Date(round.timestamp).toLocaleString();
                    return `
                        <div class="check-entry">
                            <div class="check-timestamp">Round ${round.round} - ${timestamp}</div>
                            <div class="check-results">
                                ${round.results.map(result => {
                                    if (result.error) {
                                        const machineName = result.machine_name ? ` (${result.machine_name})` : '';
                                        return `<span class="check-item check-fail">Team ${result.team_id}${machineName}: ✗ Error - ${result.error}</span>`;
                                    }
                                    const status = result.checks?.overall || 'UNKNOWN';
                                    const statusMessage = result.status_message || status;
                                    const machineName = result.machine_name ? ` (${result.machine_name})` : '';

                                    // Just use the status message without redundant details
                                    const displayMessage = statusMessage;

                                    const statusClass = status === 'OK' ? 'check-ok' :
                                                      status === 'CORRUPT' ? 'check-warning' :
                                                      status === 'MUMBLE' ? 'check-warning' : 'check-fail';
                                    return `<span class="check-item ${statusClass}">
                                        Team ${result.team_id}${machineName}: ${displayMessage}
                                    </span>`;
                                }).join('')}
                            </div>
                        </div>
                    `;
                }).join('');

                // Update both containers
                if (container) container.innerHTML = historyHTML;
                if (containerCenter) containerCenter.innerHTML = historyHTML;
            } catch (error) {
                console.error('Failed to fetch history:', error);
            }
        }

        async function updateCaptures() {
            try {
                const response = await fetch('/api/captures');
                const captures = await response.json();

                const container = document.getElementById('captures-history');

                if (!captures || captures.length === 0) {
                    container.innerHTML = '<div style="text-align: center; color: #71717a;">No flags captured yet</div>';
                    return;
                }

                container.innerHTML = captures.reverse().map(capture => {
                    const timestamp = new Date(capture.timestamp).toLocaleString();
                    const flagIcon = capture.flag_type === 'root_flag' ? '👑' : '🏳️';
                    const flagLabel = capture.flag_type === 'root_flag' ? 'ROOT FLAG' : 'USER FLAG';
                    const captureClass = capture.flag_type === 'root_flag' ? 'check-fail' : 'check-warning';
                    const machineName = capture.machine_name ? ` (${capture.machine_name})` : '';

                    return `
                        <div class="check-entry">
                            <div class="check-timestamp">Round ${capture.round} - ${timestamp}</div>
                            <div class="check-results">
                                <span class="check-item ${captureClass}">
                                    ${flagIcon} Team ${capture.attacker_team} captured ${flagLabel} from Team ${capture.victim_team}${machineName} (+${capture.points} pts)
                                </span>
                            </div>
                        </div>
                    `;
                }).join('');
            } catch (error) {
                console.error('Failed to fetch captures:', error);
            }
        }

        async function updateLogs() {
            try {
                const response = await fetch('/api/logs');
                const logs = await response.json();
                logsData = logs;
                renderLogs();
            } catch (error) {
                console.error('Failed to fetch logs:', error);
            }
        }

        function renderLogs() {
            const container = document.getElementById('logs-output');
            const showInfo = document.getElementById('filter-info').checked;
            const showWarning = document.getElementById('filter-warning').checked;
            const showError = document.getElementById('filter-error').checked;
            const showDebug = document.getElementById('filter-debug').checked;

            if (!logsData || logsData.length === 0) {
                container.innerHTML = '<div style="text-align: center; color: #71717a;">No logs available</div>';
                return;
            }

            const filteredLogs = logsData.filter(log => {
                if (log.level === 'INFO' && !showInfo) return false;
                if (log.level === 'WARNING' && !showWarning) return false;
                if (log.level === 'ERROR' && !showError) return false;
                if (log.level === 'DEBUG' && !showDebug) return false;
                return true;
            });

            if (filteredLogs.length === 0) {
                container.innerHTML = '<div style="text-align: center; color: #71717a;">No logs match current filters</div>';
                return;
            }

            container.innerHTML = filteredLogs.map(log => {
                const levelClass = log.level.toLowerCase();
                return `
                    <div class="log-entry ${levelClass}">
                        <span class="log-timestamp">${log.timestamp}</span>
                        <span class="log-level-badge log-${levelClass}">${log.level}</span>
                        <span class="log-message">${log.message}</span>
                    </div>
                `;
            }).join('');

            // Auto-scroll to bottom
            container.scrollTop = container.scrollHeight;
        }

        function clearLogs() {
            logsData = [];
            renderLogs();
        }

        // Add event listeners for filters and initialize theme
        document.addEventListener('DOMContentLoaded', () => {
            // Initialize theme first
            initTheme();

            // Add log filter event listeners
            document.getElementById('filter-info').addEventListener('change', renderLogs);
            document.getElementById('filter-warning').addEventListener('change', renderLogs);
            document.getElementById('filter-error').addEventListener('change', renderLogs);
            document.getElementById('filter-debug').addEventListener('change', renderLogs);
        });

        function updateApiDocumentation() {
            // Update all API URL references with the dynamic IP
            const apiUrls = document.querySelectorAll('.api-url');
            apiUrls.forEach(element => {
                element.textContent = `http://${serverIp}:${serverPort}`;
            });
        }

        function startTimer() {
            if (timerInterval) return;

            timerInterval = setInterval(() => {
                if (!startTime) return;

                const now = new Date();
                const diff = Math.floor((now - startTime) / 1000);

                const hours = Math.floor(diff / 3600);
                const minutes = Math.floor((diff % 3600) / 60);
                const seconds = diff % 60;

                const timer = document.getElementById('game-timer');
                timer.textContent = `${String(hours).padStart(2, '0')}:${String(minutes).padStart(2, '0')}:${String(seconds).padStart(2, '0')}`;
            }, 1000);
        }

        function stopTimer() {
            if (timerInterval) {
                clearInterval(timerInterval);
                timerInterval = null;
            }
            startTime = null;
            document.getElementById('game-timer').textContent = '00:00:00';
        }

        function showStatusBanner(text, duration = 3000) {
            const banner = document.getElementById('status-banner');
            const bannerText = document.getElementById('banner-text');

            bannerText.textContent = text;
            banner.style.display = 'block';

            if (duration > 0) {
                setTimeout(() => {
                    banner.style.display = 'none';
                }, duration);
            }
        }

        function hideStatusBanner() {
            document.getElementById('status-banner').style.display = 'none';
        }

        let startGameConfirm = false;
        let stopGameConfirm = false;
        let confirmTimeout = null;

        async function startGame() {
            const btn = document.getElementById('btn-start');

            if (!startGameConfirm) {
                // First click - change button state
                startGameConfirm = true;
                btn.classList.add('confirm');
                btn.textContent = 'Click Again to Start';

                // Reset after 3 seconds if not clicked
                confirmTimeout = setTimeout(() => {
                    startGameConfirm = false;
                    btn.classList.remove('confirm');
                    btn.textContent = 'Start Game';
                }, 3000);
            } else {
                // Second click - actually start the game
                clearTimeout(confirmTimeout);
                startGameConfirm = false;

                try {
                    showStatusBanner('Starting game...', 3000);

                    const response = await fetch('/api/start_game', { method: 'POST' });
                    const result = await response.json();

                    if (result.status === 'success') {
                        showStatusBanner('Starting game...', 2000);
                        setTimeout(updateStatus, 1000);
                    } else {
                        hideStatusBanner();
                        showAlert(result.message || 'Failed to start game', 'error');
                    }
                } catch (error) {
                    hideStatusBanner();
                    showAlert('Error starting game: ' + error.message, 'error');
                }

                btn.classList.remove('confirm');
                btn.textContent = 'Start Game';
            }
        }

        async function stopGame() {
            const btn = document.getElementById('btn-stop');

            if (!stopGameConfirm) {
                // First click - change button state
                stopGameConfirm = true;
                btn.classList.add('confirm');
                btn.textContent = 'Click Again to Stop';

                // Reset after 3 seconds if not clicked
                confirmTimeout = setTimeout(() => {
                    stopGameConfirm = false;
                    btn.classList.remove('confirm');
                    btn.textContent = 'Stop Game';
                }, 3000);
            } else {
                // Second click - actually stop the game
                clearTimeout(confirmTimeout);
                stopGameConfirm = false;

                try {
                    const response = await fetch('/api/stop_game', { method: 'POST' });
                    const result = await response.json();

                    if (result.status === 'success') {
                        showStatusBanner('Game stopped successfully!', 2000);
                        updateStatus();
                    } else {
                        showAlert(result.message || 'Failed to stop game', 'error');
                    }
                } catch (error) {
                    showAlert('Error stopping game: ' + error.message, 'error');
                }

                btn.classList.remove('confirm');
                btn.textContent = 'Stop Game';
            }
        }

        async function resetMachine(teamId, machineName) {
            if (!confirm(`Are you sure you want to reset ${machineName} for Team ${teamId}?\n\nThis will:\n- Recreate the container from registry\n- Keep the same SSH password\n- Keep the same flags\n- Remove all changes/patches made to the machine`)) {
                return;
            }

            showStatusBanner(`Resetting ${machineName} for Team ${teamId}...`, 0);

            try {
                const response = await fetch('/api/reset_machine', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        team_id: teamId,
                        machine_name: machineName
                    })
                });

                const result = await response.json();

                if (result.status === 'success') {
                    showStatusBanner(`✅ ${machineName} reset successfully for Team ${teamId}`, 3000);
                    // Refresh the status to show updated machine info
                    await updateStatus();
                } else {
                    showStatusBanner(`❌ Failed to reset: ${result.message}`, 5000);
                }
            } catch (error) {
                console.error('Failed to reset machine:', error);
                showStatusBanner(`❌ Error resetting machine: ${error.message}`, 5000);
            }
        }

        async function submitFlag(event) {
            event.preventDefault();

            const teamId = document.getElementById('team-select').value;
            const flag = document.getElementById('flag-input').value;
            const submitBtn = event.target.querySelector('button[type="submit"]');

            if (!teamId || !flag) {
                showAlert('Please select a team and enter a flag', 'error');
                return;
            }

            // Disable submit button to prevent double submission
            submitBtn.disabled = true;
            submitBtn.textContent = 'Submitting...';

            try {
                // Add timeout to prevent hanging
                const controller = new AbortController();
                const timeoutId = setTimeout(() => controller.abort(), 5000); // 5 second timeout

                const response = await fetch('/api/submit_flag', {
                    method: 'PUT',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ team_id: parseInt(teamId), flag: flag }),
                    signal: controller.signal
                });

                clearTimeout(timeoutId);

                let result;
                try {
                    result = await response.json();
                } catch (jsonError) {
                    console.error('Failed to parse JSON:', jsonError);
                    throw new Error('Invalid response from server');
                }

                if (result.status === 'success') {
                    let message = `Flag accepted! +${result.points} points`;
                    if (result.flag_type === 'root_flag') {
                        message = `🏆 ROOT FLAG CAPTURED! +${result.points} points - GAME WON!`;
                    } else if (result.flag_type === 'user_flag') {
                        message = `User flag from Team ${result.victim_team} captured! +${result.points} points`;
                    }
                    showAlert(message, 'success');
                    document.getElementById('flag-input').value = '';
                    updateStatus();

                    if (result.game_over) {
                        // Show game over in status banner instead of popup
                        const banner = document.getElementById('status-banner');
                        const bannerText = document.getElementById('banner-text');
                        banner.style.background = 'linear-gradient(135deg, rgba(251, 191, 36, 0.2) 0%, rgba(251, 146, 60, 0.2) 100%)';
                        banner.style.border = '2px solid #fbbf24';
                        bannerText.innerHTML = `🏆 GAME OVER! You won the game!`;
                        banner.style.display = 'block';
                    }
                } else {
                    showAlert(result.message || 'Invalid flag', 'error');
                    // Don't clear the input so user can check what they typed
                }
            } catch (error) {
                console.error('Flag submission error:', error);
                if (error.name === 'AbortError') {
                    showAlert('Request timed out. Please try again.', 'error');
                } else {
                    showAlert('Error submitting flag: ' + error.message, 'error');
                }
            } finally {
                // Re-enable submit button
                submitBtn.disabled = false;
                submitBtn.textContent = 'Submit';
            }
        }

        function showAlert(message, type) {
            const alert = document.getElementById('flag-alert');
            alert.textContent = message;
            alert.className = `alert alert-${type}`;
            alert.style.display = 'block';

            setTimeout(() => {
                alert.style.display = 'none';
            }, 5000);
        }
    </script>
</body>
</html>