'use strict';

/**
 * Sistema do Mercado.
 *
 * Responsabilidades:
 * - permitir enviar recursos a outros jogadores através do edifício Mercado;
 * - calcular capacidade das carroças pelo nível do Mercado;
 * - deixar o backend criar e resolver a marcha de transporte para que o destino
 *   receba os recursos mesmo com clientes fechados.
 */
(() => {
  const VERSION = 1;
  const RESOURCE_KEYS = ['wood', 'stone', 'food', 'coins'];

  function safeInt(value) {
    return Math.max(0, Math.floor(Number(value) || 0));
  }

  function marketplaceLevel(profile) {
    return Math.max(0, ...(profile?.buildings || [])
      .filter(building => building.type === 'marketplace' && building.status !== 'constructing')
      .map(building => safeInt(building.level)));
  }

  function cartCapacity(level) {
    const safeLevel = Math.max(1, safeInt(level) || 1);
    return 1000 + (safeLevel - 1) * 700;
  }

  function totalResources(resources) {
    return RESOURCE_KEYS.reduce((sum, key) => sum + safeInt(resources?.[key]), 0);
  }

  function availablePlayers(context, presetTargetUserId = '') {
    const db = context.getDb?.() || {};
    const current = context.getCurrentUser?.();
    const profiles = db.profiles || {};
    return (Array.isArray(db.users) ? db.users : [])
      .filter(user => user?.id && user.id !== current?.id && profiles[user.id])
      .sort((a, b) => String(a.username || '').localeCompare(String(b.username || ''), 'pt'))
      .map(user => {
        const profile = profiles[user.id] || {};
        return {
          id: user.id,
          username: user.username || 'Jogador',
          kingdomName: profile.kingdomName || `Reino de ${user.username || 'Jogador'}`,
          selected: user.id === presetTargetUserId
        };
      });
  }

  function resourceIcon(context, key) {
    return context.resources?.[key]?.icon || key;
  }

  function resourceName(context, key) {
    return context.resources?.[key]?.name || key;
  }

  function resourceLine(context, resources) {
    return RESOURCE_KEYS
      .filter(key => safeInt(resources?.[key]) > 0)
      .map(key => `${resourceIcon(context, key)} ${context.format(safeInt(resources[key]))}`)
      .join(' · ') || 'Sem carga';
  }

  function resourceLineText(context, resources) {
    return RESOURCE_KEYS
      .filter(key => safeInt(resources?.[key]) > 0)
      .map(key => `${resourceName(context, key)} ${context.format(safeInt(resources[key]))}`)
      .join(' · ') || 'Sem carga';
  }

  function buildingPanel(context, building) {
    if (!building || building.type !== 'marketplace') return '';
    const level = marketplaceLevel(context.getProfile?.());
    const capacity = cartCapacity(level || building.level || 1);
    return `<div class="market-building-panel">
      <div>
        <strong>Carroças do Mercado</strong>
        <small>Capacidade por envio: ${context.format(capacity)} recursos</small>
      </div>
      <button class="action-btn" data-action="market-open">Enviar recursos</button>
    </div>`;
  }

  function selectedTargetHtml(context, player) {
    if (!player) return '<small>Escolhe um jogador para enviar recursos.</small>';
    return `<small>Destino: <strong>${context.escapeHtml(player.kingdomName)}</strong> • Jogador ${context.escapeHtml(player.username)}</small>`;
  }

  function openSendModal(context, presetTargetUserId = '') {
    const profile = context.getProfile?.();
    const marketLevel = marketplaceLevel(profile);
    if (marketLevel < 1) {
      context.toast('Precisas de um Mercado construído para enviar recursos.', 'error');
      return;
    }
    const players = availablePlayers(context, presetTargetUserId);
    if (!players.length) {
      context.openModal('Enviar recursos', '<p>Ainda não existem outros jogadores no servidor para receber recursos.</p>', '<button class="action-btn" data-action="modal-close">Fechar</button>');
      return;
    }
    const selectedId = players.some(player => player.selected) ? presetTargetUserId : players[0].id;
    const selected = players.find(player => player.id === selectedId) || players[0];
    const capacity = cartCapacity(marketLevel);
    const options = players.map(player => `<option value="${context.escapeHtml(player.id)}" ${player.id === selected.id ? 'selected' : ''}>${context.escapeHtml(player.kingdomName)} — ${context.escapeHtml(player.username)}</option>`).join('');
    const rows = RESOURCE_KEYS.map(key => `<label class="market-resource-row">
      <span>${resourceIcon(context, key)} ${context.escapeHtml(resourceName(context, key))}</span>
      <input class="market-resource-input" data-resource="${key}" type="number" min="0" step="1" value="0" max="${safeInt(profile.resources?.[key])}" />
      <small>Disponível: ${context.format(safeInt(profile.resources?.[key]))}</small>
    </label>`).join('');

    context.openModal('Enviar recursos pelo Mercado', `
      <div class="market-send-modal">
        <p>As carroças levam os recursos até outro jogador. O destino só recebe quando a marcha chegar.</p>
        <div class="field">
          <label>Jogador destino</label>
          <select id="market-target-user" data-action="market-destination-change">${options}</select>
          <div class="market-selected-target">${selectedTargetHtml(context, selected)}</div>
        </div>
        <div class="market-capacity-card">
          <span>⚖️ Mercado Nv. ${marketLevel}</span>
          <strong>Capacidade: ${context.format(capacity)}</strong>
          <small data-market-total>Selecionado: 0 / ${context.format(capacity)}</small>
        </div>
        <div class="market-resource-grid">${rows}</div>
        <p class="market-note">O envio normal respeita a capacidade das carroças e os recursos disponíveis do teu castelo.</p>
      </div>`,
      '<button class="secondary-btn" data-action="modal-close">Cancelar</button><button class="action-btn" data-action="market-send-confirm">Enviar recursos</button>');
    document.querySelector('.modal')?.classList.add('market-modal');
    updateTotal(context);
  }

  function readSelectedResources() {
    const resources = {};
    document.querySelectorAll('.market-resource-input').forEach(input => {
      const key = input.dataset.resource;
      if (!RESOURCE_KEYS.includes(key)) return;
      resources[key] = safeInt(input.value);
    });
    return resources;
  }

  function updateTotal(context) {
    const profile = context.getProfile?.();
    const capacity = cartCapacity(marketplaceLevel(profile));
    const resources = readSelectedResources();
    const total = totalResources(resources);
    const totalEl = document.querySelector('[data-market-total]');
    if (totalEl) {
      totalEl.textContent = `Selecionado: ${context.format(total)} / ${context.format(capacity)}`;
      totalEl.classList.toggle('is-over', total > capacity);
    }
  }

  async function send(context) {
    const targetUserId = String(document.querySelector('#market-target-user')?.value || '').trim();
    const resources = readSelectedResources();
    const total = totalResources(resources);
    const profile = context.getProfile?.();
    const capacity = cartCapacity(marketplaceLevel(profile));
    if (!targetUserId) return context.toast('Escolhe o jogador destino.', 'error');
    if (total < 1) return context.toast('Escolhe pelo menos 1 recurso para enviar.', 'error');
    if (total > capacity) return context.toast(`As carroças só conseguem levar ${context.format(capacity)} recursos.`, 'error');
    for (const key of RESOURCE_KEYS) {
      if (safeInt(resources[key]) > safeInt(profile.resources?.[key])) {
        return context.toast(`Não tens ${resourceName(context, key)} suficiente.`, 'error');
      }
    }
    try {
      const result = await context.sendResources(targetUserId, resources);
      const sent = result?.sent || resources;
      context.closeModal();
      context.renderGame();
      context.toast(`Transporte enviado: ${resourceLineText(context, sent)}.`, 'success');
    } catch (error) {
      context.toast(error?.message || 'Não foi possível enviar recursos.', 'error');
    }
  }

  function openMission(context, mission) {
    const resources = mission.resources || mission.deliveredResources || {};
    const state = mission.state === 'returning' ? 'As carroças estão a regressar.' : 'As carroças estão a caminho do destino.';
    context.openModal(`Transporte para ${context.escapeHtml(mission.targetName || 'jogador')}`, `
      <div class="market-mission-card">
        <div class="stats-line"><span>Estado</span><strong>${context.escapeHtml(state)}</strong></div>
        <div class="stats-line"><span>Carga</span><strong>${resourceLine(context, resources)}</strong></div>
        <div class="stats-line"><span>Partida</span><strong>${context.escapeHtml(new Date(Number(mission.launchStartedAt || mission.startedAt || context.now())).toLocaleString('pt-PT'))}</strong></div>
        <div class="stats-line"><span>Chegada prevista</span><strong>${context.escapeHtml(new Date(Number(mission.endAt || context.now())).toLocaleString('pt-PT'))}</strong></div>
        <div class="stats-line"><span>Tempo restante</span><strong data-countdown="${Number(mission.endAt || context.now())}">${context.formatTime(Number(mission.endAt || context.now()) - context.now())}</strong></div>
      </div>`, '<button class="action-btn" data-action="modal-close">Fechar</button>');
  }

  async function handleAction(action, element, context) {
    if (action === 'market-open') {
      openSendModal(context);
      return true;
    }
    if (action === 'market-destination-change') {
      return true;
    }
    if (action === 'market-send-confirm') {
      await send(context);
      return true;
    }
    if (action === 'mission-open') {
      const mission = (context.getProfile?.()?.missions || []).find(item => item.id === element.dataset.id);
      if (mission?.type === 'market_transport') {
        openMission(context, mission);
        return true;
      }
    }
    return false;
  }

  const contextStore = { last: null };

  document.addEventListener('input', event => {
    if (!event.target?.classList?.contains('market-resource-input')) return;
    if (contextStore.last) updateTotal(contextStore.last);
  });

  document.addEventListener('change', event => {
    if (event.target?.id !== 'market-target-user' || !contextStore.last) return;
    const players = availablePlayers(contextStore.last, String(event.target.value || ''));
    const selected = players.find(player => player.selected) || players[0];
    const targetLine = document.querySelector('.market-selected-target');
    if (targetLine) targetLine.innerHTML = selectedTargetHtml(contextStore.last, selected);
  });

  const api = {
    VERSION,
    marketplaceLevel,
    cartCapacity,
    buildingPanel,
    openSendModal(context, presetTargetUserId = '') {
      contextStore.last = context;
      openSendModal(context, presetTargetUserId);
    },
    async handleAction(action, element, context) {
      contextStore.last = context;
      return handleAction(action, element, context);
    }
  };

  globalThis.ReinosMarketSystem = Object.freeze(api);
})();
