/**
 * Sync frontend scripts.
 *
 * @package flo-sync
 */

jQuery( document ).ready(
	function ( $ ) {

		const block_default_args = {
			message: null,
			overlayCSS: {
				background: '#fff',
				opacity: 0.6
			}
		};

		/**
		 * MAS Store select enhancement.
		 */
		const $body	      = $( 'body' );
		const is_checkout = $body.hasClass( 'woocommerce-checkout' );
		const is_cart     = $body.hasClass( 'woocommerce-cart' );

		function nmf_maybe_enhance_store_select() {
			const $store_select = $( '.nmf-backoffice-account-select' );
			if ( $store_select.length ) {
				$store_select.css( 'width', '100%' ).selectWoo().addClass( 'enhanced' );
			}
		}
		nmf_maybe_enhance_store_select();

		$( document ).on(
			'updated_cart_totals',
			function () {
				nmf_maybe_enhance_store_select();
			}
		);

		$( document ).on(
			'updated_checkout',
			function () {
				nmf_maybe_enhance_store_select();
			}
		);

		$( document ).on(
			'change',
			'.nmf-backoffice-account-select',
			function () {
				if ( is_cart ) {
					$( 'div.cart_totals' ).block( block_default_args );
				}
				if ( is_checkout ) {
					$( '.woocommerce-checkout-payment, .woocommerce-checkout-review-order-table' ).block( block_default_args );
				}

				const ajax = nmf_sync_frontend_script_vars.shipping_store_update_ajax;

				const data                 = {
					action: ajax.action,
					shipping_store: $( this ).val(),
					shipping_method: $( this ).data( 'shipping-method' ),
				};
				data[ajax.nonce_query_arg] = ajax.nonce

				$.ajax(
					{
						type: 'post',
						url: nmf_sync_frontend_script_vars.ajax_url,
						data: data,
						dataType: 'html',
						complete: function () {
							if ( is_cart ) {
								$( 'div.cart_totals' ).unblock();
							}
							if ( is_checkout ) {
								$( document.body ).trigger( 'update_checkout' );
							}
							$( document.body ).trigger( 'updated_shipping_method_store' );
						}
					}
				);
			}
		);
	}
);
