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

    /**
     * Initialize 360° Photo Viewer Widget
     */
    function initPhotoViewer360($scope) {
        const $viewer = $scope.find('.unlockafe-360-viewer');
        
        if ($viewer.length === 0) {
            return;
        }

        // Check if already initialized
        if ($viewer.data('viewer-initialized')) {
            return;
        }

        // Wait for Three.js to load if not available yet (for editor mode)
        if (typeof THREE === 'undefined') {
            // Check if Three.js script is in the page but not loaded yet
            const threeScript = document.querySelector('script[src*="three.js"], script[src*="three.min.js"]');
            if (threeScript && !threeScript.hasAttribute('data-loaded')) {
                // Wait for Three.js to load
                let attempts = 0;
                const maxAttempts = 50; // 5 seconds max wait
                const checkThree = setInterval(function() {
                    attempts++;
                    if (typeof THREE !== 'undefined') {
                        threeScript.setAttribute('data-loaded', 'true');
                        clearInterval(checkThree);
                        // Retry initialization
                        setTimeout(function() {
                            initPhotoViewer360($scope);
                        }, 100);
                    } else if (attempts >= maxAttempts) {
                        clearInterval(checkThree);
                        // Fallback to canvas-based viewer
                        initCanvasViewer($scope);
                    }
                }, 100);
                return;
            } else {
                // Three.js not available, use canvas fallback
                initCanvasViewer($scope);
                return;
            }
        }

        const imageUrl = $viewer.data('image-url');
        const placeholderUrl = $viewer.data('placeholder');
        const autoRotate = $viewer.data('auto-rotate') === 'true' || $viewer.data('auto-rotate') === true;
        const autoRotateSpeed = parseFloat($viewer.data('auto-rotate-speed')) || 1;
        const enableZoom = $viewer.data('enable-zoom') === 'true' || $viewer.data('enable-zoom') === true;
        const minZoom = parseInt($viewer.data('min-zoom')) || 50;
        const maxZoom = parseInt($viewer.data('max-zoom')) || 120;
        const initialZoom = parseInt($viewer.data('initial-zoom')) || 100;
        const showControls = $viewer.data('show-controls') === 'true' || $viewer.data('show-controls') === true;

        if (!imageUrl) {
            $viewer.addClass('error');
            $viewer.find('.viewer-loading p').text('No image URL provided.');
            return;
        }

        const container = $viewer[0];
        const $canvas = $viewer.find('.viewer-canvas');
        
        // Initialize Three.js scene
        let scene, camera, renderer, sphere, controls;
        let isDragging = false;
        let lastMouseX = 0;
        let lastMouseY = 0;
        let currentZoom = initialZoom;
        let isAutoRotating = autoRotate;
        let animationFrameId = null;
        let mouseX = 0;
        let mouseY = 0;
        let targetRotationX = 0;
        let targetRotationY = 0;
        let rotationX = 0;
        let rotationY = 0;

        // Initialize Three.js scene
        function initThreeJS() {
            const width = container.offsetWidth;
            const height = container.offsetHeight;

            // Scene
            scene = new THREE.Scene();

            // Camera
            // Invert FOV: higher zoom = lower FOV (more zoomed in)
            // FOV range: 75 (most zoomed out) to 30 (most zoomed in)
            const maxFOV = 75;
            const minFOV = 30;
            const zoomRange = maxZoom - minZoom;
            const fovRange = maxFOV - minFOV;
            const fov = maxFOV - ((currentZoom - minZoom) / zoomRange) * fovRange;
            camera = new THREE.PerspectiveCamera(fov, width / height, 0.1, 1000);
            camera.position.set(0, 0, 0.1);

            // Renderer
            renderer = new THREE.WebGLRenderer({
                canvas: $canvas[0],
                antialias: true,
                alpha: true
            });
            renderer.setSize(width, height);
            renderer.setPixelRatio(window.devicePixelRatio);

            // Create sphere geometry
            const geometry = new THREE.SphereGeometry(500, 60, 40);
            geometry.scale(-1, 1, 1); // Invert sphere

            // Load texture
            const loader = new THREE.TextureLoader();
            loader.crossOrigin = 'anonymous';
            
            loader.load(
                imageUrl,
                function(texture) {
                    // Create material with texture
                    const material = new THREE.MeshBasicMaterial({
                        map: texture
                    });

                    // Create sphere mesh
                    sphere = new THREE.Mesh(geometry, material);
                    scene.add(sphere);

                    $viewer.removeClass('loading').addClass('loaded');
                    animate();
                },
                undefined,
                function(error) {
                    $viewer.addClass('error');
                    $viewer.find('.viewer-loading p').text('Failed to load image.');
                    console.error('Error loading texture:', error);
                }
            );

            $viewer.addClass('loading');
        }

        // Animation loop
        function animate() {
            animationFrameId = requestAnimationFrame(animate);

            // Smooth rotation
            rotationX += (targetRotationX - rotationX) * 0.1;
            rotationY += (targetRotationY - rotationY) * 0.1;

            // Auto rotate
            if (isAutoRotating) {
                targetRotationX += (autoRotateSpeed * 0.01);
            }

            // Apply rotation to sphere
            if (sphere) {
                sphere.rotation.y = rotationX;
                sphere.rotation.x = rotationY;
            }

            // Update camera FOV for zoom
            if (camera) {
                // Invert FOV: higher zoom = lower FOV (more zoomed in)
                // FOV range: 75 (most zoomed out) to 30 (most zoomed in)
                const maxFOV = 75;
                const minFOV = 30;
                const zoomRange = maxZoom - minZoom;
                const fovRange = maxFOV - minFOV;
                const fov = maxFOV - ((currentZoom - minZoom) / zoomRange) * fovRange;
                camera.fov = fov;
                camera.updateProjectionMatrix();
            }

            // Render
            if (renderer && scene && camera) {
                renderer.render(scene, camera);
            }
        }

        // Canvas-based fallback viewer
        function initCanvasViewer($scope) {
            const $viewer = $scope.find('.unlockafe-360-viewer');
            
            if ($viewer.length === 0) {
                return;
            }

            // Check if already initialized
            if ($viewer.data('canvas-viewer-initialized')) {
                return;
            }

            const imageUrl = $viewer.data('image-url');
            const autoRotate = $viewer.data('auto-rotate') === 'true' || $viewer.data('auto-rotate') === true;
            const autoRotateSpeed = parseFloat($viewer.data('auto-rotate-speed')) || 1;
            const enableZoom = $viewer.data('enable-zoom') === 'true' || $viewer.data('enable-zoom') === true;
            const minZoom = parseInt($viewer.data('min-zoom')) || 50;
            const maxZoom = parseInt($viewer.data('max-zoom')) || 120;
            const initialZoom = parseInt($viewer.data('initial-zoom')) || 100;

            if (!imageUrl) {
                $viewer.addClass('error');
                $viewer.find('.viewer-loading p').text('No image URL provided.');
                return;
            }

            const $canvas = $viewer.find('.viewer-canvas');
            if ($canvas.length === 0) {
                return;
            }

            const canvas = $canvas[0];
            const container = $viewer[0];
            let isDragging = false;
            let lastMouseX = 0;
            let rotationX = 0;
            let currentZoom = initialZoom;
            let isAutoRotating = autoRotate;
            let animationFrameId = null;
            let image = null;
            let ctx = null;

            function initCanvas() {
                if (!canvas) {
                    return;
                }
                ctx = canvas.getContext('2d');
                resizeCanvas();
                
                image = new Image();
                image.crossOrigin = 'anonymous';
                
                image.onload = function() {
                    $viewer.removeClass('loading').addClass('loaded');
                    draw();
                };
                
                image.onerror = function() {
                    $viewer.addClass('error');
                    $viewer.find('.viewer-loading p').text('Failed to load image.');
                };
                
                $viewer.addClass('loading');
                image.src = imageUrl;
            }

            function resizeCanvas() {
                const rect = container.getBoundingClientRect();
                canvas.width = rect.width;
                canvas.height = rect.height;
                // Redraw after resize
                if (image && image.complete) {
                    draw();
                }
            }
            
            // Fullscreen handler for canvas viewer
            function toggleFullscreenCanvas() {
                const isFullscreen = document.fullscreenElement || document.webkitFullscreenElement || document.mozFullScreenElement || document.msFullscreenElement;
                
                if (!isFullscreen) {
                    const element = container;
                    if (element.requestFullscreen) {
                        element.requestFullscreen().then(function() {
                            $viewer.addClass('fullscreen');
                            setTimeout(resizeCanvas, 100);
                        }).catch(function(err) {
                            console.error('Error entering fullscreen:', err);
                        });
                    } else if (element.webkitRequestFullscreen) {
                        element.webkitRequestFullscreen();
                        $viewer.addClass('fullscreen');
                        setTimeout(resizeCanvas, 100);
                    } else if (element.mozRequestFullScreen) {
                        element.mozRequestFullScreen();
                        $viewer.addClass('fullscreen');
                        setTimeout(resizeCanvas, 100);
                    } else if (element.msRequestFullscreen) {
                        element.msRequestFullscreen();
                        $viewer.addClass('fullscreen');
                        setTimeout(resizeCanvas, 100);
                    } else {
                        $viewer.addClass('fullscreen');
                        setTimeout(resizeCanvas, 100);
                    }
                } else {
                    if (document.exitFullscreen) {
                        document.exitFullscreen().then(function() {
                            $viewer.removeClass('fullscreen');
                            setTimeout(resizeCanvas, 100);
                        }).catch(function(err) {
                            console.error('Error exiting fullscreen:', err);
                        });
                    } else if (document.webkitExitFullscreen) {
                        document.webkitExitFullscreen();
                        $viewer.removeClass('fullscreen');
                        setTimeout(resizeCanvas, 100);
                    } else if (document.mozCancelFullScreen) {
                        document.mozCancelFullScreen();
                        $viewer.removeClass('fullscreen');
                        setTimeout(resizeCanvas, 100);
                    } else if (document.msExitFullscreen) {
                        document.msExitFullscreen();
                        $viewer.removeClass('fullscreen');
                        setTimeout(resizeCanvas, 100);
                    } else {
                        $viewer.removeClass('fullscreen');
                        setTimeout(resizeCanvas, 100);
                    }
                }
            }
            
            // Fullscreen change for canvas viewer
            $(document).on('fullscreenchange.canvasviewer webkitfullscreenchange.canvasviewer mozfullscreenchange.canvasviewer MSFullscreenChange.canvasviewer', function() {
                const isFullscreen = document.fullscreenElement || document.webkitFullscreenElement || document.mozFullScreenElement || document.msFullscreenElement;
                if (!isFullscreen) {
                    $viewer.removeClass('fullscreen');
                } else {
                    $viewer.addClass('fullscreen');
                }
                setTimeout(resizeCanvas, 100);
            });
            
            // Add fullscreen button handler for canvas viewer
            const showControls = $viewer.data('show-controls') === 'true' || $viewer.data('show-controls') === true;
            if (showControls) {
                $viewer.find('.viewer-btn-fullscreen').on('click', toggleFullscreenCanvas);
            }

            function draw() {
                if (!ctx || !image || !image.complete) {
                    return;
                }

                const width = canvas.width;
                const height = canvas.height;
                const imageWidth = image.width;
                const imageHeight = image.height;
                
                let normalizedRotation = rotationX % 360;
                if (normalizedRotation < 0) normalizedRotation += 360;
                
                const zoomFactor = currentZoom / 100;
                const visibleWidth = Math.min(imageWidth, imageWidth * zoomFactor);
                let startX = (normalizedRotation / 360) * imageWidth;
                
                if (startX + visibleWidth > imageWidth) {
                    const firstPartWidth = imageWidth - startX;
                    const secondPartWidth = visibleWidth - firstPartWidth;
                    
                    ctx.clearRect(0, 0, width, height);
                    ctx.drawImage(image, startX, 0, firstPartWidth, imageHeight, 0, 0, (firstPartWidth / visibleWidth) * width, height);
                    ctx.drawImage(image, 0, 0, secondPartWidth, imageHeight, (firstPartWidth / visibleWidth) * width, 0, (secondPartWidth / visibleWidth) * width, height);
                } else {
                    ctx.clearRect(0, 0, width, height);
                    ctx.drawImage(image, startX, 0, visibleWidth, imageHeight, 0, 0, width, height);
                }

                if (isAutoRotating) {
                    rotationX += (autoRotateSpeed * 0.1);
                    if (rotationX >= 360) rotationX -= 360;
                }
            }

            function animate() {
                draw();
                animationFrameId = requestAnimationFrame(animate);
            }

            function handleStart(e) {
                isDragging = true;
                isAutoRotating = false;
                const clientX = e.touches ? e.touches[0].clientX : e.clientX;
                lastMouseX = clientX;
                $viewer.addClass('touching');
                e.preventDefault();
            }

            function handleMove(e) {
                if (!isDragging) return;
                const clientX = e.touches ? e.touches[0].clientX : e.clientX;
                const deltaX = clientX - lastMouseX;
                rotationX += deltaX * 0.5;
                rotationX = rotationX % 360;
                if (rotationX < 0) rotationX += 360;
                lastMouseX = clientX;
                e.preventDefault();
            }

            function handleEnd() {
                isDragging = false;
                $viewer.removeClass('touching');
            }

            canvas.addEventListener('mousedown', handleStart);
            canvas.addEventListener('mousemove', handleMove);
            canvas.addEventListener('mouseup', handleEnd);
            canvas.addEventListener('mouseleave', handleEnd);
            canvas.addEventListener('touchstart', handleStart);
            canvas.addEventListener('touchmove', handleMove);
            canvas.addEventListener('touchend', handleEnd);

            if (enableZoom) {
                canvas.addEventListener('wheel', function(e) {
                    e.preventDefault();
                    const delta = e.deltaY > 0 ? -5 : 5;
                    currentZoom = Math.max(minZoom, Math.min(maxZoom, currentZoom + delta));
                });
            }

            // Window resize handler for canvas viewer
            $(window).on('resize.canvasviewer', function() {
                resizeCanvas();
            });
            
            // Mark as initialized
            $viewer.data('canvas-viewer-initialized', true);
            $viewer.data('viewer-initialized', true);
            
            // Mark as initialized before starting
            $viewer.data('canvas-viewer-initialized', true);
            $viewer.data('viewer-initialized', true);
            
            initCanvas();
            animate();
        }

        // Mouse/Touch events
        function handleStart(e) {
            isDragging = true;
            isAutoRotating = false;
            $viewer.find('.viewer-btn-rotate').removeClass('active');
            
            const clientX = e.touches ? e.touches[0].clientX : e.clientX;
            const clientY = e.touches ? e.touches[0].clientY : e.clientY;
            
            lastMouseX = clientX;
            lastMouseY = clientY;
            
            $viewer.addClass('touching');
            e.preventDefault();
        }

        function handleMove(e) {
            if (!isDragging) return;
            
            const clientX = e.touches ? e.touches[0].clientX : e.clientX;
            const clientY = e.touches ? e.touches[0].clientY : e.clientY;
            
            const deltaX = clientX - lastMouseX;
            const deltaY = clientY - lastMouseY;
            
            // Horizontal rotation
            targetRotationX += deltaX * 0.01;
            
            // Vertical rotation (limited)
            targetRotationY += deltaY * 0.01;
            targetRotationY = Math.max(-Math.PI / 3, Math.min(Math.PI / 3, targetRotationY));
            
            lastMouseX = clientX;
            lastMouseY = clientY;
            
            e.preventDefault();
        }

        function handleEnd(e) {
            isDragging = false;
            $viewer.removeClass('touching');
        }

        // Zoom functions
        function zoomIn() {
            if (enableZoom && currentZoom < maxZoom) {
                currentZoom = Math.min(maxZoom, currentZoom + 10);
            }
        }

        function zoomOut() {
            if (enableZoom && currentZoom > minZoom) {
                currentZoom = Math.max(minZoom, currentZoom - 10);
            }
        }

        // Toggle auto rotate
        function toggleAutoRotate() {
            isAutoRotating = !isAutoRotating;
            $viewer.find('.viewer-btn-rotate').toggleClass('active', isAutoRotating);
        }

        // Fullscreen
        function toggleFullscreen() {
            const isFullscreen = document.fullscreenElement || document.webkitFullscreenElement || document.mozFullScreenElement || document.msFullscreenElement;
            
            if (!isFullscreen) {
                // Enter fullscreen
                const element = container;
                if (element.requestFullscreen) {
                    element.requestFullscreen().then(function() {
                        $viewer.addClass('fullscreen');
                        handleFullscreenResize();
                    }).catch(function(err) {
                        console.error('Error entering fullscreen:', err);
                    });
                } else if (element.webkitRequestFullscreen) {
                    element.webkitRequestFullscreen();
                    $viewer.addClass('fullscreen');
                    handleFullscreenResize();
                } else if (element.mozRequestFullScreen) {
                    element.mozRequestFullScreen();
                    $viewer.addClass('fullscreen');
                    handleFullscreenResize();
                } else if (element.msRequestFullscreen) {
                    element.msRequestFullscreen();
                    $viewer.addClass('fullscreen');
                    handleFullscreenResize();
                } else {
                    // Fallback: use CSS fullscreen
                    $viewer.addClass('fullscreen');
                    handleFullscreenResize();
                }
            } else {
                // Exit fullscreen
                if (document.exitFullscreen) {
                    document.exitFullscreen().then(function() {
                        $viewer.removeClass('fullscreen');
                        handleFullscreenResize();
                    }).catch(function(err) {
                        console.error('Error exiting fullscreen:', err);
                    });
                } else if (document.webkitExitFullscreen) {
                    document.webkitExitFullscreen();
                    $viewer.removeClass('fullscreen');
                    handleFullscreenResize();
                } else if (document.mozCancelFullScreen) {
                    document.mozCancelFullScreen();
                    $viewer.removeClass('fullscreen');
                    handleFullscreenResize();
                } else if (document.msExitFullscreen) {
                    document.msExitFullscreen();
                    $viewer.removeClass('fullscreen');
                    handleFullscreenResize();
                } else {
                    // Fallback: remove CSS fullscreen
                    $viewer.removeClass('fullscreen');
                    handleFullscreenResize();
                }
            }
        }
        
        // Handle resize when entering/exiting fullscreen
        function handleFullscreenResize() {
            setTimeout(function() {
                if (renderer && camera) {
                    const width = container.offsetWidth;
                    const height = container.offsetHeight;
                    camera.aspect = width / height;
                    camera.updateProjectionMatrix();
                    renderer.setSize(width, height);
                }
                // Also handle canvas resize for fallback viewer
                if ($canvas && $canvas.length) {
                    const canvas = $canvas[0];
                    if (canvas) {
                        const rect = container.getBoundingClientRect();
                        canvas.width = rect.width;
                        canvas.height = rect.height;
                    }
                }
            }, 100);
        }

        // Event listeners
        $canvas.on('mousedown', handleStart);
        $(document).on('mousemove.viewer360', handleMove);
        $(document).on('mouseup.viewer360', handleEnd);
        
        $canvas.on('touchstart', handleStart);
        $canvas.on('touchmove', handleMove);
        $canvas.on('touchend', handleEnd);

        // Wheel zoom
        if (enableZoom) {
            $canvas.on('wheel', function(e) {
                e.preventDefault();
                const delta = e.originalEvent.deltaY > 0 ? -5 : 5;
                currentZoom = Math.max(minZoom, Math.min(maxZoom, currentZoom + delta));
            });
        }

        // Control buttons
        if (showControls) {
            $viewer.find('.viewer-btn-zoom-in').on('click', zoomIn);
            $viewer.find('.viewer-btn-zoom-out').on('click', zoomOut);
            $viewer.find('.viewer-btn-rotate').on('click', toggleAutoRotate);
            $viewer.find('.viewer-btn-fullscreen').on('click', toggleFullscreen);
            
            if (autoRotate) {
                $viewer.find('.viewer-btn-rotate').addClass('active');
            }
        }

        // Window resize
        $(window).on('resize.viewer360', function() {
            resizeCanvas();
            draw();
        });

        // Fullscreen change
        $(document).on('fullscreenchange webkitfullscreenchange mozfullscreenchange MSFullscreenChange', function() {
            const isFullscreen = document.fullscreenElement || document.webkitFullscreenElement || document.mozFullScreenElement || document.msFullscreenElement;
            if (!isFullscreen) {
                $viewer.removeClass('fullscreen');
                handleFullscreenResize();
            } else {
                $viewer.addClass('fullscreen');
                handleFullscreenResize();
            }
        });

        // Window resize handler
        function handleResize() {
            if (!renderer || !camera || !container) return;
            const rect = container.getBoundingClientRect();
            const width = rect.width;
            const height = rect.height;
            
            if (width > 0 && height > 0) {
                camera.aspect = width / height;
                camera.updateProjectionMatrix();
                renderer.setSize(width, height);
            }
        }

        // Initialize Three.js first
        initThreeJS();
        
        // Set up resize handlers after initialization
        $(window).on('resize.viewer360', handleResize);
        
        // Use ResizeObserver for better resize detection (detects Elementor editor changes)
        if (typeof ResizeObserver !== 'undefined' && container) {
            const resizeObserver = new ResizeObserver(function(entries) {
                // Debounce resize calls
                clearTimeout($viewer.data('resize-timeout'));
                const timeout = setTimeout(function() {
                    handleResize();
                }, 100);
                $viewer.data('resize-timeout', timeout);
            });
            resizeObserver.observe(container);
            
            // Store observer for cleanup
            $viewer.data('resize-observer', resizeObserver);
        }
        
        // Also listen for Elementor editor changes
        if (typeof elementorFrontend !== 'undefined' && elementorFrontend.isEditMode) {
            $(document).on('elementor/popup/show.viewer360', handleResize);
            $(document).on('elementor/frontend/element_ready/global.viewer360', function() {
                setTimeout(handleResize, 200);
            });
        }

        // Mark as initialized
        $viewer.data('viewer-initialized', true);

        // Cleanup function
        $viewer.on('destroy', function() {
            if (animationFrameId) {
                cancelAnimationFrame(animationFrameId);
            }
            $(window).off('resize.viewer360');
            $(document).off('mousemove.viewer360 mouseup.viewer360');
            $(document).off('fullscreenchange webkitfullscreenchange mozfullscreenchange');
            if (renderer) {
                renderer.dispose();
            }
        });
    }

    // Initialize on Elementor frontend
    $(window).on('elementor/frontend/init', function() {
        elementorFrontend.hooks.addAction('frontend/element_ready/unlockafe-photo-viewer-360.default', function($scope) {
            initPhotoViewer360($scope);
        });
    });

    // Re-initialize on Elementor preview refresh (works in both frontend and editor)
    if (typeof elementorFrontend !== 'undefined') {
        elementorFrontend.hooks.addAction('frontend/element_ready/global', function($scope) {
            if ($scope.find('.unlockafe-360-viewer').length) {
                setTimeout(function() {
                    initPhotoViewer360($scope);
                }, 200);
            }
        });
    }

    // 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-photo-viewer-360') {
                setTimeout(function() {
                    $('.elementor-widget-unlockafe-photo-viewer-360').each(function() {
                        var $scope = $(this);
                        const $viewer = $scope.find('.unlockafe-360-viewer');
                        if ($viewer.length > 0) {
                            $viewer.removeData('viewer-initialized');
                            initPhotoViewer360($scope);
                        }
                    });
                }, 400);
            }
        });

        // Listen for widget updates
        elementor.channels.editor.on('element:change', function(model) {
            if (model && model.get('widgetType') === 'unlockafe-photo-viewer-360') {
                setTimeout(function() {
                    $('.elementor-widget-unlockafe-photo-viewer-360').each(function() {
                        var $scope = $(this);
                        const $viewer = $scope.find('.unlockafe-360-viewer');
                        if ($viewer.length > 0) {
                            $viewer.removeData('viewer-initialized');
                            initPhotoViewer360($scope);
                        }
                    });
                }, 400);
            }
        });
    }

    // Also initialize on document ready (for non-Elementor pages and editor fallback)
    $(document).ready(function() {
        // Initial load
        setTimeout(function() {
            $('.elementor-widget-unlockafe-photo-viewer-360, .unlockafe-360-viewer').closest('.elementor-widget-unlockafe-photo-viewer-360').each(function() {
                var $scope = $(this);
                initPhotoViewer360($scope);
            });
        }, 300);

        // Additional fallback for editor mode
        if (typeof elementorFrontend !== 'undefined' && elementorFrontend.isEditMode) {
            setTimeout(function() {
                $('.elementor-widget-unlockafe-photo-viewer-360, .unlockafe-360-viewer').closest('.elementor-widget-unlockafe-photo-viewer-360').each(function() {
                    var $scope = $(this);
                    const $viewer = $scope.find('.unlockafe-360-viewer');
                    if ($viewer.length > 0 && !$viewer.data('viewer-initialized')) {
                        $viewer.removeData('viewer-initialized');
                        $viewer.removeData('canvas-viewer-initialized');
                        initPhotoViewer360($scope);
                    }
                });
            }, 500);
            
            setTimeout(function() {
                $('.elementor-widget-unlockafe-photo-viewer-360, .unlockafe-360-viewer').closest('.elementor-widget-unlockafe-photo-viewer-360').each(function() {
                    var $scope = $(this);
                    const $viewer = $scope.find('.unlockafe-360-viewer');
                    if ($viewer.length > 0 && !$viewer.data('viewer-initialized')) {
                        $viewer.removeData('viewer-initialized');
                        $viewer.removeData('canvas-viewer-initialized');
                        initPhotoViewer360($scope);
                    }
                });
            }, 1500);
        }
    });

    // Expose function globally for inline script access
    window.initPhotoViewer360 = initPhotoViewer360;

    // Use MutationObserver for editor mode to detect new widgets
    if (typeof MutationObserver !== 'undefined') {
        const observer = new MutationObserver(function(mutations) {
            mutations.forEach(function(mutation) {
                mutation.addedNodes.forEach(function(node) {
                    if (node.nodeType === 1) { // Element node
                        const $node = $(node);
                        // Check if it's a photo viewer widget or contains one
                        if ($node.hasClass('elementor-widget-unlockafe-photo-viewer-360') || 
                            $node.find('.elementor-widget-unlockafe-photo-viewer-360').length > 0 ||
                            $node.find('.unlockafe-360-viewer').length > 0) {
                            const $widget = $node.hasClass('elementor-widget-unlockafe-photo-viewer-360') 
                                ? $node 
                                : $node.find('.elementor-widget-unlockafe-photo-viewer-360').first();
                            
                            if ($widget.length > 0) {
                                setTimeout(function() {
                                    initPhotoViewer360($widget);
                                }, 200);
                            }
                        }
                    }
                });
            });
        });

        // Start observing when DOM is ready
        $(document).ready(function() {
            if (document.body) {
                observer.observe(document.body, {
                    childList: true,
                    subtree: true
                });
            }
        });
    }

    // Re-initialize on window resize
    $(window).on('resize.viewer360', function() {
        $('.unlockafe-360-viewer').each(function() {
            const $viewer = $(this);
            if ($viewer.data('viewer-initialized')) {
                const canvas = $viewer.find('.viewer-canvas')[0];
                if (canvas) {
                    const container = $viewer[0];
                    const rect = container.getBoundingClientRect();
                    canvas.width = rect.width;
                    canvas.height = rect.height;
                }
            }
        });
    });

})(jQuery);

