<!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>Match History | <%= botName %></title>
    <meta name="description" content="Search and browse War Thunder squadron battle matches by player or map.">
    <link rel="icon" type="image/png" href="/images/transparent_toothlessssss.png">

    <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">
    <link rel="stylesheet" href="/css/output.css">
    <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);
        }

        .games-container {
            max-width: 1400px;
            margin: 0 auto;
            padding: 8rem 1rem 2rem 1rem;
            min-height: calc(100vh - 200px);
        }

        .games-header {
            text-align: center;
            margin-bottom: 2rem;
        }
        .games-title {
            font-size: 3rem;
            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;
        }
        .games-subtitle {
            font-size: 1.2rem;
            color: #90EE90;
        }

        /* Search form */
        .search-card {
            background: linear-gradient(135deg, rgba(62, 78, 62, 0.2) 0%, rgba(44, 44, 44, 0.2) 100%);
            border-radius: 1rem;
            padding: 1.5rem;
            backdrop-filter: blur(10px);
            border: 1px solid rgba(144, 238, 144, 0.15);
            margin-bottom: 2rem;
        }
        .search-form {
            display: flex;
            gap: 1rem;
            align-items: flex-end;
            flex-wrap: wrap;
        }
        .search-field {
            flex: 1;
            min-width: 200px;
            position: relative;
            z-index: 1;
        }
        .search-field:has(.autocomplete-list[style*="block"]) {
            z-index: 200;
        }
        .search-field label {
            display: block;
            font-size: 0.75rem;
            font-weight: 600;
            text-transform: uppercase;
            letter-spacing: 0.05em;
            color: #90EE90;
            margin-bottom: 0.4rem;
        }
        .search-input, .search-select {
            width: 100%;
            padding: 0.7rem 1rem;
            border-radius: 0.5rem;
            border: 1px solid rgba(144, 238, 144, 0.2);
            background: rgba(0, 0, 0, 0.4);
            color: #F5F5DC;
            font-size: 0.95rem;
            font-family: inherit;
            outline: none;
            transition: border-color 0.2s;
        }
        .search-input:focus, .search-select:focus {
            border-color: rgba(144, 238, 144, 0.5);
        }
        .search-input::placeholder { color: rgba(255, 255, 255, 0.3); }
        .search-input[type="date"]::-webkit-calendar-picker-indicator { filter: invert(0.7); cursor: pointer; }
        .search-input[type="date"] { color-scheme: dark; }
        .search-select option { background: #1E1E1E; color: #F5F5DC; }
        .search-btn {
            padding: 0.7rem 2rem;
            border-radius: 0.5rem;
            border: none;
            background: linear-gradient(135deg, #F5F5DC 0%, #E8E8D0 100%);
            color: #1E1E1E;
            font-weight: 700;
            font-size: 0.95rem;
            cursor: pointer;
            transition: all 0.3s ease;
            white-space: nowrap;
        }
        .search-btn:hover { transform: translateY(-1px); box-shadow: 0 4px 15px rgba(245, 245, 220, 0.25); }
        .search-btn:disabled { opacity: 0.5; cursor: not-allowed; transform: none; }

        /* Autocomplete */
        .autocomplete-wrapper { position: relative; }
        .autocomplete-list {
            position: absolute;
            top: 100%;
            left: 0;
            right: 0;
            background: rgba(20, 20, 20, 0.98);
            border: 1px solid rgba(144, 238, 144, 0.15);
            border-radius: 0 0 0.5rem 0.5rem;
            max-height: 240px;
            overflow-y: auto;
            z-index: 999;
            backdrop-filter: blur(24px);
            box-shadow: 0 12px 40px rgba(0, 0, 0, 0.5);
            display: none;
        }
        .autocomplete-item {
            padding: 0.5rem 1rem;
            cursor: pointer;
            font-size: 0.9rem;
            color: #F5F5DC;
            transition: background 0.1s;
        }
        .autocomplete-item:hover { background: rgba(144, 238, 144, 0.1); }
        .autocomplete-item .uid { color: rgba(255, 255, 255, 0.3); font-size: 0.75rem; margin-left: 0.5rem; }
        .autocomplete-item .sq-tag { color: rgba(144, 238, 144, 0.4); font-size: 0.8rem; margin-right: 0.4rem; font-family: 'skyquakesymbols', 'Inter', sans-serif; }
        .autocomplete-item .player-stats { color: rgba(255, 255, 255, 0.3); font-size: 0.7rem; display: block; margin-top: 0.1rem; }
        .sq-active-input { color: #90EE90 !important; font-family: 'skyquakesymbols', 'Inter', sans-serif; }

        /* Results */
        .results-info {
            font-size: 0.9rem;
            color: rgba(255, 255, 255, 0.5);
            margin-bottom: 1rem;
        }
        .matches-grid {
            display: grid;
            gap: 1rem;
        }

        /* Match card (from live.ejs) */
        .match-card {
            display: block;
            color: inherit;
            text-decoration: none;
            background: rgba(30, 30, 30, 0.8);
            border: 1px solid rgba(144, 238, 144, 0.15);
            border-radius: 0.75rem;
            padding: 1.25rem 1.5rem;
            cursor: pointer;
            position: relative;
            overflow: hidden;
            transition: border-color 0.2s, transform 0.15s;
        }
        .match-card:hover {
            border-color: rgba(144, 238, 144, 0.35);
            transform: translateY(-1px);
        }
        .match-card::before {
            content: '';
            position: absolute;
            top: 0; left: 0; right: 0; bottom: 0;
            background-image: var(--bg-img);
            background-size: cover;
            background-position: center;
            opacity: 0.08;
            pointer-events: none;
        }
        .match-card > * { position: relative; z-index: 1; }

        .match-card-inner {
            display: flex;
            align-items: center;
            justify-content: space-between;
            gap: 1.5rem;
            flex-wrap: wrap;
        }
        .match-card-teams {
            display: flex;
            align-items: center;
            gap: 0.75rem;
            font-weight: 700;
            font-size: 1.1rem;
        }
        .match-card-winner { color: #90EE90; text-shadow: 0 0 8px rgba(144, 238, 144, 0.2); font-family: 'skyquakesymbols', 'Inter', sans-serif; }
        .match-card-loser { color: rgba(255, 255, 255, 0.6); font-family: 'skyquakesymbols', 'Inter', sans-serif; }
        .match-card-vs { color: rgba(255, 255, 255, 0.3); font-size: 0.8rem; font-weight: 400; }
        .match-card-meta {
            display: flex;
            gap: 1.5rem;
            font-size: 0.85rem;
            color: rgba(255, 255, 255, 0.5);
        }
        .match-card-meta i { color: #90EE90; margin-right: 0.3rem; }
        .match-card-badge {
            padding: 0.15rem 0.5rem;
            border-radius: 0.25rem;
            font-size: 0.65rem;
            font-weight: 700;
            text-transform: uppercase;
            background: rgba(144, 238, 144, 0.12);
            color: #90EE90;
            border: 1px solid rgba(144, 238, 144, 0.25);
        }

        /* States */
        .loading-state, .empty-state {
            text-align: center;
            padding: 4rem 2rem;
            color: rgba(255, 255, 255, 0.4);
        }
        .loading-state .spinner {
            width: 32px; height: 32px;
            border: 2px solid rgba(144, 238, 144, 0.2);
            border-top-color: #90EE90;
            border-radius: 50%;
            animation: spin 0.8s linear infinite;
            margin: 0 auto 1rem;
        }
        @keyframes spin { to { transform: rotate(360deg); } }
        .empty-state i { font-size: 2rem; margin-bottom: 0.75rem; opacity: 0.5; }
    </style>
</head>
<body class="text-white antialiased">
    <%- include('partials/nav', { activePage: 'games' }) %>

    <div class="games-container">
        <div class="games-header">
            <h1 class="games-title"><%= t('games.title') %></h1>
            <p class="games-subtitle"><%= t('games.subtitle') %></p>
        </div>

        <!-- Search -->
        <div class="search-card">
            <div class="search-form" id="searchForm">
                <div class="search-field" style="flex: 2;">
                    <label><%= t('common.player') %></label>
                    <div class="autocomplete-wrapper">
                        <input type="text" class="search-input" id="playerInput" placeholder="<%= t('games.searchPlaceholder') %>" autocomplete="off">
                        <div class="autocomplete-list" id="autocompleteList"></div>
                    </div>
                </div>
                <div class="search-field">
                    <label><%= t('common.squadron') %></label>
                    <div class="autocomplete-wrapper" style="position: relative;">
                        <input type="text" class="search-input" id="squadronInput" placeholder="<%= t('games.squadronPlaceholder') %>" autocomplete="off" style="padding-right: 2rem;">
                        <button id="squadronClear" style="display: none; background: none; border: none; color: rgba(255,255,255,0.3); cursor: pointer; font-size: 11px; padding: 4px 8px; position: absolute; right: 4px; top: 50%; transform: translateY(-50%); z-index: 2;">
                            <i class="fas fa-times"></i>
                        </button>
                        <div class="autocomplete-list" id="squadronDropdown"></div>
                    </div>
                </div>
                <div class="search-field" style="flex: 1.2;">
                    <label>Game ID</label>
                    <input type="text" class="search-input" id="gameIdInput" placeholder="e.g. 3a7f…" autocomplete="off" spellcheck="false" style="font-family: monospace; letter-spacing: 0.02em;">
                </div>
                <div class="search-field">
                    <label><%= t('games.filterByMap') %></label>
                    <select class="search-select" id="mapSelect">
                        <option value=""><%= t('games.allMaps') %></option>
                    </select>
                </div>
                <div class="search-field">
                    <label><%= t('leaderboard.from') %></label>
                    <input type="date" class="search-input" id="dateFrom">
                </div>
                <div class="search-field">
                    <label><%= t('leaderboard.to') %></label>
                    <input type="date" class="search-input" id="dateTo">
                </div>
                <button class="search-btn" id="searchBtn" onclick="searchGames()">
                    <i class="fas fa-search" style="margin-right: 0.4rem;"></i><%= t('games.search') %>
                </button>
            </div>
        </div>

        <!-- Results -->
        <div id="resultsInfo" class="results-info" style="display: none;"></div>

        <div id="loadingState" class="loading-state" style="display: none;">
            <div class="spinner"></div>
            <p><%= t('games.searchingGames') %></p>
        </div>

        <div id="emptyState" class="empty-state" style="display: none;">
            <i class="fas fa-search"></i>
            <p><%= t('games.noResults') %></p>
        </div>

        <div class="matches-grid" id="matchesList"></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=3"></script>
    <script src="/js/header-search.js?v=2"></script>
    <script>
        const __t = window.__t;
        let debounceTimer = null;
        let squadronTimer = null;
        let playersData = [];
        let allSquadrons = [];
        let selectedSquadron = null;      // tagged display name
        let selectedSquadronShort = null;  // plain short name for API query

        function escapeHtml(text) {
            const div = document.createElement('div');
            div.textContent = text;
            return div.innerHTML;
        }

        function getMapImage(mapName) {
            if (!mapName) return null;
            const cleanMapName = mapName.replace(/^\s*\[[^\]]+\]\s*/, '').trim();
            const fileName = cleanMapName.replace(/\s+/g, '_').replace(/[^\w\u00C0-\u024F\-_.()]/g, '').replace(/_+/g, '_').replace(/^_|_$/g, '').toLowerCase();
            return `/MAPS/${fileName}.jpg`;
        }

        // Load player leaderboard for autocomplete data
        async function loadLeaderboardData() {
            try {
                const response = await window.apiClient.getPlayerLeaderboard();
                playersData = (response.players || []).map(p => ({
                    ...p,
                    total_kills: p.total_kills || ((p.ground_kills || 0) + (p.air_kills || 0)),
                })).sort((a, b) => b.total_kills - a.total_kills);

                const counts = {};
                const shortNameMap = {};
                playersData.forEach(p => {
                    if (p.squadron_name) {
                        counts[p.squadron_name] = (counts[p.squadron_name] || 0) + 1;
                        if (p.squadron_short_name) shortNameMap[p.squadron_name] = p.squadron_short_name;
                    }
                });
                allSquadrons = Object.entries(counts)
                    .sort((a, b) => b[1] - a[1])
                    .map(([name, count]) => ({ name, count, short_name: shortNameMap[name] || name }));
            } catch (e) { console.error('Failed to load leaderboard data:', e); }
        }

        // Populate map dropdown
        async function loadMaps() {
            try {
                const data = await window.apiClient.getMaps();
                const select = document.getElementById('mapSelect');
                (data.maps || []).forEach(map => {
                    const opt = document.createElement('option');
                    const clean = map.replace(/^\s*\[[^\]]+\]\s*/, '').trim();
                    opt.value = map;
                    opt.textContent = clean;
                    select.appendChild(opt);
                });
            } catch (e) { console.error('Failed to load maps:', e); }
        }

        // ── Player autocomplete ──
        const playerInput = document.getElementById('playerInput');
        const autocompleteList = document.getElementById('autocompleteList');

        playerInput.addEventListener('input', function() {
            clearTimeout(debounceTimer);
            const query = this.value.trim().toLowerCase();
            if (query.length < 2) { autocompleteList.style.display = 'none'; return; }
            if (/^\d+$/.test(query)) { autocompleteList.style.display = 'none'; return; }

            debounceTimer = setTimeout(() => {
                const hits = playersData
                    .filter(p => p.nick.toLowerCase().includes(query))
                    .slice(0, 10);
                if (hits.length === 0) { autocompleteList.style.display = 'none'; return; }

                autocompleteList.innerHTML = hits.map(p => {
                    const sqTag = p.squadron_name
                        ? `<span class="sq-tag">${escapeHtml(p.squadron_name)}</span>` : '';
                    const kills = p.total_kills || 0;
                    const wr = (p.win_rate || 0).toFixed(1);
                    return `<div class="autocomplete-item" data-nick="${escapeHtml(p.nick || '')}">
                        ${sqTag}${escapeHtml(p.nick || 'Unknown')}<span class="uid">${p.uid}</span>
                        <span class="player-stats">${kills} kills · ${wr}% WR</span>
                    </div>`;
                }).join('');
                autocompleteList.style.display = 'block';
            }, 150);
        });

        autocompleteList.addEventListener('click', function(e) {
            const item = e.target.closest('.autocomplete-item');
            if (!item) return;
            playerInput.value = item.dataset.nick;
            autocompleteList.style.display = 'none';
        });

        playerInput.addEventListener('keydown', function(e) {
            if (e.key === 'Enter') { e.preventDefault(); searchGames(); }
            if (e.key === 'Escape') { autocompleteList.style.display = 'none'; playerInput.blur(); }
        });

        // ── Squadron autocomplete ──
        const sqInput = document.getElementById('squadronInput');
        const sqDrop = document.getElementById('squadronDropdown');
        const sqClear = document.getElementById('squadronClear');

        sqInput.addEventListener('input', function() {
            clearTimeout(squadronTimer);
            if (selectedSquadron) {
                selectedSquadron = null;
                selectedSquadronShort = null;
                sqInput.classList.remove('sq-active-input');
                sqClear.style.display = 'none';
            }
            const val = this.value.trim().toLowerCase();
            if (val.length < 1) { sqDrop.style.display = 'none'; return; }

            squadronTimer = setTimeout(() => {
                const hits = allSquadrons.filter(s =>
                    s.name.toLowerCase().includes(val) || s.short_name.toLowerCase().includes(val)
                ).slice(0, 12);
                if (!hits.length) {
                    sqDrop.innerHTML = '<div class="autocomplete-item" style="color: rgba(255,255,255,0.3);">' + __t('js.noSquadronsFound') + '</div>';
                } else {
                    sqDrop.innerHTML = hits.map(s =>
                        `<div class="autocomplete-item" data-name="${escapeHtml(s.name)}" data-short="${escapeHtml(s.short_name)}">
                            <span class="sq-tag">${escapeHtml(s.name)}</span>
                            <span class="uid">${s.count} ${__t('common.playersCount')}</span>
                        </div>`
                    ).join('');
                }
                sqDrop.style.display = 'block';
            }, 100);
        });

        sqDrop.addEventListener('click', function(e) {
            const item = e.target.closest('.autocomplete-item');
            if (!item || !item.dataset.name) return;
            pickSquadron(item.dataset.name, item.dataset.short);
        });

        function pickSquadron(name, shortName) {
            selectedSquadron = name;
            selectedSquadronShort = shortName || name;
            sqInput.value = name;
            sqInput.classList.add('sq-active-input');
            sqClear.style.display = 'block';
            sqDrop.style.display = 'none';
        }

        sqClear.addEventListener('click', function() {
            selectedSquadron = null;
            selectedSquadronShort = null;
            sqInput.value = '';
            sqInput.classList.remove('sq-active-input');
            sqClear.style.display = 'none';
            sqInput.focus();
        });

        sqInput.addEventListener('keydown', function(e) {
            if (e.key === 'Tab') {
                const val = sqInput.value.trim().toLowerCase();
                if (!selectedSquadron && val.length >= 1) {
                    const hits = allSquadrons.filter(s => s.name.toLowerCase().includes(val));
                    if (hits.length >= 1) { e.preventDefault(); pickSquadron(hits[0].name, hits[0].short_name); }
                }
            }
            if (e.key === 'Enter') { e.preventDefault(); searchGames(); }
            if (e.key === 'Escape') { sqDrop.style.display = 'none'; sqInput.blur(); }
        });

        // Close dropdowns on outside click
        document.addEventListener('click', function(e) {
            if (!e.target.closest('.autocomplete-wrapper')) {
                autocompleteList.style.display = 'none';
                sqDrop.style.display = 'none';
            }
        });

        async function searchGames() {
            const gameId = document.getElementById('gameIdInput').value.trim();
            if (gameId) {
                if (!/^[0-9a-fA-F]+$/.test(gameId)) {
                    document.getElementById('gameIdInput').style.borderColor = 'rgba(255, 100, 100, 0.6)';
                    document.getElementById('gameIdInput').focus();
                    return;
                }
                window.location.href = `/games/${gameId}`;
                return;
            }
            document.getElementById('gameIdInput').style.borderColor = '';

            const player = document.getElementById('playerInput').value.trim();
            const map = document.getElementById('mapSelect').value;
            const squadron = selectedSquadronShort || document.getElementById('squadronInput').value.trim();
            const dateFrom = document.getElementById('dateFrom').value;
            const dateTo = document.getElementById('dateTo').value;

            autocompleteList.style.display = 'none';
            document.getElementById('loadingState').style.display = 'block';
            document.getElementById('emptyState').style.display = 'none';
            document.getElementById('matchesList').innerHTML = '';
            document.getElementById('resultsInfo').style.display = 'none';
            document.getElementById('searchBtn').disabled = true;

            try {
                const params = {};
                if (player) params.player = player;
                if (map) params.map = map;
                if (squadron) params.squadron = squadron;
                if (dateFrom) params.time_from = Math.floor(new Date(dateFrom).getTime() / 1000);
                if (dateTo) params.time_to = Math.floor(new Date(dateTo + 'T23:59:59').getTime() / 1000);
                params.limit = 100;

                const data = await window.apiClient.searchGames(params);
                const matches = data.matches || [];

                document.getElementById('loadingState').style.display = 'none';
                document.getElementById('searchBtn').disabled = false;

                if (matches.length === 0) {
                    document.getElementById('emptyState').style.display = 'block';
                    return;
                }

                document.getElementById('resultsInfo').style.display = 'block';
                document.getElementById('resultsInfo').textContent = `${matches.length} ${matches.length === 1 ? 'match' : 'matches'} found`;

                document.getElementById('matchesList').innerHTML = matches.map(match => {
                    const mapName = match.map_name || 'Unknown Map';
                    const cleanMapName = mapName.replace(/^\s*\[[^\]]+\]\s*/, '').trim() || 'Unknown Map';
                    const mapImg = getMapImage(mapName);
                    const endTime = match.endtime_iso ? new Date(match.endtime_iso).toISOString().replace('T', ' ').substring(0, 16) + ' UTC' : '';

                    return `<a href="/games/${match.session_id}" class="match-card" style="${mapImg ? `--bg-img: url('${mapImg}')` : ''}">
                        <div class="match-card-inner">
                            <div style="display: flex; align-items: center; gap: 1rem;">
                                <div class="match-card-teams">
                                    <span class="match-card-winner">${escapeHtml(match.winning_tag || match.winning_squadron || '?')}</span>
                                    <span class="match-card-vs">VS</span>
                                    <span class="match-card-loser">${escapeHtml(match.losing_tag || match.losing_squadron || '?')}</span>
                                </div>
                            </div>
                            <div class="match-card-meta">
                                <span><i class="fas fa-map-marker-alt"></i>${escapeHtml(cleanMapName)}</span>
                                <span><i class="fas fa-clock"></i>${endTime}</span>
                            </div>
                        </div>
                    </a>`;
                }).join('');


            } catch (error) {
                console.error('Search failed:', error);
                document.getElementById('loadingState').style.display = 'none';
                document.getElementById('searchBtn').disabled = false;
                document.getElementById('emptyState').style.display = 'block';
            }
        }

        document.getElementById('gameIdInput').addEventListener('input', function() {
            this.style.borderColor = '';
        });
        document.getElementById('gameIdInput').addEventListener('keydown', function(e) {
            if (e.key === 'Enter') { e.preventDefault(); searchGames(); }
        });

        document.addEventListener('DOMContentLoaded', async () => {
            await Promise.all([loadMaps(), loadLeaderboardData()]);

            const params = new URLSearchParams(window.location.search);
            if (params.get('game_id')) {
                window.location.href = `/games/${params.get('game_id')}`;
                return;
            }
            if (params.get('player')) {
                document.getElementById('playerInput').value = params.get('player');
            }
            if (params.get('map')) {
                document.getElementById('mapSelect').value = params.get('map');
            }
            if (params.get('squadron')) {
                pickSquadron(params.get('squadron'));
            }
            if (params.get('from')) {
                document.getElementById('dateFrom').value = params.get('from');
            }
            if (params.get('to')) {
                document.getElementById('dateTo').value = params.get('to');
            }
            searchGames();
        });
    </script>
</body>
</html>
