;(function($) {
    'use strict';

    /**
     * Initialize Party Propz Widget
     */
    function initPartyPropz($scope) {
        const $wrapper = $scope.find('.unlockafe-party-propz-wrapper');
        
        if ($wrapper.length === 0) {
            return;
        }

        const animationType = $wrapper.data('animation-type') || 'float';
        const animationSpeed = parseFloat($wrapper.data('animation-speed')) || 3;
        const randomDelay = $wrapper.data('random-delay') === 'yes';
        const interactive = $wrapper.data('interactive') === 'yes';
        const enableSnow = $wrapper.data('enable-snow') === 'yes';
        const snowCount = parseInt($wrapper.data('snow-count')) || 50;
        const snowSpeed = parseFloat($wrapper.data('snow-speed')) || 3;
        const snowSize = parseInt($wrapper.data('snow-size')) || 5;
        const snowColor = $wrapper.data('snow-color') || '#d3d3d3';
        const snowDesign = $wrapper.data('snow-design') || 'default';
        const snowOpacity = parseFloat($wrapper.data('snow-opacity')) || 0.7;
        const snowBlur = parseFloat($wrapper.data('snow-blur')) || 0.5;
        const $props = $wrapper.find('.unlockafe-party-prop');

        // Debug log
        if (enableSnow) {
            console.log('Party Propz: Initializing snow', {
                enableSnow: enableSnow,
                snowCount: snowCount,
                snowSpeed: snowSpeed,
                snowSize: snowSize
            });
        }

        // Apply random delays if enabled
        if ($props.length > 0 && randomDelay) {
            $props.each(function(index) {
                const $prop = $(this);
                const randomDelayValue = Math.random() * 2; // 0 to 2 seconds
                $prop.css('animation-delay', randomDelayValue + 's');
            });
        }

        // Adjust animation speed
        if ($props.length > 0) {
            $props.each(function() {
                const $prop = $(this);
                const currentAnimation = $prop.css('animation');
                if (currentAnimation && currentAnimation !== 'none') {
                    // Extract animation name and update duration
                    const animationName = animationType;
                    const baseDuration = 3; // Base duration in seconds
                    const duration = baseDuration / animationSpeed;
                    $prop.css('animation-duration', duration + 's');
                }
            });
        }

        // Interactive mouse follow effect
        if (interactive) {
            let mouseX = 0;
            let mouseY = 0;
            let propPositions = [];

            // Store initial positions
            $props.each(function() {
                const $prop = $(this);
                propPositions.push({
                    element: $prop,
                    baseX: parseFloat($prop.css('left')) || 50,
                    baseY: parseFloat($prop.css('top')) || 50,
                    offsetX: 0,
                    offsetY: 0
                });
            });

            // Track mouse position
            $wrapper.on('mousemove.partyPropz', function(e) {
                const rect = $wrapper[0].getBoundingClientRect();
                mouseX = ((e.clientX - rect.left) / rect.width) * 100;
                mouseY = ((e.clientY - rect.top) / rect.height) * 100;

                // Update prop positions based on mouse
                propPositions.forEach(function(prop) {
                    const distanceX = mouseX - prop.baseX;
                    const distanceY = mouseY - prop.baseY;
                    const distance = Math.sqrt(distanceX * distanceX + distanceY * distanceY);
                    const maxDistance = 50; // Maximum influence distance
                    
                    if (distance < maxDistance) {
                        const influence = 1 - (distance / maxDistance);
                        prop.offsetX = distanceX * influence * 0.3;
                        prop.offsetY = distanceY * influence * 0.3;
                    } else {
                        prop.offsetX = 0;
                        prop.offsetY = 0;
                    }

                    prop.element.css({
                        'transform': 'translate(' + prop.offsetX + '%, ' + prop.offsetY + '%)',
                        'transition': 'transform 0.3s ease-out'
                    });
                });
            });

            // Reset on mouse leave
            $wrapper.on('mouseleave.partyPropz', function() {
                propPositions.forEach(function(prop) {
                    prop.offsetX = 0;
                    prop.offsetY = 0;
                    prop.element.css({
                        'transform': 'translate(0, 0)',
                        'transition': 'transform 0.5s ease-out'
                    });
                });
            });
        }

        // Add hover effects
        if ($props.length > 0) {
            $props.on('mouseenter', function() {
                $(this).css('transform', 'scale(1.2)');
            }).on('mouseleave', function() {
                $(this).css('transform', 'scale(1)');
            });
        }

        // Initialize falling snow effect (works even without props)
        if (enableSnow) {
            // Find parent section
            const $section = $wrapper.closest('.elementor-section');
            const $targetContainer = $section.length > 0 ? $section : $wrapper.closest('.elementor-widget-container').parent();
            
            // Check if snow container already exists in this section
            if ($targetContainer.find('.unlockafe-snow-container').length === 0) {
                initFallingSnow($wrapper, snowCount, snowSpeed, snowSize, snowColor, snowDesign, snowOpacity, snowBlur);
            } else {
                // Update existing snow container settings
                const $existingContainer = $targetContainer.find('.unlockafe-snow-container').first();
                $existingContainer.empty();
                initFallingSnow($wrapper, snowCount, snowSpeed, snowSize, snowColor, snowDesign, snowOpacity, snowBlur);
            }
        } else {
            // Remove snow if disabled
            const $section = $wrapper.closest('.elementor-section');
            const $targetContainer = $section.length > 0 ? $section : $wrapper.closest('.elementor-widget-container').parent();
            $targetContainer.find('.unlockafe-snow-container').remove();
        }
    }

    /**
     * Initialize Falling Snow Effect
     */
    function initFallingSnow($wrapper, count, speed, size, color, design, opacity, blur) {
        // Find the parent Elementor section
        const $section = $wrapper.closest('.elementor-section');
        
        // If no section found, use the widget's parent container
        const $targetContainer = $section.length > 0 ? $section : $wrapper.closest('.elementor-widget-container').parent();
        
        // Remove existing snow container from this section
        $targetContainer.find('.unlockafe-snow-container').remove();
        $wrapper.find('.unlockafe-snow-container').remove();

        // Create snow container - append to section/container
        const $snowContainer = $('<div class="unlockafe-snow-container"></div>');
        $targetContainer.append($snowContainer);

        // Get container dimensions - ensure full width coverage
        const containerWidth = $targetContainer.outerWidth() || $targetContainer.width() || $targetContainer.innerWidth() || $(window).width();
        const containerHeight = $targetContainer.outerHeight() || $targetContainer.height() || $targetContainer.innerHeight() || $(window).height();
        
        // Ensure snow container covers 100% width
        $snowContainer.css({
            'width': '100%',
            'min-width': '100%',
            'left': '0',
            'right': '0'
        });
        
        console.log('Party Propz: Creating snow container', {
            containerWidth: containerWidth,
            containerHeight: containerHeight,
            count: count,
            speed: speed,
            size: size,
            target: $targetContainer.length > 0 ? $targetContainer[0].className : 'not found'
        });

        // Generate snowflakes - randomly distributed across full width
        for (let i = 0; i < count; i++) {
            const $snowflake = $('<div class="unlockafe-snowflake"></div>');
            
            // Random starting position across full width (0-100%)
            const startX = Math.random() * 100;
            
            // Random horizontal drift (wider range for more natural movement)
            const drift = (Math.random() - 0.5) * 80; // -40 to 40 pixels
            
            // Random animation duration (3-10 seconds based on speed)
            const baseDuration = 10 / speed;
            const duration = baseDuration + (Math.random() * 3);
            
            // Random delay (0-3 seconds for staggered effect)
            const delay = Math.random() * 3;
            
            // Random size variation (between size and size*1.5)
            const sizeVariation = size + (Math.random() * size * 0.5);
            
            // Random opacity for variety
            const opacity = 0.5 + (Math.random() * 0.3); // 0.5 to 0.8
            
            // Set CSS custom properties
            $snowflake.css({
                'left': startX + '%',
                'font-size': sizeVariation + 'px',
                'animation-duration': duration + 's',
                'animation-delay': delay + 's',
                'color': '#d3d3d3',
                'opacity': opacity
            });
            
            // Set CSS variable for drift using native method
            $snowflake[0].style.setProperty('--snow-drift', drift + 'px');
            
            $snowContainer.append($snowflake);
        }

        // Handle window resize
        let resizeTimeout;
        const $parentContainer = $snowContainer.parent();
        $(window).on('resize.partyPropzSnow', function() {
            clearTimeout(resizeTimeout);
            resizeTimeout = setTimeout(function() {
                // Recreate snowflakes on resize
                $snowContainer.empty();
                const newWidth = $parentContainer.width() || $parentContainer.innerWidth() || $(window).width();
                const newHeight = $parentContainer.height() || $parentContainer.innerHeight() || $(window).height();
                
                // Get settings from wrapper
                const snowColor = $wrapper.data('snow-color') || '#d3d3d3';
                const snowDesign = $wrapper.data('snow-design') || 'default';
                const snowOpacity = parseFloat($wrapper.data('snow-opacity')) || 0.7;
                const snowBlur = parseFloat($wrapper.data('snow-blur')) || 0.5;
                
                const designChars = {
                    'default': '❄',
                    'dot': '•',
                    'circle': '●',
                    'star': '★',
                    'cross': '✕',
                    'diamond': '◆'
                };
                const snowChar = designChars[snowDesign] || designChars['default'];
                
                for (let i = 0; i < count; i++) {
                    const $snowflake = $('<div class="unlockafe-snowflake unlockafe-snow-' + snowDesign + '"></div>');
                    const startX = Math.random() * 100;
                    const drift = (Math.random() - 0.5) * 80;
                    const baseDuration = 10 / speed;
                    const duration = baseDuration + (Math.random() * 3);
                    const delay = Math.random() * 3;
                    const sizeVariation = size + (Math.random() * size * 0.5);
                    const randomOpacity = (snowOpacity * 0.7) + (Math.random() * (snowOpacity * 0.3));
                    
                    $snowflake.css({
                        'left': startX + '%',
                        'font-size': sizeVariation + 'px',
                        'animation-duration': duration + 's',
                        'animation-delay': delay + 's',
                        'color': snowColor,
                        'opacity': randomOpacity,
                        'filter': 'blur(' + snowBlur + 'px)'
                    });
                    
                    $snowflake.attr('data-snow-char', snowChar);
                    $snowflake[0].style.setProperty('--snow-drift', drift + 'px');
                    
                    $snowContainer.append($snowflake);
                }
            }, 250);
        });
    }

    // Initialize on Elementor frontend
    $(window).on('elementor/frontend/init', function() {
        elementorFrontend.hooks.addAction('frontend/element_ready/unlockafe-party-propz.default', function($scope) {
            initPartyPropz($scope);
        });
    });

    // Also initialize on document ready (for non-Elementor pages)
    $(document).ready(function() {
        $('.elementor-widget-unlockafe-party-propz').each(function() {
            var $scope = $(this);
            initPartyPropz($scope);
        });
    });

    // Re-initialize on Elementor preview refresh
    if (typeof elementorFrontend !== 'undefined') {
        elementorFrontend.hooks.addAction('frontend/element_ready/global', function($scope) {
            if ($scope.find('.unlockafe-party-propz-wrapper').length) {
                setTimeout(function() {
                    initPartyPropz($scope);
                }, 100);
            }
        });
    }

    // Initialize in Elementor editor mode
    if (typeof elementor !== 'undefined' && elementor.on) {
        // Listen for widget settings changes
        elementor.channels.editor.on('section:activated', function(sectionName, editor, model) {
            if (model && model.get('widgetType') === 'unlockafe-party-propz') {
                setTimeout(function() {
                    $('.elementor-widget-unlockafe-party-propz').each(function() {
                        var $scope = $(this);
                        initPartyPropz($scope);
                    });
                }, 300);
            }
        });

        // Listen for widget updates
        elementor.channels.editor.on('element:change', function(model) {
            if (model && model.get('widgetType') === 'unlockafe-party-propz') {
                setTimeout(function() {
                    $('.elementor-widget-unlockafe-party-propz').each(function() {
                        var $scope = $(this);
                        initPartyPropz($scope);
                    });
                }, 300);
            }
        });
    }

    // Fallback for Elementor editor - check periodically
    if ($('body').hasClass('elementor-editor-active') || $('body').hasClass('elementor-edit-mode')) {
        var editorCheckInterval = setInterval(function() {
            $('.elementor-widget-unlockafe-party-propz').each(function() {
                var $scope = $(this);
                var $wrapper = $scope.find('.unlockafe-party-propz-wrapper');
                if ($wrapper.length > 0) {
                    var hasSnow = $wrapper.data('enable-snow') === 'yes';
                    var hasSnowContainer = $wrapper.find('.unlockafe-snow-container').length > 0;
                    if (hasSnow && !hasSnowContainer) {
                        initPartyPropz($scope);
                    }
                }
            });
        }, 1000);

        // Clear interval after 30 seconds
        setTimeout(function() {
            clearInterval(editorCheckInterval);
        }, 30000);
    }

})(jQuery);


