// phpcs:ignoreFile
/**
 * PaddleKonnect Frontend Checkout JS
 * Handles overriding the default WooCommerce checkout behavior to show Paddle.js overlay.
 */
jQuery(
	function ($) {
		if (typeof paddlekonnect_params === 'undefined' || typeof Paddle === 'undefined') {
			return;
		}

		// Initialize Paddle
		if (paddlekonnect_params.sandbox === '1') {
			Paddle.Environment.set( 'sandbox' );
		}

		Paddle.Initialize(
			{
				token: paddlekonnect_params.client_token,
				eventCallback: function (data) {
					// Handle Paddle Events
					if (data.name === 'checkout.completed') {
						// Checkout completed successfully. Redirect to WC order received page.
						var customData = data.data && data.data.custom_data ? data.data.custom_data : null;

						// We use AJAX to poll the server to see if the webhook has finished processing.
						// We keep checking every 2 seconds. Once it's processing/completed, we redirect.
						function checkStatus() {
							$.post(
								paddlekonnect_params.ajax_url,
								{
									action: 'paddlekonnect_lite_check_order_status',
									order_id: customData.wc_order_id,
									nonce: paddlekonnect_params.nonce
								},
								function (response) {
									if (response.success) {
										if (customData.return_url) {
											window.location.href = customData.return_url;
										} else {
											window.location.reload();
										}
									} else {
										setTimeout( checkStatus, 2000 );
									}
								}
							).fail(
								function () {
									setTimeout( checkStatus, 2000 );
								}
							);
						}

						// Block the UI and start polling
						$( 'form.checkout' ).block(
							{
								message: null,
								overlayCSS: {
									background: '#fff',
									opacity: 0.6
								}
							}
						);
						checkStatus();
					} else if (data.name === 'checkout.closed') {
						// User closed the overlay without completing payment
						$( '.woocommerce-error' ).remove();
						$( 'form.checkout' ).prepend( '<div class="woocommerce-error" role="alert">Payment was canceled. You can try again below.</div>' );
						$( 'form.checkout' ).removeClass( 'processing' ).unblock();
					} else if (data.name === 'checkout.error') {
						console.error( 'Paddle Checkout Error:', data );
						$( '.woocommerce-error' ).remove();
						$( 'form.checkout' ).prepend( '<div class="woocommerce-error" role="alert">A payment error occurred. Please try again.</div>' );
						$( 'form.checkout' ).removeClass( 'processing' ).unblock();
					}
				}
			}
		);

		// Listen to changes in the URL hash.
		// WooCommerce sends back {"result": "success", "redirect": "#paddlekonnect-txn_..."}
		// which automatically updates the browser's URL hash without reloading.
		$( window ).on(
			'hashchange',
			function () {
				var hash = window.location.hash;

				if (hash.indexOf( '#paddlekonnect-' ) === 0) {
					// Extract the transaction ID
					var txnId = hash.replace( '#paddlekonnect-', '' );

					// Store the current URL without the hash so we can redirect cleanly later if needed
					// Also prevents the overlay from re-opening if the user refreshes the page
					window.history.replaceState( null, null, ' ' );

					// Stop the form spinner
					$( 'form.checkout' ).removeClass( 'processing' ).unblock();

					// Open the Paddle checkout overlay
					Paddle.Checkout.open(
						{
							transactionId: txnId,
							settings: {
								displayMode: 'overlay',
								theme: 'light' // Can be configured via settings later
							}
						}
					);
				}
			}
		);
	}
);
