/**
 * Elementor frontend handler for the Testimonial widget.
 *
 * A dependency-free carousel supporting slide & fade animation, autoplay with
 * pause-on-hover, infinite looping, arrows and dots. One controller per
 * instance with editor-safe teardown.
 *
 */

(function ($) {
    'use strict';

    /**
     * Per-instance handler — called by Elementor for every widget instance.
     *
     * @param {jQuery} $scope - The widget wrapper element.
     */
    var CaptwikiTestimonialHandler = function ($scope) {

        var root = $scope[0].querySelector('.captwiki-testimonial');
        if (!root) return;

        /* Teardown a previous run (editor re-render safety). */
        if (root._cwkTeardown) {
            root._cwkTeardown();
        }

        var track = root.querySelector('.captwiki-testimonial__track');
        var slides = Array.prototype.slice.call(root.querySelectorAll('.captwiki-testimonial__slide'));
        var dots = Array.prototype.slice.call(root.querySelectorAll('.captwiki-testimonial__dot'));
        var prevBtn = root.querySelector('.captwiki-testimonial__arrow--prev');
        var nextBtn = root.querySelector('.captwiki-testimonial__arrow--next');

        if (!track || slides.length === 0) return;

        var total = slides.length;
        var animation = root.getAttribute('data-animation') || 'slide';
        var autoplay = root.getAttribute('data-autoplay') === '1';
        var speed = parseInt(root.getAttribute('data-speed'), 10) || 4000;
        var pauseOnHover = root.getAttribute('data-pause') === '1';
        var loop = root.getAttribute('data-loop') === '1';

        var current = 0;
        var timer = null;

        /**
         * Paint the active slide & dot and move the track when sliding.
         *
         * @param {number} index - Target slide index.
         */
        function goTo(index) {
            if (index < 0) {
                index = loop ? total - 1 : 0;
            } else if (index >= total) {
                index = loop ? 0 : total - 1;
            }
            current = index;

            if (animation === 'slide') {
                track.style.transform = 'translateX(' + (-index * 100) + '%)';
            }

            slides.forEach(function (slide, i) {
                slide.classList.toggle('is-active', i === index);
                slide.setAttribute('aria-hidden', i === index ? 'false' : 'true');
            });

            dots.forEach(function (dot, i) {
                dot.classList.toggle('is-active', i === index);
                dot.setAttribute('aria-selected', i === index ? 'true' : 'false');
            });

            updateArrows();
        }

        /**
         * Disable arrows at the ends when not looping.
         */
        function updateArrows() {
            if (loop) return;
            if (prevBtn) prevBtn.disabled = current === 0;
            if (nextBtn) nextBtn.disabled = current === total - 1;
        }

        function next() { goTo(current + 1); }
        function prev() { goTo(current - 1); }

        /* ── Autoplay ──────────────────────────────────────── */
        function startAuto() {
            if (!autoplay || total < 2) return;
            stopAuto();
            timer = setInterval(next, speed);
        }

        function stopAuto() {
            if (timer) {
                clearInterval(timer);
                timer = null;
            }
        }

        /**
         * Reset the autoplay clock after a manual interaction so the next
         * auto-advance waits a full interval.
         */
        function restartAuto() {
            if (autoplay) startAuto();
        }

        /* ── Events ────────────────────────────────────────── */
        var handlers = [];

        function on(el, type, fn, opts) {
            if (!el) return;
            el.addEventListener(type, fn, opts);
            handlers.push(function () { el.removeEventListener(type, fn, opts); });
        }

        on(nextBtn, 'click', function () { next(); restartAuto(); });
        on(prevBtn, 'click', function () { prev(); restartAuto(); });

        dots.forEach(function (dot) {
            on(dot, 'click', function () {
                var i = parseInt(dot.getAttribute('data-index'), 10) || 0;
                goTo(i);
                restartAuto();
            });
        });

        if (autoplay && pauseOnHover) {
            on(root, 'mouseenter', stopAuto);
            on(root, 'mouseleave', startAuto);
        }

        /* Pause when the tab is hidden to save resources. */
        var onVisibility = function () {
            if (document.hidden) {
                stopAuto();
            } else {
                restartAuto();
            }
        };
        on(document, 'visibilitychange', onVisibility);

        /* Basic touch / swipe support. */
        var startX = null;
        on(track, 'touchstart', function (e) {
            startX = e.touches[0].clientX;
            stopAuto();
        }, { passive: true });

        on(track, 'touchend', function (e) {
            if (startX === null) return;
            var diff = e.changedTouches[0].clientX - startX;
            if (Math.abs(diff) > 40) {
                if (diff < 0) { next(); } else { prev(); }
            }
            startX = null;
            restartAuto();
        });

        /* ── Init ──────────────────────────────────────────── */
        goTo(0);
        startAuto();

        root._cwkTeardown = function () {
            stopAuto();
            handlers.forEach(function (off) { off(); });
            handlers = [];
            root._cwkTeardown = null;
        };
    };

    /* ── Register with Elementor frontend ───────────────────── */
    $(window).on('elementor/frontend/init', function () {
        elementorFrontend.hooks.addAction(
            'frontend/element_ready/captwiki-testimonial.default',
            CaptwikiTestimonialHandler
        );
    });

})(jQuery);
