/**
 * Collapse JS (no bootstrap / jQuery)
 */

function customCollapse(titleEl) {
  const panel = document.getElementById(titleEl.getAttribute('data-collapse'));
  if (!panel) return;

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

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

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

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

      title.addEventListener('click', function (e) {
        e.stopPropagation();

        if (accordion && !title.classList.contains('active')) {
          const clickedPanel = document.getElementById(title.getAttribute('data-collapse'));

          const actives = Array.from(
              group.querySelectorAll('[data-collapse].active')
          );

          actives.forEach((activeTitle) => {
            if (activeTitle === title) return;

            const activePanel = document.getElementById(activeTitle.getAttribute('data-collapse'));
            if (activePanel && activePanel.contains(title)) return;
            if (clickedPanel && clickedPanel.contains(activeTitle)) return;

            activeTitle.classList.remove('active');
            customCollapse(activeTitle);
          });
        }

        const noClose = group.getAttribute('data-collapse-noclose') !== undefined
            && group.getAttribute('data-collapse-noclose') !== null;

        if (!noClose || !this.classList.contains('active')) {
          this.classList.toggle('active');
        }

        customCollapse(title);
      });
    });
  });
};
