import { Controller } from '@hotwired/stimulus';
import { useIntersection } from 'stimulus-use';
import { Component, getComponent } from '@symfony/ux-live-component';

export default class extends Controller<HTMLDivElement> {
   private component: Component;

   declare observe: () => void;
   declare unobserve: () => void;

   async initialize() {
      this.component = await getComponent(this.element);
   }

   connect() {
      const [observe, unobserve] = useIntersection(this, { rootMargin: '300px 0px 300px 0px' });
      this.observe = observe;
      this.unobserve = unobserve;
   }

   appear(entry, observer) {
      if (this.component) {
         this.component.set('visible', true);
         this.component.render();
         this.unobserve();
      }
   }
}
