/**
 * @description
 * Collapse JS sans bootstrap ni jQuery
 */

function customCollapse(el) {
  const panel = document.getElementById(el.getAttribute('data-collapse'));

  if (el.classList.contains('active')) {
    if (panel.style.maxHeight) {
      panel.style.maxHeight = null;
    } else {
      panel.style.maxHeight = `${panel.scrollHeight}px`;
    }
  } else {
    panel.style.maxHeight = null;
  }
}

export default () => {
  const els = document.querySelectorAll('.collapse-group');

  Array.from(els)
    .forEach((el) => {
      const titles = el.querySelectorAll('[data-collapse]');
      const accordion = el.classList.contains('custom-accordion');

      Array.from(titles).forEach((title) => {
        customCollapse(title);

        title.addEventListener('click', function () {
          // S'il s'agit d'un accordéon, on ferme les autres volets avant d'ouvrir le nouveau
          if (accordion && !title.classList.contains('active')) {
            const titlesActives = el.querySelectorAll('[data-collapse].active');
            Array.from(titlesActives).forEach((titleActive) => {
              titleActive.classList.remove('active');
              customCollapse(titleActive);
            });
          }

          this.classList.toggle('active');
          customCollapse(title);
        });
      });
    });
};
