(function ($) {
	"use strict";
	var WidgetChartHandler = function ($scope, $) {
		var container = $scope.find( '.eca-chart' ),
			canvas    = container.find( '> canvas' ),
			options   = container.data( 'options' );

		if (container.length && options) {
			var observer = new IntersectionObserver(
				function (entries) {
					entries.forEach(
						function (entry) {
							// Check if the element is in view
							if (entry.isIntersecting) {
								// Initialize the chart
								var $this = $( canvas ),
								ctx       = $this[0].getContext( '2d' );

								// Delay initialization slightly to ensure the element is visible
								setTimeout(
									function () {
										var myChart = new Chart( ctx, options );
									},
									100
								); // Optional: slight delay (100ms)

								// Stop observing once the chart is initialized
								observer.unobserve( entry.target );
							}
						}
					);
				},
				{
					root: null, // Use the viewport as the container
					threshold: 0.1 // Trigger when 10% of the element is visible
				}
			);

			// Observe the container element
			observer.observe( container[0] );
		}
	};

	$( window ).on(
		'elementor/frontend/init',
		function () {
			elementorFrontend.hooks.addAction( 'frontend/element_ready/ecafe-chart.default', WidgetChartHandler );
		}
	);
})( jQuery );