(function (D, settings) {
  const { sector_toc } = settings;

  if (!sector_toc) {
    return null;
  }

  const instances = Object.keys(sector_toc);
  const containers = document.querySelectorAll(`.node--full .prose`);

  if (containers.length === 0) {
    return null;
  }

  let all_selectors = []
  Object.keys(sector_toc).forEach(instanceKey => all_selectors = [...all_selectors, ...sector_toc[instanceKey].selectors.split(',').map(i => i.trim())]);
  const all_selectors_unique = [...new Set(all_selectors)];

  let groups = structuredClone(sector_toc);

  containers.forEach((container, i) => {
    all_selectors_unique.forEach((selector,o) => {
      const targets = container.querySelectorAll(selector);
      if (targets.length) {
        targets.forEach((elem, y) => {
          const elemId = `toc-${o}-${y}`;
          elem.setAttribute('id', elemId)
          elem.classList.add('toc__anchor')
          elem.setAttribute('tabindex', '-1');
          elem.setAttribute('data-toc-match', selector)
        })
      }
    })

    container.querySelectorAll('.toc__anchor').forEach(anchor => {
      const text = anchor.innerText.trim();
      const li = document.createElement('li');
      li.innerHTML = `<a class="toc__anchor-link" data-tag="${anchor.tagName}" href="#${anchor.getAttribute('id')}">${text}</a>`

      const selector = anchor.dataset.tocMatch;

      Object.keys(groups).map(instanceKey => {
        if(!groups[instanceKey].selectors.includes(selector)) {
          return false;
        }

        if(groups[instanceKey].nodes) {
          groups[instanceKey].nodes = [...groups[instanceKey].nodes, li.cloneNode(true)];
        }
        else {
          groups[instanceKey].nodes = [ li.cloneNode(true) ];
        }
      })
    })
  })

  Object.keys(groups).forEach(group => {
    const tocs = document.querySelectorAll(`.toc[data-group="${group}"]`);

    tocs.forEach(toc_group => {
      groups[group].nodes.forEach(node => {
        toc_group.querySelector('.toc__contents').appendChild(node.cloneNode(true))
      })
    })
  })

  document.querySelectorAll('.toc__loader').forEach(loader => loader.remove());

})(Drupal, drupalSettings);