;
{
  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] = "c58459bc-27e3-46d7-a84a-5fc7c671e419", e._sentryDebugIdIdentifier = "sentry-dbid-c58459bc-27e3-46d7-a84a-5fc7c671e419");
  } catch (e) {
  }
}
;
import "@tanstack/preact-query";
import { useCallback, useState, useMemo, useEffect } from "preact/hooks";
import { b as useApiContext, $ as httpPost, a0 as CountryCodes, ai as isEmpty, a3 as createLogger, u as useTranslation, ac as entriesOf } from "./StoreProvider-CqQrndhS.js";
import { e as emailPattern } from "./basePatterns-BwdnMQxI.js";
import { jsx, jsxs } from "preact/jsx-runtime";
import { F as Field } from "./Field-BL3Mh7gm.js";
import { H as Header } from "./Header-Dt-hNg1U.js";
import { m as makeMask, a as nonInputs, n as numericInputs, s as spacer, M as MaskedInput, I as InputEmail } from "./MaskedInput-DgjlsFWR.js";
import { r as resolveFieldMetadata } from "./fieldConfigurations-BUT9DTUH.js";
import { m as mergeFieldMetadataIntoProps, c as createFormUtils } from "./formUtils-CwOJPw6N.js";
import { S as Select } from "./Select-DbIpx8xz.js";
import { u as useDataset } from "./useDataset-DgIHjoGg.js";
import { I as InputGroup } from "./InputGroup-WBfGDV5F.js";
import { d as datasetIdentifier } from "./datasetUtil-BHQp0-xL.js";
const validatePhoneNumber = (baseUrl, data) => {
  return httpPost(
    {
      baseUrl,
      path: `validations/phonenumber`
    },
    data
  );
};
const useValidatePhoneNumberImperatively = () => {
  const { baseUrl } = useApiContext();
  return useCallback(
    (data) => validatePhoneNumber(baseUrl.value, data),
    [baseUrl.value]
  );
};
const validatePhoneCountryCodeNotEmptyOnBlur = {
  modes: ["blur"],
  validate: (phone) => !isEmpty(phone?.phoneCountryCode),
  errorMessage: "missingPhoneCountryCode"
};
const validatePhoneNumberNotEmpty = {
  modes: ["blur"],
  validate: (phone) => !isEmpty(phone?.number),
  errorMessage: "invalidPhoneNumber"
};
const getAsyncPhoneValidationRules = (validatePhoneNumber2) => ({
  phoneNumber: {
    asyncValidate: async (phone) => {
      if (!phone?.number) return false;
      return (await validatePhoneNumber2({ number: phone.number })).valid;
    },
    errorMessage: "invalidPhoneNumber",
    modes: ["blur"]
  }
});
const defaultValidators = [validatePhoneCountryCodeNotEmptyOnBlur, validatePhoneNumberNotEmpty];
const defaultFieldMetadata = {
  label: "phoneNumber",
  validators: defaultValidators
};
const fieldConfig = {
  [CountryCodes.Albania]: {
    label: "phoneNumber",
    validators: defaultValidators,
    mask: {
      mask: makeMask(...numericInputs(2), spacer, ...numericInputs(3), spacer, ...numericInputs(4))
    }
  },
  [CountryCodes.AmericanSamoa]: {
    label: "phoneNumber",
    validators: defaultValidators,
    mask: {
      mask: makeMask(...numericInputs(3), ...nonInputs("-"), ...numericInputs(4))
    }
  },
  [CountryCodes.Netherlands]: {
    label: "phoneNumber",
    validators: defaultValidators,
    mask: { mask: makeMask(...numericInputs(1), spacer, ...numericInputs(8)) }
  },
  [CountryCodes.Singapore]: {
    label: "phoneNumber",
    validators: defaultValidators,
    mask: { mask: makeMask(...numericInputs(4), spacer, ...numericInputs(4)) }
  },
  [CountryCodes.Japan]: {
    label: "phoneNumber",
    validators: defaultValidators,
    mask: {
      mask: makeMask(
        ...numericInputs(2),
        ...nonInputs("-"),
        ...numericInputs(4),
        ...nonInputs("-"),
        ...numericInputs(4)
      )
    }
  },
  [CountryCodes.UnitedStates]: {
    label: "phoneNumber",
    validators: defaultValidators,
    mask: {
      mask: makeMask(
        ...nonInputs("(", { displayEagerly: false }),
        ...numericInputs(3),
        ...nonInputs(")"),
        spacer,
        ...numericInputs(3),
        ...nonInputs("-"),
        ...numericInputs(4)
      )
    }
  }
};
const getPhonePlaceholder = (country) => {
  switch (country) {
    case CountryCodes.Albania:
      return "00 000 0000";
    case CountryCodes.AmericanSamoa:
      return "000-0000";
    case CountryCodes.Netherlands:
      return "0 00000000";
    case CountryCodes.Singapore:
      return "0000 0000";
    case CountryCodes.Japan:
      return "00-0000-0000";
    case CountryCodes.UnitedStates:
      return "(000) 000-0000";
    default:
      return void 0;
  }
};
const contactDetailsValidationRules = {
  email: [
    {
      modes: ["blur"],
      validate: (email) => email ? emailPattern.test(email) : false,
      errorMessage: "invalidEmail"
    }
  ]
};
const PHONE_FIELD = ["phoneNumber"];
const logger = createLogger();
const usePhonePrefixes = () => {
  const [phonePrefixes, setPhonePrefixes] = useState();
  useEffect(() => {
    const loadPhonePrefixes = async () => {
      const loaded = (await import("./phonePrefixes-CnL40uyX.js")).default;
      setPhonePrefixes(loaded);
    };
    loadPhonePrefixes().catch(logger.error);
  }, []);
  return phonePrefixes;
};
function PhoneField({
  country,
  name = "phoneNumber",
  data,
  valid,
  errors,
  labels,
  mask,
  readonly,
  optional,
  placeholder,
  handleChangeFor
}) {
  const { t } = useTranslation("common");
  const { dataset: countries } = useDataset(datasetIdentifier.country);
  const [isFocused, setIsFocused] = useState(false);
  const phonePrefixes = usePhonePrefixes();
  const currentPrefix = phonePrefixes?.[data.phoneNumber?.phoneCountryCode ?? country];
  const numberStrippedOfCountryCode = useMemo(() => {
    if (!phonePrefixes || !data.phoneNumber?.number) return "";
    return currentPrefix && data.phoneNumber?.number.startsWith(currentPrefix) ? data.phoneNumber.number.slice(currentPrefix.length) : data.phoneNumber.number;
  }, [phonePrefixes, data.phoneNumber?.number, currentPrefix]);
  const selectItems = useMemo(() => {
    const countryMap = new Map(countries.map((entry) => [entry.id, entry.name]));
    return entriesOf(phonePrefixes ?? {}).map(([countryCode, prefix]) => {
      const countryName = countryMap.get(countryCode) ?? countryCode;
      return {
        id: countryCode,
        name: `${countryName} (${prefix})`,
        selectedOptionName: `${countryCode} (${prefix})`
      };
    }).sort((a, b) => a.name.localeCompare(b.name));
  }, [phonePrefixes, countries]);
  const handleSelectChange = useCallback(
    (event) => {
      const newCC = phonePrefixes?.[event.target.value];
      const withoutCC = currentPrefix && data.phoneNumber?.number?.startsWith(currentPrefix) ? data.phoneNumber?.number?.slice(currentPrefix.length) : data.phoneNumber?.number?.replace(/\D+/g, "");
      handleChangeFor(
        "phoneNumber",
        "input"
      )({
        phoneCountryCode: event.target.value,
        number: withoutCC ? newCC + withoutCC : newCC,
        type: "mobile"
      });
    },
    [currentPrefix, data.phoneNumber?.number, handleChangeFor, phonePrefixes]
  );
  const handleOnInput = useCallback(
    (event) => {
      const strippedOfCountryCode = currentPrefix ? event.replace(currentPrefix, "") : event;
      const onlyDigits = strippedOfCountryCode.replace(/\D+/g, "");
      const number = currentPrefix ? `${currentPrefix}${onlyDigits}` : onlyDigits;
      handleChangeFor(
        "phoneNumber",
        "input"
      )({
        ...data.phoneNumber,
        number,
        type: "mobile"
      });
    },
    [currentPrefix, data.phoneNumber, handleChangeFor]
  );
  const handleOnBlur = useCallback(
    (event) => {
      const onlyDigits = event.currentTarget.value.replace(/\D+/g, "");
      const number = currentPrefix ? `${currentPrefix}${onlyDigits}` : onlyDigits;
      setIsFocused(false);
      handleChangeFor(
        "phoneNumber",
        "blur"
      )({
        ...data.phoneNumber,
        number,
        type: "mobile"
      });
    },
    [currentPrefix, data.phoneNumber, handleChangeFor]
  );
  const transformOnType = useCallback(
    (value) => currentPrefix ? value.startsWith(currentPrefix) ? value.slice(currentPrefix.length) : value : value,
    [currentPrefix]
  );
  useEffect(() => {
    if (!data.phoneNumber?.phoneCountryCode && country) {
      handleChangeFor(
        "phoneNumber",
        "input"
      )({
        ...data.phoneNumber,
        phoneCountryCode: country,
        type: "mobile"
      });
    }
  }, [country, data.phoneNumber?.phoneCountryCode, data?.phoneNumber, handleChangeFor]);
  return /* @__PURE__ */ jsx(
    Field,
    {
      el: "fieldset",
      name,
      label: labels.phoneNumber ?? t(($) => $["phoneNumber"]),
      errorMessage: errors.phoneNumber,
      isValid: Boolean(valid.phoneNumber),
      optional: Boolean(optional),
      disabled: Boolean(readonly),
      children: (childProps) => /* @__PURE__ */ jsxs(
        InputGroup,
        {
          ...childProps,
          id: "phoneInputGroup",
          isFocused,
          isInvalid: Boolean(!valid.phoneNumber && errors.phoneNumber),
          children: [
            /* @__PURE__ */ jsx(
              Select,
              {
                name: "phoneCountryCode",
                "aria-label": t(($) => $["phoneNumberPrefix"]),
                isMulti: false,
                items: selectItems,
                selected: data.phoneNumber?.phoneCountryCode,
                placeholder: t(($) => $["select"]),
                onChange: handleSelectChange,
                minimal: true
              }
            ),
            /* @__PURE__ */ jsx(
              MaskedInput,
              {
                useFieldComponent: false,
                name: "phoneNumber",
                type: "tel",
                label: labels.phoneNumber ?? t(($) => $["phoneNumber"]),
                value: numberStrippedOfCountryCode,
                "aria-invalid": Boolean(!valid.phoneNumber),
                isValid: Boolean(valid.phoneNumber),
                placeholder,
                shouldValidate: true,
                errorMessage: errors.phoneNumber,
                readonly,
                disabled: readonly,
                transformOnType,
                ...mask,
                stripNonAllowedInputs: true,
                onInput: handleOnInput,
                onBlur: handleOnBlur,
                onFocus: () => setIsFocused(true)
              }
            )
          ]
        }
      )
    }
  );
}
const contactDetailFields = [...PHONE_FIELD, "email"];
function ContactDetails(props) {
  const { t } = useTranslation("common");
  const {
    country,
    data,
    errors = {},
    handleFieldChange,
    fieldValidationErrors,
    valid = {},
    ...newProps
  } = props;
  let mergedProps = newProps;
  if (!handleFieldChange) {
    return;
  }
  mergedProps = mergeFieldMetadataIntoProps(
    "phoneNumber",
    resolveFieldMetadata(
      /*
        Use global data here to allow for config to be dynamic when the below useForm data changes
        otherwise we will use `country` which is unrelated to the phoneCountryCode
      */
      fieldConfig[data?.phoneNumber?.phoneCountryCode ?? country],
      {},
      defaultFieldMetadata
    ),
    mergedProps
  );
  const formUtils = createFormUtils(mergedProps, t);
  return /* @__PURE__ */ jsxs("div", { role: "form", className: "adyen-kyc-individual__contact-details", children: [
    mergedProps.heading && /* @__PURE__ */ jsx(Header, { title: mergedProps.heading }),
    formUtils.isRequiredField("email") && /* @__PURE__ */ jsx("div", { className: "adyen-kyc-email", children: /* @__PURE__ */ jsx(
      Field,
      {
        name: "email",
        label: formUtils.getLabel("email"),
        errorMessage: formUtils.getErrorMessage("email", errors, fieldValidationErrors),
        isValid: valid.email,
        children: (childProps) => /* @__PURE__ */ jsx(
          InputEmail,
          {
            ...childProps,
            name: "email",
            value: data?.email,
            readonly: formUtils.isReadOnly("email"),
            onInput: handleFieldChange("email", "input"),
            onBlur: handleFieldChange("email", "blur"),
            "aria-required": true,
            "aria-invalid": !valid?.email
          }
        )
      }
    ) }),
    formUtils.isRequiredField("phoneNumber") && /* @__PURE__ */ jsx(
      PhoneField,
      {
        country,
        data: formUtils.getFieldData(data ?? {}, PHONE_FIELD),
        valid: formUtils.getFieldValid(valid, PHONE_FIELD),
        errors: formUtils.getFieldErrors(errors, {}, PHONE_FIELD),
        labels: formUtils.getFieldLabels(PHONE_FIELD, {
          phoneNumber: "phoneNumber"
        }),
        placeholder: getPhonePlaceholder(country),
        optional: formUtils.isOptionalField("phoneNumber"),
        readonly: formUtils.isReadOnly("phoneNumber"),
        mask: formUtils.getMask("phoneNumber"),
        handleChangeFor: handleFieldChange
      }
    )
  ] });
}
export {
  ContactDetails as C,
  contactDetailFields as a,
  contactDetailsValidationRules as c,
  defaultFieldMetadata as d,
  fieldConfig as f,
  getAsyncPhoneValidationRules as g,
  useValidatePhoneNumberImperatively as u
};
