function dhl_polska_update_point_fields( point ) {
	var point_name = document.querySelector( '.js--dhl-polska-point-name-text' );
	var api_error_field = document.querySelector( '.js--dhl-polska-api-error' );

	if ( document.querySelector( '.js--parcelshop-id' ) ) {
		document.querySelector( '.js--parcelshop-id' ).value = point.id || '';
	}
	if ( document.querySelector( '.js--parcelshop-sap' ) ) {
		document.querySelector( '.js--parcelshop-sap' ).value = point.sap || '';
	}
	if ( document.querySelector( '.js--parcelshop-name' ) ) {
		document.querySelector( '.js--parcelshop-name' ).value = point.name || '';
	}
	if ( document.querySelector( '.js--parcelshop-zip' ) ) {
		document.querySelector( '.js--parcelshop-zip' ).value = point.zip || '';
	}
	if ( document.querySelector( '.js--parcelshop-street' ) ) {
		document.querySelector( '.js--parcelshop-street' ).value = point.street || '';
	}
	if ( document.querySelector( '.js--parcelshop-city' ) ) {
		document.querySelector( '.js--parcelshop-city' ).value = point.city || '';
	}
	if ( document.querySelector( '.js--parcelshop-streetNo' ) ) {
		document.querySelector( '.js--parcelshop-streetNo' ).value = point.streetNo || '';
	}
	if ( document.querySelector( '.js--parcelshop-houseNo' ) ) {
		document.querySelector( '.js--parcelshop-houseNo' ).value = point.houseNo || '';
	}

	if ( point_name ) {
		var lines = [];
		var name_line = ( point.name || '' ).trim();
		var street_line = ( ( point.street || '' ) + ' ' + ( point.streetNo || '' ) ).trim();
		var city_line = ( ( point.zip || '' ) + ' ' + ( point.city || '' ) ).trim();
		var sap_line = ( point.sap || point.id || '' ).trim();

		if ( name_line ) {
			lines.push( name_line );
		}
		if ( street_line ) {
			lines.push( street_line );
		}
		if ( city_line ) {
			lines.push( city_line );
		}
		if ( sap_line ) {
			lines.push( '(' + sap_line + ')' );
		}

		lines = lines.filter(
			function ( line ) {
				return line.trim() !== '';
			}
		);

		point_name.textContent = '';
		lines.forEach(
			function ( line, index ) {
				point_name.appendChild( document.createTextNode( line ) );
				if ( index !== lines.length - 1 ) {
					point_name.appendChild( document.createElement( 'br' ) );
				}
			}
		);
	}

	if ( api_error_field ) {
		api_error_field.value = 'no';
	}

	var popup = document.querySelector( '.js--popup-dhl-polska' );
	if ( popup ) {
		popup.style.display = 'none';
	}

	if ( window.jQuery ) {
		jQuery( 'body' ).trigger( 'update_checkout' );
	}
}

function dhl_polska_normalize_point( parcel ) {
	return {
		id: parcel.id || '',
		sap: parcel.sap || '',
		name: parcel.name || '',
		zip: parcel.zip || parcel.postal_code || '',
		street: parcel.street || '',
		city: parcel.city || '',
		streetNo: parcel.streetNo || parcel.street_no || '',
		houseNo: parcel.houseNo || parcel.house_no || ''
	};
}

function dhl_polska_choosen_point( parcel ) {
	var point = dhl_polska_normalize_point( parcel );
	dhl_polska_update_point_fields( point );
}

function dhl_polska_error_map_init() {
	var api_error_field = document.querySelector( '.js--dhl-polska-api-error' );
	var popup = document.querySelector( '.js--popup-dhl-polska' );

	if ( popup ) {
		popup.style.display = 'none';
	}
	if ( api_error_field ) {
		api_error_field.value = 'yes';
	}

	if ( window.__jsDHLPolskaCheckoutVars && __jsDHLPolskaCheckoutVars.l10n ) {
		alert( __jsDHLPolskaCheckoutVars.l10n.api_error );
	}
}

function dhl_polska_is_cod_enabled( cod_value ) {
	if ( typeof cod_value === 'boolean' ) {
		return cod_value;
	}

	if ( typeof cod_value === 'number' ) {
		return cod_value === 1;
	}

	var normalized = ( cod_value || '' ).toString().trim().toLowerCase();
	return [ 'yes', 'true', '1', 't' ].indexOf( normalized ) !== -1;
}

function dhl_polska_display_map( country, parcel_weight, point_type, pickup_cod ) {
	if ( ! window.__jsDHLPolskaCheckoutVars ) {
		return;
	}

	var container = document.querySelector( '.js--dhl-polska-popup-container' );

	if ( container === null ) {
		container = document.createElement( 'div' );
		container.classList.add( 'js--dhl-polska-popup-container' );
		document.body.appendChild( container );
	}

	var map_url = new URL( __jsDHLPolskaCheckoutVars.map_url );
	var pathname = map_url.pathname.replace( /\/$/, '' );
	map_url.pathname = pathname + '/mapa';

	var params = new URLSearchParams();
	var normalized_country = ( country || '' ).toString().trim().toUpperCase();
	if ( country && 'PL' !== normalized_country ) {
		params.append( 'country', country );
	}
	if ( __jsDHLPolskaCheckoutVars.locale ) {
		params.append( 'locale', __jsDHLPolskaCheckoutVars.locale );
	}
	if ( parcel_weight ) {
		params.append( 'parcel_weight', parcel_weight );
	}
	var resolved_point_type = point_type || __jsDHLPolskaCheckoutVars.point_type || '';
	if ( normalized_country && 'PL' !== normalized_country && resolved_point_type ) {
		params.append( 'ptype', resolved_point_type );
	}
	if ( dhl_polska_is_cod_enabled( pickup_cod ) ) {
		params.append( 'options_pickup_cod', 'T' );
	}
	map_url.search = params.toString();

	var popup = document.querySelector( '.js--popup-dhl-polska' );
	if ( popup === null ) {
		popup = document.createElement( 'div' );
		popup.id = 'dhl_polska_popup';
		popup.classList.add( 'js--popup-dhl-polska' );
		container.appendChild( popup );

		var close_button = document.createElement( 'a' );
		close_button.href = '#0';
		close_button.textContent = __jsDHLPolskaCheckoutVars.l10n.close_popup;
		close_button.classList.add( 'js--popup-close-button' );
		popup.appendChild( close_button );
	}

	var iframe = popup.querySelector( '#dhl_polska_map' );
	if ( iframe === null ) {
		iframe = document.createElement( 'iframe' );
		iframe.id = 'dhl_polska_map';
		iframe.setAttribute( 'allow', 'geolocation' );
		popup.appendChild( iframe );
	}

	iframe.src = map_url.toString();
	popup.style.display = 'block';
}

function dhl_polska_get_selected_shipping_method() {
	var selected_input = document.querySelector( 'input[name^="shipping_method"]:checked' );
	if ( selected_input && selected_input.value ) {
		return selected_input.value;
	}

	var selected_select = document.querySelector( 'select[name^="shipping_method"]' );
	if ( selected_select && selected_select.value ) {
		return selected_select.value;
	}

	return '';
}

function dhl_polska_get_point_type_from_link( select_point ) {
	var point_type = select_point.getAttribute( 'data-ptype' );
	var point_types = select_point.getAttribute( 'data-point-types' );

	if ( point_types ) {
		try {
			var point_types_map = JSON.parse( point_types );
			var chosen_method = dhl_polska_get_selected_shipping_method();
			if ( chosen_method && point_types_map && point_types_map[ chosen_method ] ) {
				point_type = point_types_map[ chosen_method ];
			}
		} catch ( e ) {
			return point_type;
		}
	}

	return point_type;
}

function dhl_polska_get_cod_from_link( select_point ) {
	var cod_value = select_point.getAttribute( 'data-cod' );
	var cod_map = select_point.getAttribute( 'data-point-cod' );

	if ( cod_map ) {
		try {
			var cod_map_data = JSON.parse( cod_map );
			var chosen_method = dhl_polska_get_selected_shipping_method();
			if ( chosen_method && cod_map_data && cod_map_data[ chosen_method ] !== undefined ) {
				cod_value = cod_map_data[ chosen_method ];
			}
		} catch ( e ) {
			return cod_value;
		}
	}

	return cod_value;
}

function dhl_polska_get_checkout_country_from_fields() {
	var shipping_country_field = document.querySelector( 'select#shipping_country, input#shipping_country, select[name="shipping_country"], input[name="shipping_country"]' );
	if ( shipping_country_field && shipping_country_field.value ) {
		return shipping_country_field.value;
	}

	var billing_country_field = document.querySelector( 'select#billing_country, input#billing_country, select[name="billing_country"], input[name="billing_country"]' );
	if ( billing_country_field && billing_country_field.value ) {
		return billing_country_field.value;
	}

	return '';
}

function dhl_polska_get_point_context() {
	var select_point = document.querySelector( '.js--choose-point-dhl-polska' );
	var point_type = '';
	var country = '';

	if ( select_point ) {
		point_type = dhl_polska_get_point_type_from_link( select_point );
		country = select_point.getAttribute( 'data-country' ) || '';
	}

	if ( ! country ) {
		country = dhl_polska_get_checkout_country_from_fields();
	}

	return {
		method: dhl_polska_get_selected_shipping_method(),
		point_type: point_type,
		country: country
	};
}

function dhl_polska_should_clear_point_on_method_change( previous, current ) {
	if ( ! previous || ! current ) {
		return false;
	}

	if ( ! previous.method || ! current.method || previous.method === current.method ) {
		return false;
	}

	var normalized_country = ( current.country || previous.country || '' ).toString().trim().toUpperCase();
	if ( ! normalized_country || 'PL' === normalized_country ) {
		return true;
	}

	if ( ! previous.point_type && ! current.point_type ) {
		return false;
	}

	return previous.point_type !== current.point_type;
}

window.dhl_polska_choosen_point = dhl_polska_choosen_point;
window.dhl_polska_display_map = dhl_polska_display_map;
window.dhl_polska_error_map_init = dhl_polska_error_map_init;

window.addEventListener(
	'message',
	function ( event ) {
		if ( ! window.__jsDHLPolskaCheckoutVars ) {
			return;
		}

		if ( event.data && event.origin && event.origin === __jsDHLPolskaCheckoutVars.map_url ) {
			var point = null;

			if ( typeof event.data === 'object' ) {
				point = event.data;
			} else {
				try {
					point = JSON.parse( event.data );
				} catch ( e ) {
					return;
				}
			}

			if ( point && ( point.sap || point.id ) ) {
				if ( typeof window.dhl_polska_choosen_point === 'function' ) {
					window.dhl_polska_choosen_point( point );
				} else {
					dhl_polska_choosen_point( point );
				}
			}
		}
	}
);

document.addEventListener(
	'DOMContentLoaded',
	function () {
		var previous_context = dhl_polska_get_point_context();

		if ( window.jQuery ) {
			jQuery( document.body ).on(
				'updated_checkout',
				function () {
					var current_context = dhl_polska_get_point_context();
					if ( dhl_polska_should_clear_point_on_method_change( previous_context, current_context ) ) {
						dhl_polska_update_point_fields( {} );
					}
					previous_context = current_context;
				}
			);
		}

		document.addEventListener(
			'click',
			function ( e ) {
				var select_point = e.target.closest( '.js--choose-point-dhl-polska' );
				if ( select_point ) {
					e.preventDefault();
					var country = select_point.getAttribute( 'data-country' );
					var parcel_weight = select_point.getAttribute( 'data-parcel_weight' );
					var point_type = dhl_polska_get_point_type_from_link( select_point );
					var pickup_cod = dhl_polska_get_cod_from_link( select_point );
					dhl_polska_display_map( country, parcel_weight, point_type, pickup_cod );

					return;
				}

				if ( e.target.classList.contains( 'js--popup-close-button' ) ) {
					var popup = document.querySelector( '.js--popup-dhl-polska' );
					if ( popup ) {
						popup.style.display = 'none';
					}
				}
			}
		);
	}
);
