jQuery( document ).ready( function () {

	jQuery( '.elex_simple_select' ).select2();

	jQuery( '#elex_mv_admin_as_vendor_state' ).select2( {
		placeholder:        'Search State',
		minimumInputLength: 2,
	} );

	// Load states for the given country code via AJAX.
	function loadStates( countryCode ) {
		var stateSelect = jQuery( '#elex_mv_admin_as_vendor_state' );

		stateSelect.empty();

		jQuery.ajax( {
			url:  ajaxurl,
			type: 'post',
			data: {
				action:  'elex_mv_load_states',
				country: countryCode,
				nonce:   elexMvStoreSetupParams.load_states_nonce,
			},
			success: function ( result ) {
				if ( result.data ) {
					stateSelect.parent().show();
					stateSelect.next( '.select2-container' ).show();
					stateSelect.append( result.data ).trigger( 'change' );
				} else {
					stateSelect.parent().hide();
					stateSelect.next( '.select2-container' ).hide();
				}
			},
		} );
	}

	jQuery( '#elex_mv_admin_as_vendor_country' ).on( 'change', function () {
		loadStates( jQuery( this ).val() );
	} );

	// Pre-load states if a country is already selected on page load.
	var initialCountry = jQuery( '#elex_mv_admin_as_vendor_country' ).val();
	if ( initialCountry ) {
		loadStates( initialCountry );
	}

	// Show/hide the "make me a vendor" form.
	jQuery( '.elex_mv_make_me_vendor_form' ).hide();
	jQuery( '#elex_mv_make_me_vendor_switch' ).on( 'change', function () {
		jQuery( '.elex_mv_make_me_vendor_form' ).toggle( this.checked );
	} );

	// International telephone input.
	var inputPhone = window.intlTelInput( document.querySelector( '#elex_mv_admin_as_vendor_phone_number' ), {
		autoPlaceholder: 'polite',
	} );

	function syncDialCode() {
		var data = inputPhone.getSelectedCountryData();
		jQuery( '#elex_mv_admin_as_vendor_dial_code' ).val( data.dialCode );
		jQuery( '#elex_mv_admin_as_vendor_country_iso' ).val( data.iso2 );
	}

	syncDialCode();
	document.querySelector( '#elex_mv_admin_as_vendor_phone_number' ).addEventListener( 'countrychange', syncDialCode );

} );
