class Accordion {
   isOpenClassName = "is-open";
   isClosingClassName = "is-closing";

   constructor() {
      this.initFields();
      this.initEvents();
   }

   initFields() {
      this.accordions = document.querySelectorAll(".accordion");
   }

   initEvents() {
      this.accordions.forEach((accoordion) => {
         const trigger = accoordion.querySelector(".accordion__trigger");

         trigger.addEventListener("click", (e) => {
            this.clickAccordion(accoordion);
         });
      });
   }

   clickAccordion = (accordion) => {
      const isOpen = this.isOpened(accordion);

      const isSingleMode = accordion.closest("[data-single]");

      if (isSingleMode && !isOpen) {
         this.closeAllAccordions(accordion);
      }

      accordion.classList.remove(this.isClosingClassName, this.isOpenClassName);

      const panel = accordion.querySelector(".accordion__content");

      if (!isOpen) {
         this.openAccordion(accordion);
      } else {
         this.closeAccordion(accordion);

         panel.addEventListener(
            "animationend",
            () => {
               this.removeIsClosing(accordion);
            },
            { once: true }
         );
      }
   };

   closeAllAccordions = (current) => {
      console.log(current);
      this.accordions.forEach((accordion) => {
         if (accordion !== current && this.isOpened(accordion)) {
            accordion.classList.add(this.isClosingClassName);
            accordion.classList.remove(this.isOpenClassName);

            const panel = accordion.querySelector(".accordion__content");

            panel.addEventListener(
               "animationend",
               () => {
                  this.removeIsClosing(accordion);
               },
               { once: true }
            );
         }
      });
   };

   closeAccordion = (item) => {
      item.classList.add(this.isClosingClassName);
   };

   removeIsClosing = (item) => {
      item.classList.remove(this.isClosingClassName);
   };

   isOpened = (item) => {
      return item.classList.contains(this.isOpenClassName);
   };

   openAccordion = (accordion) => {
      accordion.classList.add(this.isOpenClassName);
   };
}

export { Accordion };
