// Papeles Para Todos - Cliente de Ranking Online

const RANKING_API = 'https://api.lacharocracia.com';
const RANKING_GAME = 'papelesparatodos';
const RANKING_NICK_KEY = 'papelesparatodos_nick';

const rankingCtx = {
    nickname: null,
    lastSubmit: null,
    lastTop: null
};

function getNickname() {
    if (rankingCtx.nickname) return rankingCtx.nickname;
    try {
        const v = localStorage.getItem(RANKING_NICK_KEY);
        if (v) rankingCtx.nickname = v;
    } catch (e) {}
    return rankingCtx.nickname;
}

function setNickname(nick) {
    if (!nick) return null;
    const cleaned = String(nick).trim().replace(/\s+/g, ' ');
    if (!/^[\p{L}\p{N} ._-]{2,16}$/u.test(cleaned)) return null;
    rankingCtx.nickname = cleaned;
    try { localStorage.setItem(RANKING_NICK_KEY, cleaned); } catch (e) {}
    return cleaned;
}

function clearNickname() {
    rankingCtx.nickname = null;
    try { localStorage.removeItem(RANKING_NICK_KEY); } catch (e) {}
}

async function submitScore({ maxLevel, totalTimeMs }) {
    const nickname = getNickname();
    if (!nickname) return { ok: false, error: 'no_nickname' };
    if (!Number.isFinite(maxLevel) || maxLevel < 0) return { ok: false, error: 'invalid_level' };
    if (!Number.isFinite(totalTimeMs) || totalTimeMs < 1000) return { ok: false, error: 'invalid_time' };
    try {
        const res = await fetch(RANKING_API + '/api/ranking', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({
                game: RANKING_GAME,
                nickname,
                maxLevel: Math.floor(maxLevel),
                totalTimeMs: Math.floor(totalTimeMs)
            })
        });
        const data = await res.json().catch(() => ({}));
        if (!res.ok) return { ok: false, error: data.error || 'http_' + res.status };
        rankingCtx.lastSubmit = data;
        return { ok: true, data };
    } catch (e) {
        return { ok: false, error: 'network' };
    }
}

async function fetchTop(limit = 20) {
    try {
        const url = RANKING_API + '/api/ranking?game=' + encodeURIComponent(RANKING_GAME) + '&limit=' + limit;
        const res = await fetch(url, { method: 'GET' });
        if (!res.ok) return { ok: false, error: 'http_' + res.status };
        const data = await res.json();
        rankingCtx.lastTop = data;
        return { ok: true, data };
    } catch (e) {
        return { ok: false, error: 'network' };
    }
}
