Object.defineProperties(exports, {
	__esModule: { value: true },
	[Symbol.toStringTag]: { value: "Module" }
});
require("../chunk-BN4qSVkS.cjs");
let lodash_es = require("lodash-es");
let react = require("react");
let _uma_sdk_core = require("@uma-sdk/core");
let deep_object_diff = require("deep-object-diff");
//#region src/hooks/useFields.tsx
const defaultMsgs = {
	email: "Please enter a valid email address.",
	phone: "Please enter a valid phone number.",
	postalCode: "Please enter a valid zip code.",
	state: "Please enter a valid two-letter state abbreviation.",
	name: "Name must be at least three characters.",
	code: "Code must be eight characters long.",
	password: "Password must be at least 12 characters, must contain at least two types of characters: lowercase, uppercase, numbers, special",
	required: "This field is required.",
	umaAddress: "Please enter a valid UMA address.",
	matchesField: "Target field does not match.",
	clabe: "Please enter a valid CLABE.",
	upi: "Please enter a valid UPI.",
	domain: "Please enter a valid domain.",
	domainName: "Please enter a valid domain name.",
	url: "Please enter a valid URL.",
	digitsOnly: "Must contain only digits."
};
const regexp = {
	phone: /^[0-9]{7,15}$/,
	postalCode: /(^\d{5}$)|(^\d{5}-\d{4}$)/,
	email: /^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$/,
	state: /^(A[LKSZRAEP]|C[AOT]|D[EC]|F[LM]|G[AU]|HI|I[ADLN]|K[SY]|LA|M[ADEHINOPST]|N[CDEHJMVY]|O[HKR]|P[ARW]|RI|S[CD]|T[NX]|UT|V[AIT]|W[AIVY])$/,
	clabe: /^[0-9]{18}$/,
	upi: /^[a-zA-Z0-9.\-_]{2,256}@[a-zA-Z]{2,64}$/,
	domain: /^[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(\.[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+$/,
	domainName: /^[a-zA-Z0-9-]+$/,
	url: /^(https?:\/\/)?([\da-z.-]+)\.([a-z.]{2,6})([/\w .-]*)*\/?$/
};
const v = {
	email: (msg = defaultMsgs.email) => (value) => !regexp.email.test(value) ? msg : false,
	domain: (msg = defaultMsgs.domain) => (value) => !regexp.domain.test(value) || value.length > 253 ? msg : false,
	domainName: (msg = defaultMsgs.domainName) => (value) => !regexp.domainName.test(value) || value.length > 63 ? msg : false,
	url: (msg = defaultMsgs.url) => (value) => !regexp.url.test(value) ? msg : false,
	phone: (msg = defaultMsgs.phone) => (value) => !regexp.phone.test(value) ? msg : false,
	postalCode: (msg = defaultMsgs.postalCode) => (value) => !regexp.postalCode.test(value) ? msg : false,
	state: (msg = defaultMsgs.state) => (value) => !regexp.state.test(value) ? msg : false,
	name: (msg = defaultMsgs.name) => (value) => value.trim().length < 3 ? msg : false,
	code: (msg = defaultMsgs.code) => (value) => value.trim().length !== 8 ? msg : false,
	umaAddress: (msg = defaultMsgs.umaAddress) => (value) => !(0, _uma_sdk_core.isValidUmaAddress)(value) ? msg : false,
	clabe: (msg = defaultMsgs.clabe) => (value) => !regexp.clabe.test(value) ? msg : false,
	upi: (msg = defaultMsgs.upi) => (value) => !regexp.upi.test(value) ? msg : false,
	required: (msg = defaultMsgs.required) => (value) => value.trim() === "" ? msg : false,
	min: (msg, minLength = 3) => (value) => {
		const len = typeof minLength === "number" ? minLength : 3;
		return value.trim().length < len ? msg || `Must be at least ${len} characters long.` : false;
	},
	max: (msg, maxLength = 3) => (value) => {
		const len = typeof maxLength === "number" ? maxLength : 3;
		return value.trim().length > len ? msg || `Must be less than ${len} characters long.` : false;
	},
	length: (msg, length = 3) => (value) => {
		const len = typeof length === "number" ? length : 3;
		return value.trim().length !== len ? msg || `Must be ${len} characters long.` : false;
	},
	minLengthOrEmpty: (msg, length = 3) => (value) => {
		const len = typeof length === "number" ? length : 3;
		const trimmed = value.trim();
		return trimmed.length > 0 && trimmed.length < len ? msg || `Must be at least ${len} characters or empty.` : false;
	},
	matchesField: (msg = defaultMsgs.matchesField, targetField = "") => (value, fields) => {
		if (typeof targetField !== "string") return msg;
		return value !== fields?.[targetField] ? msg : false;
	},
	digitsOnly: (msg = defaultMsgs.digitsOnly) => (value) => value.length > 0 && !/^\d+$/.test(value) ? msg : false
};
const defaultValidators = {
	password: [v.required("Password is required."), v.min("Password must be at least eight characters.", 8)],
	city: [v.required("City is required.")],
	name: [v.required("Name is required."), v.name()],
	code: [v.required("Please enter a code."), v.code()],
	email: [v.required("Email is required."), v.email()],
	phoneNumber: [v.required("Phone number is required."), v.phone()],
	multiInput: [v.required("This field is required.")],
	birthdayDay: [v.min("Day is required.", 1)],
	birthdayMonth: [v.min("Day is required.", 1)],
	birthdayYear: [v.min("Day is required.", 4)],
	postalCode: [v.required("Zip code is required."), v.postalCode()],
	addressCountryCode: [v.required("Country code is required.")],
	addressLine1: [v.required("Address is required.")],
	addressLine2: [],
	addressCity: [v.required("City is required.")],
	addressState: [v.required("State is required.")],
	addressZipCode: [v.required("Zip code is required.")]
};
const f = { numeric: (value) => value.replace(/[^0-9]/g, "") };
const defaultFormatters = {
	birthdayDay: f.numeric,
	birthdayMonth: f.numeric,
	birthdayYear: f.numeric
};
function getFirstFieldError(fieldName, fieldValue, fields, validatorsArg) {
	if (typeof validatorsArg === "undefined" || validatorsArg === true) {
		const validators = defaultValidators[fieldName];
		if (validators) for (const validator of validators) {
			const errorMsg = validator(fieldValue, fields);
			if (errorMsg) return errorMsg;
		}
	} else if (typeof validatorsArg !== "undefined") {
		if (validatorsArg === false) return null;
		for (const validator of validatorsArg) {
			const errorMsg = validator(fieldValue, fields);
			if (errorMsg) return errorMsg;
		}
	}
	return null;
}
function reduceToUndef(fields) {
	return Object.keys(fields).reduce((acc, key) => ({
		...acc,
		[key]: void 0
	}), {});
}
function reduceToFalse(fields) {
	return Object.keys(fields).reduce((acc, key) => ({
		...acc,
		[key]: false
	}), {});
}
function reduceToFields(fields) {
	return Object.entries(fields).reduce((acc, [key, fieldValueArg]) => {
		if (typeof fieldValueArg === "string") return {
			...acc,
			[key]: fieldValueArg
		};
		return {
			...acc,
			[key]: fieldValueArg[0]
		};
	}, {});
}
function useFields(defaultFieldsFn, deps = []) {
	const defaultFields = (0, react.useMemo)(defaultFieldsFn, deps);
	const prevDefaultFields = (0, react.useRef)(defaultFields);
	const [fields, setFields] = (0, react.useState)(reduceToFields(defaultFields));
	const [fieldErrors, setFieldErrors] = (0, react.useState)(reduceToUndef(defaultFields));
	const [blurredFields, setBlurredFields] = (0, react.useState)(reduceToFalse(defaultFields));
	const checkFieldForError = (0, react.useCallback)((fieldName, fieldValue) => {
		const defaultField = defaultFields[fieldName];
		const fieldError = getFirstFieldError(fieldName, fieldValue, fields, typeof defaultField === "string" ? void 0 : defaultField[1]);
		/**
		* field must have been blurred at least once before we show any
		* validation error:
		*/
		if (blurredFields[fieldName]) setFieldErrors((currentFieldErrors) => ({
			...currentFieldErrors,
			[fieldName]: fieldError
		}));
		return fieldError;
	}, [
		defaultFields,
		blurredFields,
		fields
	]);
	const checkFieldsForError = (0, react.useCallback)((fieldsToCheck) => {
		Object.entries(fieldsToCheck).forEach(([key, value]) => {
			checkFieldForError(key, value);
		});
	}, [checkFieldForError]);
	const setFieldBlurred = (0, react.useCallback)((fieldName) => {
		setBlurredFields({
			...blurredFields,
			[fieldName]: true
		});
	}, [blurredFields]);
	const getSetFieldBlurred = (0, react.useCallback)((fieldName) => {
		return () => {
			setFieldBlurred(fieldName);
		};
	}, [setFieldBlurred]);
	const formatValue = (0, react.useCallback)((fieldName, value) => {
		const formatter = defaultFormatters[fieldName];
		return formatter ? formatter(value) : value;
	}, []);
	const mergeWithFields = (0, react.useCallback)((updatedFields) => {
		setFields((latestFields) => {
			const formatted = Object.entries(updatedFields).reduce((acc, [key, value]) => {
				const val = typeof value === "string" ? value : Array.isArray(value) && typeof value[0] === "string" ? value[0] : "";
				return {
					...acc,
					[key]: formatValue(key, val)
				};
			}, {});
			const updated = {
				...latestFields,
				...formatted
			};
			return JSON.stringify(updated) !== JSON.stringify(latestFields) ? updated : latestFields;
		});
		checkFieldsForError(updatedFields);
	}, [checkFieldsForError, formatValue]);
	const allFieldsValid = (0, react.useMemo)(() => {
		return !Object.entries(fields).some(([fieldName, fieldValue]) => {
			const defaultField = defaultFields[fieldName];
			return getFirstFieldError(fieldName, fieldValue, fields, typeof defaultField === "string" ? void 0 : defaultField[1]);
		});
	}, [fields, defaultFields]);
	const getUpdateField = (0, react.useCallback)((fieldName) => {
		return (newValue) => {
			mergeWithFields({ [fieldName]: formatValue(fieldName, newValue) });
		};
	}, [mergeWithFields, formatValue]);
	(0, react.useEffect)(() => {
		const newFields = {};
		const diffProps = (0, deep_object_diff.diff)(prevDefaultFields.current, defaultFields);
		Object.entries(diffProps).forEach(([key, value]) => {
			if (typeof value === "string") newFields[key] = value;
			else if ((0, lodash_es.isObject)(value)) Object.entries(value).forEach(([arrayKey, arrayValue]) => {
				if (arrayKey === "0" && typeof arrayValue === "string") newFields[key] = arrayValue;
			});
		});
		if (Object.keys(newFields).length > 0) mergeWithFields(newFields);
		prevDefaultFields.current = defaultFields;
	}, [defaultFields, mergeWithFields]);
	(0, react.useEffect)(() => {
		checkFieldsForError(fields);
	}, [
		blurredFields,
		fields,
		checkFieldsForError
	]);
	return {
		blurredFields,
		getUpdateField,
		allFieldsValid,
		fieldErrors,
		fields: { ...fields },
		mergeWithFields,
		checkFieldForError,
		setFieldBlurred,
		getSetFieldBlurred,
		setFieldErrors
	};
}
//#endregion
exports.default = useFields;
exports.v = v;
