import $ from 'jquery';

class IHKAnchorLinks {
  constructor(section) {
    this.section = section.addClass('initiated');
    this.scrolling = false;
    this.headlines = [];

    this.initHeadlines();
    this.buildLinks();

    const anchorLink = window.location.href.match(/#(.*)/);
    if (anchorLink != null) {
      this.scrollToTarget(anchorLink);
    }
    // IHK-5928 missing link to root channel
    $(".main-col .richtext .detail-text a[href='']").attr("href","/");
  }

  initHeadlines() {
    $('.main-col h2, article.col h2, .action-col .richtext h2').each((i, element) => {
      const h2 = $(element);
      const closestActionContent = h2.closest('.action-content');
      const hideOnlineMagazineContactH2 =  h2.closest('.online-magazine-contact').length;
      if (!h2.closest('.accordion-content').length && !closestActionContent.closest(".richtext").length && !hideOnlineMagazineContactH2 && h2.text().length > 0) {
        if (h2.is(".showInTableOfContents") || !h2.closest(".link-collection").length) {
          this.headlines.push(h2);
        }
      }
    });
  }

  buildLinks() {
    const t = this;
    const ul = t.section.find('ul li a');

    $(ul).each((i, element) => {
      // Add Ids to text h2
      const textH2 = $(this.headlines[i]);
      if(textH2.length) {
        $(textH2).addClass('has-anchor');
        $(textH2).append($('<span class="anchor" />').attr('id', 'titleInText' + i));
      }
    });

    this.anchors = $('.main-col, article.col, .action-col').find('h2 .anchor');

    t.links = t.section.find('a').on('click', (e) => {
      e.preventDefault();
      this.handleClick($(e.currentTarget));
    });

  }

  handleClick(a) {
    const index = parseInt(a.attr('data-index'));
    const target = this.anchors.eq(index).offset().top;

    let time = Math.round(Math.abs($(window).scrollTop() - target) / 6 + 300);
    if (time > 800) {
      time = 800;
    }

    this.scrolling = true;
    $('html, body').animate({'scrollTop': target}, time, 'swing', () => {
      this.scrolling = false;
    });
  }

  scrollToTarget(anchorLink) {
    const anchorLinkElement = $("#" + anchorLink[1]);
    if (anchorLinkElement.length > 0) {
      $('html, body').animate({
        scrollTop: anchorLinkElement.first().offset().top - 10
      }, 10);
    }
  }
}

export default IHKAnchorLinks;

$('body').on('ihk-init dynamic-component-loaded gfi-dynamic-init', function () {
  $('.anchor-links:not(.initiated)').each(() => {
    new IHKAnchorLinks($(this));
  });
});
