// Boomermania - UI de Ranking Online (modales + flujos)

const rankingUiCtx = {
    rankingModal: null,
    rankingList: null,
    rankingNickInfo: null,
    nicknameModal: null,
    nicknameInput: null,
    nicknameError: null,
    nicknamePending: null
};

function initRankingUi() {
    rankingUiCtx.rankingModal = document.getElementById('ranking-modal');
    rankingUiCtx.rankingList = document.getElementById('ranking-list');
    rankingUiCtx.rankingNickInfo = document.getElementById('ranking-nick-info');
    rankingUiCtx.nicknameModal = document.getElementById('nickname-modal');
    rankingUiCtx.nicknameInput = document.getElementById('nickname-input');
    rankingUiCtx.nicknameError = document.getElementById('nickname-error');

    const btnRankingStart = document.getElementById('btn-ranking-start');
    if (btnRankingStart) {
        btnRankingStart.addEventListener('click', () => mostrarRankingOnline({ from: 'start' }));
    }
    const btnRankingPausa = document.getElementById('btn-ranking-pausa');
    if (btnRankingPausa) {
        btnRankingPausa.addEventListener('click', () => {
            if (typeof cerrarPausa === 'function') cerrarPausa();
            mostrarRankingOnline({ from: 'pausa' });
        });
    }
    const btnRankingCerrar = document.getElementById('btn-ranking-cerrar');
    if (btnRankingCerrar) {
        btnRankingCerrar.addEventListener('click', cerrarRankingModal);
    }
    const btnRankingCambiarNick = document.getElementById('btn-ranking-cambiar-nick');
    if (btnRankingCambiarNick) {
        btnRankingCambiarNick.addEventListener('click', () => {
            cerrarRankingModal();
            pedirNickname({ next: () => mostrarRankingOnline({ from: 'nickname' }) });
        });
    }
    const btnNicknameGuardar = document.getElementById('btn-nickname-guardar');
    if (btnNicknameGuardar) {
        btnNicknameGuardar.addEventListener('click', _confirmarNickname);
    }
    const btnNicknameCancelar = document.getElementById('btn-nickname-cancelar');
    if (btnNicknameCancelar) {
        btnNicknameCancelar.addEventListener('click', cerrarNicknameModal);
    }
    if (rankingUiCtx.nicknameInput) {
        rankingUiCtx.nicknameInput.addEventListener('keydown', (e) => {
            if (e.key === 'Enter') { e.preventDefault(); _confirmarNickname(); }
        });
    }
}

function _formatTiempoRanking(ms) {
    if (!Number.isFinite(ms)) return '--';
    const totalSec = Math.floor(ms / 1000);
    const h = Math.floor(totalSec / 3600);
    const m = Math.floor((totalSec % 3600) / 60);
    const s = totalSec % 60;
    if (h > 0) return h + 'h ' + String(m).padStart(2, '0') + 'm';
    return m + ':' + String(s).padStart(2, '0');
}

function _formatScoreBoomermania(score) {
    return Number(score || 0).toLocaleString() + ' pts';
}

function pedirNickname({ next, prefill } = {}) {
    if (!rankingUiCtx.nicknameModal || !rankingUiCtx.nicknameInput) return;
    rankingUiCtx.nicknamePending = next || null;
    rankingUiCtx.nicknameInput.value = prefill || (typeof getNickname === 'function' ? (getNickname() || '') : '');
    if (rankingUiCtx.nicknameError) {
        rankingUiCtx.nicknameError.hidden = true;
        rankingUiCtx.nicknameError.textContent = '';
    }
    rankingUiCtx.nicknameModal.classList.add('active');
    setTimeout(() => { try { rankingUiCtx.nicknameInput.focus(); } catch (e) {} }, 50);
}

function cerrarNicknameModal() {
    if (rankingUiCtx.nicknameModal) rankingUiCtx.nicknameModal.classList.remove('active');
    rankingUiCtx.nicknamePending = null;
}

function _confirmarNickname() {
    if (typeof setNickname !== 'function' || !rankingUiCtx.nicknameInput) return;
    const value = rankingUiCtx.nicknameInput.value;
    const saved = setNickname(value);
    if (!saved) {
        if (rankingUiCtx.nicknameError) {
            rankingUiCtx.nicknameError.textContent = 'Nick inválido (2–16 caracteres, sin símbolos raros).';
            rankingUiCtx.nicknameError.hidden = false;
        }
        return;
    }
    if (rankingUiCtx.nicknameModal) rankingUiCtx.nicknameModal.classList.remove('active');
    const next = rankingUiCtx.nicknamePending;
    rankingUiCtx.nicknamePending = null;
    if (typeof next === 'function') next();
}

function mostrarRankingOnline({ from } = {}) {
    if (!rankingUiCtx.rankingModal) return;
    const nick = (typeof getNickname === 'function') ? getNickname() : null;
    if (rankingUiCtx.rankingNickInfo) {
        rankingUiCtx.rankingNickInfo.textContent = nick
            ? 'Compites como ' + nick
            : 'Sin nick — guarda uno para aparecer en el ranking.';
    }
    if (rankingUiCtx.rankingList) {
        rankingUiCtx.rankingList.innerHTML = '<p class="ranking-loading">Cargando...</p>';
    }
    rankingUiCtx.rankingModal.classList.add('active');
    if (typeof fetchTop !== 'function') {
        if (rankingUiCtx.rankingList) {
            rankingUiCtx.rankingList.innerHTML = '<p class="ranking-error">Ranking no disponible.</p>';
        }
        return;
    }
    fetchTop(20).then((res) => {
        if (!rankingUiCtx.rankingList) return;
        if (!res.ok) {
            rankingUiCtx.rankingList.innerHTML = '<p class="ranking-error">No se pudo cargar el ranking.</p>';
            return;
        }
        const top = (res.data && res.data.top) || [];
        if (top.length === 0) {
            rankingUiCtx.rankingList.innerHTML = '<p class="ranking-empty">Aún no hay puntuaciones. ¡Sé el primero!</p>';
            return;
        }
        const myNickLower = nick ? nick.toLowerCase() : null;
        const rows = top.map((r) => {
            const isMe = myNickLower && r.nickname.toLowerCase() === myNickLower;
            const cls = ['ranking-row'];
            if (isMe) cls.push('is-me');
            if (r.rank === 1) cls.push('is-top1');
            else if (r.rank === 2) cls.push('is-top2');
            else if (r.rank === 3) cls.push('is-top3');
            const safeNick = String(r.nickname).replace(/[<>&"]/g, (c) => ({ '<':'&lt;', '>':'&gt;', '&':'&amp;', '"':'&quot;' }[c]));
            return '<div class="' + cls.join(' ') + '">'
                + '<span class="ranking-rank">#' + r.rank + '</span>'
                + '<span class="ranking-nick">' + safeNick + '</span>'
                + '<span class="ranking-score">' + _formatScoreBoomermania(r.maxLevel) + '</span>'
                + '<span class="ranking-time">' + _formatTiempoRanking(r.totalTimeMs) + '</span>'
                + '</div>';
        }).join('');
        rankingUiCtx.rankingList.innerHTML = rows;
    });
}

function cerrarRankingModal() {
    if (rankingUiCtx.rankingModal) rankingUiCtx.rankingModal.classList.remove('active');
}

// Llamar desde mostrarFinJuego() después de calcular puntuación.
// Si hay nick guardado: envía y abre el ranking automáticamente.
// Si no hay nick: pide uno y al confirmarlo envía + abre el ranking.
function enviarPuntuacionAlRanking(score) {
    if (typeof submitScore !== 'function') return;
    const startedAt = (typeof gameState !== 'undefined' && gameState && gameState.runStartedAt) || Date.now();
    const elapsed = Math.max(1000, Date.now() - startedAt);
    const totalTimeMs = Math.min(24 * 60 * 60 * 1000, elapsed);
    const payload = {
        maxLevel: Math.max(0, Math.floor(score || 0)),
        totalTimeMs
    };
    const nick = getNickname();
    if (nick) {
        submitScore(payload).then(() => mostrarRankingOnline({ from: 'gameover' })).catch(() => {});
    } else {
        pedirNickname({
            next: () => {
                submitScore(payload).then(() => mostrarRankingOnline({ from: 'gameover' })).catch(() => {});
            }
        });
    }
}

if (typeof document !== 'undefined') {
    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', initRankingUi);
    } else {
        initRankingUi();
    }
}
