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

			const { __, _x, _n, sprintf } = window.wp.i18n;
			const validation_warning      = __( 'You must select a delivery point', 'inpost-international' );
			let button_text               = __( 'Choose pick-up point', 'inpost-international' );
			let button_text2              = __( 'Change pick-up point', 'inpost-international' );

			const button_texts         = inpost_intl_frontend.button_texts;
			const selected_point_texts = inpost_intl_frontend.selected_texts;

			let inpost_intl_geowidget_modal;
			let inpost_global_geowidget_api = null;
			let geowidget_countries         = 'PL,BE,IT,FR,LU,PT,ES,NL,AT,HU';
			let coords                      = null;
			let selected_country            = null;

			let token   = inpost_intl_frontend.geowidget_token;
			let config  = 'parcelCollect';
			let content = 'Inpost Global Geowidget';

			let inpost_international_frontend = {
				init_modal: function ( country_code ) {
					console.log( "Inpost_international init_modal" );

					inpost_intl_geowidget_modal = document.createElement( 'div' );

					content = '<inpost-geowidget ' +
						'id="inpost-global-geowidget" ' +
						'country="' + geowidget_countries + '" ' +
						'onpoint="inpost_international_onpoint_select_callback" ' +
						'token="' + token + '" ' +
						'language="' + country_code + '" ' +
						'config="' + config + '"></inpost-geowidget>';

					let modal_html = '<div ' +
						'class="inpost_intl_geowidget_modal"' +
						' id="inpost_intl_geowidget_modal_dynamic">' +
						'<div class="inpost_intl_geowidget_modal_inner">' +
						'<span id="inpost_international_close_modal_cross">&times;</span>' +
						'<div class="inpost_intl_geowidget_modal_inner_content">' + content + '</div>' +
						'</div>' +
						'</div>';

					inpost_intl_geowidget_modal.innerHTML = modal_html;

					document.body.appendChild( inpost_intl_geowidget_modal );

				},

				set_map_config: function (map_config) {
					let modal_inner_content = $( '.inpost_intl_geowidget_modal_inner_content' );
					if (typeof modal_inner_content != 'undefined' && modal_inner_content !== null) {
						$( '#inpost-global-geowidget' ).attr( 'config', map_config );
					}
				},

				set_geowidget_position: function (coords, zoom = 12 ) {
					if (typeof inpost_global_geowidget_api != 'undefined' && inpost_global_geowidget_api !== null) {
						try {
							// console.log('InPost INT - set map coords:');
							// console.log(coords);
							inpost_global_geowidget_api.changePosition( coords, zoom );
						} catch (error) {
							console.error( "An error occurred: " + error.message );
						}
					}
				},

				wait_for_element: function (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
								}
							);
						}
					);
				},

				get_chosen_shipping_method: function () {
					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.postfix = postfix;

					return data;
				},

				callback_on_locker_point_select: function ( point ) {

				},

				get_configured_inpost_methods: function () {
					if (typeof window.inpost_intl_frontend != 'undefined' && window.inpost_intl_frontend !== null) {
						if ( window.inpost_intl_frontend.inpost_methods ) {
							return window.inpost_intl_frontend.inpost_methods;
						}
					}
					return [];
				},

				open_validation_modal: function () {
					document.getElementById( 'inpost_intl_checkout_validation_modal' ).style.display = 'flex';
				},

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

				is_checkout_block_type: function () {
					let wc_settings = window.wcSettings;
					if (typeof wc_settings != 'undefined' && wc_settings !== null) {
						let inpost_block_data = wc_settings.inpost_intl_block_data;
						if (typeof inpost_block_data != 'undefined' && inpost_block_data !== null) {
							if (inpost_block_data.inpost_wc_block_enabled) {
								return true;
							}
						}
					}
					return false;
				},

				inpost_intl_validate_locker_for_gpay: function () {
					let checked_shipping_input = document.querySelector( '#shipping_method input[name^="shipping_method["]:checked' );
					if (checked_shipping_input !== undefined && checked_shipping_input !== null) {
						let id = checked_shipping_input.value;
						console.log( 'Shipping method ID:', id );

						if (id.indexOf( 'inpost_international_automated_locker_point' ) !== -1) {
							let checkout_block_type = inpost_international_frontend.is_checkout_block_type();
							let hidden_input        = null;
							if (  checkout_block_type ) {
								hidden_input = document.getElementById( 'inpost-international-locker-id' );
							} else {
								hidden_input = document.getElementById( 'inpost_international_locker_id' );
							}
							if (hidden_input !== undefined && hidden_input !== null) {
								let locker_id = hidden_input.value;
								console.log( 'Locker ID:', locker_id );
								if (locker_id.trim() === '') {
									return false;
								}
							}
						}
					}

					return true;
				},

				change_react_input_value: function (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 );
					}
				},

				is_js_mode_map_activated: function () {
					if (typeof window.inpost_intl_frontend != 'undefined' && window.inpost_intl_frontend !== null) {
						if ( window.inpost_intl_frontend.map_button_js_mode ) {
							return true;
						}
					}
					return false;
				},

				get_map_config_based_on_instance_id: function (instance_id, method) {
					let map_config     = 'parcelCollect';
					let inpost_methods = this.get_configured_inpost_methods();

					if (instance_id !== undefined && instance_id !== null && instance_id !== '') {
						let selected_method = inpost_methods[instance_id];
						if (typeof selected_method != 'undefined' && selected_method !== null) {
							let method_id = selected_method.inpost_title;
							if (method_id === 'easypack_parcel_machines_cod') {
								map_config = 'parcelCollectPayment';
							}
							if (method_id === 'easypack_shipping_courier_c2c') {
								map_config = 'parcelSend';
							}
							if (method_id === 'easypack_parcel_machines_weekend' || method_id === 'easypack_parcel_machines_weekend_cod') {
								map_config = 'parcelCollect247';
							}
						}

					} else {
						if (method === 'easypack_parcel_machines_cod') {
							map_config = 'parcelCollectPayment';
						}
						if (method === 'easypack_shipping_courier_c2c') {
							map_config = 'parcelSend';
						}
						if (method === 'easypack_parcel_machines_weekend' || method === 'easypack_parcel_machines_weekend_cod') {
							map_config = 'parcelCollect247';
						}
					}

					return map_config;
				},

				open_map_modal: function () {
					let map_modal = document.getElementById( 'inpost_intl_geowidget_modal_dynamic' );
					if (typeof map_modal != 'undefined' && map_modal !== null) {
						map_modal.style.display = 'flex';
					}
				},
				block_scroll: function () {
					const scrollTop  = window.pageYOffset || document.documentElement.scrollTop;
					const scrollLeft = window.pageXOffset || document.documentElement.scrollLeft;
					window.onscroll  = function () {
						window.scrollTo( scrollLeft, scrollTop );
					};
				},
				unblock_scroll: function () {
					window.onscroll = function () {};
				},
				set_initial_geowidget_position: function ( country_code = null ) {

					let checkout_block_type = inpost_international_frontend.is_checkout_block_type();
					let country_code_locale = null;

					if ( ! country_code ) {
						if ( checkout_block_type ) {
							let wc_settings = window.wcSettings;
							if ( typeof wc_settings != 'undefined' && wc_settings !== null) {
								let site_locale = wc_settings.locale.siteLocale;
								let user_locale = wc_settings.locale.userLocale;
								console.log( "site_locale" );
								console.log( site_locale );
								console.log( "user_locale" );
								console.log( user_locale );
								let checkout_data = wc_settings.checkoutData;
								if ( typeof checkout_data != 'undefined' && checkout_data !== null) {
									country_code = checkout_data.shipping_address.country;
									console.log( "country_code" );
									console.log( country_code );
								}
							}
						} else {
							country_code = $( '#shipping_country' ).val();
							if ( ! country_code ) {
								country_code = $( '#billing_country' ).val();
							}
						}
					}

					if ( typeof country_code != 'undefined' && country_code !== null) {
						if ( typeof inpost_global_geowidget_api != 'undefined' && inpost_global_geowidget_api !== null ) {
							try {
								country_code_locale = country_code.toLowerCase();
								const arr           = ['pt', 'pl', 'es', 'nl', 'it', 'fr'];
								if (arr.indexOf( country_code_locale ) !== -1) {
									console.log( 'Translation exists for this language' );
								} else {
									country_code_locale = 'en';
								}
								inpost_global_geowidget_api.changeLanguage( country_code_locale );
							} catch (error) {
								console.error( "An error occurred when we try to cahnge map language: " + error.message );
							}
						} else {
							console.error( "inpost_global_geowidget_api === undefined " );
						}
					}

					if ('PL' === country_code) {
						coords = {longitude: 20.318968, latitude: 49.731131};
					}
					if ('BE' === country_code) {
						// 50.8518425654914, 4.351724313951752
						coords = {longitude: 4.351724, latitude: 50.851842};
					}
					if ('IT' === country_code) {
						// 41.896154821545316, 12.496158445220988
						coords = {longitude: 12.496158, latitude: 41.896154};
					}
					if ('FR' === country_code) {
						// 48.85747020725999, 2.3576749096813567
						coords = {longitude: 2.357674, latitude: 48.857470};
					}
					if ('LU' === country_code) {
						// 49.612793733267004, 6.141375112248663
						coords = {longitude: 6.141375, latitude: 49.612793};
					}
					if ('PT' === country_code) {
						// 38.73202335039995, -8.871431250019862
						coords = {longitude: -8.871431, latitude: 38.732023};
					}
					if ('ES' === country_code) {
						// 40.47738373459267, -3.7204805103180743
						coords = {longitude: -3.720480, latitude: 40.4773837};
					}
					if ('NL' === country_code) {
						// 52.36841126990683, 5.106379478772352
						coords = {longitude: 5.106379, latitude: 52.368411};
					}
					if ('HU' === country_code) {
						// 47.49805747944981, 19.125168494702145
						coords = {longitude: 19.125168, latitude: 47.498057};
					}

					inpost_international_frontend.set_geowidget_position( coords );
				}

			};

			let js_mode             = inpost_international_frontend.is_js_mode_map_activated();
			let checkout_block_type = inpost_international_frontend.is_checkout_block_type();

			let checkout_data = null;
			if ( checkout_block_type ) {
				let wc_block_data = window.wcSettings;
				if (typeof wc_block_data != 'undefined' && wc_block_data !== null) {
					checkout_data = wc_block_data.checkoutData;
					if (typeof checkout_data != 'undefined' && checkout_data !== null) {
						selected_country = checkout_data.shipping_address.country;
						// console.log( "window.wcSettings country_code" );
						// console.log( selected_country );
					}
				}
			} else {
				selected_country = $( '#shipping_country' ).val();
				if ( ! selected_country || 'undefined' === typeof selected_country ) {
					selected_country = $( '#billing_country' ).val();
				}
			}

			inpost_international_frontend.init_modal( selected_country );

			inpost_international_frontend.wait_for_element( '#inpost-global-geowidget' ).then(
				function (geowidget) {
					geowidget.addEventListener(
						'inpost.geowidget.init',
						function (event) {
							inpost_global_geowidget_api = event.detail.api;
							// console.log( 'inpost_global_geowidget_api' );
							// console.log( inpost_global_geowidget_api );
							// console.log( selected_country );

							if (typeof selected_country != 'undefined' && selected_country !== null) {
								setTimeout(
									function () {
										inpost_international_frontend.set_initial_geowidget_position( selected_country );
									},
									5000
								);
							}
						}
					);
				}
			);

			if ( js_mode ) {
				console.log( 'JS MODE: true' );
			} else {
				console.log( 'JS MODE: false' );
			}

			if ( checkout_block_type ) {
				console.log( 'CHECKOUT TYPE BLOCK: true' );

				inpost_international_frontend.wait_for_element( '#shipping-country' ).then(
					function (shipping_country) {
						shipping_country.addEventListener(
							'change',
							function (event) {
								localStorage.setItem( 'inpost_international_point_object', null );
								inpost_international_frontend.set_initial_geowidget_position( this.value );
								selected_country = this.value;
								if ( button_texts.hasOwnProperty( selected_country ) ) {
									button_text = button_texts[selected_country];
									if (typeof $( '#inpost_intl_show_geowidget' ) != 'undefined' && $( '#inpost_intl_show_geowidget' ) !== null ) {
										$('#inpost_intl_show_geowidget').text(button_text);
									}
								} else {
									if (typeof $( '#inpost_intl_show_geowidget' ) != 'undefined' && $( '#inpost_intl_show_geowidget' ) !== null ) {
										$( '#inpost_intl_show_geowidget' ).css( 'display', 'none' );
									}
								}

								$( '.inpost_intl_selected_point_data' ).each(
									function (ind, elem) {
										$( elem ).remove();
									}
								);
								$( '.inpost_pl_additional_validation_field' ).each(
									function (ind, elem) {
										$( elem ).remove();
									}
								);
								inpost_international_frontend.change_react_input_value( document.getElementById( 'inpost-international-locker-id' ), '' );
								inpost_international_frontend.change_react_input_value( document.getElementById( 'inpost-international-locker-description' ), '' );

							}
						);
					}
				);

				let inpost_methods = inpost_international_frontend.get_configured_inpost_methods();
				console.log( "inpost_methods" );
				console.log( inpost_methods );

				let modal       = document.createElement( 'div' );
				modal.innerHTML = "<div id='inpost_intl_checkout_validation_modal' style='display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background-color: rgba(0, 0, 0, 0.5); justify-content: center; align-items: center; z-index: 1000;'><div style='background-color: white; width: 90%; max-width: 300px; padding: 20px; position: relative; text-align: center; border-radius: 10px; box-shadow: 0px 4px 10px rgba(0, 0, 0, 0.1);'><span id='inp_intl_close_modal_cross' style='position: absolute; top: 10px; right: 15px; font-size: 20px; cursor: pointer;'>&times;</span><div style='margin:20px 0; font-size:18px;'>InPost International:<br>" + validation_warning + "</div><button id='inp_intl_close_modal_button' style='padding: 10px 20px; background-color: #FFA900; color: white; border: none; border-radius: 5px; cursor: pointer; font-size: 16px;'>Ok</button></div></div>";

				// Append modal to body.
				document.body.appendChild( modal );

				// Event Listeners for closing modal.
				let modal_close_1 = document.getElementById( 'inp_intl_close_modal_cross' );
				if (typeof modal_close_1 != 'undefined' && modal_close_1 !== null) {
					modal_close_1.addEventListener( 'click', inpost_international_frontend.close_validation_modal );
				}
				let modal_close_2 = document.getElementById( 'inp_intl_close_modal_button' );
				if (typeof modal_close_2 != 'undefined' && modal_close_2 !== null) {
					modal_close_2.addEventListener( 'click', inpost_international_frontend.close_validation_modal );
				}

				let is_inpost_shipping_method = false;
				let selected_shipping_radio   = null;

				inpost_international_frontend.wait_for_element( '#shipping-option' ).then(
					function (shipping_options) {
						console.log( "shipping_options_is_appeared" );
						selected_shipping_radio = document.querySelector( '#shipping-option .wc-block-components-radio-control__input:checked' );
						// console.log( "selected_shipping_radio" );
						// console.log( selected_shipping_radio );

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

							if ( typeof inpost_methods != 'undefined' && inpost_methods !== null) {
								let map_config_settings = inpost_methods[instance_id];
								// console.log( "map_config_settings" );
								// console.log( map_config_settings );
								inpost_international_frontend.wait_for_element( '#inpost_intl_show_geowidget' ).then(
									function (map_button) {
										// console.log( "map_button_is_visible" );
										if ( typeof map_config_settings != 'undefined' && map_config_settings !== null) {
											if ( 'need_map' in map_config_settings ) {
												if (button_texts.hasOwnProperty(selected_country)) {
													button_text = button_texts[selected_country];
												}
												$(map_button).text(button_text);
												$(map_button).css('display', 'block');

												console.log( "NEED MAP:" );

											} else {

												console.log( "NO NEED MAP:" );

												$( map_button ).css( 'display', 'none' );
												inpost_international_frontend.change_react_input_value( document.getElementById( 'inpost-international-locker-id' ), '' );
												inpost_international_frontend.change_react_input_value( document.getElementById( 'inpost-international-locker-description' ), '' );
											}
										} else {
											$( map_button ).css( 'display', 'none' );
											inpost_international_frontend.change_react_input_value( document.getElementById( 'inpost-international-locker-id' ), '' );
											inpost_international_frontend.change_react_input_value( document.getElementById( 'inpost-international-locker-description' ), '' );
										}
									}
								);

							}
						}
					}
				);

			} else {
				console.log( 'CHECKOUT TYPE BLOCK: false' );
				// console.log( "wc_checkout_params" );
				// console.log( window.wc_checkout_params );
			}

			let shipping_data = inpost_international_frontend.get_chosen_shipping_method();
			let method        = shipping_data.method;
			let instance_id   = shipping_data.postfix;

			let shipping_option_input = null;
			let li_parent             = null;

			if (typeof method != 'undefined' && method !== null) {
				config = inpost_international_frontend.get_map_config_based_on_instance_id( instance_id, method );
			}

			$( '#shipping_country' ).on(
				'change',
				function () {
					localStorage.setItem( 'inpost_international_point_object', null );
					selected_country = $( this ).val();
					inpost_international_frontend.set_initial_geowidget_position( $( this ).val() );
				}
			);

			$( '#billing_country' ).on(
				'change',
				function () {
					localStorage.setItem( 'inpost_international_point_object', null );
					selected_country = $( this ).val();
					inpost_international_frontend.set_initial_geowidget_position( $( this ).val() );
				}
			);

			$( document.body ).on(
				'updated_checkout update_checkout',
				function () {

					let selected_point_text = '';
					if ( button_texts.hasOwnProperty( selected_country ) ) {
						button_text = button_texts[selected_country];
					}
					if ( selected_point_texts.hasOwnProperty( selected_country ) ) {
						selected_point_text = selected_point_texts[selected_country];
					}

					let is_need_to_show_map_button = false;
					let js_mode                    = inpost_international_frontend.is_js_mode_map_activated();
					if ( js_mode ) {
						$( '.inpost_intl_show_geowidget' ).each(
							function (ind, elem) {
								$( elem ).remove();
							}
						);
						$( '.inpost_intl_selected_point_data' ).each(
							function (ind, elem) {
								$( elem ).remove();
							}
						);
					}

					shipping_data = inpost_international_frontend.get_chosen_shipping_method();
					method        = shipping_data.method;
					instance_id   = shipping_data.postfix;
					if ( typeof method != 'undefined' && method !== null ) {
						config = inpost_international_frontend.get_map_config_based_on_instance_id( instance_id, method );
						inpost_international_frontend.set_map_config( config );
						let selector               = method + ':' + instance_id;
						let shipping_options_block = $( '#shipping_method' );
						if ( typeof shipping_options_block != 'undefined' && shipping_options_block !== null ) {
							$( shipping_options_block ).find( 'input' ).each(
								function (index, input) {
									if ( selector === $( input ).val() ) {
										shipping_option_input = input;
									}
								}
							);
						}
					}

					let map_button = '<div class="inpost_intl_show_geowidget" id="inpost_intl_show_geowidget">\n' +
						button_text + '</div>';
					if ( shipping_option_input ) {
						li_parent = $( shipping_option_input ).closest( 'li' );
					}

					if ( typeof method != 'undefined' && method !== null ) {
						if ( method.indexOf( 'inpost_international_automated_locker_point' ) !== -1 ) {
							is_need_to_show_map_button = true;
						} else {

							let inpost_methods        = inpost_international_frontend.get_configured_inpost_methods();
							let linked_fs_method_data = inpost_methods[instance_id];
							if ( typeof linked_fs_method_data != 'undefined' && linked_fs_method_data !== null ) {
								let linked_fs_method = linked_fs_method_data.inpost_title;
								if ( linked_fs_method.indexOf( 'inpost_international_automated_locker_point' ) !== -1 ) {
									is_need_to_show_map_button = true;
								}
							}
						}
					}

					let phone_input             = $( '#shipping_phone' );
					let phone_input_placeholder = '';
					if (typeof phone_input === 'undefined' || phone_input === null || ! phone_input.length > 0 ) {
						phone_input = $( '#billing_phone' );
					}
					if (typeof phone_input != 'undefined' && phone_input !== null) {
						phone_input_placeholder = $( phone_input ).attr( 'placeholder' );
					}

					if ( is_need_to_show_map_button ) {
						if (js_mode) {
							if (typeof li_parent != 'undefined' && li_parent !== null) {
								$( li_parent ).after( map_button );
							}
						}

						$( '#inpost_intl_show_geowidget' ).each(
							function (ind, elem) {
								$( elem ).text( button_text );
							}
						);
						$( '.inpost_intl-visible-point-header' ).each(
							function (ind, elem) {
								$( elem ).text( selected_point_text );
							}
						);

						$( '#inpost_intl_show_geowidget' ).css( 'display', 'block' );

						if (typeof phone_input != 'undefined' && phone_input !== null) {
							$( phone_input ).attr( 'placeholder', 'Please start with country code...' );
						}

					} else {
						$( '#inpost_intl_show_geowidget' ).css( 'display', 'none' );
						$( '.inpost_intl_hidden_point_data' ).css( 'display', 'none' );
						if (typeof phone_input != 'undefined' && phone_input !== null) {
							$( phone_input ).attr( 'placeholder', '' );
						}
					}

					let inpost_international_point_object = localStorage.getItem( 'inpost_international_point_object' );

					if (inpost_international_point_object !== null) {
						let point_code;
						let visible_desc;
						let point_decription = '';

						let pointData = JSON.parse( inpost_international_point_object );
						if (typeof pointData != 'undefined' && pointData !== null) {
							if (typeof pointData.pointName != 'undefined' && pointData.pointName !== null) {
								point_code = pointData.pointName;
							}
							if (typeof pointData.visiblePointData != 'undefined' && pointData.visiblePointData !== null) {
								visible_desc = pointData.visiblePointData;
							}
							if (typeof pointData.pointDesc != 'undefined' && pointData.pointDesc !== null) {
								point_decription = pointData.pointDesc;
							}

							let selected_point_data = '';

							if (typeof point_code != 'undefined' && point_code !== null) {

								selected_point_data = '<div class="inpost_intl_selected_point_data" id="inpost_intl_selected_point_data" style="margin-bottom:15px">\n'
									+ '<div id="selected-parcel-machine-id">' + point_code + '</div>\n'
									+ '<span id="selected-parcel-machine-desc">' + visible_desc + '</span>' +
									'<input type="hidden" id="inpost_international_locker_id"\n' +
									'name="inpost_international_locker_id" class="inpost_international_locker_id" value="' + point_code + '"/>\n' +
									'<input type="hidden" id="inpost_international_locker_desc"\n' +
									'name="inpost_international_locker_desc" class="inpost_international_locker_desc" value="' + point_decription + '"/></div>\n';

							}

							if (typeof point_code != 'undefined' && point_code !== null) {
								if ( is_need_to_show_map_button ) {
									if ( js_mode ) {
										$( '#inpost_intl_show_geowidget' ).after( selected_point_data );
									} else {
										$( '.inpost_intl-visible-point-description' ).each(
											function (ind, elem) {
												$( elem ).html( selected_point_data );
											}
										);
										$( '.inpost_international_locker_id' ).each(
											function (ind, elem) {
												$( elem ).val( point_code );
											}
										);
										$( '.inpost_international_locker_desc' ).each(
											function (ind, elem) {
												$( elem ).val( point_decription );
											}
										);
										$( '.inpost_intl-visible-point-header' ).each(
											function (ind, elem) {
												$( elem ).show();
											}
										);
										$( '.inpost_intl_hidden_point_data' ).each(
											function (ind, elem) {
												$( elem ).show();
											}
										);
									}
								}
							}
						}
					}
				}
			);

			$( '.inpost_intl_show_geowidget' ).on(
				'click',
				function () {
					if ( typeof inpost_intl_geowidget_modal != 'undefined' && inpost_intl_geowidget_modal !== null ) {

						try {
							inpost_international_frontend.open_map_modal();
							inpost_international_frontend.block_scroll();
							return true;
						} catch (error) {
							console.error( 'Error opening map modal:', error );
							inpost_international_frontend.unblock_scroll();
							return false;
						}
					}
				}
			);

			$( '#inpost_international_close_modal_cross' ).on(
				'click',
				function () {
					inpost_international_frontend.unblock_scroll();
					let map_modal = document.getElementById( 'inpost_intl_geowidget_modal_dynamic' );
					if (typeof map_modal != 'undefined' && map_modal !== null) {
						map_modal.style.display = 'none';
					}
				}
			);

			// open modal with map.
			document.addEventListener(
				'click',
				function (e) {
					e          = e || window.event;
					let target = e.target || e.srcElement;

					if (target.hasAttribute( 'id' ) && target.getAttribute( 'id' ) === 'inpost_international_close_modal_cross') {
						inpost_international_frontend.unblock_scroll();
						let map_modal = document.getElementById( 'inpost_intl_geowidget_modal_dynamic' );
						if (typeof map_modal != 'undefined' && map_modal !== null) {
							map_modal.style.display = 'none';
						}
					}

					if (target.hasAttribute( 'id' ) && target.getAttribute( 'id' ) === 'inpost_intl_show_geowidget') {
						e.preventDefault();
						if ( typeof inpost_intl_geowidget_modal != 'undefined' && inpost_intl_geowidget_modal !== null ) {

							try {
								inpost_international_frontend.open_map_modal();
								inpost_international_frontend.block_scroll();
								return true;
							} catch (error) {
								console.error( 'Error opening map modal:', error );
								inpost_international_frontend.unblock_scroll();
								return false;
							}
						}
					}

					if ( target.closest( '.wc-block-components-checkout-place-order-button' ) ) {
						let reactjs_input                  = document.getElementById( 'inpost-international-locker-id' );
						let reactjs_input_lalue            = false;
						let map_config_for_selected_method = null;
						if (typeof reactjs_input != 'undefined' && reactjs_input !== null) {
							let selected_shipping_radio = document.querySelector( '#shipping-option .wc-block-components-radio-control__input:checked' );

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

								let inpost_methods = inpost_international_frontend.get_configured_inpost_methods();
								if (typeof inpost_methods != 'undefined' && inpost_methods !== null) {
									map_config_for_selected_method = inpost_methods[instance_id];
								}
							}
							if ( typeof map_config_for_selected_method != 'undefined' && map_config_for_selected_method !== null ) {
								if ( 'need_map' in map_config_for_selected_method ) {
									reactjs_input_lalue = reactjs_input.value;
									if (!reactjs_input_lalue) {
										inpost_international_frontend.open_validation_modal();
									}
								}
							}
						}
					}
				}
			);

			document.addEventListener(
				'inpost_international_onpoint_select_callback',
				function (point) {
					console.log( point.detail );

					let point_code = point.detail.name;

					const regex = /^[A-Za-z]{2}_/;

					if ( typeof point_code != 'undefined' && point_code !== null ) {
						if (regex.test( point_code )) {
							point_code = point_code.slice( 3 );
						}
					}

					let address_line1 = '';
					let address_line2 = '';

					if ( typeof point.detail.address.line1 != 'undefined' && point.detail.address.line1 !== null ) {
						address_line1 = point.detail.address.line1;
					}
					if ( typeof point.detail.address.line2 != 'undefined' && point.detail.address.line2 !== null ) {
						address_line2 = point.detail.address.line2;
					}

					let point_decription         = address_line1 + ' ' + address_line2;
					let point_decription_visible = address_line1 + '<br>' + address_line2;
					let point_decription_plus    = '';

					if ( point.detail.location_description ) {
						point_decription_plus = point.detail.location_description;

						selected_point_data = '<div class="inpost_intl_selected_point_data" id="inpost_intl_selected_point_data" style="margin-bottom:15px">\n'
							+ '<div id="selected-parcel-machine-id">' + point_code + '</div>\n'
							+ '<span id="selected-parcel-machine-desc">' + address_line1 + '<br>' + address_line2 + '</span><br>'
							+ '<span id="selected-parcel-machine-desc1">(' + point.detail.location_description + ')</span>' +
							'<input type="hidden" id="inpost_international_locker_id"\n' +
							'name="inpost_international_locker_id" class="inpost_international_locker_id" value="' + point_code + '"/>\n' +
							'<input type="hidden" id="inpost_international_locker_desc"\n' +
							'name="inpost_international_locker_desc" class="inpost_international_locker_desc" value="' + point_decription + ' ' + point.detail.location_description + '"/></div>\n';

					} else {
						selected_point_data = '<div class="inpost_intl_selected_point_data" id="inpost_intl_selected_point_data" style="margin-bottom:15px">\n'
							+ '<div id="selected-parcel-machine-id">' + point_code + '</div>\n'
							+ '<span id="selected-parcel-machine-desc">' + address_line1 + '<br>' + address_line2 + '</span><br>'
						'<input type="hidden" id="inpost_international_locker_id"\n' +
						'name="inpost_international_locker_id" class="inpost_international_locker_id" value="' + point_code + '"/>\n' +
						'<input type="hidden" id="inpost_international_locker_desc"\n' +
						'name="inpost_international_locker_desc" class="inpost_international_locker_desc" value="' + point_decription + '"/></div>';
					}

					$( '.inpost_intl-visible-point-header' ).each(
						function (ind, elem) {
							$( elem ).hide();
						}
					);

					$( '#inpost_intl_selected_point_data' ).each(
						function (ind, elem) {
							$( elem ).remove();
						}
					);

					$( '.inpost_pl_additional_validation_field' ).each(
						function (ind, elem) {
							$( elem ).remove();
						}
					);

					let checkout_block_type = inpost_international_frontend.is_checkout_block_type();
					if ( checkout_block_type ) {
						$( '#inpost_intl_selected_point_data_wrap' ).html( selected_point_data );
						$( '#inpost_intl_selected_point_data_wrap' ).show();

						inpost_international_frontend.change_react_input_value( document.getElementById( 'inpost-international-locker-id' ), point_code );
						inpost_international_frontend.change_react_input_value( document.getElementById( 'inpost-international-locker-description' ), point_decription );

					} else {
						if ( js_mode ) {
							$( '#inpost_intl_show_geowidget' ).after( selected_point_data );
						} else {
							$( '.inpost_intl-visible-point-description' ).each(
								function (ind, elem) {
									$( elem ).html( selected_point_data );
								}
							);
							$( '.inpost_international_locker_id' ).each(
								function (ind, elem) {
									$( elem ).val( point_code );
								}
							);
							$( '.inpost_international_locker_desc' ).each(
								function (ind, elem) {
									$( elem ).val( point_decription );
								}
							);
							$( '.inpost_intl-visible-point-header' ).each(
								function (ind, elem) {
									$( elem ).show();
								}
							);
							$( '.inpost_intl_hidden_point_data' ).each(
								function (ind, elem) {
									$( elem ).show();
								}
							);
						}
					}

					// $( "#inpost_intl_show_geowidget" ).text( button_text2 );

					// for some templates like Divi - add hidden fields for Inpost Parcel locker dynamically.
					let form               = document.getElementsByClassName( 'checkout woocommerce-checkout' )[0];
					let additionalInput1   = document.createElement( 'input' );
					additionalInput1.type  = 'hidden';
					additionalInput1.name  = 'inpost_international_locker_id';
					additionalInput1.value = point_code;
					additionalInput1.classList.add( 'inpost_pl_additional_validation_field' );

					let additionalInput2   = document.createElement( 'input' );
					additionalInput2.type  = 'hidden';
					additionalInput2.name  = 'inpost_international_locker_desc';
					additionalInput2.value = point_decription;
					additionalInput2.classList.add( 'inpost_pl_additional_validation_field' );

					if (form) {
						form.appendChild( additionalInput1 );
						form.appendChild( additionalInput2 );
					}

					let map_modal = document.getElementById( 'inpost_intl_geowidget_modal_dynamic' );
					if (typeof map_modal != 'undefined' && map_modal !== null) {
						map_modal.style.display = 'none';
					}
					inpost_international_frontend.unblock_scroll();
					let chosen_coords = point.detail.location;
					coords            = {longitude: chosen_coords.longitude, latitude: chosen_coords.latitude};
					inpost_international_frontend.set_geowidget_position( coords, 16 );

					point_decription_visible = point_decription_visible + '<br>' + point_decription_plus;

					let inpost_international_point_object = { 'pointName': point_code, 'pointDesc': point_decription, 'visiblePointData': point_decription_visible };
					localStorage.setItem( 'inpost_international_point_object', JSON.stringify( inpost_international_point_object ) );

					$.ajax(
						{
							type: 'POST',
							url: inpost_intl_frontend.ajaxurl,
							data: {
								action: 'inpost_intl_save_locker_to_wc_session',
								security: inpost_intl_frontend.nonce,
								inpost_intl_locker: point_code
							},
							dataType: 'json',
							success: function (response) {
								console.log( 'Inpost INT: Locker saved in session data:', response );
							},
							error: function (jqXHR, textStatus, errorThrown) {
								console.log( "Error response saving locker into session" );
								console.log( textStatus );
								console.log( 'Error: ' + errorThrown + ' ' + jqXHR.responseText );

							}
						}
					);

					if ( point.detail.country !== selected_country ) {
						console.log( 'point.country !== selected_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 WC CHECKOUT Block");.
							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];
								let inpost_methods = inpost_international_frontend.get_configured_inpost_methods();
								if ( typeof inpost_methods != 'undefined' && inpost_methods !== null) {
									let map_config_settings = inpost_methods[instance_id];
									const map_button        = document.getElementById( "inpost_intl_show_geowidget" );
									if ( typeof map_button != 'undefined' && map_button !== null) {
										if ( typeof map_config_settings != 'undefined' && map_config_settings !== null) {
											//console.log("Exact SM map_config_settings:");
											//console.log(map_config_settings);
											if ( 'need_map' in map_config_settings ) {
												console.log('need_map');
												if (button_texts.hasOwnProperty(selected_country)) {
													button_text = button_texts[selected_country];
												}
												$(map_button).text(button_text);
												$(map_button).css('display', 'block');
												$('#inpost_intl_selected_point_data').show();

											} else {
												$( map_button ).css( 'display', 'none' );
												$( '#inpost_intl_selected_point_data' ).hide();
												console.log( 'hide btn, clear data' );
											}

										} else {
											$( map_button ).css( 'display', 'none' );
											$( '#inpost_intl_selected_point_data' ).hide();
											console.log( 'hide btn, clear data' );
										}
									}
								}
							}

						}
					}

					if ( target.classList.contains( 'shipping_method' ) ) {
						const parent = document.getElementById( "shipping_method" );
						if (parent && parent.contains( target )) {
							console.log( "Change shipping method input" );
						}
					}
				}
			);

			window.addEventListener(
				'message',
				function (event) {
					let parsedData;
					try {
						if (typeof event.data === 'string') {
							parsedData = JSON.parse( event.data );
						} else {
							parsedData = event.data;
						}

						if (
							parsedData.message.payload &&
							parsedData.message.payload.event === "shippingratechange" &&
							parsedData.message.payload.data &&
							parsedData.message.payload.data.shippingRate &&
							parsedData.message.payload.data.shippingRate.id
						) {
							let chosen_shipping_method = parsedData.message.payload.data.shippingRate.id;

							// console.log( 'Chosen_shipping_method:' );
							// console.log( chosen_shipping_method );

							if ( chosen_shipping_method.indexOf( 'inpost_international_automated_locker_point' ) !== -1 ) {
								let checked_shipping_input = document.querySelector( '#shipping_method input[name^="shipping_method["]:checked' );
								if (checked_shipping_input !== undefined && checked_shipping_input !== null) {
									let id = checked_shipping_input.value;
									console.log( 'Shipping method ID:', id );

									if (id.indexOf( 'inpost_international_automated_locker_point' ) !== -1) {
										if ( ! inpost_international_frontend.inpost_intl_validate_locker_for_gpay() ) {
											alert( 'InPost International:' + "\n\n" + ' Please select locker point before, then return to payment.' );
											return false;
										}
									}
								}
							}
						}

						if (
							parsedData.type === "parent" &&
							parsedData.message &&
							parsedData.message.action === "stripe-frame-event" &&
							parsedData.message.payload &&
							parsedData.message.payload.event === "click" &&
							parsedData.message.payload.data
						) {

							if (
								"google_pay" === parsedData.message.payload.data.paymentMethodType
								|| "apple_pay" === parsedData.message.payload.data.paymentMethodType
								|| "apple_pay_inner" === parsedData.message.payload.data.paymentMethodType
							) {
								// console.log('Google Pay or Apple Pay button click detected');
								if ( ! inpost_international_frontend.inpost_intl_validate_locker_for_gpay() ) {
									alert( 'InPost International:' + "\n\n" + ' Please select locker point before, then return to payment.' );
									return false;
								}
							}

						}
					} catch (err) {
						// console.log('Error processing message:', err);
					}
				}
			);
		}
	);

})( jQuery );
