/**
* DO NOT EDIT THIS FILE.
* See the following change record for more information,
* https://www.drupal.org/node/2815083
* @preserve
**/

(function ($, Drupal, window) {
  function processCommentNewIndicators(placeholders) {
    let isFirstNewComment = true;
    const newCommentString = Drupal.t('new');
    let $placeholder;
    placeholders.forEach(placeholder => {
      $placeholder = $(placeholder);
      const timestamp = parseInt($placeholder.attr('data-comment-timestamp'), 10);
      const $node = $placeholder.closest('[data-history-node-id]');
      const nodeID = $node.attr('data-history-node-id');
      const lastViewTimestamp = Drupal.history.getLastRead(nodeID);

      if (timestamp > lastViewTimestamp) {
        placeholder.textContent = newCommentString;
        $placeholder.removeClass('hidden').closest('.js-comment').addClass('new');

        if (isFirstNewComment) {
          isFirstNewComment = false;
          $placeholder.prev().before('<a id="new"></a>');

          if (window.location.hash === '#new') {
            window.scrollTo(0, $placeholder.offset().top - Drupal.displace.offsets.top);
          }
        }
      }
    });
  }

  Drupal.behaviors.commentNewIndicator = {
    attach(context) {
      const nodeIDs = [];
      const placeholders = once('history', '[data-comment-timestamp]', context).filter(placeholder => {
        const $placeholder = $(placeholder);
        const commentTimestamp = parseInt($placeholder.attr('data-comment-timestamp'), 10);
        const nodeID = $placeholder.closest('[data-history-node-id]').attr('data-history-node-id');

        if (Drupal.history.needsServerCheck(nodeID, commentTimestamp)) {
          nodeIDs.push(nodeID);
          return true;
        }

        return false;
      });

      if (placeholders.length === 0) {
        return;
      }

      Drupal.history.fetchTimestamps(nodeIDs, () => {
        processCommentNewIndicators(placeholders);
      });
    }

  };
})(jQuery, Drupal, window);