/**
 * Shois Chat Button — Animation Engine
 *
 * Controls animation playback: entrance → idle repeat → hover →
 * popup transition → platform expansion. All animations reference
 * CSS classes defined in the /animations/ folder.
 *
 * @package ShoisChatButton
 */
(function () {
    'use strict';

    var config = window.shcb_config;
    if (!config) {
        return;
    }

    /**
     * SCBAnimationEngine constructor.
     *
     * @param {Object} animConfig Animation config from shcb_config.
     */
    function SCBAnimationEngine(animConfig) {
        this.config = animConfig || {};
        this.trigger = null;
        this.popup = null;
        this.widget = null;

        // Idle repeat state.
        this.idleInterval = null;
        this.idleIsRunning = false;

        // Reduced motion check.
        this.reducedMotion = false;
        if (window.matchMedia) {
            this.reducedMotion = window.matchMedia('(prefers-reduced-motion: reduce)').matches;
        }
    }

    /**
     * Initialize the animation engine.
     */
    SCBAnimationEngine.prototype.init = function () {
        this.widget = document.getElementById('shcb-widget');
        this.trigger = document.getElementById('shcb-trigger');
        this.popup = document.getElementById('shcb-popup');

        if (!this.widget || !this.trigger) {
            return;
        }

        // If reduced motion is preferred, skip all animations.
        if (this.reducedMotion) {
            this.widget.style.opacity = '1';
            return;
        }

        // Play entrance animation.
        this.playEntrance();

        // Setup hover.
        this.setupHover();

        // Apply popup transition class.
        this.applyPopupTransition();
    };

    /**
     * Play the entrance animation for the trigger button.
     */
    SCBAnimationEngine.prototype.playEntrance = function () {
        var entrance = this.config.entrance || 'shcb-enter-bounce';
        var delay = (this.config.entrance_delay || 0) * 1000;
        var self = this;

        // Initially hidden.
        this.trigger.style.opacity = '0';

        setTimeout(function () {
            self.trigger.style.opacity = '';
            self.trigger.classList.add(entrance);

            // After entrance completes, start idle loop.
            var onEnd = function () {
                self.trigger.removeEventListener('animationend', onEnd);
                self.trigger.classList.remove(entrance);
                self.startIdleLoop();
            };

            self.trigger.addEventListener('animationend', onEnd);
        }, delay);
    };

    /**
     * Start the idle animation repeat loop.
     */
    SCBAnimationEngine.prototype.startIdleLoop = function () {
        var idle = this.config.idle || '';
        var interval = (this.config.idle_interval || 5) * 1000;

        if (!idle) {
            return;
        }

        var self = this;
        this.idleIsRunning = true;

        this.idleInterval = setInterval(function () {
            if (!self.idleIsRunning) {
                return;
            }

            self.trigger.classList.add(idle);

            var onEnd = function () {
                self.trigger.removeEventListener('animationend', onEnd);
                self.trigger.classList.remove(idle);
            };

            self.trigger.addEventListener('animationend', onEnd);
        }, interval);
    };

    /**
     * Pause idel animations (when popup is open).
     */
    SCBAnimationEngine.prototype.pauseIdle = function () {
        this.idleIsRunning = false;
    };

    /**
     * Resume idle animations (when popup is closed).
     */
    SCBAnimationEngine.prototype.resumeIdle = function () {
        this.idleIsRunning = true;
    };

    /**
     * Setup hover animation on the trigger button.
     */
    SCBAnimationEngine.prototype.setupHover = function () {
        var hover = this.config.hover || '';

        if (!hover) {
            return;
        }

        // Apply hover class so CSS :hover rules take effect.
        this.trigger.classList.add(hover);

        // Ripple effect handler.
        if (hover === 'shcb-hover-ripple') {
            this.trigger.addEventListener('click', function (e) {
                var rect = this.getBoundingClientRect();
                var size = Math.max(rect.width, rect.height);
                var x = e.clientX - rect.left - size / 2;
                var y = e.clientY - rect.top - size / 2;

                var ripple = document.createElement('span');
                ripple.className = 'shcb-ripple-effect';
                ripple.style.width = size + 'px';
                ripple.style.height = size + 'px';
                ripple.style.left = x + 'px';
                ripple.style.top = y + 'px';

                this.appendChild(ripple);

                setTimeout(function () {
                    ripple.parentNode.removeChild(ripple);
                }, 600);
            });
        }
    };

    /**
     * Apply the popup transition class to the widget root.
     */
    SCBAnimationEngine.prototype.applyPopupTransition = function () {
        var popup_anim = this.config.popup || '';
        if (popup_anim) {
            this.widget.classList.add(popup_anim);
        }
    };

    /**
     * Animate platform icons when popup opens.
     *
     * @param {Element} container The popup agents container.
     */
    SCBAnimationEngine.prototype.animatePlatformIcons = function (container) {
        var platformAnim = this.config.platform_icons || '';

        if (!platformAnim || this.reducedMotion || !container) {
            return;
        }

        var icons = container.querySelectorAll('.shcb-platform-btn');

        for (var i = 0; i < icons.length; i++) {
            (function (el, index) {
                el.style.opacity = '0';
                setTimeout(function () {
                    el.style.opacity = '';
                    el.classList.add(platformAnim);
                }, index * 60);
            })(icons[i], i);
        }
    };

    /**
     * Animate badge appearance.
     */
    SCBAnimationEngine.prototype.animateBadge = function () {
        var badgeAnim = this.config.badge || '';
        var badge = this.widget.querySelector('.shcb-badge');

        if (!badgeAnim || !badge || this.reducedMotion) {
            return;
        }

        badge.classList.add(badgeAnim);
    };

    /**
     * Clean up — clear intervals.
     */
    SCBAnimationEngine.prototype.destroy = function () {
        if (this.idleInterval) {
            clearInterval(this.idleInterval);
        }
    };

    // Export to global scope.
    window.SCBAnimationEngine = SCBAnimationEngine;
})();
