(function ($) {
	$( window ).on( 'elementor/frontend/init', () => {
		/*
		 * Bound once for the page rather than inside bindEvents(). The handler
		 * is delegated on body and resolves its own widget from the button, so
		 * there was never anything per instance about it; binding it per
		 * instance meant every widget re-registered it and the leading off()
		 * left only the last one alive. The off() is kept so a double enqueue
		 * still cannot stack two redirects.
		 */
		$( 'body' )
			.off( 'added_to_cart.pp_cart' )
			.on( 'added_to_cart.pp_cart', function ( e, fragments, cart_hash, this_button ) {
				const $btn = $( this_button );

				// closest() rather than a fixed parent chain: the
				// elementor-widget-container wrapper is dropped when the
				// Optimized Markup experiment is active, which changes
				// how deep the widget root sits.
				if ( ! $btn.closest( '.elementor-widget-pp-woo-add-to-cart' ).length ) {
					return;
				}

				if ( pp_woo_products_script.is_cart || ! $btn.hasClass( 'added' ) ) {
					return;
				}

				if ( $btn.hasClass( 'pp-redirect' ) ) {
					setTimeout( function () {
						window.location = pp_woo_products_script.cart_url;
					}, 500 );
				}
			} );

		class WidgetPPWooAddToCart extends elementorModules.frontend.handlers.Base {
			getDefaultSettings() {
				return {};
			}

			getDefaultElements() {
				return {};
			}

			bindEvents() {
				// Scoped to this widget only. The previous document wide
				// fallback would have collected every instance's input and
				// copied the first one's value onto all of them.
				const $qty = this.$element.find( '.pp-woo-add-to-cart input.pp-add-to-cart-qty-ajax' );

				$qty.on( 'keyup mouseup', function () {
					$qty.siblings( '.ajax_add_to_cart' ).attr( 'data-quantity', $qty.val() );
				} );
			}
		}

		elementorFrontend.elementsHandler.attachHandler( 'pp-woo-add-to-cart', WidgetPPWooAddToCart );
	} );
})(jQuery);
