<!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('squadrons.title') %> | <%= botName %></title>
    <meta name="description" content="<%= t('squadrons.subtitle') %>">
    <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);
        }
        
        .squadron-hub-container {
            max-width: 1400px;
            margin: 0 auto;
            padding: 6rem 1rem 2rem;
            min-height: calc(100vh - 200px);
        }
        
        .squadron-header {
            text-align: center;
            margin-bottom: 2rem;
        }
        
        .squadron-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;
        }
        
        .squadron-subtitle {
            font-size: 1.1rem;
            color: rgba(255, 255, 255, 0.8);
            margin-bottom: 1rem;
        }
        
        .squadron-search-section {
            background: rgba(30, 30, 30, 0.6);
            border-radius: 1rem;
            padding: 1.5rem 2rem;
            backdrop-filter: blur(10px);
            border: 1px solid rgba(144, 238, 144, 0.1);
            margin-bottom: 2rem;
            position: relative;
            z-index: 100;
        }
        
        .search-title {
            font-size: 1.1rem;
            font-weight: 600;
            color: #90EE90;
            margin-bottom: 0.75rem;
            text-align: center;
        }
        
        .squadron-search-container {
            max-width: 500px;
            margin: 0 auto;
            position: relative;
            z-index: 10;
        }
        
        .squadron-search-input {
            width: 100%;
            padding: 0.875rem 0.875rem 0.875rem 2.75rem;
            background: rgba(30, 30, 30, 0.9);
            border: 1px solid rgba(144, 238, 144, 0.2);
            border-radius: 0.5rem;
            color: #ffffff;
            font-size: 1rem;
            font-weight: 500;
            transition: all 0.3s ease;
        }

        .squadron-search-input:focus {
            outline: none;
            border-color: rgba(144, 238, 144, 0.4);
            box-shadow: 0 0 0 2px rgba(144, 238, 144, 0.1);
        }
        
        .squadron-search-input::placeholder {
            color: rgba(255, 255, 255, 0.5);
        }
        
        .squadron-search-icon {
            position: absolute;
            left: 0.875rem;
            top: 50%;
            transform: translateY(-50%);
            color: #90EE90;
            font-size: 1.1rem;
        }
        
        .squadron-search-results {
            position: absolute;
            top: 100%;
            left: 0;
            right: 0;
            background: rgba(30, 30, 30, 0.98);
            border: 1px solid rgba(144, 238, 144, 0.2);
            border-radius: 0.75rem;
            margin-top: 0.5rem;
            max-height: 400px;
            overflow-y: auto;
            z-index: 999;
            box-shadow: 0 8px 32px rgba(0, 0, 0, 0.5);
            display: none;
        }

        .squadron-search-results.show {
            display: block;
        }

        .squadron-search-result-item {
            display: block;
            color: inherit;
            text-decoration: none;
            padding: 1rem 1.5rem;
            cursor: pointer;
            transition: all 0.2s ease;
            border-bottom: 1px solid rgba(144, 238, 144, 0.1);
        }

        .squadron-search-result-item:last-child {
            border-bottom: none;
        }

        .squadron-search-result-item:hover {
            background: rgba(144, 238, 144, 0.05);
        }

        .squadron-result-name {
            font-weight: 600;
            color: #90EE90;
            font-size: 1.1rem;
            margin-bottom: 0.25rem;
        }

        .squadron-result-stats {
            font-size: 0.9rem;
            color: rgba(255, 255, 255, 0.7);
        }
        
        .stats-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 1rem;
            margin-bottom: 2rem;
        }
        
        .stat-card {
            background: rgba(30, 30, 30, 0.6);
            border-radius: 0.75rem;
            padding: 1.25rem;
            backdrop-filter: blur(10px);
            border: 1px solid rgba(144, 238, 144, 0.1);
            text-align: center;
            transition: all 0.3s ease;
        }

        .stat-card:hover {
            border-color: rgba(144, 238, 144, 0.3);
            transform: translateY(-2px);
        }

        .stat-value {
            font-size: 2rem;
            font-weight: 700;
            color: #F5F5DC;
            display: block;
            margin-bottom: 0.35rem;
        }

        .stat-label {
            font-size: 0.9rem;
            color: rgba(255, 255, 255, 0.8);
            font-weight: 500;
        }
        
        .leaderboard-preview {
            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);
        }

        .leaderboard-preview-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 1.5rem;
        }

        .leaderboard-preview-title {
            font-size: 1.5rem;
            font-weight: 600;
            color: #F5F5DC;
        }

        .view-full-btn {
            background: linear-gradient(135deg, #F5F5DC 0%, #E8E8D0 100%);
            color: #1E1E1E;
            border: none;
            padding: 0.75rem 1.5rem;
            border-radius: 0.5rem;
            font-weight: 700;
            cursor: pointer;
            transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
            text-decoration: none;
            display: inline-block;
            box-shadow: 0 4px 20px rgba(245, 245, 220, 0.15), inset 0 1px 0 rgba(255, 255, 255, 0.4);
        }

        .view-full-btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 8px 25px rgba(245, 245, 220, 0.3), inset 0 1px 0 rgba(255, 255, 255, 0.4);
        }
        
        .squadron-table {
            width: 100%;
            border-collapse: collapse;
            background: rgba(30, 30, 30, 0.8);
            border-radius: 0.75rem;
            overflow: hidden;
        }

        .squadron-table th {
            background: linear-gradient(135deg, rgba(144, 238, 144, 0.15), rgba(144, 238, 144, 0.05));
            color: #F5F5DC;
            padding: 1rem;
            text-align: left;
            font-weight: 600;
            text-transform: uppercase;
            font-size: 0.9rem;
            text-shadow: 0 0 10px rgba(144, 238, 144, 0.3);
            border-bottom: 1px solid rgba(144, 238, 144, 0.2);
        }

        .squadron-table td {
            padding: 1rem;
            border-bottom: 1px solid rgba(144, 238, 144, 0.1);
            color: #ffffff;
        }

        .squadron-table tr:hover {
            background: rgba(144, 238, 144, 0.05);
            cursor: pointer;
        }

        .squadron-name {
            font-family: 'skyquakesymbols', 'Inter', sans-serif !important;
            font-weight: 600;
            color: #90EE90;
            font-size: 1.1rem;
        }
        
        .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); }
        }
        
    </style>
</head>
<body class="text-white antialiased">
    <%- include('partials/nav', { activePage: 'squadrons' }) %>

    <div class="squadron-hub-container">
        <div class="squadron-header">
            <h1 class="squadron-title"><%= t('squadrons.title') %></h1>
            <p class="squadron-subtitle"><%= t('squadrons.subtitle') %></p>
        </div>
        
        <div class="squadron-search-section">
            <h2 class="search-title"><%= t('squadrons.findSquadron') %></h2>
            <div class="squadron-search-container">
                <i class="fas fa-search squadron-search-icon"></i>
                <input type="text" 
                       class="squadron-search-input" 
                       id="squadronSearchInput" 
                       placeholder="<%= t('squadrons.searchPlaceholder') %>"
                       oninput="searchSquadrons()"
                       onkeydown="handleSquadronKeydown(event)">
                <div class="squadron-search-results" id="squadronSearchResults"></div>
            </div>
        </div>
        
        <div class="stats-grid" id="statsGrid">
            <div class="stat-card">
                <span class="stat-value" id="totalSquadrons">-</span>
                <span class="stat-label"><%= t('squadrons.totalSquadrons') %></span>
            </div>
            <div class="stat-card">
                <span class="stat-value" id="totalPlayers">-</span>
                <span class="stat-label"><%= t('squadrons.totalPlayers') %></span>
            </div>
            <div class="stat-card">
                <span class="stat-value" id="totalBattles">-</span>
                <span class="stat-label"><%= t('squadrons.totalBattles') %></span>
            </div>
            <div class="stat-card">
                <span class="stat-value" id="avgWinRate">-</span>
                <span class="stat-label"><%= t('squadrons.avgWinRate') %></span>
            </div>
        </div>
        
        <div class="leaderboard-preview">
            <div class="leaderboard-preview-header">
                <h2 class="leaderboard-preview-title"><%= t('squadrons.topSquadrons') %></h2>
                <a href="/leaderboard/squadrons" class="view-full-btn">
                    <i class="fas fa-list"></i> <%= t('leaderboard.viewFullLeaderboard') %>
                </a>
            </div>
            
            <div class="loading-state" id="loadingState">
                <div class="loading-spinner"></div>
                <p><%= t('squadrons.loadingSquadrons') %></p>
            </div>
            
            <div id="leaderboardPreview" style="display: none;">
                <table class="squadron-table">
                    <thead>
                        <tr>
                            <th><%= t('common.rank') %></th>
                            <th><%= t('common.squadron') %></th>
                            <th><%= t('common.players') %></th>
                            <th><%= t('common.wins') %></th>
                            <th><%= t('common.winRate') %></th>
                        </tr>
                    </thead>
                    <tbody id="squadronTableBody">
                    </tbody>
                </table>
            </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/header-search.js?v=2"></script>
    <script>
        let allSquadrons = [];
        let searchTimeout;
        
        async function loadSquadronData() {
            const loadingState = document.getElementById('loadingState');
            const leaderboardPreview = document.getElementById('leaderboardPreview');
            
            try {
                await window.ensureAPIClient();
                
                const leaderboardData = await window.apiClient.getSquadronLeaderboard();
                
                if (!leaderboardData || !leaderboardData.squadrons || leaderboardData.squadrons.length === 0) {
                    loadingState.innerHTML = '<p>' + __t('squadrons.noSquadronData') + '</p>';
                    return;
                }
                
                allSquadrons = leaderboardData.squadrons;
                
                // Update stats
                document.getElementById('totalSquadrons').textContent = leaderboardData.total_squadrons || allSquadrons.length;
                
                let totalPlayers = 0;
                let totalBattles = 0;
                let totalWinRate = 0;
                
                allSquadrons.forEach(squadron => {
                    totalPlayers += squadron.player_count || 0;
                    totalBattles += squadron.total_battles || 0;
                    totalWinRate += squadron.win_rate || 0;
                });
                
                document.getElementById('totalPlayers').textContent = formatNumber(totalPlayers);
                document.getElementById('totalBattles').textContent = formatNumber(totalBattles);
                document.getElementById('avgWinRate').textContent = (totalWinRate / allSquadrons.length).toFixed(1) + '%';
                
                // Display top 10 squadrons
                displayTopSquadrons(allSquadrons.slice(0, 10));
                
                loadingState.style.display = 'none';
                leaderboardPreview.style.display = 'block';
                
            } catch (error) {
                console.error('Error loading squadron data:', error);
                loadingState.innerHTML = '<p style="color: #ff3838;">' + __t('squadrons.failedToLoad') + '</p>';
            }
        }
        
        function displayTopSquadrons(squadrons) {
            const tbody = document.getElementById('squadronTableBody');
            tbody.innerHTML = '';
            
            squadrons.forEach((squadron, index) => {
                const row = document.createElement('tr');
                row.className = 'row-link';
                // Canonical URL is /squadrons/<clan_id>; fall back to name only
                // for older API responses that didn't include clan_id.
                const squadronUrlPath = squadron.clan_id != null
                    ? String(squadron.clan_id)
                    : encodeURIComponent(squadron.long_name || squadron.tag_name || squadron.squadron_name);
                const squadronDisplayName = squadron.tag_name || squadron.squadron_name;
                
                row.innerHTML = `
                    <td><a href="/squadrons/${squadronUrlPath}" class="row-link-overlay" aria-label="View ${escapeHtml(squadronDisplayName)}"></a>${index + 1}</td>
                    <td class="squadron-name" style="font-family: 'skyquakesymbols', 'Inter', sans-serif !important;">${escapeHtml(squadronDisplayName)}</td>
                    <td>${squadron.player_count}</td>
                    <td>${formatNumber(squadron.wins)}</td>
                    <td>${squadron.win_rate.toFixed(1)}%</td>
                `;
                
                tbody.appendChild(row);
            });
        }
        
        function searchSquadrons() {
            const searchTerm = document.getElementById('squadronSearchInput').value.trim();
            const resultsDiv = document.getElementById('squadronSearchResults');
            
            clearTimeout(searchTimeout);
            
            if (searchTerm.length < 2) {
                resultsDiv.classList.remove('show');
                return;
            }
            
            searchTimeout = setTimeout(() => {
                const searchLower = searchTerm.toLowerCase();
                const seenClanIds = new Set();
                const filteredSquadrons = allSquadrons
                    .filter(squadron => {
                        const names = [squadron.long_name, squadron.tag_name, squadron.short_name, squadron.squadron_name]
                            .filter(Boolean)
                            .map(n => n.toLowerCase());
                        if (!names.some(n => n.includes(searchLower))) return false;
                        // De-dupe by clan_id so a short_name + long_name hit on the same clan
                        // can't show twice in the dropdown.
                        if (squadron.clan_id != null) {
                            if (seenClanIds.has(squadron.clan_id)) return false;
                            seenClanIds.add(squadron.clan_id);
                        }
                        return true;
                    })
                    .slice(0, 10);
                
                if (filteredSquadrons.length === 0) {
                    resultsDiv.innerHTML = '<div class="squadron-search-result-item">' + __t('common.noSquadronsFound') + '</div>';
                } else {
                    resultsDiv.innerHTML = filteredSquadrons.map(squadron => {
                        const squadronUrlPath = squadron.clan_id != null
                            ? String(squadron.clan_id)
                            : encodeURIComponent(squadron.long_name || squadron.tag_name || squadron.squadron_name);
                        const squadronDisplayName = squadron.tag_name && squadron.long_name
                            ? `${squadron.tag_name} ${squadron.long_name}`
                            : (squadron.tag_name || squadron.long_name || squadron.squadron_name);
                        return `
                            <a href="/squadrons/${escapeHtml(squadronUrlPath)}" class="squadron-search-result-item">
                                <div class="squadron-result-name" style="font-family: 'skyquakesymbols', 'Inter', sans-serif !important;">${escapeHtml(squadronDisplayName)}</div>
                                <div class="squadron-result-stats">${squadron.player_count} ${__t('common.playersCount')} • ${formatNumber(squadron.total_kills)} ${__t('js.killsSuffix')} • ${squadron.win_rate.toFixed(1)}% ${__t('js.winRateSuffix')}</div>
                            </a>
                        `;
                    }).join('');
                }
                
                resultsDiv.classList.add('show');
            }, 300);
        }
        
        function handleSquadronKeydown(event) {
            if (event.key === 'Escape') {
                document.getElementById('squadronSearchResults').classList.remove('show');
                document.getElementById('squadronSearchInput').blur();
            }
        }
        
        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;
        }
        
        document.addEventListener('click', function(event) {
            if (!event.target.closest('.squadron-search-container')) {
                document.getElementById('squadronSearchResults').classList.remove('show');
            }
        });
        
        document.addEventListener('DOMContentLoaded', () => {
            setTimeout(loadSquadronData, 100);
        });
    </script>
</body>
</html>
