import { useEffect, useState } from 'react';
import { useReveal, getBootstrap } from './atoms.jsx';

export default function Realm() {
    const seed = (getBootstrap().realm) || {};
    const ref = useReveal();

    const isOnline = seed.online !== false;
    const realPlayers = typeof seed.players === 'number' ? seed.players : null;

    // Лёгкий "живой" дрейф пинга, чтобы число не было статичным.
    const [ping, setPing] = useState(seed.ping ?? 38);
    useEffect(() => {
        if (!isOnline) return;
        const t = setInterval(() => {
            setPing((v) => Math.max(20, Math.min(80, v + Math.round((Math.random() - 0.5) * 6))));
        }, 2200);
        return () => clearInterval(t);
    }, [isOnline]);

    const name = seed.name || "Elune's Grace";
    const mode = seed.mode || 'PvE · x1 rate · RU';
    const uptime = seed.uptime || '99.94%';
    const factions = seed.factions || { alliance: 50, horde: 50 };

    return (
        <div className="wrap realm reveal" ref={ref}>
            <div className="realm-panel">
                <div className="realm-status">
                    <span className="orb"></span>
                    <span className="label">{isOnline ? 'Онлайн' : 'Оффлайн'}</span>
                </div>
                <div className="realm-name">
                    {name}
                    <small>{mode}</small>
                </div>
                <div className="realm-stat">
                    <span className="k">Игроков</span>
                    <span className="v">
                        {realPlayers !== null ? realPlayers.toLocaleString('ru-RU') : '—'}
                    </span>
                </div>
                <div className="realm-stat">
                    <span className="k">Аптайм</span>
                    <span className="v small">{uptime}</span>
                </div>
                <div className="realm-stat">
                    <span className="k">Пинг</span>
                    <span className="v small">{isOnline ? `${ping} ms` : '—'}</span>
                </div>
                <div className="realm-stat">
                    <span className="k">Фракции</span>
                    <span className="v small">{factions.alliance} / {factions.horde}</span>
                </div>
            </div>
        </div>
    );
}
