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

export default class extends Controller<HTMLElement> {
   static targets = [ 'slider', 'controlls' ];
   declare sliderTarget: HTMLDivElement;
   declare controllsTarget: HTMLDivElement;

   private component: Component;

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

   async initialize() {
      this.component = await getComponent(this.element);
      if (this.component === undefined) {
         await getComponent(this.element).then(() => {
            this.initSlider();
         });
      } else if (this.component.getData('visible')) {
         this.initSlider();
      }
   }

   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.getData('visible')) {
         this.component.set('visible', true);
         this.component.render().then(() => {
            this.initSlider();
         });
         this.unobserve();
      }
   }

   initSlider() {
      const slider = this.sliderTarget;
      if (slider && !slider.classList.contains('tns-slider')) {
         const has_controls = slider.getAttribute('data-controls') === 'true';
         const controlsContainer = this.controllsTarget;
         const has_nav = slider.getAttribute('data-nav') === 'true';
         const number_of_slides = parseInt(slider.getAttribute('data-number-of-slides') || '1', 10);
         const gap_between_sliders = parseInt(slider.getAttribute('data-gap-between-sliders') || '0', 10);
         const is_loop = slider.getAttribute('data-is-loop') === 'true';
         const is_autoplay = slider.getAttribute('data-is-autoplay') === 'true';

         tns({
            container: slider,
            nav: has_nav,
            controls: has_controls,
            controlsContainer: controlsContainer,
            autoplay: is_autoplay,
            autoplayTimeout: 6000,
            speed: 1000,
            autoplayButtonOutput: false,
            items: number_of_slides,
            gutter: gap_between_sliders,
            loop: is_loop,
            responsive: {
               0: {
                  items: number_of_slides > 1 ? 1.25 : 1
               },
               768: {
                  items: number_of_slides
               }
            }
         });
      }
   }
}
