'use strict';

/**
 * Sistema modular de relatórios de batalha.
 *
 * Responsabilidades deste ficheiro:
 * - guardar o resumo completo de cada batalha;
 * - apresentar o relatório recebido no fim do combate;
 * - apresentar os detalhes por flanco e o assalto ao pátio;
 * - integrar os relatórios de batalha na página geral de Relatórios.
 *
 * Não altera o cálculo das batalhas, as marchas, os recursos ou a evolução dos Barões.
 */
(() => {
  const REPORT_TYPE = 'battle';
  const REPORT_VERSION = 1;
  const FLANKS = Object.freeze([
    { id: 'left', name: 'Flanco esquerdo', shortName: 'Esquerdo', icon: '◀' },
    { id: 'center', name: 'Frontal', shortName: 'Centro', icon: '◆' },
    { id: 'right', name: 'Flanco direito', shortName: 'Direito', icon: '▶' }
  ]);

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

  function cloneTroops(troops, troopMeta = {}) {
    const types = new Set([...Object.keys(troopMeta || {}), ...Object.keys(troops || {})]);
    return Object.fromEntries([...types].map(type => [type, safeNumber(troops?.[type])]));
  }

  function totalTroops(troops) {
    return Object.values(troops || {}).reduce((sum, count) => sum + safeNumber(count), 0);
  }

  function troopDifference(initial, survivors, troopMeta = {}) {
    const result = cloneTroops(initial, troopMeta);
    Object.keys(result).forEach(type => {
      result[type] = Math.max(0, safeNumber(initial?.[type]) - safeNumber(survivors?.[type]));
    });
    return result;
  }

  function normalizeLoot(loot) {
    return {
      wood: safeNumber(loot?.wood),
      stone: safeNumber(loot?.stone),
      food: safeNumber(loot?.food),
      coins: safeNumber(loot?.coins)
    };
  }

  function normalizeSector(source, troopMeta = {}) {
    return {
      id: String(source?.id || ''),
      name: String(source?.name || ''),
      wallBonus: safeNumber(source?.wallBonus),
      gateBonus: safeNumber(source?.gateBonus),
      rangedBonus: safeNumber(source?.rangedBonus),
      defenseTools: source?.defenseTools ? (globalThis.ReinosFalkenDefenseTools?.normalizeToolMap?.(source.defenseTools) || source.defenseTools) : null,
      baseBonuses: {
        wall: safeNumber(source?.baseBonuses?.wall),
        gate: safeNumber(source?.baseBonuses?.gate),
        ranged: safeNumber(source?.baseBonuses?.ranged)
      },
      toolBonuses: {
        wall: safeNumber(source?.toolBonuses?.wall),
        gate: safeNumber(source?.toolBonuses?.gate),
        ranged: safeNumber(source?.toolBonuses?.ranged)
      },
      units: cloneTroops(source?.units, troopMeta)
    };
  }

  function normalizeBattleData(payload, context) {
    const troopMeta = context.getTroopsMeta?.() || {};
    const sent = cloneTroops(payload.troopsSent, troopMeta);
    const survived = cloneTroops(payload.troopsSurvived, troopMeta);
    const attackBySector = {};
    const defenseInitial = {};
    const defenseFinal = {};

    FLANKS.forEach(flank => {
      const attack = payload.attackBySector?.[flank.id] || {};
      attackBySector[flank.id] = {
        sent: cloneTroops(attack.sent, troopMeta),
        wallSurvivors: cloneTroops(attack.wallSurvivors, troopMeta),
        toolsUsed: globalThis.ReinosSiegeTools?.normalizeToolMap?.(attack.toolsUsed) || {},
        toolReductions: {
          wall: safeNumber(attack.toolReductions?.wall),
          gate: safeNumber(attack.toolReductions?.gate),
          ranged: safeNumber(attack.toolReductions?.ranged)
        }
      };
      defenseInitial[flank.id] = normalizeSector(payload.defenseInitial?.[flank.id] || { id: flank.id, name: flank.name }, troopMeta);
      defenseFinal[flank.id] = normalizeSector(payload.defenseFinal?.[flank.id] || { id: flank.id, name: flank.name }, troopMeta);
    });

    return {
      version: REPORT_VERSION,
      victory: Boolean(payload.victory),
      attackerName: String(payload.attackerName || context.getCurrentUser?.()?.username || 'Atacante'),
      attackerKingdom: String(payload.attackerKingdom || context.getProfile?.()?.kingdomName || ''),
      attackerLevel: Math.max(1, safeNumber(payload.attackerLevel) || 1),
      defenderName: String(payload.defenderName || 'Barão Falken'),
      defenderLevel: Math.max(1, safeNumber(payload.defenderLevel) || 1),
      coordinates: {
        x: Math.round(Number(payload.coordinates?.x) || 0),
        y: Math.round(Number(payload.coordinates?.y) || 0)
      },
      wavesUsed: safeNumber(payload.wavesUsed),
      usedFlanks: [...new Set((payload.usedFlanks || []).filter(id => FLANKS.some(flank => flank.id === id)))],
      breachedFlanks: [...new Set((payload.breachedFlanks || []).filter(id => FLANKS.some(flank => flank.id === id)))],
      courtyardBonus: Number(payload.courtyardBonus) || 0,
      honorDelta: Math.trunc(Number(payload.honorDelta) || 0),
      xpGained: safeNumber(payload.xpGained),
      loot: normalizeLoot(payload.loot),
      troopsSent: sent,
      troopsSurvived: survived,
      troopsLost: troopDifference(sent, survived, troopMeta),
      toolsUsed: globalThis.ReinosSiegeTools?.normalizeToolMap?.(payload.toolsUsed) || {},
      equipmentDrop: normalizeEquipmentDrop(payload.equipmentDrop),
      attackBySector,
      defenseInitial,
      defenseFinal,
      courtyard: {
        attackersEntered: cloneTroops(payload.courtyard?.attackersEntered, troopMeta),
        attackersSurvived: cloneTroops(payload.courtyard?.attackersSurvived, troopMeta),
        defendersBefore: safeNumber(payload.courtyard?.defendersBefore),
        defendersAfter: safeNumber(payload.courtyard?.defendersAfter),
        attackPower: safeNumber(payload.courtyard?.attackPower),
        defensePower: safeNumber(payload.courtyard?.defensePower)
      }
    };
  }

  function findReport(context, reportId) {
    return context.getProfile?.()?.reports?.find(report => report.id === reportId) || null;
  }

  function resourceLine(resources, context) {
    if (globalThis.ReinosResourceIcons?.line) {
      return globalThis.ReinosResourceIcons.line(resources, context.format);
    }
    return `Madeira ${context.format(resources.wood)} · Pedra ${context.format(resources.stone)} · Comida ${context.format(resources.food)} · Moedas ${context.format(resources.coins)}`;
  }

  function totalTools(tools) {
    return Object.values(tools || {}).reduce((sum, count) => sum + safeNumber(count), 0);
  }

  function toolChips(tools, context) {
    const catalog = globalThis.ReinosSiegeTools?.CATALOG || {};
    const rows = Object.entries(catalog).filter(([type]) => safeNumber(tools?.[type]) > 0).map(([type, tool]) => `<span class="battle-tool-chip">${globalThis.ReinosSiegeTools.icon(type, 'normal')}<b>${context.format(tools[type])}</b><small>${context.escapeHtml(tool.name)}</small></span>`);
    return rows.length ? rows.join('') : '<span class="battle-tool-none">Sem ferramentas</span>';
  }

  function resourceCards(resources, context) {
    const types = ['wood', 'stone', 'food', 'coins'];
    return types.map(type => {
      const icon = globalThis.ReinosResourceIcons?.icon?.(type) || '◆';
      return `<div class="battle-loot-card">${icon}<b>${context.format(resources?.[type] || 0)}</b></div>`;
    }).join('');
  }

  function troopRows(troops, context, compact = false) {
    const troopMeta = context.getTroopsMeta?.() || {};
    const entries = Object.entries(troopMeta).map(([type, meta]) => ({
      type,
      meta,
      count: safeNumber(troops?.[type])
    }));
    const visible = compact ? entries.filter(entry => entry.count > 0) : entries;
    if (!visible.length) return '<div class="battle-empty-troops">Sem tropas</div>';
    return visible.map(({ meta, count }) => `<div class="battle-troop-row"><span>${meta.icon || '⚔️'} ${context.escapeHtml(meta.name || '')}</span><b>${context.format(count)}</b></div>`).join('');
  }

  function troopChips(troops, context) {
    const troopMeta = context.getTroopsMeta?.() || {};
    const rows = Object.entries(troopMeta)
      .map(([type, meta]) => ({ meta, count: safeNumber(troops?.[type]) }))
      .filter(item => item.count > 0);
    if (!rows.length) return '<span class="battle-troop-chip empty">0</span>';
    return rows.map(({ meta, count }) => `<span class="battle-troop-chip" title="${context.escapeHtml(meta.name)}">${meta.icon || '⚔️'} <b>${context.format(count)}</b></span>`).join('');
  }

  function normalizeEquipmentDrop(item) {
    if (!item || typeof item !== 'object') return null;
    const stats = {};
    Object.entries(item.stats || {}).forEach(([key, value]) => {
      const num = Number(value);
      if (Number.isFinite(num) && num > 0) stats[key] = Math.round(num);
    });
    return {
      id: String(item.id || ''),
      name: String(item.name || 'Equipamento encontrado'),
      role: item.role === 'governors' ? 'governors' : 'commanders',
      slot: String(item.slot || ''),
      rarity: String(item.rarity || 'common'),
      setId: item.setId ? String(item.setId) : '',
      level: Math.max(1, safeNumber(item.level) || 1),
      icon: String(item.icon || '🎁'),
      source: String(item.source || 'Barão Falken'),
      stats
    };
  }

  function equipmentTextMeta(item) {
    const system = globalThis.ReinosEquipmentSystem || {};
    const slot = system.SLOTS?.[item.slot]?.name || item.slot || 'Peça';
    const rarity = system.RARITIES?.[item.rarity]?.name || item.rarity || 'Comum';
    const rarityColor = system.RARITIES?.[item.rarity]?.color || '#b8873c';
    const set = item.setId ? system.EQUIPMENT_SETS?.[item.setId] : null;
    const role = item.role === 'governors' ? 'Governador' : 'Comandante';
    return { slot, rarity, rarityColor, set, role };
  }

  const EQUIPMENT_STAT_LABELS = Object.freeze({
    meleeAttack: ['Ataque corpo a corpo', '%'],
    rangedAttack: ['Ataque à distância', '%'],
    wallReduction: ['Redução de muralha', '%'],
    gateReduction: ['Redução de portão', '%'],
    travelSpeed: ['Velocidade de viagem', '%'],
    lootBonus: ['Saque obtido', '%'],
    findEquipment: ['Encontrar equipamento', '%'],
    meleeDefense: ['Defesa corpo a corpo', '%'],
    rangedDefense: ['Defesa à distância', '%'],
    wallDefense: ['Bónus de muralha', '%'],
    gateDefense: ['Bónus de portão', '%'],
    resourceProtection: ['Proteção de recursos', '%'],
    publicOrder: ['Ordem pública', '']
  });

  function equipmentStatsHtml(item, context, limit = 4) {
    const rows = Object.entries(item.stats || {})
      .filter(([, value]) => Number(value) > 0)
      .slice(0, limit)
      .map(([key, value]) => {
        const [label, suffix] = EQUIPMENT_STAT_LABELS[key] || [key, ''];
        return `<span><b>+${context.format(value)}${suffix}</b> ${context.escapeHtml(label)}</span>`;
      });
    return rows.length ? rows.join('') : '<span>Sem bónus visíveis</span>';
  }

  function equipmentRewardSection(data, context) {
    const item = data.equipmentDrop;
    if (!item) return '';
    const meta = equipmentTextMeta(item);
    return `<section class="battle-equipment-section" style="--equipment-rarity:${meta.rarityColor}">
      <h4>Equipamento encontrado</h4>
      <div class="battle-equipment-card">
        <div class="battle-equipment-icon">${context.escapeHtml(item.icon)}</div>
        <div class="battle-equipment-info">
          <small>${context.escapeHtml(meta.rarity)} · ${context.escapeHtml(meta.slot)} · Nv. ${context.format(item.level)}</small>
          <strong>${context.escapeHtml(item.name)}</strong>
          <em>${context.escapeHtml(meta.role)}${meta.set ? ` · ${context.escapeHtml(meta.set.name)}` : ''}</em>
          <div class="battle-equipment-stats">${equipmentStatsHtml(item, context)}</div>
        </div>
      </div>
      <small>A peça foi enviada para o teu inventário de equipamentos.</small>
    </section>`;
  }

  function create(context, payload, options = {}) {
    const profile = context.getProfile?.();
    if (!profile) return null;
    const data = normalizeBattleData(payload, context);
    const sentTotal = totalTroops(data.troopsSent);
    const lostTotal = totalTroops(data.troopsLost);
    const report = {
      id: context.uid('battle'),
      at: context.now(),
      title: `Batalha: ${data.defenderName} • Nv. ${data.defenderLevel}`,
      result: data.victory ? 'win' : 'loss',
      reportType: REPORT_TYPE,
      targetId: String(payload.targetId || ''),
      targetName: data.defenderName,
      targetLevel: data.defenderLevel,
      targetCoordinates: { ...data.coordinates },
      text: data.victory
        ? `Vitória com ${context.format(sentTotal)} tropas enviadas e ${context.format(lostTotal)} baixas.${data.equipmentDrop ? ` Equipamento encontrado: ${data.equipmentDrop.name}.` : ''}`
        : `Derrota com ${context.format(sentTotal)} tropas enviadas e ${context.format(lostTotal)} baixas.`,
      battleData: data
    };
    profile.reports.push(report);
    if (options.open !== false) openSummary(context, report.id);
    return report;
  }

  function summaryMessage(data) {
    if (data.victory) {
      return 'As tuas tropas venceram a batalha. Os sobreviventes e o saque estão agora a regressar ao teu castelo.';
    }
    return 'O ataque foi derrotado. As tropas sobreviventes estão a regressar ao teu castelo.';
  }

  function openSummary(context, reportId) {
    const report = findReport(context, reportId);
    if (!report?.battleData) return;
    const data = report.battleData;
    const sentTotal = totalTroops(data.troopsSent);
    const survivedTotal = totalTroops(data.troopsSurvived);
    const lostTotal = totalTroops(data.troopsLost);
    const defenseInitialTotal = FLANKS.reduce((sum, flank) => sum + totalTroops(data.defenseInitial?.[flank.id]?.units), 0);
    const defenseFinalTotal = FLANKS.reduce((sum, flank) => sum + totalTroops(data.defenseFinal?.[flank.id]?.units), 0);
    const defenseLostTotal = Math.max(0, defenseInitialTotal - defenseFinalTotal);
    const title = data.victory ? 'Vitória gloriosa!' : 'Derrota no campo de batalha';

    context.openModal(
      title,
      `<div class="battle-report-sheet ${data.victory ? 'victory' : 'defeat'}">
        <header class="battle-report-ribbon">
          <h2>${title}</h2>
          <span>A batalha de ${context.escapeHtml(data.defenderName)}</span>
        </header>
        <div class="battle-report-meta">
          <div><b>X ${data.coordinates.x} • Y ${data.coordinates.y}</b><small>${new Date(report.at).toLocaleString('pt-PT')}</small></div>
          <div class="battle-report-result-seal">${data.victory ? '🏆' : '⚔️'}</div>
        </div>
        <div class="battle-report-scene" aria-hidden="true">
          <div class="battle-scene-army">🛡️ ⚔️ 🏹</div>
          <div class="battle-scene-fortress">🏰</div>
        </div>
        <div class="battle-summary-grid">
          <section class="battle-lord-card attacker">
            <small>Atacante</small><h3>${context.escapeHtml(data.attackerName)}</h3>
            <span>${context.escapeHtml(data.attackerKingdom || 'Castelo do jogador')}</span>
            <div class="battle-big-stat"><b>${context.format(sentTotal)}</b><small>tropas enviadas</small></div>
            <div class="battle-mini-stats"><span>Sobreviventes <b>${context.format(survivedTotal)}</b></span><span>Baixas <b>${context.format(lostTotal)}</b></span></div>
          </section>
          <section class="battle-result-card">
            <div><span>Experiência</span><b>+${context.format(data.xpGained)}</b></div>
            <div><span>Honra</span><b class="${data.honorDelta >= 0 ? 'positive' : 'negative'}">${data.honorDelta >= 0 ? '+' : ''}${context.format(data.honorDelta)}</b></div>
            <div><span>Vagas usadas</span><b>${context.format(data.wavesUsed)}</b></div>
            <div><span>Brechas abertas</span><b>${context.format(data.breachedFlanks.length)}</b></div>
            <div><span>Ferramentas usadas</span><b>${context.format(totalTools(data.toolsUsed))}</b></div>
          </section>
          <section class="battle-lord-card defender">
            <small>Defensor</small><h3>${context.escapeHtml(data.defenderName)}</h3>
            <span>Nível ${context.format(data.defenderLevel)}</span>
            <div class="battle-big-stat"><b>${context.format(defenseInitialTotal)}</b><small>defensores encontrados</small></div>
            <div class="battle-mini-stats"><span>Restantes <b>${context.format(data.victory ? 0 : defenseFinalTotal)}</b></span><span>Baixas <b>${context.format(data.victory ? defenseInitialTotal : defenseLostTotal)}</b></span></div>
          </section>
        </div>
        <section class="battle-loot-section">
          <h4>Saque</h4><div class="battle-loot-grid">${resourceCards(data.loot, context)}</div>
          <small>${data.victory ? 'O saque será recebido quando o exército regressar ao castelo.' : 'Não foi obtido qualquer saque.'}</small>
        </section>
        ${equipmentRewardSection(data, context)}
        <p class="battle-report-message">${summaryMessage(data)}</p>
      </div>`,
      `<button class="secondary-btn" data-action="modal-close">Fechar</button>
       <button class="action-btn" data-action="battle-report-details" data-report-id="${context.escapeHtml(report.id)}">📋 Detalhes</button>`
    );
    document.querySelector('.modal')?.classList.add('battle-report-modal');
  }

  function sectorCard(flank, data, context) {
    const attack = data.attackBySector?.[flank.id] || {};
    const defenseInitial = data.defenseInitial?.[flank.id] || {};
    const defenseFinal = data.defenseFinal?.[flank.id] || {};
    const attackersSent = cloneTroops(attack.sent, context.getTroopsMeta?.());
    const attackersAfterWall = cloneTroops(attack.wallSurvivors, context.getTroopsMeta?.());
    const attackersLost = troopDifference(attackersSent, attackersAfterWall, context.getTroopsMeta?.());
    const defendersInitial = cloneTroops(defenseInitial.units, context.getTroopsMeta?.());
    const defendersFinal = cloneTroops(defenseFinal.units, context.getTroopsMeta?.());
    const defendersLost = troopDifference(defendersInitial, defendersFinal, context.getTroopsMeta?.());
    const breached = data.breachedFlanks.includes(flank.id);
    const used = data.usedFlanks.includes(flank.id);

    return `<article class="battle-sector-card ${breached ? 'breached' : ''} ${used ? 'used' : 'unused'}">
      <header><span>${flank.icon}</span><h4>${context.escapeHtml(flank.name)}</h4><b>${breached ? 'Brecha' : used ? 'Resistiu' : 'Não atacado'}</b></header>
      <div class="battle-fort-bonuses">
        <span>🧱 +${context.format(defenseInitial.wallBonus || 0)}%</span>
        ${defenseInitial.gateBonus ? `<span>🚪 +${context.format(defenseInitial.gateBonus)}%</span>` : ''}
        <span>🏹 +${context.format(defenseInitial.rangedBonus || 0)}%</span>
      </div>
      ${globalThis.ReinosFalkenDefenseTools?.sectorSummaryHtml?.(defenseInitial, context) || ''}
      <div class="battle-sector-tools">${toolChips(attack.toolsUsed, context)}${totalTools(attack.toolsUsed) ? `<small>Reduções: muralha −${context.format(attack.toolReductions?.wall || 0)}% · portão −${context.format(attack.toolReductions?.gate || 0)}% · distância −${context.format(attack.toolReductions?.ranged || 0)}%</small>` : ''}</div>
      <div class="battle-sector-versus">
        <div class="battle-side attack-side">
          <h5>Atacante</h5>
          <div class="battle-sector-total">${context.format(totalTroops(attackersSent))}</div>
          <div class="battle-chip-row">${troopChips(attackersSent, context)}</div>
          <small>Baixas: ${context.format(totalTroops(attackersLost))}</small>
          <small>Passaram: ${context.format(totalTroops(attackersAfterWall))}</small>
        </div>
        <div class="battle-sector-arrow">⚔️</div>
        <div class="battle-side defense-side">
          <h5>Defensor</h5>
          <div class="battle-sector-total">${context.format(totalTroops(defendersInitial))}</div>
          <div class="battle-chip-row">${troopChips(defendersInitial, context)}</div>
          <small>Baixas: ${context.format(totalTroops(defendersLost))}</small>
          <small>Restantes: ${context.format(totalTroops(defendersFinal))}</small>
        </div>
      </div>
    </article>`;
  }

  function openDetails(context, reportId) {
    const report = findReport(context, reportId);
    if (!report?.battleData) return;
    const data = report.battleData;
    const courtyardAttackers = data.courtyard.attackersEntered;
    const courtyardSurvivors = data.courtyard.attackersSurvived;
    const courtyardLosses = troopDifference(courtyardAttackers, courtyardSurvivors, context.getTroopsMeta?.());
    const bonusPercent = Math.round((Number(data.courtyardBonus) || 0) * 100);

    context.openModal(
      `Detalhes — ${context.escapeHtml(data.defenderName)}`,
      `<div class="battle-details-sheet">
        <header class="battle-details-head">
          <div><small>Alvo</small><b>${context.escapeHtml(data.defenderName)} • Nv. ${context.format(data.defenderLevel)}</b></div>
          <div><small>Coordenadas</small><b>X ${data.coordinates.x} • Y ${data.coordinates.y}</b></div>
          <div><small>Data</small><b>${new Date(report.at).toLocaleString('pt-PT')}</b></div>
          <div class="battle-detail-outcome ${data.victory ? 'victory' : 'defeat'}">${data.victory ? 'Vitória' : 'Derrota'}</div>
        </header>
        <div class="battle-detail-sectors">${FLANKS.map(flank => sectorCard(flank, data, context)).join('')}</div>
        <section class="battle-courtyard-card ${data.victory ? 'victory' : 'defeat'}">
          <header><h4>Assalto ao pátio</h4><span>Bónus de flancos: ${bonusPercent >= 0 ? '+' : ''}${bonusPercent}%</span></header>
          <div class="battle-courtyard-versus">
            <div>
              <small>Atacantes que entraram</small><b>${context.format(totalTroops(courtyardAttackers))}</b>
              <div class="battle-chip-row">${troopChips(courtyardAttackers, context)}</div>
              <span>Baixas no pátio: ${context.format(totalTroops(courtyardLosses))}</span>
            </div>
            <div class="battle-courtyard-result">${data.victory ? '🏆' : '🛡️'}<strong>${data.victory ? 'Pátio conquistado' : 'Ataque repelido'}</strong></div>
            <div>
              <small>Força defensiva</small><b>${context.format(data.courtyard.defensePower)}</b>
              <span>Defensores antes: ${context.format(data.courtyard.defendersBefore)}</span>
              <span>Defensores depois: ${context.format(data.courtyard.defendersAfter)}</span>
            </div>
          </div>
        </section>
        ${equipmentRewardSection(data, context)}
        <details class="battle-full-breakdown">
          <summary>Ver totais por tipo de tropa</summary>
          <div class="battle-breakdown-grid">
            <section><h4>Tropas enviadas</h4>${troopRows(data.troopsSent, context)}</section>
            <section><h4>Tropas sobreviventes</h4>${troopRows(data.troopsSurvived, context)}</section>
            <section><h4>Baixas</h4>${troopRows(data.troopsLost, context)}</section>
            <section><h4>Ferramentas consumidas</h4><div class="battle-tools-breakdown">${toolChips(data.toolsUsed, context)}</div></section>
          </div>
        </details>
      </div>`,
      `<button class="secondary-btn" data-action="battle-report-open" data-report-id="${context.escapeHtml(report.id)}">← Voltar ao relatório</button>
       <button class="action-btn" data-action="modal-close">Concluir</button>`
    );
    document.querySelector('.modal')?.classList.add('battle-details-modal');
  }

  function reportPresentation(report, context) {
    if (report?.reportType !== REPORT_TYPE || !report.battleData) return null;
    const data = report.battleData;
    return {
      label: data.victory ? 'Vitória' : 'Derrota',
      className: data.victory ? 'report-win' : 'report-loss',
      detailsHtml: `<div class="battle-report-table-summary">${context.escapeHtml(report.text)}<small>${resourceLine(data.loot, context)}${data.equipmentDrop ? ` · 🎁 ${context.escapeHtml(data.equipmentDrop.name)}` : ''}</small></div><button class="report-open-btn battle-report-open-btn" data-action="battle-report-open" data-report-id="${context.escapeHtml(report.id)}">Abrir relatório</button>`
    };
  }

  async function handleAction(action, actionElement, context) {
    if (action === 'battle-report-open') {
      openSummary(context, actionElement.dataset.reportId);
      return true;
    }
    if (action === 'battle-report-details') {
      openDetails(context, actionElement.dataset.reportId);
      return true;
    }
    return false;
  }

  globalThis.RealmBattleReports = Object.freeze({
    REPORT_TYPE,
    REPORT_VERSION,
    create,
    openSummary,
    openDetails,
    reportPresentation,
    handleAction,
    totalTroops,
    cloneTroops,
    troopDifference
  });
})();
