

$(document).ready(function() {
    $('.shuffle-hover .tn-atom').each(function() {
        var text = $(this).text();
        $(this).attr('data-text', text);
        $(this).attr('data-animation-in-progress', 'false'); // Индивидуальная переменная
    });

    // Обрабатываем наведение мыши
    $('.shuffle-hover .tn-atom').mouseenter(function() {
        var animationInProgress = $(this).attr('data-animation-in-progress') === 'true';
        if (animationInProgress) return;
        
        var element = $(this).find('a').length > 0 ? $(this).find('a') : $(this);
        var originalText = $(this).data('text');
        var animationDuration = 300; // Длительность всей анимации в миллисекундах

        // Изменяем цвет текста при наведении
        $(this).css('color', '#E94545');
        
        $(this).attr('data-animation-in-progress', 'true'); // Устанавливаем анимацию в процессе
        shuffleText(element, originalText, animationDuration, () => {
            reverseText(element, originalText, animationDuration, () => {
                $(this).attr('data-animation-in-progress', 'false'); // Анимация завершена
            });
        });
    });

    // Возвращаем исходный цвет текста при уходе мыши
    $('.shuffle-hover .tn-atom').mouseleave(function() {
        $(this).css('color', ''); // Вернуть исходный цвет
    });

    // Функция для анимации текста (перемешивание символов)
    function shuffleText(element, originalText, duration, onComplete) {
        var elementTextArray = originalText.split('');
        var currentIndex = 0;
        var stepDuration = duration / elementTextArray.length;
        var randomChars = '!-_\\/[]{}—=+*^?#________';

        function shuffleStep() {
            if (currentIndex < elementTextArray.length) {
                elementTextArray[currentIndex] = randomChars.charAt(Math.floor(Math.random() * randomChars.length));
                element.text(elementTextArray.join(''));
                currentIndex++;
                setTimeout(shuffleStep, stepDuration);
            } else {
                onComplete();
            }
        }
        shuffleStep();
    }

    // Функция для возврата текста в исходное состояние
    function reverseText(element, originalText, duration, onComplete) {
        var elementTextArray = element.text().split('');
        var currentIndex = elementTextArray.length - 1;
        var stepDuration = duration / elementTextArray.length;

        function reverseStep() {
            if (currentIndex >= 0) {
                elementTextArray[currentIndex] = originalText.charAt(currentIndex);
                element.text(elementTextArray.join(''));
                currentIndex--;
                setTimeout(reverseStep, stepDuration);
            } else {
                onComplete();
            }
        }
        reverseStep();
    }
});
