'use strict';

(() => {
  const VERSION = 1;

  function refundFor(building, ctx) {
    const level = Math.max(1, Number(building?.level) || 1);
    const cost = ctx.buildingCost(building.type, level);
    return Object.fromEntries(Object.entries(cost).map(([type, amount]) => [type, Math.round((Number(amount) || 0) * 0.35)]));
  }

  function openConfirmation(buildingId, ctx) {
    const profile = ctx.getProfile();
    const building = profile?.buildings?.find(item => item.id === buildingId);
    if (!building || building.type === 'keep') return true;
    const definition = ctx.getBuildingsMeta()[building.type];
    if (!definition) return true;

    const image = globalThis.ReinosIllustratedBuildings?.assetFor?.(building.type, building.level || 1) || '';
    const art = image
      ? `<img src="${image}" alt="${ctx.escapeHtml(definition.name)}" draggable="false" />`
      : `<span>${definition.icon || '🏠'}</span>`;
    const refund = refundFor(building, ctx);

    ctx.openModal('Confirmar demolição', `<div class="building-demolition-confirmation">
      <div class="building-demolition-art">${art}</div>
      <div class="building-demolition-copy">
        <h3>Demolir ${ctx.escapeHtml(definition.name)}?</h3>
        <p>O edifício de <strong>nível ${Math.max(1, Number(building.level) || 1)}</strong> será eliminado definitivamente e o espaço ficará livre.</p>
        <div class="building-demolition-warning">Esta ação não pode ser anulada.</div>
        <div class="building-demolition-refund"><span>Materiais recuperados (35%)</span><div class="costs">${ctx.costsHtml(refund)}</div></div>
      </div>
    </div>`, `<button class="secondary-btn" data-action="modal-close">Cancelar</button><button class="danger-btn building-demolition-final" data-action="building-demolish-confirm" data-id="${ctx.escapeHtml(building.id)}">Sim, demolir</button>`);

    requestAnimationFrame(() => document.querySelector('#modal-root .modal')?.classList.add('building-demolition-modal'));
    return true;
  }

  async function handleAction(action, element, ctx) {
    if (action === 'building-demolish') return openConfirmation(String(element.dataset.id || ''), ctx);
    if (action === 'building-demolish-confirm') {
      const buildingId = String(element.dataset.id || '');
      const profile = ctx.getProfile();
      const building = profile?.buildings?.find(item => item.id === buildingId);
      if (!building || building.type === 'keep') {
        ctx.closeModal();
        return true;
      }
      ctx.demolishBuilding(buildingId);
      return true;
    }
    return false;
  }

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