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

export default class extends Controller<HTMLDivElement> {
   static values = {
      lazy: Boolean
   };

   private component: Component;

   declare lazyValue: boolean;
   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 === undefined) {
         this.initialize().then(() => this.lazyRender());
      } else {
         this.lazyRender();
      }
   }

   lazyRender() {
      if (this.lazyValue && this.component) {
         this.component.set('lazy', false);
         recommenderSetLazyInitData(this.component);
         this.component.render();
         this.unobserve();
      }
   }
}

export function recommenderSetLazyInitData(component: Component) {
   if (component.getData('label') == 'last-visited') {
      const data = component.getData('data');
      const lastVisited = window.wpj.jsShop.lastVisitedProducts?.get(data.product ?? 0);
      component.set('data', { ...data, lastVisited });
   }
}
