/**
 * @description Permet d'afficher et de cacher une partie d'un texte.
 */
function initShowHide() {
  const showHideElems = document.querySelectorAll('.show-hide');

  showHideElems.forEach((showHide) => {
    const showHideBody = showHide.querySelector('.show-hide-body');
    const showHideFooter = showHide.querySelector('.show-hide-footer');
    const showHideFooterLink = showHide.querySelector('.show-hide-footer-link');
    const showHideTextReadMore = showHideFooter.querySelector('.text-read-more');
    const showHideTextReadLess = showHideFooter.querySelector('.text-read-less');
    const showHideBodyOuterHeight = showHideBody.offsetHeight;

    // Initialisation (load, changeorientation, resize)
    showHide.classList.remove('preview');
    showHideFooter.classList.remove('hidden');
    showHideBody.style.height = '';

    // On défini à partir de quelle hauteur de ".showHideBody" on rend pliable-dépliable la showHide
    let showHideBodyMaxheight = 150; // 6 lignes par défaut
    if (showHide.hasAttribute('data-height')) {
      showHideBodyMaxheight = showHide.getAttribute('data-height');
    }

    if (showHideBodyOuterHeight >= showHideBodyMaxheight) {
      showHide.classList.add('preview');
      showHideFooter.classList.remove('hidden');
      if (!showHide.classList.contains('preview-disabled')) {
        showHideBody.style.height = `${showHideBodyMaxheight}px`;
      }

      showHideFooterLink.addEventListener('click', (e) => {
        e.preventDefault();

        showHideFooterLink.classList.toggle('active');
        showHide.classList.toggle('preview');
        showHide.classList.toggle('preview-disabled');


        // Animation de la hauteur
        if (showHide.classList.contains('preview-disabled')) {
          showHideBody.style.height = `${showHideBodyOuterHeight}px`;
        } else {
          showHideBody.style.height = `${showHideBodyMaxheight}px`;
        }

        // changement de bouton afficher plus / voir moins
        if (showHideFooterLink.classList.contains('active') === true) {
          showHideTextReadMore.classList.add('hidden');
          showHideTextReadLess.classList.remove('hidden');
        } else {
          showHideTextReadMore.classList.remove('hidden');
          showHideTextReadLess.classList.add('hidden');
        }
      });
    } else {
      showHideFooter.style.display = 'none';
    }
  });
}

export default initShowHide;
