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

    /**
     * Initialize Table of Contents Widget
     */
    function initTableOfContents($scope) {
        const $toc = $scope.find('.unlockafe-toc');
        
        if ($toc.length === 0) {
            return;
        }

        // Check if manual items are being used
        const useManualItems = $toc.data('manual-items') === 'yes' || $toc.hasClass('toc-manual');
        
        // If manual items are used, skip auto-generation
        if (useManualItems) {
            // Just handle scroll spy and smooth scroll for manual items
            const smoothScroll = $toc.data('smooth-scroll') === 'yes' || $toc.data('smooth-scroll') === true;
            const scrollSpy = $toc.data('scroll-spy') === 'yes' || $toc.data('scroll-spy') === true;
            const scrollOffset = parseInt($toc.data('scroll-offset')) || 100;
            
            if (smoothScroll) {
                $('html').addClass('smooth-scroll-enabled');
            }
            
            // Handle scroll spy for manual items
            if (scrollSpy) {
                setupScrollSpyForManual($toc, scrollOffset);
            }
            
            // Handle smooth scroll for manual links
            if (smoothScroll) {
                $toc.find('.toc-item a').on('click', function(e) {
                    const href = $(this).attr('href');
                    if (href && href.startsWith('#')) {
                        e.preventDefault();
                        const target = $(href);
                        if (target.length) {
                            $('html, body').scrollTop(target.offset().top - scrollOffset);
                        }
                    }
                });
            }
            
            return;
        }

        const headingLevels = $toc.data('heading-levels') ? $toc.data('heading-levels').split(',') : ['h2', 'h3', 'h4'];
        const scope = $toc.data('scope') || 'page';
        const customSelector = $toc.data('custom-selector') || '';
        const smoothScroll = $toc.data('smooth-scroll') === 'yes' || $toc.data('smooth-scroll') === true;
        const scrollSpy = $toc.data('scroll-spy') === 'yes' || $toc.data('scroll-spy') === true;
        const scrollOffset = parseInt($toc.data('scroll-offset')) || 100;
        const $tocList = $toc.find('.toc-list');
        const $tocContent = $toc.find('.toc-content');

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

        /**
         * Generate unique ID for heading if it doesn't have one
         */
        function generateHeadingId($heading) {
            let id = $heading.attr('id');
            
            if (!id) {
                const text = $heading.text().trim();
                id = text.toLowerCase()
                    .replace(/[^\w\s-]/g, '') // Remove special characters
                    .replace(/\s+/g, '-') // Replace spaces with hyphens
                    .replace(/-+/g, '-') // Replace multiple hyphens with single
                    .replace(/^-|-$/g, ''); // Remove leading/trailing hyphens
                
                // Make it unique
                let counter = 1;
                let uniqueId = id;
                while ($('#' + uniqueId).length > 0) {
                    uniqueId = id + '-' + counter;
                    counter++;
                }
                
                id = uniqueId;
                $heading.attr('id', id);
            }
            
            return id;
        }

        /**
         * Build table of contents from headings
         */
        function buildTOC() {
            let $container;
            
            // Determine container to scan
            if (scope === 'custom' && customSelector) {
                $container = $(customSelector);
            } else if (scope === 'post') {
                $container = $('.elementor-post__content, .entry-content, .post-content, article');
            } else {
                $container = $('body');
            }

            if ($container.length === 0) {
                $tocList.html('<li class="toc-error">' + 'No content found to scan.' + '</li>');
                return;
            }

            // Find all headings
            const selector = headingLevels.join(',');
            const $headings = $container.find(selector).filter(function() {
                // Exclude headings inside the TOC itself
                return !$(this).closest('.unlockafe-toc').length;
            });

            if ($headings.length === 0) {
                $tocList.html('<li class="toc-empty">' + 'No headings found in the selected content.' + '</li>');
                return;
            }

            // Build TOC structure
            let tocHTML = '';
            let previousLevel = 0;

            $headings.each(function(index) {
                const $heading = $(this);
                const tagName = $heading.prop('tagName').toLowerCase();
                const level = parseInt(tagName.replace('h', ''));
                const id = generateHeadingId($heading);
                const text = $heading.text().trim();
                const levelClass = 'toc-level-' + level;

                // Determine if we need to close previous items
                if (previousLevel > 0 && level > previousLevel) {
                    // Opening a nested level
                    tocHTML += '<ul class="toc-sublist">';
                } else if (previousLevel > 0 && level < previousLevel) {
                    // Closing nested levels
                    const levelsToClose = previousLevel - level;
                    for (let i = 0; i < levelsToClose; i++) {
                        tocHTML += '</ul></li>';
                    }
                } else if (previousLevel > 0 && level === previousLevel) {
                    // Same level, close previous item
                    tocHTML += '</li>';
                }

                // Add list item
                tocHTML += '<li class="toc-item ' + levelClass + '">';
                tocHTML += '<a href="#' + id + '" data-heading-id="' + id + '">';
                tocHTML += '<span class="toc-text">' + text + '</span>';
                tocHTML += '</a>';

                previousLevel = level;
            });

            // Close remaining items
            for (let i = 0; i < previousLevel; i++) {
                tocHTML += '</li>';
            }

            $tocList.html(tocHTML);

            // Initialize click handlers
            initClickHandlers();
            
            // Initialize scroll spy if enabled
            if (scrollSpy) {
                initScrollSpy();
            }
        }

        /**
         * Initialize click handlers for TOC links
         */
        function initClickHandlers() {
            $tocList.find('a').on('click', function(e) {
                e.preventDefault();
                
                const $link = $(this);
                const headingId = $link.data('heading-id') || $link.attr('href').substring(1);
                const $target = $('#' + headingId);
                
                if ($target.length) {
                    const targetPosition = $target.offset().top - scrollOffset;
                    
                    // Remove active class from all items
                    $tocList.find('.toc-item').removeClass('active');
                    
                    // Add active class to clicked item
                    $link.closest('.toc-item').addClass('active');
                    
                    // Scroll to heading (no animation)
                    $('html, body').scrollTop(targetPosition);
                    if (history.pushState) {
                        history.pushState(null, null, '#' + headingId);
                    }
                }
            });
        }

        /**
         * Initialize scroll spy
         */
        function initScrollSpy() {
            let scrollTimeout;
            
            $(window).on('scroll.tocSpy', function() {
                clearTimeout(scrollTimeout);
                scrollTimeout = setTimeout(function() {
                    updateActiveItem();
                }, 10);
            });

            // Initial update
            updateActiveItem();
        }

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

            // Find the current heading based on scroll position
            $tocList.find('a').each(function() {
                const headingId = $(this).data('heading-id') || $(this).attr('href').substring(1);
                const $heading = $('#' + headingId);
                
                if ($heading.length) {
                    const headingTop = $heading.offset().top;
                    const headingBottom = headingTop + $heading.outerHeight();
                    
                    if (scrollPos >= headingTop && scrollPos < headingBottom) {
                        currentHeading = headingId;
                        $currentHeading = $heading;
                        return false; // Break loop
                    }
                }
            });

            // If no heading found, find the last one that's above viewport
            if (!currentHeading) {
                let lastHeading = '';
                $tocList.find('a').each(function() {
                    const headingId = $(this).data('heading-id') || $(this).attr('href').substring(1);
                    const $heading = $('#' + headingId);
                    
                    if ($heading.length && $heading.offset().top <= scrollPos) {
                        lastHeading = headingId;
                    }
                });
                
                if (lastHeading) {
                    currentHeading = lastHeading;
                }
            }

            // Update active class
            $tocList.find('.toc-item').removeClass('active');
            if (currentHeading) {
                $tocList.find('a[data-heading-id="' + currentHeading + '"]').closest('.toc-item').addClass('active');
            } else {
                // Activate first item if at top
                $tocList.find('.toc-item').first().addClass('active');
            }
        }

        /**
         * Handle collapsible toggle
         */
        $toc.find('.toc-toggle').on('click', function() {
            $toc.toggleClass('collapsed');
        });

        /**
         * Handle hash in URL on page load
         */
        if (window.location.hash) {
            const hash = window.location.hash.substring(1);
            const $targetHeading = $('#' + hash);
            
            if ($targetHeading.length) {
                const targetPosition = $targetHeading.offset().top - scrollOffset;
                $('html, body').scrollTop(targetPosition);
                $tocList.find('a[data-heading-id="' + hash + '"]').closest('.toc-item').addClass('active');
            }
        }

        /**
         * Build TOC on page load
         */
        setTimeout(function() {
            buildTOC();
        }, 500);

        /**
         * Rebuild TOC on content change (for dynamic content)
         */
        if (typeof MutationObserver !== 'undefined') {
            const observer = new MutationObserver(function(mutations) {
                let shouldRebuild = false;
                
                mutations.forEach(function(mutation) {
                    if (mutation.addedNodes.length > 0 || mutation.removedNodes.length > 0) {
                        shouldRebuild = true;
                    }
                });
                
                if (shouldRebuild) {
                    setTimeout(function() {
                        buildTOC();
                    }, 300);
                }
            });

            // Observe body for changes
            observer.observe(document.body, {
                childList: true,
                subtree: true
            });
        }
    }

    /**
     * Setup scroll spy for manual TOC items
     */
    function setupScrollSpyForManual($toc, scrollOffset) {
        const $tocList = $toc.find('.toc-list');
        let scrollTimeout;
        
        function updateActiveItem() {
            const scrollPos = $(window).scrollTop() + scrollOffset + 50;
            let currentId = '';
            
            $tocList.find('a').each(function() {
                const href = $(this).attr('href');
                if (href && href.startsWith('#')) {
                    const targetId = href.substring(1);
                    const $target = $('#' + targetId);
                    
                    if ($target.length) {
                        const targetTop = $target.offset().top;
                        const targetBottom = targetTop + $target.outerHeight();
                        
                        if (scrollPos >= targetTop && scrollPos < targetBottom) {
                            currentId = targetId;
                            return false;
                        }
                    }
                }
            });
            
            // Update active class
            $tocList.find('.toc-item').removeClass('active');
            if (currentId) {
                $tocList.find('a[href="#' + currentId + '"]').closest('.toc-item').addClass('active');
            }
        }
        
        $(window).on('scroll.tocSpyManual', function() {
            clearTimeout(scrollTimeout);
            scrollTimeout = setTimeout(updateActiveItem, 10);
        });
        
        updateActiveItem();
    }

    // Initialize on Elementor frontend
    $(window).on('elementor/frontend/init', function() {
        elementorFrontend.hooks.addAction('frontend/element_ready/unlockafe-table-of-contents.default', function($scope) {
            initTableOfContents($scope);
        });
    });

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

    // Re-initialize on window resize
    $(window).on('resize.toc', function() {
        $('.unlockafe-toc').each(function() {
            const $toc = $(this);
            const $scope = $toc.closest('.elementor-widget-unlockafe-table-of-contents');
            if ($scope.length) {
                // Recalculate active item
                const scrollSpy = $toc.data('scroll-spy') === 'yes' || $toc.data('scroll-spy') === true;
                if (scrollSpy) {
                    setTimeout(function() {
                        const scrollPos = $(window).scrollTop() + parseInt($toc.data('scroll-offset')) + 50;
                        $toc.find('a').each(function() {
                            const headingId = $(this).data('heading-id') || $(this).attr('href').substring(1);
                            const $heading = $('#' + headingId);
                            
                            if ($heading.length) {
                                const headingTop = $heading.offset().top;
                                if (scrollPos >= headingTop) {
                                    $toc.find('.toc-item').removeClass('active');
                                    $(this).closest('.toc-item').addClass('active');
                                }
                            }
                        });
                    }, 100);
                }
            }
        });
    });

})(jQuery);

