(function ($) {
	"use strict";

	var WidgetPageScrollToId = function ($scope) {
		var wrapper = $scope.find( '.ecafe-page-scroll-to-id-wrapper' );
		if ( ! wrapper.length) {
			return;
		}
		var settings = wrapper.data( 'settings' );
		var $anchors = wrapper.find( '.ecafe-psi-anchor' );

		// Init
		$anchors.mPageScroll2id(
			{
				highlightSelector: $anchors,
				highlightClass: "highlighted-menu-item",
				forceSingleHighlight: true,
				offset: +settings.sectionoffset,
				scrollSpeed: +settings.pagescrollspeed,
				pageEndSmoothScroll: true,
				keepHighlightUntilNext: false,
				highlightByNextTarget: false,
				appendHash: JSON.parse( settings.hashtag )
			}
		);

		// Click scroll
		$anchors.on(
			'click',
			function (e) {
				e.preventDefault();
				var nextId = $( this ).closest( "section" ).next().attr( "id" );
				if (nextId) {
					$.mPageScroll2id( "scrollTo", nextId );
				}
			}
		);

		// Show after scroll
		$( window ).on(
			'scroll',
			function () {
				var scrollTop = $( this ).scrollTop();

				// only apply if wrapper has psiafterscroll
				if (wrapper.hasClass( "psiafterscroll" )) {
					var $scrolls = $( "." + settings.uid );
					$scrolls.toggleClass( "psivisible", scrollTop > settings.showafterscroll );
				}
			}
		);

	};

	$( window ).on(
		'elementor/frontend/init',
		function () {
			elementorFrontend.hooks.addAction(
				'frontend/element_ready/ecafe-page-scroll-to-id.default',
				WidgetPageScrollToId
			);
		}
	);

})( jQuery );
