;
{
  try {
    let e = "undefined" != typeof window ? window : "undefined" != typeof global ? global : "undefined" != typeof globalThis ? globalThis : "undefined" != typeof self ? self : {}, n = new e.Error().stack;
    n && (e._sentryDebugIds = e._sentryDebugIds || {}, e._sentryDebugIds[n] = "9f13ee30-ffe6-4829-92d3-c0cc45a733a5", e._sentryDebugIdIdentifier = "sentry-dbid-9f13ee30-ffe6-4829-92d3-c0cc45a733a5");
  } catch (e) {
  }
}
;
import { jsxs, Fragment, jsx } from "preact/jsx-runtime";
import { useCallback, useState, useMemo, useEffect } from "preact/hooks";
import { useQuery } from "@tanstack/preact-query";
import { b as useApiContext, $ as httpPost, k as httpGet, u as useTranslation, r as Icon, p as useAnalyticsContext, a2 as translateStringOrObject, a0 as CountryCodes, aZ as getFormattingRegEx, a_ as SPECIAL_CHARS, a$ as trimValWithOneSpace, a3 as createLogger, au as hasText, am as matchesRegex, aq as isInvalidName, ap as hasRepeatedCharacters, b0 as isValidMinLength, b1 as chomeAndBanchiValidator, an as NO_ALPHABET_REGEX, ao as EMOJI_REGEX, b2 as ADDRESS_VALID_CHAR_REGEX, aa as useI18nContext, v as useExperimentsContext, ac as entriesOf, b3 as getMaxLengthByFieldAndCountry } from "./StoreProvider-CqQrndhS.js";
import { u as useForm } from "./useForm-BFLyeF0c.js";
import { c as createFormUtils } from "./formUtils-CwOJPw6N.js";
import { F as Field } from "./Field-BL3Mh7gm.js";
import { I as InputText } from "./InputText-DRSK56ma.js";
import { S as Select } from "./Select-DbIpx8xz.js";
import { u as useDebouncedCallback } from "./debouncedInputEvent-Cv2S512Y.js";
import { C as CountryField } from "./CountryField-DDFphSWX.js";
import { u as useDataset } from "./useDataset-DgIHjoGg.js";
import { d as datasetIdentifier } from "./datasetUtil-BHQp0-xL.js";
import { C as COUNTRIES_WITH_STATES_DATASET, c as getKeyForField, d as COUNTRIES_WITH_HOUSE_NUMBER_FIRST, g as getAddressSchemaForCountry, e as CONDENSED_ADDRESS_FIELDS } from "./utils-DmjdHPet.js";
import { a as validateNotEmptyOnBlur } from "./patternValidators-Bv0Mmhgd.js";
const getNestedTrustedFields = (field, data, trustedFields) => {
  if (trustedFields && data?.[field] && typeof data[field] === "object") {
    return trustedFields.reduce(
      (fields, trustedField) => {
        const splitField = trustedField.split(".");
        if (splitField[0] === field) {
          return [...fields, splitField[1]];
        }
        return fields;
      },
      []
    );
  }
  return [];
};
const mapAddressData = (verifiedBusiness) => ({
  address: verifiedBusiness.street ?? "",
  otherAddressInformation: verifiedBusiness.street2 ?? "",
  city: verifiedBusiness.city ?? "",
  postalCode: verifiedBusiness.zipCode ?? "",
  stateOrProvince: verifiedBusiness.state ?? ""
});
const isDateOlderThanAYear = (dateString) => {
  if (!dateString) {
    return false;
  }
  const inputDate = new Date(dateString);
  if (isNaN(inputDate.getTime())) {
    console.error(`Error: Invalid date format or value for: ${dateString}`);
    return false;
  }
  const oneYearAgo = /* @__PURE__ */ new Date();
  oneYearAgo.setFullYear(oneYearAgo.getFullYear() - 1);
  return inputDate.getTime() < oneYearAgo.getTime();
};
const cleanseAddress = async (legalEntityId, baseUrl, data) => {
  return httpPost(
    {
      baseUrl,
      path: `legalEntities/${legalEntityId}/addresses/cleanse`
    },
    data
  );
};
const useAddressCleanse = (data, options) => {
  const { rootLegalEntityId, baseUrl } = useApiContext();
  return useQuery({
    queryKey: ["addressCleanse", data],
    queryFn: () => cleanseAddress(rootLegalEntityId.value, baseUrl.value, data),
    ...options
  });
};
const useAddressCleanseImperatively = () => {
  const { rootLegalEntityId, baseUrl } = useApiContext();
  return useCallback(
    (data) => cleanseAddress(rootLegalEntityId.value, baseUrl.value, data),
    [baseUrl.value, rootLegalEntityId.value]
  );
};
const formatAddressForCleanse = ({
  address,
  city,
  country,
  postalCode
}) => {
  if (!address || !country) return void 0;
  return `${address} ${city ?? ""} ${country} ${postalCode ?? ""}`.trim();
};
const getProvidersStatus = async (legalEntityId, baseUrl, data) => {
  return httpPost(
    {
      baseUrl,
      path: `legalEntities/${legalEntityId}/configurations/providers/status`
    },
    data
  );
};
const useProviderStatus = (data, options) => {
  const { rootLegalEntityId, baseUrl } = useApiContext();
  return useQuery({
    queryKey: ["providersStatus", data],
    queryFn: () => getProvidersStatus(rootLegalEntityId.value, baseUrl.value, data),
    ...options
  });
};
const retrieveAddress = async (legalEntityId, baseUrl, addressId) => {
  return httpGet({
    baseUrl,
    path: `legalEntities/${legalEntityId}/addresses/${addressId}`
  });
};
const useRetrieveAddress = (addressId, options) => {
  const { rootLegalEntityId, baseUrl } = useApiContext();
  return useQuery({
    queryKey: ["retrieveAddress", addressId],
    queryFn: () => retrieveAddress(rootLegalEntityId.value, baseUrl.value, addressId),
    ...options
  });
};
const searchAddress = async (legalEntityId, baseUrl, data) => {
  return httpPost(
    {
      baseUrl,
      path: `legalEntities/${legalEntityId}/addresses`
    },
    data
  );
};
const useSearchAddress = (data, options) => {
  const { rootLegalEntityId, baseUrl } = useApiContext();
  return useQuery({
    queryKey: ["searchAddress", data],
    queryFn: () => searchAddress(rootLegalEntityId.value, baseUrl.value, data),
    ...options
  });
};
const getFormattedText = (highlightItems, text) => {
  const formattedText = [];
  let lastHighlightIndex = 0;
  if (highlightItems[0] === "") {
    return [text];
  }
  highlightItems.forEach((highlightValue) => {
    const highlightRange = highlightValue.split("-");
    const highlightInit = parseInt(highlightRange[0]);
    const highlightEnd = parseInt(highlightRange[1]);
    if (lastHighlightIndex < highlightInit) {
      const remain = text.substring(lastHighlightIndex, highlightInit);
      formattedText.push(`${remain}`);
    }
    const boldText = text.substring(highlightInit, highlightEnd);
    formattedText.push(
      /* @__PURE__ */ jsx("span", { className: "adyen-kyc-dropdown-search-element__description--highlight", children: boldText })
    );
    lastHighlightIndex = highlightEnd;
  });
  if (lastHighlightIndex < text.length) {
    formattedText.push(`${text.substring(lastHighlightIndex)}`);
  }
  return formattedText;
};
const getHighlightedText = ({
  text = "",
  highlight = "",
  description = ""
}) => {
  let formattedText = [];
  if (highlight === "") {
    if (description) {
      formattedText.push(`${text}, ${description}`);
    } else {
      formattedText.push(text);
    }
  } else {
    const highlightItems = highlight.split(";");
    formattedText = getFormattedText(highlightItems[0].split(","), text);
    if (highlightItems.length > 1) {
      formattedText.push(`, `);
      formattedText.push(/* @__PURE__ */ jsx(Fragment, { children: getFormattedText(highlightItems[1].split(","), description) }));
    } else if (description) {
      formattedText.push(`, ${description}`);
    }
  }
  return formattedText;
};
const SearchAddressItem = (item) => {
  const { t } = useTranslation("common");
  const { addressAmount } = item;
  return /* @__PURE__ */ jsxs(Fragment, { children: [
    /* @__PURE__ */ jsx("span", { className: "adyen-kyc-dropdown-search-element__description", children: getHighlightedText(item) }),
    addressAmount && /* @__PURE__ */ jsxs("div", { className: "adyen-kyc-dropdown-search-element__addresses", children: [
      addressAmount,
      " ",
      /* @__PURE__ */ jsxs("span", { className: "adyen-kyc-dropdown-search-element__addresses--text", children: [
        " ",
        t(($) => $["addresses"])
      ] }),
      /* @__PURE__ */ jsx(Icon, { name: "arrow-right", className: "adyen-kyc-dropdown-search-element__addresses--icon" })
    ] })
  ] });
};
const SearchAddress = ({
  addressText,
  country,
  labelKey,
  errorMessage,
  isValid,
  readOnly,
  optional,
  handleBlur,
  onAddressTextChange,
  onAutofillAddress
}) => {
  const { t } = useTranslation("common");
  const userEvents = useAnalyticsContext();
  const [textToSearch, setTextToSearch] = useState();
  const [showSearchList, setShowSearchList] = useState(false);
  const [selectedAddress, setSelectedAddress] = useState();
  const [drilldownContainerId, setDrilldownContainerId] = useState();
  const debouncedSetTextToSearch = useDebouncedCallback(setTextToSearch, 500);
  const searchAddressQuery = useSearchAddress(
    {
      text: textToSearch,
      country,
      container: drilldownContainerId
    },
    { enabled: showSearchList && Boolean(textToSearch) && Boolean(country) }
  );
  const retrieveAddressQuery = useRetrieveAddress(selectedAddress?.id ?? "", {
    enabled: Boolean(selectedAddress)
  });
  const results = useMemo(
    () => searchAddressQuery.data?.results?.map(formatAddressResult) ?? [],
    [searchAddressQuery.data?.results]
  );
  useEffect(() => {
    if (retrieveAddressQuery.data) {
      userEvents.addPageEvent("Success", {
        actionType: "select",
        actionLevel: "field",
        returnType: "backend",
        returnValue: "retrieveAddress"
      });
      onAutofillAddress(retrieveAddressQuery.data);
    }
  }, [retrieveAddressQuery.data]);
  const onSelectItem = useCallback(
    (selected) => {
      const selectedResult = results.find((i) => i.id === selected.id);
      if (!selectedResult) return;
      if (selectedResult.type === "Address") {
        setSelectedAddress(selected);
        setDrilldownContainerId(void 0);
      } else {
        setDrilldownContainerId(selectedResult.id);
        setTextToSearch(`${selectedResult.text}`);
        setTimeout(() => setShowSearchList(true));
      }
    },
    [results]
  );
  const items = useMemo(
    () => results.map((item) => ({
      ...item,
      name: item.text
    })),
    [results]
  );
  return /* @__PURE__ */ jsx(
    Field,
    {
      name: "address",
      label: translateStringOrObject(t, labelKey),
      errorMessage,
      isValid,
      optional,
      children: (childProps) => /* @__PURE__ */ jsx(
        Select,
        {
          ...childProps,
          name: "address",
          filterable: "prefiltered",
          items,
          selected: selectedAddress,
          loading: searchAddressQuery.isLoading || retrieveAddressQuery.isLoading,
          onSelect: onSelectItem,
          getSearchItem: SearchAddressItem,
          behaviour: "textIsData",
          text: addressText,
          setText: (text) => {
            onAddressTextChange(text);
            debouncedSetTextToSearch(text);
          },
          showList: showSearchList,
          setShowList: setShowSearchList,
          readonly: Boolean(readOnly),
          placeholder: t(($) => $["address__placeHolder"]),
          onBlur: handleBlur
        }
      )
    }
  );
};
const formatAddressResult = (item) => {
  if (item.description.includes("Addresses")) {
    const splitDescription = item.description.split(" - ");
    if (splitDescription.length === 1) {
      return {
        ...item,
        description: "",
        addressAmount: splitDescription[0].replace("Addresses", "")
      };
    }
    return {
      ...item,
      description: splitDescription[0],
      addressAmount: splitDescription[1].replace("Addresses", "")
    };
  }
  return item;
};
const defaultFieldMetadata = {
  label: "stateOrProvince",
  validators: validateNotEmptyOnBlur
};
const defaultFieldConfig = {
  [CountryCodes.Australia]: {
    label: "state",
    validators: validateNotEmptyOnBlur
  },
  [CountryCodes.Brazil]: {
    label: "state",
    validators: validateNotEmptyOnBlur
  },
  [CountryCodes.Canada]: {
    label: "provinceOrTerritory",
    validators: validateNotEmptyOnBlur
  },
  [CountryCodes.NewZealand]: {
    label: "region",
    validators: validateNotEmptyOnBlur
  },
  [CountryCodes.UnitedStates]: ({ isBusiness }) => ({
    label: isBusiness ? "stateOrProvince__US__business" : "state",
    validators: validateNotEmptyOnBlur
  })
};
const getStatePlaceholderText = (t, { country }) => {
  switch (country) {
    case CountryCodes.Australia:
    case CountryCodes.Brazil:
      return t(($) => $["selectState"]);
    case CountryCodes.Canada:
      return t(($) => $["selectProvinceOrTerritory"]);
    case CountryCodes.UnitedStates:
      return t(($) => $[`stateOrProvince__placeHolder__US`]);
    default:
      return t(($) => $["stateOrProvince__placeHolder"]);
  }
};
const STATE_FIELD = ["stateOrProvince"];
function StateField({
  data,
  valid,
  errors,
  labels,
  readonly,
  handleChangeFor,
  selectedCountry,
  handleBlur
}) {
  const { t } = useTranslation("common");
  const { dataset: states, loaded } = useDataset(
    datasetIdentifier.state(selectedCountry),
    !selectedCountry || !COUNTRIES_WITH_STATES_DATASET.includes(selectedCountry)
  );
  const labelKey = getKeyForField("stateOrProvince", selectedCountry);
  if (!loaded || !states.length) return null;
  return /* @__PURE__ */ jsx(
    Field,
    {
      name: "stateOrProvince",
      label: labels?.stateOrProvince || t(($) => $[labelKey]),
      errorMessage: errors.stateOrProvince,
      isValid: valid.stateOrProvince,
      dataTestId: "stateOrProvince",
      children: (childProps) => /* @__PURE__ */ jsx(
        Select,
        {
          ...childProps,
          name: "stateOrProvince",
          selected: data.stateOrProvince,
          placeholder: getStatePlaceholderText(t, { country: selectedCountry }),
          items: states,
          readonly: readonly && !!data.stateOrProvince,
          onChange: handleChangeFor("stateOrProvince"),
          onBlur: handleBlur
        }
      )
    }
  );
}
function AddressField({
  schema,
  data,
  valid,
  errors,
  fieldProblems,
  fieldName,
  trimOnBlur,
  hideField,
  maxlength,
  readOnly,
  optional,
  handleChangeFor,
  handleBlur
}) {
  const { t } = useTranslation("common");
  const { data: providerStatus } = useProviderStatus({ providers: ["address"] });
  const addressSearchEnabled = providerStatus?.statuses?.address?.enabled ?? false;
  const formUtils = createFormUtils({}, t);
  const errorMessage = formUtils.getErrorMessage(fieldName, errors ?? {}, fieldProblems);
  const value = data[fieldName];
  const labelKey = getKeyForField(fieldName, data.country);
  const setAddressFieldFromFoundAddress = useCallback(
    ({ houseNumberOrName, street, line1 }) => {
      const hasHouseNumber = !!houseNumberOrName;
      if (!street && line1) return handleChangeFor("address", "input")(line1);
      if (hasHouseNumber) {
        const isHouseNumberFirst = data.country ? COUNTRIES_WITH_HOUSE_NUMBER_FIRST.includes(data.country) : false;
        const formattedAddress = isHouseNumberFirst ? `${houseNumberOrName}${" "}${street}` : `${street}${" "}${houseNumberOrName}`;
        return handleChangeFor("address", "input")(formattedAddress);
      }
      return handleChangeFor("address", "input")(street);
    },
    [data.country, handleChangeFor]
  );
  const onAutofillAddress = useCallback(
    (foundAddress) => {
      schema?.forEach((field) => {
        switch (field) {
          case "country":
            handleChangeFor("country", "input")(foundAddress.country ?? " ");
            break;
          case "address":
            setAddressFieldFromFoundAddress(foundAddress);
            break;
          case "otherAddressInformation":
            handleChangeFor("otherAddressInformation", "blur")(foundAddress.street2 ?? " ");
            break;
          case "city":
            handleChangeFor("city", "input")(foundAddress.city ?? " ");
            break;
          case "postalCode":
            handleChangeFor("postalCode", "input")(foundAddress.postalCode ?? " ");
            break;
          case "stateOrProvince":
            handleChangeFor("stateOrProvince", "input")(foundAddress.stateOrProvince ?? " ");
            break;
        }
      });
    },
    [handleChangeFor, schema, setAddressFieldFromFoundAddress]
  );
  if (hideField) return null;
  switch (fieldName) {
    case "address":
      return addressSearchEnabled ? /* @__PURE__ */ jsx(
        SearchAddress,
        {
          addressText: data.address,
          country: data.country,
          labelKey,
          errorMessage,
          isValid: valid?.address,
          readOnly,
          optional,
          handleBlur: (e) => {
            handleChangeFor("address", "blur")(data.address);
            handleBlur?.(e);
          },
          onAddressTextChange: handleChangeFor("address", "input"),
          onAutofillAddress
        }
      ) : /* @__PURE__ */ jsx(
        Field,
        {
          name: fieldName,
          label: t(($) => $[labelKey]),
          errorMessage,
          isValid: valid?.[fieldName],
          optional,
          children: (childProps) => /* @__PURE__ */ jsx(
            InputText,
            {
              ...childProps,
              name: fieldName,
              value,
              onInput: handleChangeFor(fieldName, "input"),
              onBlur: (e) => {
                handleChangeFor(fieldName, "blur")(e);
                handleBlur?.(e);
              },
              maxLength: maxlength,
              "aria-required": true,
              "aria-invalid": !valid?.[fieldName],
              trimOnBlur,
              readonly: Boolean(readOnly)
            }
          )
        }
      );
    case "country":
      return /* @__PURE__ */ jsx(
        CountryField,
        {
          data: { country: value },
          valid: { country: valid?.country },
          errors: { country: errorMessage },
          labels: { country: formUtils.getLabel(fieldName, labelKey) },
          readonly: Boolean(readOnly),
          handleChangeFor,
          handleBlur
        }
      );
    case "stateOrProvince":
      return /* @__PURE__ */ jsx(
        StateField,
        {
          data: { stateOrProvince: value },
          valid: { stateOrProvince: valid?.stateOrProvince },
          errors: { stateOrProvince: errorMessage },
          labels: { stateOrProvince: formUtils.getLabel(fieldName, labelKey) },
          readonly: Boolean(readOnly),
          selectedCountry: data.country,
          handleChangeFor,
          handleBlur
        }
      );
    default:
      return /* @__PURE__ */ jsx(
        Field,
        {
          name: fieldName,
          label: t(($) => $[labelKey]),
          errorMessage,
          isValid: valid?.[fieldName],
          optional,
          children: (childProps) => /* @__PURE__ */ jsx(
            InputText,
            {
              ...childProps,
              name: fieldName,
              value: fieldName === "postalCode" ? value?.toUpperCase() : value,
              onInput: handleChangeFor(fieldName, "input"),
              onBlur: (e) => {
                handleChangeFor(fieldName, "blur")(e);
                handleBlur?.(e);
              },
              maxLength: maxlength,
              "aria-required": true,
              "aria-invalid": !valid?.[fieldName],
              trimOnBlur,
              readonly: Boolean(readOnly)
            }
          )
        }
      );
  }
}
const createRegExpByDigits = (digits) => new RegExp(`^\\d{${digits}}$`);
const postalCodePatterns = {
  [CountryCodes.Australia]: createRegExpByDigits(4),
  [CountryCodes.Austria]: createRegExpByDigits(4),
  [CountryCodes.Belgium]: /^[1-9]\d{3}$/,
  [CountryCodes.Brazil]: createRegExpByDigits(8),
  [CountryCodes.Bulgaria]: createRegExpByDigits(4),
  [CountryCodes.Canada]: /^[ABCEGHJKLMNPRSTVXY]\d[A-Z][ -]?(?:\d[A-Z]\d)?$/,
  [CountryCodes.Croatia]: /^([1-5])\d{4}$/,
  [CountryCodes.Cyprus]: createRegExpByDigits(4),
  [CountryCodes.CzechRepublic]: /^\d{3} ?\d{2}$/,
  [CountryCodes.Denmark]: /^(?:DK-)?\d{4}$/,
  [CountryCodes.Estonia]: createRegExpByDigits(5),
  [CountryCodes.Finland]: createRegExpByDigits(5),
  [CountryCodes.France]: createRegExpByDigits(5),
  [CountryCodes.Georgia]: createRegExpByDigits(4),
  [CountryCodes.Germany]: createRegExpByDigits(5),
  [CountryCodes.Gibraltar]: /^GX11[ -]?1AA$/,
  [CountryCodes.Greece]: /^\d{3} ?\d{2}$/,
  [CountryCodes.Hungary]: createRegExpByDigits(4),
  [CountryCodes.Iceland]: createRegExpByDigits(3),
  [CountryCodes.Ireland]: /^(?:[ACDEFHKNPRTVWXY]\d{2}|D6W)[ -]?[0-9ACDEFHKNPRTVWXY]{4}$/,
  [CountryCodes.Italy]: createRegExpByDigits(5),
  [CountryCodes.Japan]: createRegExpByDigits(7),
  [CountryCodes.Latvia]: /^(?:LV-)?\d{4}$/,
  [CountryCodes.Liechtenstein]: createRegExpByDigits(4),
  [CountryCodes.Lithuania]: /^(?:LT-)?\d{4,5}$/,
  [CountryCodes.Luxembourg]: createRegExpByDigits(4),
  [CountryCodes.Malaysia]: createRegExpByDigits(5),
  [CountryCodes.Malta]: /^[A-Za-z]{2,3} ?\d{2}(?:\d{2})?$/,
  [CountryCodes.Monaco]: /^980\d{2}$/,
  [CountryCodes.Netherlands]: /^(?:NL-)?[1-9]\d{3} ?(?:[ABCDEFGHIJKLMNOPQRTUVWXYZ][A-Z]|S[BCEFGHIJKLMNOPQRTUVWXYZ])$/,
  [CountryCodes.NewZealand]: createRegExpByDigits(4),
  [CountryCodes.Norway]: createRegExpByDigits(4),
  [CountryCodes.Poland]: /^\d{2}-\d{3}$/,
  [CountryCodes.Portugal]: /^[1-9]\d{3}([- ]?\d{3})?$/,
  [CountryCodes.PuertoRico]: /^\d{5}(?:[ -]?\d{4})?$/,
  // should exactly match CountryCodes.UnitedStates
  [CountryCodes.Romania]: createRegExpByDigits(6),
  [CountryCodes.Slovakia]: /^(SK-)?\d{5}$/,
  [CountryCodes.Slovenia]: /^(SI-)?\d{4}$/,
  [CountryCodes.Singapore]: createRegExpByDigits(6),
  [CountryCodes.Spain]: /(?:0[1-9]|[1-4]\d|5[0-2])\d{3}/,
  [CountryCodes.Sweden]: createRegExpByDigits(5),
  [CountryCodes.Switzerland]: /^[1-9]\d{3}$/,
  // https://en.wikipedia.org/wiki/Postcodes_in_the_United_Kingdom#Validation
  // follows most of the bullet points but not all the restrictions
  [CountryCodes.UnitedKingdom]: /^[ABCDEFGHIJKLMNOPRSTUWYZ](?:[ABCDEFGHKLMNOPQRSTUVWXY][0-9][ABEHMNPRVWXY0-9]?|[0-9][ABCDEFGHJKPSTUW0-9]?)(?: ?[0-9][ABDEFGHJLNPQRSTUWXYZ]{1,2})?$/,
  [CountryCodes.UnitedStates]: /^\d{5}(?:[ -]?\d{4})?$/
};
const createFormatByDigits = (digits) => {
  const format = new Array(digits).fill("9").join("");
  return {
    // Formatter - excludes non digits and limits to maxlength
    formatter: (val) => val ? val.replace(getFormattingRegEx("^\\d", "g"), "").substring(0, digits) : void 0,
    format,
    maxlength: digits
  };
};
const addressDisallowedChars = getFormattingRegEx(SPECIAL_CHARS.replace(/[-(\\/)]/g, ""));
const addressFormatters = {
  postalCode: {
    formatter: (val, context) => {
      const country = context?.state.data.country;
      const specificRule = countrySpecificFormatters[country]?.postalCode?.formatter;
      if (specificRule) {
        return specificRule(val);
      }
      return val;
    }
  },
  address: {
    formatter: (val) => val ? trimValWithOneSpace(val).replace(addressDisallowedChars, "") : void 0
  },
  otherAddressInformation: {
    formatter: (val) => val ? trimValWithOneSpace(val).replace(addressDisallowedChars, "") : void 0
  },
  city: {
    formatter: (val) => val ? trimValWithOneSpace(val).replace(addressDisallowedChars, "") : void 0
  }
};
const countrySpecificFormatters = {
  [CountryCodes.Australia]: { postalCode: createFormatByDigits(4) },
  [CountryCodes.Austria]: { postalCode: createFormatByDigits(4) },
  [CountryCodes.Belgium]: { postalCode: createFormatByDigits(4) },
  [CountryCodes.Brazil]: { postalCode: createFormatByDigits(8) },
  [CountryCodes.Bulgaria]: { postalCode: createFormatByDigits(4) },
  [CountryCodes.Canada]: { postalCode: { format: "A9A 9A9 or A9A9A9", maxlength: 7 } },
  [CountryCodes.Croatia]: { postalCode: { format: "[1-5]9999", maxlength: 5 } },
  [CountryCodes.Cyprus]: { postalCode: createFormatByDigits(4) },
  [CountryCodes.CzechRepublic]: { postalCode: { format: "999 99", maxlength: 6 } },
  [CountryCodes.Denmark]: { postalCode: { format: "9999", maxlength: 7 } },
  [CountryCodes.Estonia]: { postalCode: createFormatByDigits(5) },
  [CountryCodes.Finland]: { postalCode: createFormatByDigits(5) },
  [CountryCodes.France]: { postalCode: createFormatByDigits(5) },
  [CountryCodes.Germany]: { postalCode: createFormatByDigits(5) },
  [CountryCodes.Gibraltar]: { postalCode: { format: "GX11 1AA", maxlength: 8 } },
  [CountryCodes.Greece]: { postalCode: { format: "999 99", maxlength: 6 } },
  [CountryCodes.Hungary]: { postalCode: createFormatByDigits(4) },
  [CountryCodes.Iceland]: { postalCode: createFormatByDigits(3) },
  [CountryCodes.Ireland]: { postalCode: { format: "A99 A999", maxlength: 8 } },
  [CountryCodes.Italy]: { postalCode: createFormatByDigits(5) },
  [CountryCodes.Japan]: {
    postalCode: createFormatByDigits(7)
  },
  [CountryCodes.Latvia]: { postalCode: { format: "9999 or LV-9999", maxlength: 7 } },
  [CountryCodes.Liechtenstein]: { postalCode: createFormatByDigits(4) },
  [CountryCodes.Lithuania]: { postalCode: { format: "9999 or 99999 or LT-99999", maxlength: 8 } },
  [CountryCodes.Luxembourg]: { postalCode: createFormatByDigits(4) },
  [CountryCodes.Malaysia]: { postalCode: createFormatByDigits(5) },
  [CountryCodes.Malta]: {
    postalCode: { format: "2 or 3 letters + 2 or 4 digits (with optional space)", maxlength: 8 }
  },
  [CountryCodes.Monaco]: { postalCode: { format: "980NN", maxlength: 5 } },
  [CountryCodes.Netherlands]: { postalCode: { format: "9999AA", maxlength: 7 } },
  [CountryCodes.NewZealand]: { postalCode: createFormatByDigits(4) },
  [CountryCodes.Norway]: { postalCode: createFormatByDigits(4) },
  [CountryCodes.Poland]: {
    postalCode: {
      // Formatter - excludes non digits & hyphens and limits to a maxlength that varies depending on whether a hyphen is present or not
      formatter: (val) => {
        if (!val) return void 0;
        const nuVal = val.replace(getFormattingRegEx("^\\d-", "g"), "");
        const maxlength = nuVal.includes("-") ? 6 : 5;
        return nuVal.substring(0, maxlength);
      },
      format: "99-999",
      maxlength: 6
    }
  },
  [CountryCodes.Portugal]: {
    postalCode: {
      formatter: (val) => {
        if (!val) return void 0;
        const nuVal = val.replace(getFormattingRegEx("^\\d-", "g"), "");
        return nuVal.substring(0, 8);
      },
      format: "9999-999",
      maxlength: 8
    }
  },
  [CountryCodes.PuertoRico]: { postalCode: createFormatByDigits(5) },
  [CountryCodes.Romania]: { postalCode: createFormatByDigits(6) },
  [CountryCodes.Singapore]: { postalCode: createFormatByDigits(6) },
  [CountryCodes.Slovakia]: { postalCode: { format: "99999 or SK-99999", maxlength: 8 } },
  [CountryCodes.Slovenia]: { postalCode: { format: "9999 or SI-9999", maxlength: 7 } },
  [CountryCodes.Spain]: { postalCode: createFormatByDigits(5) },
  [CountryCodes.Sweden]: { postalCode: createFormatByDigits(5) },
  [CountryCodes.Switzerland]: { postalCode: createFormatByDigits(4) },
  [CountryCodes.UnitedKingdom]: {
    postalCode: {
      // Disallow special chars & set to maxlength
      formatter: (val) => val ? val.replace(getFormattingRegEx(SPECIAL_CHARS), "").substring(0, 8) : void 0,
      format: "AA99 9AA or A99 9AA or A9 9AA",
      maxlength: 8
    }
  },
  [CountryCodes.UnitedStates]: {
    postalCode: {
      format: "12345 or 12345-6789",
      maxlength: 10
    }
  }
};
const logger = createLogger();
const addressValidationRules = (country) => {
  const postalCodeFormat = country ? countrySpecificFormatters[country]?.postalCode?.format : void 0;
  return {
    address: [
      {
        modes: ["blur"],
        validate: (val) => hasText(val),
        errorMessage: "fieldIsRequired"
      }
    ],
    postalCode: {
      modes: ["blur"],
      validate: (val) => {
        const pattern = country ? postalCodePatterns[country] : void 0;
        return pattern ? !!val && pattern.test(val) : !!val;
      },
      errorMessage: postalCodeFormat ? {
        key: "invalidFormatExpects",
        values: {
          format: postalCodeFormat
        }
      } : "invalidFormat"
    },
    city: {
      modes: ["blur"],
      validate: hasText,
      errorMessage: "fieldIsRequired"
    },
    stateOrProvince: {
      modes: ["blur"],
      validate: (val) => !!val,
      errorMessage: "fieldIsRequired"
    },
    country: {
      modes: ["blur"],
      validate: (val) => !!val,
      errorMessage: "fieldIsRequired"
    }
  };
};
const countrySpecificOtherAddressInformationValidators = (country) => {
  switch (country) {
    case CountryCodes.Japan:
      return [
        {
          modes: ["blur"],
          validate: (input) => {
            return hasText(input);
          },
          errorMessage: "checkForTypos"
        },
        {
          modes: ["blur"],
          validate: (input) => {
            return chomeAndBanchiValidator(input);
          },
          errorMessage: "pleaseUseOnlyNumbersAndDashes"
        }
      ];
    default:
      return void 0;
  }
};
const addressValidationRulesV4 = (country, i18n) => {
  const postalCodeFormat = country ? countrySpecificFormatters[country]?.postalCode?.format : void 0;
  const MIN_LENGTH_3 = 3;
  const MIN_LENGTH_2 = 2;
  const otherAddressInformation = countrySpecificOtherAddressInformationValidators(country);
  return {
    address: [
      {
        modes: ["blur"],
        validate: (val) => hasText(val),
        errorMessage: "fieldIsRequired"
      },
      {
        modes: ["blur"],
        validate: (input) => !matchesRegex(NO_ALPHABET_REGEX, input),
        errorMessage: "nameMustContainLetters"
      },
      {
        modes: ["blur"],
        validate: (val) => !matchesRegex(EMOJI_REGEX, val) && !hasRepeatedCharacters(val) && !isInvalidName(val) && matchesRegex(ADDRESS_VALID_CHAR_REGEX, val),
        errorMessage: "checkForTypos"
      },
      {
        modes: ["blur"],
        validate: (val) => isValidMinLength(val, MIN_LENGTH_3),
        errorMessage: {
          key: "fieldMustContainAtLeast",
          values: {
            fieldName: i18n.get("address"),
            minLength: String(MIN_LENGTH_3)
          }
        }
      }
    ],
    postalCode: {
      modes: ["blur"],
      validate: (val) => {
        const pattern = country ? postalCodePatterns[country] : void 0;
        return pattern ? !!val && pattern.test(val) : !!val;
      },
      errorMessage: postalCodeFormat ? {
        key: "invalidFormatExpects",
        values: {
          format: postalCodeFormat
        }
      } : "invalidFormat"
    },
    city: [
      {
        modes: ["blur"],
        validate: hasText,
        errorMessage: "fieldIsRequired"
      },
      {
        modes: ["blur"],
        validate: (input) => !matchesRegex(NO_ALPHABET_REGEX, input),
        errorMessage: "nameMustContainLetters"
      },
      {
        modes: ["blur"],
        validate: (val) => !matchesRegex(EMOJI_REGEX, val) && !hasRepeatedCharacters(val) && !isInvalidName(val),
        errorMessage: "checkForTypos"
      },
      {
        modes: ["blur"],
        validate: (val) => isValidMinLength(val, MIN_LENGTH_2),
        errorMessage: {
          key: "fieldMustContainAtLeast",
          values: {
            fieldName: i18n.get("city"),
            minLength: String(MIN_LENGTH_2)
          }
        }
      }
    ],
    stateOrProvince: [
      {
        modes: ["blur"],
        validate: (val) => !!val,
        errorMessage: "fieldIsRequired"
      },
      {
        modes: ["blur"],
        validate: (input) => !matchesRegex(NO_ALPHABET_REGEX, input),
        errorMessage: "nameMustContainLetters"
      },
      {
        modes: ["blur"],
        validate: (val) => !hasRepeatedCharacters(val) && !isInvalidName(val),
        errorMessage: "checkForTypos"
      }
    ],
    country: [
      {
        modes: ["blur"],
        validate: (val) => !!val,
        errorMessage: "fieldIsRequired"
      },
      {
        modes: ["blur"],
        validate: (input) => !matchesRegex(NO_ALPHABET_REGEX, input),
        errorMessage: "nameMustContainLetters"
      },
      {
        modes: ["blur"],
        validate: (val) => !matchesRegex(EMOJI_REGEX, val) && !isInvalidName(val) && matchesRegex(ADDRESS_VALID_CHAR_REGEX, val),
        errorMessage: "checkForTypos"
      }
    ],
    otherAddressInformation
  };
};
const addressValidators = ({
  isExperimentEnabled = () => false,
  country,
  i18n
}) => ({
  ...isExperimentEnabled?.("StrictNameAndAddressValidationV4") ? addressValidationRulesV4(country, i18n) : addressValidationRules(country)
});
const preventPoBoxValidation = (cleanseAddress2) => ({
  address: {
    modes: ["blur"],
    errorMessage: "addressPoBoxError",
    asyncValidate: async (address, context) => {
      const formData = context?.state?.data ?? {};
      const { country } = formData;
      if (!address || !country) return true;
      const text = formatAddressForCleanse({ ...formData, address });
      if (!text) return true;
      try {
        const { poBox } = await cleanseAddress2({
          text,
          country
        });
        return !poBox;
      } catch (error) {
        logger.error("Error while checking if address is PO box", error);
        return true;
      }
    }
  }
});
function Address({
  data: dataProp,
  labels,
  readOnly,
  hideCountry,
  fieldValidationErrors: propFieldValidationErrors,
  allFields,
  requiredFields,
  optionalFields = ["otherAddressInformation"],
  readOnlyFields,
  obscuredFields,
  trustedFields,
  shouldValidate,
  onChange,
  verifiedAddress,
  condensed,
  handleFieldChange,
  errors: errorProp,
  valid: validProp,
  addressType
}) {
  const { i18n } = useI18nContext();
  const { t } = useTranslation("common");
  const { isExperimentEnabled } = useExperimentsContext();
  const isStrictNameAndAddressValidationEnabled = isExperimentEnabled(
    "StrictNameAndAddressValidationV4"
  );
  const preventPoBoxes = addressType === "operationalAddress";
  const schema = useMemo(() => {
    if (requiredFields?.length) {
      return requiredFields?.includes("stateOrProvince") || dataProp?.country && COUNTRIES_WITH_STATES_DATASET.includes(dataProp?.country) ? requiredFields : requiredFields?.filter((field) => field !== "stateOrProvince");
    }
    return dataProp?.country && COUNTRIES_WITH_STATES_DATASET.includes(dataProp?.country) ? getAddressSchemaForCountry(dataProp?.country) : getAddressSchemaForCountry(dataProp?.country).filter((ad) => ad !== "stateOrProvince");
  }, [dataProp?.country, requiredFields]);
  const rules = useMemo(() => addressValidationRules(dataProp?.country), [dataProp?.country]);
  const rulesV4 = useMemo(
    () => addressValidationRulesV4(dataProp?.country, i18n),
    [dataProp?.country, i18n]
  );
  const cleanseAddress2 = useAddressCleanseImperatively();
  const asyncRules = useMemo(
    () => preventPoBoxes ? preventPoBoxValidation(cleanseAddress2) : void 0,
    [cleanseAddress2, preventPoBoxes]
  );
  const form = useForm({
    schema,
    defaultData: dataProp,
    formatters: addressFormatters,
    rules: isStrictNameAndAddressValidationEnabled ? rulesV4 : rules,
    asyncRules,
    fieldProblems: propFieldValidationErrors,
    optionalFields,
    obscuredFields,
    trustedFields,
    shouldValidate
  });
  let {
    schema: formSchema,
    data: formData,
    errors: formErrors,
    valid: formValid,
    fieldProblems: formFieldProblems,
    handleChangeFor
  } = form;
  const { isValid } = form;
  if (handleFieldChange && requiredFields && propFieldValidationErrors) {
    const allFields2 = [...requiredFields, ...optionalFields];
    const fieldsInOrder = getAddressSchemaForCountry(dataProp?.country).filter(
      (field) => allFields2.includes(field)
    );
    handleChangeFor = handleFieldChange;
    formData = dataProp ?? {};
    formErrors = errorProp;
    formValid = validProp;
    formFieldProblems = propFieldValidationErrors;
    formSchema = fieldsInOrder;
  }
  useEffect(() => {
    if (verifiedAddress) {
      entriesOf(verifiedAddress).forEach(([key, value]) => {
        if (formData[key] !== value) handleChangeFor(key, "input")(value);
      });
    }
  }, [verifiedAddress]);
  const formUtils = createFormUtils(
    {
      labels,
      readOnly,
      requiredFields: schema,
      optionalFields,
      readOnlyFields,
      trustedFields
    },
    t
  );
  useEffect(() => {
    if (hideCountry && dataProp?.country && dataProp.country !== formData.country) {
      schema.forEach((field) => {
        return field === "country" ? handleChangeFor("country", "input")(dataProp.country) : handleChangeFor(field, "input")(" ");
      });
    }
  }, [dataProp?.country, hideCountry]);
  useEffect(() => {
    onChange?.({
      schema: formSchema,
      data: formData,
      valid: formValid,
      errors: formErrors,
      fieldProblems: formFieldProblems,
      isValid
    });
  }, [formData, formErrors, formFieldProblems, formSchema, formValid, isValid]);
  const createField = (fieldName) => {
    if (!formUtils.isRequiredField(fieldName) && !formUtils.isOptionalField(fieldName)) return null;
    const hideField = fieldName === "country" && hideCountry;
    return /* @__PURE__ */ jsx(
      AddressField,
      {
        schema: formSchema,
        data: formData,
        valid: formValid,
        errors: formErrors,
        fieldProblems: formFieldProblems,
        fieldName,
        maxlength: getMaxLengthByFieldAndCountry(
          countrySpecificFormatters,
          fieldName,
          formData.country
        ),
        hideField,
        readOnly: formUtils.isReadOnly(fieldName) || formUtils.isTrusted(fieldName),
        optional: formUtils.isOptionalField(fieldName),
        trimOnBlur: true,
        handleChangeFor
      },
      fieldName
    );
  };
  if (condensed && formData?.country) {
    const condensedFields = CONDENSED_ADDRESS_FIELDS[formData.country] ?? [];
    switch (formData?.country) {
      case "US":
        return /* @__PURE__ */ jsxs("fieldset", { "aria-label": t(($) => $[addressType]), className: "adyen-kyc-address", children: [
          formSchema.filter((field) => !condensedFields.includes(field)).map((filteredField) => createField(filteredField)),
          condensedFields.length && /* @__PURE__ */ jsx("div", { className: "adyen-kyc-address__condensed-fields", children: condensedFields.map((field) => createField(field)) })
        ] });
      default:
        return /* @__PURE__ */ jsx("fieldset", { "aria-label": t(($) => $[addressType]), className: "adyen-kyc-address", children: formSchema.map((field) => createField(field)) });
    }
  }
  return /* @__PURE__ */ jsx("fieldset", { "aria-label": t(($) => $[addressType]), className: "adyen-kyc-address", children: formSchema.map((field) => createField(field)) });
}
export {
  Address as A,
  STATE_FIELD as S,
  addressValidators as a,
  useAddressCleanse as b,
  defaultFieldConfig as c,
  defaultFieldMetadata as d,
  StateField as e,
  formatAddressForCleanse as f,
  getNestedTrustedFields as g,
  addressValidationRulesV4 as h,
  isDateOlderThanAYear as i,
  addressValidationRules as j,
  mapAddressData as m,
  useProviderStatus as u
};
