import { Controller } from '@hotwired/stimulus';

export default class extends Controller<HTMLFormElement> {
   static targets = ['buttonText'];
   declare buttonTextTarget: HTMLTemplateElement;

   initialize() {
      // TODO předělat na stimulus
      const button = this.element.querySelector('[data-toggle]') as HTMLButtonElement;
      const popup = this.element.querySelector('[data-popup]') as HTMLDivElement;
      button.onclick = () => {
         if (popup.classList.contains('active')) {
            popup.classList.remove('active');
            button.classList.remove('active')
         } else {
            popup.classList.add('active');
            button.classList.add('active');
         }
      }

      document.addEventListener('click', (event: MouseEvent) => {
         if (popup.classList.contains('active')) {
            const target = event.target as HTMLElement;

            if (!popup.contains(target) && !button.contains(target)) {
               popup.classList.remove('active');
               button.classList.remove('active')
            }
         }
      });

         popup.addEventListener("change", () => {
            popup.classList.remove('active');
            button.classList.remove('active')
         });

   }

   changeChosenSortTitle(e) {
      this.buttonTextTarget.textContent = e.params.name;
   }
}
