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

export default class extends Controller {
    static targets = ["active"];

    connect() {
        this.revealFrame = null;

        this.splide = new Splide(this.element, {
            arrows: false,
            autoWidth: true,
            breakpoints: {
                768: {
                    gap: "2.5rem",
                },
            },
            drag: true,
            dragMinThreshold: {
                mouse: 10,
                touch: 10,
            },
            focus: 0,
            gap: "1.5rem",
            keyboard: "focused",
            mediaQuery: "min",
            pagination: false,
            perMove: 1,
            start: this.activeIndex,
            trimSpace: true,
        });

        this.splide.on("mounted resized", () => this.revealActive());
        this.splide.mount();
    }

    disconnect() {
        if (this.revealFrame) {
            cancelAnimationFrame(this.revealFrame);
            this.revealFrame = null;
        }

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

    revealActive() {
        if (!this.hasActiveTarget || !this.splide) {
            return;
        }

        if (this.revealFrame) {
            cancelAnimationFrame(this.revealFrame);
        }

        this.revealFrame = requestAnimationFrame(() => {
            this.splide?.go(this.activeIndex);
            this.revealFrame = null;
        });
    }

    get activeIndex() {
        if (!this.hasActiveTarget) {
            return 0;
        }

        const activeSlide = this.activeTarget.closest(".splide__slide");
        const slides = Array.from(
            this.element.querySelectorAll(".splide__slide"),
        );

        return Math.max(0, slides.indexOf(activeSlide));
    }
}
