/**
 * @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);
            });
          }

          // Toggle uniquement si la fermeture est autorisé ou si le collapse n'est pas déjà ouvert
          if (el.getAttribute('data-collapse-noclose') === undefined || el.getAttribute('data-collapse-noclose') === null || !this.classList.contains('active')) {
            this.classList.toggle('active');
          }
          customCollapse(title);
        });
      });
    });
};
