<!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.statsTitle') %> | <%= botName %></title>
    <meta name="description" content="<%= t('leaderboard.statsSubtitle') %>">
    <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);
        }
        
        .stats-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
            gap: 2rem;
            margin-bottom: 2rem;
        }
        
        .stats-card {
            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);
            text-align: center;
        }
        
        .stats-card-title {
            font-size: 1.2rem;
            font-weight: 600;
            color: #90EE90;
            margin-bottom: 1rem;
            text-shadow: 0 0 10px rgba(144, 238, 144, 0.3);
        }
        
        .stats-card-value {
            font-size: 2.5rem;
            font-weight: 700;
            color: #ffffff;
            margin-bottom: 0.5rem;
            text-shadow: 0 2px 4px rgba(0, 0, 0, 0.3);
        }
        
        .stats-card-label {
            font-size: 0.9rem;
            color: rgba(255, 255, 255, 0.7);
            text-transform: uppercase;
            letter-spacing: 0.5px;
        }
        
        .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); }
        }
        
        .vehicles-section {
            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);
        }
        
        .section-title {
            font-size: 1.5rem;
            font-weight: 600;
            color: #90EE90;
            margin-bottom: 1.5rem;
            text-align: center;
            text-shadow: 0 0 10px rgba(144, 238, 144, 0.3);
        }
        
        .vehicles-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
            gap: 1rem;
        }
        
        .vehicle-item {
            display: block;
            color: inherit;
            text-decoration: none;
            background: rgba(30, 30, 30, 0.8);
            border-radius: 0.75rem;
            padding: 1.5rem;
            border: 1px solid rgba(144, 238, 144, 0.1);
            transition: all 0.3s ease;
            cursor: pointer;
        }
        
        .vehicle-item:hover {
            border-color: rgba(144, 238, 144, 0.3);
            background: rgba(30, 30, 30, 0.95);
            transform: translateY(-2px);
        }
        
        .vehicle-rank {
            font-size: 0.9rem;
            color: rgba(255, 255, 255, 0.6);
            margin-bottom: 0.5rem;
        }
        
        .vehicle-name {
            font-family: 'skyquakesymbols', 'Inter', sans-serif !important;
            font-size: 1.1rem;
            font-weight: 600;
            color: #90EE90;
            margin-bottom: 0.5rem;
            text-shadow: 0 0 10px rgba(144, 238, 144, 0.3);
        }
        
        .vehicle-usage {
            font-size: 1.2rem;
            font-weight: 700;
            color: #ffffff;
        }
        
        .vehicle-label {
            font-size: 0.8rem;
            color: rgba(255, 255, 255, 0.7);
            text-transform: uppercase;
            letter-spacing: 0.5px;
        }
        
        .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);
        }
        
        .last-updated {
            text-align: center;
            color: rgba(255, 255, 255, 0.6);
            font-size: 0.9rem;
            margin-top: 2rem;
            font-style: italic;
        }
        
        .vehicle-kills-leaderboard {
            margin-top: 1rem;
        }
        
        .leaderboard-table-container {
            overflow-x: auto;
            -webkit-overflow-scrolling: touch;
        }
        
        .vehicle-kills-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;
        }
        
        .vehicle-kills-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);
            cursor: pointer;
            transition: all 0.3s ease;
            position: relative;
        }
        
        .vehicle-kills-table th:first-child {
            text-align: left;
        }
        
        .vehicle-kills-table th.sortable {
            user-select: none;
        }
        
        .vehicle-kills-table th.sortable:hover {
            background: linear-gradient(135deg, rgba(144, 238, 144, 0.25), rgba(144, 238, 144, 0.1));
        }
        
        .vehicle-kills-table .sort-icon {
            font-size: 0.8rem;
            opacity: 0.6;
            margin-left: 0.5rem;
        }
        
        .vehicle-kills-table th.sortable.sorted-asc .sort-icon {
            opacity: 1;
        }
        
        .vehicle-kills-table th.sortable.sorted-asc .sort-icon::before {
            content: "\f0de"; /* fa-sort-up */
        }
        
        .vehicle-kills-table th.sortable.sorted-desc .sort-icon {
            opacity: 1;
        }
        
        .vehicle-kills-table th.sortable.sorted-desc .sort-icon::before {
            content: "\f0dd"; /* fa-sort-down */
        }
        
        .vehicle-kills-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;
        }
        
        .vehicle-kills-table td:first-child {
            text-align: left;
        }
        
        .vehicle-kills-table tr:hover td {
            background: rgba(144, 238, 144, 0.05);
        }
        
        .vehicle-kills-table tr:last-child td {
            border-bottom: none;
        }
        
        .vehicle-kills-table th:nth-child(1), 
        .vehicle-kills-table td:nth-child(1) {
            width: 80px;
            min-width: 80px;
        }
        
        .vehicle-kills-table th:nth-child(2), 
        .vehicle-kills-table td:nth-child(2) {
            width: 25%;
            min-width: 180px;
            text-align: left !important;
            white-space: normal;
            word-wrap: break-word;
            max-width: 250px;
        }
        
        .vehicle-kills-table th:nth-child(3), 
        .vehicle-kills-table td:nth-child(3),
        .vehicle-kills-table th:nth-child(4), 
        .vehicle-kills-table td:nth-child(4),
        .vehicle-kills-table th:nth-child(5), 
        .vehicle-kills-table td:nth-child(5),
        .vehicle-kills-table th:nth-child(6), 
        .vehicle-kills-table td:nth-child(6),
        .vehicle-kills-table th:nth-child(7), 
        .vehicle-kills-table td:nth-child(7),
        .vehicle-kills-table th:nth-child(8), 
        .vehicle-kills-table td:nth-child(8) {
            width: 110px;
            min-width: 110px;
        }
        
        .vehicle-kills-rank-cell {
            font-weight: 700;
            font-size: 1.1rem;
            width: 80px;
        }
        
        .vehicle-kills-rank-1 { color: #ffd700; text-shadow: 0 0 10px rgba(255, 215, 0, 0.5); }
        .vehicle-kills-rank-2 { color: #c0c0c0; text-shadow: 0 0 10px rgba(192, 192, 192, 0.5); }
        .vehicle-kills-rank-3 { color: #cd7f32; text-shadow: 0 0 10px rgba(205, 127, 50, 0.5); }
        
        .vehicle-kills-name-cell {
            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);
        }
        
        .vehicle-kills-stat-cell {
            font-weight: 600;
            font-size: 1rem;
            color: #90EE90;
            text-shadow: 0 0 10px rgba(144, 238, 144, 0.5);
        }
        
        /* 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.statsTitle') %></h1>
            <p class="leaderboard-subtitle"><%= t('leaderboard.statsSubtitle') %></p>
            <div class="disclaimer">
                <i class="fas fa-info-circle" style="margin-right: 0.5rem;"></i>
                <%= t('common.recordingSince') %>
            </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">
                <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 active">
                <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="loading-state" id="loadingState">
            <div class="loading-spinner"></div>
            <p><%= t('leaderboard.loadingGlobalStats') %></p>
        </div>
        
        <div class="error-state" id="errorState" style="display: none;">
            <i class="fas fa-exclamation-triangle error-icon"></i>
            <h3><%= t('leaderboard.failedToLoadStats') %></h3>
            <p id="errorMessage"><%= t('leaderboard.unableToFetchStats') %></p>
            <button class="retry-btn" onclick="loadStatistics()">
                <i class="fas fa-redo"></i> <%= t('common.retry') %>
            </button>
        </div>
        
        <div id="statisticsContent" style="display: none;">
            <div class="stats-grid" id="statsGrid">
            </div>
            
            <div class="vehicles-section">
                <h2 class="section-title"><%= t('leaderboard.mostPopularVehicles') %></h2>
                <div class="vehicles-grid" id="vehiclesGrid">
                </div>
            </div>
            
            <div class="vehicles-section" style="margin-top: 2rem;">
                <h2 class="section-title"><%= t('leaderboard.vehicleKillsLeaderboardTitle') %></h2>
                <div class="vehicle-kills-leaderboard">
                    <div class="leaderboard-table-container">
                        <table class="vehicle-kills-table" id="vehicleKillsTable">
                            <thead>
                                <tr>
                                    <th>
                                        <%= t('common.rank') %>
                                    </th>
                                    <th>
                                        <%= t('common.vehicle') %>
                                    </th>
                                    <th class="sortable" onclick="sortVehicleKills('total_battles')" data-sort="total_battles">
                                        <%= t('common.totalBattles') %> <i class="fas fa-sort sort-icon"></i>
                                    </th>
                                    <th class="sortable" onclick="sortVehicleKills('avg_win_rate')" data-sort="avg_win_rate">
                                        <%= t('leaderboard.avgWinRate') %> <i class="fas fa-sort sort-icon"></i>
                                    </th>
                                    <th class="sortable" onclick="sortVehicleKills('ground_kills')" data-sort="ground_kills">
                                        <%= t('common.groundKills') %> <i class="fas fa-sort sort-icon"></i>
                                    </th>
                                    <th class="sortable" onclick="sortVehicleKills('air_kills')" data-sort="air_kills">
                                        Air Kills <i class="fas fa-sort sort-icon"></i>
                                    </th>
                                    <th class="sortable" onclick="sortVehicleKills('players')" data-sort="players">
                                        Players <i class="fas fa-sort sort-icon"></i>
                                    </th>
                                    <th class="sortable" onclick="sortVehicleKills('avg_kills')" data-sort="avg_kills">
                                        Average Kills/Player <i class="fas fa-sort sort-icon"></i>
                                    </th>
                                </tr>
                            </thead>
                            <tbody id="vehicleKillsBody">
                            </tbody>
                        </table>
                    </div>
                    <div class="loading-placeholder" id="vehicleKillsLoading" style="text-align: center; padding: 2rem; color: #90EE90;">
                        <div class="loading-spinner"></div>
                        <p><%= t('leaderboard.loadingVehicleKills') %></p>
                    </div>
                </div>
            </div>
            
            <div class="last-updated" id="lastUpdated"></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>
        let statisticsData = null;
        
        async function loadStatistics() {
            const loadingState = document.getElementById('loadingState');
            const errorState = document.getElementById('errorState');
            const statisticsContent = document.getElementById('statisticsContent');
            
            loadingState.style.display = 'block';
            errorState.style.display = 'none';
            statisticsContent.style.display = 'none';
            
            try {
                if (!window.apiClient || typeof window.apiClient.getLeaderboardStats !== 'function') {
                    throw new Error(__t('leaderboard.apiNotLoaded'));
                }
                
                await window.ensureAPIClient();
                
                statisticsData = await window.apiClient.getLeaderboardStats();
                displayStatistics();
                
            } catch (error) {
                console.error('Error loading statistics:', error);
                showError(error.message || __t('leaderboard.failedToLoadStats'));
            }
        }
        
        function displayStatistics() {
            const loadingState = document.getElementById('loadingState');
            const statisticsContent = document.getElementById('statisticsContent');
            
            if (!statisticsData) {
                showError(__t('leaderboard.noStatsData'));
                return;
            }
            
            loadingState.style.display = 'none';
            statisticsContent.style.display = 'block';
            
            displayGlobalStats();
            
            displayTopVehicles();
            
            loadVehicleKillsLeaderboard();
            
            displayLastUpdated();
        }
        
        function displayGlobalStats() {
            const statsGrid = document.getElementById('statsGrid');
            
            const stats = [
                {
                    title: __t('leaderboard.totalPlayersCard'),
                    value: formatLargeNumber(statisticsData.total_players || 0),
                    label: __t('leaderboard.activePlayers'),
                    icon: 'fas fa-users'
                },
                {
                    title: __t('leaderboard.vehiclesUsed'),
                    value: formatLargeNumber(statisticsData.total_vehicles_used || 0),
                    label: __t('leaderboard.differentVehicles'),
                    icon: 'fas fa-tank'
                },
                {
                    title: __t('common.totalBattles'),
                    value: formatLargeNumber(Math.floor((statisticsData.total_battles || 0) / 16)),
                    label: __t('leaderboard.squadronBattlesLabel'),
                    icon: 'fas fa-crosshairs'
                }
            ];
            
            statsGrid.innerHTML = '';
            
            stats.forEach(stat => {
                const card = document.createElement('div');
                card.className = 'stats-card';
                
                card.innerHTML = `
                    <div class="stats-card-title">
                        <i class="${stat.icon}" style="margin-right: 0.5rem;"></i>
                        ${stat.title}
                    </div>
                    <div class="stats-card-value">${stat.value}</div>
                    <div class="stats-card-label">${stat.label}</div>
                `;
                
                statsGrid.appendChild(card);
            });
        }
        
        function displayTopVehicles() {
            const vehiclesGrid = document.getElementById('vehiclesGrid');
            
            if (!statisticsData.top_vehicles || statisticsData.top_vehicles.length === 0) {
                vehiclesGrid.innerHTML = '<p style="text-align: center; color: rgba(255, 255, 255, 0.6);">' + __t('leaderboard.noVehicleData') + '</p>';
                return;
            }
            
            vehiclesGrid.innerHTML = '';
            
            console.log(`API returned ${statisticsData.top_vehicles.length} vehicles, requesting 12`);
            
            const topVehicles = statisticsData.top_vehicles.slice(0, 12);
            
            topVehicles.forEach((vehicle, index) => {
                const item = document.createElement('a');
                item.className = 'vehicle-item';
                item.href = `/leaderboard/vehicles?vehicle=${encodeURIComponent(vehicle.vehicle)}`;
                
                item.innerHTML = `
                    <div class="vehicle-rank">#${index + 1} ${__t('leaderboard.mostPopular')}</div>
                    <div class="vehicle-name" data-vehicle-internal="${escapeHtml(vehicle.vehicle_internal || '')}">${escapeHtml(vehicle.vehicle)}</div>
                    <div class="vehicle-usage">${formatLargeNumber(vehicle.usage_count)}</div>
                    <div class="vehicle-label">${__t('leaderboard.timesUsed')}</div>
                `;
                
                vehiclesGrid.appendChild(item);
            });
        }
        
        function displayLastUpdated() {
            const lastUpdated = document.getElementById('lastUpdated');
            
            if (statisticsData.last_updated) {
                const date = new Date(statisticsData.last_updated);
                const formattedDate = date.toLocaleString('en-US', {
                    year: 'numeric',
                    month: 'short',
                    day: 'numeric',
                    hour: '2-digit',
                    minute: '2-digit',
                    timeZoneName: 'short'
                });
                
                lastUpdated.innerHTML = `
                    <i class="fas fa-clock" style="margin-right: 0.5rem;"></i>
                    ${__t('leaderboard.lastUpdated')}: ${formattedDate}
                `;
            } else {
                lastUpdated.innerHTML = '';
            }
        }
        
        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 formatLargeNumber(num) {
            if (num >= 1000000) {
                return (num / 1000000).toFixed(1) + 'M';
            } else if (num >= 1000) {
                return (num / 1000).toFixed(1) + 'K';
            }
            return num.toLocaleString();
        }
        
        function escapeHtml(text) {
            const div = document.createElement('div');
            div.textContent = text;
            return div.innerHTML;
        }
        
        let vehicleKillsData = [];
        let vehicleKillsSort = { field: 'total_battles', direction: 'desc' };
        
        async function loadVehicleKillsLeaderboard() {
            const loadingEl = document.getElementById('vehicleKillsLoading');
            const tableEl = document.getElementById('vehicleKillsTable');
            
            try {
                loadingEl.style.display = 'block';
                tableEl.style.display = 'none';
                
                const vehicleData = await window.apiClient.getVehicleLeaderboard(null);
                
                if (!vehicleData || !vehicleData.vehicles) {
                    throw new Error(__t('leaderboard.noVehicleData'));
                }
                
                const vehicleAggregates = {};
                
                vehicleData.vehicles.forEach(entry => {
                    const vehicleName = entry.vehicle;
                    
                    if (!vehicleAggregates[vehicleName]) {
                        vehicleAggregates[vehicleName] = {
                            vehicle: vehicleName,
                            total_battles: 0,
                            total_wins: 0,
                            ground_kills: 0,
                            air_kills: 0,
                            players: 0,
                            total_kills: 0
                        };
                    }
                    
                    vehicleAggregates[vehicleName].total_battles += entry.battles || 0;
                    vehicleAggregates[vehicleName].total_wins += entry.wins || 0;
                    vehicleAggregates[vehicleName].ground_kills += entry.ground_kills || 0;
                    vehicleAggregates[vehicleName].air_kills += entry.air_kills || 0;
                    vehicleAggregates[vehicleName].total_kills += entry.total_kills || 0;
                    vehicleAggregates[vehicleName].players += 1;
                });
                
                vehicleKillsData = Object.values(vehicleAggregates).map(vehicle => ({
                    ...vehicle,
                    avg_win_rate: vehicle.total_battles > 0 ? ((vehicle.total_wins / vehicle.total_battles) * 100) : 0,
                    avg_kills: vehicle.players > 0 ? (vehicle.total_kills / vehicle.players) : 0
                }));
                
                sortVehicleKillsData();
                displayVehicleKillsLeaderboard();
                
                loadingEl.style.display = 'none';
                tableEl.style.display = 'table';
                
            } catch (error) {
                console.error('Error loading vehicle kills leaderboard:', error);
                loadingEl.innerHTML = `
                    <p style="color: #ff3838;">
                        <i class="fas fa-exclamation-triangle"></i>
                        ${__t('leaderboard.failedToLoadVehicleKills')}
                    </p>
                `;
            }
        }
        
        function sortVehicleKillsData() {
            const field = vehicleKillsSort.field;
            const direction = vehicleKillsSort.direction;
            
            vehicleKillsData.sort((a, b) => {
                let aVal = a[field];
                let bVal = b[field];
                
                if (field === 'vehicle') {
                    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;
            });
        }
        
        function displayVehicleKillsLeaderboard() {
            const tbody = document.getElementById('vehicleKillsBody');
            const fragment = document.createDocumentFragment();
            
            // 20
            const topVehicles = vehicleKillsData.slice(0, 20);
            
            topVehicles.forEach((vehicle, index) => {
                const row = document.createElement('tr');
                const rank = index + 1;
                const rankClass = rank <= 3 ? `vehicle-kills-rank-${rank}` : '';
                
                row.innerHTML = `
                    <td class="vehicle-kills-rank-cell ${rankClass}">
                        ${rank <= 3 ? getRankIcon(rank) : `#${rank}`}
                    </td>
                    <td class="vehicle-kills-name-cell" data-vehicle-internal="${escapeHtml(vehicle.vehicle_internal || '')}">${escapeHtml(vehicle.vehicle)}</td>
                    <td class="vehicle-kills-stat-cell">${formatLargeNumber(vehicle.total_battles)}</td>
                    <td class="vehicle-kills-stat-cell">${vehicle.avg_win_rate.toFixed(1)}%</td>
                    <td class="vehicle-kills-stat-cell">${formatLargeNumber(vehicle.ground_kills)}</td>
                    <td class="vehicle-kills-stat-cell">${formatLargeNumber(vehicle.air_kills)}</td>
                    <td class="vehicle-kills-stat-cell">${formatLargeNumber(vehicle.players)}</td>
                    <td class="vehicle-kills-stat-cell">${vehicle.avg_kills.toFixed(1)}</td>
                `;
                
                fragment.appendChild(row);
            });
            
            tbody.innerHTML = '';
            tbody.appendChild(fragment);
        }
        
        
        function sortVehicleKills(field) {
            if (vehicleKillsSort.field === field) {
                vehicleKillsSort.direction = vehicleKillsSort.direction === 'desc' ? 'asc' : 'desc';
            } else {
                vehicleKillsSort.field = field;
                vehicleKillsSort.direction = 'desc';
            }
            
            document.querySelectorAll('.vehicle-kills-table th').forEach(th => {
                th.classList.remove('sorted-asc', 'sorted-desc');
            });
            
            const currentHeader = document.querySelector(`.vehicle-kills-table th[data-sort="${field}"]`);
            if (currentHeader) {
                currentHeader.classList.add(`sorted-${vehicleKillsSort.direction}`);
            }
            
            sortVehicleKillsData();
            displayVehicleKillsLeaderboard();
        }
        
        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 '';
            }
        }
        
        document.addEventListener('DOMContentLoaded', () => {
            setTimeout(loadStatistics, 100);
        });
    </script>
</body>
</html>
