'use strict';

(function () {
  const LAYOUT_CLASS = 'gge-layout-active';

  function text(selector, fallback = '') {
    const element = document.querySelector(selector);
    return element?.textContent?.trim() || fallback;
  }

  function currentViewLabel() {
    const active = document.querySelector('.nav-btn.active span:not(.nav-icon)');
    return active?.textContent?.trim() || 'Castelo';
  }

  function attachPlayerLevel() {
    const card = document.querySelector('.player-card');
    const level = text('#player-level', '1');
    if (card) card.setAttribute('data-gge-level', level);
  }

  function ensureEventsDock(shell) {
    shell.querySelectorAll('.gge-tax-button').forEach(button => button.remove());
    shell.querySelectorAll('.gge-events-dock').forEach(dock => dock.remove());
    shell.querySelectorAll('.gge-daily-reward-dock').forEach(dock => dock.remove());

    if (!shell.querySelector('.gge-location-pill')) {
      shell.insertAdjacentHTML('beforeend', `
        <div class="gge-location-pill" data-action="location-menu-open" role="button" title="Selecionar local">
          <span id="gge-location-label">Castelo</span>
          <button type="button" data-action="location-menu-open" title="Selecionar local">▲</button>
        </div>`);
    }
  }

  function updateDailyRewardBadge(shell) {
    const updater = globalThis.ReinosUpdateDailyRewardIndicators;
    if (typeof updater === 'function') {
      updater();
      return;
    }
  }

  function updateLocation() {
    const label = document.querySelector('#gge-location-label');
    if (!label) return;
    const gameLabel = globalThis.ReinosGetCurrentLocationLabel?.();
    if (gameLabel) {
      label.textContent = gameLabel;
      return;
    }
    const kingdom = text('#kingdom-label', 'Castelo');
    const view = currentViewLabel();
    label.textContent = view === 'Castelo' ? kingdom : view;
  }

  function enhance() {
    const shell = document.querySelector('.game-shell');
    if (!shell) {
      document.body.classList.remove(LAYOUT_CLASS);
      return;
    }
    document.body.classList.add(LAYOUT_CLASS);
    ensureEventsDock(shell);
    updateDailyRewardBadge(shell);
    attachPlayerLevel();
    updateLocation();
  }

  let frame = 0;
  function scheduleEnhance() {
    cancelAnimationFrame(frame);
    frame = requestAnimationFrame(enhance);
  }

  const observer = new MutationObserver(scheduleEnhance);
  observer.observe(document.documentElement, { childList: true, subtree: true });
  document.addEventListener('click', scheduleEnhance, true);
  window.addEventListener('resize', scheduleEnhance);
  setInterval(scheduleEnhance, 30000);

  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', enhance, { once: true });
  } else {
    enhance();
  }
})();
