"use strict";Object.defineProperty(exports, "__esModule", {value: true});


var _chunkZ6EUSUADcjs = require('./chunk-Z6EUSUAD.cjs');

// src/hooks/useFields.tsx
var _core = require('@uma-sdk/core');
var _deepobjectdiff = require('deep-object-diff');
var _lodashes = require('lodash-es');
var _react = require('react');
var 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."
};
var regexp = {
  phone: /^[2-9]{1}[0-9]{9}$/,
  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}$/
};
var v = {
  email: (msg = defaultMsgs.email) => (value) => !regexp.email.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) => !_core.isValidUmaAddress.call(void 0, value) ? msg : false,
  clabe: (msg = defaultMsgs.clabe) => (value) => !regexp.clabe.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;
  },
  matchesField: (msg = defaultMsgs.matchesField, targetField = "") => (value, fields) => {
    if (typeof targetField !== "string") {
      return msg;
    }
    return value !== (fields == null ? void 0 : fields[targetField]) ? msg : false;
  }
};
var defaultValidators = {
  password: [
    v.required("Password is required."),
    // This needs to stay as 8 otherwise users with old shorter passwords
    // can't login.
    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.")]
};
var f = {
  numeric: (value) => value.replace(/[^0-9]/g, "")
};
var 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) => _chunkZ6EUSUADcjs.__spreadProps.call(void 0, _chunkZ6EUSUADcjs.__spreadValues.call(void 0, {}, acc), { [key]: void 0 }),
    {}
  );
}
function reduceToFalse(fields) {
  return Object.keys(fields).reduce(
    (acc, key) => _chunkZ6EUSUADcjs.__spreadProps.call(void 0, _chunkZ6EUSUADcjs.__spreadValues.call(void 0, {}, acc), { [key]: false }),
    {}
  );
}
function reduceToFields(fields) {
  return Object.entries(fields).reduce((acc, [key, fieldValueArg]) => {
    if (typeof fieldValueArg === "string") {
      return _chunkZ6EUSUADcjs.__spreadProps.call(void 0, _chunkZ6EUSUADcjs.__spreadValues.call(void 0, {}, acc), { [key]: fieldValueArg });
    }
    return _chunkZ6EUSUADcjs.__spreadProps.call(void 0, _chunkZ6EUSUADcjs.__spreadValues.call(void 0, {}, acc), { [key]: fieldValueArg[0] });
  }, {});
}
function useFields(defaultFieldsFn, deps = []) {
  const defaultFields = _react.useMemo.call(void 0, defaultFieldsFn, deps);
  const prevDefaultFields = _react.useRef.call(void 0, defaultFields);
  const [fields, setFields] = _react.useState.call(void 0, reduceToFields(defaultFields));
  const [fieldErrors, setFieldErrors] = _react.useState.call(void 0, reduceToUndef(defaultFields));
  const [blurredFields, setBlurredFields] = _react.useState.call(void 0, 
    reduceToFalse(defaultFields)
  );
  const checkFieldForError = _react.useCallback.call(void 0, 
    (fieldName, fieldValue) => {
      const defaultField = defaultFields[fieldName];
      const customValidators = typeof defaultField === "string" ? void 0 : defaultField[1];
      const fieldError = getFirstFieldError(
        fieldName,
        fieldValue,
        fields,
        customValidators
      );
      if (blurredFields[fieldName]) {
        setFieldErrors((currentFieldErrors) => _chunkZ6EUSUADcjs.__spreadProps.call(void 0, _chunkZ6EUSUADcjs.__spreadValues.call(void 0, {}, currentFieldErrors), {
          [fieldName]: fieldError
        }));
      }
      return fieldError;
    },
    [defaultFields, blurredFields, fields]
  );
  const checkFieldsForError = _react.useCallback.call(void 0, 
    (fieldsToCheck) => {
      Object.entries(fieldsToCheck).forEach(([key, value]) => {
        checkFieldForError(key, value);
      });
    },
    [checkFieldForError]
  );
  const setFieldBlurred = _react.useCallback.call(void 0, 
    (fieldName) => {
      const newBlurredFields = _chunkZ6EUSUADcjs.__spreadProps.call(void 0, _chunkZ6EUSUADcjs.__spreadValues.call(void 0, {}, blurredFields), {
        [fieldName]: true
      });
      setBlurredFields(newBlurredFields);
    },
    [blurredFields]
  );
  const getSetFieldBlurred = _react.useCallback.call(void 0, 
    (fieldName) => {
      return () => {
        setFieldBlurred(fieldName);
      };
    },
    [setFieldBlurred]
  );
  const formatValue = _react.useCallback.call(void 0, (fieldName, value) => {
    const formatter = defaultFormatters[fieldName];
    return formatter ? formatter(value) : value;
  }, []);
  const mergeWithFields = _react.useCallback.call(void 0, 
    (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 _chunkZ6EUSUADcjs.__spreadProps.call(void 0, _chunkZ6EUSUADcjs.__spreadValues.call(void 0, {}, acc), {
              [key]: formatValue(key, val)
            });
          },
          {}
        );
        const updated = _chunkZ6EUSUADcjs.__spreadValues.call(void 0, _chunkZ6EUSUADcjs.__spreadValues.call(void 0, {}, latestFields), formatted);
        const fieldsChanged = JSON.stringify(updated) !== JSON.stringify(latestFields);
        return fieldsChanged ? updated : latestFields;
      });
      checkFieldsForError(updatedFields);
    },
    [checkFieldsForError, formatValue]
  );
  const allFieldsValid = _react.useMemo.call(void 0, () => {
    const valid = !Object.entries(fields).some(([fieldName, fieldValue]) => {
      const defaultField = defaultFields[fieldName];
      const customValidators = typeof defaultField === "string" ? void 0 : defaultField[1];
      const firstFieldError = getFirstFieldError(
        fieldName,
        fieldValue,
        fields,
        customValidators
      );
      return firstFieldError;
    });
    return valid;
  }, [fields, defaultFields]);
  const getUpdateField = _react.useCallback.call(void 0, 
    (fieldName) => {
      return (newValue) => {
        mergeWithFields({
          [fieldName]: formatValue(fieldName, newValue)
        });
      };
    },
    [mergeWithFields, formatValue]
  );
  _react.useEffect.call(void 0, () => {
    const newFields = {};
    const diffProps = _deepobjectdiff.diff.call(void 0, prevDefaultFields.current, defaultFields);
    Object.entries(diffProps).forEach(([key, value]) => {
      if (typeof value === "string") {
        newFields[key] = value;
      } else if (_lodashes.isObject.call(void 0, 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]);
  _react.useEffect.call(void 0, () => {
    checkFieldsForError(fields);
  }, [blurredFields, fields, checkFieldsForError]);
  return {
    blurredFields,
    getUpdateField,
    allFieldsValid,
    fieldErrors,
    /* needs to be a new object to ensure downstream effects are notified on updates: */
    fields: _chunkZ6EUSUADcjs.__spreadValues.call(void 0, {}, fields),
    mergeWithFields,
    setFieldBlurred,
    getSetFieldBlurred,
    setFieldErrors
  };
}




exports.v = v; exports.useFields = useFields;
