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

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

  if (el.classList.contains('active')) {
    panel.style.maxHeight = `${panel.scrollHeight}px`;
    setTimeout(() => {
      panel.style.maxHeight = 'none';
      panel.classList.add('opened');
    }, 300);
  } else {
    panel.classList.remove('active');
    if (panel.classList.contains('opened')) {
      panel.style.maxHeight = `${panel.scrollHeight}px`;
    }
    setTimeout(() => {
      panel.style.maxHeight = null;
    }, 100);
  }
}

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);
        });
      });
    });
};
