/** @odoo-module **/

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

publicWidget.registry.DealSwitcher = publicWidget.Widget.extend({
    selector: '.s_popular_deals_premium',
    events: {
        'mouseenter .deal-item': '_onDealHover',
    },

    /**
     * @override
     */
    start: function () {
        this.$centerImg = this.$('#dealCenterImg');
        return this._super.apply(this, arguments);
    },

    //--------------------------------------------------------------------------
    // Handlers
    //--------------------------------------------------------------------------

    /**
     * @private
     * @param {Event} ev
     */
    _onDealHover: function (ev) {
        const $item = $(ev.currentTarget);
        const newImg = $item.data('deal-img');

        if (newImg && this.$centerImg.length) {
            // Remove active class from others
            this.$('.deal-item').removeClass('active');
            // Add active to current
            $item.addClass('active');

            // Fade out, change src, fade in
            this.$centerImg.css('opacity', '0');
            setTimeout(() => {
                this.$centerImg.attr('src', newImg);
                this.$centerImg.css('opacity', '1');
            }, 300);
        }
    },
});


publicWidget.registry.GallerySlider = publicWidget.Widget.extend({
    selector: '.s_gallery_slider_premium',

    start: function () {
        this.$track = this.$('.gallery-track');
        this.slideWidth = 315; // 300px width + 15px gap
        this.currentIndex = 0;
        this.totalOriginal = 6;

        // Start auto-slide
        this._startAutoSlide();

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

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

    _startAutoSlide: function () {
        this.interval = setInterval(this._slide.bind(this), 2000);
    },

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

    _slide: function () {
        this.currentIndex++;
        this.$track.css({
            'transition': 'transform 0.8s cubic-bezier(0.165, 0.84, 0.44, 1)',
            'transform': `translateX(-${this.currentIndex * this.slideWidth}px)`
        });

        // Seamless loop reset
        if (this.currentIndex >= this.totalOriginal) {
            setTimeout(() => {
                this.$track.css({
                    'transition': 'none',
                    'transform': 'translateX(0)'
                });
                this.currentIndex = 0;
            }, 800); // Match transition duration
        }
    }
});

export default {
    DealSwitcher: publicWidget.registry.DealSwitcher,
    GallerySlider: publicWidget.registry.GallerySlider,
};
