'use strict';

(() => {
  const VERSION = 2;
  const original = globalThis.ReinosCastleSystem;
  if (!original) return;

  const CATEGORIES = Object.freeze({
    economy: {
      name: 'Economia',
      icon: '🌾',
      types: ['woodcutter', 'quarry', 'farm', 'house', 'warehouse', 'marketplace']
    },
    military: {
      name: 'Militares',
      icon: '⚔️',
      types: ['barracks', 'workshop', 'stables', 'hospital', 'tavern']
    },
    defense: {
      name: 'Defesa',
      icon: '🛡️',
      types: ['watchtower']
    },
    decoration: {
      name: 'Decorações',
      icon: '🌳',
      types: ['decoration']
    }
  });

  let selectedCategory = 'economy';

  const COST_ORDER = Object.freeze(['wood', 'stone', 'food', 'coins', 'gems']);

  function formatAmount(ctx, amount) {
    const formatter = typeof ctx?.format === 'function' ? ctx.format : (value => String(value));
    return formatter(Number(amount) || 0);
  }

  function costTitle(type, amount, ctx) {
    const labels = globalThis.ReinosResourceIcons?.labels || {};
    const label = labels[type] || type;
    return `${label}: ${formatAmount(ctx, amount)}`;
  }

  function buildCostHtml(cost, ctx) {
    const data = cost || {};
    const keys = COST_ORDER.filter(type => Number(data[type]) > 0)
      .concat(Object.keys(data).filter(type => !COST_ORDER.includes(type) && Number(data[type]) > 0));
    if (!keys.length) return '<span class="gge-build-cost-chip"><strong>Grátis</strong></span>';

    return keys.map(type => {
      const value = Number(data[type]) || 0;
      const title = ctx.escapeHtml ? ctx.escapeHtml(costTitle(type, value, ctx)) : costTitle(type, value, ctx);
      const icon = globalThis.ReinosResourceIcons?.icon?.(type) || '';
      return `<span class="gge-build-cost-chip gge-build-cost-${type}" title="${title}">${icon}<strong>${formatAmount(ctx, value)}</strong></span>`;
    }).join('');
  }


  function imageFor(type) {
    const illustrated = globalThis.ReinosIllustratedBuildings?.assetFor?.(type);
    if (illustrated) return illustrated;
    if (type === 'barracks') return globalThis.ReinosIllustratedBuildings?.assetFor?.('barracks', 1) || '../assets/buildings/levels/barracks/level_01.png';
    return '';
  }

  function availability(profile, type, definition, ctx) {
    const maxed = Boolean(definition.max && ctx.buildingCount(type) >= definition.max);
    const requiredLevel = Math.max(1, Number(definition.keepRequired) || 1);
    const keepLocked = requiredLevel > ctx.getKeepLevel();
    const noSpace = original.firstEmptySlot(profile, type) < 0;
    const cost = ctx.buildingCost(type, 1);
    const affordable = ctx.canAfford(cost);
    return {
      maxed,
      keepLocked,
      noSpace,
      affordable,
      requiredLevel,
      cost,
      disabled: maxed || keepLocked || noSpace
    };
  }

  function stateLabel(state) {
    if (state.maxed) return 'Limite atingido';
    if (state.keepLocked) return `Fortaleza Nv. ${state.requiredLevel}`;
    if (state.noSpace) return 'Sem espaço';
    if (!state.affordable) return 'Recursos insuficientes';
    return 'Selecionar';
  }

  function buildingCard(profile, type, ctx) {
    const definition = ctx.getBuildingsMeta()[type];
    if (!definition) return '';
    const state = availability(profile, type, definition, ctx);
    const size = original.sizeFor(type);
    const image = imageFor(type);
    const imageHtml = image
      ? `<img src="${image}" alt="${ctx.escapeHtml(definition.name)}" draggable="false" />`
      : `<span class="gge-build-card-fallback">${definition.icon || '🏠'}</span>`;
    const classes = [
      'gge-build-card',
      state.disabled ? 'is-locked' : '',
      !state.affordable && !state.disabled ? 'is-unaffordable' : ''
    ].filter(Boolean).join(' ');

    return `<button type="button" class="${classes}" data-action="castle-build-placement-start" data-type="${type}" data-gge-build-category="${type}" ${state.disabled ? 'disabled' : ''} title="${ctx.escapeHtml(definition.description)}">
      <span class="gge-build-card-art">${imageHtml}</span>
      <span class="gge-build-card-name">${ctx.escapeHtml(definition.name)}</span>
      <span class="gge-build-card-meta"><b>${size.w}×${size.h}</b><em>⏱ ${ctx.formatTime(ctx.buildingTime(type, 1))}</em></span>
      <span class="gge-build-card-costs">${buildCostHtml(state.cost, ctx)}</span>
      <span class="gge-build-card-status">${stateLabel(state)}</span>
      ${state.disabled ? '<span class="gge-build-card-lock">🔒</span>' : ''}
    </button>`;
  }

  function tabsHtml() {
    return Object.entries(CATEGORIES).map(([id, category]) => `<button type="button" class="gge-build-tab ${id === selectedCategory ? 'is-active' : ''}" data-action="gge-build-category" data-category="${id}">
      <span>${category.icon}</span><b>${category.name}</b>
    </button>`).join('');
  }

  function cardsHtml(profile, ctx) {
    return Object.entries(CATEGORIES).map(([categoryId, category]) => category.types.map(type => {
      const card = buildingCard(profile, type, ctx);
      return card ? `<div class="gge-build-card-slot ${categoryId === selectedCategory ? '' : 'is-hidden'}" data-category-panel="${categoryId}">${card}</div>` : '';
    }).join('')).join('');
  }

  function applyCategory(categoryId) {
    if (!CATEGORIES[categoryId]) return;
    selectedCategory = categoryId;
    document.querySelectorAll('.gge-build-tab').forEach(button => {
      button.classList.toggle('is-active', button.dataset.category === categoryId);
    });
    document.querySelectorAll('.gge-build-card-slot').forEach(slot => {
      slot.classList.toggle('is-hidden', slot.dataset.categoryPanel !== categoryId);
    });
    const track = document.querySelector('.gge-build-track');
    if (track) track.scrollLeft = 0;
  }

  function decorateModal() {
    const backdrop = document.querySelector('#modal-root .modal-backdrop');
    const modal = backdrop?.querySelector('.modal');
    if (!backdrop || !modal) return;
    backdrop.classList.add('gge-build-backdrop');
    modal.classList.add('gge-build-modal');
  }

  function openBuildModal(_slot, ctx) {
    const profile = ctx.getProfile();
    original.ensureState(profile);
    if (profile.constructionQueue.length >= ctx.constructionQueueLimit()) {
      ctx.toast('A fila de construção está ocupada.', 'error');
      return true;
    }

    const body = `<div class="gge-building-dock">
      <div class="gge-building-dock-header">
        <div class="gge-building-tabs">${tabsHtml()}</div>
        <button type="button" class="gge-building-close" data-action="modal-close" title="Fechar">✕</button>
      </div>
      <div class="gge-building-carousel">
        <button type="button" class="gge-build-arrow" data-action="gge-build-scroll" data-direction="-1" title="Edifícios anteriores">‹</button>
        <div class="gge-build-track" aria-label="Catálogo de edifícios">${cardsHtml(profile, ctx)}</div>
        <button type="button" class="gge-build-arrow" data-action="gge-build-scroll" data-direction="1" title="Mais edifícios">›</button>
      </div>
      <div class="gge-building-hint"><span>Seleciona um edifício</span><b>e arrasta-o para os quadrados livres dentro da muralha.</b></div>
    </div>`;

    ctx.openModal('Construir', body, '');
    requestAnimationFrame(decorateModal);
    return true;
  }

  async function handleAction(action, element, ctx) {
    if (action === 'gge-build-category') {
      applyCategory(String(element.dataset.category || 'economy'));
      return true;
    }
    if (action === 'gge-build-scroll') {
      const track = document.querySelector('.gge-build-track');
      const direction = Number(element.dataset.direction) < 0 ? -1 : 1;
      track?.scrollBy?.({ left: direction * Math.max(260, track.clientWidth * 0.72), behavior: 'smooth' });
      return true;
    }
    return original.handleAction(action, element, ctx);
  }

  globalThis.ReinosCastleSystem = Object.freeze({
    ...original,
    openBuildModal,
    handleAction,
    GGE_BUILDING_CATALOG_VERSION: VERSION
  });
})();
