const updateHistoryButtons = () => {
  const back = document.querySelector('#global-back');
  const forward = document.querySelector('#global-forward');
  if (!back && !forward) {return;}

  const hasHistory = window.history.length > 1;

  if (back) {
    back.setAttribute('aria-disabled', hasHistory ? 'false' : 'true');
    back.classList.toggle('is-disabled', !hasHistory);
  }
  if (forward) {
    forward.setAttribute('aria-disabled', hasHistory ? 'false' : 'true');
    forward.classList.toggle('is-disabled', !hasHistory);
  }
};

const initHistoryButtons = () => {
  const back = document.querySelector('#global-back');
  const forward = document.querySelector('#global-forward');

  const isEditableTarget = (target) => {
    if (!target) {return false;}
    if (target.isContentEditable) {return true;}
    const tag = target.tagName;
    return tag === 'INPUT' || tag === 'TEXTAREA' || tag === 'SELECT';
  };

  document.addEventListener('keydown', (event) => {
    if (!event.altKey || event.metaKey || event.ctrlKey) {return;}
    if (isEditableTarget(event.target)) {return;}
    if (event.key === 'ArrowLeft') {
      if (window.history.length > 1) {
        event.preventDefault();
        window.history.back();
      }
    } else if (event.key === 'ArrowRight') {
      if (window.history.length > 1) {
        event.preventDefault();
        window.history.forward();
      }
    }
  });

  if (back) {
    back.addEventListener('click', (event) => {
      if (window.history.length > 1) {
        event.preventDefault();
        window.history.back();
      }
    });
  }

  if (forward) {
    forward.addEventListener('click', (event) => {
      if (window.history.length > 1) {
        event.preventDefault();
        window.history.forward();
      }
    });
  }

  updateHistoryButtons();
  window.addEventListener('popstate', updateHistoryButtons);
};

if (document.readyState === 'loading') {
  document.addEventListener('DOMContentLoaded', initHistoryButtons);
} else {
  initHistoryButtons();
}
