import { Controller } from '@hotwired/stimulus';
import { Splide } from '@splidejs/splide';
import '@splidejs/splide/css';
import '@cpcreation/viti-core/css/product-gallery.css';

export default class extends Controller {
    static targets = ['main', 'thumbnail'];

    connect() {
        if (!this.hasMainTarget) {
            return;
        }

        this.splide = new Splide(this.mainTarget, {
            type: 'slide',
            rewind: true,
            arrows: false,
            pagination: true,
            drag: true,
            speed: 500,
            gap: 0,
            perPage: 1,
            perMove: 1,
            reducedMotion: {
                speed: 0,
                rewindSpeed: 0,
            },
        });

        this.splide.on('mounted moved', () => {
            this.updateActiveThumbnail(this.splide.index);
        });
        this.splide.mount();
    }

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

    selectThumbnail(event) {
        if (!this.splide) {
            return;
        }

        const index = Number(event.params.index);

        if (Number.isInteger(index)) {
            this.splide.go(index);
        }
    }

    updateActiveThumbnail(activeIndex) {
        this.thumbnailTargets.forEach((thumbnail, index) => {
            if (index === activeIndex) {
                thumbnail.setAttribute('aria-current', 'true');
            } else {
                thumbnail.removeAttribute('aria-current');
            }
        });
    }
}
