let scroll; 
const body = document.body;
const select = (e) => document.querySelector(e);
const selectAll = (e) => document.querySelectorAll(e);


function initAccordion() {

  const accordion = select('.js-accordion');

  if (!accordion) {
    return;
  }

  else{

    const groups = gsap.utils.toArray('.js-accordion__group');
    const menus = gsap.utils.toArray('.js-accordion__menu');
    const animations = [];

    groups.forEach(group => createAnimation(group));

    menus.forEach(menu => {
      menu.addEventListener('click', () => toggleAnimation(menu));
    });

    function toggleAnimation(menu) {
      // Save the current state of the clicked animation
      const selectedReversedState = menu.animation.reversed();
      
      // Reverse all animations
      animations.forEach(animation => animation.reverse());
      
      // Set the reversed state of the clicked accordion element to the opposite of what it was before
      menu.animation.reversed(!selectedReversedState);
    }

    function createAnimation(element) {
      const menu = element.querySelector('.js-accordion__menu');
      const box  = element.querySelector('.js-accordion__content');
      const icon  = element.querySelector('.js-accordion__icon');
      
      gsap.set(box, { height: 'auto'})
      gsap.set(icon, { rotation: 90})

      const tlAccordion = gsap.timeline({
        reversed:true,
        paused: !0,
        onComplete: updateLoco
      }); 
      
      // Keep a reference to the animation on the menu item itself
      
      tlAccordion     
        .from(box, {
          height: 0, 
          duration: 0.5, 
          ease: 'power1.inOut',
          //reversed: true
        })
        .to(icon, {
          duration:0.25,
          rotation:-90,
          ease:'linear'
          //onComplete: updateLoco
        }, '<');
           
      menu.animation = tlAccordion;
      animations.push(tlAccordion);
    }

  }

}

function initScript() {
  initSmoothScroll();
  initAccordion();
}

function updateLoco(){
  scroll.update();
} 

window.onresize = updateLoco;

window.addEventListener('load', function(){
  initScript();
});


