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

  const hasHistory = window.history.length > 1;
  const setDisabledState = (link, disabled) => {
    link.setAttribute('aria-disabled', disabled ? 'true' : 'false');
    link.classList.toggle('is-disabled', disabled);
    if (disabled) {
      link.setAttribute('tabindex', '-1');
    } else {
      link.removeAttribute('tabindex');
    }
  };

  if (back) {
    setDisabledState(back, !hasHistory);
  }
  if (forward) {
    setDisabledState(forward, !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) => {
      event.preventDefault();
      if (window.history.length > 1) {
        window.history.back();
      }
    });
  }

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

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

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