(function($) {
    'use strict';
    
function initSlider($container) {
    // ✅ FIX 1: Skip if already initialized
    if ($container.data('sitsel-initialized')) {
        return;
    }
    
    var $beforeImg = $container.find('.sitsel-before-image');
    var $divider = $container.find('.sitsel-divider');
    var $handle = $container.find('.sitsel-handle');
    var $beforeLabel = $container.find('.sitsel-label.before');
    var $afterLabel = $container.find('.sitsel-label.after');
    
    // ✅ Validate elements exist
    if ($beforeImg.length === 0 || $divider.length === 0) {
        return;
    }
    
    var direction = $container.data('direction') || 'horizontal';
    var initialPos = parseFloat($container.data('initial-position')) || 50;
    var triggerType = $container.data('trigger-type') || 'click_drag';
    
    // Generate unique ID for this slider instance
    var sliderId = 'slider-' + Math.random().toString(36).substr(2, 9);
    $container.attr('data-slider-id', sliderId);
    
    var isDragging = false;
    var lastPercentage = initialPos;
    var containerElement = $container[0];
    
    // Detect if device is mobile/tablet
    var isMobile = /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);
    
    updateSlider(initialPos);
    $container.removeAttr('style');
    $container.addClass('sitsel-ready');
    
    function updateSlider(percentage) {
        percentage = Math.max(0, Math.min(100, percentage));
        lastPercentage = percentage;
        
        if (direction === 'horizontal') {
            var containerWidth = $container.outerWidth();
            var position = (percentage / 100) * containerWidth;
            
            $beforeImg.css('clip-path', 'inset(0 ' + (100 - percentage) + '% 0 0)');
            $divider.css('left', position + 'px');
        } else {
            var containerHeight = $container.outerHeight();
            var position = (percentage / 100) * containerHeight;
            
            $beforeImg.css('clip-path', 'inset(0 0 ' + (100 - percentage) + '% 0)');
            $divider.css('top', position + 'px');
        }
        
        updateLabelVisibility(percentage);
    }

    function updateLabelVisibility(percentage) {
        if (percentage < 15) {
            $beforeLabel.addClass('sitsel-label-hidden');
        } else {
            $beforeLabel.removeClass('sitsel-label-hidden');
        }
        
        if (percentage > 85) {
            $afterLabel.addClass('sitsel-label-hidden');
        } else {
            $afterLabel.removeClass('sitsel-label-hidden');
        }
    }
    
    function handleMove(e) {
        if (!isDragging && triggerType === 'click_drag') return;
        
        if (isDragging) {
            e.stopPropagation();
        }
        
        if (triggerType === 'hover' && !isMobile && !$container.is(':hover')) return;
        
        var rect = containerElement.getBoundingClientRect();
        var percentage;
        
        var isTouchEvent = e.type.indexOf('touch') !== -1;
        var touches = isTouchEvent ? (e.originalEvent ? e.originalEvent.touches : e.touches) : null;
        
        if (direction === 'horizontal') {
            var clientX = isTouchEvent ? touches[0].clientX : e.clientX;
            var x = clientX - rect.left;
            percentage = (x / rect.width) * 100;
        } else {
            var clientY = isTouchEvent ? touches[0].clientY : e.clientY;
            var y = clientY - rect.top;
            percentage = (y / rect.height) * 100;
        }
        
        updateSlider(percentage);
    }
    
    // ✅ FIX 2: Clean up previous events before attaching new ones
    var cleanupKey = 'slider-cleanup-' + sliderId;
    var existingCleanup = $container.data(cleanupKey);
    if (existingCleanup) {
        existingCleanup();
    }
    
    // Mouse events on container (for click & drag)
    if (triggerType === 'click_drag') {
        $container.on('mousedown.sitsel.' + sliderId, function(e) {
            if (!$(e.target).closest('.sitsel-divider, .sitsel-handle').length &&
                !$(e.target).is('.sitsel-before-after-container')) {
                return;
            }
            isDragging = true;
            handleMove(e);
        });
        
        $(document).on('mousemove.sitsel.' + sliderId, function(e) {
            if (isDragging) {
                handleMove(e);
            }
        });
        
        $(document).on('mouseup.sitsel.' + sliderId, function() {
            isDragging = false;
        });
        
        // Touch events
        $container.on('touchstart.sitsel.' + sliderId, function(e) {
            if (!$(e.target).closest('.sitsel-divider, .sitsel-handle').length &&
                !$(e.target).is('.sitsel-before-after-container')) {
                return;
            }
            e.preventDefault();
            isDragging = true;
            handleMove(e);
        });
        
        $(document).on('touchmove.sitsel.' + sliderId, function(e) {
            if (isDragging) {
                e.preventDefault();
                handleMove(e);
            }
        });
        
        $(document).on('touchend.sitsel.' + sliderId, function(e) {
            if (isDragging) {
                e.preventDefault();
            }
            isDragging = false;
        });
    }
    
    // Hover events with mobile drag fallback
    if (triggerType === 'hover') {
        $container.on('mousemove.sitsel.' + sliderId, function(e) {
            handleMove(e);
        });
        
        if (isMobile) {
            var isTouching = false;
            
            containerElement.addEventListener('touchstart', function(e) {
                isTouching = true;
                isDragging = true;
                handleMove(e);
            }, false);
            
            containerElement.addEventListener('touchmove', function(e) {
                if (isTouching) {
                    e.preventDefault();
                    handleMove(e);
                }
            }, false);
            
            containerElement.addEventListener('touchend', function(e) {
                isTouching = false;
                isDragging = false;
            }, false);
            
            containerElement.addEventListener('touchcancel', function(e) {
                isTouching = false;
                isDragging = false;
            }, false);
        } else {
            var isTouching = false;
            
            containerElement.addEventListener('touchstart', function(e) {
                isTouching = true;
            }, false);
            
            containerElement.addEventListener('touchmove', function(e) {
                if (isTouching) {
                    e.preventDefault();
                    handleMove(e);
                }
            }, false);
            
            containerElement.addEventListener('touchend', function(e) {
                isTouching = false;
            }, false);
            
            containerElement.addEventListener('touchcancel', function(e) {
                isTouching = false;
            }, false);
        }
    }
    
    // Handle resize
    $(window).on('resize.sitsel.' + sliderId, function() {
        updateSlider(lastPercentage);
    });
    
    // ✅ Store cleanup function
    $container.data(cleanupKey, function() {
        $(document).off('.sitsel.' + sliderId);
        $(window).off('resize.sitsel.' + sliderId);
        $container.off('.sitsel.' + sliderId);
    });
    
    // ✅ Mark as initialized AFTER everything is set up
    $container.data('sitsel-initialized', true);
}
    
function initAllSliders(scope) {
    var $scope = scope ? $(scope) : $(document);
    var $containers = $scope.find('.sitsel-before-after-container');
    
    if ($scope.hasClass('sitsel-before-after-container')) {
        $containers = $scope;
    }
    
    $containers.each(function() {
        var $container = $(this);
        
        // ✅ FIX 3: This check now works because initSlider() sets the flag
        if ($container.data('sitsel-initialized')) {
            return; // Skip already initialized containers
        }
        
        initSlider($container);
    });
}
    
$(document).ready(function() {
    initAllSliders();
});

// ✅ Elementor support - properly scoped
if (typeof window.elementorFrontend !== 'undefined' && window.elementorFrontend.hooks) {
    window.elementorFrontend.hooks.addAction('frontend/element_ready/sitsel_before_after_slider.default', function($scope) {
        initAllSliders($scope);
    });
}
    
})(jQuery);