'use strict';

/**
 * Progressão modular dos Barões Falken.
 * Cada Barão guarda o próprio nível e o progresso de vitórias do jogador atual.
 */
(() => {
  const VERSION = 3;
  const MAX_LEVEL = 80;

  // Número de vitórias necessário para passar do nível indicado ao seguinte.
  // Valores reproduzidos da tabela comunitária publicada para os Robber Baron Castles.
  const VICTORIES_REQUIRED = Object.freeze([
    0,
    1, 1, 1, 1, 2, 2, 3, 3, 3, 3,
    4, 4, 4, 5, 5, 5, 5, 6, 6, 6,
    6, 7, 7, 7, 7, 8, 8, 8, 8, 9,
    9, 9, 9, 9, 10, 10, 10, 10, 11, 11,
    11, 11, 12, 11, 12, 12, 12, 13, 13, 13,
    13, 13, 14, 14, 14, 14, 14, 15, 15, 15,
    15, 15, 16, 16, 16, 16, 16, 17, 17, 17,
    17, 17, 18, 18, 18, 18, 18, 19, 18, 0
  ]);

  const safeInteger = (value, fallback = 0) => {
    const parsed = Number(value);
    return Number.isFinite(parsed) ? Math.max(0, Math.floor(parsed)) : fallback;
  };

  function normalizeLevel(level) {
    return Math.max(1, Math.min(MAX_LEVEL, safeInteger(level, 1)));
  }

  function victoriesNeeded(level) {
    const safeLevel = normalizeLevel(level);
    return safeLevel >= MAX_LEVEL ? 0 : (VICTORIES_REQUIRED[safeLevel] || 1);
  }

  function normalizeTarget(target, options = {}) {
    if (!target || typeof target !== 'object') return target;
    target.level = normalizeLevel(target.level);

    const legacyVictories = safeInteger(target.victories, Math.max(0, target.level - 1));
    target.totalVictories = safeInteger(target.totalVictories, legacyVictories);
    target.victories = target.totalVictories; // compatibilidade com versões anteriores

    const needed = victoriesNeeded(target.level);
    target.levelVictories = target.level >= MAX_LEVEL
      ? 0
      : Math.min(Math.max(0, needed - 1), safeInteger(target.levelVictories, 0));

    if (typeof options.strengthFn === 'function') target.strength = options.strengthFn(target.level);
    if (typeof options.lootFn === 'function') target.loot = options.lootFn(target.level);
    return target;
  }

  function progress(target) {
    const level = normalizeLevel(target?.level);
    const maxed = level >= MAX_LEVEL;
    const needed = victoriesNeeded(level);
    const current = maxed ? 0 : Math.min(Math.max(0, needed - 1), safeInteger(target?.levelVictories, 0));
    return {
      level,
      current,
      needed,
      remaining: maxed ? 0 : Math.max(0, needed - current),
      maxed,
      label: maxed ? `Nível ${MAX_LEVEL} • Máximo` : `Nível ${level} • ${current}/${needed} vitórias`
    };
  }

  function registerVictory(target, options = {}) {
    normalizeTarget(target, options);
    const previousLevel = target.level;
    target.totalVictories += 1;
    target.victories = target.totalVictories;

    if (target.level >= MAX_LEVEL) {
      return { previousLevel, level: target.level, leveledUp: false, maxed: true, ...progress(target) };
    }

    target.levelVictories += 1;
    const required = victoriesNeeded(target.level);
    let leveledUp = false;
    if (target.levelVictories >= required) {
      target.level = Math.min(MAX_LEVEL, target.level + 1);
      target.levelVictories = 0;
      leveledUp = true;
      if (typeof options.strengthFn === 'function') target.strength = options.strengthFn(target.level);
      if (typeof options.lootFn === 'function') target.loot = options.lootFn(target.level);
    }

    return { previousLevel, level: target.level, leveledUp, maxed: target.level >= MAX_LEVEL, ...progress(target) };
  }

  function compactLabel(target) {
    const info = progress(target);
    return info.maxed ? `Nv. ${info.level} • Máx.` : `Nv. ${info.level} • ${info.current}/${info.needed}`;
  }

  function victoryMessage(target, result) {
    const info = result || progress(target);
    if (info.maxed && !info.leveledUp) return `O Barão Falken permanece no nível máximo ${MAX_LEVEL}.`;
    if (info.leveledUp) return `O Barão Falken subiu para o nível ${info.level}.`;
    return `Progresso do Barão Falken: ${info.current}/${info.needed} vitórias no nível ${info.level}.`;
  }

  globalThis.ReinosFalkenProgression = Object.freeze({
    VERSION,
    MAX_LEVEL,
    VICTORIES_REQUIRED,
    normalizeLevel,
    victoriesNeeded,
    normalizeTarget,
    progress,
    registerVictory,
    compactLabel,
    victoryMessage
  });
})();
