
jQuery( document ).ready( function() {
	jQuery( '#elex-vendor-onboard-state' ).select2( {
		placeholder: 'Select State',
	} );

	// Function to load states based on the selected country
	function loadStates( countryCode ) {
		var stateSelect = jQuery( '#elex-vendor-onboard-state' );

		// Clear the current options
		stateSelect.empty();
		// Load new options based on the selected country
		return new Promise( function( resolve, reject ) {

			jQuery.ajax( {
				url:  elexMvOnboardStoreDetailsParams.ajax_url,
				type: 'post',
				data: {
					action:  'elex_mv_load_states',
					country: countryCode,
					nonce:   elexMvOnboardStoreDetailsParams.load_states_nonce,
				},
				success: function( result ) {
					if ( result.data ) {
						stateSelect.parent().show();
						stateSelect.append( '<option value=""></option>' );
						stateSelect.append( result.data );
						stateSelect.select2( 'destroy' );
						stateSelect.select2( { placeholder: 'Select State' } );
						resolve( true );
					} else {
						stateSelect.parent().hide();
						resolve( true );
					}
				},
			} );
		} );
	}

	// Event listener to load states when the country changes
	jQuery( '#elex-vendor-onboard-country' ).on( 'change', function() {
		var countryCode = jQuery( this ).val();
		loadStates( countryCode );
	} );

	// Load states on page load (if a country is already selected)
	var countryCode = jQuery( '#elex-vendor-onboard-country' ).val();
	if ( countryCode ) {
		loadStates( countryCode ).then( function() {
			var stateCode = elexMvOnboardStoreDetailsParams.state_code;
			if ( stateCode ) {
				jQuery( '#elex-vendor-onboard-state' ).val( stateCode ).trigger( 'change' );
			}
		} );
	}

	var input_phone_number = window.intlTelInput( document.querySelector( '#elex-vendor-onboard-number' ), { autoPlaceholder: 'polite' } );

	input_phone_number.setCountry( elexMvOnboardStoreDetailsParams.country_iso );
} );
