(function ($) {

	let apaczka_geowidget_supplier;
	let geowidget_only_cod                  = false;
	let apaczka_only_cod                    = false;
	let alsendo_connect_initial_map_address = '';
	let alsendo_connect_initial_map_country = '';
	let alsendo_connect_blocks_zip_val      = '';

	function alsendo_connect_delay_on_typein(callback, ms) {
		var timer = 0;
		return function () {
			var context = this, args = arguments;
			clearTimeout( timer );
			timer = setTimeout(
				function () {
					callback.apply( context, args );
				},
				ms || 0
			);
		};
	}

	function apaczkaCreateOperatorWcBlock(operatorId, operatorName) {
		operatorName = operatorName.toUpperCase();
		if ( 'ZASILKOVNA' === operatorName ) {
			operatorName = 'PACKETA';
		}
		return {
			operator: operatorName,
			price: null
		};
	}

	function alsendo_connect_wait_elem(selector) {
		return new Promise(
			function (resolve) {
				if (document.querySelector( selector )) {
					return resolve( document.querySelector( selector ) );
				}
				let observer = new MutationObserver(
					function (mutations) {
						if (document.querySelector( selector )) {
							resolve( document.querySelector( selector ) );
							observer.disconnect();
						}
					}
				);
				observer.observe(
					document.body,
					{
						childList: true,
						subtree: true
					}
				);
			}
		);
	}

	function apaczka_change_react_input(input, value) {
		if (typeof input != 'undefined' && input !== null) {
			var nativeInputValueSetter = Object.getOwnPropertyDescriptor(
				window.HTMLInputElement.prototype,
				"value"
			).set;
			nativeInputValueSetter.call( input, value );
			var inputEvent = new Event( "input", {bubbles: true} );
			input.dispatchEvent( inputEvent );
		}
	}

	function apaczka_wc_block_point_callback(record) {

		console.log( 'Alsendo_connect: selected_point' );
		console.log( record );

		let visible_point_id   = '';
		let visible_point_desc = '';
		let visible_city       = '';
		let visible_street     = '';
		let visible_house      = '';
		let apaczka_point_data = {};

		if ('code' in record) {
			if ('brand' in record) {
				apaczka_point_data.apm_access_point_id = record.code;
				visible_point_id                       = '<div id="selected-parcel-machine-id">' + record.brand + ': ' + record.code + '</div>\n';
			} else {
				apaczka_point_data.apm_access_point_id = record.code;
				visible_point_id                       = '<div id="selected-parcel-machine-id">' + record.code + '</div>\n';
			}
		}

		if ('operator' in record) {
			apaczka_point_data.apm_supplier = record.operator;
		}

		if ('description' in record && typeof record.description != 'undefined' && record.description !== null ) {
			apaczka_point_data.apm_name = record.description;
			visible_point_desc         += record.description;
		}

		if ('code' in record) {
			apaczka_point_data.apm_foreign_access_point_id = record.code;
		}

		if ('street' in record) {
			apaczka_point_data.apm_street = record.street;
			visible_point_desc           += '<br>' + record.street;
		}

		if ('city' in record) {
			apaczka_point_data.apm_city = record.city;
			visible_point_desc         += '<br>' + record.city;
		}

		if ('postalCode' in record) {
			apaczka_point_data.apm_postal_code = record.postalCode;
			visible_point_desc                += '<br>' + record.postalCode;
		}

		if ('country_code' in record) {
			apaczka_point_data.apm_country_code = record.country_code;
		}

		if (typeof wc_block_data != 'undefined' && wc_block_data !== null) {
			if (wc_block_data?.checkoutData?.shipping_address?.country != null) {
				apaczka_point_data.apm_country_code = wc_block_data.checkoutData.shipping_address.country;
			} else {
				let shipping_country = $( '#shipping-country' );
				if (typeof shipping_country != 'undefined' && shipping_country !== null) {
					shipping_country_code = $( shipping_country ).val();
					if (typeof shipping_country_code != 'undefined' && shipping_country_code !== null) {
						apaczka_point_data.apm_country_code = record.shipping_country_code;
					}
				}
			}
		}


		apaczka_change_react_input( document.getElementById( 'apaczka-point' ), JSON.stringify( apaczka_point_data ) );

		
		let point_desc = '<span id="selected-parcel-machine-desc">' + visible_point_desc + '</span>';

		let apaczka_point = '<div class="apaczka_selected_point_data" id="apaczka_selected_point_data">\n'
		+ visible_point_id
		+ point_desc + '</div>';

		$( '#apaczka_selected_point_data_wrap' ).html( apaczka_point );
		$( '#apaczka_selected_point_data_wrap' ).show();

		$( '#shipping-phone' ).prop( 'required', true );
		$( 'label[for="shipping-phone"]' ).text( 'Telefon (wymagany)' );

	}

	function apaczka_pl_open_modal() {
		document.getElementById( 'apaczka_pl_checkout_validation_modal' ).style.display = 'flex';
	}

	function alsendo_connect_close_modal() {
		document.getElementById( 'apaczka_pl_checkout_validation_modal' ).style.display = 'none';
		// Scroll to map button.
		let scrollToElement = document.getElementById( 'shipping-option' );
		if (scrollToElement) {
			scrollToElement.scrollIntoView( {behavior: 'smooth'} );
		}
	}

	function alsendo_get_block_order_address_country(data) {

		let country = '';
		if( 'shipping_address' in data ) {
			if( 'country' in data.shipping_address ) {
				country = data.shipping_address.country;
			}
		}

		return country;

	}

	document.addEventListener(
		'change',
		function (e) {
			e          = e || window.event;
			var target = e.target || e.srcElement;

			if (target.classList.contains( 'wc-block-components-radio-control__input' )) {
				const parent = document.getElementById( "shipping-option" );
				if (parent && parent.contains( target )) {
					console.log( "Inside Shipping Block" );
					$( '#apaczka_selected_point_data' ).each(
						function (ind, elem) {
							$( elem ).remove();
						}
					);
					apaczka_change_react_input( document.getElementById( 'apaczka-point' ), '' );
				}
			}
		}
	);

	document.addEventListener(
		'click',
		function (e) {
			e          = e || window.event;
			var target = e.target || e.srcElement;

			if (target.hasAttribute( 'id' )) {
				if (target.getAttribute( 'id' ) === 'apaczka_geowidget_modal_cross') {
					e.preventDefault();
					let map_modal = document.getElementById( 'apaczka_geowidget_modal_dynamic' );
					if (typeof map_modal != 'undefined' && map_modal !== null) {
						map_modal.style.display = 'none';
					}
				}

				if (target.getAttribute( 'id' ) === 'geowidget_show_map') {
					e.preventDefault();

					let zaslat_map_sdk = '';
					if (typeof alsendo_shipment != 'undefined' && alsendo_shipment !== null) {
						zaslat_map_sdk = alsendo_shipment.zaslat_map_sdk;
					}

					let checked_radio_control = $( 'input[name^="radio-control-"]:checked' );
					if (typeof checked_radio_control != 'undefined' && checked_radio_control !== null) {
						let id          = $( checked_radio_control ).attr( 'id' );
						let instance_id = null;
						let method_data = null;
						if (typeof id != 'undefined' && id !== null) {
							method_data = id.split( ":" );
							instance_id = method_data[method_data.length - 1];
						}

						if (instance_id) {
							console.log( 'Alsendo_Connect: MAP shipping config' );
							console.log( alsendo_connect_block.map_config );

							if ( ! $.isEmptyObject( alsendo_connect_block.map_config )) {
								if (alsendo_connect_block.map_config.hasOwnProperty( instance_id )) {

									let operators             = null;
									if (typeof alsendo_connect_initial_map_country === 'undefined' || alsendo_connect_initial_map_country == null || alsendo_connect_initial_map_country === '' ) {
										let shipping_country      = $( '#shipping-country' );
										if (typeof shipping_country != 'undefined' && shipping_country !== null) {
											alsendo_connect_initial_map_country = $( shipping_country ).val();
										}
									}

									var key             = instance_id;
									var shipping_config = alsendo_connect_block.map_config[key];

									apaczka_geowidget_supplier = shipping_config.hasOwnProperty( "geowidget_supplier" ) ? shipping_config.geowidget_supplier : null;


									geowidget_only_cod = shipping_config.hasOwnProperty( "geowidget_only_cod" ) ? shipping_config.geowidget_only_cod : null;
									if (geowidget_only_cod && 'yes' === geowidget_only_cod) {
										apaczka_only_cod = true;
									} else {
										apaczka_only_cod = false;
									}

									if (typeof alsendo_connect_initial_map_country === 'undefined' || alsendo_connect_initial_map_country == null || alsendo_connect_initial_map_country === '' ) {
										let wc_settings = window.wcSettings;
										if (typeof wc_settings != 'undefined' && wc_settings !== null) {
											let saved_checkout_data = wc_settings.checkoutData;
											if (typeof saved_checkout_data != 'undefined' && saved_checkout_data !== null) {
												alsendo_connect_initial_map_country = alsendo_get_block_order_address_country(saved_checkout_data);
											}
										}
									}

									if (typeof alsendo_connect_initial_map_country === 'undefined' || alsendo_connect_initial_map_country == null || alsendo_connect_initial_map_country === '' ) {
										if ('ecolet' === alsendo_connect_block.api_type) {
											alsendo_connect_initial_map_country = 'ro';
										}
										if ('zaslat' === alsendo_connect_block.api_type) {
											alsendo_connect_initial_map_country = 'cz';
										}
										if ('apaczka' === alsendo_connect_block.api_type) {
											alsendo_connect_initial_map_country = 'pl';
										}
									}

									
									if (apaczka_geowidget_supplier !== null) {

										if (Array.isArray(apaczka_geowidget_supplier)) {
											// Find index of 'DHL' in array.
											let dhlIndex = apaczka_geowidget_supplier.indexOf('DHL');

											if ( dhlIndex !== -1 && 'PL' !== alsendo_connect_initial_map_country.toUpperCase() ) {
												// Replace 'DHL' with 'DHL_PARCEL' at the same position.
												apaczka_geowidget_supplier[dhlIndex] = 'DHL_PARCEL';
											}
										}


										operators = apaczka_geowidget_supplier.map(
											function (operator) {
												return apaczkaCreateOperatorWcBlock( 'operators - ' + operator, operator );
											}
										).filter( Boolean );
										operators = operators.length ? operators : null;
									}

									let bpwidget_config = {
										language: alsendo_connect_block.lang,
										posType: 'DELIVERY',
										mapOptions: { zoom: 14 },
										codOnly: apaczka_only_cod,
										operatorMarkers: true,
										countryCodes: alsendo_connect_initial_map_country,
										initialAddress: alsendo_connect_initial_map_address,
										operators: operators,
										codeSearch: true
									};

									console.log( 'Alsendo_Connect: map_initial_address: ', alsendo_connect_initial_map_country + ' ' + alsendo_connect_initial_map_address );
									console.log( 'bpwidget_config:' );
									console.log( bpwidget_config );

									BPWidget.init(
										document.getElementById( 'apaczka_geowidget_modal_inner_content' ),
										{
											callback: function (point) {
												let map_modal           = document.getElementById( 'apaczka_geowidget_modal_dynamic' );
												map_modal.style.display = 'none';
												apaczka_wc_block_point_callback( point );
											},
											language: alsendo_connect_block.lang,
											posType: 'DELIVERY',
											mapOptions: { zoom: 14 },
											codOnly: apaczka_only_cod,
											operatorMarkers: true,
											countryCodes: alsendo_connect_initial_map_country,
											initialAddress: alsendo_connect_initial_map_address,
											operators: operators,
											codeSearch: true
										}
									);

									let map_modal = document.getElementById( 'apaczka_geowidget_modal_dynamic' );
									if (typeof map_modal != 'undefined' && map_modal !== null) {
										map_modal.style.display = 'flex';
									}

								}
							}
						}
					}
				}
			}

			if (target.classList.contains( 'wc-block-components-checkout-place-order-button' )
			|| target.classList.contains( 'wc-block-checkout__actions_row' )
			|| target.classList.contains( 'wc-block-components-button__text' )
			|| target.closest( '.wc-block-components-checkout-place-order-button' )
			) {

				let reactjs_input       = document.getElementById( 'apaczka-point' );
				let reactjs_input_lalue = false;
				if (typeof reactjs_input != 'undefined' && reactjs_input !== null) {
					reactjs_input_lalue = reactjs_input.value;
					if ( ! reactjs_input_lalue) {
						apaczka_pl_open_modal();
					}
				}
			}

		}
	);

	$( document ).ready(
		function () {

			let wc_block_data = window.wcSettings;
			if (typeof wc_block_data != 'undefined' && wc_block_data !== null) {
				if (wc_block_data?.checkoutData?.shipping_address?.city != null) {
					alsendo_connect_initial_map_address = wc_block_data.checkoutData.shipping_address.city;
				}
				if (wc_block_data?.checkoutData?.shipping_address?.country != null) {
					alsendo_connect_initial_map_country = wc_block_data.checkoutData.shipping_address.country;
				}
			}

			let apaczka_geowidget_modal       = document.createElement( 'div' );
			let modal_html                    = '<div ' +
			'class="apaczka_geowidget_modal"' + ' style="display:none;"' +
			' id="apaczka_geowidget_modal_dynamic" style="display: none">' +
			'<div class="apaczka_geowidget_modal_inner">' +
			'<span id="apaczka_geowidget_modal_cross">&times;</span>' +
			'<div id="apaczka_geowidget_modal_inner_content"></div>' +
			'</div>' +
			'</div>';
			apaczka_geowidget_modal.innerHTML = modal_html;
			document.body.appendChild( apaczka_geowidget_modal );

			function createValidationModal(alertText) {
				const modal = document.createElement( 'div' );
				modal.id    = 'apaczka_pl_checkout_validation_modal';
				Object.assign(
					modal.style,
					{
						display: 'none',
						position: 'fixed',
						top: '0',
						left: '0',
						width: '100%',
						height: '100%',
						backgroundColor: 'rgba(0, 0, 0, 0.5)',
						justifyContent: 'center',
						alignItems: 'center',
						zIndex: '1000'
					}
				);

				const modalContent = document.createElement( 'div' );
				Object.assign(
					modalContent.style,
					{
						backgroundColor: 'white',
						width: '90%',
						maxWidth: '300px',
						padding: '20px',
						position: 'relative',
						textAlign: 'center',
						borderRadius: '10px',
						boxShadow: '0px 4px 10px rgba(0, 0, 0, 0.1)'
					}
				);

				const closeSpan     = document.createElement( 'span' );
				closeSpan.id        = 'alsendo_connect_close_modal_cross';
				closeSpan.innerHTML = '&times;';
				Object.assign(
					closeSpan.style,
					{
						position: 'absolute',
						top: '10px',
						right: '15px',
						fontSize: '20px',
						cursor: 'pointer'
					}
				);

				const messageDiv       = document.createElement( 'div' );
				messageDiv.textContent = alertText;
				Object.assign(
					messageDiv.style,
					{
						margin: '20px 0',
						fontSize: '18px'
					}
				);

				const okButton       = document.createElement( 'button' );
				okButton.id          = 'alsendo_connect_close_modal_button';
				okButton.textContent = 'Ok';
				Object.assign(
					okButton.style,
					{
						padding: '10px 20px',
						backgroundColor: '#007BFF',
						color: 'white',
						border: 'none',
						borderRadius: '5px',
						cursor: 'pointer',
						fontSize: '16px'
					}
				);

				modalContent.appendChild( closeSpan );
				modalContent.appendChild( messageDiv );
				modalContent.appendChild( okButton );
				modal.appendChild( modalContent );

				return modal;
			}

			const validation_modal = createValidationModal( alsendo_connect_block.alert_text );
			document.body.appendChild( validation_modal );
			document.getElementById( 'alsendo_connect_close_modal_cross' ).addEventListener( 'click', alsendo_connect_close_modal );
			document.getElementById( 'alsendo_connect_close_modal_button' ).addEventListener( 'click', alsendo_connect_close_modal );

			
			alsendo_connect_wait_elem('#shipping-postcode').then(
				function (zip) {
					let city = $('#shipping-city');

					if (typeof city != 'undefined' && city !== null) {
						const cityElement = city[0];

						const updateCityValue = function(value) {
							if (value && 'undefined' !== typeof value) {
								alsendo_connect_initial_map_address = value;
							}
						};

						const handleChange = alsendo_connect_delay_on_typein(
							function(e) {
								updateCityValue(e.target.value);
                                console.log('Alsendo: updateCityValue');
							},
							500
						);

						['keyup', 'change', 'input', 'blur'].forEach(eventType => {
							cityElement.addEventListener(eventType, handleChange);
						});
					}
				}
			);

			alsendo_connect_wait_elem( '#shipping-country' ).then(
				function (country) {
					country.addEventListener(
						'change',
						function (e) {
							e = e || window.event;
							let target = e.target;
							alsendo_connect_initial_map_country = target.value;
							console.log('alsendo_connect_wait_elem shipping-country');							
							console.log(alsendo_connect_initial_map_country);
						}
					);
				}
			);
		}
	);

})( jQuery );
