'use strict';

/** Classificação composta exclusivamente por contas realmente criadas. */
(() => {
  const VERSION = 1;

  function calculatePower(profile, troopMeta = {}) {
    const buildingPower = Array.isArray(profile?.buildings)
      ? profile.buildings.reduce((sum, building) => sum + Math.max(0, Number(building?.level) || 0) * 55, 0)
      : 0;
    const troopPower = Object.entries(profile?.troops || {}).reduce((sum, [type, count]) => {
      return sum + Math.max(0, Number(count) || 0) * Math.max(0, Number(troopMeta[type]?.attack) || 0);
    }, 0);
    return Math.round(buildingPower + troopPower);
  }

  function entries(database, currentUserId, troopMeta = {}) {
    const users = Array.isArray(database?.users) ? database.users : [];
    const profiles = database?.profiles || {};
    return users
      .filter(user => user?.id && profiles[user.id])
      .map(user => {
        const profile = profiles[user.id];
        const power = calculatePower(profile, troopMeta);
        profile.power = power;
        return {
          id: user.id,
          name: user.username || 'Jogador',
          power,
          honor: Math.max(0, Math.floor(Number(profile.honor) || 0)),
          you: user.id === currentUserId,
          createdAt: Number(profile.createdAt) || Number(user.createdAt) || 0
        };
      })
      .sort((left, right) => right.power - left.power || right.honor - left.honor || left.createdAt - right.createdAt || left.name.localeCompare(right.name, 'pt'));
  }

  globalThis.ReinosRealRanking = Object.freeze({ VERSION, calculatePower, entries });
})();
