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

    /**
     * Initialize One Page Navigation Widget
     */
    function initOnePageNavigation($scope) {
        const $nav = $scope.find('.unlockafe-one-page-nav');
        
        if ($nav.length === 0) {
            return;
        }
        
        // Check if already initialized to prevent duplicate handlers
        if ($nav.data('onePageNavInitialized')) {
            return;
        }
        
        // Mark as initialized
        $nav.data('onePageNavInitialized', true);

        const scrollOffset = parseInt($nav.data('scroll-offset')) || 80;
        const smoothScroll = $nav.data('smooth-scroll') === 'yes' || $nav.data('smooth-scroll') === true;
        const $navLinks = $nav.find('.nav-link');
        
        // Debug log
        console.log('One Page Navigation: Initializing', $navLinks.length, 'links');

        // Enable smooth scroll on html if needed
        if (smoothScroll) {
            $('html').addClass('smooth-scroll-enabled');
        }

        /**
         * Smooth scroll to section
         */
        function scrollToSection(anchor, offset) {
            const $target = $(anchor);
            
            if ($target.length) {
                const targetPosition = $target.offset().top - offset;
                
                if (smoothScroll) {
                    $('html, body').animate({
                        scrollTop: targetPosition
                    }, 800, 'swing');
                } else {
                    $('html, body').scrollTop(targetPosition);
                }
            }
        }

        /**
         * Update active navigation item based on scroll position
         */
        function updateActiveNav() {
            const scrollPos = $(window).scrollTop() + scrollOffset + 50;
            let currentSection = '';

            // Find the current section based on scroll position
            $navLinks.each(function() {
                const $link = $(this);
                const anchor = $link.data('anchor');
                
                if (anchor) {
                    const $section = $('#' + anchor);
                    
                    if ($section.length) {
                        const sectionTop = $section.offset().top;
                        const sectionBottom = sectionTop + $section.outerHeight();
                        
                        if (scrollPos >= sectionTop && scrollPos < sectionBottom) {
                            currentSection = anchor;
                            return false; // Break loop
                        }
                    }
                }
            });

            // Update active class
            $navLinks.removeClass('active');
            if (currentSection) {
                $navLinks.filter('[data-anchor="' + currentSection + '"]').addClass('active');
            } else {
                // If no section found, activate first item
                $navLinks.first().addClass('active');
            }
        }

        /**
         * Handle navigation link clicks - Use event delegation for better reliability
         */
        $nav.off('click.onePageNav', '.nav-link').on('click.onePageNav', '.nav-link', function(e) {
            e.preventDefault();
            e.stopPropagation();
            
            const $link = $(this);
            const anchor = $link.data('anchor') || $link.attr('data-anchor');
            
            console.log('One Page Navigation: Link clicked', anchor);
            
            if (anchor) {
                // Remove active class from all links
                $nav.find('.nav-link').removeClass('active');
                
                // Add active class to clicked link
                $link.addClass('active');
                
                // Scroll to section
                scrollToSection('#' + anchor, scrollOffset);
            } else {
                console.warn('One Page Navigation: No anchor found for link');
            }
        });

        /**
         * Update active nav on scroll
         */
        let scrollTimeout;
        $(window).on('scroll.onePageNav', function() {
            clearTimeout(scrollTimeout);
            scrollTimeout = setTimeout(function() {
                updateActiveNav();
            }, 10);
        });

        /**
         * Update active nav on page load
         */
        updateActiveNav();

        /**
         * Handle hash in URL on page load
         */
        if (window.location.hash) {
            const hash = window.location.hash.substring(1);
            const $targetLink = $navLinks.filter('[data-anchor="' + hash + '"]');
            
            if ($targetLink.length) {
                setTimeout(function() {
                    scrollToSection('#' + hash, scrollOffset);
                    $navLinks.removeClass('active');
                    $targetLink.addClass('active');
                }, 100);
            }
        }

        /**
         * Handle browser back/forward buttons
         */
        $(window).on('hashchange', function() {
            const hash = window.location.hash.substring(1);
            const $targetLink = $navLinks.filter('[data-anchor="' + hash + '"]');
            
            if ($targetLink.length) {
                scrollToSection('#' + hash, scrollOffset);
                $navLinks.removeClass('active');
                $targetLink.addClass('active');
            }
        });

        /**
         * Update URL hash when scrolling (optional)
         */
        let lastHash = '';
        $(window).on('scroll.hashUpdate', function() {
            const scrollPos = $(window).scrollTop() + scrollOffset + 50;
            
            $navLinks.each(function() {
                const $link = $(this);
                const anchor = $link.data('anchor');
                
                if (anchor) {
                    const $section = $('#' + anchor);
                    
                    if ($section.length) {
                        const sectionTop = $section.offset().top;
                        const sectionBottom = sectionTop + $section.outerHeight();
                        
                        if (scrollPos >= sectionTop && scrollPos < sectionBottom) {
                            if (lastHash !== anchor) {
                                lastHash = anchor;
                                if (history.pushState) {
                                    history.pushState(null, null, '#' + anchor);
                                }
                            }
                            return false;
                        }
                    }
                }
            });
        });
    }

    // Initialize on Elementor frontend
    $(window).on('elementor/frontend/init', function() {
        elementorFrontend.hooks.addAction('frontend/element_ready/unlockafe-one-page-navigation.default', function($scope) {
            initOnePageNavigation($scope);
        });
        
        // Handle editor preview mode
        if (elementorFrontend.isEditMode) {
            // Initialize navigation in editor preview
            elementorFrontend.hooks.addAction('frontend/element_ready/global', function($scope) {
                if ($scope.find('.unlockafe-one-page-nav').length) {
                    setTimeout(function() {
                        initOnePageNavigation($scope);
                    }, 100);
                }
            });
            
            // Also initialize on editor preview refresh
            $(window).on('elementor:preview:loaded', function() {
                setTimeout(function() {
                    $('.elementor-widget-unlockafe-one-page-navigation').each(function() {
                        var $scope = $(this);
                        initOnePageNavigation($scope);
                    });
                }, 200);
            });
        }
    });

    // Also initialize on document ready (for non-Elementor pages and after save)
    $(document).ready(function() {
        $('.elementor-widget-unlockafe-one-page-navigation').each(function() {
            var $scope = $(this);
            initOnePageNavigation($scope);
        });
        
        // Also initialize in editor mode after a delay
        if (typeof elementorFrontend !== 'undefined' && elementorFrontend.isEditMode) {
            setTimeout(function() {
                $('.elementor-widget-unlockafe-one-page-navigation').each(function() {
                    var $scope = $(this);
                    initOnePageNavigation($scope);
                });
            }, 500);
        }
    });
    
    // Re-initialize after page load (for saved pages)
    $(window).on('load', function() {
        setTimeout(function() {
            $('.elementor-widget-unlockafe-one-page-navigation').each(function() {
                var $scope = $(this);
                initOnePageNavigation($scope);
            });
        }, 300);
    });

    // Re-initialize on window resize
    $(window).on('resize.onePageNav', function() {
        $('.unlockafe-one-page-nav').each(function() {
            const $nav = $(this);
            const $scope = $nav.closest('.elementor-widget-unlockafe-one-page-navigation');
            if ($scope.length) {
                initOnePageNavigation($scope);
            }
        });
    });

})(jQuery);





