// source --> https://elanillounico.com/wp-content/plugins/juego-buen-saqueador/assets/js/buen-saqueador.js?ver=0.4.11 
(function(){
'use strict';

const $ = (s, c = document) => c.querySelector(s);
const $$ = (s, c = document) => Array.from(c.querySelectorAll(s));

const game = $('[data-bsaq-game]');
const story = $('[data-bsaq-story]');
const msg = $('[data-bsaq-message]');
const errors = $('[data-bsaq-errors]');
const hints = $('[data-bsaq-hints]');
const score = $('[data-bsaq-score]');
const aux = $('[data-bsaq-aux]');
const auxContent = $('[data-bsaq-aux-content]');
const currentCornerEl = $('[data-bsaq-current-corner]');
const hintsBox = $('[data-bsaq-hints-box]');
const startMessage = $('[data-bsaq-start-message]');

let bsaqLive = false;
let bsaqCompleted = false;
let movementMap = '';
let currentCorner = 0;
let currentResultId = 0;
let trackedFinish = false;
const track = (event, params = {}) => {
  if (typeof window.eauTrack === 'function') window.eauTrack(event, Object.assign({game_name: 'buen_saqueador', game_slug: 'buen-saqueador'}, params));
};
const hintLabels = {8367:'Pista: runas lunares',3981:'Pista: destino en el mapa',6578:'Pista: tengwar',7478:'Ayuda: quenya',2132:'Pista: acertijo',4091:'Pista: camino'};

const maps = {
  tierramedia: {
    1:{3:8},2:{3:9},3:{3:10},4:{3:11},5:{3:11,4:11},6:{2:7},
    7:{2:8,3:13,4:6},8:{1:1,2:9,3:14,4:7},9:{1:2,2:10,4:8},
    10:{1:3,2:11,3:15,4:9},11:{1:4,2:5,4:10},12:{2:13},
    13:{1:7,2:14,4:12},14:{1:8,2:18,3:18,4:13},15:{1:10,3:17,4:26},
    16:{2:17},17:{1:15,3:19,4:16},18:{1:14,2:19,3:20,4:20},
    19:{1:17,2:23,4:18},20:{1:18},21:{4:23},22:{3:24},
    23:{1:21,3:24,4:19},24:{1:23,3:25,4:22},25:{4:24},26:{2:15}
  },
  cuevas1: {
    1:{4:5},2:{3:6},3:{2:7},4:{2:5},5:{1:1,2:6,3:11,4:4},
    6:{1:2,2:7,3:8,4:5},7:{1:3,3:12,4:6},8:{1:6},9:{4:12},
    10:{2:11},11:{1:5,2:12,3:13,4:10},12:{1:7,2:9,4:11},13:{1:11}
  },
  cuevas2: {
    1:{3:14,4:14},2:{3:4},3:{2:4},4:{1:2,3:5,4:3},5:{1:4,2:6,4:14},
    6:{4:5},7:{1:14},8:{2:9,3:11,4:10},9:{4:8},10:{1:8,2:8},
    11:{1:8,3:13,4:12},12:{2:11},13:{1:11},14:{1:1,2:5,3:7}
  },
  cuevas3: {
    1:{2:2},2:{2:3,3:5,4:1},3:{4:2},4:{2:5},5:{1:2,2:6,3:7,4:4},
    6:{4:5},7:{1:5,2:10,4:8},8:{1:7,2:9,3:11},9:{4:8},10:{4:7},11:{4:8}
  }
};

function request(path, body) {
  return fetch(BSAQ.restUrl + path, {
    method: 'POST',
    headers: {'Content-Type': 'application/json', 'X-WP-Nonce': BSAQ.nonce},
    credentials: 'same-origin',
    cache: 'no-store',
    body: JSON.stringify(body || {})
  }).then(async r => {
    const data = await readJson(r);
    if (!r.ok && !data.message) data.message = 'Error de comunicación con WordPress.';
    return data;
  });
}

async function readJson(response) {
  const text = await response.text();
  if (!text) return {};
  try {
    return JSON.parse(text.replace(/^\uFEFF/, ''));
  } catch (e) {
    return {};
  }
}

function refreshSession() {
  return fetch(BSAQ.restUrl + 'bootstrap', {
    method: 'GET',
    credentials: 'same-origin',
    cache: 'no-store'
  }).then(async r => {
    const data = await readJson(r);
    if (r.ok && data.nonce) BSAQ.nonce = data.nonce;
    if (r.ok) {
      BSAQ.currentUserId = data.currentUserId || 0;
      BSAQ.isLoggedIn = !!data.isLoggedIn;
    }
    return data;
  });
}

function render(data) {
  if (!data || !data.ok) {
    if (msg) msg.textContent = (data && data.message) || 'No se pudo procesar la acción.';
    return;
  }
  story.innerHTML = data.html || '';
  msg.textContent = data.message || '';
  errors.textContent = data.errors || 0;
  hints.textContent = data.hints || 0;
  score.textContent = data.score || 0;
  movementMap = data.movementMap || '';
  currentCorner = parseInt(data.currentCorner || 0, 10);
  currentResultId = parseInt(data.resultId || 0, 10);
  renderAvailableHints(data.availableHints || []);
  updateMovementUi();
  document.body.style.overflow = 'hidden';

  if (data.completed) {
    bsaqCompleted = true;
    if (!trackedFinish) {
      trackedFinish = true;
      track('game_finish', {result: 'win', score: Number(data.score || 0), turns: Number(data.errors || 0), difficulty: 'default'});
    }
    let rows = '';
    (data.ranking || []).forEach((r, i) => {
      const name = r.display_name || r.legacy_nick || r.user_login || '—';
      rows += `<tr><td>${i + 1}</td><td>${escapeHtml(name)}</td><td class="bsaq-col-errors">${r.errors}</td><td class="bsaq-col-hints">${r.hints}</td><td>${escapeHtml(r.grade_label || '—')}</td></tr>`;
    });
    auxContent.innerHTML = `<h2>Has conseguido el título de Buen Saqueador</h2><p>Errores: ${data.errors}. Pistas: ${data.hints}.</p><p>Grado: <strong>${escapeHtml(data.gradeLabel || '')}</strong></p><h3>Buenos Saqueadores</h3><table class="bsaq-ranking"><tbody>${rows}</tbody></table>`;
    aux.hidden = false;
  }
}

function renderAvailableHints(keys) {
  if (!hintsBox) return;
  hintsBox.innerHTML = '';
  if (!keys.length) {
    const p = document.createElement('p');
    p.className = 'bsaq-muted-note';
    p.textContent = 'No hay pistas específicas disponibles en esta escena.';
    hintsBox.appendChild(p);
    return;
  }
  keys.forEach(key => {
    const button = document.createElement('button');
    button.type = 'button';
    button.dataset.bsaqHint = String(key);
    button.textContent = hintLabels[key] || ('Pista ' + key);
    button.addEventListener('click', () => hint(parseInt(key, 10)));
    hintsBox.appendChild(button);
  });
}

function escapeHtml(s) {
  return String(s).replace(/[&<>'"]/g, c => ({'&':'&amp;','<':'&lt;','>':'&gt;',"'":'&#039;','"':'&quot;'}[c]));
}

function start() {
  track('game_start', {difficulty: 'default', mode: 'adventure'});
  if (startMessage) startMessage.textContent = 'Iniciando aventura...';
  refreshSession()
    .catch(() => ({}))
    .then(() => request('start'))
    .then(data => {
      if (!data || !data.ok) {
        if (startMessage) startMessage.textContent = (data && data.message) || 'No se pudo iniciar la aventura.';
        return;
      }
      if (startMessage) startMessage.textContent = '';
      bsaqLive = true;
      bsaqCompleted = false;
      game.hidden = false;
      render(data);
    })
    .catch(() => {
      if (startMessage) startMessage.textContent = 'No se pudo iniciar la aventura. Recarga la página e inténtalo de nuevo.';
    });
}

function action(type, value) {
  request('action', {type, value}).then(render);
}

function hint(key) {
  request('hint', {key}).then(data => {
    if (data.ok) {
      hints.textContent = (data.hints !== undefined) ? data.hints : hints.textContent;
      score.textContent = (data.score !== undefined) ? data.score : score.textContent;
      if (msg && data.message) msg.textContent = data.message;
      auxContent.innerHTML = '<h2>Pista</h2>' + data.html;
      aux.hidden = false;
    } else {
      msg.textContent = data.message || 'No se pudo cargar la pista.';
    }
  });
}

function updateMovementUi() {
  if (!currentCornerEl) return;
  currentCornerEl.textContent = currentCorner && movementMap ? String(currentCorner) : '—';
  $$('[data-bsaq-dir]').forEach(button => {
    const dir = parseInt(button.dataset.bsaqDir, 10);
    const available = !!(movementMap && maps[movementMap] && maps[movementMap][currentCorner] && maps[movementMap][currentCorner][dir]);
    button.disabled = !available;
  });
}

function moveDirection(dir) {
  if (!movementMap || !maps[movementMap] || !maps[movementMap][currentCorner]) return;
  const next = maps[movementMap][currentCorner][dir];
  if (!next) return;
  action('mover', String(dir));
}

$('[data-bsaq-start]')?.addEventListener('click', start);
$('[data-bsaq-open-instructions]')?.addEventListener('click', () => {$('[data-bsaq-instructions]').hidden = false;});
$('[data-bsaq-close-instructions]')?.addEventListener('click', () => {$('[data-bsaq-instructions]').hidden = true;});
$('[data-bsaq-close-aux]')?.addEventListener('click', () => {aux.hidden = true;});
$('[data-bsaq-exit]')?.addEventListener('click', () => {
  if (confirm('Si sales ahora perderás todo el progreso de esta partida. ¿Quieres salir?')) {
    request('exit').finally(() => {
      track('game_finish', {result: 'abandoned', score: Number(score && score.textContent || 0)});
      bsaqLive = false;
      game.hidden = true;
      document.body.style.overflow = '';
      story.innerHTML = '';
      movementMap = '';
      currentCorner = 0;
      currentResultId = 0;
      renderAvailableHints([]);
      updateMovementUi();
    });
  }
});
$('[data-bsaq-pronounce-form]')?.addEventListener('submit', e => {
  e.preventDefault();
  const input = e.currentTarget.elements.word;
  action('pronunciar', input.value);
  input.value = '';
});
$('[data-bsaq-submit-date]')?.addEventListener('click', () => {action('fecha', $('[data-bsaq-date]').value);});
$('[data-bsaq-use-key]')?.addEventListener('click', () => action('llave', '1624'));
$$('[data-bsaq-dir]').forEach(b => b.addEventListener('click', () => moveDirection(parseInt(b.dataset.bsaqDir, 10))));
$$('[data-bsaq-consult]').forEach(b => b.addEventListener('click', () => showConsult(b.dataset.bsaqConsult)));

document.addEventListener('submit', e => {
  if (e.target.matches('[data-bsaq-diploma-form]')) {
    e.preventDefault();
    const name = e.target.elements.name.value.trim();
    if (!name) return;
    const url = `${BSAQ.diplomaUrl}&_wpnonce=${encodeURIComponent(BSAQ.diplomaNonce)}&result_id=${encodeURIComponent(String(currentResultId || 0))}&name=${encodeURIComponent(name)}`;
    window.open(url, 'diploma_buen_saqueador', 'toolbar=0,location=0,status=1,menubar=1,scrollbars=0,resizable=1,width=720,height=529');
  }
});

function showConsult(which) {
  const base = BSAQ.assetsUrl + 'img/';
  let html = '';
  if (which === 'mapa') html = '<h2>Mapa de Dróin</h2><img class="bsaq-consult-img" src="' + base + 'mapa.gif" alt="Mapa">';
  if (which === 'runas') html = '<h2>Runas tradicionales</h2><img class="bsaq-consult-img" src="' + base + 'runas.gif" alt="Runas">';
  if (which === 'tengwar') html = '<h2>Tengwar</h2><img class="bsaq-consult-img" src="' + base + 'tengwar.gif" alt="Tengwar">';
  if (which === 'anotaciones') html = '<h2>Anotaciones</h2><img class="bsaq-consult-img" src="' + base + 'mapa_droin_girado.gif" alt="Anotaciones del mapa">';
  auxContent.innerHTML = html;
  aux.hidden = false;
}

function buildDateSelect() {
  const sel = $('[data-bsaq-date]');
  if (!sel) return;
  for (let i = 1; i <= 365; i++) {
    const o = document.createElement('option');
    o.value = String(i);
    o.textContent = 'Día ' + i;
    if (i === 102) o.textContent += ' — opción clave';
    if (i === 303) o.textContent += ' — Lithe 1';
    sel.appendChild(o);
  }
  sel.value = '303';
}

window.addEventListener('beforeunload', () => {
  if (bsaqLive && !bsaqCompleted) {
    try {
      fetch(BSAQ.restUrl + 'exit', {
        method: 'POST',
        headers: {'Content-Type':'application/json','X-WP-Nonce':BSAQ.nonce},
        credentials: 'same-origin',
        cache: 'no-store',
        body: '{}',
        keepalive: true
      });
    } catch (e) {}
  }
});

buildDateSelect();
updateMovementUi();
})();