'use strict';

/**
 * Mensagens detalhadas de recursos insuficientes.
 *
 * Este módulo apenas calcula e apresenta o recurso em falta. Não altera os
 * saldos, preços, filas de construção, recrutamento, oficina ou expansões.
 */
(() => {
  const FAILURE_TTL_MS = 1200;
  const LABELS = Object.freeze({
    wood: 'Madeira',
    stone: 'Pedra',
    food: 'Comida',
    coins: 'Moedas',
    gems: 'Coroas'
  });

  let lastFailure = null;

  function number(value) {
    const parsed = Number(value);
    return Number.isFinite(parsed) ? parsed : 0;
  }

  function format(value) {
    return Math.max(0, Math.floor(number(value))).toLocaleString('pt-PT');
  }

  function inspect(resources, cost) {
    const balances = resources && typeof resources === 'object' ? resources : {};
    const prices = cost && typeof cost === 'object' ? cost : {};

    return Object.entries(prices)
      .map(([type, rawRequired]) => {
        const required = Math.max(0, number(rawRequired));
        const current = Math.max(0, number(balances[type]));
        const missing = Math.max(0, required - current);
        return {
          type,
          label: LABELS[type] || type,
          current,
          required,
          missing
        };
      })
      .filter(item => item.missing > 0.000001);
  }

  function remember(resources, cost) {
    const missing = inspect(resources, cost);
    lastFailure = missing.length ? { at: Date.now(), missing } : null;
    return missing;
  }

  function canAfford(resources, cost) {
    return remember(resources, cost).length === 0;
  }

  function isGenericInsufficientMessage(message) {
    const text = String(message || '').toLocaleLowerCase('pt-PT');
    return text.includes('recursos suficientes')
      || text.includes('coroas suficientes')
      || text.includes('madeira e pedra suficientes')
      || text.includes('moedas suficientes')
      || text.includes('saldo insuficiente');
  }

  function consumeToast(message, type) {
    if (type !== 'error' || !lastFailure || !isGenericInsufficientMessage(message)) return null;
    if (Date.now() - lastFailure.at > FAILURE_TTL_MS) {
      lastFailure = null;
      return null;
    }

    const failure = lastFailure;
    lastFailure = null;
    const lines = failure.missing.map(item => {
      const current = format(item.current);
      const required = Math.ceil(item.required).toLocaleString('pt-PT');
      const missing = Math.ceil(item.missing).toLocaleString('pt-PT');
      return `${item.label}: tens ${current}, precisas de ${required} — faltam ${missing}`;
    });

    return {
      message: `Recursos insuficientes:\n${lines.join('\n')}`,
      className: 'resource-shortage-toast',
      duration: 7200
    };
  }

  globalThis.ReinosResourceShortageFeedback = Object.freeze({
    inspect,
    remember,
    canAfford,
    consumeToast,
    labels: LABELS
  });
})();
