jQuery( function ( $ ) {
	$( '.dsm_image_hotspots_wrapper.dsm-hotspot-frontend' ).each(
		function ( index, item ) {
			const $item = $( item );
			const $wrap = $item.closest( '.dsm_image_hotspots_wrap' );

			const popup = $item.closest( '.dsm-popup' ).length ? 1000002 : 9999;

			// jQuery maps data-dsm-tooltip-animation → .data('dsmTooltipAnimation'); support both.
			let animation =
				$wrap.data( 'dsmTooltipAnimation' ) ||
				$wrap.data( 'dsm-tooltip-animation' );
			if ( ! animation && $wrap.attr( 'data-dsm-tooltip-animation' ) ) {
				animation = $wrap.attr( 'data-dsm-tooltip-animation' );
			}
			if ( ! animation ) {
				animation = 'fade';
			}

			const tooltip_show = $item.data( 'dsmTooltipShow' ) || $item.data( 'dsm-tooltip-show' );

			let tooltip_close =
				$wrap.data( 'dsmTooltipClose' ) || $wrap.data( 'dsm-tooltip-close' );
			if ( typeof tooltip_close === 'undefined' && $wrap.attr( 'data-dsm-tooltip-close' ) ) {
				tooltip_close = $wrap.attr( 'data-dsm-tooltip-close' );
			}
			if ( typeof tooltip_close === 'undefined' ) {
				tooltip_close = 'off';
			}

			const orderClass = $item.data( 'orderClass' ) || $item.data( 'order-class' );

			const trigger =
				$wrap.data( 'tippyTrigger' ) ||
				$wrap.data( 'tippy-trigger' ) ||
				'hover';

			// data-tippy-delay → .data('tippyDelay'); fallback parse JSON string.
			let delay = $wrap.data( 'tippyDelay' ) || $wrap.data( 'tippy-delay' );
			if ( ! delay ) {
				const rawDelay = $wrap.attr( 'data-tippy-delay' );
				if ( rawDelay ) {
					try {
						delay = JSON.parse( rawDelay );
					} catch ( e ) {
						delay = [ 50, 50 ];
					}
				} else {
					delay = [ 50, 50 ];
				}
			}

			const instance = tippy( this, {
				appendTo: document.body,
				sticky: 'on' === tooltip_show ? true : false,
				hideOnClick: 'off' === tooltip_close ? 'toggle' : true,
				duration: 300,
				maxWidth: 'none',
				delay: delay,
				trigger: 'hover' === trigger ? 'mouseenter focus' : 'click',
				interactive: true,
				animation: animation,
				distance: 15,
				content: $item.next().html(),
				allowHTML: true,
				zIndex: popup,
				onCreate( instance ) {
					instance.popper.classList.add( 'tippy-popper' );
					instance.popper.classList.add(
						instance.reference.parentElement.closest(
							'.dsm_image_hotspots_wrap'
						).dataset.dsmHotspot
					);

					instance.popper.firstChild.classList.add(
						'dsm_image_hotspot_tooltip_wrapper',
						orderClass
					);
				},
				onShow( instance ) {},
			} );

			instance.hide();
		}
	);
} );
