(function ($) {

	$( document ).ready(
		function () {

			console.log( inpost_rates_table.saved_templates );

			let method_main_prefix = '';

			$( '.wc-settings-sub-title' ).each(
				function (ind, elem) {
					// Check if element has ID attribute.
					if ($( elem ).attr( 'id' )) {
						var id = $( elem ).attr( 'id' );
						// Check if last character is a digit.
						var last_char = id.slice( -1 );
						if (/\d/.test( last_char )) {
							// Remove last character if it's a digit.
							let new_id         = id.slice( 0, -1 );
							method_main_prefix = new_id;
						}
					}
				}
			);

			let insurance_checkbox = $( 'input:checkbox[id$="insurance_inpost_intl"]' );
			let insurance_value    = $( 'input[id$="insurance_value_inpost_intl"]' );

			if ( typeof insurance_checkbox != 'undefined' && insurance_checkbox !== null ) {
				if ( $( insurance_checkbox ).prop( 'checked' ) ) {
					$( insurance_value ).closest( 'tr' ).hide();
				} else {
					$( insurance_value ).closest( 'tr' ).show();
				}

				$( insurance_checkbox ).on(
					'change',
					function () {
						if ( this.checked ) {
							$( insurance_value ).closest( 'tr' ).hide();
						} else {
							$( insurance_value ).closest( 'tr' ).show();
						}
					}
				);
			}

			let rates_table = $( '.inpost-international-rates-settings' );
			if ( typeof rates_table == 'undefined' || rates_table === null ) {
				return;
			}

			const INPOST_INTL_PLUGIN_SLUG = window.inpost_rates_table.plugin_slug;
			let flat_rate_option_selector = '.' + INPOST_INTL_PLUGIN_SLUG + '_flat_rate';

			let flat_rate_option = $( flat_rate_option_selector );
			if ( typeof flat_rate_option != 'undefined' && flat_rate_option !== null ) {

				$( flat_rate_option ).on(
					'change',
					function () {
						display_rates();
					}
				);
				display_rates();
			}

			const { __, _x, _n, sprintf } = window.wp.i18n;
			const warning                 = __( 'Are you sure?', 'inpost-international' );

			let $tbody    = $( '.' + INPOST_INTL_PLUGIN_SLUG + '_rates' ).find( 'tbody' );
			let append_id = $tbody.find( 'tr' ).size();

			let size = $tbody.find( 'tr' ).size();
			if ( size === 0 ) {
				append_id = append_id + 1;
				append_row( append_id );
			}
			$( '#insert_rate' ).click(
				function () {
					append_id = append_id + 1;
					append_row( append_id );
					$( '#rates_' + append_id + '_min' ).focus();
					return false;
				}
			);
			$( document ).on(
				'click',
				'.inpost_intl_delete_rate',
				function () {
					if (confirm( warning )) {
						$( this ).closest( 'tr' ).remove();
					}
					return false;
				}
			);

			// show-hide size fields.
			let select_position = $( '.' + INPOST_INTL_PLUGIN_SLUG + '_based_on' ).val();

			show_hide_gabaryt_rows( select_position );

			$( '.' + INPOST_INTL_PLUGIN_SLUG + '_based_on' ).on(
				'change',
				function () {
					show_hide_gabaryt_rows( $( this ).val() );
				}
			);

			// show hide fields for Flexible shipping integration.
			let fs_integration_select            = $( '#woocommerce_flexible_shipping_fs_inpost_international_method' );
			let fs_integration_insurance_field_1 = $( 'label[for="woocommerce_flexible_shipping_fs_insurance_inpost_intl"]' );
			let fs_integration_insurance_field_2 = $( 'label[for="woocommerce_flexible_shipping_fs_insurance_value_inpost_intl"]' );

			if ($( fs_integration_select ).val() !== '0') {
				$( fs_integration_insurance_field_1 ).closest( 'tr' ).show();
				$( fs_integration_insurance_field_2 ).closest( 'tr' ).show();
			} else {
				$( fs_integration_insurance_field_1 ).closest( 'tr' ).hide();
				$( fs_integration_insurance_field_2 ).closest( 'tr' ).hide();
			}

			$( fs_integration_select ).on(
				'change',
				function () {
					if ($( this ).val() !== '0') {
						$( fs_integration_insurance_field_1 ).closest( 'tr' ).show();
						$( fs_integration_insurance_field_2 ).closest( 'tr' ).show();
					} else {
						$( fs_integration_insurance_field_1 ).closest( 'tr' ).hide();
						$( fs_integration_insurance_field_2 ).closest( 'tr' ).hide();
					}
				}
			);

			$( 'input[name="woocommerce_inpost_international_automated_locker_point_logo_selected_radio"], input[name="woocommerce_inpost_international_courier_logo_selected_radio"]' ).on(
				'change',
				function (e) {
					e.preventDefault();
					let logo_name = $( this ).val();
					console.log( logo_name );
					$( '#inpost_intl_logo_selected' ).val( logo_name );
				}
			);

			let selector_id = method_main_prefix + 'logo_custom';
			let custom_logo = $( '#' + selector_id ).val();
			if ( custom_logo ) {
				$( '#inpost_intl_logo_custom_preview' ).attr( 'src', custom_logo ).css( 'display', 'block' );
				$( '#inpost-intl-logo-upload-btn' ).text( 'Change' );
			}

			let mediaUploader;

			$( '#inpost-intl-logo-upload-btn' ).on(
				'click',
				function (e) {
					e.preventDefault();

					if ( mediaUploader ) {
						mediaUploader.open();
						return;
					}

					mediaUploader = wp.media.frames.file_frame = wp.media(
						{
							title: 'Choose a shipping method logo',
							button: {
								text: 'Choose Image'
							},
							multiple:false
						}
					);

					mediaUploader.on(
						'select',
						function () {
							let attachment = mediaUploader.state().get( 'selection' ).first().toJSON();
							// $( '#inpost_intl_logo_custom' ).val( attachment.url );
							$( '#' + selector_id ).val( attachment.url );
							$( '#inpost_intl_logo_custom_preview' ).attr( 'src', attachment.url ).css( 'display', 'block' );
							$( '#inpost-intl-logo-upload-btn' ).text( 'Change' );
							console.log( attachment.url );
						}
					);
					mediaUploader.open();
				}
			);

		}
	);

	function display_rates() {
		const INPOST_INTL_PLUGIN_SLUG = window.inpost_rates_table.plugin_slug;

		if ($( '.' + INPOST_INTL_PLUGIN_SLUG + '_flat_rate' ).prop( 'checked' )) {

			$( '.' + INPOST_INTL_PLUGIN_SLUG + '_cost_per_order' ).closest( 'tr' ).css( 'display', 'table-row' );
			$( '.' + INPOST_INTL_PLUGIN_SLUG + '_based_on' ).closest( 'tr' ).css( 'display', 'none' );
			$( '.' + INPOST_INTL_PLUGIN_SLUG + '_rates' ).closest( 'tr' ).css( 'display', 'none' );

			$( '.' + INPOST_INTL_PLUGIN_SLUG + '_gabaryt_a' ).closest( 'tr' ).css( 'display', 'none' );
			$( '.' + INPOST_INTL_PLUGIN_SLUG + '_gabaryt_b' ).closest( 'tr' ).css( 'display', 'none' );
			$( '.' + INPOST_INTL_PLUGIN_SLUG + '_gabaryt_c' ).closest( 'tr' ).css( 'display', 'none' );

			inpost_intl_wait_element( '.inpost-international-rates-settings' ).then(
				function (elm) {
					$( elm ).hide();
					$( '.' + INPOST_INTL_PLUGIN_SLUG + '_rates_table_title' ).hide();
				}
			);

			inpost_intl_wait_element( '.inpost-international-rates-settings_templates' ).then(
				function (elm) {
					$( elm ).hide();
					$( '.' + INPOST_INTL_PLUGIN_SLUG + '_rates_table_title' ).hide();
				}
			);

		} else {

			$( '.' + INPOST_INTL_PLUGIN_SLUG + '_cost_per_order' ).closest( 'tr' ).css( 'display', 'none' );
			$( '.' + INPOST_INTL_PLUGIN_SLUG + '_based_on' ).closest( 'tr' ).css( 'display', 'table-row' );
			$( '.' + INPOST_INTL_PLUGIN_SLUG + '_rates' ).closest( 'tr' ).css( 'display', 'block' );

			$( '.' + INPOST_INTL_PLUGIN_SLUG + '_rates_table_title' ).show();

			let select_position = $( '.' + INPOST_INTL_PLUGIN_SLUG + '_based_on' ).val();

			if (select_position === 'parcel_templates') {

				$( '.inpost-international-rates-settings_templates' ).css( 'display', 'table-row' );
				$( '#inpost-international-rates-table_templates' ).css( 'display', 'block' );

				inpost_intl_wait_element( '.inpost-international-rates-settings' ).then(
					function (elm) {
						$( elm ).hide();
						$( '#inpost-international-rates-table' ).css( 'display', 'none' );
					}
				);

			} else {

				inpost_intl_wait_element( '.inpost-international-rates-settings_templates' ).then(
					function (elm) {
						$( elm ).hide();
						$( '#inpost-international-rates-table_templates' ).css( 'display', 'none' );
					}
				);

				$( '.inpost-international-rates-settings' ).css( 'display', 'table-row' );
				$( '#inpost-international-rates-table' ).css( 'display', 'block' );
			}
		}
	}

	function show_hide_gabaryt_rows(select_position) {
		const INPOST_INTL_PLUGIN_SLUG = window.inpost_rates_table.plugin_slug;

		if (select_position === 'parcel_templates') {

			$( '.inpost-international-rates-settings_templates' ).css( 'display', 'table-row' );
			$( '#inpost-international-rates-table_templates' ).css( 'display', 'block' );

			$( '.inpost-international-rates-settings' ).css( 'display', 'none' );
			$( '#inpost-international-rates-table' ).css( 'display', 'none' );

		} else {
			$( '#inpost_intl_dimensions_warning' ).parent( 'p' ).hide();

			$( '.inpost-international-rates-settings_templates' ).css( 'display', 'none' );
			$( '#inpost-international-rates-table_templates' ).css( 'display', 'none' );

			$( '.inpost-international-rates-settings' ).css( 'display', 'table-row' );
			$( '#inpost-international-rates-table' ).css( 'display', 'block' );
		}
	}

	function append_row( id ) {
		const INPOST_INTL_PLUGIN_SLUG = window.inpost_rates_table.plugin_slug;

		const { __, _x, _n, sprintf } = wp.i18n;
		const text                    = __( 'Delete row', 'inpost-international' );
		let code                      = '<tr class="new">\
                    <td class="sort"></td>\
                    <td>\
                        <input id="rates_' + id + '_min" class="input-text regular-input" type="number" style="" value="" placeholder="0.00" step="any" min="0" name=rates[' + id + '][min]>\
                    </td>\
                    <td>\
                        <input class="input-text regular-input" type="number" style="" value="" placeholder="0.00" step="any" min="0" name=rates[' + id + '][max]>\
                    </td>\
                    <td>\
                        <input class="input-text regular-input" type="number" style="" value="" placeholder="0.00" step="any" min="0" name=rates[' + id + '][cost]>\
                    </td>\
                    <td>\
                        <a id="delete_rate_' + id + '" href="#" class="button inpost_intl_delete_rate" data-id="' + id + '">' + text + '</a>\
                    </td>\
                </tr>';
		let $tbody                    = $( '.' + INPOST_INTL_PLUGIN_SLUG + '_rates' ).find( 'tbody' );
		$tbody.append( code );
	}

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

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

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

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

})( jQuery );
