'use strict';

/**
 * Integração modular das ferramentas de cerco no painel de Administração.
 *
 * Este módulo não altera a Oficina nem o sistema de batalha. Apenas permite
 * consultar, adicionar ou retirar Escadas, Arietes e Manteletes dos jogadores
 * autorizados através do painel e da consola administrativa.
 */
(() => {
  const TOOL_ALIASES = Object.freeze({
    escada: 'ladder',
    escadas: 'ladder',
    ladder: 'ladder',
    ladders: 'ladder',
    ariete: 'ram',
    arietes: 'ram',
    ram: 'ram',
    rams: 'ram',
    mantelete: 'mantlet',
    manteletes: 'mantlet',
    mantlet: 'mantlet',
    mantlets: 'mantlet'
  });

  function siegeSystem() {
    return globalThis.ReinosSiegeTools || null;
  }

  function catalog() {
    return siegeSystem()?.CATALOG || {};
  }

  function ensure(profile) {
    if (!profile) return;
    siegeSystem()?.ensureState?.(profile);
    if (!profile.siegeTools || typeof profile.siegeTools !== 'object') profile.siegeTools = {};
    for (const type of Object.keys(catalog())) {
      profile.siegeTools[type] = Math.max(0, Math.floor(Number(profile.siegeTools[type]) || 0));
    }
  }

  function label(type) {
    return catalog()[type]?.name || type;
  }

  function options() {
    return Object.keys(catalog())
      .map(type => `<option value="${type}">${label(type)}</option>`)
      .join('');
  }

  function renderControls({ profile } = {}) {
    ensure(profile);
    return `
      <div class="admin-form-row admin-siege-tools-row">
        <select id="admin-siege-tool-type" aria-label="Ferramenta de cerco">${options()}</select>
        <input id="admin-siege-tool-amount" type="number" value="100" step="1" aria-label="Quantidade de ferramentas" />
        <button class="action-btn" data-admin-action="siege-tool-apply">Aplicar</button>
      </div>`;
  }

  function renderSummary({ profile, fmt } = {}) {
    ensure(profile);
    const format = typeof fmt === 'function' ? fmt : value => String(Math.floor(Number(value) || 0));
    const values = Object.keys(catalog()).map(type => `${label(type)} ${format(profile?.siegeTools?.[type] || 0)}`);
    return `<div class="admin-stat"><small>Ferramentas</small><strong>${values.join(' · ')}</strong></div>`;
  }

  function normalizeRequested(value, normalizeName) {
    const normalized = typeof normalizeName === 'function'
      ? normalizeName(value)
      : String(value || '').trim().toLocaleLowerCase('pt-PT');
    return normalized === 'todas' || normalized === 'todos' ? 'all' : TOOL_ALIASES[normalized];
  }

  function keysFor(requested) {
    return requested === 'all' ? Object.keys(catalog()) : requested ? [requested] : [];
  }

  async function handleCommand({
    command,
    tokens,
    targetUser,
    targetProfile,
    normalizeName,
    safeInteger,
    fmt,
    commit,
    adminGrantInventory
  } = {}) {
    if (!['ferramentas', 'ferramenta', 'tools', 'tool'].includes(command)) return false;
    ensure(targetProfile);

    const requestedRaw = tokens.shift();
    const requested = normalizeRequested(requestedRaw, normalizeName);
    const amount = safeInteger(tokens.shift(), NaN);
    if (!Number.isFinite(amount)) throw new Error('Indica uma quantidade válida de ferramentas.');

    const keys = keysFor(requested);
    if (!keys.length) throw new Error('Ferramenta inválida. Usa escada, ariete, mantelete ou todas.');

    const siegeTools = {};
    keys.forEach(type => { siegeTools[type] = amount; });

    const requestedLabel = requested === 'all' ? 'todas as ferramentas' : label(requested);
    if (typeof adminGrantInventory === 'function') {
      await adminGrantInventory(targetUser.id, { siegeTools });
      await commit(
        `${amount >= 0 ? 'Adicionadas' : 'Retiradas'} ${fmt(Math.abs(amount))} unidades de ${requestedLabel} a ${targetUser.username}.`,
        targetUser,
        'FERRAMENTAS',
        `${requestedLabel}: ${amount >= 0 ? '+' : ''}${amount}`
      );
      return true;
    } else {
      keys.forEach(type => {
        targetProfile.siegeTools[type] = Math.max(0, safeInteger(targetProfile.siegeTools[type]) + amount);
      });
      await commit(
        `${amount >= 0 ? 'Adicionadas' : 'Retiradas'} ${fmt(Math.abs(amount))} unidades de ${requestedLabel} a ${targetUser.username}.`,
        targetUser,
        'FERRAMENTAS',
        `${requestedLabel}: ${amount >= 0 ? '+' : ''}${amount}`
      );
      return true;
    }
    return true;
  }

  async function handleAction({
    action,
    user,
    targetProfile,
    safeInteger,
    fmt,
    commit,
    adminGrantInventory
  } = {}) {
    if (action !== 'siege-tool-apply') return false;
    ensure(targetProfile);

    const type = document.querySelector('#admin-siege-tool-type')?.value;
    const amount = safeInteger(document.querySelector('#admin-siege-tool-amount')?.value, NaN);
    if (!catalog()[type] || !Number.isFinite(amount)) throw new Error('Ferramenta ou quantidade inválida.');

    if (typeof adminGrantInventory === 'function') {
      await adminGrantInventory(user.id, { siegeTools: { [type]: amount } });
    } else {
      targetProfile.siegeTools[type] = Math.max(0, safeInteger(targetProfile.siegeTools[type]) + amount);
    }
    await commit(
      `${label(type)} de ${user.username}: ${amount >= 0 ? '+' : ''}${fmt(amount)}.`,
      user,
      'FERRAMENTAS',
      `${label(type)} ${amount >= 0 ? '+' : ''}${amount}`
    );
    return true;
  }

  async function resetTools({ targetUser, targetProfile, commit } = {}) {
    ensure(targetProfile);
    Object.keys(catalog()).forEach(type => { targetProfile.siegeTools[type] = 0; });
    await commit(`Ferramentas de ${targetUser.username} foram zeradas.`, targetUser, 'RESET', 'Ferramentas zeradas');
    return true;
  }

  function infoLine(profile) {
    ensure(profile);
    return `Ferramentas: escadas ${profile.siegeTools.ladder || 0}, arietes ${profile.siegeTools.ram || 0}, manteletes ${profile.siegeTools.mantlet || 0}`;
  }

  function helpLines() {
    return ['/ferramentas "Jogador" <escada|ariete|mantelete|todas> <quantidade>'];
  }

  globalThis.ReinosAdminSiegeTools = Object.freeze({
    ensure,
    renderControls,
    renderSummary,
    handleCommand,
    handleAction,
    resetTools,
    infoLine,
    helpLines
  });
})();
