import { React } from '@gravityforms/libraries';
import { slugify } from '@gravityforms/utils';

/**
 * @function getId
 * @description Get the id from the prefix and key provided.
 *
 * @since 5.5.0
 *
 * @param {string} prefix The id prefix.
 * @param {string} key    The id key.
 *
 * @return {string} The id.
 */
export const getId = ( prefix, key ) => slugify( `${ prefix }-${ key }` );

/**
 * @function convertGeodataToPhoneListItems
 * @description Convert the countries data to phone list items.
 *
 * @since 5.5.0
 *
 * @param {Array} countries The countries data.
 *
 * @return {Array} The augmented countries data.
 */
export const convertGeodataToPhoneListItems = ( countries ) => {
	return countries.map( ( country ) => {
		const { iso, name, calling_code: callingCode, flag } = country;
		const fullCallingCode = `+${ callingCode }`;

		return {
			searchValue: `${ name } ${ fullCallingCode } ${ iso }`,
			label: name,
			value: iso,
			beforeLabel: <span className="gform-phone__flag-icon">{ flag }</span>,
			afterLabel: <span className="gform-phone__country-code">{ fullCallingCode }</span>,
		};
	} );
};

/**
 * @function e164ToNumber
 * @description Convert an E.164 formatted phone number to a number.
 *
 * @since 5.5.0
 *
 * @throws {TypeError} If the input is not a string.
 *
 * @param {string} e164 The E.164 formatted phone number.
 *
 * @return {string} The phone number.
 */
export const e164ToNumber = ( e164 ) => {
	if ( typeof e164 !== 'string' ) {
		throw new TypeError( 'Input must be a string' );
	}
	return e164.replace( /^\+/, '' );
};

/**
 * @function numberToE164
 * @description Convert a phone number to E.164 format.
 *
 * @since 5.5.0
 *
 * @throws {TypeError} If the input is not a string.
 *
 * @param {string} number The phone number.
 *
 * @return {string} The E.164 formatted phone number.
 */
export const numberToE164 = ( number ) => {
	if ( typeof number !== 'string' ) {
		throw new TypeError( 'Input must be a string' );
	}
	return number.startsWith( '+' )
		? number
		: `+${ number }`;
};
