import $ from 'jquery';

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

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

    // 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) => {
      // 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));
      }
    });
  }
}

export default IHKAnchorLinks;

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