(function ($) {

	const PocztaKurier48                         = 160;
	const PocztaKurier48Punkty                   = 162;
	const PocztexPunktDrzwi                      = 65;
	const PocztexPunktPunkt                      = 66;
	const AllegroSMARTKurier48Punkty             = 164;
	const AllegroSMARTPocztaKurier48             = 165;
	const AllegroSMARTPaczkomatInPost            = 40;
	const PaczkomatInPost                        = 41;
	const PaczkomatInPostInternational           = 43;
	const PaczkomatInPostInternationalDrzwiPunkt = 45;
	const PaczkomatInPostInternationalFR         = 46;
	const UPSAPPunktDrzwi                        = 13;
	const UPSAPPunktDrzwiFR                      = 16;
	const UPSAPPunktPunkt                        = 14;
	const DPD_kurier                             = 21;
	const AllegroSMARTPocztex                    = 67;
	const AllegroSMARTPocztexPunkty              = 68;
	const InPostPaczkomatDrzwi                   = 43;
	const PocztexDrzwiPunkt                      = 64;
	const AllegroSMARTDPDPickup                  = 20;
	const DPDCourierEurope                       = 22;
	const DPDPickupEurope                        = 29;
	const FedexInternationalEconomy              = 153;
	const UPSstandard                            = 5;
	const UPSexpressSaver                        = 6;
	const DPDPickupPunktPunkt = 26;
    const DPDPickupPunktDzrwi = 30;
    const PacketaPunktDrzwi = 313;
    const PacketaPunktPunkt = 314;

	// Shared counter for dynamically added parcel wrappers.
	// Must be outside document.ready because some helpers use it on load.
	let parcelCounter = 0;


	const EcoletFANCourierStandard          = 1;
	const EcoletStandardDPD                 = 42;
	const EcoletCargusStandard              = 4;
	const EcoletFANMarfaCourier             = 70;
	const EcoletInternationalImportZoneDPD1 = 71;
	const EcoletInternationalImportZoneDPD2 = 72;
	const EcoletInternationalImportZoneDPD3 = 73;
	const EcoletFANboxCourierAutomatul      = 59;
	const EcoletFANboxAutomatulAutomatul    = 60;
	const EcoletFANnboxAutomatulCourier     = 61;
	const EcoletBucuresti24                 = 53;
	const EcoletSamedayCourierAutomatul     = 41;
	const EcoletSamedayAutomatulAutomatul   = 63;
	const EcoletNextday                     = 8;
	const EcoletMetropolitan                = 55;
	const EcoletExpressRegionalDPD          = 57;
	const EcoletStandardGLS                 = 5;
	const EcoletExpressRegionalDPDCzechia   = 56;
	const EcoletExpressRegionalDPDBulgaria  = 12;
	const EcoletExpressRegionalDPDHungary   = 13;
	const EcoletExpressRegionalDPDGreece    = 14;
	const EcoletClassicInternationalDPD1    = 16;
	const EcoletClassicInternationalDPD2    = 17;
	const EcoletClassicInternationalDPD3    = 19;
	const EcoletDPDAutomatulCourier         = 44;
	const EcoletDPDCourierAutomatul         = 45;
	const EcoletOfficePointToPointDPD       = 46;
	const EcoletOfficePointToCourierDPD     = 47;
	const EcoletOfficeCourierToPointDPD     = 48;
	const EcoletEasyCollectLockerXLCargus   = 84;
	const EcoletEasyCollectCargus           = 49;
	const EcoletInternationalGLS1           = 64;
	const EcoletInternationalGLS2           = 65;
	const EcoletInternationalGLS3           = 66;
	const EcoletInternationalGLS4           = 67;
	const EcoletInternationalGLS5           = 68;
	const EcoletGLSCourierAutomatul         = 74;
	const EcoletGLSAutomatulAutomatul       = 75;
	const EcoletGLSAutomatulCourier         = 76;
	const EcoletStandardUPS1                = 86;
	const EcoletStandardUPS4                = 89;
	const EcoletStandardUPS2                = 87;
	const EcoletStandardUPS3                = 88;
	const EcoletExpressUPS1                 = 91;
	const EcoletExpressUPS2                 = 92;
	const EcoletExpressUPS3                 = 93;
	const EcoletExpressUPS4                 = 94;
	const EcoletImportStandardUPS2          = 99;
	const EcoletImportStandardUPS1          = 100;
	const EcoletImportStandardUPS3          = 101;
	const EcoletImportStandardUPS4          = 102;
	const EcoletImportExpressUPS1           = 103;
	const EcoletImportExpressUPS2           = 104;
	const EcoletImportExpressUPS3           = 105;
	const EcoletImportExpressUPS4           = 106;
	const EcoletImportStandardMultipackUPS1 = 107;
	const EcoletImportStandardMultipackUPS2 = 108;
	const EcoletImportStandardMultipackUPS3 = 109;
	const EcoletImportStandardMultipackUPS4 = 110;
	const EcoletStandardMultipackUPS1       = 95;
	const EcoletStandardMultipackUPS2       = 96;
	const EcoletStandardMultipackUPS3       = 97;
	const EcoletStandardMultipackUPS4       = 98;
	const EcoletWorldwideDHL1               = 78;
	const EcoletWorldwideDHL2               = 79;
	const EcoletWorldwideDHL3               = 80;
	const EcoletEasyCollectLockerSCargus    = 81;
	const EcoletEasyCollectLockerMCargus    = 82;
	const EcoletEasyCollectLockerLCargus    = 83;
	const EcoletStadard30PlusCargus         = 85;
	const EcoletPostaRomanaStandard         = 90;

	let apaczka_dispath_point_handler_to_validate = false;

	function getNextBusinessDay(date) {
		const result = new Date( date );
		result.setDate( result.getDate() + 1 );

		// Keep adding days until we get a business day (Mon-Fri).
		while (result.getDay() === 0 || result.getDay() === 6) {
			result.setDate( result.getDate() + 1 );
		}

		return result;
	}

	function alsendo_connect_add_border_to_selected_service() {
		const elements = document.querySelectorAll( "#apaczka_calculate_radio > .apaczka-calculate-item > .apaczka-calculate-item-price-wrapper > input[type='radio']" );
		if (elements) {
			elements.forEach(
				function (element) {
					if (element.checked) {
						is_any_element_checked = true;
						element.closest( ".apaczka-calculate-item" ).classList.toggle( "selected" );
						element.setAttribute( "checked", "checked" );
					}
					let radioInputs = document.querySelectorAll( "#apaczka_calculate_radio > .apaczka-calculate-item > .apaczka-calculate-item-price-wrapper > input[type='radio']" );
					radioInputs.forEach(
						function (radioElement) {
							if (radioElement.checked === false) {
								radioElement.closest( ".apaczka-calculate-item" ).classList.remove( "selected" );
								radioElement.removeAttribute( "checked" );
							}
						}
					);
				}
			);

		}
	}

	function formatJSON(obj, indent = 0) {
		const indentStr = '  '.repeat( indent );
		let output      = '';

		if (Array.isArray( obj )) {
			output += 'array:' + obj.length + ' [▼\n';
			obj.forEach(
				function (item, index) {
					output += indentStr + '  ' + index + ' => ' + formatJSON( item, indent + 1 ) + '\n';
				}
			);
			output += indentStr + ']';
		} else if (typeof obj === 'object' && obj !== null) {
			output += 'array:' + Object.keys( obj ).length + ' [▼\n';
			Object.entries( obj ).forEach(
				function (entry) {
					let key   = entry[0];
					let value = entry[1];
					output   += indentStr + '  "' + key + '" => ' + formatJSON( value, indent + 1 ) + '\n';
				}
			);
			output += indentStr + ']';
		} else {
			output += JSON.stringify( obj );
		}

		return output;
	}

	function alsendo_process_api_response(object) {
		let api_response = '';
		if (typeof object === 'string') {
			api_response = object;
		} else if (Array.isArray( object )) {
			let errorsString = '\n\n';
			object.forEach(
				function (errorObj) {
					if (errorObj.field && errorObj.message) {
						errorsString += errorObj.field + ' => ' + errorObj.message + '\n';
					}
				}
			);
			api_response += errorsString;
		} else {
			if (object.status_code) {
				api_response += 'API response code: ' + object.status_code + '\n\n';
			}
			if (object.message) {
				api_response += object.message + '\n\n';
			}
			// Handle errors, whether they're in object.errors or directly in the object.
			let errors = object.errors || object;
			if (typeof errors === 'object' && ! Array.isArray( errors )) {
				let errorsString = '\n\n';
				// Iterate through each error.
				for (let key in errors) {
					if (Object.prototype.hasOwnProperty.call( errors, key )) {
						let errorValue = errors[key];
						if (Array.isArray( errorValue )) {
							errorValue.forEach(
								function (error) {
									errorsString += key + ' => ' + error + '\n';
								}
							);
						} else if (typeof errorValue === 'string') {
							errorsString += key + ' => ' + errorValue + '\n';
						}
					}
				}
				api_response += errorsString;
			}
		}

		api_response = api_response.trim();
		return api_response;
	}

	function changeShippingMethodTriggers(method) {

		if ('SELF' === method) {
			$( "label[data-pickup_courier='2']" ).remove();
			$( "label[data-pickup_courier='0']" ).show();
			$( "label[data-pickup_courier='1']" ).show();
			$( "label[data-service_id='41']" ).remove();
			$( "label[data-service_id='14']" ).remove();
			$( "label[data-service_id='13']" ).remove();
			$( "label[data-service_id='50']" ).remove();
			$( "label[data-service_id='26']" ).remove();
			$( "label[data-service_id='43']" ).remove();
			$( "label[data-service_id='162']" ).remove();
			$( "label[data-service_id='160']" ).remove();
			$( "label[data-service_id='165']" ).remove();
			$( "label[data-service_id='40']" ).remove();
			$( "label[data-service_id='164']" ).remove();
			$( "label[data-service_id='66']" ).remove();
			$( "label[data-service_id='65']" ).remove();

		} else {
			$( "label[data-service_id='65']" ).show();
			$( "label[data-service_id='66']" ).show();
			$( "label[data-service_id='164']" ).show();
			$( "label[data-service_id='40']" ).show();
			$( "label[data-service_id='165']" ).show();
			$( "label[data-service_id='160']" ).show();
			$( "label[data-service_id='162']" ).show();
			$( "label[data-service_id='43']" ).show();
			$( "label[data-service_id='26']" ).show();
			$( "label[data-service_id='50']" ).show();
			$( "label[data-service_id='41']" ).show();
			$( "label[data-service_id='14']" ).show();
			$( "label[data-service_id='13']" ).show();
			$( "label[data-pickup_courier='2']" ).show();
			$( "label[data-pickup_courier='0']" ).show();
			$( "label[data-pickup_courier='1']" ).show();
		}

		apaczka_check_shipping_methods();

	}


	function apaczka_check_shipping_methods() {
		var $wrapper = $('#apaczka-calculate-wrapper');
		var $fieldset = $('#apaczka_calculate_radio');

		// Check if there are any .apaczka-calculate-item elements.
		var hasItems = $fieldset.find('.apaczka-calculate-item').length > 0;

		// Remove any existing message first.
		$wrapper.find('.apaczka-no-methods-message').remove();

		if (!hasItems) {
			// No shipping methods found - show message.
			var message = '<div class="apaczka-no-methods-message" style="padding: 15px; background-color: #fff3cd; border: 1px solid #ffc107; border-radius: 4px; color: #856404; margin: 10px 0; text-align: center;">' +
				'<strong>⚠ No available methods found for such shipping method</strong>' +
				'</div>';

			$fieldset.after(message);
		}
	}

	function createOperator(operatorId, operatorName) {
		operatorName = operatorName.toUpperCase();
		return {
			operator: operatorName,
			price: null
		};
	}

	function fillSenderFormByTemplate(templateSlug) {
		console.log( 'templateSlug' );
		console.log( templateSlug );
		let apaczka_sender_templates = alsendo_order_metabox.sender_templates;
		for (const [key, value] of Object.entries( apaczka_sender_templates )) {
			if (key === templateSlug) {
				for (const [key2, value2] of Object.entries( value.options )) {
					key2_new = key2.replace( "alsendo_connect_settings_general_sender_", "" );
					$( '#' + '_apaczka\\[sender\\]\\[' + key2_new + '\\]' ).val( value2 )
				}
			}
		}
	}

	function fillPackagePropertiesFormByTemplate(templateSlug) {

		let apaczka_package_properties_templates = alsendo_order_metabox.package_properties_templates;

		let package_contents_disabled = true;
		let maybe_custom_package_contents = false;
		let custom_package_contents_value = '';
		let package_contents_value = '';
		let package_contents_tag = '';

        let declare_content_as_order = alsendo_order_metabox.declare_content_as_order;
		console.log('declare_content_as_order : ' + declare_content_as_order);


		for (const [key, value] of Object.entries( apaczka_package_properties_templates )) {
			if (key === templateSlug) {
				for (const [key2, value2] of Object.entries( value.options )) {
					key2_new = key2.replace( "alsendo_connect_settings_general_", "" );
					
					if ('declared_content' === key2_new) {
						if( declare_content_as_order ) {
							continue;
						}
					}

					if( 'custom_text_content' === key2_new ) {
						custom_package_contents_value = value2;
					}
					if( 'package_contents' === key2_new ) {
						package_contents_tag = value2;
						if( 'custom_text' === value2 ) {
							maybe_custom_package_contents = true;
							package_contents_disabled = false;
						}
						if( 'order_id' === value2 ) {
							package_contents_value = alsendo_order_metabox.text_contents_order_id;
						}
						if( 'product_id' === value2 ) {
							package_contents_value = alsendo_order_metabox.text_contents_product_id;
						}
						if( 'product_name' === value2 ) {
							package_contents_value = alsendo_order_metabox.text_contents_product_name;
						}
					}

					$( '#' + '_apaczka\\[package_properties\\]\\[' + key2_new + '\\]' ).val( value2 )
				}
			}
		}

		if( maybe_custom_package_contents ) {
			$( '#' + '_apaczka\\[package_properties\\]\\[package_contents\\]' ).val( custom_package_contents_value );
		} else {
			$( '#' + '_apaczka\\[package_properties\\]\\[package_contents\\]' ).val( package_contents_value );
		}

		if( package_contents_disabled ) {
			$( '#' + '_apaczka\\[package_properties\\]\\[package_contents\\]' ).prop( 'disabled', true );
			let hidden_input_tag_content = '<input type="hidden" name="_apaczka[package_properties][package_contents_tag]" id="_apaczka[package_properties][package_contents_tag]" value="' + package_contents_tag + '">';
			$( '#' + '_apaczka\\[package_properties\\]\\[package_contents\\]' ).append( hidden_input_tag_content );
		} else {
			$( '#' + '_apaczka\\[package_properties\\]\\[package_contents_tag\\]' ).each(
				function (ind, elem) {
					$( elem ).remove();
				}
			);

			$( '#' + '_apaczka\\[package_properties\\]\\[package_contents\\]' ).prop( 'disabled', false );
		}

		$( '#_apaczka\\[package_properties\\]\\[parcel_type\\]' ).trigger( 'change' );

	}

	function fillPackagePropertiesFormByTemplateInWrapper( templateSlug, wrapper, parcelIndex ) {
		if ( ! templateSlug ) {
			return;
		}

		let apaczka_package_properties_templates = alsendo_order_metabox.package_properties_templates;

		let package_contents_disabled     = true;
		let maybe_custom_package_contents = false;
		let custom_package_contents_value = '';
		let package_contents_value        = '';
		let package_contents_tag          = '';

		for ( const [key, value] of Object.entries( apaczka_package_properties_templates ) ) {
			if ( key === templateSlug ) {
				for ( const [key2, value2] of Object.entries( value.options ) ) {
					let key2_new = key2.replace( "alsendo_connect_settings_general_", "" );

					if ( 'custom_text_content' === key2_new ) {
						custom_package_contents_value = value2;
					}
					if ( 'package_contents' === key2_new ) {
						package_contents_tag = value2;
						if ( 'custom_text' === value2 ) {
							maybe_custom_package_contents = true;
							package_contents_disabled     = false;
						}
						if ( 'order_id' === value2 ) {
							package_contents_value = alsendo_order_metabox.text_contents_order_id;
						}
						if ( 'product_id' === value2 ) {
							package_contents_value = alsendo_order_metabox.text_contents_product_id;
						}
						if ( 'product_name' === value2 ) {
							package_contents_value = alsendo_order_metabox.text_contents_product_name;
						}
					}

					// Update only fields inside this wrapper.
					const fieldHandle = wrapper.find( '[data-key="' + key2_new + '"]' );
					if ( fieldHandle.length ) {
						fieldHandle.val( value2 );
					}
				}
			}
		}

		// Handle package_contents special rules (value + disabled state + hidden tag).
		const contentsInput = wrapper.find( '[data-key="package_contents"]' );
		if ( contentsInput.length ) {
			const contentsTagName = '_apaczka[package_properties][' + parcelIndex + '][package_contents_tag]';
			wrapper.find( 'input[name="' + contentsTagName + '"]' ).remove();

			if ( maybe_custom_package_contents ) {
				contentsInput.val( custom_package_contents_value );
			} else {
				contentsInput.val( package_contents_value );
			}

			if ( package_contents_disabled ) {
				contentsInput.prop( 'disabled', true );
				const hiddenTag = $( '<input>', { type: 'hidden', name: contentsTagName, value: package_contents_tag } );
				contentsInput.after( hiddenTag );
			} else {
				contentsInput.prop( 'disabled', false );
			}
		}
	}

	function alsendoAddApaczkaAdditionalParcel( parcelData ) {
		if ( parcelCounter >= 9 ) {
			return false;
		}

		parcelCounter++;
		const wrapId = 'parcel_wrap_' + parcelCounter;
		const apaczka_default_parcel = $( '.apaczka-cloned-fields-wrapper.default-wrapper' );

		if ( typeof apaczka_default_parcel === 'undefined' || apaczka_default_parcel.length === 0 ) {
			return false;
		}

		const fieldsToClone = [
			'._apaczka\\[package_properties\\]\\[parcel_type\\]_field',
			'._apaczka\\[package_properties\\]\\[is_nstd\\]_field',
			'._apaczka\\[package_properties\\]\\[package_length\\]_field',
			'._apaczka\\[package_properties\\]\\[package_width\\]_field',
			'._apaczka\\[package_properties\\]\\[package_height\\]_field',
			'._apaczka\\[package_properties\\]\\[package_weight\\]_field'
		];

		const class_name = 'apaczka-additional-parcel_' + parcelCounter;
		const wrapper = $( '<div>', { 'class': 'apaczka-cloned-fields-wrapper', 'data-wrap-id': wrapId } )
			.append(
				$( '<span>', { 'class': class_name + ' apaczka-additional-parcel-title', 'text': alsendo_order_metabox.text_additional_parcel + ' #' + parcelCounter } )
			);

		// Parcel-level template select.
		if ( alsendo_order_metabox.package_properties_templates
			&& Object.keys( alsendo_order_metabox.package_properties_templates ).length > 0
			&& $( '#_apaczka\\[package_properties\\]\\[selected_template\\]' ).length
		) {
			const mainTemplateSelect = $( '#_apaczka\\[package_properties\\]\\[selected_template\\]' );
			const mainSelectedTemplateSlug = mainTemplateSelect.val();

			const selectId   = 'apaczka_additional_package_template_' + parcelCounter;
			const selectName = '_apaczka[package_properties][' + parcelCounter + '][selected_template]';

			const templateSelect = mainTemplateSelect.clone();
			templateSelect
				.attr( 'id', selectId )
				.attr( 'name', selectName )
				.attr( 'data-key', 'selected_template_additional' )
				.addClass( 'apaczka-additional-package-template-select' )
				.data( 'parcel-index', parcelCounter )
				.val( mainSelectedTemplateSlug );

			const templateField = $( '<p>', { 'class': 'form-field apaczka-additional-package-template-field' } )
				.append( $( '<label>', { 'for': selectId, 'text': alsendo_order_metabox.text_choose_shipment_template || 'Choose shipment template' } ) )
				.append( templateSelect );

			wrapper.append( templateField );
		}

		fieldsToClone.forEach(
			function (fieldSelector) {
				const originalField = apaczka_default_parcel.find( fieldSelector );
				if ( originalField.length > 0 ) {
					const clonedField = originalField.clone();

					clonedField.find( 'input, select' ).each(
						function () {
							const originalId   = $( this ).attr( 'id' );
							const originalName = $( this ).attr( 'name' );

							if ( originalId ) {
								$( this ).attr( 'id', originalId + '_' + parcelCounter );
							}
							if ( originalName ) {
								const newName = originalName.replace(
									/_apaczka\[package_properties\]/,
									'_apaczka[package_properties][' + parcelCounter + ']'
								);
								$( this ).attr( 'name', newName );
							}
						}
					);

					clonedField.find( 'label' ).each(
						function () {
							const originalFor = $( this ).attr( 'for' );
							if ( originalFor ) {
								$( this ).attr( 'for', originalFor + '_' + parcelCounter );
							}
						}
					);

					wrapper.append( clonedField );
				}
			}
		);

		const removeButton = $( '<button>', { 'class': 'apaczka_remove_parcel button-secondary', 'data-wrap-id': wrapId, 'text': alsendo_order_metabox.text_remove_parcel } );
		wrapper.append( removeButton );
		$( '.apaczka_add_parcel_field' ).before( wrapper );

		// Prefill values (per-parcel overrides from template).
		if ( parcelData && typeof parcelData === 'object' ) {
			const keys = ['parcel_type', 'is_nstd', 'package_length', 'package_width', 'package_height', 'package_weight'];
			keys.forEach(
				function (k) {
					if ( typeof parcelData[k] !== 'undefined' && parcelData[k] !== null && parcelData[k] !== '' ) {
						wrapper.find( '[data-key="' + k + '"]' ).val( parcelData[k] );
					}
				}
			);
		}

		// Apply any dependent UI updates.
		wrapper.find( '[data-key="parcel_type"]' ).trigger( 'change' );
		wrapper.find( '[data-key="is_nstd"]' ).trigger( 'change' );

		return true;
	}

	function alsendoClearApaczkaAdditionalParcels() {
		// Remove all additional parcel wrappers (keep the default wrapper with parcel_wrap_0).
		$( '.apaczka-cloned-fields-wrapper' ).not( '.default-wrapper' ).remove();
		parcelCounter = 0;
	}

	function serviceIdToApmSupplierId(serviceId) {

		switch (serviceId) {
			case 14:
			case 15:
			case 16:
				return 'UPS';
			case 20:
			case 23:
			case 26:
			case 29:
				return 'DPD';
			case 50:
			case 53:
				return 'RUCH';
			case 203:
			case 206:
				return 'GLS';
			case 40:
			case 41:
			case 45:
			case 46:
				return 'INPOST';
			case 64:
			case 66:
			case 68:
			case 162:
			case 163:
				return 'POCZTA';
			case 314:
			case 317:
				return 'PACKETA';
			case 86:
				return 'DHL';
			default:
				return null
		}

	}



	function is_cod_amount_defined() {
		return parseInt( $( '#_apaczka\\[additional_options\\]\\[cod_amount\\]' ).val() ) > 0
	}

	function alsendo_debug_print_r(obj) {
		function inpost_intl_format_value(value) {
			if (typeof value === 'string') {
				return '"' + value + '"';
			}
			if (Array.isArray( value )) {
				return 'Array\n' + alsendo_debug_format_object( value );
			}
			if (typeof value === 'object' && value !== null) {
				return alsendo_debug_format_object( value );
			}
			return value;
		}

		function alsendo_debug_format_object(obj) {
			let result = '(\n';
			for (let key in obj) {
				if (obj.hasOwnProperty( key )) {
					result += '    [' + key + '] => ' + inpost_intl_format_value( obj[key] ) + '\n';
				}
			}
			result += ')';
			return result;
		}

		return alsendo_debug_format_object( obj );
	}

	function alsendo_process_api_response(object) {
		let api_response = '';
		const standardLength = "We\u2019re sorry, you can\u2019t place and order for such a late hour.".length;

		// Helper function to add line breaks after dots followed by uppercase letters
		function formatLongString(str) {
			if (str.length <= standardLength) {
				return str;
			}
			// Replace "." followed by uppercase letter (with or without space) with ".<br>"
			return str.replace(/\.\s*(?=[A-Z])/g, '.<br>');
		}

		// Check if object is a string.
		if (typeof object === 'string') {
			api_response = formatLongString(object);
		} else if (Array.isArray(object)) {
			let errorsString = '\n\n';
			object.forEach(
				function (errorObj) {
					if (errorObj.field && errorObj.message) {
						let formattedMessage = formatLongString(errorObj.message);
						errorsString += errorObj.field + ' => ' + formattedMessage + '\n';
					}
				}
			);
			api_response += errorsString;
		} else {
			if (object.status_code) {
				api_response += 'API response code: ' + object.status_code + '\n\n';
			}
			if (object.message) {
				let formattedMessage = formatLongString(object.message);
				api_response += formattedMessage + '\n\n';
			}
			// Handle errors, whether they're in object.errors or directly in the object.
			let errors = object.errors || object;
			if (typeof errors === 'object' && !Array.isArray(errors)) {
				let errorsString = '\n\n';
				// Iterate through each error.
				for (let key in errors) {
					if (Object.prototype.hasOwnProperty.call(errors, key)) {
						let errorValue = errors[key];
						if (Array.isArray(errorValue)) {
							errorValue.forEach(
								function (error) {
									let formattedError = formatLongString(error);
									errorsString += key + ' => ' + formattedError + '\n';
								}
							);
						} else if (typeof errorValue === 'string') {
							let formattedError = formatLongString(errorValue);
							errorsString += key + ' => ' + formattedError + '\n';
						}
					}
				}
				api_response += errorsString;
			}
		}

		api_response = api_response.trim();
		return api_response;
	}

	/**
	 * /**
	 *  * UPS Access Point (service id: 14,15, 16)
	 * DPD Pickup (service id: 23, 26)
	 * ORLEN Paczka  (service id: 50)
	 * Paczkomaty InPost  (service id: 41)
	 * Poczta Polska Ekspres24 Punkty  (service id: 163)
	 * DHL POP  (service id: 86)
	 * Poczta Polska Kurier48 Punkty  (service id: 162)
	 * DHL_PARCEL
	 * DPD
	 * INPOST
	 * POCZTA
	 * UPS
	 */
	function handleCalculateDynamicFields(selectedService) {

		console.log( 'handleCalculateDynamicFields: selectedService' );
		console.log( selectedService );

		$( '#_apaczka\\[sender\\]\\[apm_foreign_access_point_id\\]' ).val( '' );
		console.log( 'Alsendo Apaczka: reset hidden sender foreign_access_point_id value' );

		let method = null;
		let shipping_method = $( '#_apaczka\\[package_properties\\]\\[shipping_method\\]' ).val();
		let debug           = serviceIdToApmSupplierId( selectedService );
		console.log( 'serviceIdToApmSupplierId' );
		console.log( debug );

		if (serviceIdToApmSupplierId( selectedService ) !== null) {
			$( '#apaczka_delivery_point_id_wrapper' ).removeClass( 'apaczka-hidden' );
		} else {
			$( '#apaczka_delivery_point_id_wrapper' ).addClass( 'apaczka-hidden' );
		}

		
		if (selectedService === AllegroSMARTPaczkomatInPost
			|| selectedService === PaczkomatInPost
			|| selectedService === InPostPaczkomatDrzwi
			|| selectedService === PaczkomatInPostInternational
			|| selectedService === PaczkomatInPostInternationalFR
			|| selectedService === PaczkomatInPostInternationalDrzwiPunkt

		) {
			method = 'inpost';
		}

		if ((selectedService === PocztaKurier48
			|| selectedService === PocztaKurier48Punkty
			|| selectedService === AllegroSMARTKurier48Punkty
			|| selectedService === AllegroSMARTPocztaKurier48
			|| selectedService === PocztexPunktDrzwi
			|| selectedService === PocztexPunktPunkt
			|| selectedService === AllegroSMARTPocztex
			|| selectedService === AllegroSMARTPocztexPunkty
			|| selectedService === PacketaPunktDrzwi
			|| selectedService === PacketaPunktPunkt
		)
		) {
			method = 'kurier48';

		}

		if (selectedService === AllegroSMARTPaczkomatInPost
			|| selectedService === PaczkomatInPost
			|| selectedService === InPostPaczkomatDrzwi
			|| selectedService === PaczkomatInPostInternational
			|| selectedService === PaczkomatInPostInternationalFR
			|| selectedService === PaczkomatInPostInternationalDrzwiPunkt

		) {
			method = 'inpost';
		}

		if (selectedService === UPSAPPunktPunkt
			|| selectedService === UPSAPPunktDrzwi
		) {
			method = 'ups';

		}

		if (selectedService === AllegroSMARTDPDPickup
			|| selectedService === DPDPickupPunktPunkt
                || selectedService === DPDPickupPunktDzrwi
		) {
			method = 'dpd';

		}

		/*if ( selectedService === FedexInternationalEconomy
		) {
			method = 'fedex';
		}*/

		if ('POINT' === shipping_method) {
			if (selectedService === DPD_kurier) {
				method = 'dpd';

			}
		}


		console.log( 'Alsendo connect - selectedService: ' + selectedService );
		console.log( 'selected_method: ' + method );
		console.log( 'handleCalculateDynamicFields: shipping_method ' + shipping_method );

		if ('kurier48' === method) {
			$( '#dispath_point_kurier48_wrapper' ).removeClass( 'apaczka-hidden' );
			$( '#dispath_point_ups_wrapper' ).addClass( 'apaczka-hidden' );
			$( '#dispath_point_dpd_wrapper' ).addClass( 'apaczka-hidden' );
			$( '#dispath_point_inpost_wrapper' ).addClass( 'apaczka-hidden' );

			$( '#_apaczka\\[sender\\]\\[apm_foreign_access_point_id\\]' ).val( $( '#_apaczka\\[package_properties\\]\\[dispath_point_kurier48\\]' ).val() );
			apaczka_dispath_point_handler_to_validate = $( '#_apaczka\\[package_properties\\]\\[dispath_point_kurier48\\]' );

		}

		if ('inpost' === method) {
			$( '#dispath_point_kurier48_wrapper' ).addClass( 'apaczka-hidden' );
			$( '#dispath_point_ups_wrapper' ).addClass( 'apaczka-hidden' );
			$( '#dispath_point_dpd_wrapper' ).addClass( 'apaczka-hidden' );
			$( '#dispath_point_inpost_wrapper' ).removeClass( 'apaczka-hidden' );

			$( '#_apaczka\\[sender\\]\\[apm_foreign_access_point_id\\]' ).val( $( '#_apaczka\\[package_properties\\]\\[dispath_point_inpost\\]' ).val() );
			apaczka_dispath_point_handler_to_validate = $( '#_apaczka\\[package_properties\\]\\[dispath_point_inpost\\]' );

			if ('COURIER' === shipping_method) {
				$( '#dispath_point_inpost_wrapper' ).addClass( 'apaczka-hidden' );
				apaczka_dispath_point_handler_to_validate = false;
			} else {
				$( '#dispath_point_inpost_wrapper' ).removeClass( 'apaczka-hidden' );
				apaczka_dispath_point_handler_to_validate = $( '#_apaczka\\[package_properties\\]\\[dispath_point_inpost\\]' );
			}
		}

		if ('ups' === method) {
			$( '#dispath_point_kurier48_wrapper' ).addClass( 'apaczka-hidden' );
			$( '#dispath_point_ups_wrapper' ).removeClass( 'apaczka-hidden' );
			$( '#dispath_point_inpost_wrapper' ).addClass( 'apaczka-hidden' );
			$( '#dispath_point_dpd_wrapper' ).addClass( 'apaczka-hidden' );

			$( '#_apaczka\\[sender\\]\\[apm_foreign_access_point_id\\]' ).val( $( '#_apaczka\\[package_properties\\]\\[dispath_point_ups\\]' ).val() )
			apaczka_dispath_point_handler_to_validate = $( '#_apaczka\\[package_properties\\]\\[dispath_point_ups\\]' );

		}

		if ('dpd' === method) {
			$( '#dispath_point_kurier48_wrapper' ).addClass( 'apaczka-hidden' );
			$( '#dispath_point_ups_wrapper' ).addClass( 'apaczka-hidden' );
			$( '#dispath_point_inpost_wrapper' ).addClass( 'apaczka-hidden' );
			$( '#dispath_point_dpd_wrapper' ).removeClass( 'apaczka-hidden' );

			$( '#_apaczka\\[sender\\]\\[apm_foreign_access_point_id\\]' ).val( $( '#_apaczka_dispath_point_dpd' ).val() );
			apaczka_dispath_point_handler_to_validate = $( '#_apaczka_dispath_point_dpd' );

		} else {
			$( '#dispath_point_dpd_wrapper' ).addClass( 'apaczka-hidden' );
		}

		if (null === method) {
			$( '#dispath_point_kurier48_wrapper' ).addClass( 'apaczka-hidden' );
			$( '#dispath_point_ups_wrapper' ).addClass( 'apaczka-hidden' );
			$( '#dispath_point_inpost_wrapper' ).addClass( 'apaczka-hidden' );
			apaczka_dispath_point_handler_to_validate = false;
		}

		if( 90 === selectedService || 310 === selectedService || 311 === selectedService || 316 === selectedService || 317 === selectedService ) {

			var warehouseMessages = {
				310: {
					content: '<div style="margin-bottom:15px;"><strong style="font-size:15px;">Klient zobowiązany jest do dostarczenia przesyłki na adres magazynu:</strong></div>' +
						'<div style="background:#fff;padding:15px;border-radius:4px;margin-bottom:10px;">' +
						'<div style="font-weight:bold;font-size:15px;margin-bottom:8px;color:#1f2937;">Crossborder Logistic</div>' +
						'<div style="color:#4b5563;">Generała Józefa Sowińskiego 42A</div>' +
						'<div style="color:#4b5563;">PL 65-419 Zielona Góra</div>' +
						'</div>' +
						'<div style="background:#fff;padding:15px;border-radius:4px;">' +
						'<div style="font-weight:bold;margin-bottom:8px;color:#1f2937;">Dane kontaktowe:</div>' +
						'<div style="color:#4b5563;">📧 Email: <a href="mailto:ops@cblog.pl" style="color:#ef4444;text-decoration:none;">ops@cblog.pl</a></div>' +
						'<div style="color:#4b5563;">📞 Tel.: <a href="tel:+48223803070" style="color:#ef4444;text-decoration:none;">22 380 30 70</a></div>' +
						'</div>'
				},
				311: {
					content: '<div style="margin-bottom:15px;"><strong style="font-size:15px;">Klient zobowiązany jest do dostarczenia przesyłki na adres magazynu:</strong></div>' +
						'<div style="background:#fff;padding:15px;border-radius:4px;margin-bottom:10px;">' +
						'<div style="font-weight:bold;font-size:15px;margin-bottom:8px;color:#1f2937;">Crossborder Logistic</div>' +
						'<div style="color:#4b5563;">Generała Józefa Sowińskiego 42A</div>' +
						'<div style="color:#4b5563;">PL 65-419 Zielona Góra</div>' +
						'</div>' +
						'<div style="background:#fff;padding:15px;border-radius:4px;">' +
						'<div style="font-weight:bold;margin-bottom:8px;color:#1f2937;">Dane kontaktowe:</div>' +
						'<div style="color:#4b5563;">📧 Email: <a href="mailto:ops@cblog.pl" style="color:#ef4444;text-decoration:none;">ops@cblog.pl</a></div>' +
						'<div style="color:#4b5563;">📞 Tel.: <a href="tel:+48223803070" style="color:#ef4444;text-decoration:none;">22 380 30 70</a></div>' +
						'</div>'
				},
				316: {
					content: '<div style="margin-bottom:15px;"><strong style="font-size:15px;">Klient zobowiązany jest do dostarczenia przesyłki na adres magazynu:</strong></div>' +
						'<div style="background:#fff;padding:15px;border-radius:4px;margin-bottom:10px;">' +
						'<div style="font-weight:bold;font-size:15px;margin-bottom:8px;color:#1f2937;">Packeta</div>' +
						'<div style="color:#4b5563;">Księdza Józefa Londzina 106</div>' +
						'<div style="color:#4b5563;">43-382 Bielsko-Biała</div>' +
						'</div>' +
						'<div style="background:#fff;padding:15px;border-radius:4px;">' +
						'<div style="font-weight:bold;margin-bottom:8px;color:#1f2937;">Dane kontaktowe:</div>' +
						'<div style="color:#4b5563;">📞 Tel.: <a href="tel:+48334457020" style="color:#ef4444;text-decoration:none;">+48 334 457 020</a></div>' +
						'<div style="color:#4b5563;">📧 Email: <a href="mailto:sales@packeta.pl" style="color:#ef4444;text-decoration:none;">sales@packeta.pl</a></div>' +
						'</div>'
				},
				317: {
					content: '<div style="margin-bottom:15px;"><strong style="font-size:15px;">Klient zobowiązany jest do dostarczenia przesyłki na adres magazynu:</strong></div>' +
						'<div style="background:#fff;padding:15px;border-radius:4px;margin-bottom:10px;">' +
						'<div style="font-weight:bold;font-size:15px;margin-bottom:8px;color:#1f2937;">Packeta</div>' +
						'<div style="color:#4b5563;">Księdza Józefa Londzina 106</div>' +
						'<div style="color:#4b5563;">43-382 Bielsko-Biała</div>' +
						'</div>' +
						'<div style="background:#fff;padding:15px;border-radius:4px;">' +
						'<div style="font-weight:bold;margin-bottom:8px;color:#1f2937;">Dane kontaktowe:</div>' +
						'<div style="color:#4b5563;">📞 Tel.: <a href="tel:+48334457020" style="color:#ef4444;text-decoration:none;">+48 334 457 020</a></div>' +
						'<div style="color:#4b5563;">📧 Email: <a href="mailto:sales@packeta.pl" style="color:#ef4444;text-decoration:none;">sales@packeta.pl</a></div>' +
						'</div>'
				},
				90: {
					content: '<div style="margin-bottom:15px;"><strong style="font-size:15px;">Klient zobowiązany jest do dostarczenia przesyłki na adres magazynu:</strong></div>' +
						'<div style="background:#fff;padding:15px;border-radius:4px;margin-bottom:10px;">' +
						'<div style="font-weight:bold;font-size:15px;margin-bottom:8px;color:#1f2937;">Log4World</div>' +
						'<div style="color:#4b5563;">ul. Kępska 124</div>' +
						'<div style="color:#4b5563;">45-129 Opole</div>' +
						'</div>' +
						'<div style="background:#fff;padding:15px;border-radius:4px;">' +
						'<div style="font-weight:bold;margin-bottom:8px;color:#1f2937;">Dane kontaktowe:</div>' +
						'<div style="color:#4b5563;">📞 Tel.: <a href="tel:+48790715402" style="color:#ef4444;text-decoration:none;">+48 790 715 402</a></div>' +
						'<div style="color:#4b5563;">📧 Email: <a href="mailto:alsendo@log4world.com" style="color:#ef4444;text-decoration:none;">alsendo@log4world.com</a></div>' +
						'</div>'
				}
			};

			// Remove existing notices
			$('#alsendo-warehouse-add-notice').remove();

			// Check if selectedService requires a warehouse notice
			if (warehouseMessages[selectedService]) {
				var warehouse_notice = $('<div></div>')
					.attr('id', 'alsendo-warehouse-add-notice')
					.css({
						'padding': '20px 25px',
						'margin-bottom': '20px',
						'background-color': '#fef2f2',
						'border': '1px solid #fecaca',
						'border-left': '4px solid #ef4444',
						'border-radius': '6px',
						'color': '#991b1b',
						'font-size': '14px',
						'position': 'relative',
						'line-height': '1.6'
					})
					.html('⚠️ ' + warehouseMessages[selectedService].content +
						'<span style="position:absolute;right:15px;top:15px;cursor:pointer;font-size:20px;font-weight:bold;color:#991b1b;" class="alsendo-warehouse-close-notice" title="Zamknij">&times;</span>');

				warehouse_notice.insertBefore('#apaczka_send');
			}

		} else {
			$( '#alsendo-warehouse-add-notice' ).each(
				function (i, elem) {
					$( elem ).remove();
				}
			);
		}

	}

	function alsendoMetaboxChangeParcelTypeActions(select) {

		let type = select.value;

		// Find the common parent container (adjust the selector as needed).
		let container = select.closest('.apaczka-cloned-fields-wrapper');

		if (typeof container != 'undefined' ) {
			// Find the related fields within this container.
			let apaczka_parcel_length = container.querySelector('input[data-key="package_length"]');
			let apaczka_parcel_width = container.querySelector('input[data-key="package_width"]');
			let apaczka_parcel_height = container.querySelector('input[data-key="package_height"]');

			if (typeof type != 'undefined' && apaczka_parcel_length && apaczka_parcel_width && apaczka_parcel_height) {
				switch (type) {
					case 'europalette':
						apaczka_parcel_length.value = 120;
						apaczka_parcel_width.value = 80;
						apaczka_parcel_length.readOnly = true;
						apaczka_parcel_width.readOnly = true;

						if (parseInt(apaczka_parcel_height.value) > 220) {
							apaczka_parcel_height.value = 220;
						}

						apaczka_parcel_height.setAttribute('max', 220);
						break;
					case 'palette_60x80':
						apaczka_parcel_width.value = 60;
						apaczka_parcel_length.value = 80;
						apaczka_parcel_length.readOnly = true;
						apaczka_parcel_width.readOnly = true;

						if (parseInt(apaczka_parcel_height.value) > 220) {
							apaczka_parcel_height.value = 220;
						}

						apaczka_parcel_height.setAttribute('max', 220);
						break;
					case 'palette_120x100':
						apaczka_parcel_width.value = 100;
						apaczka_parcel_length.value = 120;
						apaczka_parcel_length.readOnly = true;
						apaczka_parcel_width.readOnly = true;

						if (parseInt(apaczka_parcel_height.value) > 220) {
							apaczka_parcel_height.value = 220;
						}

						apaczka_parcel_height.setAttribute('max', 220);
						break;
					case 'palette_120x120':
						apaczka_parcel_length.value = 120;
						apaczka_parcel_width.value = 120;
						apaczka_parcel_length.readOnly = true;
						apaczka_parcel_width.readOnly = true;

						if (parseInt(apaczka_parcel_height.value) > 220) {
							apaczka_parcel_height.value = 220;
						}

						apaczka_parcel_height.setAttribute('max', 220);
						break;
					default:
						apaczka_parcel_length.readOnly = false;
						apaczka_parcel_width.readOnly = false;
						apaczka_parcel_height.removeAttribute('max');
				}
			}
		}
	}

	function alsendo_connect_add_mask() {
		const bank_account_input = $( '#_apaczka\\[sender\\]\\[bank_account_number\\]' );
		if (typeof bank_account_input != 'undefined') {
			$(bank_account_input).on(
				'input',
				function (e) {
					let cursor_position = this.selectionStart;
					let old_value       = this.value;
					let new_value       = format_bank_account( old_value );
					if (new_value !== old_value) {
						this.value = new_value;
						if (cursor_position) {
							if (new_value.charAt( cursor_position - 1 ) === ' ') {
								cursor_position++;
							}
							if (cursor_position > new_value.length) {
								cursor_position = new_value.length;
							}
							this.setSelectionRange( cursor_position, cursor_position );
						}
					}
				}
			);

			function format_bank_account(value) {
				let digits    = value.replace( /\D/g, '' );
				let formatted = '';
				for (let i = 0; i < digits.length && i < 26; i++) {
					// Add space after positions: 2, 6, 10, 14, 18, 22.
					if (i === 2 || (i > 2 && (i - 2) % 4 === 0)) {
						formatted += ' ';
					}
					formatted += digits[i];
				}
				return formatted;
			}
		}

		const sender_zip_code = $( '#_apaczka\\[sender\\]\\[postal_code\\]' );
		if (typeof sender_zip_code != 'undefined' && sender_zip_code !== null) {
			$(sender_zip_code).on(
				'input',
				function (e) {
					let cursor_position = this.selectionStart;
					let old_value       = this.value;
					let new_value       = format_zip_code( old_value );
					if (new_value !== old_value) {
						this.value = new_value;
						if (cursor_position) {
							if (new_value.charAt( cursor_position - 1 ) === '-') {
								cursor_position++;
							}
							if (cursor_position > new_value.length) {
								cursor_position = new_value.length;
							}
							this.setSelectionRange( cursor_position, cursor_position );
						}
					}
				}
			);

			function format_zip_code(value) {
				// Remove all non-digit characters.
				let digits    = value.replace( /\D/g, '' );
				let formatted = '';
				for (let i = 0; i < digits.length && i < 5; i++) {
					if (i === 2) {
						formatted += '-';
					}
					formatted += digits[i];
				}

				return formatted;
			}
		}
	}

	function alsendo_connect_maybe_need_recalculate() {
		console.log( 'alsendo_connect_maybe_need_recalculate' );
		$( '#alsendo-recalc-notice' ).remove();
		let send_parcel_button = $( '#apaczka_send' );
		if (typeof send_parcel_button != 'undefined' && send_parcel_button !== null) {
			if ($( '#apaczka_send' ).css( 'display' ) === 'block') {
				let notice = '<span id="alsendo-recalc-notice"><b><pre>' + alsendo_order_metabox.recalc_notice + '</pre></b></span>';
				$( "#apaczka_send" ).prop( "disabled", true );
				$( "#apaczka_send" ).after( notice );

			}
		}
	}


	$( document ).ready(
		function () {

			console.log( 'alsendo-connect-order-metabox-apaczka.js' );

			$( 'body #woocommerce-order-downloads .buttons .select2-container' ).css( "width", "100% !important" );

			parcelCounter           = 0;
			let is_order_caclulated = $( '#alsendo_connect_calculated' ).val();

			let selected_sender_template = alsendo_order_metabox.selected_sender_template;


			alsendo_connect_add_mask();

			$( '#alsendo_connect' ).on(
				'keyup',
				'input',
				function () {
					alsendo_connect_maybe_need_recalculate();
				}
			);
			$( '#_apaczka\\[sender\\]\\[is_residential\\]' ).on(
				'change',
				function () {
					alsendo_connect_maybe_need_recalculate();
				}
			);
			$( '#_apaczka\\[package_properties\\]\\[parcel_type\\]' ).on(
				'change',
				function () {
					alsendo_connect_maybe_need_recalculate();
				}
			);
			$( '#_apaczka\\[package_properties\\]\\[pickup_hour_from\\]' ).on(
				'change',
				function () {
					alsendo_connect_maybe_need_recalculate();
				}
			);
			$( '#_apaczka\\[package_properties\\]\\[pickup_hour_to\\]' ).on(
				'change',
				function () {
					alsendo_connect_maybe_need_recalculate();
				}
			);

			$( '#_apaczka\\[package_properties\\]\\[pickup_date\\]' ).on(
				'change',
				function () {
					alsendo_connect_maybe_need_recalculate();
				}
			);


			if ( '1' !== is_order_caclulated ) {
				fillSenderFormByTemplate( selected_sender_template );
				fillPackagePropertiesFormByTemplate( alsendo_order_metabox.selected_package_template );
			}

			// If selected template has additional parcels, render them on load.
			const mainSelectedTemplateSlug = $( '#_apaczka\\[package_properties\\]\\[selected_template\\]' ).val();
			const tpl = mainSelectedTemplateSlug
				? ( alsendo_order_metabox.package_properties_templates[ mainSelectedTemplateSlug ] || null )
				: null;
			if ( tpl && Array.isArray( tpl.additional_parcels ) && tpl.additional_parcels.length > 0 && parcelCounter === 0 ) {
				tpl.additional_parcels.slice( 0, 9 ).forEach(
					function (p) {
						alsendoAddApaczkaAdditionalParcel( p );
					}
				);
			}

			let iban_order                = $( 'input[name="_apaczka[sender][bank_account_number]"]' );
			let sender_phone_number_order = $( 'input[name="_apaczka[sender][phone]"]' );

			let order_metabox_parcel_type_handle = document.getElementById( '_apaczka[package_properties][parcel_type]' );
			if (typeof order_metabox_parcel_type_handle != 'undefined' && order_metabox_parcel_type_handle !== null) {
				alsendoMetaboxChangeParcelTypeActions( order_metabox_parcel_type_handle );
			}

			// let apaczka_calculate_selected_service = 0.
			let apaczka_calculate_selected_service        = $( 'input[name="apaczka_calculate_radio"]:checked' ).val();
			//let apaczka_dispath_point_handler_to_validate = false;

			/*let map_country_code          = 'PL';
			let sender_country_code_field = $( '#_apaczka\\[sender\\]\\[country\\]' );
			if (typeof sender_country_code_field != 'undefined' && sender_country_code_field !== null) {
				let sender_country_code = $( sender_country_code_field ).val();
				if (typeof sender_country_code != 'undefined' && sender_country_code !== null) {
					map_country_code = sender_country_code;
				}
			}*/


			$( "#apaczka_calculate_radio > .apaczka-calculate-item > input[type='radio']" ).change(
				function (e) {
					console.log( "change", e );
				}
			);

			$( '#alsendo_connect_calculate_price_btn' ).click(
				function (e) {
					let observer = new MutationObserver(
						function (mutations) {
							if ($( "#apaczka_calculate_radio" ).length) {
								let selected_tile = false;
								$( '.apaczka-calculate-item' ).each(
									function (ind, element) {
										if ( $( element ).hasClass( 'selected' ) ) {
											selected_tile                      = true;
											apaczka_calculate_selected_service = $( element ).attr( 'data-service_id' );
											handleCalculateDynamicFields( parseInt( apaczka_calculate_selected_service ) );
										}
									}
								);
								if ( ! selected_tile ) {
									$( "#apaczka_calculate_radio > .apaczka-calculate-item:first-child" ).click();
									const valOfFirstItem = $( "#apaczka_calculate_radio > .apaczka-calculate-item > .apaczka-calculate-item-price-wrapper > input[type='radio']:checked" ).val();
									console.log( "valOfFirstItem", valOfFirstItem );
									apaczka_calculate_selected_service = valOfFirstItem;
									handleCalculateDynamicFields( parseInt( valOfFirstItem ) );
								}
								observer.disconnect();
							}
						}
					);
					// Start observing.
					observer.observe(
						document.body,
						{
							childList: true,
							subtree: true
						}
					);
				}
			);

			$( "#apaczka_add_parcel" ).click(
				function (e) {
					e.preventDefault();

					if ( parcelCounter >= 9 ) {
						alert( alsendo_order_metabox.text_max_parcels );
						return false;
					}

					parcelCounter++;
					const wrapId = 'parcel_wrap_' + parcelCounter;

					// Get the default wrapper to clone fields from.
					const apaczka_default_parcel = $( '.apaczka-cloned-fields-wrapper.default-wrapper' );

					if (typeof apaczka_default_parcel !== 'undefined' && apaczka_default_parcel.length > 0) {
						// Fields to clone (search only within the default wrapper).
						const fieldsToClone = [
							'._apaczka\\[package_properties\\]\\[parcel_type\\]_field',
							'._apaczka\\[package_properties\\]\\[is_nstd\\]_field',
							'._apaczka\\[package_properties\\]\\[package_length\\]_field',
							'._apaczka\\[package_properties\\]\\[package_width\\]_field',
							'._apaczka\\[package_properties\\]\\[package_height\\]_field',
							'._apaczka\\[package_properties\\]\\[package_weight\\]_field'
						];

						let class_name = 'apaczka-additional-parcel_' + parcelCounter;

						const wrapper = $(
							'<div>',
							{
								'class': 'apaczka-cloned-fields-wrapper',
								'data-wrap-id': wrapId
							}
						).append(
							$(
								'<span>',
								{
									'class': class_name + ' apaczka-additional-parcel-title',
									'text': alsendo_order_metabox.text_additional_parcel + ' #' + parcelCounter
									}
							)
						);

						// Insert package template select for this parcel (if templates exist).
						if ( alsendo_order_metabox.package_properties_templates
							&& Object.keys( alsendo_order_metabox.package_properties_templates ).length > 0
							&& $( '#_apaczka\\[package_properties\\]\\[selected_template\\]' ).length
						) {
							const mainTemplateSelect = $( '#_apaczka\\[package_properties\\]\\[selected_template\\]' );
							const mainSelectedTemplateSlug = mainTemplateSelect.val();

							const selectId  = 'apaczka_additional_package_template_' + parcelCounter;
							const selectName = '_apaczka[package_properties][' + parcelCounter + '][selected_template]';

							const templateSelect = mainTemplateSelect.clone();
							templateSelect
								.attr( 'id', selectId )
								.attr( 'name', selectName )
								.attr( 'data-key', 'selected_template_additional' )
								.addClass( 'apaczka-additional-package-template-select' )
								.data( 'parcel-index', parcelCounter )
								.val( mainSelectedTemplateSlug );

							const templateField = $( '<p>', { 'class': 'form-field apaczka-additional-package-template-field' } )
								.append( $( '<label>', { 'for': selectId, 'text': alsendo_order_metabox.text_choose_shipment_template || 'Choose shipment template' } ) )
								.append( templateSelect );

							wrapper.append( templateField );
						}

						// Clone each field from the default wrapper only.
						fieldsToClone.forEach(
							function (fieldSelector) {
								let originalField = apaczka_default_parcel.find( fieldSelector );
								if ( originalField.length === 0 ) {
									// Some fields may be outside the default parcel wrapper (e.g. package contents / declared value).
									originalField = $( fieldSelector ).filter(
										function () {
											return $( this ).closest( '.apaczka-cloned-fields-wrapper' ).length === 0;
										}
									).first();
								}
								if (originalField.length > 0) {
									const clonedField = originalField.clone();

									// Update IDs and names to make them unique.
									clonedField.find( 'input, select' ).each(
										function () {
											const originalId   = $( this ).attr( 'id' );
											const originalName = $( this ).attr( 'name' );

											if ( '_apaczka[package_properties][package_contents_tag]' === originalId ) {
												return;
											}

											if (originalId) {
												$( this ).attr( 'id', originalId + '_' + parcelCounter );
											}
											if ( '_apaczka[package_properties][package_contents]' === originalId ) {
												$( this ).prop( 'disabled', false );
											}
											if (originalName) {
												// Update name to include parcel index.
												const newName = originalName.replace(
													/_apaczka\[package_properties\]/,
													'_apaczka[package_properties][' + parcelCounter + ']'
												);
												$( this ).attr( 'name', newName );
											}

											// Clear values for inputs.
											if ($( this ).is( 'input[type="number"]' ) || $( this ).is( 'input[type="text"]' )) {
												$( this ).val( '' );
											}
										}
									);

									// Update label for attribute.
									clonedField.find( 'label' ).each(
										function () {
											const originalFor = $( this ).attr( 'for' );
											if (originalFor) {
												$( this ).attr( 'for', originalFor + '_' + parcelCounter );
											}
										}
									);

									wrapper.append( clonedField );
								}
							}
						);

						// Create remove button.
						const removeButton = $(
							'<button>',
							{
								'class': 'apaczka_remove_parcel button-secondary',
								'data-wrap-id': wrapId,
								'text': alsendo_order_metabox.text_remove_parcel
							}
						);

						wrapper.append( removeButton );

						// Insert before the add parcel button.
						$( '.apaczka_add_parcel_field' ).before( wrapper );

						// Immediately fill fields from the currently selected main template (scoped to this wrapper).
						const mainSelectedTemplateSlug = $( '#_apaczka\\[package_properties\\]\\[selected_template\\]' ).val();
						if ( mainSelectedTemplateSlug ) {
							fillPackagePropertiesFormByTemplateInWrapper( mainSelectedTemplateSlug, wrapper, parcelCounter );
						}

						// Ensure any dependent UI updates run for this wrapper.
						wrapper.find( '[data-key="parcel_type"]' ).trigger( 'change' );
						wrapper.find( '[data-key="is_nstd"]' ).trigger( 'change' );
					}

				}
			);

			// Handle template change for additional parcels (scoped to parcel wrapper).
			$( document ).on(
				'change',
				'.apaczka-additional-package-template-select',
				function () {
					const selectedTemplateSlug = $( this ).val();
					const parcelIndex          = $( this ).data( 'parcel-index' );
					const wrap                 = $( this ).closest( '.apaczka-cloned-fields-wrapper' );
					fillPackagePropertiesFormByTemplateInWrapper( selectedTemplateSlug, wrap, parcelIndex );
					alsendo_connect_maybe_need_recalculate();
				}
			);

			// Remove parcel functionality (using event delegation).
			$( document ).on(
				'click',
				'.apaczka_remove_parcel',
				function () {
					const wrapId = $( this ).data( 'wrap-id' );
					$( '[data-wrap-id="' + wrapId + '"]' ).remove();
					parcelCounter--;
				}
			);

			$( "#alsendo_connect_load_sender_settings_btn" ).click(
				function (e) {
					e.preventDefault();
					let selectedTemplateSlug = $( '#_apaczka\\[sender_template\\]' ).val();
					fillSenderFormByTemplate( selectedTemplateSlug );
					alsendo_connect_maybe_need_recalculate();
				}
			);

			$( "#alsendo_connect_load_package_properties_settings_btn" ).click(
				function (e) {
					e.preventDefault();
					let selectedTemplateSlug = $( '#_apaczka\\[package_properties\\]\\[selected_template\\]' ).val();

					// Apply base template values to the main (default) parcel.
					fillPackagePropertiesFormByTemplate( selectedTemplateSlug );

					// Sync additional parcels with selected template.
					alsendoClearApaczkaAdditionalParcels();
					const tpl = selectedTemplateSlug
						? ( alsendo_order_metabox.package_properties_templates[ selectedTemplateSlug ] || null )
						: null;
					if ( tpl && Array.isArray( tpl.additional_parcels ) && tpl.additional_parcels.length > 0 ) {
						tpl.additional_parcels.slice( 0, 9 ).forEach(
							function (p) {
								alsendoAddApaczkaAdditionalParcel( p );
							}
						);
					}

					alsendo_connect_maybe_need_recalculate();
				}
			);

			$( '#_apaczka\\[package_properties\\]\\[shipping_method\\]' ).change(
				function (e) {
					$('#deliver_to_any_shipping_point').hide();
					if ($( '#apaczka-calculate-wrapper' ).html() !== '') {
						$( '#apaczka_calculate_price_btn' ).click();
						return false;
					}
				}
			);

			$( ".apaczka_calculate_price" ).click(
				function () {
					//let shipment_type = $( '#_apaczka\\[package_properties\\]\\[parcel_type\\]' ).val();

					$( '#alsendo-recalc-notice' ).remove();
					$('#deliver_to_any_shipping_point').hide();
					$( '#alsendo-warehouse-add-notice' ).each(
						function (i, elem) {
							$( elem ).remove();
						}
					);

					if ( ! $( this ).closest( "form" )[0].checkValidity()) {
						$( this ).closest( "form" )[0].reportValidity();
						return false;
					}

					$( 'div' ).each(
						function () {
							let id = $( this ).attr( 'id' );
							if (id && id.startsWith( 'dispath_point_' )) {
								$( this ).addClass( 'apaczka-hidden' );
							}
							if (id && id.startsWith( 'apaczka_delivery_point_id_wrapper' )) {
								$( this ).addClass( 'apaczka-hidden' );
							}
						}
					);

					$( "#apaczka-calculate-wrapper" ).html( '' );
					$( this ).parent().find( ".spinner_courier" ).hide();
					$( this ).parent().find( ".spinner" ).hide();

					let data = {
						action: 'alsendo_connect',
						order_id: $( '#alsendo_connect_wc_order_id' ).val(),
						alsendo_connect_action: 'calculate',
						security: $( '#alsendo_connect_order_metabox_nonce' ).val(),
						alsendo_connect_calculate: {
							sender: {},
							receiver: {},
							package_properties: {},
							additional_options: {},
						}
					};

					let package_properties      = $( 'input[id^="_apaczka[package_properties]"], select[id^="_apaczka[package_properties]"]' );
					let sender                  = $( 'input[id^="_apaczka[sender]"]' );
					let receiver                = $( 'input[id^="_apaczka[receiver]"]' );
					let additional_options      = $( 'input[id^="_apaczka[additional_options]"]' );
					let is_residential_sender   = $( 'select[id="_apaczka[sender][is_residential]"]' ).val();
					let is_residential_receiver = $( 'select[id="_apaczka[receiver][is_residential]"]' ).val();

					sender.each(
						function () {
							data.alsendo_connect_calculate.sender[$( this ).data( 'key' )] = $( this ).val()
						}
					);
					data.alsendo_connect_calculate.sender['is_residential'] = is_residential_sender;

					receiver.each(
						function () {
							data.alsendo_connect_calculate.receiver[$( this ).data( 'key' )] = $( this ).val()
						}
					);
					data.alsendo_connect_calculate.receiver['is_residential'] = is_residential_receiver;

					let parcelGroups = {};
					let parcels      = [];

					package_properties.each(
						function () {
							/*if ( typeof $(this).data('key') != 'undefined' ) {
								data.alsendo_connect_calculate.package_properties[$(this).data('key')] = $(this).val();
							}*/

							let key          = $( this ).data( 'key' );
							let parcel_value = $( this ).val();
							let name         = $( this ).attr( 'name' );

							if (key && ['package_length', 'package_width', 'package_height', 'package_weight', 'parcel_type', 'is_nstd'].includes( key )) {
								// Extract parcel index from name.
								let parcelIndex = 0; // default for original fields
								let matches     = name.match( /_apaczka\[package_properties\]\[(\d+)\]/ );
								if (matches) {
									parcelIndex = parseInt( matches[1] );
								}

								// Initialize parcel group if not exists.
								if ( ! parcelGroups[parcelIndex]) {
									parcelGroups[parcelIndex] = {};
								}

								// Add field to parcel group.
								parcelGroups[parcelIndex][key] = parcel_value;


							} else if (key) {
								// Non-parcel specific properties.
								if ( key != 'undefined' ) {
									data.alsendo_connect_calculate.package_properties[$(this).data('key')] = $(this).val();
								}
							}
						}
					);

					// Convert parcel groups to array.
					Object.keys( parcelGroups ).sort( (a, b) => a - b ).forEach(
						function (parcelIndex) {
							parcels.push( parcelGroups[parcelIndex] );
						}
					);

					data.alsendo_connect_calculate.parcels = parcels;

					let may_be_contents_tag_used = $( '#' + '_apaczka\\[package_properties\\]\\[package_contents_tag\\]' );
					if( typeof may_be_contents_tag_used != 'undefined' && may_be_contents_tag_used !== null ) {
						let contents_tag = $( may_be_contents_tag_used ).val();
						if( typeof contents_tag != 'undefined' && contents_tag !== null ) {
							data.alsendo_connect_calculate.package_properties['package_contents_tag'] = contents_tag;
						}
					}

					additional_options.each(
						function () {
							data.alsendo_connect_calculate.additional_options[$( this ).data( 'key' )] = $( this ).val()
						}
					);

					let receiver_postal_code = data.alsendo_connect_calculate.receiver.postal_code;

					$( '#alsendo_pre_js_debug' ).remove();
					$( '#apaczka_error' ).html( '' );

					console.log( "alsendo connect evaluation data - prepared:" );
					console.log( data );

					$( '.apaczka_calculate_price'  ).each(
						function (ind, elem) {
							$( elem ).attr( 'disabled', true );
						}
					);

					$( '#alsendo_connect_preloader' ).css( 'display', 'inline-block' );
					$( '.apaczka_send' ).css( 'display', 'none' );

					if( $(this).hasClass('alsendo_full') ) {
						console.log( 'we need all available services' );
						data.alsendo_connect_calculate.alsendo_full = 1;
					}

					// return;

					$.post(
						ajaxurl,
						data,
						function (response) {
							console.log( 'Alsendo connect: evaluate package response' );
							if (response != 0) {
								response = JSON.parse( response );
								console.log( response.status );
								// console.log( response );
								if (response.status === 'ok') {
									$( '.apaczka_send' ).css( 'display', 'block' );
									$( '#apaczka_error' ).html( '' );
									let calculate_html   = response.calculate_html;
									let calcualted_tiles = $.parseHTML( calculate_html );
									$( "#apaczka-calculate-wrapper" ).html( calcualted_tiles );
									$( "#apaczka_send" ).prop( "disabled", false );
									changeShippingMethodTriggers( $( '#_apaczka\\[package_properties\\]\\[shipping_method\\]' ).val() );
									// $('.apaczka-calculate-item[data-item="0"]').click();

									let selected_tile = $( '.apaczka-calculate-item.selected' );
									if (typeof selected_tile === 'object' && selected_tile !== null) {
										$( selected_tile ).trigger('click');
										console.log('SELECTED SERV_ID:');
										let selected_carrier_id = $(selected_tile).attr('data-service_id');
										console.log(selected_carrier_id);
										handleCalculateDynamicFields( parseInt( selected_carrier_id ) );
									}

								} else {
									console.log( 'Calculation: error:' );
									console.log( response.status );
									console.log( response );
									$( '#apaczka_error' ).html( '' );
									let api_response = '';
									if ( 'errors' in response ) {
										console.log( response.errors );
										if (typeof response.errors === 'object' && response.errors !== null) {
											if ( 'errors' in response.errors ) {
												api_response += '<br>' + alsendo_process_api_response( response.errors.errors );
											}
										} else {
											api_response += '<br>' + alsendo_process_api_response( response.errors );
										}
									}
									if ( 'error_messages' in response ) {
										console.log( response.error_messages );
										api_response += alsendo_process_api_response( response.error_messages );
									}
									if ( 'status' in response && response.status.length > 0 ) {
										// api_response += '<br>' + 'Status: ' + response.status;
									}
									if ( 'status_code' in response && response.status_code.length > 0) {
										api_response += '<br>' + 'Status code: ' + response.status_code;
									}
									if ( 'message' in response ) {
										console.log( response.message );
										api_response += '<br>' + alsendo_process_api_response( response.message );
									}

									console.log( 'Error: api_response' );
									console.log( api_response );

									if (typeof api_response != 'undefined' && api_response !== null && api_response != '' ) {
										$( '#apaczka_error' ).html( '<pre>' + api_response.replace( /\n/g, '<br>' ) + '</pre>' );
									} else {
										let formatted_JSON = formatJSON( response );
										$( '#apaczka_error' ).html( '<pre>' + formatted_JSON + '</pre>' );
									}

									$( "#apaczka-calculate-wrapper" ).html( '' );
									$( "#apaczka_send" ).prop( "disabled", true );
								}

								$( '#alsendo_connect_preloader' ).css( 'display', 'none' );

								$( '.apaczka_calculate_price'  ).each(
									function (ind, elem) {
										$( elem ).attr( 'disabled', false );
									}
								);

								return false;

							} else {
								$( '#apaczka_error' ).html( 'Invalid response.' );
							}

						}
					);

					return false;
				}
			);

			$( document ).on(
				"click",
				'.apaczka_calculate_radio',
				function (event) {
					apaczka_calculate_selected_service = $( 'input[name="apaczka_calculate_radio"]:checked' ).val();
					handleCalculateDynamicFields( parseInt( apaczka_calculate_selected_service ) );
				}
			);

			$( document ).on(
				"click",
				'#apaczka_get_waybill',
				function (event) {
					event.preventDefault();

					let order_id = $( '#ecolet_wc_order_id' ).attr( 'data-id' );
					$.ajax(
						{
							type: 'POST',
							url: alsendo_admin.ajaxurl,
							dataType: 'json',
							data: {
								action: 'alsendo_connect',
								alsendo_connect_action: 'apaczka_get_waybill',
								security: $( '#alsendo_connect_order_metabox_nonce' ).val(),
								apaczka_order_id: $( '#alsendo_connect_order_created' ).val(),
								order_id: order_id
							},
							beforeSend: function () {
								$( '#apaczka_get_waybill' ).prop( 'disabled', true );
								$( '#alsendo_connect_preloader' ).css( 'display', 'block' );
								$( '#ecolet_some_error' ).remove();
							},
							success: function (response) {
								console.log( "Apaczka waybill response:" );
								console.log( response.data );

								if ( 'pdf' in response.data) {
									let win = window.open();
									win.document.write( '<iframe src="data:application/pdf;base64,' + response.data.pdf + '" frameborder="0" style="border:0; top:0px; left:0px; bottom:0px; right:0px; width:100%; height:100%;" allowfullscreen></iframe>' );

								}

							},
							error: function (jqXHR, textStatus, errorThrown) {
								console.log( "Error response on get Apaczka waybill:" );
								console.log( textStatus );
								console.log( 'Error: ' + errorThrown + ' ' + jqXHR.responseText );
								let woo_logs_section_url = ' <a target="blank_" href="' + alsendo_order_metabox.log_path + '">' + alsendo_order_metabox.text_here + '</a>';
								let error_message        = "<br><br>Error:<br> Unexpected response from server.<br>Check log file 'alsendo-connect-apaczka-get-waybill-order-' for order #" + order_id + woo_logs_section_url + "</span>";
								$( '#ecolet_wc_order_id' ).after( '<span id="ecolet_some_error" style="color:#e03636"><b>' + error_message + '</b></span>' );

							},
							complete: function (response) {
								$( '#apaczka_get_waybill' ).prop( 'disabled', false );
								$( '#alsendo_connect_preloader' ).css( 'display', 'none' );

							}
						}
					);
				}
			);

			$( "#apaczka_cancel" ).click(
				function () {

					const cancelled_only_on_apaczka_pl = new Array( '260', '220', '250', '230', '240', '150' );

					let service_id   = $( '#apaczka_choosed_carrier_id' ).attr( 'data-id' );
					let service_name = $( '#apaczka_choosed_carrier_id' ).text();

					if (service_id) {
						if ($.inArray( service_id, cancelled_only_on_apaczka_pl ) !== -1) {
							$( '#apaczka_alert_modal' ).addClass( 'active' );
							return false;
						}
					}

					$( this ).attr( 'disabled', true );
					$( '#alsendo_connect_preloader' ).css( 'display', 'inline-block' );

					let data = {
						action: 'alsendo_connect',
						order_id: $( '#alsendo_connect_wc_order_id' ).val(),
						alsendo_connect_action: 'cancel_package',
						security: $( '#alsendo_connect_order_metabox_nonce' ).val(),
						apaczka_order_id: $( '#alsendo_connect_order_created' ).val(),
					};

					$.post(
						ajaxurl,
						data,
						function (response) {
							if (response != 0) {
								response = JSON.parse( response );
								console.log( response.status );
								if (response.status === 'ok') {
									window.location.reload();
								} else {
									console.log( response.status );
									console.log( response.error_messages );
									$( '#apaczka_error' ).html( '<pre>' + response.error_messages + '</pre>' );
									$( '#apaczka_cancel' ).attr( 'disabled', false );

								}

								$( '#alsendo_connect_preloader' ).css( 'display', 'none' );

								return false;
							} else {
								$( '#apaczka_cancel' ).attr( 'disabled', false );
								$( '#apaczka_error' ).html( 'Invalid response.' );
							}

						}
					);

				}
			);

			$( document ).on(
				"click",
				'#apaczka_download_turn_in',
				function (event) {
					let data = {
						action: 'alsendo_connect',
						order_id: $( '#alsendo_connect_wc_order_id' ).val(),
						alsendo_connect_action: 'download_turn_in',
						security: $( '#alsendo_connect_order_metabox_nonce' ).val(),
					};

					$( '#alsendo_connect_preloader' ).css( 'display', 'inline-block' );

					$.post(
						ajaxurl,
						data,
						function (response) {
							if (response != 0) {
								response = JSON.parse( response );
								console.log( 'apaczka_download_turn_in' );
								console.log( response );
								console.log( response.status );
								if (response.status === 'ok') {
									$( '#apaczka_error' ).html( '' );
									let win = window.open();
									win.document.write( '<iframe src="data:application/pdf;base64,' + response.base64 + '" frameborder="0" style="border:0; top:0px; left:0px; bottom:0px; right:0px; width:100%; height:100%;" allowfullscreen></iframe>' );
								} else {
									console.log( 'apaczka_download_turn_in error:' );
									console.log( response.status );
									console.log( response.error_messages );

									$( '#apaczka_error' ).html( '<pre>' + response.error_messages + '</pre>' );
								}

								$( '#alsendo_connect_preloader' ).css( 'display', 'none' );
								$( '.apaczka_calculate_price'  ).each(
									function (ind, elem) {
										$( elem ).attr( 'disabled', false );
									}
								);

								return false;
							} else {
								$( '#apaczka_error' ).html( 'Invalid response.' );
								$( '.apaczka_calculate_price'  ).each(
									function (ind, elem) {
										$( elem ).attr( 'disabled', false );
									}
								);
							}

						}
					);

					return false;
				}
			);

			$( "#apaczka_send" ).click(
				function (e) {

					let selected_tile = $( '.apaczka-calculate-item.selected' );
					if ( ! selected_tile || typeof selected_tile == 'undefined' || selected_tile === null) {
						e.preventDefault();
						alert( alsendo_order_metabox.text_no_selected );
						return false;
					}

					if ( selected_tile.length === 0 ) {
						e.preventDefault();
						alert( alsendo_order_metabox.text_no_selected );
						return false;
					}

					let shipping_method = $( '#_apaczka\\[package_properties\\]\\[shipping_method\\]' ).val();

					if (false !== apaczka_dispath_point_handler_to_validate) {
						if ('' === apaczka_dispath_point_handler_to_validate.val()) {
							alert( "Punkt nadania nie może być pusty." );
							return false;
						}
					}

					let delivery_point_id;

					if ($( '#apaczka_delivery_point_id_wrapper' ).hasClass( 'apaczka-hidden' )) {
						delivery_point_id = ''
					} else {
						delivery_point_id = $( '#_apaczka\\[delivery_point_id\\]' ).val();
						if ('' === delivery_point_id) {
							alert( "Punkt odbioru nie może być pusty." );
							return false;
						}
					}

					if ( ! $( this ).closest( "form" )[0].checkValidity()) {
						$( this ).closest( "form" )[0].reportValidity();
						return false;
					}

					if ( ! apaczka_calculate_selected_service || typeof apaczka_calculate_selected_service == 'undefined' || apaczka_calculate_selected_service === null) {
						apaczka_calculate_selected_service = $( 'input[name="apaczka_calculate_radio"]:checked' ).val();
					}

					let test = $( 'input[name="apaczka_calculate_radio"]:checked' ).val();
					console.log('test selected service');
					console.log(test);
					console.log(apaczka_calculate_selected_service);

					let data = {
						action: 'alsendo_connect',
						order_id: $( '#alsendo_connect_wc_order_id' ).val(),
						alsendo_connect_action: 'create_package',
						security: $( '#alsendo_connect_order_metabox_nonce' ).val(),
						alsendo_connect_create: {
							sender: {},
							receiver: {},
							package_properties: {},
							additional_options: {},
							delivery_point: {},
							delivery_point_id: delivery_point_id,
							selected_service: apaczka_calculate_selected_service,
							selected_supplier: '',

						}
					};


					// let xxx = data.alsendo_connect_create.selected_service;
					// console.log('XXX test selected service');
					// console.log(xxx);


					let package_properties = $( 'input[id^="_apaczka[package_properties]"], select[id^="_apaczka[package_properties]"]' );
					let sender             = $( 'input[id^="_apaczka[sender]"]' );

					let additional_options      = $( 'input[id^="_apaczka[additional_options]"]' );
					let receiver                = $( 'input[id^="_apaczka[receiver]"]' );
					let delivery_point          = $( 'input[name^="_apaczka[delivery_point]"]' );
					let is_residential_sender   = $( 'select[id="_apaczka[sender][is_residential]"]' ).val();
					let is_residential_receiver = $( 'select[id="_apaczka[receiver][is_residential]"]' ).val();

					receiver.each(
						function () {
							data.alsendo_connect_create.receiver[$( this ).data( 'key' )] = $( this ).val()
						}
					);
					data.alsendo_connect_create.receiver['is_residential'] = is_residential_receiver;

					sender.each(
						function () {
							data.alsendo_connect_create.sender[$( this ).data( 'key' )] = $( this ).val()
						}
					);
					data.alsendo_connect_create.sender['is_residential'] = is_residential_sender;
					data.alsendo_connect_create.sender['apm_foreign_access_point_id'] = $( '#_apaczka\\[sender\\]\\[apm_foreign_access_point_id\\]' ).val();
					if ('COURIER' === shipping_method) {
						console.log('shipping method == Courier == clear sender apm_foreign_access_point_id');
						data.alsendo_connect_create.sender.apm_foreign_access_point_id = '';
					}

					// fix #25653.
					if (apaczka_calculate_selected_service === '42') {
						data.alsendo_connect_create.sender['apm_foreign_access_point_id'] = '';
					}

					// fix #25629.
					if (apaczka_calculate_selected_service === '41' && 'COURIER' === shipping_method) {
						data.alsendo_connect_create.sender['apm_foreign_access_point_id'] = '';
					}

					/*if (53 == data.alsendo_connect_create.selected_service && 'COURIER' === shipping_method) {
						console.log( 'Orlen Drzwi - Punkt: delivery_point_id' );
						console.log( data.alsendo_connect_create.delivery_point_id );
						data.alsendo_connect_create.delivery_point_id = '';
					}*/

					/*package_properties.each(
						function () {
							if ( typeof $(this).data('key') != 'undefined' ) {
								data.alsendo_connect_create.package_properties[$(this).data('key')] = $(this).val();
							}
						}
					);*/


					let parcelGroups = {};
					let parcels      = [];

					package_properties.each(
						function () {
							/*if ( typeof $(this).data('key') != 'undefined' ) {
								data.alsendo_connect_calculate.package_properties[$(this).data('key')] = $(this).val();
							}*/

							let key          = $( this ).data( 'key' );
							let parcel_value = $( this ).val();
							let name         = $( this ).attr( 'name' );

							if (key && ['package_length', 'package_width', 'package_height', 'package_weight', 'parcel_type', 'is_nstd'].includes( key )) {
								// Extract parcel index from name.
								let parcelIndex = 0; // default for original fields
								let matches     = name.match( /_apaczka\[package_properties\]\[(\d+)\]/ );
								if (matches) {
									parcelIndex = parseInt( matches[1] );
								}

								// Initialize parcel group if not exists.
								if ( ! parcelGroups[parcelIndex]) {
									parcelGroups[parcelIndex] = {};
								}

								// Add field to parcel group.
								parcelGroups[parcelIndex][key] = parcel_value;


							} else if (key) {
								// Non-parcel specific properties.
								if ( key != 'undefined' ) {
									data.alsendo_connect_create.package_properties[$(this).data('key')] = $(this).val();
								}
							}
						}
					);

					// Convert parcel groups to array.
					Object.keys( parcelGroups ).sort( (a, b) => a - b ).forEach(
						function (parcelIndex) {
							parcels.push( parcelGroups[parcelIndex] );
						}
					);

					data.alsendo_connect_create.parcels = parcels;

					let may_be_contents_tag_used = $( '#' + '_apaczka\\[package_properties\\]\\[package_contents_tag\\]' );
					if( typeof may_be_contents_tag_used != 'undefined' && may_be_contents_tag_used !== null ) {
						let contents_tag = $( may_be_contents_tag_used ).val();
						if( typeof contents_tag != 'undefined' && contents_tag !== null ) {
							data.alsendo_connect_create.package_properties['package_contents_tag'] = contents_tag;
						}
					}

					additional_options.each(
						function () {
							data.alsendo_connect_create.additional_options[$( this ).data( 'key' )] = $( this ).val();
						}
					);

					$( '#alsendo_pre_js_debug' ).remove();
					$( '#apaczka_error' ).html( '' );
					$( '#alsendo_connect_preloader' ).css( 'display', 'block' );
					$( this ).attr( 'disabled', true );

					console.log( 'Alsendo connect: create_order_ajax_data' );
					console.log( data );

					$.post(
						ajaxurl,
						data,
						function (response) {
							if (response != 0) {
								response = JSON.parse( response );
								if (response.status === 'ok') {
									console.log( response );

									if ( 'apaczka_order' in response ) {
										if ( 'apaczka_ok' in response ) {
											console.log( 'Order created in Apaczka.pl' );
											window.location.reload();
											console.log( 'window.location.reload' );
										}
									}

									if ( 'zaslat_order' in response ) {
										if ( 'zaslat_ok' in response ) {
											console.log( 'Order created in Zaslat.cz' );
											window.location.reload();
											console.log( 'window.location.reload' );
										}
									}

								} else {

									console.log( 'Alsendo: send_order_error' );
									console.log( response.status );
									console.log( response );

									$( '#alsendo_connect_preloader' ).css( 'display', 'none' );
									let order_id = $( '#alsendo_connect_wc_order_id' ).val();

									let api_response = 'Error: ';

									if ( 'ecolet_error' in response ) {
										api_response += alsendo_order_metabox.text_no_order_id + '\n\n';
										api_response += alsendo_order_metabox.text_order_section + '\n\n';
										api_response += alsendo_order_metabox.text_order_details + '\n\n';
									}

									if ( 'status_code' in response  ) {
										api_response += '<br>' + 'API response code: ' + response.status_code + '\n\n';
									}
									if ( 'error_messages' in response  ) {
										console.log( response.error_messages );
										api_response += alsendo_process_api_response( response.error_messages );
									}
									if ( 'error' in response  ) {
										console.log( response.error );
										api_response += alsendo_process_api_response( response.error );
									}
									if ( 'errors' in response  ) {
										console.log( response.errors );
										if ( 'errors' in response.errors  ) {
											console.log( 'eeeeeeeeeee' );
											console.log( response.errors.errors );
											api_response += alsendo_process_api_response( response.errors.errors );
										} else {
											api_response += alsendo_process_api_response( response.errors );
										}

									}

									if ( 'status_text' in response  ) {
										api_response += 'Details: ' + response.status_text + '\n\n';
									}
									if ( 'raw_json' in response  ) {
										api_response += response.raw_json + '\n\n';
									}

									if ( 'apaczka_response' in response ) {
										if ( 'status_code' in response.apaczka_response  ) {
											api_response += 'API response code: ' + response.apaczka_response.status_code + '\n\n';
										}
										if ( 'message' in response.apaczka_response || 'errors' in response.apaczka_response ) {
											if (  'message' in response.apaczka_response ) {
												api_response += '<br>' + alsendo_process_api_response( response.apaczka_response.message );
											}
											if ( 'errors' in response.apaczka_response ) {
												console.log( 'additional_api_errors:' );
												console.log( response.apaczka_response.errors );
												api_response += '<br>' + alsendo_process_api_response( response.apaczka_response.errors );
											}
										}
									}

									console.log( 'api_response_errors:' );
									console.log( api_response );

									let woo_logs_section_url = ' <a target="blank_" href="' + alsendo_order_metabox.log_path + '">' + alsendo_order_metabox.text_here + '</a>';
									api_response            += "<br>Check log file 'alsendo-connect-create-order-' for order #" + order_id + woo_logs_section_url + "</span>";

									$( '#apaczka_error' ).html( '<pre>' + api_response.replace( /\n/g, '<br>' ) + '</pre>' );

									$( '.apaczka_send' ).attr( 'disabled', false );
									// $( this ).parent().find( ".spinner" ).removeClass( 'is-active' );
									$( '#alsendo_connect_preloader' ).css( 'display', 'none' );
								}

								return false;
							} else {
								// console.log('Invalid response.');
								$( '#apaczka_error' ).html( 'Invalid response.' );
								$( '.apaczka_send' ).attr( 'disabled', false );
								$( '#alsendo_connect_preloader' ).css( 'display', 'none' );
							}

						}
					);

					return false;
				}
			);



			$( '#_apaczka\\[package_properties\\]\\[dispath_point_inpost\\]' ).click(
				function (e) {
					const field = $( this );
					e.preventDefault();

					let dispath_point_inpost_opeartor = ['INPOST'];

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

					console.log( 'alsendo_order_metabox: dispath_point_inpost_click' );

					let sender_country = document.getElementById( "_apaczka[sender][country]" ).value;
					console.log( 'alsendo_apaczka_metabox: sender_country ' +  sender_country );


					BPWidget.init(
						document.getElementById( 'apaczka_geowidget_modal_inner_content' ),
						{
							callback: function (point) {
								// console.log(point);.
								field.val( point.code );
								$( '#_apaczka\\[sender\\]\\[apm_foreign_access_point_id\\]' ).val( point.code );
								let map_modal           = document.getElementById( 'apaczka_geowidget_modal_dynamic' );
								map_modal.style.display = 'none';
							},
							posType: 'DELIVERY',
							mapOptions: { zoom: 12 },
							codOnly: false,
							operatorMarkers: true,
							countryCodes: sender_country,
							initialAddress: $( '#_apaczka\\[sender\\]\\[city\\]' ).val(),
							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';
					}
				}
			);


			$( '#_apaczka\\[package_properties\\]\\[dispath_point_gls\\]' ).click(
				function (e) {
					const field = $( this );
					e.preventDefault();

					let sender_country = document.getElementById( "_apaczka[sender][country]" ).value;
					console.log( 'alsendo_apaczka_metabox: sender_country ' +  sender_country );

					console.log( 'alsendo_order_metabox: dispath_point_gls_click' );
					BPWidget.init(
						document.getElementById( 'apaczka_geowidget_modal_inner_content' ),
						{
							callback: function (point) {
								// console.log(point);.
								field.val( point.code );
								$( '#_apaczka\\[sender\\]\\[apm_foreign_access_point_id\\]' ).val( point.code );
								let map_modal           = document.getElementById( 'apaczka_geowidget_modal_dynamic' );
								map_modal.style.display = 'none';
							},
							posType: 'DELIVERY',
							mapOptions: { zoom: 12 },
							codOnly: false,
							operatorMarkers: true,
							countryCodes: sender_country,
							initialAddress: $( '#_apaczka\\[sender\\]\\[city\\]' ).val(),
							operators: [{ operator: 'GLS' }],
							codeSearch: true
						}
					);

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



			$( '#_apaczka\\[package_properties\\]\\[dispath_point_kurier48\\]' ).click(
				function (e) {
					const field = $( this );
					e.preventDefault();

					let dispath_point_kurier48_opeartor = ['POCZTA'];

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

					console.log( 'alsendo_order_metabox: dispath_point_kurier48_click' );
					console.log( dispath_point_kurier48_opeartor );
					console.log( operators );

					let sender_country = document.getElementById( "_apaczka[sender][country]" ).value;
					console.log( 'alsendo_apaczka_metabox: sender_country ' +  sender_country );

					BPWidget.init(
						document.getElementById( 'apaczka_geowidget_modal_inner_content' ),
						{
							callback: function (point) {
								console.log( point );
								console.log( point.code );
								field.val( point.code );
								$( '#_apaczka\\[sender\\]\\[apm_foreign_access_point_id\\]' ).val( point.code );
								let map_modal           = document.getElementById( 'apaczka_geowidget_modal_dynamic' );
								map_modal.style.display = 'none';
							},
							posType: 'DELIVERY',
							mapOptions: { zoom: 12 },
							codOnly: false,
							operatorMarkers: true,
							countryCodes: sender_country,
							initialAddress: $( '#_apaczka\\[sender\\]\\[city\\]' ).val(),
							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';
					}
				}
			);

			$( '#_apaczka\\[package_properties\\]\\[dispath_point_ups\\]' ).click(
				function (e) {
					const field = $( this );
					e.preventDefault();

					let dispath_point_ups = ['UPS'];

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

					console.log( 'alsendo_order_metabox: dispath_point_ups_click' );

					let sender_country = document.getElementById( "_apaczka[sender][country]" ).value;
					console.log( 'alsendo_apaczka_metabox: sender_country ' +  sender_country );

					BPWidget.init(
						document.getElementById( 'apaczka_geowidget_modal_inner_content' ),
						{
							callback: function (point) {
								// console.log(point);
								field.val( point.code );
								$( '#_apaczka\\[sender\\]\\[apm_foreign_access_point_id\\]' ).val( point.code );
								let map_modal           = document.getElementById( 'apaczka_geowidget_modal_dynamic' );
								map_modal.style.display = 'none';
							},
							posType: 'DELIVERY',
							mapOptions: { zoom: 12 },
							codOnly: false,
							operatorMarkers: true,
							countryCodes: sender_country,
							initialAddress: $( '#_apaczka\\[sender\\]\\[city\\]' ).val(),
							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';
					}
				}
			);

			$( '#_apaczka\\[package_properties\\]\\[dispath_point_dpd\\]' ).click(
				function (e) {
					const field = $( this );
					e.preventDefault();

					let dispath_point_dpd = ['DPD'];

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

					console.log( 'alsendo_order_metabox: dispath_point_dpd_click' );


					let sender_country = document.getElementById( "_apaczka[sender][country]" ).value;
					console.log( 'alsendo_apaczka_metabox: sender_country ' +  sender_country );


					BPWidget.init(
						document.getElementById( 'apaczka_geowidget_modal_inner_content' ),
						{
							callback: function (point) {
								// console.log(point);
								field.val( point.code );
								$( '#_apaczka\\[sender\\]\\[apm_foreign_access_point_id\\]' ).val( point.code );
								let map_modal           = document.getElementById( 'apaczka_geowidget_modal_dynamic' );
								map_modal.style.display = 'none';
							},
							posType: 'DELIVERY',
							mapOptions: { zoom: 12 },
							codOnly: false,
							operatorMarkers: true,
							countryCodes: sender_country,
							initialAddress: $( '#_apaczka\\[sender\\]\\[city\\]' ).val(),
							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';
					}
				}
			);

			$( '#_apaczka\\[package_properties\\]\\[dispath_point_dhl\\]' ).click(
				function (e) {
					const field = $( this );
					e.preventDefault();

					let sender_country = document.getElementById( "_apaczka[sender][country]" ).value;
					console.log( 'alsendo_apaczka_metabox: sender_country ' +  sender_country );

					let dispath_point_dhl = ['DHL'];

					if( 'PL' !== sender_country.toUpperCase() ) {
						dispath_point_dhl = ['DHL_PARCEL'];
					}

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

					console.log( 'alsendo_order_metabox: dispath_point_dhl_click' );

					BPWidget.init(
						document.getElementById( 'apaczka_geowidget_modal_inner_content' ),
						{
							callback: function (point) {
								// console.log(point);
								field.val( point.code );
								$( '#_apaczka\\[sender\\]\\[apm_foreign_access_point_id\\]' ).val( point.code );
								let map_modal           = document.getElementById( 'apaczka_geowidget_modal_dynamic' );
								map_modal.style.display = 'none';
							},
							posType: 'DELIVERY',
							mapOptions: { zoom: 12 },
							codOnly: false,
							operatorMarkers: true,
							countryCodes: sender_country,
							initialAddress: $( '#_apaczka\\[sender\\]\\[city\\]' ).val(),
							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';
					}
				}
			);

			$( '#_apaczka\\[delivery_point_id\\]' ).click(
				function (e) {
					let field = $( this );
					e.preventDefault();
					let cod_amount_defined = is_cod_amount_defined();
					let is_cod_only        = false;
					if ( cod_amount_defined ) {
						is_cod_only = true;
					}

					let apaczka_calculate_selected_service = $( 'input[name="apaczka_calculate_radio"]:checked' ).val();

					console.log( 'alsendo_order_metabox: delivery_point_id_click' );
					console.log( 'alsendo_order_metabox__selected_service ID: ' + apaczka_calculate_selected_service );
					console.log( [serviceIdToApmSupplierId( parseInt( apaczka_calculate_selected_service ) )] );

					let shipping_country = document.getElementById( "_apaczka[receiver][country_code]" ).value;
					if (typeof shipping_country != 'undefined' && shipping_country !== null) {
						shipping_country = shipping_country.toUpperCase();
					}

					let amp_supplier = serviceIdToApmSupplierId( parseInt( apaczka_calculate_selected_service ) );

					if( 'DHL' === amp_supplier ) {
						if( 'PL' !== shipping_country ) {
							amp_supplier = 'DHL_PARCEL';
						}
					}

					let operatorsArray = [amp_supplier];

					console.log( 'operatorsArray' );
					console.log( operatorsArray );

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

					console.log( 'operators' );
					console.log( operators );




					BPWidget.init(
						document.getElementById( 'apaczka_geowidget_modal_inner_content' ),
						{
							callback: function (point) {
								// console.log(point);
								console.log( point.code );
								field.val( point.code );
								// $('#_apaczka_apm_access_point_id').val(record.foreign_access_point_id);
								$( 'input[id=_apaczka_apm_access_point_id]' ).each(
									function (ind, elem) {
										$( elem ).val( point.code );
									}
								);

								// $('#_apaczka_apm_supplier').val(record.supplier);
								$( 'input[id=_apaczka_apm_supplier]' ).each(
									function (ind, elem) {
										$( elem ).val( point.operator );
									}
								);

								// $('#_apaczka_apm_name').val(record.name);
								$( 'input[id=_apaczka_apm_name]' ).each(
									function (ind, elem) {
										$( elem ).val( point.description );
									}
								);

								// $('#_apaczka_apm_foreign_access_point_id').val(record.foreign_access_point_id);
								$( 'input[id=_apaczka_apm_foreign_access_point_id]' ).each(
									function (ind, elem) {
										$( elem ).val( point.code );
									}
								);

								// $('#_apaczka_apm_street').val(record.street);
								$( 'input[id=_apaczka_apm_street]' ).each(
									function (ind, elem) {
										$( elem ).val( point.street );
									}
								);

								// $('#_apaczka_apm_city').val(record.city);
								$( 'input[id=_apaczka_apm_city]' ).each(
									function (ind, elem) {
										$( elem ).val( point.city );
									}
								);

								// $('#_apaczka_apm_postal_code').val(record.postal_code);
								$( 'input[id=_apaczka_apm_postal_code]' ).each(
									function (ind, elem) {
										$( elem ).val( point.postalCode );
									}
								);

								// $('#_apaczka_apm_country_code').val(record.country_code);
								$( 'input[id=_apaczka_apm_country_code]' ).each(
									function (ind, elem) {
										$( elem ).val( shipping_country );
									}
								);

								let map_modal           = document.getElementById( 'apaczka_geowidget_modal_dynamic' );
								map_modal.style.display = 'none';
							},
							posType: 'DELIVERY',
							mapOptions: { zoom: 12 },
							codOnly: is_cod_only,
							operatorMarkers: true,
							countryCodes: shipping_country,
							initialAddress: $( '#_apaczka\\[receiver\\]\\[city\\]' ).val(),
							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';
					}

				}
			);

			let pckg_selected_template = alsendo_order_metabox.selected_package_template;
			let apaczka_package_properties_templates = alsendo_order_metabox.package_properties_templates;
			if( pckg_selected_template in apaczka_package_properties_templates ) {
				let template_data = apaczka_package_properties_templates[pckg_selected_template];

				if (template_data.options && template_data.options.hasOwnProperty('alsendo_connect_settings_general_package_contents')) {
					const value = template_data.options.alsendo_connect_settings_general_package_contents;
					console.log('Contents Tag Value:', value); // Will output for example: "product_name".
					if (typeof value !== 'undefined') {
						if( 'product_id' === value || 'product_name' === value || 'order_id' === value ) {
							$( '#' + '_apaczka\\[package_properties\\]\\[package_contents\\]' ).prop( 'disabled', true );
							let hidden_input_tag_content = '<input type="hidden" name="_apaczka[package_properties][package_contents_tag]" id="_apaczka[package_properties][package_contents_tag]" value="' + value + '">';
							$( '#' + '_apaczka\\[package_properties\\]\\[package_contents\\]' ).append( hidden_input_tag_content );
						} else {
							$( '#' + '_apaczka\\[package_properties\\]\\[package_contents\\]' ).prop( 'disabled', false );
							$( '#' + '_apaczka\\[package_properties\\]\\[package_contents_tag\\]' ).each(
								function (ind, elem) {
									$( elem ).remove();
								}
							);
						}
					} else {
						$( '#' + '_apaczka\\[package_properties\\]\\[package_contents\\]' ).prop( 'disabled', false );
						$( '#' + '_apaczka\\[package_properties\\]\\[package_contents_tag\\]' ).each(
							function (ind, elem) {
								$( elem ).remove();
							}
						);
					}
				}
			}


		}
	);

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


			if (target.hasAttribute( 'id' ) && 'alsendo_connect_alert_modal_close_button' === target.getAttribute( 'id' ) ) {
				// hide cancel package alert modal.
				$( "#apaczka_alert_modal" ).removeClass( "active" );
			}

			if (target.closest( '#apaczka_calculate_radio' ) ) {
				// orange borders.
				//console.log( 'CLOSEST: apaczka_calculate_radio' );
				alsendo_connect_add_border_to_selected_service();
			}

			if (target.classList.contains( 'apaczka_calculate_radio' )) {
				if (typeof (target.value) !== 'undefined') {
					let id = +target.value;
					if (id === 50 || id === 86) {
						$( '#deliver_to_any_shipping_point' ).show();
					} else {
						$( '#deliver_to_any_shipping_point' ).hide();
					}
				}
			}

			if ( target.hasAttribute( 'id' ) ) {
				if (target.getAttribute( 'id' ) === 'ecolet_get_order_details') {
					e.preventDefault();
					console.log( 'ecolet_get_order_details' );

					$( '#json-display-alsendo' ).text( '' );
					$( '#json-display-alsendo' ).css( 'display', 'none' );

					let data = {
						action: 'alsendo_connect',
						alsendo_connect_action: 'ecolet_get_order',
						security: $( '#alsendo_connect_order_metabox_nonce' ).val(),
						ecolet_id: target.getAttribute( 'data-ecolet-id' )
					};

					console.log( data );

					$.ajax(
						{
							type: 'POST',
							url: alsendo_admin.ajaxurl,
							data: data,
							beforeSend: function () {
								$( '#ecolet_get_order_details' ).prop( 'disabled', true );
								$( '#alsendo_connect_preloader' ).css( 'display', 'block' );
								$( '#ecolet_some_error' ).remove();
							},
							success: function (response) {
								console.log( "Ecolet ecolet_get_order_details response:" );
								console.log( response );
								if ( 0 !== response && '0' !== response ) {
									if ( 'success' in response && response.success) {
										if ('data' in response /*&& 'data' in response.data*/) {
											// let order_data = JSON.parse( response.data.data );
											// console.log( response.data );
											let formatted_JSON = formatJSON( response.data );
											$( '#json-display-alsendo' ).text( formatted_JSON );
											$( '#json-display-alsendo' ).css( 'display', 'block' );

										}
									}
								}

							},
							error: function (jqXHR, textStatus, errorThrown) {
								console.log( "Error response on Ecolet get order details:" );
								console.log( textStatus );
								console.log( 'Error: ' + errorThrown + ' ' + jqXHR.responseText );
							},
							complete: function (response) {
								$( '#ecolet_get_order_details' ).prop( 'disabled', false );
								$( '#alsendo_connect_preloader' ).css( 'display', 'none' );

							}
						}
					);
				}

				if (target.getAttribute( 'id' ) === 'zaslat_get_order_details') {
					e.preventDefault();
					console.log( 'zaslat_get_order_details' );

					$( '#json-display-alsendo' ).text( '' );
					$( '#json-display-alsendo' ).css( 'display', 'none' );

					let data = {
						action: 'alsendo_connect',
						alsendo_connect_action: 'zaslat_get_order',
						security: $( '#alsendo_connect_order_metabox_nonce' ).val(),
						zaslat_id: target.getAttribute( 'data-zaslat-id' )
					};

					console.log( data );

					$.ajax(
						{
							type: 'POST',
							url: alsendo_admin.ajaxurl,
							data: data,
							beforeSend: function () {
								$( '#zaslat_get_order_details' ).prop( 'disabled', true );
								$( '#alsendo_connect_preloader' ).css( 'display', 'block' );
							},
							success: function (response) {
								console.log( "Zaslat ecolet_get_order_details response:" );
								console.log( response );
								if ( 0 !== response ) {
									if ( 'success' in response && response.success) {
										if ('data' in response && 'data' in response.data) {
											// let order_data = JSON.parse( response.data.data );.

											let formatted_JSON = formatJSON( response.data.data );
											$( '#json-display-alsendo' ).text( formatted_JSON );
											$( '#json-display-alsendo' ).css( 'display', 'block' );

										} else {
											if ('data' in response ) {
												// let order_data = JSON.parse( response.data.data );.

												let formatted_JSON = formatJSON( response.data );
												$( '#json-display-alsendo' ).text( formatted_JSON );
												$( '#json-display-alsendo' ).css( 'display', 'block' );

											}
										}

									} else {
										if ('data' in response && 'error' in response.data) {

											console.log( response.data.error );
											let status_color = '#e03636';
											let message      = '<br>' + alsendo_process_api_response( response.data.error );
											$( '#ecolet_wc_order_id' ).after( '<span id="alsendo_zaslat_get_details_message" style="display:block;margin-top:20px;font-weight:bold;color:' + status_color + '">' + message + '</span>' );
										}

									}
								}

							},
							error: function (jqXHR, textStatus, errorThrown) {
								console.log( "Error response on Zaslat get details" );
								console.log( textStatus );
								console.log( 'Error: ' + errorThrown + ' ' + jqXHR.responseText );
							},
							complete: function (response) {
								$( '#zaslat_get_order_details' ).prop( 'disabled', false );
								$( '#alsendo_connect_preloader' ).css( 'display', 'none' );

							}
						}
					);
				}

				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';
					}
				}
			}
		},
		false
	);


	document.addEventListener(
		'change',
		function (e) {
			e = e || window.event;
			var target = e.target;
			if ( target.hasAttribute('data-key') ) {
				if( 'parcel_type' === target.getAttribute('data-key') ) {
					console.log('change apaczka parcel type');
					alsendoMetaboxChangeParcelTypeActions(target);
				}
			}
		}
	);


	$('body').on('click', '.alsendo-warehouse-close-notice', function() {
		$('#alsendo-warehouse-add-notice').fadeOut(300, function() {
			$(this).remove();
		});
	});




})( jQuery );