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

export default class extends Controller<HTMLElement> {
   private observer?: IntersectionObserver;
   private buyFormElement: HTMLElement | null = null;

   connect(): void {
      this.buyFormElement = document.querySelector<HTMLElement>(COMPONENTS['Product:BuyForm'].selector);

      if (!this.buyFormElement) return;

      this.observer = new IntersectionObserver(this.handleIntersection, {
         root: null,
         threshold: 0.1,
      });

      this.observer.observe(this.buyFormElement);
   }

   disconnect(): void {
      if (this.buyFormElement && this.observer) {
         this.observer.unobserve(this.buyFormElement);
         this.observer.disconnect();
      }
   }

   private handleIntersection = ([entry]: IntersectionObserverEntry[]): void => {
      this.element.classList.toggle('is-visible', !entry.isIntersecting);
   };

   scrollToBuyForm(): void {
      this.buyFormElement?.scrollIntoView({ behavior: 'smooth', block: 'start' });
   }
}
