<!DOCTYPE html>
<html lang="<%= lang %>">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover">
    <title><%= t('leaderboard.playersTitle') %> | <%= botName %></title>
    <meta name="description" content="<%= t('leaderboard.playersSubtitle') %>, kills, and win rate.">
    <link rel="icon" type="image/png" href="/images/transparent_toothlessssss.png">
    
    <!-- Fonts -->
    <link rel="preconnect" href="https://fonts.googleapis.com" crossorigin>
    <link rel="preload" href="/Fonts/symbols_skyquake.ttf" as="font" type="font/ttf" crossorigin="anonymous">
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800&display=swap" rel="stylesheet">
    
    <!-- Tailwind CSS -->
    <link rel="stylesheet" href="/css/output.css">
    
    <!-- Font Awesome -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" media="print" onload="this.media='all'">
    
    <style>
        @font-face {
            font-family: 'skyquakesymbols';
            src: url('/Fonts/symbols_skyquake.ttf') format('truetype');
            font-display: swap;
        }
        
        body {
            background: #1b1b1b;
            min-height: 100vh;
        }
        
        .text-accent { color: #F5F5DC; }
        .text-muted { color: #90EE90; }
        
        .btn-primary {
            background: linear-gradient(135deg, #F5F5DC 0%, #E8E8D0 100%);
            box-shadow: 0 4px 20px rgba(245, 245, 220, 0.15), inset 0 1px 0 rgba(255, 255, 255, 0.4);
            color: #1E1E1E;
            font-weight: 700;
            transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
        }

        .btn-primary:hover {
            box-shadow: 0 8px 25px rgba(245, 245, 220, 0.3), inset 0 1px 0 rgba(255, 255, 255, 0.4);
            transform: translateY(-2px);
        }
        
        .leaderboard-container {
            max-width: 1400px;
            margin: 0 auto;
            padding: 6rem 1rem 2rem; 
            min-height: calc(100vh - 200px);
        }
        
        .leaderboard-header {
            text-align: center;
            margin-bottom: 2rem;
        }
        
        .leaderboard-title {
            font-size: 2.5rem;
            font-weight: 700;
            margin-bottom: 0.5rem;
            background: linear-gradient(135deg, #F5F5DC 0%, #E8E8D0 100%);
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
            background-clip: text;
        }
        
        .leaderboard-subtitle {
            font-size: 1.1rem;
            color: rgba(255, 255, 255, 0.8);
            margin-bottom: 1rem;
        }
        
        .disclaimer {
            font-size: 0.9rem;
            opacity: 0.8;
            font-style: italic;
            color: rgba(255, 255, 255, 0.7);
        }
        
        .leaderboard-nav {
            background: rgba(30, 30, 30, 0.6);
            border-radius: 1rem;
            padding: 1rem;
            backdrop-filter: blur(10px);
            border: 1px solid rgba(144, 238, 144, 0.1);
            margin-bottom: 2rem;
            display: flex;
            justify-content: center;
            gap: 1rem;
            flex-wrap: wrap;
        }

        .leaderboard-tab {
            padding: 0.75rem 1.5rem;
            background: rgba(30, 30, 30, 0.8);
            border: 1px solid rgba(144, 238, 144, 0.2);
            border-radius: 0.5rem;
            color: #ffffff;
            text-decoration: none;
            font-weight: 500;
            transition: all 0.3s ease;
        }

        .leaderboard-tab:hover {
            background: rgba(144, 238, 144, 0.1);
            color: #90EE90;
            border-color: #90EE90;
            text-shadow: 0 0 10px rgba(144, 238, 144, 0.3);
        }

        .leaderboard-tab.active {
            background: linear-gradient(135deg, rgba(144, 238, 144, 0.15), rgba(144, 238, 144, 0.05));
            color: #90EE90;
            border-color: #90EE90;
            text-shadow: 0 0 15px rgba(144, 238, 144, 0.6);
        }

        .leaderboard-content {
            background: rgba(30, 30, 30, 0.6);
            border-radius: 1rem;
            padding: 2rem;
            backdrop-filter: blur(10px);
            border: 1px solid rgba(144, 238, 144, 0.1);
        }
        
        .loading-state {
            text-align: center;
            padding: 4rem;
            color: #90EE90;
        }
        
        .loading-spinner {
            border: 3px solid rgba(144, 238, 144, 0.3);
            border-top: 3px solid #90EE90;
            border-radius: 50%;
            width: 40px;
            height: 40px;
            animation: spin 1s linear infinite;
            margin: 0 auto 1rem;
        }
        
        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }
        
        .leaderboard-table {
            width: 100%;
            border-collapse: collapse;
            background: rgba(30, 30, 30, 0.8);
            border-radius: 0.75rem;
            overflow: hidden;
            box-shadow: 0 8px 32px rgba(0, 0, 0, 0.3);
            border: 1px solid rgba(144, 238, 144, 0.1);
            table-layout: auto;
            min-width: 800px;
        }
        
        .leaderboard-table th {
            background: linear-gradient(135deg, rgba(144, 238, 144, 0.15), rgba(144, 238, 144, 0.05));
            color: #F5F5DC;
            padding: 1.25rem;
            text-align: center;
            font-weight: 600;
            border-bottom: 1px solid rgba(144, 238, 144, 0.2);
            font-size: 0.95rem;
            text-transform: uppercase;
            letter-spacing: 0.5px;
            text-shadow: 0 0 10px rgba(144, 238, 144, 0.3);
        }
        
        .leaderboard-table th:first-child {
            text-align: left;
        }
        
        .leaderboard-table td {
            padding: 1rem;
            border-bottom: 1px solid rgba(144, 238, 144, 0.1);
            background: rgba(30, 30, 30, 0.4);
            color: #ffffff;
            transition: all 0.3s ease;
            text-align: center;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
        }
        
        /* Specific column widths for players */
        .leaderboard-table th:nth-child(1), 
        .leaderboard-table td:nth-child(1) {
            width: 80px;
            min-width: 80px;
        }
        
        .leaderboard-table th:nth-child(2), 
        .leaderboard-table td:nth-child(2) {
            width: 30%;
            min-width: 200px;
            text-align: left !important;
            white-space: normal;
            word-wrap: break-word;
            max-width: 300px;
        }
        
        .leaderboard-table th:nth-child(3), 
        .leaderboard-table td:nth-child(3),
        .leaderboard-table th:nth-child(4), 
        .leaderboard-table td:nth-child(4),
        .leaderboard-table th:nth-child(5), 
        .leaderboard-table td:nth-child(5),
        .leaderboard-table th:nth-child(6), 
        .leaderboard-table td:nth-child(6),
        .leaderboard-table th:nth-child(7), 
        .leaderboard-table td:nth-child(7),
        .leaderboard-table th:nth-child(8), 
        .leaderboard-table td:nth-child(8),
        .leaderboard-table th:nth-child(9), 
        .leaderboard-table td:nth-child(9) {
            width: 110px;
            min-width: 110px;
        }
        
        .leaderboard-table td:first-child {
            text-align: left;
        }
        
        .leaderboard-table tr:hover td {
            background: rgba(144, 238, 144, 0.05);
            cursor: pointer;
        }
        
        .leaderboard-table tr:last-child td {
            border-bottom: none;
        }
        
        .rank-cell {
            font-weight: 700;
            font-size: 1.1rem;
            width: 80px;
        }
        
        .rank-1 { color: #ffd700; text-shadow: 0 0 10px rgba(255, 215, 0, 0.5); }
        .rank-2 { color: #c0c0c0; text-shadow: 0 0 10px rgba(192, 192, 192, 0.5); }
        .rank-3 { color: #cd7f32; text-shadow: 0 0 10px rgba(205, 127, 50, 0.5); }
        
        .player-info {
            display: flex;
            align-items: center;
            gap: 0.75rem;
        }
        
        .player-nick {
            font-weight: 600;
            color: #90EE90;
            font-size: 1.1rem;
            text-shadow: 0 0 10px rgba(144, 238, 144, 0.3);
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 0.5rem;
        }
        .player-nick .pdm-details-btn {
            display: inline-flex;
            align-items: center;
            justify-content: center;
            background: transparent;
            border: 1px solid rgba(144,238,144,0.15);
            color: rgba(144,238,144,0.5);
            width: 22px; height: 22px;
            border-radius: 4px;
            cursor: pointer;
            font-size: 0.65rem;
            margin-left: 0;
            vertical-align: middle;
            padding: 0;
            flex-shrink: 0;
            transition: all 0.2s;
        }
        .player-nick .pdm-details-btn:hover {
            background: rgba(144,238,144,0.12);
            color: #90EE90;
            border-color: rgba(144,238,144,0.4);
        }

        .player-squadron {
            font-family: 'skyquakesymbols', 'Inter', sans-serif !important;
            font-size: 0.85rem;
            color: rgba(255, 255, 255, 0.4);
            font-weight: 500;
            margin-right: 0.5rem;
        }
        
        .stat-cell {
            font-weight: 600;
            font-size: 1rem;
        }
        
        /* Consistent green color scheme for all stats */
        .stat-score,
        .stat-kills,
        .stat-kills-per-spawn,
        .stat-kdr,
        .stat-winrate,
        .stat-battles,
        .stat-wins,
        .stat-assists,
        .stat-captures {
            color: #90EE90;
            text-shadow: 0 0 10px rgba(144, 238, 144, 0.5);
        }
        
        .error-state {
            text-align: center;
            padding: 4rem;
            color: #ff3838;
        }
        
        .error-icon {
            font-size: 3rem;
            margin-bottom: 1rem;
        }
        
        .retry-btn {
            background: linear-gradient(135deg, #F5F5DC 0%, #E8E8D0 100%);
            color: #1E1E1E;
            border: none;
            padding: 0.75rem 1.5rem;
            border-radius: 0.5rem;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s ease;
            margin-top: 1rem;
        }
        
        .retry-btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 6px 20px rgba(245, 245, 220, 0.4);
        }
        
        .responsive-table {
            overflow-x: auto;
            -webkit-overflow-scrolling: touch;
        }
        
        /* Controls and Filters */
        .leaderboard-controls {
            background: rgba(30, 30, 30, 0.6);
            border-radius: 1rem;
            padding: 1.5rem;
            backdrop-filter: blur(10px);
            border: 1px solid rgba(144, 238, 144, 0.1);
            margin-bottom: 2rem;
        }
        
        .controls-row {
            display: flex;
            gap: 1.5rem;
            align-items: end;
            flex-wrap: wrap;
            margin-bottom: 1.5rem;
        }

        .sort-btn-group {
            display: flex;
            gap: 0.5rem;
        }

        .sort-mode-btn {
            flex: 1;
            padding: 0.75rem 1rem;
            background: rgba(30, 30, 30, 0.9);
            border: 2px solid rgba(144, 238, 144, 0.2);
            border-radius: 0.75rem;
            color: rgba(255, 255, 255, 0.6);
            font-size: 0.9rem;
            font-weight: 500;
            font-family: inherit;
            cursor: pointer;
            transition: all 0.2s ease;
            white-space: nowrap;
        }

        .sort-mode-btn:hover {
            border-color: rgba(144, 238, 144, 0.5);
            color: #ffffff;
        }

        .sort-mode-btn.active {
            border-color: #90EE90;
            color: #90EE90;
            background: rgba(144, 238, 144, 0.08);
        }
        
        .search-section {
            display: flex;
            flex-direction: column;
            gap: 0.75rem;
        }
        
        .search-section label {
            color: #ffffff;
            font-weight: 600;
            font-size: 1rem;
            margin-bottom: 0;
        }
        
        .search-input-wrapper {
            position: relative;
        }
        
        .search-input-icon {
            position: absolute;
            left: 1rem;
            top: 50%;
            transform: translateY(-50%);
            color: #90EE90;
            font-size: 1.1rem;
            z-index: 2;
        }
        
        .filter-input {
            width: 100%;
            padding: 1rem 1rem 1rem 2.75rem;
            background: rgba(30, 30, 30, 0.9);
            border: 2px solid rgba(144, 238, 144, 0.2);
            border-radius: 0.75rem;
            color: #ffffff;
            font-size: 1rem;
            font-weight: 500;
            transition: all 0.3s ease;
            backdrop-filter: blur(10px);
            box-shadow: 0 4px 15px rgba(0, 0, 0, 0.2);
        }
        
        .filter-input:focus {
            outline: none;
            border-color: #90EE90;
            box-shadow: 0 0 20px rgba(144, 238, 144, 0.4), 0 4px 25px rgba(0, 0, 0, 0.3);
        }
        
        .filter-input:hover {
            border-color: rgba(144, 238, 144, 0.5);
            box-shadow: 0 6px 20px rgba(0, 0, 0, 0.25);
        }
        
        .filter-input::placeholder {
            color: rgba(255, 255, 255, 0.6);
            font-weight: 400;
        }
        
        .filter-group {
            display: flex;
            flex-direction: column;
            gap: 0.75rem;
        }
        
        .filter-group label {
            color: #ffffff;
            font-weight: 600;
            font-size: 1rem;
            white-space: nowrap;
        }
        
        .filter-select {
            padding: 1rem;
            background: rgba(30, 30, 30, 0.9);
            border: 2px solid rgba(144, 238, 144, 0.2);
            border-radius: 0.75rem;
            color: #ffffff;
            font-size: 1rem;
            font-weight: 500;
            transition: all 0.3s ease;
            backdrop-filter: blur(10px);
            box-shadow: 0 4px 15px rgba(0, 0, 0, 0.2);
            min-width: 150px;
        }
        
        .filter-select:focus {
            outline: none;
            border-color: #90EE90;
            box-shadow: 0 0 20px rgba(144, 238, 144, 0.4), 0 4px 25px rgba(0, 0, 0, 0.3);
        }
        
        .filter-select:hover {
            border-color: rgba(144, 238, 144, 0.5);
            box-shadow: 0 6px 20px rgba(0, 0, 0, 0.25);
        }
        
        .clear-filters-btn {
            background: linear-gradient(135deg, rgba(239, 68, 68, 0.2), rgba(220, 38, 38, 0.2));
            border: 1px solid rgba(239, 68, 68, 0.3);
            color: #ef4444;
            padding: 0.5rem 1rem;
            border-radius: 0.5rem;
            cursor: pointer;
            font-weight: 500;
            transition: all 0.3s ease;
        }
        
        .clear-filters-btn:hover {
            background: linear-gradient(135deg, rgba(239, 68, 68, 0.3), rgba(220, 38, 38, 0.3));
            border-color: #ef4444;
            text-shadow: 0 0 10px rgba(239, 68, 68, 0.5);
        }
        
        .results-info {
            color: #90EE90;
            font-weight: 600;
            text-align: center;
        }
        
        /* Sortable Headers */
        .sortable {
            cursor: pointer;
            position: relative;
            user-select: none;
        }
        
        .sortable:hover {
            background: linear-gradient(135deg, rgba(144, 238, 144, 0.3), rgba(144, 238, 144, 0.15));
        }
        
        .sort-icon {
            font-size: 0.8rem;
            opacity: 0.6;
            margin-left: 0.5rem;
        }
        
        .sortable.sorted-asc .sort-icon {
            opacity: 1;
        }
        
        .sortable.sorted-asc .sort-icon::before {
            content: "\f0de"; /* fa-sort-up */
        }
        
        .sortable.sorted-desc .sort-icon {
            opacity: 1;
        }
        
        .sortable.sorted-desc .sort-icon::before {
            content: "\f0dd"; /* fa-sort-down */
        }
        
        /* Pagination */
        .pagination-controls {
            display: flex;
            justify-content: center;
            align-items: center;
            gap: 1rem;
            margin-top: 2rem;
            padding: 1rem;
            background: rgba(30, 30, 30, 0.6);
            border-radius: 1rem;
            backdrop-filter: blur(10px);
            border: 1px solid rgba(144, 238, 144, 0.1);
        }
        
        .pagination-btn {
            background: rgba(30, 30, 30, 0.8);
            border: 1px solid rgba(144, 238, 144, 0.2);
            color: #ffffff;
            padding: 0.5rem 0.75rem;
            border-radius: 0.5rem;
            cursor: pointer;
            transition: all 0.3s ease;
            font-size: 0.9rem;
        }
        
        .pagination-btn:hover:not(:disabled) {
            background: rgba(144, 238, 144, 0.1);
            border-color: #90EE90;
            color: #90EE90;
        }
        
        .pagination-btn:disabled {
            opacity: 0.5;
            cursor: not-allowed;
        }
        
        .pagination-info {
            color: #90EE90;
            font-weight: 600;
            margin: 0 1rem;
        }
        
        /* Center align table content */
        .leaderboard-table td {
            text-align: center;
            vertical-align: middle;
        }
        
        .player-info {
            text-align: center;
        }
        
        .player-nick {
            text-align: center;
        }
        
    </style>
</head>

<body class="text-white antialiased">
    <%- include('partials/nav', { activePage: 'leaderboards' }) %>

    <div class="leaderboard-container">
        <div class="leaderboard-header">
            <h1 class="leaderboard-title"><%= t('leaderboard.playersTitle') %></h1>
            <p class="leaderboard-subtitle"><%= t('leaderboard.playersSubtitle') %></p>
            <div class="disclaimer">
                <i class="fas fa-info-circle" style="margin-right: 0.5rem;"></i>
                <%= t('common.recordingSince') %> • <%= t('leaderboard.minimumBattlesRequired') %>
            </div>
        </div>
        
        <div class="leaderboard-nav">
            <a href="/leaderboard/players" class="leaderboard-tab active">
                <i class="fas fa-user"></i> <%= t('common.players') %>
            </a>
            <a href="/leaderboard/vehicles" class="leaderboard-tab">
                <i class="fas fa-fighter-jet"></i> <%= t('common.vehicles') %>
            </a>
            <a href="/leaderboard/squadrons" class="leaderboard-tab">
                <i class="fas fa-users"></i> <%= t('common.squadrons') %>
            </a>
            <a href="/leaderboard/stats" class="leaderboard-tab">
                <i class="fas fa-chart-bar"></i> <%= t('common.statistics') %>
            </a>
            <a href="/leaderboard/comparison" class="leaderboard-tab">
                <i class="fas fa-balance-scale"></i> <%= t('common.comparison') %>
            </a>
        </div>
        
        <div class="leaderboard-controls">
            <div class="controls-row">
                <div class="search-section">
                    <label for="playerSearch"><%= t('leaderboard.searchPlayer') %></label>
                    <div class="search-input-wrapper">
                        <i class="fas fa-search search-input-icon"></i>
                        <input type="text" id="playerSearch" class="filter-input" placeholder="<%= t('leaderboard.searchByPlayerName') %>">
                    </div>
                </div>
                <div class="filter-group">
                    <label for="minBattles"><%= t('leaderboard.minimumBattles') %></label>
                    <input type="number" id="minBattles" class="filter-input" placeholder="<%= t('leaderboard.minBattlesPlaceholder') %>" min="0" value="5">
                </div>
                <div class="filter-group" style="position: relative;">
                    <label for="squadronFilter"><%= t('common.squadron') %></label>
                    <input type="text" id="squadronFilter" class="filter-input" placeholder="<%= t('leaderboard.searchSquadronsPlaceholder') %>" autocomplete="off">
                    <div id="squadronFilterResults" style="display:none; position:absolute; top:100%; left:0; right:0; z-index:50; background:rgba(30,30,30,0.98); border:1px solid rgba(144,238,144,0.2); border-radius:0.5rem; max-height:16rem; overflow-y:auto; margin-top:0.25rem;"></div>
                </div>
                <div class="filter-group">
                    <label><%= t('leaderboard.sortBy') %></label>
                    <div class="sort-btn-group">
                        <button class="sort-mode-btn active" id="sortWinsBtn" onclick="setSortMode('wins')"><%= t('common.wins') %></button>
                        <button class="sort-mode-btn" id="sortKDRBtn" onclick="setSortMode('kdr')"><%= t('leaderboard.kdRatio') %></button>
                    </div>
                </div>
                <div class="filter-group" id="resetBtnWrapper" style="display: none;">
                    <button class="clear-filters-btn" onclick="clearAllFilters()">
                        <i class="fas fa-times"></i> <%= t('leaderboard.resetFilters') %>
                    </button>
                </div>
            </div>
            <div class="controls-row" style="padding-top: 0.75rem; border-top: 1px solid rgba(144, 238, 144, 0.08);">
                <div class="filter-group">
                    <label for="timeFilterCategory"><i class="fas fa-calendar" style="margin-right: 0.3rem;"></i><%= t('leaderboard.timePeriod') %>:</label>
                    <select id="timeFilterCategory" class="filter-select" onchange="updateTimeFilterUI()">
                        <option value="all"><%= t('leaderboard.allTime') %></option>
                        <option value="date"><%= t('leaderboard.dateRange') %></option>
                        <option value="season"><%= t('leaderboard.season') %></option>
                        <option value="week"><%= t('leaderboard.week') %></option>
                    </select>
                </div>
                <div class="filter-group" id="dateTypeFilter" style="display: none;">
                    <label for="dateFilterType"><%= t('leaderboard.dateType') %>:</label>
                    <select id="dateFilterType" class="filter-select" onchange="handleDateTypeChange()">
                        <option value="last7"><%= t('leaderboard.last7Days') %></option>
                        <option value="last30"><%= t('leaderboard.last30Days') %></option>
                        <option value="last90"><%= t('leaderboard.last90Days') %></option>
                        <option value="custom"><%= t('leaderboard.customRange') %></option>
                    </select>
                </div>
                <div class="filter-group" id="customRangeFilter" style="display: none; flex-direction: row; gap: 0.75rem; align-items: flex-end;">
                    <div style="display: flex; flex-direction: column; gap: 0.25rem;">
                        <label for="startDateInput"><%= t('leaderboard.from') %>:</label>
                        <input type="date" id="startDateInput" class="filter-input" onchange="applyTimeFilter()">
                    </div>
                    <div style="display: flex; flex-direction: column; gap: 0.25rem;">
                        <label for="endDateInput"><%= t('leaderboard.to') %>:</label>
                        <input type="date" id="endDateInput" class="filter-input" onchange="applyTimeFilter()">
                    </div>
                </div>
                <div class="filter-group" id="seasonFilter" style="display: none;">
                    <label for="seasonSelect"><%= t('leaderboard.season') %>:</label>
                    <select id="seasonSelect" class="filter-select" onchange="applyTimeFilter()">
                        <option value=""><%= t('leaderboard.selectSeason') %></option>
                    </select>
                </div>
                <div class="filter-group" id="weekSeasonFilter" style="display: none;">
                    <label for="weekSeasonSelect"><%= t('leaderboard.season') %>:</label>
                    <select id="weekSeasonSelect" class="filter-select" onchange="updateWeekOptions()">
                        <option value=""><%= t('leaderboard.selectSeason') %></option>
                    </select>
                </div>
                <div class="filter-group" id="weekFilter" style="display: none;">
                    <label for="weekSelect"><%= t('leaderboard.week') %>:</label>
                    <select id="weekSelect" class="filter-select" onchange="applyTimeFilter()">
                        <option value=""><%= t('leaderboard.selectWeek') %></option>
                    </select>
                </div>
            </div>
            <div class="results-info" id="resultsInfo">
                <span id="filteredCount">0</span> <%= t('leaderboard.playersShown') %> (<%= t('leaderboard.page') %> <span id="currentPageNum">1</span> <%= t('leaderboard.of') %> <span id="totalPages">1</span>)
            </div>
        </div>

        <div class="leaderboard-content">
            <div class="loading-state" id="loadingState">
                <div class="loading-spinner"></div>
                <p><%= t('leaderboard.loadingPlayerLeaderboard') %></p>
            </div>
            
            <div class="error-state" id="errorState" style="display: none;">
                <i class="fas fa-exclamation-triangle error-icon"></i>
                <h3><%= t('leaderboard.failedToLoadLeaderboard') %></h3>
                <p id="errorMessage"><%= t('leaderboard.unableToFetch') %></p>
                <button class="retry-btn" onclick="loadLeaderboard()">
                    <i class="fas fa-redo"></i> <%= t('common.retry') %>
                </button>
            </div>
            
            <div class="responsive-table" id="leaderboardTable" style="display: none;">
                    <table class="leaderboard-table">
                        <thead>
                            <tr>
                                <th><%= t('common.rank') %></th>
                                <th class="sortable" onclick="sortTable('nick')" data-sort="nick">
                                    <%= t('common.player') %> <i class="fas fa-sort sort-icon"></i>
                                </th>
                                <th class="sortable" onclick="sortTable('total_kills')" data-sort="total_kills">
                                    <%= t('common.totalKills') %> <i class="fas fa-sort sort-icon"></i>
                                </th>
                                <th class="sortable" onclick="sortTable('kills_per_spawn')" data-sort="kills_per_spawn">
                                    <%= t('leaderboard.killsPerSpawn') %> <i class="fas fa-sort sort-icon"></i>
                                </th>
                                <th class="sortable" onclick="sortTable('kdr')" data-sort="kdr">
                                    <%= t('leaderboard.kdRatio') %> <i class="fas fa-sort sort-icon"></i>
                                </th>
                                <th class="sortable" onclick="sortTable('win_rate')" data-sort="win_rate">
                                    <%= t('common.winRate') %> <i class="fas fa-sort sort-icon"></i>
                                </th>
                                <th class="sortable" onclick="sortTable('total_battles')" data-sort="total_battles">
                                    <%= t('common.battles') %> <i class="fas fa-sort sort-icon"></i>
                                </th>
                                <th class="sortable" onclick="sortTable('wins')" data-sort="wins">
                                    <%= t('common.wins') %> <i class="fas fa-sort sort-icon"></i>
                                </th>
                                <th class="sortable" onclick="sortTable('assists')" data-sort="assists">
                                    <%= t('common.assists') %> <i class="fas fa-sort sort-icon"></i>
                                </th>
                                <th class="sortable" onclick="sortTable('captures')" data-sort="captures">
                                    <%= t('leaderboard.caps') %> <i class="fas fa-sort sort-icon"></i>
                                </th>
                            </tr>
                        </thead>
                    <tbody id="leaderboardBody">
                    </tbody>
                </table>
            </div>
            
            <div class="pagination-controls" id="paginationControls" style="display: none;">
                <button class="pagination-btn" id="firstPageBtn" onclick="goToPage(1)">
                    <i class="fas fa-angle-double-left"></i>
                </button>
                <button class="pagination-btn" id="prevPageBtn" onclick="goToPage(currentPage - 1)">
                    <i class="fas fa-angle-left"></i>
                </button>
                <div class="pagination-info">
                    <%= t('leaderboard.page') %> <span id="currentPageDisplay">1</span> <%= t('leaderboard.of') %> <span id="totalPagesDisplay">1</span>
                </div>
                <button class="pagination-btn" id="nextPageBtn" onclick="goToPage(currentPage + 1)">
                    <i class="fas fa-angle-right"></i>
                </button>
                <button class="pagination-btn" id="lastPageBtn" onclick="goToPage(totalPagesCount)">
                    <i class="fas fa-angle-double-right"></i>
                </button>
            </div>
        </div>
    </div>

    <!-- Footer -->
    <%- include('partials/footer') %>

    <script>
        window.__lang = '<%= lang %>';
        window.__i18n = <%- localeJson %>;
        window.__t = function(key) {
            var parts = key.split('.'), obj = window.__i18n;
            for (var i = 0; i < parts.length; i++) { obj = obj && obj[parts[i]]; }
            return obj !== undefined ? obj : key;
        };
        window.switchLanguage = function(lang) {
            var next = lang || (document.documentElement.lang === 'en' ? 'ru' : 'en');
            if (next === document.documentElement.lang) return;
            document.cookie = 'lang=' + next + ';path=/;max-age=31536000;SameSite=Lax';
            window.location.reload();
        };
    </script>
    <script src="/js/main.js?v=3"></script>
    <script src="/js/chart.umd.min.js"></script>
    <script src="/js/api-client.js?v=2"></script>
    <script src="/js/player-details-modal.js"></script>
    <script src="/js/header-search.js?v=2"></script>
    <script src="/js/seasons-filter.js"></script>
    <script>
        let allPlayers = [];
        let filteredPlayers = [];
        let allSquadrons = [];
        let currentPage = 1;
        let playersPerPage = 100;
        let totalPagesCount = 1;
        let currentSort = { field: 'wins', direction: 'desc' };
        let currentPlayerSearch = '';
        let currentSquadronFilter = '';
        let currentStartDate = null;
        let currentEndDate = null;

        async function loadLeaderboard(startDate = null, endDate = null) {
            const loadingState = document.getElementById('loadingState');
            const errorState = document.getElementById('errorState');
            const leaderboardTable = document.getElementById('leaderboardTable');

            loadingState.style.display = 'block';
            errorState.style.display = 'none';
            leaderboardTable.style.display = 'none';

            try {
                if (!window.apiClient || typeof window.apiClient.getPlayerLeaderboard !== 'function') {
                    throw new Error(__t('leaderboard.apiNotLoaded'));
                }

                const clientReady = await window.ensureAPIClient();
                if (!clientReady) {
                    throw new Error(__t('leaderboard.failedToInitApi'));
                }

                let leaderboardData;
                if (startDate || endDate) {
                    const params = new URLSearchParams();
                    if (startDate) params.append('start_date', startDate.toISOString());
                    if (endDate) params.append('end_date', endDate.toISOString());
                    leaderboardData = await window.apiClient.request(`/api/leaderboard/players?${params.toString()}`);
                } else {
                    leaderboardData = await window.apiClient.getPlayerLeaderboard();
                }
                if (!leaderboardData || !leaderboardData.players || leaderboardData.players.length === 0) {
                    showError(__t('leaderboard.noPlayersInLeaderboard'));
                    return;
                }
                
                // Build squadron list from player data (sorted by number of members desc)
                const squadronCounts = {};
                leaderboardData.players.forEach(p => {
                    if (p.squadron_name) {
                        squadronCounts[p.squadron_name] = (squadronCounts[p.squadron_name] || 0) + 1;
                    }
                });
                allSquadrons = Object.entries(squadronCounts)
                    .sort((a, b) => b[1] - a[1])
                    .map(([name, count]) => ({ name, count }));

                allPlayers = leaderboardData.players.map((player, index) => {
                    const total_kills = player.total_kills || ((player.ground_kills || 0) + (player.air_kills || 0));
                    const assists = player.total_assists || player.assists || 0;
                    const captures = player.total_captures || player.captures || 0;
                    
                    const wins = player.wins || 0;
                    const battles = player.total_battles || 0;
                    let winRate = 0;
                    
                    if (battles > 0) {
                        winRate = (wins / battles) * 100;
                    }
                    
                    const kdr = (player.deaths || 0) > 0 ? (total_kills / player.deaths) : total_kills;
                    
                    const kills_per_spawn = battles > 0 ? (total_kills / battles) : 0;
                    
                    return {
                        uid: player.uid,
                        nick: player.nick,
                        squadron_name: player.squadron_name || null,
                        originalRank: index + 1,
                        total_kills: total_kills,
                        ground_kills: player.ground_kills || 0,
                        air_kills: player.air_kills || 0,
                        assists: assists,
                        captures: captures,
                        deaths: player.deaths || 0,
                        total_battles: player.total_battles || 0,
                        wins: player.wins || 0,
                        win_rate: winRate,
                        kdr: kdr,
                        kills_per_spawn: kills_per_spawn
                    };
                });
                
                sortAndRankAllPlayers(); 
                applyFiltersAndDisplay();
                
            } catch (error) {
                let errorMessage = __t('leaderboard.failedToLoadLeaderboard');
                if (error.message.includes('500')) {
                    errorMessage = __t('leaderboard.serverError500');
                } else if (error.message.includes('404')) {
                    errorMessage = __t('leaderboard.apiEndpoint404');
                } else if (error.message.includes('fetch')) {
                    errorMessage = __t('leaderboard.networkError');
                } else if (error.message) {
                    errorMessage = error.message;
                }
                
                showError(errorMessage);
            }
        }
        
        function applyFiltersAndDisplay() {
            const minBattles = parseInt(document.getElementById('minBattles').value) || 0;

            filteredPlayers = allPlayers.filter(player => {
                if (currentPlayerSearch) {
                    const searchTerm = currentPlayerSearch.toLowerCase().trim();
                    const playerNick = (player.nick || '').toLowerCase();
                    const playerUid = (player.uid || '').toString().toLowerCase();

                    if (!playerNick.includes(searchTerm) && !playerUid.includes(searchTerm)) {
                        return false;
                    }
                }

                if (currentSquadronFilter) {
                    const playerSquadron = (player.squadron_name || '').toLowerCase();
                    if (playerSquadron !== currentSquadronFilter.toLowerCase()) return false;
                }

                const totalBattles = player.total_battles || 0;
                if (totalBattles < minBattles) return false;

                return true;
            });
            
            updatePagination();
            displayCurrentPage();
        }
        
        function sortAndRankAllPlayers() {
            const field = currentSort.field;
            const direction = currentSort.direction;
            
            allPlayers.sort((a, b) => {
                let aVal = a[field];
                let bVal = b[field];
                
                if (field === 'nick') {
                    aVal = (aVal || '').toLowerCase();
                    bVal = (bVal || '').toLowerCase();
                    return direction === 'asc' ? aVal.localeCompare(bVal) : bVal.localeCompare(aVal);
                }
                
                aVal = Number(aVal) || 0;
                bVal = Number(bVal) || 0;
                
                return direction === 'asc' ? aVal - bVal : bVal - aVal;
            });
            
            allPlayers.forEach((player, index) => {
                player.currentRank = index + 1;
            });
        }
        
        function sortTable(field) {
            if (currentSort.field === field) {
                currentSort.direction = currentSort.direction === 'asc' ? 'desc' : 'asc';
            } else {
                currentSort.field = field;
                currentSort.direction = field === 'nick' ? 'asc' : 'desc';
            }

            document.querySelectorAll('.sortable').forEach(header => {
                header.classList.remove('sorted-asc', 'sorted-desc');
            });

            const currentHeader = document.querySelector('[data-sort="' + field + '"]');
            if (currentHeader) {
                currentHeader.classList.add(currentSort.direction === 'asc' ? 'sorted-asc' : 'sorted-desc');
            }

            document.getElementById('sortWinsBtn').classList.toggle('active', field === 'wins');
            document.getElementById('sortKDRBtn').classList.toggle('active', field === 'kdr');

            sortAndRankAllPlayers();
            applyFiltersAndDisplay();
        }
        
        function displayCurrentPage() {
            const loadingState = document.getElementById('loadingState');
            const leaderboardTable = document.getElementById('leaderboardTable');
            const paginationControls = document.getElementById('paginationControls');
            const leaderboardBody = document.getElementById('leaderboardBody');
            
            loadingState.style.display = 'none';
            leaderboardTable.style.display = 'block';
            paginationControls.style.display = totalPagesCount > 1 ? 'flex' : 'none';

            leaderboardBody.innerHTML = '';
            
            const startIndex = (currentPage - 1) * playersPerPage;
            const endIndex = Math.min(startIndex + playersPerPage, filteredPlayers.length);
            const currentPagePlayers = filteredPlayers.slice(startIndex, endIndex);
            
            currentPagePlayers.forEach((player, pageIndex) => {
                const row = document.createElement('tr');
                row.className = 'row-link';
                
                const displayRank = player.currentRank || (startIndex + pageIndex + 1);
                const rankClass = displayRank <= 3 ? 'rank-' + displayRank : '';
                
                const squadronTag = player.squadron_name ? `<span class="player-squadron" style="font-family: 'skyquakesymbols', 'Inter', sans-serif !important;">${escapeHtml(player.squadron_name)}</span>` : '';
                
                row.innerHTML = `
                    <td class="rank-cell ${rankClass}">
                        <a href="/players/${player.uid}" class="row-link-overlay" aria-label="View ${escapeHtml(player.nick)}"></a>
                        ${displayRank <= 3 ? getRankIcon(displayRank) : '#' + displayRank}
                    </td>
                    <td>
                        <div class="player-info">
                            <div>
                                <div class="player-nick">${squadronTag}${escapeHtml(player.nick)}<button class="pdm-details-btn" onclick="event.stopPropagation(); openPlayerDetailsModal('${player.uid}', '${escapeHtml(player.nick).replace(/'/g, "\\'")}')" title="Quick details"><i class="fas fa-eye"></i></button></div>
                            </div>
                        </div>
                    </td>
                    <td class="stat-cell stat-kills">${formatNumber(player.total_kills)}</td>
                    <td class="stat-cell stat-kills-per-spawn">${player.kills_per_spawn.toFixed(2)}</td>
                    <td class="stat-cell stat-kdr">${player.kdr.toFixed(2)}</td>
                    <td class="stat-cell stat-winrate">${player.win_rate.toFixed(1)}%</td>
                    <td class="stat-cell stat-battles">${formatNumber(player.total_battles)}</td>
                    <td class="stat-cell stat-wins">${formatNumber(player.wins)}</td>
                    <td class="stat-cell stat-assists">${formatNumber(player.assists)}</td>
                    <td class="stat-cell stat-captures">${formatNumber(player.captures)}</td>
                `;
                
                leaderboardBody.appendChild(row);
            });
            
            const filteredCount = document.getElementById('filteredCount');
            const currentPageNum = document.getElementById('currentPageNum');  
            const totalPages = document.getElementById('totalPages');
            
            if (filteredCount) filteredCount.textContent = filteredPlayers.length.toLocaleString();
            if (currentPageNum) currentPageNum.textContent = currentPage;
            if (totalPages) totalPages.textContent = totalPagesCount;
        }
        
        function updatePagination() {
            totalPagesCount = Math.ceil(filteredPlayers.length / playersPerPage);

            if (currentPage > totalPagesCount) {
                currentPage = Math.max(1, totalPagesCount);
            }

            const currentPageDisplay = document.getElementById('currentPageDisplay');
            const totalPagesDisplay = document.getElementById('totalPagesDisplay');
            const firstPageBtn = document.getElementById('firstPageBtn');
            const prevPageBtn = document.getElementById('prevPageBtn');
            const nextPageBtn = document.getElementById('nextPageBtn');
            const lastPageBtn = document.getElementById('lastPageBtn');

            if (currentPageDisplay) currentPageDisplay.textContent = currentPage;
            if (totalPagesDisplay) totalPagesDisplay.textContent = totalPagesCount;

            if (firstPageBtn) firstPageBtn.disabled = currentPage <= 1;
            if (prevPageBtn) prevPageBtn.disabled = currentPage <= 1;
            if (nextPageBtn) nextPageBtn.disabled = currentPage >= totalPagesCount;
            if (lastPageBtn) lastPageBtn.disabled = currentPage >= totalPagesCount;
        }
        
        function goToPage(page) {
            currentPage = Math.max(1, Math.min(page, totalPagesCount));
            displayCurrentPage();
            updatePagination();
        }
        
        function clearAllFilters() {
            document.getElementById('playerSearch').value = '';
            document.getElementById('minBattles').value = '5';
            document.getElementById('squadronFilter').value = '';
            currentPlayerSearch = '';
            currentSquadronFilter = '';
            currentPage = 1;
            setSortMode('wins');
            document.getElementById('timeFilterCategory').value = 'all';
            updateTimeFilterUI(); // hides sub-filters and reloads with no dates
            document.getElementById('resetBtnWrapper').style.display = 'none';
        }

        function updateResetVisibility() {
            const search = document.getElementById('playerSearch').value.trim();
            const minBattles = parseInt(document.getElementById('minBattles').value);
            const timeCat = document.getElementById('timeFilterCategory').value;
            const squadron = currentSquadronFilter;
            const isDefault = search === '' && minBattles === 5 && timeCat === 'all' && !squadron;
            document.getElementById('resetBtnWrapper').style.display = isDefault ? 'none' : 'flex';
        }

        function updateTimeFilterUI() {
            const cat = document.getElementById('timeFilterCategory').value;
            document.getElementById('dateTypeFilter').style.display = 'none';
            document.getElementById('customRangeFilter').style.display = 'none';
            document.getElementById('seasonFilter').style.display = 'none';
            document.getElementById('weekSeasonFilter').style.display = 'none';
            document.getElementById('weekFilter').style.display = 'none';

            if (cat === 'date') {
                document.getElementById('dateTypeFilter').style.display = 'flex';
                handleDateTypeChange();
            } else if (cat === 'season') {
                document.getElementById('seasonFilter').style.display = 'flex';
            } else if (cat === 'week') {
                document.getElementById('weekSeasonFilter').style.display = 'flex';
                document.getElementById('weekFilter').style.display = 'flex';
            }

            updateResetVisibility();
            if (cat === 'all' || cat === 'season') {
                applyTimeFilter();
            }
        }

        function handleDateTypeChange() {
            const type = document.getElementById('dateFilterType').value;
            document.getElementById('customRangeFilter').style.display = type === 'custom' ? 'flex' : 'none';
            if (type !== 'custom') {
                applyTimeFilter();
            }
        }

        function resolveTimeDates() {
            const cat = document.getElementById('timeFilterCategory').value;
            const now = new Date();
            if (cat === 'all') return { start: null, end: null };
            if (cat === 'date') {
                const type = document.getElementById('dateFilterType').value;
                switch (type) {
                    case 'last7':  return { start: new Date(now - 7*24*60*60*1000), end: now };
                    case 'last30': return { start: new Date(now - 30*24*60*60*1000), end: now };
                    case 'last90': return { start: new Date(now - 90*24*60*60*1000), end: now };
                    case 'custom': {
                        const s = document.getElementById('startDateInput').value;
                        const e = document.getElementById('endDateInput').value;
                        if (!s && !e) return null;
                        const end = e ? new Date(e) : new Date(s);
                        end.setHours(23, 59, 59, 999);
                        return { start: s ? new Date(s) : end, end };
                    }
                }
            }
            if (cat === 'season') {
                const seasonName = document.getElementById('seasonSelect').value;
                if (!seasonName || !window.seasonsFilter) return null;
                const range = window.seasonsFilter.getSeasonDateRange(seasonName);
                if (!range) return null;
                return { start: range.startDate, end: range.endDate };
            }
            if (cat === 'week') {
                const seasonName = document.getElementById('weekSeasonSelect').value;
                const weekVal = document.getElementById('weekSelect').value;
                if (!seasonName || !weekVal || !window.seasonsFilter) return null;
                if (weekVal === 'all') {
                    const range = window.seasonsFilter.getSeasonDateRange(seasonName);
                    if (!range) return null;
                    return { start: range.startDate, end: range.endDate };
                }
                const weekNum = weekVal === 'final' ? null : parseInt(weekVal);
                const range = window.seasonsFilter.getWeekDateRange(seasonName, weekNum);
                if (!range) return null;
                return { start: range.startDate, end: range.endDate };
            }
            return { start: null, end: null };
        }

        function applyTimeFilter() {
            const result = resolveTimeDates();
            if (result === null) return; // incomplete selection
            currentStartDate = result.start;
            currentEndDate = result.end;
            currentPage = 1;
            updateResetVisibility();
            loadLeaderboard(currentStartDate, currentEndDate);
        }

        function updateWeekOptions() {
            const seasonName = document.getElementById('weekSeasonSelect').value;
            const weekSelect = document.getElementById('weekSelect');
            if (seasonName && window.seasonsFilter) {
                window.seasonsFilter.populateWeekSelect(weekSelect, seasonName, true);
            } else {
                weekSelect.innerHTML = '<option value="">' + __t('leaderboard.selectWeek') + '</option>';
            }
        }

        async function initSeasonsFilter() {
            try {
                await window.seasonsFilter.loadSeasons();
                if (window.seasonsFilter.loaded) {
                    window.seasonsFilter.populateSeasonSelect(document.getElementById('seasonSelect'), false);
                    window.seasonsFilter.populateSeasonSelect(document.getElementById('weekSeasonSelect'), false);
                }
            } catch (e) {
                console.error('[Leaderboard] Error initializing seasons:', e);
            }
        }

        function setSortMode(field) {
            currentSort.field = field;
            currentSort.direction = 'desc';

            document.querySelectorAll('.sortable').forEach(h => h.classList.remove('sorted-asc', 'sorted-desc'));
            const header = document.querySelector('[data-sort="' + field + '"]');
            if (header) header.classList.add('sorted-desc');

            document.getElementById('sortWinsBtn').classList.toggle('active', field === 'wins');
            document.getElementById('sortKDRBtn').classList.toggle('active', field === 'kdr');

            sortAndRankAllPlayers();
            applyFiltersAndDisplay();
        }
        
        function setupEventListeners() {
            const playerSearchInput = document.getElementById('playerSearch');
            let searchTimeout;
            
            playerSearchInput.addEventListener('input', function() {
                clearTimeout(searchTimeout);
                searchTimeout = setTimeout(() => {
                    currentPlayerSearch = this.value.trim();
                    currentPage = 1;
                    updateResetVisibility();
                    applyFiltersAndDisplay();
                }, 300);
            });

            playerSearchInput.addEventListener('keypress', function(e) {
                if (e.key === 'Enter') {
                    clearTimeout(searchTimeout);
                    currentPlayerSearch = this.value.trim();
                    currentPage = 1;
                    updateResetVisibility();
                    applyFiltersAndDisplay();
                }
            });

            const minBattlesInput = document.getElementById('minBattles');

            minBattlesInput.addEventListener('input', debounce(() => {
                currentPage = 1;
                updateResetVisibility();
                applyFiltersAndDisplay();
            }, 300));

            // Squadron filter
            const squadronInput = document.getElementById('squadronFilter');
            const squadronResults = document.getElementById('squadronFilterResults');
            let squadronTimeout;

            squadronInput.addEventListener('input', function() {
                clearTimeout(squadronTimeout);
                const val = this.value.trim().toLowerCase();
                if (val.length < 1) {
                    squadronResults.style.display = 'none';
                    if (currentSquadronFilter) {
                        currentSquadronFilter = '';
                        currentPage = 1;
                        updateResetVisibility();
                        applyFiltersAndDisplay();
                    }
                    return;
                }
                squadronTimeout = setTimeout(() => {
                    const matches = allSquadrons
                        .filter(s => s.name.toLowerCase().includes(val))
                        .slice(0, 15);
                    if (matches.length === 0) {
                        squadronResults.innerHTML = '<div style="padding:0.75rem 1rem; color:rgba(255,255,255,0.5); font-size:0.9rem;">' + __t('js.noSquadronsFound') + '</div>';
                    } else {
                        squadronResults.innerHTML = matches.map(s =>
                            `<div style="padding:0.75rem 1rem; cursor:pointer; border-bottom:1px solid rgba(144,238,144,0.05); transition:background 0.2s;" onmouseover="this.style.background='rgba(144,238,144,0.08)'" onmouseout="this.style.background=''" data-squadron="${escapeHtml(s.name)}" onclick="selectSquadronFilter(this.dataset.squadron)"><span style="font-family:'skyquakesymbols','Inter',sans-serif; color:#90EE90;">${escapeHtml(s.name)}</span> <span style="color:rgba(255,255,255,0.35); font-size:0.85rem;">(${s.count} players)</span></div>`
                        ).join('');
                    }
                    squadronResults.style.display = 'block';
                }, 150);
            });

            squadronInput.addEventListener('keydown', function(e) {
                if (e.key === 'Escape') {
                    squadronResults.style.display = 'none';
                }
            });

            document.addEventListener('click', function(e) {
                if (!squadronInput.contains(e.target) && !squadronResults.contains(e.target)) {
                    squadronResults.style.display = 'none';
                }
            });
        }

        function selectSquadronFilter(name) {
            currentSquadronFilter = name;
            document.getElementById('squadronFilter').value = name;
            document.getElementById('squadronFilterResults').style.display = 'none';
            currentPage = 1;
            updateResetVisibility();
            applyFiltersAndDisplay();
        }
        
        
        function debounce(func, wait) {
            let timeout;
            return function executedFunction(...args) {
                const later = () => {
                    clearTimeout(timeout);
                    func(...args);
                };
                clearTimeout(timeout);
                timeout = setTimeout(later, wait);
            };
        }
        
        function showError(message) {
            const loadingState = document.getElementById('loadingState');
            const errorState = document.getElementById('errorState');
            const errorMessage = document.getElementById('errorMessage');
            
            loadingState.style.display = 'none';
            errorState.style.display = 'block';
            errorMessage.textContent = message;
        }
        
        function getRankIcon(rank) {
            switch(rank) {
                case 1: return '<i class="fas fa-crown" style="margin-right: 0.5rem; color: #ffd700;"></i>';
                case 2: return '<i class="fas fa-medal" style="margin-right: 0.5rem; color: #c0c0c0;"></i>';
                case 3: return '<i class="fas fa-trophy" style="margin-right: 0.5rem; color: #cd7f32;"></i>';
                default: return '';
            }
        }
        
        function formatNumber(num) {
            if (num >= 1000000) {
                return (num / 1000000).toFixed(1) + 'M';
            } else if (num >= 1000) {
                return (num / 1000).toFixed(1) + 'K';
            }
            return num.toString();
        }
        
        function escapeHtml(text) {
            const div = document.createElement('div');
            div.textContent = text;
            return div.innerHTML;
        }
        
        
        function getWinRateColor(winRate) {
            if (winRate >= 70) return '#90EE90';
            if (winRate >= 60) return '#A8E6CF';
            if (winRate >= 50) return '#FFD700';
            if (winRate >= 40) return '#FFA500';
            return '#FF6B6B';
        }
        
        function getKDRColor(kdr) {
            if (kdr >= 3) return '#90EE90';
            if (kdr >= 2) return '#A8E6CF';
            if (kdr >= 1.5) return '#FFD700';
            if (kdr >= 1) return '#FFA500';
            return '#FF6B6B';
        }
        
        document.addEventListener('DOMContentLoaded', () => {
            setupEventListeners();
            const winsHeader = document.querySelector('[data-sort="wins"]');
            if (winsHeader) winsHeader.classList.add('sorted-desc');
            initSeasonsFilter();
            setTimeout(loadLeaderboard, 100);
        });
    </script>
</body>
</html>
