<!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.vehiclesTitle') %> | <%= botName %></title>
    <meta name="description" content="<%= t('leaderboard.vehiclesSubtitle') %>">
    <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: 900px;
        }
        
        .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;
            vertical-align: middle;
        }
        
        .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: 35%;
            min-width: 250px;
            text-align: left !important;
            white-space: normal;
            word-wrap: break-word;
            max-width: 350px;
        }
        
        .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) {
            width: 120px;
            min-width: 120px;
        }
        
        .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) {
            width: 100px;
            min-width: 100px;
        }
        
        .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); }
        
        .vehicle-info {
            display: flex;
            flex-direction: column;
            align-items: center;
            gap: 0.25rem;
            text-align: center;
        }
        
        .vehicle-name {
            font-family: 'skyquakesymbols', 'Inter', sans-serif !important;
            font-weight: 600;
            color: #90EE90;
            font-size: 1.1rem;
            text-shadow: 0 0 10px rgba(144, 238, 144, 0.3);
            text-align: center;
        }
        
        .player-info {
            font-size: 0.9rem;
            color: rgba(255, 255, 255, 0.7);
        }
        
        .player-nick {
            color: #ffffff;
            text-decoration: none;
            transition: color 0.3s ease;
            text-align: center;
        }
        
        .player-nick:hover {
            color: #90EE90;
        }
        
        .player-squadron {
            font-family: 'skyquakesymbols', 'Inter', sans-serif !important;
            font-size: 0.75rem;
            color: rgba(255, 255, 255, 0.4);
            font-weight: 500;
            margin-right: 0.4rem;
        }
        
        .stat-cell {
            font-weight: 600;
            font-size: 1rem;
        }
        
        .stat-kills { color: #ff4757; text-shadow: 0 0 10px rgba(255, 71, 87, 0.5); }
        .stat-kdr { color: #90EE90; text-shadow: 0 0 10px rgba(144, 238, 144, 0.5); }
        .stat-winrate { color: #f59e0b; text-shadow: 0 0 10px rgba(245, 158, 11, 0.5); }
        .stat-battles { color: #a855f7; text-shadow: 0 0 10px rgba(168, 85, 247, 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: 1rem 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: 0.75rem;
        }
        
        .filter-group {
            display: flex;
            flex-direction: column;
            gap: 0.5rem;
        }
        
        .filter-group label {
            color: #ffffff;
            font-weight: 600;
            font-size: 0.9rem;
            white-space: nowrap;
            margin-bottom: 0;
        }
        
        .filter-input, .filter-select {
            background: rgba(30, 30, 30, 0.9);
            border: 2px solid rgba(144, 238, 144, 0.2);
            border-radius: 0.75rem;
            padding: 0.625rem 0.875rem;
            color: #ffffff;
            font-size: 0.95rem;
            font-weight: 500;
            transition: all 0.3s ease;
            min-width: 140px;
            backdrop-filter: blur(10px);
            box-shadow: 0 4px 15px rgba(0, 0, 0, 0.2);
        }
        
        .filter-input:focus, .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);
            transform: translateY(-1px);
        }
        
        .filter-input:hover, .filter-select: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;
        }

        /* Vehicle and squadron filters echo back text containing skyquake
           glyphs (▄ ◢ ◊ ␗) — render them as proper symbols, not tofu. */
        #vehicleFilter, #squadronFilter {
            font-family: 'skyquakesymbols', 'Inter', sans-serif;
        }
        
        .filter-select option {
            background: rgba(30, 30, 30, 0.95);
            color: #ffffff;
        }
        
        .clear-filter-btn {
            background: linear-gradient(135deg, rgba(239, 68, 68, 0.2), rgba(220, 38, 38, 0.2));
            border: 2px solid rgba(239, 68, 68, 0.3);
            color: #ef4444;
            padding: 0.625rem 0.875rem;
            border-radius: 0.75rem;
            cursor: pointer;
            font-weight: 500;
            font-size: 0.95rem;
            transition: all 0.3s ease;
            white-space: nowrap;
        }
        
        .clear-filter-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;
            margin-bottom: 1rem;
        }
        
        /* Sortable Headers */
        .sortable {
            cursor: pointer;
            position: relative;
            user-select: none;
        }
        
        .sortable:hover {
            background: linear-gradient(135deg, rgba(144, 238, 144, 0.25), rgba(144, 238, 144, 0.1));
        }
        
        .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";
        }
        
        .sortable.sorted-desc .sort-icon {
            opacity: 1;
        }
        
        .sortable.sorted-desc .sort-icon::before {
            content: "\f0dd";
        }
        
        /* 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;
        }
        
        /* Footer Styles */
        footer {
            background: rgba(30, 30, 30, 0.8);
            backdrop-filter: blur(10px);
            border-top: 1px solid rgba(144, 238, 144, 0.1);
            padding: 2rem 0;
            margin-top: auto;
        }
        
        footer a {
            color: #888;
            text-decoration: none;
            transition: all 0.3s ease;
        }
        
        footer a:hover {
            color: #90EE90;
            text-shadow: 0 0 10px rgba(144, 238, 144, 0.5);
        }
        
    </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.vehiclesTitle') %></h1>
            <p class="leaderboard-subtitle"><%= t('leaderboard.vehiclesSubtitle') %></p>
            <div class="disclaimer">
                <i class="fas fa-info-circle" style="margin-right: 0.5rem;"></i>
                <%= t('common.recordingSince') %> • <%= t('leaderboard.minBattlesPerVehicle') %>
            </div>
        </div>
        
        <div class="leaderboard-nav">
            <a href="/leaderboard/players" class="leaderboard-tab">
                <i class="fas fa-user"></i> <%= t('common.players') %>
            </a>
            <a href="/leaderboard/vehicles" class="leaderboard-tab active">
                <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="filter-group" style="position: relative;">
                    <label for="vehicleFilter"><%= t('leaderboard.vehicleName') %></label>
                    <input type="text" id="vehicleFilter" class="filter-input" placeholder="<%= t('leaderboard.searchVehiclePlaceholder') %>" autocomplete="off">
                    <div id="vehicleFilterResults" style="display:none; position:absolute; top:100%; left:0; right:0; z-index:50; background:rgba(20,20,20,0.98); border:1px solid rgba(144,238,144,0.15); border-radius:0.5rem; max-height:18rem; overflow-y:auto; margin-top:0.25rem; box-shadow:0 12px 40px rgba(0,0,0,0.5);"></div>
                </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 for="minKillsFilter"><%= t('leaderboard.minKills') %></label>
                    <select id="minKillsFilter" class="filter-select">
                        <option value="0"><%= t('leaderboard.any') %></option>
                        <option value="10">10+</option>
                        <option value="25">25+</option>
                        <option value="50">50+</option>
                        <option value="100">100+</option>
                        <option value="250">250+</option>
                    </select>
                </div>
                <div class="filter-group">
                    <label for="vehiclesPerPage"><%= t('leaderboard.perPage') %></label>
                    <select id="vehiclesPerPage" class="filter-select">
                        <option value="25" selected>25</option>
                        <option value="50">50</option>
                        <option value="100">100</option>
                    </select>
                </div>
                <div class="filter-group">
                    <button class="clear-filter-btn" onclick="clearFilters()">
                        <i class="fas fa-times"></i> <%= t('leaderboard.clear') %>
                    </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.vehiclesShown') %> (<%= 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.loadingVehicleLeaderboard') %></p>
            </div>
            
            <div class="error-state" id="errorState" style="display: none;">
                <i class="fas fa-exclamation-triangle error-icon"></i>
                <h3><%= t('leaderboard.failedToLoadVehicles') %></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 id="leaderboardContent" style="display: none;">
                <div class="results-info" id="resultsInfo"></div>
                <div class="responsive-table" id="leaderboardTable">
                    <table class="leaderboard-table">
                        <thead>
                            <tr>
                                <th><%= t('common.rank') %></th>
                                <th class="sortable" onclick="sortTable('vehicle')" data-sort="vehicle">
                                    <%= t('leaderboard.vehicleAndPlayer') %> <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('ground_kills')" data-sort="ground_kills">
                                    <%= t('common.groundKills') %> <i class="fas fa-sort sort-icon"></i>
                                </th>
                                <th class="sortable" onclick="sortTable('air_kills')" data-sort="air_kills">
                                    <%= t('common.airKills') %> <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('battles')" data-sort="battles">
                                    <%= t('common.battles') %> <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('common.captures') %> <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>
    </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/api-client.js?v=2"></script>
    <script src="/js/vehicle-i18n.js"></script>
    <script src="/js/seasons-filter.js"></script>
    <script>
        let allSquadrons = [];
        let currentSquadronFilter = '';
        let currentPage = 1;
        let vehiclesPerPage = 25;
        let totalPagesCount = 1;
        let currentSort = { field: 'total_kills', direction: 'desc' };
        let currentSearch = '';
        let currentVehicleInternal = '';
        let vehicleListCache = null;
        let currentMinKills = 0;
        let currentStartDate = null;
        let currentEndDate = null;
        let fetchController = null;

        async function fetchPage() {
            const loadingState = document.getElementById('loadingState');
            const errorState = document.getElementById('errorState');
            const leaderboardContent = document.getElementById('leaderboardContent');

            // Only show full loading spinner on first load
            if (!leaderboardContent || leaderboardContent.style.display === 'none') {
                loadingState.style.display = 'block';
            }
            errorState.style.display = 'none';

            // Cancel any in-flight request
            if (fetchController) fetchController.abort();
            fetchController = new AbortController();

            try {
                await window.ensureAPIClient();

                const params = new URLSearchParams();
                params.append('page', currentPage);
                params.append('limit', vehiclesPerPage);
                params.append('sort', currentSort.field);
                params.append('order', currentSort.direction);
                // Picker-selected internal id is the precise filter (distinguishes
                // country variants). currentSearch is only used as a free-text
                // fallback for the rare case the user hits Enter without picking.
                if (currentVehicleInternal) params.append('vehicle_internal', currentVehicleInternal);
                else if (currentSearch) params.append('search', currentSearch);
                if (currentSquadronFilter) params.append('squadron', currentSquadronFilter);
                if (currentMinKills > 0) params.append('min_kills', currentMinKills);
                if (currentStartDate) params.append('start_date', currentStartDate.toISOString());
                if (currentEndDate) params.append('end_date', currentEndDate.toISOString());

                const data = await window.apiClient.request(`/api/leaderboard/vehicles?${params.toString()}`);

                if (!data || !data.vehicles) {
                    showError(window.__t('leaderboard.noVehicleData'));
                    return;
                }

                // Update squadron list from API response
                if (data.squadrons && data.squadrons.length > 0) {
                    allSquadrons = data.squadrons;
                }

                // Update pagination state
                const pg = data.pagination || {};
                totalPagesCount = pg.total_pages || 1;
                if (currentPage > totalPagesCount) currentPage = totalPagesCount;

                document.getElementById('filteredCount').textContent = (pg.total_rows || 0).toLocaleString();
                document.getElementById('currentPageNum').textContent = currentPage;
                document.getElementById('totalPages').textContent = totalPagesCount;
                document.getElementById('currentPageDisplay').textContent = currentPage;
                document.getElementById('totalPagesDisplay').textContent = totalPagesCount;

                const firstBtn = document.getElementById('firstPageBtn');
                const prevBtn = document.getElementById('prevPageBtn');
                const nextBtn = document.getElementById('nextPageBtn');
                const lastBtn = document.getElementById('lastPageBtn');
                firstBtn.disabled = prevBtn.disabled = currentPage <= 1;
                nextBtn.disabled = lastBtn.disabled = currentPage >= totalPagesCount;

                // Render rows
                const leaderboardBody = document.getElementById('leaderboardBody');
                const paginationControls = document.getElementById('paginationControls');
                loadingState.style.display = 'none';
                leaderboardContent.style.display = 'block';
                paginationControls.style.display = totalPagesCount > 1 ? 'flex' : 'none';

                const startIndex = (currentPage - 1) * vehiclesPerPage;
                requestAnimationFrame(() => {
                    const fragment = document.createDocumentFragment();
                    data.vehicles.forEach((entry, i) => {
                        const row = document.createElement('tr');
                        row.className = 'row-link';

                        const globalRank = startIndex + i + 1;
                        const rankClass = globalRank <= 3 ? `rank-${globalRank}` : '';
                        const squadronTag = entry.player_squadron_name ?
                            `<span class="player-squadron" style="font-family: 'skyquakesymbols', 'Inter', sans-serif !important;">${escapeHtml(entry.player_squadron_name)}</span>` : '';

                        row.innerHTML = [
                            `<td class="rank-cell ${rankClass}"><a href="/players/${entry.player_uid}" class="row-link-overlay" aria-label="View player"></a>${globalRank <= 3 ? getRankIcon(globalRank) : `#${globalRank}`}</td>`,
                            `<td><div class="vehicle-info"><div class="vehicle-name" data-vehicle-internal="${escapeHtml(entry.vehicle_internal || '')}">${escapeHtml(entry.vehicle)}</div><div class="player-info">${squadronTag}<a href="/players/${entry.player_uid}" class="player-nick">${escapeHtml(entry.player_nick)}</a></div></div></td>`,
                            `<td class="stat-cell stat-kills">${formatNumber(entry.total_kills)}</td>`,
                            `<td class="stat-cell">${formatNumber(entry.ground_kills)}</td>`,
                            `<td class="stat-cell">${formatNumber(entry.air_kills)}</td>`,
                            `<td class="stat-cell stat-kdr">${entry.kdr}</td>`,
                            `<td class="stat-cell stat-winrate">${entry.win_rate}%</td>`,
                            `<td class="stat-cell stat-battles">${formatNumber(entry.battles)}</td>`,
                            `<td class="stat-cell">${formatNumber(entry.assists)}</td>`,
                            `<td class="stat-cell">${formatNumber(entry.captures)}</td>`
                        ].join('');
                        fragment.appendChild(row);
                    });
                    leaderboardBody.innerHTML = '';
                    leaderboardBody.appendChild(fragment);
                });

            } catch (error) {
                if (error.name === 'AbortError') return;
                console.error('Error loading vehicle leaderboard:', error);
                showError(error.message || window.__t('leaderboard.failedToLoadVehicles'));
            }
        }

        function loadLeaderboard(startDate = null, endDate = null) {
            currentStartDate = startDate;
            currentEndDate = endDate;
            currentPage = 1;
            fetchPage();
        }

        function sortTable(field) {
            if (currentSort.field === field) {
                currentSort.direction = currentSort.direction === 'asc' ? 'desc' : 'asc';
            } else {
                currentSort.field = field;
                currentSort.direction = (field === 'vehicle' || field === 'player_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');
            }

            currentPage = 1;
            fetchPage();
        }

        function goToPage(page) {
            currentPage = Math.max(1, Math.min(page, totalPagesCount));
            fetchPage();
        }

        function showError(message) {
            document.getElementById('loadingState').style.display = 'none';
            document.getElementById('errorState').style.display = 'block';
            document.getElementById('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';
            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 clearFilters() {
            document.getElementById('vehicleFilter').value = '';
            document.getElementById('minKillsFilter').value = '0';
            document.getElementById('vehiclesPerPage').value = '25';
            document.getElementById('squadronFilter').value = '';
            currentSearch = '';
            currentVehicleInternal = '';
            currentSquadronFilter = '';
            currentMinKills = 0;
            vehiclesPerPage = 25;
            currentPage = 1;
            document.getElementById('timeFilterCategory').value = 'all';
            updateTimeFilterUI();
        }

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

            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);
                return range ? { start: range.startDate, end: range.endDate } : null;
            }
            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);
                    return range ? { start: range.startDate, end: range.endDate } : null;
                }
                const weekNum = weekVal === 'final' ? null : parseInt(weekVal);
                const range = window.seasonsFilter.getWeekDateRange(seasonName, weekNum);
                return range ? { start: range.startDate, end: range.endDate } : null;
            }
            return { start: null, end: null };
        }

        function applyTimeFilter() {
            const result = resolveTimeDates();
            if (result === null) return;
            currentStartDate = result.start;
            currentEndDate = result.end;
            currentPage = 1;
            fetchPage();
        }

        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="">' + window.__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);
            }
        }

        async function ensureVehicleList() {
            if (vehicleListCache) return vehicleListCache;
            try {
                const data = await window.apiClient.request('/api/analytics/vehicle-list');
                vehicleListCache = (data && data.vehicles) || [];
            } catch (e) {
                console.error('vehicle-list fetch failed', e);
                vehicleListCache = [];
            }
            return vehicleListCache;
        }

        function vehicleDisplay(internal) {
            if (!internal) return '';
            if (window.vehicleI18n && window.vehicleI18n.translate) {
                return window.vehicleI18n.translate(internal, internal);
            }
            return internal;
        }

        function setupEventListeners() {
            const vehicleFilterInput = document.getElementById('vehicleFilter');
            const vehicleFilterResults = document.getElementById('vehicleFilterResults');
            let vehicleFilterTimeout;

            // Translation-map dropdown picker — country variants share the same
            // localized name (e.g. F-16A USA vs F-16A ▄ Italy), so only an exact
            // pick by internal id can distinguish them. Free-text typing no
            // longer auto-fires a search; the user must select a row.
            function renderVehicleHits(query) {
                const list = vehicleListCache || [];
                const hits = [];
                for (const v of list) {
                    const display = vehicleDisplay(v.vehicle_internal);
                    if (!display.toLowerCase().includes(query)) continue;
                    hits.push({ display, internal: v.vehicle_internal, total: v.total });
                    if (hits.length >= 25) break;
                }
                if (!hits.length) {
                    vehicleFilterResults.innerHTML = '<div style="padding:0.75rem 1rem; color:rgba(255,255,255,0.5); font-size:0.9rem;">' + (window.__t('common.noVehiclesFound') || 'No vehicles found') + '</div>';
                } else {
                    vehicleFilterResults.innerHTML = hits.map(h =>
                        '<div class="vf-hit" data-pick-internal="' + escapeHtml(h.internal) + '" data-pick-display="' + escapeHtml(h.display) + '" style="padding:0.6rem 1rem; cursor:pointer; border-bottom:1px solid rgba(255,255,255,0.04); transition:background 0.15s;" onmouseover="this.style.background=\'rgba(144,238,144,0.06)\'" onmouseout="this.style.background=\'\'">' +
                            '<span style="font-family:\'skyquakesymbols\',\'Inter\',sans-serif; color:#A8E6CF; font-size:0.95rem;">' + escapeHtml(h.display) + '</span>' +
                            '<span style="color:rgba(255,255,255,0.4); margin-left:0.5rem; font-size:0.75rem;">' + (h.total || 0) + ' uses</span>' +
                        '</div>'
                    ).join('');
                    vehicleFilterResults.querySelectorAll('.vf-hit').forEach(el => {
                        el.addEventListener('click', () => pickVehicleFilter(el.dataset.pickInternal, el.dataset.pickDisplay));
                    });
                }
                vehicleFilterResults.style.display = 'block';
            }

            function pickVehicleFilter(internal, display) {
                currentVehicleInternal = internal || '';
                currentSearch = '';
                vehicleFilterInput.value = display || internal || '';
                vehicleFilterResults.style.display = 'none';
                currentPage = 1;
                fetchPage();
            }

            vehicleFilterInput.addEventListener('focus', () => {
                ensureVehicleList();
                if (window.vehicleI18n && window.vehicleI18n.ensureLoaded) window.vehicleI18n.ensureLoaded();
            });

            vehicleFilterInput.addEventListener('input', function() {
                clearTimeout(vehicleFilterTimeout);
                const val = this.value.trim().toLowerCase();
                // Clearing the input clears the active pick.
                if (currentVehicleInternal && val === '') {
                    currentVehicleInternal = '';
                    currentSearch = '';
                    vehicleFilterResults.style.display = 'none';
                    currentPage = 1;
                    fetchPage();
                    return;
                }
                if (val.length < 1) { vehicleFilterResults.style.display = 'none'; return; }
                vehicleFilterTimeout = setTimeout(async () => {
                    await ensureVehicleList();
                    if (window.vehicleI18n && window.vehicleI18n.ensureLoaded) await window.vehicleI18n.ensureLoaded();
                    renderVehicleHits(val);
                }, 150);
            });

            vehicleFilterInput.addEventListener('keydown', function(e) {
                if (e.key === 'Escape') { vehicleFilterResults.style.display = 'none'; this.blur(); }
                else if (e.key === 'Enter') {
                    e.preventDefault();
                    // Prefer first dropdown hit so country variants still get
                    // disambiguated by internal id when the user mashes Enter.
                    const first = vehicleFilterResults.querySelector('.vf-hit');
                    if (first) pickVehicleFilter(first.dataset.pickInternal, first.dataset.pickDisplay);
                }
            });

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

            document.getElementById('vehiclesPerPage').addEventListener('change', function() {
                vehiclesPerPage = parseInt(this.value) || 25;
                currentPage = 1;
                fetchPage();
            });

            document.getElementById('minKillsFilter').addEventListener('change', function() {
                currentMinKills = parseInt(this.value) || 0;
                currentPage = 1;
                fetchPage();
            });

            // Squadron filter autocomplete
            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;
                        fetchPage();
                    }
                    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;">' + window.__t('common.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} entries)</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;
            fetchPage();
        }

        document.addEventListener('DOMContentLoaded', () => {
            setupEventListeners();
            initSeasonsFilter();
            setTimeout(loadLeaderboard, 100);
        });
    </script>
</body>
</html>
