import { Controller } from '@hotwired/stimulus';
import { Splide } from '@splidejs/splide';

export default class extends Controller {
    static values = {
        index: {
            type: Number,
            default: 0,
        },
    };

    connect() {
        const slidesCount = this.element.querySelectorAll('.splide__slide').length;
        const start = Math.min(Math.max(this.indexValue, 0), Math.max(slidesCount - 1, 0));

        this.splide = new Splide(this.element.querySelector('.splide'), {
            type: 'slide',
            start,
            focus: 'center',
            trimSpace: true,
            perPage: 3,
            perMove: 1,
            gap: '2.5rem',
            arrows: false,
            pagination: false,
            drag: true,
            keyboard: 'focused',
            speed: 450,
            breakpoints: {
                1023: {
                    perPage: 2,
                    gap: '1.5rem',
                },
                767: {
                    perPage: 1,
                    gap: '1rem',
                },
            },
            reducedMotion: {
                speed: 0,
                rewindSpeed: 0,
            },
        });

        this.splide.mount();
    }

    disconnect() {
        if (this.splide) {
            this.splide.destroy(true);
            this.splide = null;
        }
    }
}
