/** @odoo-module **/

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

publicWidget.registry.StatsCounter = publicWidget.Widget.extend({
    selector: '.s_stats_section',
    start: function () {
        this.$counters = this.$('.stat-counter');
        if (!this.$counters.length) {
            return this._super.apply(this, arguments);
        }

        // Initialize IntersectionObserver to track when stats section is in view
        this.observer = new IntersectionObserver((entries) => {
            entries.forEach(entry => {
                if (entry.isIntersecting) {
                    this._animateCounters();
                } else {
                    this._resetCounters();
                }
            });
        }, { threshold: 0.1 });

        this.observer.observe(this.el);

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

    destroy: function () {
        if (this.observer) {
            this.observer.disconnect();
        }
        this._super.apply(this, arguments);
    },

    /**
     * Formats numerical value to human readable format (e.g. 2000 -> 2K)
     * @param {number} value
     * @returns {string|number}
     */
    _formatValue: function (value) {
        if (value >= 1000) {
            const kValue = value / 1000;
            return kValue % 1 === 0 ? kValue.toFixed(0) + 'K' : kValue.toFixed(1) + 'K';
        }
        return value;
    },

    _animateCounters: function () {
        this.$counters.each((index, el) => {
            const $el = $(el);
            if ($el.data('animating')) return;
            $el.data('animating', true);

            const target = parseFloat($el.data('target')) || 0;
            const suffix = $el.data('suffix') || '';
            const duration = 1500; // 1.5 seconds animation
            const startTime = performance.now();

            const updateCount = (currentTime) => {
                const elapsedTime = currentTime - startTime;
                const progress = Math.min(elapsedTime / duration, 1);
                
                // easeOutQuad easing function
                const easeProgress = progress * (2 - progress);
                
                const currentValue = Math.floor(easeProgress * target);
                $el.text(this._formatValue(currentValue) + suffix);

                if (progress < 1) {
                    requestAnimationFrame(updateCount);
                } else {
                    $el.text(this._formatValue(target) + suffix);
                    $el.data('animating', false);
                }
            };

            requestAnimationFrame(updateCount);
        });
    },

    _resetCounters: function () {
        this.$counters.each((index, el) => {
            const $el = $(el);
            const suffix = $el.data('suffix') || '';
            $el.text('0' + suffix);
            $el.data('animating', false);
        });
    }
});

export default publicWidget.registry.StatsCounter;
