(function () {
    'use strict';

    function initTimelineTabs(wrapper) {
        var settings = {};
        try { settings = JSON.parse(wrapper.dataset.settings || '{}'); } catch (e) {}

        var trigger            = settings.trigger || 'click';
        var autoplay           = settings.autoplay === 'on';
        var autoplaySpeed      = parseInt(settings.autoplaySpeed, 10) || 3000;
        var autoplayPauseHover = settings.autoplayPauseHover !== false;
        var loop               = settings.loop !== false;
        var defaultActiveIndex = parseInt(settings.defaultActiveIndex, 10) || 0;

        var nav   = wrapper.querySelector('.difl-tt-nav');
        var slider_items = wrapper.querySelectorAll('.difl-tt-tab-item');
        var items = wrapper.querySelectorAll('.difl-tt-item');
        var total = slider_items.length;

        if (!total || !items.length) return;
        if (wrapper.dataset.ttInit) return;
        wrapper.dataset.ttInit = '1';

        var currentIndex  = 0;
        var autoplayTimer = null;
        var isFirstActivation = true;
        var animDataCache = null;

        function findAnimData() {
            if (animDataCache) return animDataCache;
            if (!window.diviElementAnimationData || !window.jQuery || !items.length) return null;
            var $first = window.jQuery(items[0]);
            var entry = window.diviElementAnimationData.find(function (d) {
                if (!d || !d.class || !d.style) return false;
                var sel = d.class.charAt(0) === '.' || d.class.charAt(0) === '#' ? d.class : '.' + d.class;
                try { return $first.is(sel); } catch (e) { return false; }
            });
            if (entry) animDataCache = entry;
            return entry || null;
        }

        function restoreAnimAttrs($item) {
            var d = findAnimData();
            if (!d || !d.style) return false;
            $item.attr({
                'data-animation-style':            d.style,
                'data-animation-repeat':           d.repeat === 'once' ? '' : 'infinite',
                'data-animation-duration':         d.duration         || '1000ms',
                'data-animation-delay':            d.delay            || '0ms',
                'data-animation-intensity':        d.intensity        || '50%',
                'data-animation-starting-opacity': d.starting_opacity || '0%',
                'data-animation-speed-curve':      d.speed_curve      || 'ease-in-out',
            });
            return true;
        }

        var pinEl   = nav ? nav.querySelector('.difl-tt-pin') : null;
        var prevBtn = wrapper.querySelector('.difl-tt-arrow--prev');
        var nextBtn = wrapper.querySelector('.difl-tt-arrow--next');

        var firstDot = slider_items[0] ? slider_items[0].querySelector('.difl-tt-tab-item__dot') : null;
        var lastDot  = slider_items[total - 1] ? slider_items[total - 1].querySelector('.difl-tt-tab-item__dot') : null;

        // ── Track / fill helpers ─────────────────────────────────────

        function updateTrackVars() {
            if (!nav || !firstDot || !lastDot) return null;
            var navRect   = nav.getBoundingClientRect();
            var firstRect = firstDot.getBoundingClientRect();
            var lastRect  = lastDot.getBoundingClientRect();
            var trackLeft  = (firstRect.left + firstRect.width  / 2) - navRect.left;
            var trackRight = navRect.right - (lastRect.left + lastRect.width / 2);
            var trackTop   = (firstRect.top  + firstRect.height / 2) - navRect.top;
            nav.style.setProperty('--tt-track-left',  trackLeft  + 'px');
            nav.style.setProperty('--tt-track-right', trackRight + 'px');
            nav.style.setProperty('--tt-track-top',   trackTop   + 'px');
            return { trackLeft: trackLeft, firstRect: firstRect, navRect: navRect };
        }

        function setFill(index) {
            if (!nav) return;
            var track = updateTrackVars();
            if (!track) return;

            var activeDotEl = slider_items[index] ? slider_items[index].querySelector('.difl-tt-tab-item__dot') : null;
            if (!activeDotEl) return;

            var activeDotRect = activeDotEl.getBoundingClientRect();
            var fillWidth = (activeDotRect.left + activeDotRect.width / 2)
                          - (track.firstRect.left + track.firstRect.width / 2);

            nav.style.setProperty('--tt-fill', fillWidth + 'px');

            if (pinEl) {
                var pinLeft = (activeDotRect.left + activeDotRect.width / 2) - track.navRect.left;
                var pinTop  = (activeDotRect.top  + activeDotRect.height / 2) - track.navRect.top;
                nav.style.setProperty('--tt-pin-left', pinLeft + 'px');
                nav.style.setProperty('--tt-pin-top',  pinTop  + 'px');
            }
        }

        // ── Activate ─────────────────────────────────────────────────

        function activate(index) {
            if (!loop && (index < 0 || index >= total)) return;
            index = ((index % total) + total) % total;

            if (!isFirstActivation && index === currentIndex) return;

            var skipAnim = isFirstActivation;
            isFirstActivation = false;
            currentIndex = index;

            slider_items.forEach(function (s, i) {
                s.classList.toggle('difl-tt-tab-item--active', i === index);
            });
            items.forEach(function (item, i) {
                var isActive = i === index;
                item.classList.toggle('difl-tt-item--active', isActive);
                if (isActive && !skipAnim && window.et_animate_element && window.jQuery) {
                    var $item = window.jQuery(item);
                    $item.removeClass('et_had_animation');
                    if (!$item.attr('data-animation-style')) {
                        restoreAnimAttrs($item);
                    }
                    if ($item.attr('data-animation-style')) {
                        window.et_animate_element($item);
                    }
                }
            });

            setFill(index);

            // Auto-scroll only when the active item is at/past the viewport edge.
            if (wrapper.classList.contains('difl-tt--scrollable-nav') && slider_items[index]) {
                slider_items[index].scrollIntoView({ behavior: 'smooth', inline: 'nearest', block: 'nearest' });
            }

            if (!loop && prevBtn) prevBtn.disabled = index === 0;
            if (!loop && nextBtn) nextBtn.disabled = index === total - 1;
        }

        // ── Init ─────────────────────────────────────────────────────

        if (defaultActiveIndex >= total) defaultActiveIndex = 0;
        activate(defaultActiveIndex, true);

        // Enable pin transition only AFTER the first paint with correct coords,
        // so the pin appears at the active dot without a slide-in from the fallback position.
        requestAnimationFrame(function () {
            requestAnimationFrame(function () {
                wrapper.classList.add('is-tt-ready');
            });
        });

        // ── Event listeners ───────────────────────────────────────────

        slider_items.forEach(function (slider_item, i) {
            if (trigger === 'hover') {
                // Hover trigger: only activate the tab. Do NOT touch the autoplay timer here —
                // that's the wrapper-level Pause-on-Hover listeners' job (added below only when
                // autoplayPauseHover is true). This way the user's "Pause on Hover" toggle is
                // the single source of truth, and turning it OFF keeps autoplay cycling even
                // while the cursor sits on a tab.
                slider_item.addEventListener('mouseenter', function () {
                    activate(i);
                });
            } else {
                // Click trigger: discrete event — reset the autoplay cycle so the newly active
                // tab gets a full autoplaySpeed window before the next advance.
                slider_item.addEventListener('click', function () {
                    if (autoplay) slider_itemAutoplay();
                    activate(i);
                    if (autoplay) startAutoplay();
                });
            }
        });

        if (prevBtn) {
            prevBtn.addEventListener('click', function () {
                if (autoplay) slider_itemAutoplay();
                activate(currentIndex - 1);
                if (autoplay) startAutoplay();
            });
        }

        if (nextBtn) {
            nextBtn.addEventListener('click', function () {
                if (autoplay) slider_itemAutoplay();
                activate(currentIndex + 1);
                if (autoplay) startAutoplay();
            });
        }

        // ── Autoplay ──────────────────────────────────────────────────

        function startAutoplay() {
            if (autoplayTimer) clearInterval(autoplayTimer);
            autoplayTimer = setInterval(function () {
                if (!loop && currentIndex === total - 1) { slider_itemAutoplay(); return; }
                activate((currentIndex + 1) % total);
            }, autoplaySpeed);
        }

        function slider_itemAutoplay() {
            if (autoplayTimer) { clearInterval(autoplayTimer); autoplayTimer = null; }
        }

        if (autoplay) {
            if (autoplayPauseHover) {
                wrapper.addEventListener('mouseenter', slider_itemAutoplay);
                wrapper.addEventListener('mouseleave', startAutoplay);
            }
            startAutoplay();
        }

        window.addEventListener('resize', function () { setFill(currentIndex); });
    }

    function init() {
        document.querySelectorAll('.difl-timeline-tabs').forEach(function (wrapper) {
            initTimelineTabs(wrapper);
        });
    }

    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', init);
    } else {
        init();
    }

    if (window.jQuery) {
        jQuery(document).on('after_tone_set', init);
    }
})();
