import { Controller } from '@hotwired/stimulus';
import { RESPONSE } from '@assets/filters/common/events/eventTypes';

export default class extends Controller<HTMLButtonElement> {
   static targets = ['spinner'];

   private lastBoundForm: HTMLFormElement = null;
   declare spinnerTarget: HTMLSpanElement;

   connect() {
      this.doBind();
      document.addEventListener('wpj-products-loaded', this.doBind.bind(this));
   }

   private doBind() {
      const myForm = this.element.form;

      if (!myForm || myForm === this.lastBoundForm) {
         return;
      }

      myForm.addEventListener('submit', () => {
         this.spinnerTarget.style.display = 'flex';
         this.element.classList.add('loading');
      });

      myForm.addEventListener(RESPONSE, () => {
         this.spinnerTarget.style.display = 'none';
         this.element.classList.remove('loading');
      });

      this.lastBoundForm = myForm;
   }
}
