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

   initFields() {
      this.popovers = document.querySelectorAll(".popover");
   }

   initEvents() {
      this.popovers.forEach((popover) => {
         const trigger = popover.querySelector(".popover__trigger");
         trigger.addEventListener("click", () => this.togglePopover(popover));
      });

      document.addEventListener("click", (event) => {
         const { target } = event;
         this.popovers.forEach((popover) => {
            if (target && target !== popover && !popover.contains(target)) {
               this.hidePopover(popover);
            }
         });
      });
   }

   togglePopover = (elem) => {
      elem.classList.toggle("active");
   };

   showPopover = (elem) => {
      elem.classList.add("active");
   };

   hidePopover = (elem) => {
      elem.classList.remove("active");
   };
}

export { Popover };
