import _extends from "@babel/runtime/helpers/extends";
// Copyright 1999-2022. Plesk International GmbH. All rights reserved.
import React, { Fragment, useState, useEffect } from 'react';
import Popover from '../Popover';
import Translate from '../Translate';
import estimatePassword, { DEFAULT_RULES } from './estimatePassword';
import locale from './locale/en-US';
const strengthIntents = {
  VeryWeak: 'danger',
  Weak: 'danger',
  Medium: 'warning',
  Strong: 'success',
  VeryStrong: 'success'
};

const PasswordMeter = ({
  value,
  visible,
  onEstimate,
  children,
  ...props
}) => {
  const [result, setResult] = useState(null);
  useEffect(() => {
    if (!visible) {
      return;
    }

    Promise.resolve(onEstimate ? onEstimate(value, estimatePassword, DEFAULT_RULES) : estimatePassword(value)).then(result => {
      setResult(result);
    });
  }, [visible, value, onEstimate]);
  return /*#__PURE__*/React.createElement(Popover, _extends({
    visible: visible && result !== null,
    target: children,
    placement: "bottom-right",
    intent: result ? strengthIntents[result.strength] : undefined,
    canCloseOnOutsideClick: false,
    canCloseOnEscapePress: false
  }, props), result !== null && result !== void 0 && result.strength ? /*#__PURE__*/React.createElement(Translate, {
    component: "div",
    content: "FormFieldPassword.passwordStrength",
    fallback: locale.passwordStrength,
    params: {
      strength: /*#__PURE__*/React.createElement("b", null, /*#__PURE__*/React.createElement(Translate, {
        content: `FormFieldPassword.strength${result === null || result === void 0 ? void 0 : result.strength}`,
        fallback: locale[`strength${result === null || result === void 0 ? void 0 : result.strength}`]
      }))
    }
  }) : null, result !== null && result !== void 0 && result.suggestions.length ? /*#__PURE__*/React.createElement(Fragment, null, /*#__PURE__*/React.createElement(Translate, {
    content: "FormFieldPassword.improvePassword",
    fallback: locale.improvePassword
  }), /*#__PURE__*/React.createElement("br", null), /*#__PURE__*/React.createElement("ul", null, result.suggestions.slice(0, 3).map((suggestion, index) => /*#__PURE__*/React.createElement("li", {
    key: index.toString()
  }, suggestion)))) : /*#__PURE__*/React.createElement(Translate, {
    content: "FormFieldPassword.yourPasswordIsStrong",
    fallback: locale.yourPasswordIsStrong
  }));
};

export default PasswordMeter;