'use strict';

/**
 * Interface modular do Quartel.
 *
 * Responsabilidades:
 * - abrir o menu completo de recrutamento ao clicar no Quartel;
 * - apresentar tropas, custos, tempos, fila e consumo de comida;
 * - encaminhar o recrutamento para a lógica central já existente no jogo.
 */
(() => {
  const VERSION = 1;
  const VISIBLE_QUEUE_SLOTS = 5;
  let selectedType = 'spearman';
  let selectedBuildingId = null;
  let quantity = 10;
  let currentContext = null;

  function safeQuantity(value) {
    return Math.max(1, Math.min(500, Math.floor(Number(value) || 1)));
  }

  function troopUnlocked(type, troop, building, context) {
    if (!building || building.status !== 'ready' || Number(building.level) < 1) return false;
    if (troop.buildingRequired && !context.hasBuilding(troop.buildingRequired)) return false;
    return true;
  }

  function queueLabel(item, index, context, profile) {
    const troop = context.getTroopsMeta()[item.type];
    const now = context.now();
    const waiting = Number(item.startedAt) > now;
    return `<div class="barracks-queue-slot is-filled ${index === 0 && !waiting ? 'is-active' : ''}">
      <div class="barracks-queue-icon">${troop?.icon || '⚔️'}</div>
      <div class="barracks-queue-data">
        <b>${context.format(item.count)} ${context.escapeHtml(troop?.name || item.type)}</b>
        <small>${waiting ? 'Em espera' : 'Em treino'}</small>
        <span data-countdown="${item.endAt}">${context.formatTime(item.endAt - now)}</span>
      </div>
    </div>`;
  }

  function queueHtml(context, profile) {
    const items = profile.recruitQueue || [];
    const slots = Array.from({ length: VISIBLE_QUEUE_SLOTS }, (_, index) => items[index]
      ? queueLabel(items[index], index, context, profile)
      : `<div class="barracks-queue-slot is-empty"><span>${index + 1}</span><small>Fila livre</small></div>`).join('');
    const extra = items.length > VISIBLE_QUEUE_SLOTS
      ? `<div class="barracks-extra-queue">+ ${items.length - VISIBLE_QUEUE_SLOTS} recrutamento(s) adicional(is) em espera</div>`
      : '';
    return slots + extra;
  }

  function troopCard(type, troop, building, context, profile) {
    const unlocked = troopUnlocked(type, troop, building, context);
    const selected = selectedType === type;
    const available = Math.max(0, Number(profile.troops?.[type]) || 0);
    return `<button class="barracks-troop-card ${selected ? 'is-selected' : ''} ${unlocked ? '' : 'is-locked'}" data-action="barracks-select" data-type="${type}" ${unlocked ? '' : 'disabled'}>
      <div class="barracks-card-level">Nv. ${Math.max(1, Number(building.level) || 1)}</div>
      <div class="barracks-card-portrait"><span>${troop.icon}</span></div>
      <strong>${context.escapeHtml(troop.name)}</strong>
      <small>${unlocked ? `No castelo: ${context.format(available)}` : 'Unidade bloqueada'}</small>
      <div class="barracks-card-stats"><span>⚔ ${troop.attack}</span><span>🛡 ${troop.defense}</span><span>🎒 ${troop.carry}</span></div>
    </button>`;
  }

  function costHtml(cost, context) {
    return context.costsHtml(cost);
  }

  function selectedPanel(context, profile, building) {
    const troops = context.getTroopsMeta();
    const troop = troops[selectedType] || troops.spearman || Object.values(troops)[0];
    const count = safeQuantity(quantity);
    const totalCost = Object.fromEntries(Object.entries(troop.cost || {}).map(([key, value]) => [key, value * count]));
    const baseTrainingMs = Math.max(0, Number(troop.seconds) || 0) * count * 1000;
    const trainingMs = globalThis.ReinosBuildingUpgradeBenefits?.barracksTrainingTimeMs?.(baseTrainingMs, building.level) || baseTrainingMs;
    const upkeep = globalThis.ReinosTroopUpkeep;
    const currentConsumption = upkeep?.hourlyConsumption?.(profile) || 0;
    const addedConsumption = upkeep?.consumptionForUnits?.(count) || count * 2;
    const available = Math.max(0, Number(profile.troops?.[selectedType]) || 0);

    return `<section class="barracks-selected-panel">
      <div class="barracks-selected-portrait">
        <span>${troop.icon}</span>
        <b>${context.escapeHtml(troop.name)}</b>
        <small>${context.format(available)} disponíveis no castelo</small>
      </div>
      <div class="barracks-selected-info">
        <h3>${context.escapeHtml(troop.name)}</h3>
        <div class="barracks-selected-stats">
          <div><span>Ataque</span><strong>${troop.attack}</strong></div>
          <div><span>Defesa</span><strong>${troop.defense}</strong></div>
          <div><span>Capacidade de saque</span><strong>${troop.carry}</strong></div>
          <div><span>Comida por unidade</span><strong>${upkeep?.FOOD_PER_UNIT_PER_HOUR || 2}/h</strong></div>
        </div>
        <div class="barracks-quantity-row">
          <button data-action="barracks-quantity-minus" aria-label="Diminuir quantidade">−</button>
          <label><span>Quantidade</span><input id="barracks-quantity" type="number" min="1" max="500" value="${count}" /></label>
          <button data-action="barracks-quantity-plus" aria-label="Aumentar quantidade">＋</button>
        </div>
        <div class="barracks-recruit-summary">
          <div><span>Tempo de treino</span><strong id="barracks-total-time">${context.formatTime(trainingMs)}</strong></div>
          <div><span>Custo total</span><div class="costs" id="barracks-total-cost">${costHtml(totalCost, context)}</div></div>
          <div><span>Consumo adicional</span><strong id="barracks-added-upkeep">−${context.format(addedConsumption)} comida/h</strong></div>
          <div><span>Consumo total após treino</span><strong id="barracks-total-upkeep">−${context.format(currentConsumption + addedConsumption)} comida/h</strong></div>
        </div>
        <button class="barracks-recruit-btn" data-action="barracks-recruit" data-type="${selectedType}">Recrutar</button>
      </div>
    </section>`;
  }

  function bodyHtml(context, profile, building) {
    const troops = context.getTroopsMeta();
    if (!troops[selectedType]) selectedType = Object.keys(troops)[0];
    if (!troopUnlocked(selectedType, troops[selectedType], building, context)) {
      selectedType = Object.entries(troops).find(([type, troop]) => troopUnlocked(type, troop, building, context))?.[0] || Object.keys(troops)[0];
    }
    const currentConsumption = globalThis.ReinosTroopUpkeep?.hourlyConsumption?.(profile) || 0;
    const foodIcon = context.getResourceMeta?.()?.food?.icon || 'Comida';
    const visualPreview = globalThis.ReinosBarracksVisuals?.previewHtml?.(building.level) || '';
    const cards = Object.entries(troops).map(([type, troop]) => troopCard(type, troop, building, context, profile)).join('');
    const comparison = globalThis.ReinosBuildingUpgradeBenefits?.comparisonHtml?.(building, {
      profile,
      definitions: context.getBuildingsMeta(),
      resourceMeta: context.getResourceMeta(),
      format: context.format,
      formatTime: context.formatTime,
      escapeHtml: context.escapeHtml
    }, { compact: true }) || '';
    const level = Math.max(1, Number(building.level) || 1);
    const maxLevel = globalThis.ReinosBarracksVisuals?.MAX_LEVEL || 20;
    const upgradeOrder = level >= maxLevel ? '' : `<div class="building-upgrade-order"><div><span>Tempo da melhoria</span><strong>${context.formatTime(context.buildingTime('barracks', level + 1))}</strong></div><div><span>Custo da melhoria</span><div class="costs">${context.costsHtml(context.buildingCost('barracks', level + 1))}</div></div></div>`;
    return `<div id="barracks-system" class="barracks-shell">
      <header class="barracks-banner">
        <div class="barracks-crest">⚔</div>
        <div><small>Edifício militar</small><h2>Recrutar</h2><p>Treina unidades para defender o castelo e conquistar novos territórios.</p></div>
        <div class="barracks-level barracks-level-visual">${visualPreview}<span>Quartel</span><strong>Nível ${Math.max(1, Number(building.level) || 1)}</strong></div>
      </header>
      ${comparison}${upgradeOrder}
      <section class="barracks-queue-section">
        <div class="barracks-section-heading"><div><small>Treino</small><h3>Fila de recrutamento</h3></div><span>${profile.recruitQueue?.length || 0} lote(s) em curso</span></div>
        <div class="barracks-queue-grid">${queueHtml(context, profile)}</div>
      </section>
      <section class="barracks-catalog-section">
        <div class="barracks-section-heading"><div><small>Unidades</small><h3>Escolhe a tropa</h3></div><span class="barracks-food-consumption">${foodIcon} Consumo atual: <b>−${context.format(currentConsumption)}/h</b></span></div>
        <div class="barracks-troop-grid">${cards}</div>
      </section>
      ${selectedPanel(context, profile, building)}
    </div>`;
  }

  function footerHtml(building) {
    const maxLevel = globalThis.ReinosBarracksVisuals?.MAX_LEVEL || 20;
    const atMaximum = Math.max(1, Number(building.level) || 1) >= maxLevel;
    return `<button class="danger-btn" data-action="building-demolish" data-id="${building.id}">Demolir</button>
      <button class="secondary-btn" data-action="castle-move-start" data-id="${building.id}">Mover</button>
      <button class="secondary-btn" data-action="modal-close">Fechar</button>
      <button class="action-btn" data-action="building-upgrade" data-id="${building.id}" ${atMaximum ? 'disabled' : ''}>${atMaximum ? 'Quartel no nível máximo' : 'Melhorar quartel'}</button>`;
  }

  function open(buildingId, context, focusType = null) {
    const profile = context.getProfile();
    const building = profile?.buildings?.find(item => item.id === buildingId && item.type === 'barracks');
    if (!building || building.status !== 'ready' || Number(building.level) < 1) return false;
    if (focusType && context.getTroopsMeta()[focusType]) selectedType = focusType;
    selectedBuildingId = building.id;
    currentContext = context;
    quantity = safeQuantity(quantity);
    context.openModal('Recrutar', bodyHtml(context, profile, building), footerHtml(building));
    document.querySelector('.modal')?.classList.add('barracks-modal');
    return true;
  }

  function reopen() {
    if (!currentContext || !selectedBuildingId) return;
    open(selectedBuildingId, currentContext);
  }

  function updatePreview() {
    if (!currentContext || !selectedBuildingId) return;
    const profile = currentContext.getProfile();
    const troop = currentContext.getTroopsMeta()[selectedType];
    if (!troop) return;
    const input = document.querySelector('#barracks-quantity');
    quantity = safeQuantity(input?.value ?? quantity);
    if (input && String(quantity) !== input.value) input.value = String(quantity);
    const cost = Object.fromEntries(Object.entries(troop.cost || {}).map(([key, value]) => [key, value * quantity]));
    const building = profile.buildings?.find(item => item.id === selectedBuildingId);
    const baseTrainingMs = Math.max(0, Number(troop.seconds) || 0) * quantity * 1000;
    const trainingMs = globalThis.ReinosBuildingUpgradeBenefits?.barracksTrainingTimeMs?.(baseTrainingMs, building?.level || 1) || baseTrainingMs;
    const currentConsumption = globalThis.ReinosTroopUpkeep?.hourlyConsumption?.(profile) || 0;
    const addedConsumption = globalThis.ReinosTroopUpkeep?.consumptionForUnits?.(quantity) || quantity * 2;
    const timeEl = document.querySelector('#barracks-total-time');
    const costEl = document.querySelector('#barracks-total-cost');
    const addedEl = document.querySelector('#barracks-added-upkeep');
    const totalEl = document.querySelector('#barracks-total-upkeep');
    if (timeEl) timeEl.textContent = currentContext.formatTime(trainingMs);
    if (costEl) costEl.innerHTML = costHtml(cost, currentContext);
    if (addedEl) addedEl.textContent = `−${currentContext.format(addedConsumption)} comida/h`;
    if (totalEl) totalEl.textContent = `−${currentContext.format(currentConsumption + addedConsumption)} comida/h`;
  }

  async function recruit(context) {
    const count = safeQuantity(document.querySelector('#barracks-quantity')?.value ?? quantity);
    const success = await context.queueRecruitment(selectedType, count, { keepOpen: true });
    if (!success) return;
    quantity = count;
    reopen();
  }

  async function handleAction(action, element, context) {
    const profile = context.getProfile?.();
    if (!profile) return false;

    if (action === 'building-open') {
      const building = profile.buildings?.find(item => item.id === element.dataset.id);
      if (building?.type !== 'barracks' || building.status !== 'ready' || Number(building.level) < 1) return false;
      open(building.id, context);
      return true;
    }
    if (action === 'recruit-open') {
      const building = profile.buildings?.find(item => item.type === 'barracks' && item.status === 'ready' && Number(item.level) > 0);
      if (!building) return false;
      open(building.id, context, element.dataset.type);
      return true;
    }
    if (action === 'barracks-select') {
      selectedType = String(element.dataset.type || selectedType);
      reopen();
      return true;
    }
    if (action === 'barracks-quantity-minus') {
      quantity = safeQuantity((Number(document.querySelector('#barracks-quantity')?.value) || quantity) - 1);
      const input = document.querySelector('#barracks-quantity');
      if (input) input.value = String(quantity);
      updatePreview();
      return true;
    }
    if (action === 'barracks-quantity-plus') {
      quantity = safeQuantity((Number(document.querySelector('#barracks-quantity')?.value) || quantity) + 1);
      const input = document.querySelector('#barracks-quantity');
      if (input) input.value = String(quantity);
      updatePreview();
      return true;
    }
    if (action === 'barracks-recruit') {
      selectedType = String(element.dataset.type || selectedType);
      await recruit(context);
      return true;
    }
    return false;
  }

  document.addEventListener('input', event => {
    if (event.target?.id !== 'barracks-quantity') return;
    updatePreview();
  });

  globalThis.ReinosBarracksSystem = Object.freeze({ VERSION, open, handleAction });
})();
