// Copyright 1999-2023. Plesk International GmbH. All rights reserved.

import { useState, useEffect } from 'react';
import Popover from '../Popover';
import Translate from '../Translate';
import estimatePassword, { DEFAULT_RULES } from './estimatePassword';
import locale from './locale/en-US';
import { jsx as _jsx } from "react/jsx-runtime";
import { Fragment as _Fragment } from "react/jsx-runtime";
import { jsxs as _jsxs } from "react/jsx-runtime";
const strengthIntents = {
  VeryWeak: 'danger',
  Weak: 'danger',
  Medium: 'warning',
  Strong: 'success',
  VeryStrong: 'success'
};
const PasswordMeter = _ref => {
  let {
    value,
    visible,
    onEstimate,
    children,
    ...props
  } = _ref;
  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__*/_jsxs(Popover, {
    visible: visible && result !== null,
    placement: "bottom-right",
    intent: result ? strengthIntents[result.strength] : undefined,
    canCloseOnOutsideClick: false,
    canCloseOnEscapePress: false,
    ...props,
    target: children,
    children: [result?.strength ? /*#__PURE__*/_jsx(Translate, {
      component: "div",
      content: "FormFieldPassword.passwordStrength",
      fallback: locale.passwordStrength,
      params: {
        strength: /*#__PURE__*/_jsx("b", {
          children: /*#__PURE__*/_jsx(Translate, {
            content: `FormFieldPassword.strength${result?.strength}`,
            fallback: locale[`strength${result?.strength}`]
          })
        })
      }
    }) : null, result?.suggestions.length ? /*#__PURE__*/_jsxs(_Fragment, {
      children: [/*#__PURE__*/_jsx(Translate, {
        content: "FormFieldPassword.improvePassword",
        fallback: locale.improvePassword
      }), /*#__PURE__*/_jsx("br", {}), /*#__PURE__*/_jsx("ul", {
        children: result.suggestions.slice(0, 3).map((suggestion, index) =>
        /*#__PURE__*/
        // eslint-disable-next-line react/no-array-index-key
        _jsx("li", {
          children: suggestion
        }, index.toString()))
      })]
    }) : /*#__PURE__*/_jsx(Translate, {
      content: "FormFieldPassword.yourPasswordIsStrong",
      fallback: locale.yourPasswordIsStrong
    })]
  });
};
export default PasswordMeter;