/** @odoo-module **/

import publicWidget from "@web/legacy/js/public/public_widget";

publicWidget.registry.CategoryCarousel = publicWidget.Widget.extend({
    selector: '.s_category_slider',
    start: function () {
        this.$track = this.$('.category-track');
        this.$items = this.$('.category-item');

        if (!this.$track.length || !this.$items.length) {
            return;
        }

        this.currentIndex = 0;
        this.totalOriginal = this.$items.length;

        // Clone all items and append for seamless loop
        // We ensure we have enough content to scroll endlessly
        const itemsToClone = this.$items.clone();
        this.$track.append(itemsToClone);

        // Update items list
        this.$newItems = this.$('.category-item');

        // 3 seconds interval
        this._startAutoSlide();

        // Pause on hover
        this.$el.on('mouseenter', () => this._stopAutoSlide());
        this.$el.on('mouseleave', () => this._startAutoSlide());

        // Handle window resize to reset alignment
        $(window).on('resize', () => {
            this._slide(true);
        });

        return this._super.apply(this, arguments);
    },

    _startAutoSlide: function () {
        if (this.interval) clearInterval(this.interval);
        this.interval = setInterval(this._slide.bind(this), 3000); // 3 seconds
    },

    _stopAutoSlide: function () {
        if (this.interval) clearInterval(this.interval);
    },

    _slide: function (resize = false) {
        if (resize) {
            // Just reset position on resize to avoid misalignment
            const itemWidth = this.$newItems.first().outerWidth(true);
            this.$track.css({
                'transition': 'none',
                'transform': `translateX(-${this.currentIndex * itemWidth}px)`
            });
            return;
        }

        // Get current item width (responsive)
        const itemWidth = this.$newItems.first().outerWidth(true);

        this.currentIndex++;

        this.$track.css({
            'transition': 'transform 0.5s ease-in-out',
            'transform': `translateX(-${this.currentIndex * itemWidth}px)`
        });

        // Loop check
        // If we have moved past the original set
        if (this.currentIndex >= this.totalOriginal) {
            setTimeout(() => {
                // Snap back to 0 (visually identical position)
                // We use 0 because 0 is the start of Original Set
                // When currentIndex == totalOriginal, we are at the start of Cloned Set
                // Cloned Set is identical to Original Set.
                this.$track.css({
                    'transition': 'none',
                    'transform': 'translateX(0)'
                });
                this.currentIndex = 0;
            }, 500); // Wait for transition to finish
        }
    }
});

export default publicWidget.registry.CategoryCarousel;
