(function ($) {
    'use strict';

    var isEditMode = false;

    var getElementSettings = function( $element ) {
		var elementSettings = {},
			modelCID 		= $element.data( 'model-cid' );

		if ( isEditMode && modelCID ) {
			var settings     = elementorFrontend.config.elements.data[ modelCID ],
				settingsKeys = elementorFrontend.config.elements.keys[ settings.attributes.widgetType || settings.attributes.elType ];

			jQuery.each( settings.getActiveControls(), function( controlKey ) {
				if ( -1 !== settingsKeys.indexOf( controlKey ) ) {
					elementSettings[ controlKey ] = settings.attributes[ controlKey ];
				}
			} );
		} else {
			elementSettings = $element.data('settings') || {};
		}

		return elementSettings;
	};

	var ElementsTooltipHandler = function( $scope, $ ) {
		var elementSettings = getElementSettings( $scope ),
			isTooltip       = elementSettings.pp_elements_tooltip_enable;

		if ( 'yes' !== isTooltip ) {
			return;
		}

		var tooltipElem     = $scope,
			id              = $scope.data('id'),
			ppclass         = 'pp-tooltip' + ' pp-tooltip-' + id,
			ttPosition      = elementSettings.pp_elements_tooltip_position,
			ttArrow         = elementSettings.pp_elements_tooltip_arrow,
			ttTarget        = elementSettings.pp_elements_tooltip_target,
			ttSelector      = elementSettings.pp_elements_tooltip_selector,
			ttTrigger       = elementSettings.pp_elements_tooltip_trigger,
			ttDistance      = ( '' !== elementSettings.pp_elements_tooltip_distance && undefined !== elementSettings.pp_elements_tooltip_distance ) ? elementSettings.pp_elements_tooltip_distance.size : '',
			animation       = elementSettings.pp_elements_tooltip_animation,
			tooltipWidth    = ( '' !== elementSettings.pp_elements_tooltip_width && undefined !== elementSettings.pp_elements_tooltip_width ) ? elementSettings.pp_elements_tooltip_width.size : '',
			tooltipZindex   = elementSettings.pp_elements_tooltip_zindex,
			isViewport      = ( 'viewport' === ttTrigger ),
			autoHide        = parseInt( elementSettings.pp_elements_tooltip_auto_hide, 10 ) || 0,
			showOnce        = ( 'yes' === elementSettings.pp_elements_tooltip_show_once ),
			viewportThreshold = ( elementSettings.pp_elements_tooltip_viewport_threshold && '' !== elementSettings.pp_elements_tooltip_viewport_threshold.size ) ? parseInt( elementSettings.pp_elements_tooltip_viewport_threshold.size, 10 ) : 10;

		if ( 'custom' === ttTarget ) {
			if ( '' !== ttSelector ) {
				var target = $scope.find( ttSelector );

				if ( ttSelector.length ) {
					tooltipElem = target;
				}
			}
		}

		if ( $scope.hasClass('tooltipstered') ) {
			$scope.pptooltipster('destroy');
		}

		if ( tooltipElem.hasClass('tooltipstered') ) {
			$(tooltipElem).pptooltipster('destroy');
		}

		// For the viewport trigger, hand tooltipster a non-hover/non-click value
		// so it leaves triggerOpen / triggerClose at their (false) defaults.
		// We then drive open/close ourselves via IntersectionObserver below.
		var tooltipsterTrigger = isViewport ? 'custom' : ttTrigger;

		$(tooltipElem).pptooltipster({
			trigger:         tooltipsterTrigger,
			content:         $scope.find('#pp-tooltip-content-' + id),
			animation:       animation,
			minWidth:        0,
			maxWidth:        tooltipWidth,
			ppclass:         ppclass,
			position:        ttPosition,
			arrow:           ( 'yes' === ttArrow ),
			distance:        ttDistance,
			interactive:     true,
			positionTracker: true,
			zIndex:          tooltipZindex,
			functionInit:   function(instance, helper) {
				var content = $scope.find('#pp-tooltip-content-' + id).detach();
				instance.content(content);
			}
		});

		if ( isViewport ) {
			bindViewportTrigger( $(tooltipElem), {
				autoHide:  autoHide,
				showOnce:  showOnce,
				threshold: Math.min( Math.max( viewportThreshold, 0 ), 100 ) / 100
			});
		}
	};

	/**
	 * Open the tooltip when its target scrolls into the viewport.
	 *
	 * Falls back to a one-shot open on legacy browsers that lack
	 * IntersectionObserver — better than silently doing nothing.
	 */
	var bindViewportTrigger = function( $target, opts ) {
		var node = $target.get(0);
		if ( ! node ) {
			return;
		}

		var hasShown    = false,
			hideTimer   = null,
			scheduleHide = function() {
				if ( opts.autoHide > 0 ) {
					clearTimeout( hideTimer );
					hideTimer = setTimeout(function() {
						if ( $target.hasClass('tooltipstered') ) {
							$target.pptooltipster('close');
						}
					}, opts.autoHide * 1000);
				}
			};

		if ( typeof window.IntersectionObserver === 'undefined' ) {
			$target.pptooltipster('open');
			scheduleHide();
			return;
		}

		var observer = new IntersectionObserver(function( entries ) {
			entries.forEach(function( entry ) {
				if ( entry.isIntersecting ) {
					if ( opts.showOnce && hasShown ) {
						return;
					}
					hasShown = true;
					if ( $target.hasClass('tooltipstered') ) {
						$target.pptooltipster('open');
					}
					scheduleHide();
					if ( opts.showOnce ) {
						observer.disconnect();
					}
				} else if ( ! opts.showOnce && opts.autoHide === 0 ) {
					// No auto-hide configured: close when the target leaves the viewport
					// so the tooltip re-opens cleanly on the next entry.
					if ( $target.hasClass('tooltipstered') ) {
						$target.pptooltipster('close');
					}
				}
			});
		}, { threshold: opts.threshold });

		observer.observe( node );
	};

    $(window).on('elementor/frontend/init', function () {
        if ( elementorFrontend.isEditMode() ) {
			isEditMode = true;
		}

		elementorFrontend.hooks.addAction( 'frontend/element_ready/widget', ElementsTooltipHandler );
    });

}(jQuery));
