/**
 * Utility functions for working with Gravity Forms fields
 */

/**
 * Get a field by ID from the form fields array
 *
 * @param fieldId The ID of the field to find
 * @return The field object or undefined if not found
 */
export function getFieldById(
	fieldId: string | number
): GravityFormsField | undefined {
	return window.form.fields.find((field) => field.id === Number(fieldId));
}

/**
 * Get the resource for an advanced inventory field
 *
 * @param field The field to get the resource for
 * @return The resource object or null if not found
 */
export function getAdvancedInventoryFieldResource(
	field: GravityFormsField
): Resource | null {
	const resources = window.gpi_inventory_page_strings.resources || {};
	const resourceId = field.gpiResource;
	return resourceId ? resources[resourceId] : null;
}

/**
 * Determines whether a field is a choice-based field
 *
 * @param field The field to check
 * @return Whether the field is choice-based
 */
export function isChoiceField(field: GravityFormsField): boolean {
	// List of input types that are considered choice-based
	const types = [
		'radio',
		'select',
		'checkbox',
		'multiselect',
		'product',
		'option',
	];

	// Check if the field has choices and its input type is in the list of choice input types
	return (
		Array.isArray(field.choices) &&
		field.choices.length > 0 &&
		types.includes(field.type)
	);
}
