// La Charocracia - Cliente de Ranking Online

const ONLINE_RANKING_API = 'https://api.lacharocracia.com';
const ONLINE_RANKING_GAME = 'charocracia';
const ONLINE_RANKING_NICK_KEY = 'charocracia_nick';

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

function getOnlineNickname() {
    if (onlineRankingCtx.nickname) return onlineRankingCtx.nickname;
    try {
        const v = localStorage.getItem(ONLINE_RANKING_NICK_KEY);
        if (v) onlineRankingCtx.nickname = v;
    } catch (e) {}
    return onlineRankingCtx.nickname;
}

function setOnlineNickname(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;
    onlineRankingCtx.nickname = cleaned;
    try { localStorage.setItem(ONLINE_RANKING_NICK_KEY, cleaned); } catch (e) {}
    return cleaned;
}

async function submitOnlineScore({ maxLevel, totalTimeMs }) {
    const nickname = getOnlineNickname();
    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(ONLINE_RANKING_API + '/api/ranking', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({
                game: ONLINE_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 };
        onlineRankingCtx.lastSubmit = data;
        return { ok: true, data };
    } catch (e) {
        return { ok: false, error: 'network' };
    }
}

async function fetchOnlineTop(limit = 20) {
    try {
        const url = ONLINE_RANKING_API + '/api/ranking?game=' + encodeURIComponent(ONLINE_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();
        onlineRankingCtx.lastTop = data;
        return { ok: true, data };
    } catch (e) {
        return { ok: false, error: 'network' };
    }
}
