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

export default class extends Controller<HTMLElement> {
   static targets = [ 'search', 'input' ];

   declare searchTarget: HTMLElement;
   declare inputTarget: HTMLInputElement;
   private boundShowSearch: (event: Event) => void;

   private scrollLockPosition = 0;

   connect() {
      this.boundShowSearch = this.showSearch.bind(this);
      window.addEventListener('HeaderSearch:showSearch', this.boundShowSearch);
   }

   disconnect() {
      window.removeEventListener('HeaderSearch:showSearch', this.boundShowSearch);
   }

   showSearch(e: Event): void {
      e.preventDefault();
      this.scrollLockPosition = window.scrollY;
      window.scrollTo(0, 0);
      this.searchTarget.classList.add('search-active');
      this.inputTarget.focus();
   }

   hideSearch(): void {
      this.searchTarget.classList.remove('search-active');
      this.element.dispatchEvent(new CustomEvent('focusout', {
         bubbles: true,
         cancelable: true,
         detail: {
            close: true,
         }
      }));
      if (this.scrollLockPosition > 0) {
         requestAnimationFrame(() => {
            window.scrollTo(0, this.scrollLockPosition);
         });
      }
   }
}
