import { tns } from 'tiny-slider';
import { Controller } from '@hotwired/stimulus';

export default class extends Controller<HTMLElement> {
   initialize() {
      const slider = this.element.querySelector('.slider-tns');

      if (slider && !slider.classList.contains('tns-slider')) {
         const has_controls = slider.getAttribute('data-controls') === 'true';
         const controlsContainer = slider.parentElement.querySelector('[data-tns-controls]');
         const has_nav = slider.getAttribute('data-nav') === 'true';
         const number_of_slides = parseInt(slider.getAttribute('data-number-of-slides') || '1', 10);
         const number_of_slides_md = parseInt(slider.getAttribute('data-number-of-slides-md') || '1', 10);
         const number_of_slides_sm = parseFloat(slider.getAttribute('data-number-of-slides-sm') || '1');
         const gap_between_sliders = parseInt(slider.getAttribute('data-gap-between-sliders') || '0', 10);

         const carousel = tns({
            container: slider,
            nav: has_nav,
            controls: has_controls,
            controlsContainer: controlsContainer,
            autoplay: true,
            autoplayTimeout: 6000,
            speed: 1000,
            autoplayButtonOutput: false,
            items: number_of_slides,
            gutter: gap_between_sliders,
            responsive: {
               0: {
                  items: number_of_slides_sm
               },
               544: {
                  items: number_of_slides_md
               },
               991: {
                  items: number_of_slides
               }
            }

         });

         carousel.events.on('indexChanged', (info) => {
            for (let i = 0; i < info.slideItems.length; i++) {
               info.slideItems[i].querySelectorAll('a, button, input, textarea, select, [tabindex]').forEach((item) => {
                  item.setAttribute('tabindex', i == info.index ? '0' : '-1');
               });
            }
         });
      }
   }
}
