// source --> https://elanillounico.com/wp-content/plugins/juego-ajedrez-esdla/public/js/ajedrez-app.js?ver=0.6.14 
(function () {
    'use strict';

    const app = document.getElementById('eau-ajedrez-app');
    if (!app || !window.EAUAjedrez) return;

    const modalSelector = '[data-eau-modal]';
    let currentGame = null;
    let selectedSquare = null;
    let pendingPromotion = null;
    let toastTimer = null;
    const track = (event, params = {}) => {
        if (typeof window.eauTrack === 'function') window.eauTrack(event, Object.assign({game_name: 'ajedrez', game_slug: 'ajedrez'}, params));
    };

    function openModal(name) {
        const modal = document.querySelector(`[data-eau-modal="${name}"]`);
        if (!modal) return;
        modal.setAttribute('aria-hidden', 'false');
        document.documentElement.classList.add('eau-ajedrez-modal-open');
        const firstFocusable = modal.querySelector('button, input, select, textarea, [tabindex]:not([tabindex="-1"])');
        if (firstFocusable) firstFocusable.focus({preventScroll: true});
    }

    function closeModal(modal) {
        if (!modal) return;
        const name = modal.getAttribute('data-eau-modal');
        if (name === 'promotion' && pendingPromotion) return;
        if (name === 'game') {
            const dialog = modal.querySelector('.eau-ajedrez-game-dialog');
            if (dialog) dialog.classList.remove('is-board-expanded');
        }
        modal.setAttribute('aria-hidden', 'true');
        if (name === 'game') {
            const url = new URL(window.location.href);
            url.searchParams.delete('partida');
            window.history.replaceState({}, '', url.toString());
        }
        if (!document.querySelector(`${modalSelector}[aria-hidden="false"]`)) {
            document.documentElement.classList.remove('eau-ajedrez-modal-open');
        }
    }

    function setBoardExpanded(expanded) {
        const dialog = document.querySelector('[data-eau-modal="game"] .eau-ajedrez-game-dialog');
        if (!dialog) return;
        dialog.classList.toggle('is-board-expanded', !!expanded);
    }

    function statusLabel(game) {
        if (game.mate) return 'Jaque mate';
        if (game.tablas) return 'Tablas';
        if (game.jaque) return 'Jaque';
        return game.estado_label || 'En curso';
    }

    function statusClass(game) {
        if (game.mate) return 'is-mate';
        if (game.tablas) return 'is-draw';
        if (game.jaque) return 'is-check';
        return 'is-active';
    }

    function gameRow(game, mine) {
        const turnLabel = game.turno_name || (game.turno === game.jug1 ? game.jug1_name : game.jug2_name);
        const status = statusLabel(game);
        const mineClass = mine ? ' eau-ajedrez-game-row--mine' : '';
        const turnClass = game.can_move ? ' eau-ajedrez-turn--mine' : '';
        const actionLabel = game.is_player ? 'Abrir partida' : 'Ver partida';
        const badge = game.can_move ? '<span class="eau-ajedrez-badge eau-ajedrez-badge--turn">Tu turno</span>' : `<span class="eau-ajedrez-badge ${statusClass(game)}">${escapeHtml(status)}</span>`;
        const modeLabel = game.game_mode === 'ai' ? ` · ${escapeHtml(game.ai_difficulty_label || 'IA')}` : '';

        return `
            <article class="eau-ajedrez-game-row${mineClass}">
                <div>
                    <strong>Partida #${game.id}${modeLabel}</strong>
                    <span>Pueblos Libres: ${escapeHtml(game.jug1_name)}</span>
                    <span>Mordor: ${escapeHtml(game.jug2_name)}</span>
                </div>
                <div class="${turnClass}">Turno: ${escapeHtml(turnLabel)}</div>
                <div>${badge}</div>
                <button type="button" class="eau-ajedrez-button eau-ajedrez-button--small" data-eau-open-game="${game.id}">${actionLabel}</button>
            </article>
        `;
    }

    function escapeHtml(value) {
        return String(value == null ? '' : value).replace(/[&<>'"]/g, function (char) {
            return ({'&':'&amp;', '<':'&lt;', '>':'&gt;', "'":'&#039;', '"':'&quot;'})[char];
        });
    }

    async function api(path, options) {
        const headers = Object.assign({'X-WP-Nonce': EAUAjedrez.nonce}, (options && options.headers) || {});
        const response = await fetch(`${EAUAjedrez.restUrl}${path}`, Object.assign({
            credentials: 'same-origin',
            cache: 'no-store'
        }, options || {}, {headers}));
        const payload = await response.json().catch(function () { return {}; });
        if (!response.ok) {
            throw new Error(payload.message || 'Error al procesar la petición.');
        }
        return payload;
    }

    async function refreshSession() {
        const response = await fetch(`${EAUAjedrez.restUrl}/bootstrap`, {
            credentials: 'same-origin',
            cache: 'no-store'
        });
        const payload = await response.json().catch(function () { return {}; });
        if (!response.ok) return;
        if (payload.nonce) EAUAjedrez.nonce = payload.nonce;
        EAUAjedrez.currentUserId = payload.currentUserId || 0;
        EAUAjedrez.isLoggedIn = !!payload.isLoggedIn;
    }

    function showToast(message, tone) {
        const toast = document.getElementById('eau-ajedrez-toast');
        if (!toast || !message) return;
        toast.textContent = message;
        toast.className = `eau-ajedrez-toast is-visible ${tone ? 'is-' + tone : ''}`;
        window.clearTimeout(toastTimer);
        toastTimer = window.setTimeout(function () {
            toast.classList.remove('is-visible');
        }, 4200);
    }

    function setLoading(container, label) {
        if (container) container.innerHTML = `<p class="eau-ajedrez-loading">${escapeHtml(label || 'Cargando...')}</p>`;
    }

    async function loadGames() {
        const myContainer = document.getElementById('eau-ajedrez-my-games');
        const publicContainer = document.getElementById('eau-ajedrez-public-games');
        setLoading(myContainer, 'Cargando tus partidas...');
        setLoading(publicContainer, 'Cargando partidas públicas...');
        try {
            const data = await api('/games');
            myContainer.innerHTML = data.mine && data.mine.length
                ? data.mine.map(game => gameRow(game, true)).join('')
                : '<p>No tienes partidas activas.</p>';
            publicContainer.innerHTML = data.public && data.public.length
                ? data.public.map(game => gameRow(game, false)).join('')
                : '<p>No hay partidas públicas en curso.</p>';
        } catch (error) {
            myContainer.innerHTML = `<p>${escapeHtml(error.message)}</p>`;
            publicContainer.innerHTML = '';
            showToast(error.message, 'error');
        }
    }

    async function openGame(gameId) {
        currentGame = await api(`/games/${encodeURIComponent(gameId)}`);
        selectedSquare = null;
        document.getElementById('eau-ajedrez-game-title').textContent = `Partida #${currentGame.id}`;
        document.getElementById('eau-ajedrez-game-meta').textContent = `Pueblos Libres: ${currentGame.jug1_name} · Mordor: ${currentGame.jug2_name}`;
        document.getElementById('eau-ajedrez-board-orientation').textContent = orientationLabel(currentGame);
        renderAlert(currentGame, null);
        renderStatus(currentGame);
        renderBoard(currentGame);
        renderLastMove(currentGame);
        renderCaptured(currentGame);
        renderLog(currentGame);
        updateSelectedPiece(null);
        openModal('game');
        const url = new URL(window.location.href);
        url.searchParams.set('partida', currentGame.id);
        window.history.replaceState({}, '', url.toString());
        track('game_open', {mode: currentGame.game_mode || 'unknown', result: currentGame.mate ? 'win' : currentGame.tablas ? 'draw' : 'active'});
    }

    function renderAlert(game, message) {
        const alert = document.getElementById('eau-ajedrez-game-alert');
        if (!alert) return;
        let text = message || '';
        let tone = 'info';
        if (!text && game) {
            if (game.mate) {
                text = 'Jaque mate. La partida ha finalizado.';
                tone = 'mate';
            } else if (game.jaque) {
                text = 'Jaque. El rey amenazado debe responder.';
                tone = 'check';
            } else if (game.can_move) {
                text = 'Es tu turno. Selecciona una pieza y después una casilla de destino.';
                tone = 'turn';
            } else if (game.is_player) {
                text = 'La partida está en modo lectura hasta que vuelva tu turno.';
            } else {
                text = 'Modo espectador. Puedes observar la partida sin intervenir.';
            }
        }
        alert.className = `eau-ajedrez-game-alert is-${tone}`;
        alert.textContent = text;
    }

    function renderStatus(game) {
        const panel = document.getElementById('eau-ajedrez-game-status');
        const access = accessLabel(game);
        const status = statusLabel(game);
        const counts = game.counts || {white: {active: 16, captured: 0}, black: {active: 16, captured: 0}};
        panel.innerHTML = `
            <div class="eau-ajedrez-status-card ${statusClass(game)}">
                <span class="eau-ajedrez-status-card__label">Estado</span>
                <strong>${escapeHtml(status)}</strong>
            </div>
            <p><strong>Turno:</strong> ${escapeHtml(game.turno_name)}</p>
            <p><strong>Última actividad:</strong> ${escapeHtml(game.fecha_label || 'Sin fecha')}</p>
            <p><strong>Acceso:</strong> ${escapeHtml(access)}</p>
            <p><strong>Piezas activas:</strong> Pueblos Libres ${counts.white.active}/16 · Mordor ${counts.black.active}/16</p>
            <div class="eau-ajedrez-share">
                <button type="button" class="eau-ajedrez-button eau-ajedrez-button--small" data-eau-copy-link>Copiar enlace</button>
                ${game.is_player && !game.mate && !game.tablas && Number(game.estado) === 1 ? '<button type="button" class="eau-ajedrez-button eau-ajedrez-button--small eau-ajedrez-button--danger" data-eau-resign>Abandonar partida</button>' : ''}
            </div>
        `;
    }

    function accessLabel(game) {
        if (!game.is_player) return 'Espectador público.';
        if (game.can_move) return 'Jugador: es tu turno.';
        return 'Jugador: no es tu turno.';
    }

    function orientationLabel(game) {
        if (game.orientation === 'black') return 'Orientación: Mordor abajo';
        if (game.viewer_role === 'spectator') return 'Orientación: pública, Pueblos Libres abajo';
        return 'Orientación: Pueblos Libres abajo';
    }

    function renderBoard(game) {
        const board = document.getElementById('eau-ajedrez-board');
        if (!board) return;
        const boardMap = game.board || {};
        const squares = Array.isArray(game.squares) && game.squares.length === 64 ? game.squares : defaultSquares(game.orientation);
        const last = game.last_move || {};
        const selectedPiece = selectedSquare ? boardMap[String(selectedSquare)] : null;
        let html = '';

        board.className = `eau-ajedrez-board eau-ajedrez-board--${game.orientation === 'black' ? 'black' : 'white'} ${game.can_move ? 'can-move' : 'is-readonly'}`;

        squares.forEach(function (square) {
            const row = Math.floor((square - 1) / 8);
            const col = (square - 1) % 8;
            const dark = (row + col) % 2 === 1;
            const piece = boardMap[String(square)];
            const label = squareToAlgebraic(square);
            const isOwnTurnPiece = canSelectPiece(game, piece);
            const isLastFrom = Number(last.from) === Number(square);
            const isLastTo = Number(last.to) === Number(square);
            const isOwnOccupiedTarget = selectedPiece && piece && piece.side === selectedPiece.side && selectedSquare !== square;
            const isTarget = selectedSquare && selectedSquare !== square && game.can_move && !isOwnOccupiedTarget;
            const squareClasses = [
                'eau-ajedrez-square',
                dark ? 'is-dark' : 'is-light',
                isOwnTurnPiece ? 'is-selectable' : '',
                isLastFrom ? 'is-last-from' : '',
                isLastTo ? 'is-last-to' : '',
                selectedSquare === square ? 'is-selected' : '',
                isTarget ? 'is-move-target' : '',
                piece && piece.type === 'king' && game.checked_side && piece.side === game.checked_side ? 'is-king-in-check' : ''
            ].filter(Boolean).join(' ');
            const aria = `${label}${piece ? ', ' + piece.character + ' - ' + piece.label : ', casilla vacía'}`;
            html += `<button type="button" class="${squareClasses}" data-square="${square}" aria-label="${escapeHtml(aria)}">`;
            html += `<span class="eau-ajedrez-square-label">${label}</span>`;
            if (piece) {
                html += `<img class="eau-ajedrez-piece eau-ajedrez-piece--${escapeHtml(piece.side)}" src="${EAUAjedrez.imagesUrl}${escapeHtml(piece.image)}" alt="${escapeHtml(piece.character + ' - ' + piece.label)}" title="${escapeHtml(piece.character + ' - ' + piece.label)}">`;
            }
            html += `</button>`;
        });
        board.innerHTML = html;
    }

    function defaultSquares(orientation) {
        const squares = Array.from({length: 64}, (_, index) => index + 1);
        return orientation === 'black' ? squares.reverse() : squares;
    }

    function canSelectPiece(game, piece) {
        if (!piece || !game || !game.can_move) return false;
        return piece.side === game.viewer_role;
    }

    function renderLastMove(game) {
        const container = document.getElementById('eau-ajedrez-last-move');
        if (!container) return;
        const last = game.last_move || {};
        if (!last.piece_id || !last.from || !last.to) {
            container.textContent = 'Sin movimientos registrados.';
            return;
        }
        const piece = (game.pieces || []).find(item => Number(item.id) === Number(last.piece_id));
        const captured = last.captured_id ? (game.pieces || []).find(item => Number(item.id) === Number(last.captured_id)) : null;
        container.innerHTML = `
            <p><strong>${piece ? escapeHtml(piece.character + ' - ' + piece.label) : 'Pieza #' + escapeHtml(last.piece_id)}</strong></p>
            <p>${escapeHtml(last.from_label)} → ${escapeHtml(last.to_label)}</p>
            ${captured ? `<p>Captura: ${escapeHtml(captured.character + ' - ' + captured.label)}</p>` : ''}
        `;
    }

    function renderCaptured(game) {
        const container = document.getElementById('eau-ajedrez-captured');
        if (!container) return;
        const captured = game.captured || {white: [], black: []};
        container.innerHTML = `
            <div>
                <h4>Capturados de Pueblos Libres</h4>
                ${capturedGroup(captured.white)}
            </div>
            <div>
                <h4>Capturados de Mordor</h4>
                ${capturedGroup(captured.black)}
            </div>
        `;
    }

    function capturedGroup(items) {
        if (!items || !items.length) return '<p>Ninguna pieza capturada.</p>';
        return `<div class="eau-ajedrez-captured-list">${items.map(function (piece) {
            return `<img src="${EAUAjedrez.imagesUrl}${escapeHtml(piece.image)}" alt="${escapeHtml(piece.character + ' - ' + piece.label)}" title="${escapeHtml(piece.character + ' - ' + piece.label)}">`;
        }).join('')}</div>`;
    }

    function updateSelectedPiece(piece) {
        const box = document.getElementById('eau-ajedrez-selected-piece');
        if (!box) return;
        if (!piece) {
            box.textContent = currentGame && currentGame.can_move
                ? 'Selecciona una pieza propia.'
                : 'Tablero en modo lectura.';
            return;
        }
        box.innerHTML = `<strong>${escapeHtml(piece.character)}:</strong> ${escapeHtml(piece.label)} en ${escapeHtml(piece.algebraic || '')}. ${currentGame && currentGame.can_move && piece.side === currentGame.viewer_role ? 'Ahora selecciona destino.' : ''}`;
    }

    function renderLog(game) {
        const container = document.getElementById('eau-ajedrez-game-log');
        if (!container) return;
        if (!game.logs || !game.logs.length) {
            container.innerHTML = '<p>Sin registros todavía.</p>';
            return;
        }
        container.innerHTML = game.logs.map(function (log) {
            return `<div class="eau-ajedrez-log-entry">${log.html}</div>`;
        }).join('');
        container.scrollTop = 0;
    }

    function squareToAlgebraic(square) {
        const file = (square - 1) % 8;
        const rank = 8 - Math.floor((square - 1) / 8);
        return String.fromCharCode(65 + file) + rank;
    }

    function isPromotionMove(piece, toSquare) {
        if (!piece || piece.type !== 'pawn') return false;
        const row = Math.floor((toSquare - 1) / 8);
        return (piece.side === 'white' && row === 0) || (piece.side === 'black' && row === 7);
    }

    function choosePromotion(piece, toSquare) {
        if (!isPromotionMove(piece, toSquare)) return Promise.resolve('queen');
        return new Promise(function (resolve) {
            pendingPromotion = resolve;
            const pieceBox = document.getElementById('eau-ajedrez-promotion-piece');
            if (pieceBox) {
                pieceBox.textContent = `${piece.character} llega a ${squareToAlgebraic(toSquare)}. Elige nueva pieza.`;
            }
            openModal('promotion');
        });
    }

    function resolvePromotion(value) {
        if (!pendingPromotion) return;
        const resolve = pendingPromotion;
        pendingPromotion = null;
        closeModal(document.querySelector('[data-eau-modal="promotion"]'));
        resolve(value || 'queen');
    }

    async function attemptMove(toSquare) {
        if (!currentGame || !currentGame.can_move || !selectedSquare) return;
        const fromSquare = selectedSquare;
        const piece = currentGame.board ? currentGame.board[String(fromSquare)] : null;
        if (!piece || piece.side !== currentGame.viewer_role) {
            selectedSquare = null;
            renderBoard(currentGame);
            updateSelectedPiece(null);
            return;
        }

        const promotion = await choosePromotion(piece, toSquare);
        const box = document.getElementById('eau-ajedrez-selected-piece');
        if (box) box.textContent = 'Validando movimiento...';
        try {
            const data = await api(`/games/${encodeURIComponent(currentGame.id)}/move`, {
                method: 'POST',
                headers: {'Content-Type': 'application/json'},
                body: JSON.stringify({from: fromSquare, to: toSquare, promotion: promotion})
            });
            currentGame = data.game;
            selectedSquare = null;
            document.getElementById('eau-ajedrez-game-meta').textContent = `Pueblos Libres: ${currentGame.jug1_name} · Mordor: ${currentGame.jug2_name}`;
            renderAlert(currentGame, data.message);
            renderStatus(currentGame);
            renderBoard(currentGame);
            renderLastMove(currentGame);
            renderCaptured(currentGame);
            renderLog(currentGame);
            updateSelectedPiece(null);
            await loadGames();
            showToast(data.message || 'Movimiento realizado.', data.move && data.move.checkmate ? 'mate' : (data.move && data.move.draw ? 'draw' : (data.move && data.move.check ? 'check' : 'success')));
            if (data.move && (data.move.checkmate || data.move.draw)) {
                track('game_finish', {result: data.move.checkmate ? 'win' : 'draw', mode: currentGame.game_mode || 'unknown'});
            }
        } catch (error) {
            if (box) box.textContent = error.message;
            renderAlert(currentGame, error.message);
            showToast(error.message, 'error');
        }
    }

    async function submitNewGame(form) {
        const message = form.querySelector('[data-eau-new-game-message]');
        const button = form.querySelector('button[type="submit"]');
        const formData = new FormData(form);
        const payload = {
            mode: String(formData.get('mode') || 'ai'),
            opponent_login: String(formData.get('opponent_login') || '').trim(),
            side: String(formData.get('side') || 'white'),
            ai_difficulty: String(formData.get('ai_difficulty') || 'basic')
        };

        if (payload.mode === 'human' && !payload.opponent_login) {
            message.textContent = 'Introduce el nombre de usuario del rival.';
            return;
        }

        button.disabled = true;
        message.textContent = 'Creando partida...';

        try {
            const data = await api('/games', {
                method: 'POST',
                headers: {'Content-Type': 'application/json'},
                body: JSON.stringify(payload)
            });
            message.textContent = data.message || 'Partida creada.';
            track('game_start', {mode: payload.mode, difficulty: payload.mode === 'ai' ? payload.ai_difficulty : 'human'});
            await loadGames();
            closeModal(form.closest(modalSelector));
            if (data.game && data.game.id) {
                await openGame(data.game.id);
            }
            form.reset();
            showToast('Partida creada correctamente.', 'success');
        } catch (error) {
            message.textContent = error.message;
            showToast(error.message, 'error');
        } finally {
            button.disabled = false;
        }
    }

    function syncNewGameMode(form) {
        const mode = String((new FormData(form)).get('mode') || 'ai');
        const human = form.querySelector('[data-eau-human-opponent]');
        const ai = form.querySelector('[data-eau-ai-options]');
        const opponent = form.querySelector('input[name="opponent_login"]');
        if (human) human.hidden = mode !== 'human';
        if (ai) ai.hidden = mode !== 'ai';
        if (opponent) opponent.required = mode === 'human';
    }

    async function copyGameLink() {
        if (!currentGame) return;
        const url = new URL(window.location.href);
        url.searchParams.set('partida', currentGame.id);
        try {
            await navigator.clipboard.writeText(url.toString());
            showToast('Enlace de la partida copiado.', 'success');
        } catch (error) {
            window.prompt('Copia el enlace de la partida:', url.toString());
        }
    }


    async function resignCurrentGame() {
        if (!currentGame || !currentGame.is_player || currentGame.mate || currentGame.tablas || Number(currentGame.estado) !== 1) return;
        const ok = window.confirm('¿Quieres abandonar esta partida? Se dará la victoria al rival.');
        if (!ok) return;
        try {
            const data = await api(`/games/${encodeURIComponent(currentGame.id)}/resign`, {method: 'POST'});
            currentGame = data.game;
            renderAlert(currentGame, data.message);
            renderStatus(currentGame);
            renderBoard(currentGame);
            renderLastMove(currentGame);
            renderCaptured(currentGame);
            renderLog(currentGame);
            await loadGames();
            showToast(data.message || 'Partida finalizada.', 'success');
            track('game_finish', {result: 'abandoned', mode: currentGame.game_mode || 'unknown'});
        } catch (error) {
            renderAlert(currentGame, error.message);
            showToast(error.message, 'error');
        }
    }

    document.addEventListener('click', function (event) {
        const promotionButton = event.target.closest('[data-eau-promotion]');
        if (promotionButton) {
            resolvePromotion(promotionButton.getAttribute('data-eau-promotion'));
            return;
        }

        const copyButton = event.target.closest('[data-eau-copy-link]');
        if (copyButton) {
            copyGameLink();
            return;
        }

        const expandBoardButton = event.target.closest('[data-eau-expand-board]');
        if (expandBoardButton) {
            setBoardExpanded(true);
            return;
        }

        const collapseBoardButton = event.target.closest('[data-eau-collapse-board]');
        if (collapseBoardButton) {
            setBoardExpanded(false);
            return;
        }

        const resignButton = event.target.closest('[data-eau-resign]');
        if (resignButton) {
            resignCurrentGame();
            return;
        }

        const openButton = event.target.closest('[data-eau-modal-open]');
        if (openButton) {
            openModal(openButton.getAttribute('data-eau-modal-open'));
            return;
        }

        const closeButton = event.target.closest('[data-eau-modal-close]');
        if (closeButton) {
            closeModal(closeButton.closest(modalSelector));
            return;
        }

        const gameButton = event.target.closest('[data-eau-open-game]');
        if (gameButton) {
            openGame(gameButton.getAttribute('data-eau-open-game')).catch(function (error) {
                showToast(error.message, 'error');
            });
            return;
        }

        const squareButton = event.target.closest('[data-square]');
        if (squareButton && currentGame) {
            const square = Number(squareButton.getAttribute('data-square'));
            const piece = currentGame.board ? currentGame.board[String(square)] : null;
            const ownPiece = piece && currentGame.can_move && piece.side === currentGame.viewer_role;

            if (!currentGame.can_move) {
                updateSelectedPiece(piece || null);
                return;
            }

            if (ownPiece) {
                selectedSquare = square;
                renderBoard(currentGame);
                updateSelectedPiece(piece);
                return;
            }

            if (selectedSquare) {
                attemptMove(square);
                return;
            }

            updateSelectedPiece(piece || null);
        }
    });

    document.addEventListener('submit', function (event) {
        const form = event.target.closest('[data-eau-new-game-form]');
        if (!form) return;
        event.preventDefault();
        submitNewGame(form);
    });

    document.addEventListener('change', function (event) {
        const input = event.target.closest('input[name="mode"]');
        if (!input) return;
        const form = input.closest('[data-eau-new-game-form]');
        if (form) syncNewGameMode(form);
    });

    document.addEventListener('keydown', function (event) {
        if (event.key === 'Escape') {
            if (pendingPromotion) return;
            document.querySelectorAll(`${modalSelector}[aria-hidden="false"]`).forEach(closeModal);
        }
    });

    document.querySelectorAll('[data-eau-new-game-form]').forEach(syncNewGameMode);

    refreshSession().catch(function () {}).then(loadGames).then(function () {
        const params = new URLSearchParams(window.location.search);
        const gameId = params.get('partida');
        if (gameId) {
            openGame(gameId).catch(function (error) {
                showToast(error.message, 'error');
            });
        }
    });
})();