// Waits for the element to exist as in the Blocks checkout, sometimes the field is not immediately available.
export const getTargetElement = ( selector ) => {
	if ( ! selector ) {
		return null;
	}
	return new Promise( ( resolve ) => {
		if ( document.querySelector( selector ) ) {
			return resolve( document.querySelector( selector ) );
		}

		const checkoutBlock = document.querySelector(
			'[data-block-name="woocommerce/checkout"]'
		);

		if ( ! checkoutBlock ) {
			return resolve( null );
		}

		const observer = new MutationObserver( ( mutationList, obs ) => {
			if ( document.querySelector( selector ) ) {
				resolve( document.querySelector( selector ) );
				obs.disconnect();
			}
		} );

		observer.observe( checkoutBlock, {
			childList: true,
			subtree: true,
		} );
	} );
};

export const validateEmail = ( value ) => {
	/* Borrowed from WooCommerce checkout.js with a slight tweak to add `{2,}` to the end and make the TLD at least 2 characters. */
	/* eslint-disable */
	const pattern = new RegExp(
		/^([a-z\d!#$%&'*+\-\/=?^_`{|}~\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]+(\.[a-z\d!#$%&'*+\-\/=?^_`{|}~\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]+)*|"((([ \t]*\r\n)?[ \t]+)?([\x01-\x08\x0b\x0c\x0e-\x1f\x7f\x21\x23-\x5b\x5d-\x7e\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]|\\[\x01-\x09\x0b\x0c\x0d-\x7f\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))*(([ \t]*\r\n)?[ \t]+)?")@(([a-z\d\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]|[a-z\d\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF][a-z\d\-._~\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]*[a-z\d\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])\.)+([a-z\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]|[a-z\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF][a-z\d\-._~\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]*[0-9a-z\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]){2,}\.?$/i
	);
	/* eslint-enable */
	return pattern.test( value );
};

export const appendRedirectionParams = ( woopayUrl ) => {
	const isPayForOrder = window.wcpayConfig.pay_for_order;
	const orderId = window.wcpayConfig.order_id;
	const key = window.wcpayConfig.key;
	const billingEmail = window.wcpayConfig.billing_email;

	if ( ! isPayForOrder || ! orderId || ! key ) {
		return woopayUrl;
	}

	const url = new URL( woopayUrl );
	url.searchParams.append( 'pay_for_order', isPayForOrder );
	url.searchParams.append( 'order_id', orderId );
	url.searchParams.append( 'key', key );
	url.searchParams.append( 'billing_email', billingEmail );

	return url.href;
};

/**
 * Checks if a session cookie is set in order to determine if the user has opted to skip WooPay.
 *
 * @return {boolean} True if the user has opted to skip WooPay.
 */
export const shouldSkipWooPay = () => {
	const cookies = document.cookie.split( ';' );
	const skipWooPayCookie = cookies.find( ( cookie ) =>
		cookie.includes( 'skip_woopay' )
	);

	if ( ! skipWooPayCookie ) {
		return false;
	}

	const skipWooPayCookieSplit = skipWooPayCookie?.split( '=' );

	return (
		skipWooPayCookieSplit[ 0 ].trim() === 'skip_woopay' &&
		skipWooPayCookieSplit[ 1 ].trim() === '1'
	);
};

/**
 * Deletes the skip_woopay cookie.
 * This should be called when the user explicitly opts to pay with WooPay.
 */
export const deleteSkipWooPayCookie = () => {
	if ( ! shouldSkipWooPay() ) {
		return;
	}

	document.cookie =
		'skip_woopay=; path=/; expires=Thu, 01 Jan 1970 00:00:00 UTC;';
};
