/** @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;
        this.isHovered = false;

        // 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');

        // Initial dots setup
        this._updateDots();

        // 1 second interval
        this._startAutoSlide();

        // Pause on hover
        this.$el.on('mouseenter', () => {
            this.isHovered = true;
            this._stopAutoSlide();
        });
        this.$el.on('mouseleave', () => {
            this.isHovered = false;
            this._startAutoSlide();
        });

        // Click on dots to slide
        this.$el.on('click', '.dot', (e) => {
            const index = parseInt($(e.currentTarget).data('index'));
            this._slideToIndex(index);
        });

        // 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), 1000); // 1 second
    },

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

    _updateDots: function () {
        const dotIndex = this.currentIndex % this.totalOriginal;
        this.$('.dot').removeClass('active');
        this.$(`.dot[data-index="${dotIndex}"]`).addClass('active');
    },

    _slideToIndex: function (index) {
        this._stopAutoSlide();
        this.currentIndex = index;
        const itemWidth = this.$newItems.first().outerWidth(true);
        this.$track.css({
            'transition': 'transform 0.5s ease-in-out',
            'transform': `translateX(-${this.currentIndex * itemWidth}px)`
        });
        this._updateDots();
        if (!this.isHovered) {
            this._startAutoSlide();
        }
    },

    _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) {
            this._updateDots();
            setTimeout(() => {
                // Snap back to 0 (visually identical position)
                // We use 0 because 0 is the start of Original Set
                this.$track.css({
                    'transition': 'none',
                    'transform': 'translateX(0)'
                });
                this.currentIndex = 0;
            }, 500); // Wait for transition to finish
        } else {
            this._updateDots();
        }
    }
});

export default publicWidget.registry.CategoryCarousel;
