"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = exports.ZIP_MASK = exports.SSN_MASK_OBFUSCATED = exports.SSN_MASK = exports.RE_ZIP = exports.RE_SSN = exports.RE_PHONE = exports.RE_DATE = exports.RE_CURRENCY = exports.PHONE_MASK = exports.DATE_MASK = exports.CURRENCY_MASK = void 0;
exports.useLabelMask = useLabelMask;
var _compat = require("preact/compat");
var _classnames = _interopRequireDefault(require("classnames"));
var _mergeIds = _interopRequireDefault(require("../utilities/mergeIds"));
var _useId = _interopRequireDefault(require("../utilities/useId"));
var _jsxRuntime = require("preact/compat/jsx-runtime");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
 * Regular expressions for matching commonly used masks, ensure capture groups are
 * set for each set of items that are separated by a delimiter, delimiters are
 * optional and so should be shown as well with the `?` optional flag.
 */
const RE_DATE = /^(\d{1,2})[\D]?(\d{1,2})?[\D]?(\d{1,4})?/;
exports.RE_DATE = RE_DATE;
const RE_PHONE = /^\(?(\d{1,3})?\)?[\s.-]?(\d{1,3})?[\s.-]?(\d{1,4})?/;
exports.RE_PHONE = RE_PHONE;
const RE_SSN = /([*\d]{1,3})[\s.-]?([*\d]{1,2})?[\s.-]?([\d{1,4}]+)?/;
exports.RE_SSN = RE_SSN;
const RE_ZIP = /(\d{1,5})/;
exports.RE_ZIP = RE_ZIP;
const RE_CURRENCY = /\$?[\d,.-]*/;

/**
 * This function returns a mask function which returns either the formatted match only, or
 * the formatted match + the hint substring which the regular expressions above match against
 * when determining what content has been filled in.
 */
exports.RE_CURRENCY = RE_CURRENCY;
const makeMask = (regex, hint, formatter) => {
  return function () {
    let rawInput = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : '';
    let valueOnly = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
    const match = regex.exec(rawInput);
    const formattedMatch = match ? formatter(match) : '';
    if (valueOnly) {
      return formattedMatch;
    }
    const hintSub = hint.substring(formattedMatch.length);
    return formattedMatch + hintSub;
  };
};

/**
 * The date mask automatically pads months and days that are one digit
 */
const DATE_MASK = makeMask(RE_DATE, 'MM/DD/YYYY', match => {
  const [month, day, year] = match.slice(1);
  const formattedDate = [
  // We treat all non-numeric characters as a delimiter. If they're using a
  // delimiter after a month or day, we interpret that as the user supplying
  // a single digit for month or day, which we will automatically pad for them.
  month && month.padStart(2, '0'), day && day.padStart(2, '0'), year].filter(s => s).join('/');
  return formattedDate;
});

/**
 * Formatting for US phone numbers
 */
exports.DATE_MASK = DATE_MASK;
const PHONE_MASK = makeMask(RE_PHONE, '###-###-####', match => {
  return match.slice(1).filter(s => s).join('-');
});

/**
 * Formatting for US Postal codes, this could be expanded to allow for 9 digit numbers
 */
exports.PHONE_MASK = PHONE_MASK;
const ZIP_MASK = makeMask(RE_ZIP, '#####', match => {
  return match[1];
});

/**
 * Formatting for social security numbers.
 */
exports.ZIP_MASK = ZIP_MASK;
const SSN_MASK = makeMask(RE_SSN, '###-##-####', match => {
  /**
   * for future notice, there are rules regarding social security numbers, these could be validated
   * if we were to add error handling to useLabelMask as an additional set of functionality
   * The first part should have 3 digits and should not be 000, 666, or between 900 and 999.
   * The second part should have 2 digits and it should be from 01 to 99.
   * The third part should have 4 digits and it should be from 0001 to 9999.
   */
  return match.slice(1).filter(s => s).join('-');
});

/**
 * Does the same thing as SSN_MASK except that it obfuscates the first five digits
 */
exports.SSN_MASK = SSN_MASK;
const SSN_MASK_OBFUSCATED = (rawInput, valueOnly) => {
  // Use the normal SSN_MASK function just to clean the raw input and format it
  const formatted = SSN_MASK(rawInput, true);
  // We only hide the first five digits of the SSNs
  const obfuscation = '***-**';
  let obfuscated;
  if (formatted.length < obfuscation.length) {
    obfuscated = obfuscation.substring(0, formatted.length);
  } else {
    obfuscated = obfuscation + formatted.substring(obfuscation.length);
  }
  return SSN_MASK(obfuscated, valueOnly);
};

/**
 * Currency mask is a little different, we need to modify the incoming content to strip
 * out any commas or dollar signs before evaluating it via the Intl.NumberFormat function.
 */
exports.SSN_MASK_OBFUSCATED = SSN_MASK_OBFUSCATED;
const CURRENCY_MASK = makeMask(RE_CURRENCY, '$', match => {
  const signed = match[0].includes('-');
  const stripped = match[0].replace(/[^0-9.]/g, '');
  const clipped = stripped.includes('.') ? stripped.slice(0, stripped.indexOf('.') + 3) : stripped;
  const USDollar = new Intl.NumberFormat('en-US', {
    style: 'currency',
    currency: 'USD'
  });
  const formatted = USDollar.format(Number(clipped)).replace(/\.00/, '');
  if (Number(clipped) > 0) {
    return signed ? '-' + formatted : formatted;
  } else {
    return '';
  }
});
exports.CURRENCY_MASK = CURRENCY_MASK;
function useLabelMask(maskFn, originalInputProps) {
  // TODO: Once we're on React 18, we can use the `useId` hook
  const generatedId = (0, _useId.default)('label-mask--');
  const labelMaskId = originalInputProps.id ? `${originalInputProps.id}__label-mask` : generatedId;
  const [focused, setFocused] = (0, _compat.useState)(false);
  const {
    onFocus,
    onBlur,
    onChange
  } = originalInputProps;
  const value = originalInputProps.value?.toString() ?? originalInputProps.defaultValue?.toString() ?? '';
  const [currentValue, setCurrentValue] = (0, _compat.useState)(value);
  (0, _compat.useEffect)(() => {
    setCurrentValue(value);
  }, [value, setCurrentValue]);
  const inputProps = {
    ...originalInputProps,
    defaultValue: undefined,
    value: currentValue,
    onChange: e => {
      setCurrentValue(e.currentTarget.value);
      if (onChange) {
        onChange(e);
      }
    },
    onFocus: e => {
      if (onFocus) {
        onFocus(e);
      }
      setFocused(true);
    },
    onBlur: e => {
      const maskedValue = maskFn(currentValue, true);
      e.currentTarget.value = maskedValue;
      e.target.value = maskedValue;
      setCurrentValue(maskedValue);
      if (onChange) {
        onChange(e);
      }
      if (onBlur) {
        onBlur(e);
      }
      setFocused(false);
    },
    type: 'text',
    inputMode: 'numeric',
    'aria-describedby': (0, _mergeIds.default)(originalInputProps['aria-describedby'], labelMaskId)
  };
  let currentMask = maskFn(currentValue);

  // Date mask needs to return the default empty mask when not focused
  if (maskFn === DATE_MASK && !focused) {
    currentMask = maskFn('');
  }

  // SSN mask needs to obfuscate the SSN when not focused
  if (maskFn === SSN_MASK && !focused && currentValue !== '') {
    currentMask = SSN_MASK_OBFUSCATED(currentValue);
    inputProps.value = SSN_MASK_OBFUSCATED(currentValue, true);
  }
  return {
    labelMask: /*#__PURE__*/(0, _jsxRuntime.jsxs)("div", {
      className: "ds-c-label-mask",
      id: labelMaskId,
      children: [/*#__PURE__*/(0, _jsxRuntime.jsx)("span", {
        className: (0, _classnames.default)(focused && 'ds-u-visibility--screen-reader'),
        children: currentMask
      }), /*#__PURE__*/(0, _jsxRuntime.jsx)("span", {
        className: (0, _classnames.default)(!focused && 'ds-u-display--none'),
        "aria-hidden": "true",
        children: currentMask
      })]
    }),
    inputProps
  };
}
var _default = useLabelMask;
exports.default = _default;