// La Charocracia - UI de Ranking Online (modales). IDs prefijados con "online-" para
// evitar colisión con el ranking in-game (#ranking-list, js/ui/ranking.js).

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

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

    const btnStart = document.getElementById('btn-online-ranking-start');
    if (btnStart) btnStart.addEventListener('click', () => mostrarRankingOnline({ from: 'start' }));
    const btnPausa = document.getElementById('btn-online-ranking-pausa');
    if (btnPausa) {
        btnPausa.addEventListener('click', () => {
            if (typeof toggleHelp === 'function') {
                const overlay = document.getElementById('help-overlay');
                if (overlay && overlay.style.display === 'flex') overlay.style.display = 'none';
            }
            mostrarRankingOnline({ from: 'pausa' });
        });
    }
    const btnCerrar = document.getElementById('btn-online-ranking-cerrar');
    if (btnCerrar) btnCerrar.addEventListener('click', cerrarRankingOnlineModal);
    const btnCambiar = document.getElementById('btn-online-ranking-cambiar-nick');
    if (btnCambiar) {
        btnCambiar.addEventListener('click', () => {
            cerrarRankingOnlineModal();
            pedirOnlineNickname({ next: () => mostrarRankingOnline({ from: 'nickname' }) });
        });
    }
    const btnGuardar = document.getElementById('btn-online-nickname-guardar');
    if (btnGuardar) btnGuardar.addEventListener('click', _confirmarOnlineNickname);
    const btnCancelar = document.getElementById('btn-online-nickname-cancelar');
    if (btnCancelar) btnCancelar.addEventListener('click', cerrarOnlineNicknameModal);
    if (onlineRankingUiCtx.nicknameInput) {
        onlineRankingUiCtx.nicknameInput.addEventListener('keydown', (e) => {
            if (e.key === 'Enter') { e.preventDefault(); _confirmarOnlineNickname(); }
        });
    }
}

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 _formatScoreCharocracia(votos) {
    const v = Number(votos || 0);
    if (v >= 1_000_000) return (v / 1_000_000).toFixed(2) + 'M votos';
    if (v >= 1_000) return (v / 1_000).toFixed(1) + 'k votos';
    return v.toLocaleString('es-ES') + ' votos';
}

function pedirOnlineNickname({ next, prefill } = {}) {
    if (!onlineRankingUiCtx.nicknameModal || !onlineRankingUiCtx.nicknameInput) return;
    onlineRankingUiCtx.nicknamePending = next || null;
    onlineRankingUiCtx.nicknameInput.value = prefill || (typeof getOnlineNickname === 'function' ? (getOnlineNickname() || '') : '');
    if (onlineRankingUiCtx.nicknameError) {
        onlineRankingUiCtx.nicknameError.hidden = true;
        onlineRankingUiCtx.nicknameError.textContent = '';
    }
    onlineRankingUiCtx.nicknameModal.style.display = 'flex';
    setTimeout(() => { try { onlineRankingUiCtx.nicknameInput.focus(); } catch (e) {} }, 50);
}

function cerrarOnlineNicknameModal() {
    if (onlineRankingUiCtx.nicknameModal) onlineRankingUiCtx.nicknameModal.style.display = 'none';
    onlineRankingUiCtx.nicknamePending = null;
}

function _confirmarOnlineNickname() {
    if (typeof setOnlineNickname !== 'function' || !onlineRankingUiCtx.nicknameInput) return;
    const value = onlineRankingUiCtx.nicknameInput.value;
    const saved = setOnlineNickname(value);
    if (!saved) {
        if (onlineRankingUiCtx.nicknameError) {
            onlineRankingUiCtx.nicknameError.textContent = 'Nick inválido (2–16 caracteres, sin símbolos raros).';
            onlineRankingUiCtx.nicknameError.hidden = false;
        }
        return;
    }
    if (onlineRankingUiCtx.nicknameModal) onlineRankingUiCtx.nicknameModal.style.display = 'none';
    const next = onlineRankingUiCtx.nicknamePending;
    onlineRankingUiCtx.nicknamePending = null;
    if (typeof next === 'function') next();
}

function mostrarRankingOnline({ from } = {}) {
    if (!onlineRankingUiCtx.rankingModal) return;
    const nick = (typeof getOnlineNickname === 'function') ? getOnlineNickname() : null;
    if (onlineRankingUiCtx.rankingNickInfo) {
        onlineRankingUiCtx.rankingNickInfo.textContent = nick
            ? 'Compites como ' + nick
            : 'Sin nick — guarda uno para aparecer en el ranking.';
    }
    if (onlineRankingUiCtx.rankingList) {
        onlineRankingUiCtx.rankingList.innerHTML = '<p class="online-ranking-loading">Cargando...</p>';
    }
    onlineRankingUiCtx.rankingModal.style.display = 'flex';
    if (typeof fetchOnlineTop !== 'function') {
        if (onlineRankingUiCtx.rankingList) {
            onlineRankingUiCtx.rankingList.innerHTML = '<p class="online-ranking-error">Ranking no disponible.</p>';
        }
        return;
    }
    fetchOnlineTop(20).then((res) => {
        if (!onlineRankingUiCtx.rankingList) return;
        if (!res.ok) {
            onlineRankingUiCtx.rankingList.innerHTML = '<p class="online-ranking-error">No se pudo cargar el ranking.</p>';
            return;
        }
        const top = (res.data && res.data.top) || [];
        if (top.length === 0) {
            onlineRankingUiCtx.rankingList.innerHTML = '<p class="online-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 = ['online-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="online-ranking-rank">#' + r.rank + '</span>'
                + '<span class="online-ranking-nick">' + safeNick + '</span>'
                + '<span class="online-ranking-score">' + _formatScoreCharocracia(r.maxLevel) + '</span>'
                + '<span class="online-ranking-time">' + _formatTiempoRanking(r.totalTimeMs) + '</span>'
                + '</div>';
        }).join('');
        onlineRankingUiCtx.rankingList.innerHTML = rows;
    });
}

function cerrarRankingOnlineModal() {
    if (onlineRankingUiCtx.rankingModal) onlineRankingUiCtx.rankingModal.style.display = 'none';
}

function enviarPuntuacionAlRanking(score) {
    if (typeof submitOnlineScore !== '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 = getOnlineNickname();
    if (nick) {
        submitOnlineScore(payload).then(() => mostrarRankingOnline({ from: 'gameover' })).catch(() => {});
    } else {
        pedirOnlineNickname({
            next: () => {
                submitOnlineScore(payload).then(() => mostrarRankingOnline({ from: 'gameover' })).catch(() => {});
            }
        });
    }
}

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