/**
 * Start table of content widget script
 */

( function( $, elementor ) {

	'use strict';

	var widgetTableOfContent = function( $scope, $ ) {

		var $tableOfContent = $scope.find( '.bdt-table-of-content' );
				
        if ( ! $tableOfContent.length ) {
            return;
        }

        // Move fixed layout TOC to body so position:fixed works (not broken by parent transform)
        var $fixedContainer = $scope.find( '.table-of-content-layout-fixed' ).first();
        if ( $fixedContainer.length && ! $fixedContainer.data( 'ep-toc-moved' ) ) {
            $fixedContainer.data( 'ep-toc-moved', true );
            $fixedContainer.after( '<div class="bdt-toc-fixed-placeholder" style="width:320px;min-height:1px;" aria-hidden="true"></div>' );
            $fixedContainer.appendTo( 'body' );
        }

        var settings = $tableOfContent.data('settings') || {};
        $($tableOfContent).tocify(settings);

        // When Auto Collapse is on: start with all sub-items closed (scroll will open the active section's submenu)
        if ( settings.showAndHide ) {
            $tableOfContent.find( '.tocify-subheader' ).hide();
            // After a click, disable scroll-driven open until scroll settles so submenu doesn't close-then-open
            $tableOfContent.on( 'click.toc-ep', 'li', function() {
                $tableOfContent.tocify( 'option', 'showAndHideOnScroll', false );
                clearTimeout( $tableOfContent.data( 'ep-toc-scroll-lock' ) );
                $tableOfContent.data( 'ep-toc-scroll-lock', setTimeout( function() {
                    $tableOfContent.tocify( 'option', 'showAndHideOnScroll', true );
                }, 2500 ) );
            } );
        }

        // Handle incoming hash URLs only if hash navigation is enabled
        if (settings && settings.hashNavigation) {
            handleHashOnLoad($tableOfContent);
        }

	};

    function handleHashOnLoad($tableOfContent) {
        var hash = window.location.hash;
        if (hash && hash.length > 1) {
            setTimeout(function() {
                var target = $('[name="' + hash.substring(1) + '"]');
                if (target.length) {
                    // Get scroll offset from TOC settings
                    var settings = $tableOfContent.data('settings');
                    var scrollOffset = settings ? (settings.scrollTo || 0) : 0;
                    
                    $('html, body').animate({
                        scrollTop: target.offset().top - scrollOffset
                    }, 800);
                }
            }, 1500);
        }
    }

	jQuery(window).on('elementor/frontend/init', function() {
		elementorFrontend.hooks.addAction( 'frontend/element_ready/bdt-table-of-content.default', widgetTableOfContent );
	});

}( jQuery, window.elementorFrontend ) );

/**
 * End table of content widget script
 */


