(function ($) {
    'use strict';

    const SifencyTextualShowcase = function ($scope, $) {
        const $wrapper = $scope.find('.sifency-textual-showcase-wrapper');
        const $follower = $scope.find('.sifency-ts-cursor-follower');
        const $followerImg = $follower.find('img');
        const $mediaItems = $scope.find('.sifency-ts-media-item');

        if (!$follower.length) return;

        let settings = { speed: 0.1 };
        try {
            const raw = $wrapper.data('ts-settings');
            if (raw) $.extend(settings, raw);
        } catch (e) {}

        // Cursor Position Logic
        let mouseX = 0, mouseY = 0;
        let cursorX = 0, cursorY = 0;

        $wrapper.on('mousemove', function(e) {
            const offset = $wrapper.offset();
            mouseX = e.pageX - offset.left;
            mouseY = e.pageY - offset.top;
        });

        // Hover Logic per Item
        $mediaItems.on('mouseenter', function() {
            const cursorSrc = $(this).data('cursor-src');
            
            // Only show cursor if this specific item has a cursor image set
            if(cursorSrc) {
                $followerImg.attr('src', cursorSrc);
                $follower.addClass('is-visible');
            }
        });

        $mediaItems.on('mouseleave', function() {
            $follower.removeClass('is-visible');
            // Optional: clear src after transition to avoid flicker, or keep for cache
        });

        // Animation Loop
        function animateCursor() {
            if (!$wrapper.closest('body').length) return;

            const speed = settings.speed;
            cursorX += (mouseX - cursorX) * speed;
            cursorY += (mouseY - cursorY) * speed;

            $follower.css({
                'transform': `translate(${cursorX}px, ${cursorY}px)`
            });

            requestAnimationFrame(animateCursor);
        }

        animateCursor();
    };

    $(window).on('elementor/frontend/init', function () {
        elementorFrontend.hooks.addAction('frontend/element_ready/sifency-textual-showcase.default', SifencyTextualShowcase);
    });

})(jQuery);