(function ($) {

	$( document ).ready(
		function () {

			var alsendo_map_country_code = '';
			var initial_map_address      = '';

			console.log( 'Alsendo Connect, ver: ' + alsendo_checkout.plugin_version );

			let apaczka_geowidget_modal;
			let cod_only       = false;
			let is_cod_only    = false;
			let operatorsArray = [];

			let shipping_methods_config = alsendo_checkout.map_config;
			console.log( 'shipping_methods_config:' );
			console.log( shipping_methods_config );
			let shipping_method_data = alsendo_connect_get_chosen_shipping_method();
			if ( 'instance_id' in shipping_method_data ) {
				let instance_id = shipping_method_data.instance_id;
				console.log( 'instance_id:' );
				console.log( instance_id );
				let config_by_instance_id = shipping_methods_config[instance_id];
				if (typeof config_by_instance_id != 'undefined' && config_by_instance_id !== null) {
					operatorsArray = config_by_instance_id.geowidget_supplier;
					//is_cod_only    = config_by_instance_id.geowidget_only_cod;
				}
			}

			window.apaczka_mp_map_callback = function (point) {

				$( '.alsendo_after_rate_description' ).each(
					function (i, elem) {
						$( elem ).remove();
					}
				);

				$( '.alsendo_connect_several_checkout_forms' ).each(
					function (i, elem) {
						$( elem ).remove();
					}
				);

				console.log( point );
				console.log( 'point code:', point.code );
				console.log( 'point operator:', point.operator );
				let map_modal           = document.getElementById( 'apaczka_geowidget_modal_dynamic' );
				map_modal.style.display = 'none';
				$( '#selected-parcel-machine' ).removeClass( 'apaczka-hidden' );
				if ( 'brand' in point ) {
					let point_brand = point.brand + ': ' + point.code;
					$( '#selected-parcel-machine-id' ).html( point_brand );
				} else {
					$( '#selected-parcel-machine-id' ).html( point.code );
				}

				let visible_point_desc = '';
				if ( 'description' in point && typeof point.description != 'undefined' ) {
					visible_point_desc += point.description;
				}
				if ('street' in point) {
					visible_point_desc += '<br>' + point.street;
				}
				if ('city' in point) {
					visible_point_desc += '<br>' + point.city;
				}
				if ('postalCode' in point) {
					visible_point_desc += '<br>' + point.postalCode;
				}

				$( '#selected-parcel-machine-desc' ).html( visible_point_desc );

				$( '#apm_name' ).each(
					function (i, elem) {
						$( elem ).val( point.description );
					}
				);
				$( '#apm_city' ).each(
					function (i, elem) {
						$( elem ).val( point.city );
					}
				);
				$( '#apm_street' ).each(
					function (i, elem) {
						$( elem ).val( point.street );
					}
				);
				$( '#apm_postal_code' ).each(
					function (i, elem) {
						$( elem ).val( point.postalCode );
					}
				);
				$( '#apm_country_code' ).each(
					function (i, elem) {
						$( elem ).val( alsendo_map_country_code );
					}
				);
				$( '#apm_supplier' ).each(
					function (i, elem) {
						$( elem ).val( point.operator );
					}
				);
				$( '#apm_access_point_id' ).each(
					function (i, elem) {
						$( elem ).val( point.code );
					}
				);
				$( '#apm_foreign_access_point_id' ).each(
					function (i, elem) {
						$( elem ).val( point.code );
					}
				);

				if ($( '.alsendo_after_rate_btn' ).length > 0) {
					console.log( 'alsendo_after_rate_btn' );

					$( '#selected-parcel-machine' ).each(
						function (i, elem) {
							$( elem ).addClass( 'apaczka-hidden' );
						}
					);

					let point_brand = '';
					if ( 'brand' in point ) {
						point_brand = point.brand + ': ' + point.code;

					} else {
						point_brand = point.code;
					}

					let wrap_open = '<span id="selected-parcel-machine" class="alsendo_after_rate_description" style="display:block;margin-top: 0px;">';

					let point_id = '<span style="font-size:1.1em;color: #249b20;">' + point_brand + '</span><br>';

					visible_point_desc += '<input type="hidden" id="apm_access_point_id" name="apm_access_point_id" value="' + point.code + '"/>\n' +
						'<input type="hidden" id="apm_supplier" name="apm_supplier" value="' + point.operator + '"/>\n' +
						'<input type="hidden" id="apm_name" name="apm_name" value="' + point.description + '"/>\n' +
						'<input type="hidden" id="apm_foreign_access_point_id" name="apm_foreign_access_point_id" value="' + point.code + '"/>\n' +
						'<input type="hidden" id="apm_street" name="apm_street" value="' + point.street + '"/>\n' +
						'<input type="hidden" id="apm_city" name="apm_city" value="' + point.city + '"/>\n' +
						'<input type="hidden" id="apm_postal_code" name="apm_postal_code" value="' + point.postalCode + '"/>\n' +
						'<input type="hidden" id="apm_country_code" name="apm_country_code" value="' + alsendo_map_country_code + '"/>\n' +
						'<input type="hidden" id="alsendo_connect_checkout" name="alsendo_connect_checkout" value="' + alsendo_checkout.checkout_nonce + '"/>';

					let wrap_close = '</span>';

					let after_rate_btn_point_desc = wrap_open + point_id + visible_point_desc + wrap_close;

					$( '.alsendo_after_rate_btn' ).after( after_rate_btn_point_desc );

					$( 'form' ).each(
						function () {
							if ( $( this ).find( '.alsendo_connect_several_checkout_forms' ).length === 0 ) {
								$( this ).append(
									'<span class="alsendo_connect_several_checkout_forms">' +
									'<input type="hidden" name="apm_access_point_id" value="' + point.code + '"/>\n' +
									'<input type="hidden" name="apm_supplier" value="' + point.operator + '"/>\n' +
									'<input type="hidden" name="apm_name" value="' + point.description + '"/>\n' +
									'<input type="hidden" name="apm_foreign_access_point_id" value="' + point.code + '"/>\n' +
									'<input type="hidden" name="apm_street" value="' + point.street + '"/>\n' +
									'<input type="hidden" name="apm_city" value="' + point.city + '"/>\n' +
									'<input type="hidden" name="apm_postal_code" value="' + point.postalCode + '"/>\n' +
									'<input type="hidden" name="apm_country_code" value="' + alsendo_map_country_code + '"/>\n' +
									'<input type="hidden" name="alsendo_connect_checkout" value="' + alsendo_checkout.checkout_nonce + '"/>' +
									'</span>'
								);
							}
						}
					);
				}
			}

			$( document.body ).on(
				'updated_checkout update_checkout',
				function () {
					let shipping_method_data = alsendo_connect_get_chosen_shipping_method();
					if ( 'instance_id' in shipping_method_data ) {
						let instance_id           = shipping_method_data.instance_id;
						let map_button            = document.getElementById( "alsendo_geowidget_show_map_classic_checkout" );
						let config_by_instance_id = shipping_methods_config[instance_id];
						if (typeof config_by_instance_id != 'undefined' && config_by_instance_id !== null) {
							operatorsArray = config_by_instance_id.geowidget_supplier;
							//is_cod_only    = config_by_instance_id.geowidget_only_cod;
							if ( typeof map_button != 'undefined' && map_button !== null) {
								console.log( 'show button:' );
								$( map_button ).removeClass( 'alsendo-hidden' );
							}
						} else {
							$( map_button ).addClass( 'alsendo-hidden' );
							$( '#selected-parcel-machine' ).addClass( 'apaczka-hidden' );
							$( '#selected-parcel-machine-id' ).html( '' );
							$( '#selected-parcel-machine-desc' ).html( '' );
						}

					}
				}
			);

			initial_map_address = alsendo_get_initial_map_address();

			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 );

			$( '#shipping_country' ).on(
				'change',
				function () {
					apaczkaShippingDataObject = { 'shipping_country': $( this ).val() };
					//localStorage.setItem( 'apaczkaShippingData', JSON.stringify( apaczkaShippingDataObject ) );
					alsendo_map_country_code = $( this ).val()
				}
			);

			$( '#billing_country' ).on(
				'change',
				function () {
					apaczkaShippingDataObject = { 'shipping_country': $( this ).val() };
					//localStorage.setItem( 'apaczkaShippingData', JSON.stringify( apaczkaShippingDataObject ) );
					alsendo_map_country_code = $( this ).val();
				}
			);

			document.addEventListener(
				'change',
				function (e) {
					e          = e || window.event;
					var target = e.target || e.srcElement;
					if ( target.classList.contains( 'shipping_method' ) ) {
						const parent = document.getElementById( "shipping_method" );
						if ( parent && parent.contains( target ) ) {
							console.log( "Change shipping option" );
							$( '#selected-parcel-machine' ).addClass( 'apaczka-hidden' );
							$( '#selected-parcel-machine-id' ).html( '' );
							$( '#selected-parcel-machine-desc' ).html( '' );

							let input_value = target.value;
							if (typeof input_value != 'undefined' && input_value !== null) {
								let instance_id = null;
								let method_data = null;
								method_data     = input_value.split( ":" );
								instance_id     = method_data[method_data.length - 1];

								// console.log( 'Change shipping instance_id:' );.
								// console.log( instance_id );
								let config_by_instance_id = shipping_methods_config[instance_id];
								let map_button            = document.getElementById( "alsendo_geowidget_show_map_classic_checkout" );
								if (typeof config_by_instance_id != 'undefined' && config_by_instance_id !== null) {
									// console.log( 'mamy config:' );.
									operatorsArray = config_by_instance_id.geowidget_supplier;
									
									if ( typeof map_button != 'undefined' && map_button !== null) {
										console.log( 'show button:' );
										$( map_button ).removeClass( 'alsendo-hidden' );
									}
								} else {
									// console.log( 'no config for selected shipping method:' );.
									$( map_button ).addClass( 'alsendo-hidden' );
								}
							}
						}
					}

					if (target.hasAttribute( 'id' ) && 'ship-to-different-address-checkbox' === target.getAttribute( 'id' ) ) {
						initial_map_address = alsendo_get_initial_map_address();
					}

				}
			);

			document.addEventListener(
				'click',
				function (e) {
					e          = e || window.event;
					var target = e.target || e.srcElement;
					if (target.hasAttribute( 'id' ) && 'alsendo_geowidget_show_map_classic_checkout' === target.getAttribute( 'id' ) ) {
						e.preventDefault();
						//let apaczkaShippingData = localStorage.getItem( 'apaczkaShippingData' );
						if ( '' === alsendo_map_country_code ) {
							/*let apaczkaShippingDataObject = JSON.parse( apaczkaShippingData );
							if ( 'shipping_country' in apaczkaShippingDataObject ) {
								alsendo_map_country_code = apaczkaShippingDataObject.shipping_country;
							}*/

							let shipping_country_input = $( '#shipping_country' );
							if (typeof shipping_country_input != 'undefined' && shipping_country_input !== null) {
								let country_code_shipping = $( shipping_country_input ).val();
								if (typeof country_code_shipping != 'undefined' && country_code_shipping !== null) {
									alsendo_map_country_code = country_code_shipping;
								} else {
									let billing_country = $( '#billing_country' );
									if (typeof billing_country != 'undefined' && billing_country !== null) {
										country_code_billing = $( billing_country ).val();
										if (typeof country_code_billing != 'undefined' && country_code_billing !== null) {
											alsendo_map_country_code = country_code_billing;
										}
									}
								}
							}

						}

						initial_map_address = alsendo_get_initial_map_address();

						if ( 'ecolet' === alsendo_checkout.api_type ) {
							alsendo_map_country_code = 'ro';
						}

						console.log( 'country_code_ before_map_init: ', alsendo_map_country_code );
						console.log( 'map_initial_address: ', initial_map_address );

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

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

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

						let current_shipping_method_id = $( 'input[name^="shipping_method"]:checked' ).val();
						let current_instance_id        = '';
						if (typeof current_shipping_method_id != 'undefined' && current_shipping_method_id !== null) {
							if (current_shipping_method_id.indexOf( ':' ) > -1) {
								let arr = current_shipping_method_id.split( ':' );
								if (arr && arr.length > 1) {
									current_instance_id       = arr[1];
									let config_by_instance_id = shipping_methods_config[current_instance_id];
									if (typeof config_by_instance_id != 'undefined' && config_by_instance_id !== null) {
										is_cod_only = config_by_instance_id.geowidget_only_cod;
										console.log( 'Alsendo connect: is_cod_only = ' + is_cod_only );

										if ('yes' === is_cod_only) {
											cod_only = true;
										} else {
											cod_only = false;
										}
									}
								}
							}
						}

						let bp_widget_params = {
							language: alsendo_checkout.lang,
							posType: 'DELIVERY',
							mapOptions: { zoom: 14 },
							codOnly: cod_only,
							operatorMarkers: true,
							countryCodes: alsendo_map_country_code,
							initialAddress: initial_map_address,
							operators: operators,
							codeSearch: true
						};

						console.log( 'Alsendo connect: bp_widget_params' );
						console.log( bp_widget_params );

						BPWidget.init(
							document.getElementById( 'apaczka_geowidget_modal_inner_content' ),
							{
								callback: function (point) {
									window.apaczka_mp_map_callback( point );
								},
								language: alsendo_checkout.lang,
								posType: 'DELIVERY',
								mapOptions: { zoom: 14 },
								codOnly: cod_only,
								operatorMarkers: true,
								countryCodes: alsendo_map_country_code,
								initialAddress: 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';
						}

					}

				},
				false
			);

			$( '#apaczka_geowidget_modal_cross' ).on(
				'click',
				function () {

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

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

			function alsendo_connect_wait_for_element(selector) {
				return new Promise(
					function (resolve) {
						if (document.querySelector( selector )) {
							return resolve( document.querySelector( selector ) );
						}

						const observer = new MutationObserver(
							function (mutations) {
								if (document.querySelector( selector )) {
									resolve( document.querySelector( selector ) );
									observer.disconnect();
								}
							}
						);

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

			function alsendo_connect_get_chosen_shipping_method() {
				let data    = {};
				let method  = $( 'input[name^="shipping_method"]:checked' ).val();
				let postfix = '';
				if ('undefined' == typeof method || null === method ) {
					method = $( 'input[name^="shipping_method"]' ).val();
				}
				if (typeof method != 'undefined' && method !== null) {
					if (method.indexOf( ':' ) > -1) {
						let arr = method.split( ':' );
						method  = arr[0];
						postfix = arr[1];
					}
				}
				data.method      = method;
				data.instance_id = postfix;

				return data;
			}

			function alsendo_get_initial_map_address() {

				let country_code        = '';
				let initial_map_address = '';

				let shipping_country_input = $( '#shipping_country' );

				if (typeof shipping_country_input != 'undefined' && shipping_country_input !== null) {
					let country_code_shipping_raw = $( shipping_country_input ).val();
					if (typeof country_code_shipping_raw != 'undefined' && country_code_shipping_raw !== null && '' !== country_code_shipping_raw ) {
						country_code = country_code_shipping_raw;
					} else {
						let billing_country = $( '#billing_country' );
						if (typeof billing_country != 'undefined' && billing_country !== null) {
							let country_code_billing = $( billing_country ).val();
							if (typeof country_code_billing != 'undefined' && country_code_billing !== null && '' !== country_code_billing ) {
								country_code = country_code_billing;
							}
						}
					}
				}

				let city = $( '#shipping_city' ).val();
				if (typeof city != 'undefined' && city !== null) {
					initial_map_address = city;
				} else {
					let city_2 = $( '#billing_city' ).val();
					if (typeof city_2 != 'undefined' && city_2 !== null) {
						initial_map_address = city_2;
					}
				}

				return initial_map_address;
			}

		}
	);

})( jQuery );
