/**
 * @file
 * Claro's enhancement for autocomplete form element.
 */

// cspell:ignore is-autocompleting

((Drupal, once) => {
  Drupal.behaviors.articleBehaviors = {
    attach(context) {
      let rightSidebar = once('articleBehavior', '#article-body .right-side', context);
      rightSidebar.forEach(function(elem) {
        let anchor = document.querySelector('.right-side').offsetTop;
        // get all headings.
        let headings = context.querySelectorAll(".article-content h2, h3, h4, h5, h6");
        // create an <ol>
        // add each item as <li><a href="#name">Text</a></li>
        let jumpLinks = document.createElement('ul');
        headings.forEach(function(heading) {
          if (heading.classList.contains("visually-hidden")) {
            return;
          }
          // convert text to a name.
          let headingText = heading.innerText;
          let headingId = headingText.replace(/\s+/g, '-').toLowerCase();
          // set as the id.
          heading.id = headingId;
          let listElement = document.createElement('li');
          let listElementLink = document.createElement('a');
          listElementLink.href = "#" + headingId;
          listElementLink.innerText = headingText;
          listElement.appendChild(listElementLink)
          jumpLinks.appendChild(listElement);
        });
        elem.innerHTML = "";
        elem.append(jumpLinks);
        // Function to check if the nav should stick.
        const seeIfSticky = (element) => {
          // get right sidebar scroll top.
          let jumpLinks = document.querySelector('.right-side');
          var curScroll =
            (window.pageYOffset !== undefined) ?
              window.pageYOffset : (document.documentElement || document.body.parentNode || document.body).scrollTop;
          if (curScroll >= anchor) {
            jumpLinks.classList.add('fixed-sidebar');
          }
          else if (curScroll < anchor) {
            jumpLinks.classList.remove('fixed-sidebar');
          }
        };
        document.addEventListener("scroll", seeIfSticky);
      });
    },
  };
})(Drupal, once);
