'use strict';

/**
 * Integração modular de Equipamentos no painel de Administração.
 * Permite criar peças para Comandantes e Governadores sem mexer no sistema de drops dos Barões.
 */
(() => {
  const ROLE_ALIASES = Object.freeze({
    comandante: 'commanders', comandantes: 'commanders', commander: 'commanders', commanders: 'commanders', ataque: 'commanders',
    governador: 'governors', governadores: 'governors', castelao: 'governors', castelão: 'governors', casteloes: 'governors', castelões: 'governors', governor: 'governors', governors: 'governors', defesa: 'governors',
    todos: 'all', todas: 'all', all: 'all'
  });

  const SLOT_ALIASES = Object.freeze({
    arma: 'weapon', armas: 'weapon', weapon: 'weapon', espada: 'weapon',
    capacete: 'helmet', elmo: 'helmet', helmet: 'helmet',
    armadura: 'armor', armor: 'armor', cota: 'armor', couraca: 'armor', couraça: 'armor',
    artefacto: 'artifact', artefato: 'artifact', artifact: 'artifact', amuleto: 'artifact',
    visual: 'look', look: 'look', capa: 'look', estandarte: 'look',
    heroi: 'hero', herói: 'hero', hero: 'hero', campeao: 'hero', campeão: 'hero',
    todos: 'all', todas: 'all', all: 'all'
  });

  const RARITY_ALIASES = Object.freeze({
    comum: 'common', common: 'common', cinzento: 'common', cinza: 'common',
    raro: 'rare', rare: 'rare', verde: 'rare',
    epico: 'epic', épico: 'epic', epic: 'epic', roxo: 'epic',
    lendario: 'legendary', lendário: 'legendary', legendary: 'legendary', laranja: 'legendary',
    unico: 'unique', único: 'unique', unique: 'unique', vermelho: 'unique',
    reliquia: 'relic', relíquia: 'relic', relic: 'relic', azul: 'relic'
  });

  const SET_ALIASES = Object.freeze({
    sem: null, nenhum: null, normal: null, generico: null, genérico: null, none: null,
    falken: 'falken_baron', barao: 'falken_baron', barão: 'falken_baron', baraofalken: 'falken_baron', barãofalken: 'falken_baron', falkenbaron: 'falken_baron', falken_baron: 'falken_baron',
    guerreiro: 'royal_warrior', real: 'royal_warrior', guerreiroreal: 'royal_warrior', royal: 'royal_warrior', royal_warrior: 'royal_warrior',
    guardiao: 'fortress_guardian', guardião: 'fortress_guardian', fortaleza: 'fortress_guardian', guardiaodafortaleza: 'fortress_guardian', guardiãodafortaleza: 'fortress_guardian', fortress_guardian: 'fortress_guardian',
    saqueador: 'raider', raider: 'raider', saque: 'raider',
    pedra: 'stone_defender', defensor: 'stone_defender', defensordepedra: 'stone_defender', stone_defender: 'stone_defender',
    imperial: 'imperial_relic', reliquiaimperial: 'imperial_relic', relíquiaimperial: 'imperial_relic', imperial_relic: 'imperial_relic'
  });

  const ROLE_LABELS = Object.freeze({ commanders: 'Comandantes', governors: 'Governadores', all: 'Todos' });
  const ROLE_SINGULAR = Object.freeze({ commanders: 'Comandante', governors: 'Governador' });
  const SLOT_LABELS = Object.freeze({ weapon: 'Arma', helmet: 'Capacete', armor: 'Armadura', artifact: 'Artefacto', look: 'Visual', hero: 'Herói', all: 'Todos os espaços' });
  const SLOT_ICONS = Object.freeze({ weapon: '🗡️', helmet: '⛑️', armor: '🛡️', artifact: '📿', look: '🎖️', hero: '🦁' });
  const RARITY_LABELS = Object.freeze({ common: 'Comum', rare: 'Raro', epic: 'Épico', legendary: 'Lendário', unique: 'Único', relic: 'Relíquia' });
  const SLOT_ORDER = Object.freeze(['weapon', 'helmet', 'armor', 'artifact', 'look', 'hero']);

  function equipmentSystem() {
    return globalThis.ReinosEquipmentSystem || null;
  }

  function ensure(profile) {
    equipmentSystem()?.ensureState?.(profile);
  }

  function escapeHtml(value) {
    return String(value ?? '').replace(/[&<>'"]/g, char => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', "'": '&#039;', '"': '&quot;' }[char]));
  }

  function normalize(value, normalizeName) {
    return typeof normalizeName === 'function'
      ? normalizeName(value)
      : String(value || '').trim().toLocaleLowerCase('pt-PT');
  }

  function optionList(source, selected) {
    return Object.entries(source).map(([key, label]) => `<option value="${key}" ${key === selected ? 'selected' : ''}>${escapeHtml(label)}</option>`).join('');
  }

  function roleOptions() {
    return optionList({ commanders: 'Comandante', governors: 'Governador', all: 'Comandante + Governador' }, 'commanders');
  }

  function slotOptions() {
    return optionList(SLOT_LABELS, 'all');
  }

  function rarityOptions() {
    return optionList(RARITY_LABELS, 'legendary');
  }

  function setLabels() {
    const system = equipmentSystem();
    const labels = { none: 'Sem conjunto' };
    (system?.SET_ORDER || []).forEach(setId => {
      const set = system?.EQUIPMENT_SETS?.[setId];
      if (set) labels[setId] = set.name;
    });
    return labels;
  }

  function setOptions() {
    return optionList(setLabels(), 'falken_baron');
  }

  function inventory(profile) {
    const state = equipmentSystem()?.ensureState?.(profile);
    return Array.isArray(state?.inventory) ? state.inventory : [];
  }

  function renderSummary({ profile, fmt } = {}) {
    ensure(profile);
    const format = typeof fmt === 'function' ? fmt : value => String(Math.floor(Number(value) || 0));
    const items = inventory(profile);
    const commanderCount = items.filter(item => item.role === 'commanders').length;
    const governorCount = items.filter(item => item.role === 'governors').length;
    return `<div class="admin-stat"><small>Equipamentos</small><strong>⚔️ ${format(commanderCount)} · 🛡️ ${format(governorCount)}</strong></div>`;
  }

  function renderControls({ profile } = {}) {
    ensure(profile);
    return `
      <div class="admin-equipment-admin">
        <h4>🎒 Equipamentos de Comandantes e Governadores</h4>
        <p class="admin-note">Cria peças normais ou peças de set diretamente no inventário do jogador selecionado. Usa “todos os espaços” para entregar o set completo com arma, capacete, armadura, artefacto, visual e herói.</p>
        <div class="admin-equipment-grid">
          <label class="admin-equipment-field admin-equipment-role-field">Destino<select id="admin-equipment-role">${roleOptions()}</select></label>
          <label class="admin-equipment-field admin-equipment-set-field">Set<select id="admin-equipment-set">${setOptions()}</select></label>
          <label class="admin-equipment-field admin-equipment-slot-field">Espaço<select id="admin-equipment-slot">${slotOptions()}</select></label>
          <label class="admin-equipment-field admin-equipment-rarity-field">Raridade<select id="admin-equipment-rarity">${rarityOptions()}</select></label>
          <label class="admin-equipment-field admin-equipment-level-field">Nível<input id="admin-equipment-level" type="number" min="1" max="80" value="60" step="1" /></label>
          <label class="admin-equipment-field admin-equipment-amount-field">Qtd.<input id="admin-equipment-amount" type="number" min="1" max="50" value="1" step="1" /></label>
          <button class="action-btn admin-equipment-add-btn" data-admin-action="equipment-admin-add">Adicionar</button>
        </div>
        <div class="admin-equipment-actions">
          <button class="secondary-btn" data-admin-action="equipment-admin-full-commanders">Set completo Comandante</button>
          <button class="secondary-btn" data-admin-action="equipment-admin-full-governors">Set completo Governador</button>
          <button class="secondary-btn" data-admin-action="equipment-admin-full-both">Set completo para ambos</button>
          <button class="danger-btn" data-admin-action="equipment-admin-clear">Limpar equipamentos</button>
        </div>
      </div>`;
  }

  function roleKeys(role) {
    return role === 'all' ? ['commanders', 'governors'] : role ? [role] : [];
  }

  function slotKeys(slot) {
    return slot === 'all' ? [...SLOT_ORDER] : slot ? [slot] : [];
  }

  function createItems(targetProfile, { role = 'commanders', slot = 'all', rarity = 'legendary', level = 60, amount = 1, setId = null, source = 'Administração' } = {}) {
    const system = equipmentSystem();
    if (!system?.createEquipment) throw new Error('Sistema de equipamentos indisponível.');
    const state = system.ensureState(targetProfile);
    const created = [];
    const safeLevel = Math.max(1, Math.min(80, Math.floor(Number(level) || 1)));
    const safeAmount = Math.max(1, Math.min(50, Math.floor(Number(amount) || 1)));
    const safeSetId = system.EQUIPMENT_SETS?.[setId] ? setId : null;
    const setSource = safeSetId ? `Administração — ${system.EQUIPMENT_SETS[safeSetId].name}` : source;

    for (const roleKey of roleKeys(role)) {
      for (const slotKey of slotKeys(slot)) {
        for (let index = 0; index < safeAmount; index += 1) {
          const item = system.createEquipment(safeLevel, { role: roleKey, slot: slotKey, rarity, setId: safeSetId, source: setSource });
          item.icon = system.EQUIPMENT_SETS?.[safeSetId]?.icon || SLOT_ICONS[slotKey] || item.icon;
          item.source = setSource;
          state.inventory.push(item);
          created.push(item);
        }
      }
    }
    return created;
  }

  function requestedRole(value, normalizeName) {
    return ROLE_ALIASES[normalize(value, normalizeName)] || null;
  }

  function requestedSlot(value, normalizeName) {
    return SLOT_ALIASES[normalize(value, normalizeName)] || null;
  }

  function requestedRarity(value, normalizeName) {
    return RARITY_ALIASES[normalize(value, normalizeName)] || null;
  }

  function requestedSet(value, normalizeName) {
    const normalized = normalize(value, normalizeName).replace(/[\s\-_]/g, '');
    if (Object.prototype.hasOwnProperty.call(SET_ALIASES, normalized)) return SET_ALIASES[normalized];
    const system = equipmentSystem();
    return system?.EQUIPMENT_SETS?.[value] ? value : null;
  }

  function setName(setId) {
    return equipmentSystem()?.EQUIPMENT_SETS?.[setId]?.name || 'Sem conjunto';
  }

  function createdDescription(created, role, slot, rarity, level, setId = null) {
    const roleText = ROLE_LABELS[role] || ROLE_LABELS.all;
    const slotText = SLOT_LABELS[slot] || SLOT_LABELS.all;
    const rarityText = RARITY_LABELS[rarity] || rarity;
    const setText = setId ? `, ${setName(setId)}` : '';
    return `${created.length} equipamento(s) — ${roleText}, ${slotText}, ${rarityText}, nível ${level}${setText}`;
  }

  async function handleCommand({ command, tokens, targetUser, targetProfile, normalizeName, safeInteger, commit } = {}) {
    const isSetCommand = ['setequipamento', 'setequipamentos', 'setequip', 'set', 'sets', 'conjunto', 'conjuntos'].includes(command);
    const isGenericCommand = ['equipamento', 'equipamentos', 'equipment', 'equip'].includes(command);
    if (!isSetCommand && !isGenericCommand) return false;
    ensure(targetProfile);

    const role = requestedRole(tokens.shift(), normalizeName);
    let setId = null;
    if (isSetCommand) setId = requestedSet(tokens.shift(), normalizeName);
    const slot = requestedSlot(tokens.shift(), normalizeName);
    const rarity = requestedRarity(tokens.shift(), normalizeName);
    const level = safeInteger(tokens.shift(), NaN);
    const amount = safeInteger(tokens.shift() || 1, 1);

    if (!role) throw new Error('Destino inválido. Usa comandante, governador ou todos.');
    if (isSetCommand && !setId) throw new Error('Set inválido. Usa falken, guerreiro-real, guardião-fortaleza, saqueador, defensor-pedra ou relíquia-imperial.');
    if (!slot) throw new Error('Equipamento inválido. Usa arma, capacete, armadura, artefacto, visual, herói ou todos.');
    if (!rarity) throw new Error('Raridade inválida. Usa comum, raro, épico, lendário, único ou relíquia.');
    if (!Number.isFinite(level)) throw new Error('Indica um nível válido para o equipamento.');

    const created = createItems(targetProfile, { role, slot, rarity, level, amount, setId, source: 'Administração' });
    await commit(
      `Foram adicionados ${created.length} equipamento(s) a ${targetUser.username}.`,
      targetUser,
      isSetCommand ? 'SETS' : 'EQUIPAMENTOS',
      createdDescription(created, role, slot, rarity, Math.max(1, Math.min(80, Math.floor(Number(level) || 1))), setId)
    );
    return true;
  }

  async function handleAction({ action, user, targetProfile, safeInteger, commit } = {}) {
    if (!String(action || '').startsWith('equipment-admin-')) return false;
    ensure(targetProfile);

    if (action === 'equipment-admin-clear') {
      await resetEquipment({ targetUser: user, targetProfile, commit });
      return true;
    }

    let role = document.querySelector('#admin-equipment-role')?.value || 'commanders';
    let setId = document.querySelector('#admin-equipment-set')?.value || 'falken_baron';
    let slot = document.querySelector('#admin-equipment-slot')?.value || 'all';
    let rarity = document.querySelector('#admin-equipment-rarity')?.value || 'legendary';
    let level = safeInteger(document.querySelector('#admin-equipment-level')?.value, 60);
    let amount = safeInteger(document.querySelector('#admin-equipment-amount')?.value, 1);
    setId = setId === 'none' ? null : setId;

    if (action === 'equipment-admin-full-commanders') {
      role = 'commanders';
      slot = 'all';
      rarity = 'legendary';
      setId = setId || 'falken_baron';
      level = Math.max(1, Math.min(80, Number(level) || 60));
      amount = 1;
    }
    if (action === 'equipment-admin-full-governors') {
      role = 'governors';
      slot = 'all';
      rarity = 'legendary';
      setId = setId || 'falken_baron';
      level = Math.max(1, Math.min(80, Number(level) || 60));
      amount = 1;
    }
    if (action === 'equipment-admin-full-both') {
      role = 'all';
      slot = 'all';
      rarity = 'legendary';
      setId = setId || 'falken_baron';
      level = Math.max(1, Math.min(80, Number(level) || 60));
      amount = 1;
    }

    if (!ROLE_LABELS[role] || !SLOT_LABELS[slot] || !RARITY_LABELS[rarity]) throw new Error('Escolha de equipamento inválida.');
    if (setId && !equipmentSystem()?.EQUIPMENT_SETS?.[setId]) throw new Error('Set selecionado inválido.');
    const created = createItems(targetProfile, { role, slot, rarity, level, amount, setId, source: 'Administração' });
    await commit(
      `Foram adicionados ${created.length} equipamento(s) a ${user.username}.`,
      user,
      'EQUIPAMENTOS',
      createdDescription(created, role, slot, rarity, Math.max(1, Math.min(80, Math.floor(Number(level) || 1))), setId)
    );
    return true;
  }

  async function resetEquipment({ targetUser, targetProfile, commit } = {}) {
    const state = equipmentSystem()?.ensureState?.(targetProfile);
    if (!state) throw new Error('Sistema de equipamentos indisponível.');
    state.inventory = [];
    [...(state.commanders || []), ...(state.governors || [])].forEach(character => {
      character.slots = Object.fromEntries(SLOT_ORDER.map(slot => [slot, null]));
    });
    await commit(`Equipamentos de ${targetUser.username} foram limpos.`, targetUser, 'RESET', 'Equipamentos limpos');
    return true;
  }

  function infoLine(profile) {
    ensure(profile);
    const items = inventory(profile);
    return `Equipamentos: comandantes ${items.filter(item => item.role === 'commanders').length}, governadores ${items.filter(item => item.role === 'governors').length}`;
  }

  function helpLines() {
    return [
      '/equipamentos "Jogador" <comandante|governador|todos> <arma|capacete|armadura|artefacto|visual|herói|todos> <comum|raro|épico|lendário|único|relíquia> <nível> [quantidade]',
      '/setequipamentos "Jogador" <comandante|governador|todos> <falken|guerreiro-real|guardião-fortaleza|saqueador|defensor-pedra|relíquia-imperial> <arma|capacete|armadura|artefacto|visual|herói|todos> <comum|raro|épico|lendário|único|relíquia> <nível> [quantidade]'
    ];
  }

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