import { t, T as Trans, f as Button, j as Alert, bc as TWOFA_PAGE, aZ as headerAlertsQueue, h as AlertType, E as ErrorHelper, i as CommonError, D as DesktopChecker, v as LoginPath, a as Ctx, k as UIEvent, l as bgCommon, bd as Alerts, be as logo, bf as UrlConstants, m as mod } from "./index.js";
import { A as AuthAppIcon, B as BackupCodeIcon, E as EmailIcon } from "./EmailIcon.js";
import React__default from "react";
import { C as Checkbox } from "./Checkbox.js";
import { g as getDefaultExportFromCjs } from "./dateFns.js";
import "./validator.js";
import "./reactPlayer.js";
import "react-router-dom";
import "./reactSlick.js";
var _2FA = "";
var lib = {};
(function(exports) {
  Object.defineProperty(exports, "__esModule", { value: true });
  exports["default"] = void 0;
  var _react = _interopRequireWildcard(React__default);
  var _excluded = ["placeholder", "separator", "isLastChild", "inputStyle", "focus", "isDisabled", "hasErrored", "errorStyle", "focusStyle", "disabledStyle", "shouldAutoFocus", "isInputNum", "index", "value", "className", "isInputSecure"];
  function _getRequireWildcardCache(nodeInterop) {
    if (typeof WeakMap !== "function")
      return null;
    var cacheBabelInterop = /* @__PURE__ */ new WeakMap();
    var cacheNodeInterop = /* @__PURE__ */ new WeakMap();
    return (_getRequireWildcardCache = function _getRequireWildcardCache2(nodeInterop2) {
      return nodeInterop2 ? cacheNodeInterop : cacheBabelInterop;
    })(nodeInterop);
  }
  function _interopRequireWildcard(obj, nodeInterop) {
    if (!nodeInterop && obj && obj.__esModule) {
      return obj;
    }
    if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") {
      return { "default": obj };
    }
    var cache = _getRequireWildcardCache(nodeInterop);
    if (cache && cache.has(obj)) {
      return cache.get(obj);
    }
    var newObj = {};
    var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor;
    for (var key in obj) {
      if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) {
        var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null;
        if (desc && (desc.get || desc.set)) {
          Object.defineProperty(newObj, key, desc);
        } else {
          newObj[key] = obj[key];
        }
      }
    }
    newObj["default"] = obj;
    if (cache) {
      cache.set(obj, newObj);
    }
    return newObj;
  }
  function _extends() {
    _extends = Object.assign || function(target) {
      for (var i = 1; i < arguments.length; i++) {
        var source = arguments[i];
        for (var key in source) {
          if (Object.prototype.hasOwnProperty.call(source, key)) {
            target[key] = source[key];
          }
        }
      }
      return target;
    };
    return _extends.apply(this, arguments);
  }
  function _objectWithoutProperties(source, excluded) {
    if (source == null)
      return {};
    var target = _objectWithoutPropertiesLoose(source, excluded);
    var key, i;
    if (Object.getOwnPropertySymbols) {
      var sourceSymbolKeys = Object.getOwnPropertySymbols(source);
      for (i = 0; i < sourceSymbolKeys.length; i++) {
        key = sourceSymbolKeys[i];
        if (excluded.indexOf(key) >= 0)
          continue;
        if (!Object.prototype.propertyIsEnumerable.call(source, key))
          continue;
        target[key] = source[key];
      }
    }
    return target;
  }
  function _objectWithoutPropertiesLoose(source, excluded) {
    if (source == null)
      return {};
    var target = {};
    var sourceKeys = Object.keys(source);
    var key, i;
    for (i = 0; i < sourceKeys.length; i++) {
      key = sourceKeys[i];
      if (excluded.indexOf(key) >= 0)
        continue;
      target[key] = source[key];
    }
    return target;
  }
  function _classCallCheck(instance, Constructor) {
    if (!(instance instanceof Constructor)) {
      throw new TypeError("Cannot call a class as a function");
    }
  }
  function _defineProperties(target, props) {
    for (var i = 0; i < props.length; i++) {
      var descriptor = props[i];
      descriptor.enumerable = descriptor.enumerable || false;
      descriptor.configurable = true;
      if ("value" in descriptor)
        descriptor.writable = true;
      Object.defineProperty(target, descriptor.key, descriptor);
    }
  }
  function _createClass(Constructor, protoProps, staticProps) {
    if (protoProps)
      _defineProperties(Constructor.prototype, protoProps);
    if (staticProps)
      _defineProperties(Constructor, staticProps);
    return Constructor;
  }
  function _inherits(subClass, superClass) {
    if (typeof superClass !== "function" && superClass !== null) {
      throw new TypeError("Super expression must either be null or a function");
    }
    subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } });
    if (superClass)
      _setPrototypeOf(subClass, superClass);
  }
  function _setPrototypeOf(o, p) {
    _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf2(o2, p2) {
      o2.__proto__ = p2;
      return o2;
    };
    return _setPrototypeOf(o, p);
  }
  function _createSuper(Derived) {
    var hasNativeReflectConstruct = _isNativeReflectConstruct();
    return function _createSuperInternal() {
      var Super = _getPrototypeOf(Derived), result;
      if (hasNativeReflectConstruct) {
        var NewTarget = _getPrototypeOf(this).constructor;
        result = Reflect.construct(Super, arguments, NewTarget);
      } else {
        result = Super.apply(this, arguments);
      }
      return _possibleConstructorReturn(this, result);
    };
  }
  function _possibleConstructorReturn(self, call) {
    if (call && (_typeof(call) === "object" || typeof call === "function")) {
      return call;
    }
    return _assertThisInitialized(self);
  }
  function _assertThisInitialized(self) {
    if (self === void 0) {
      throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
    }
    return self;
  }
  function _isNativeReflectConstruct() {
    if (typeof Reflect === "undefined" || !Reflect.construct)
      return false;
    if (Reflect.construct.sham)
      return false;
    if (typeof Proxy === "function")
      return true;
    try {
      Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function() {
      }));
      return true;
    } catch (e) {
      return false;
    }
  }
  function _getPrototypeOf(o) {
    _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf2(o2) {
      return o2.__proto__ || Object.getPrototypeOf(o2);
    };
    return _getPrototypeOf(o);
  }
  function _defineProperty(obj, key, value) {
    if (key in obj) {
      Object.defineProperty(obj, key, { value, enumerable: true, configurable: true, writable: true });
    } else {
      obj[key] = value;
    }
    return obj;
  }
  function _typeof(obj) {
    "@babel/helpers - typeof";
    if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
      _typeof = function _typeof2(obj2) {
        return typeof obj2;
      };
    } else {
      _typeof = function _typeof2(obj2) {
        return obj2 && typeof Symbol === "function" && obj2.constructor === Symbol && obj2 !== Symbol.prototype ? "symbol" : typeof obj2;
      };
    }
    return _typeof(obj);
  }
  var BACKSPACE = 8;
  var LEFT_ARROW = 37;
  var RIGHT_ARROW = 39;
  var DELETE = 46;
  var SPACEBAR = 32;
  var isStyleObject = function isStyleObject2(obj) {
    return _typeof(obj) === "object";
  };
  var SingleOtpInput = function(_PureComponent) {
    _inherits(SingleOtpInput2, _PureComponent);
    var _super = _createSuper(SingleOtpInput2);
    function SingleOtpInput2(props) {
      var _this;
      _classCallCheck(this, SingleOtpInput2);
      _this = _super.call(this, props);
      _defineProperty(_assertThisInitialized(_this), "getClasses", function() {
        for (var _len = arguments.length, classes = new Array(_len), _key = 0; _key < _len; _key++) {
          classes[_key] = arguments[_key];
        }
        return classes.filter(function(c) {
          return !isStyleObject(c) && c !== false;
        }).join(" ");
      });
      _defineProperty(_assertThisInitialized(_this), "getType", function() {
        var _this$props = _this.props, isInputSecure = _this$props.isInputSecure, isInputNum = _this$props.isInputNum;
        if (isInputSecure) {
          return "password";
        }
        if (isInputNum) {
          return "tel";
        }
        return "text";
      });
      _this.input = _react["default"].createRef();
      return _this;
    }
    _createClass(SingleOtpInput2, [{ key: "componentDidMount", value: function componentDidMount() {
      var _this$props2 = this.props, focus = _this$props2.focus, shouldAutoFocus = _this$props2.shouldAutoFocus;
      var inputEl = this.input.current;
      if (inputEl && focus && shouldAutoFocus) {
        inputEl.focus();
      }
    } }, { key: "componentDidUpdate", value: function componentDidUpdate(prevProps) {
      var focus = this.props.focus;
      var inputEl = this.input.current;
      if (prevProps.focus !== focus && inputEl && focus) {
        inputEl.focus();
        inputEl.select();
      }
    } }, { key: "render", value: function render() {
      var _this$props3 = this.props, placeholder = _this$props3.placeholder, separator = _this$props3.separator, isLastChild = _this$props3.isLastChild, inputStyle = _this$props3.inputStyle, focus = _this$props3.focus, isDisabled = _this$props3.isDisabled, hasErrored = _this$props3.hasErrored, errorStyle = _this$props3.errorStyle, focusStyle = _this$props3.focusStyle, disabledStyle = _this$props3.disabledStyle;
      _this$props3.shouldAutoFocus;
      var isInputNum = _this$props3.isInputNum, index = _this$props3.index, value = _this$props3.value, className = _this$props3.className;
      _this$props3.isInputSecure;
      var rest = _objectWithoutProperties(_this$props3, _excluded);
      return _react["default"].createElement("div", { className, style: { display: "flex", alignItems: "center" } }, _react["default"].createElement("input", _extends({ "aria-label": "".concat(index === 0 ? "Please enter verification code. " : "").concat(isInputNum ? "Digit" : "Character", " ").concat(index + 1), autoComplete: "off", style: Object.assign({ width: "1em", textAlign: "center" }, isStyleObject(inputStyle) && inputStyle, focus && isStyleObject(focusStyle) && focusStyle, isDisabled && isStyleObject(disabledStyle) && disabledStyle, hasErrored && isStyleObject(errorStyle) && errorStyle), placeholder, className: this.getClasses(inputStyle, focus && focusStyle, isDisabled && disabledStyle, hasErrored && errorStyle), type: this.getType(), maxLength: "1", ref: this.input, disabled: isDisabled, value: value ? value : "" }, rest)), !isLastChild && separator);
    } }]);
    return SingleOtpInput2;
  }(_react.PureComponent);
  var OtpInput2 = function(_Component) {
    _inherits(OtpInput3, _Component);
    var _super2 = _createSuper(OtpInput3);
    function OtpInput3() {
      var _this2;
      _classCallCheck(this, OtpInput3);
      for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
        args[_key2] = arguments[_key2];
      }
      _this2 = _super2.call.apply(_super2, [this].concat(args));
      _defineProperty(_assertThisInitialized(_this2), "state", { activeInput: 0 });
      _defineProperty(_assertThisInitialized(_this2), "getOtpValue", function() {
        return _this2.props.value ? _this2.props.value.toString().split("") : [];
      });
      _defineProperty(_assertThisInitialized(_this2), "getPlaceholderValue", function() {
        var _this2$props = _this2.props, placeholder = _this2$props.placeholder, numInputs = _this2$props.numInputs;
        if (typeof placeholder === "string") {
          if (placeholder.length === numInputs) {
            return placeholder;
          }
          if (placeholder.length > 0) {
            console.error("Length of the placeholder should be equal to the number of inputs.");
          }
        }
      });
      _defineProperty(_assertThisInitialized(_this2), "handleOtpChange", function(otp) {
        var onChange = _this2.props.onChange;
        var otpValue = otp.join("");
        onChange(otpValue);
      });
      _defineProperty(_assertThisInitialized(_this2), "isInputValueValid", function(value) {
        var isTypeValid = _this2.props.isInputNum ? !isNaN(parseInt(value, 10)) : typeof value === "string";
        return isTypeValid && value.trim().length === 1;
      });
      _defineProperty(_assertThisInitialized(_this2), "focusInput", function(input) {
        var numInputs = _this2.props.numInputs;
        var activeInput = Math.max(Math.min(numInputs - 1, input), 0);
        _this2.setState({ activeInput });
      });
      _defineProperty(_assertThisInitialized(_this2), "focusNextInput", function() {
        var activeInput = _this2.state.activeInput;
        _this2.focusInput(activeInput + 1);
      });
      _defineProperty(_assertThisInitialized(_this2), "focusPrevInput", function() {
        var activeInput = _this2.state.activeInput;
        _this2.focusInput(activeInput - 1);
      });
      _defineProperty(_assertThisInitialized(_this2), "changeCodeAtFocus", function(value) {
        var activeInput = _this2.state.activeInput;
        var otp = _this2.getOtpValue();
        otp[activeInput] = value[0];
        _this2.handleOtpChange(otp);
      });
      _defineProperty(_assertThisInitialized(_this2), "handleOnPaste", function(e) {
        e.preventDefault();
        var activeInput = _this2.state.activeInput;
        var _this2$props2 = _this2.props, numInputs = _this2$props2.numInputs, isDisabled = _this2$props2.isDisabled;
        if (isDisabled) {
          return;
        }
        var otp = _this2.getOtpValue();
        var nextActiveInput = activeInput;
        var pastedData = e.clipboardData.getData("text/plain").slice(0, numInputs - activeInput).split("");
        for (var pos = 0; pos < numInputs; ++pos) {
          if (pos >= activeInput && pastedData.length > 0) {
            otp[pos] = pastedData.shift();
            nextActiveInput++;
          }
        }
        _this2.setState({ activeInput: nextActiveInput }, function() {
          _this2.focusInput(nextActiveInput);
          _this2.handleOtpChange(otp);
        });
      });
      _defineProperty(_assertThisInitialized(_this2), "handleOnChange", function(e) {
        var value = e.target.value;
        if (_this2.isInputValueValid(value)) {
          _this2.changeCodeAtFocus(value);
        }
      });
      _defineProperty(_assertThisInitialized(_this2), "handleOnKeyDown", function(e) {
        if (e.keyCode === BACKSPACE || e.key === "Backspace") {
          e.preventDefault();
          _this2.changeCodeAtFocus("");
          _this2.focusPrevInput();
        } else if (e.keyCode === DELETE || e.key === "Delete") {
          e.preventDefault();
          _this2.changeCodeAtFocus("");
        } else if (e.keyCode === LEFT_ARROW || e.key === "ArrowLeft") {
          e.preventDefault();
          _this2.focusPrevInput();
        } else if (e.keyCode === RIGHT_ARROW || e.key === "ArrowRight") {
          e.preventDefault();
          _this2.focusNextInput();
        } else if (e.keyCode === SPACEBAR || e.key === " " || e.key === "Spacebar" || e.key === "Space") {
          e.preventDefault();
        }
      });
      _defineProperty(_assertThisInitialized(_this2), "handleOnInput", function(e) {
        if (_this2.isInputValueValid(e.target.value)) {
          _this2.focusNextInput();
        } else {
          if (!_this2.props.isInputNum) {
            var nativeEvent = e.nativeEvent;
            if (nativeEvent.data === null && nativeEvent.inputType === "deleteContentBackward") {
              e.preventDefault();
              _this2.changeCodeAtFocus("");
              _this2.focusPrevInput();
            }
          }
        }
      });
      _defineProperty(_assertThisInitialized(_this2), "renderInputs", function() {
        var activeInput = _this2.state.activeInput;
        var _this2$props3 = _this2.props, numInputs = _this2$props3.numInputs, inputStyle = _this2$props3.inputStyle, focusStyle = _this2$props3.focusStyle, separator = _this2$props3.separator, isDisabled = _this2$props3.isDisabled, disabledStyle = _this2$props3.disabledStyle, hasErrored = _this2$props3.hasErrored, errorStyle = _this2$props3.errorStyle, shouldAutoFocus = _this2$props3.shouldAutoFocus, isInputNum = _this2$props3.isInputNum, isInputSecure = _this2$props3.isInputSecure, className = _this2$props3.className;
        var inputs = [];
        var otp = _this2.getOtpValue();
        var placeholder = _this2.getPlaceholderValue();
        var dataCy = _this2.props["data-cy"];
        var dataTestId = _this2.props["data-testid"];
        var _loop = function _loop2(i2) {
          inputs.push(_react["default"].createElement(SingleOtpInput, { placeholder: placeholder && placeholder[i2], key: i2, index: i2, focus: activeInput === i2, value: otp && otp[i2], onChange: _this2.handleOnChange, onKeyDown: _this2.handleOnKeyDown, onInput: _this2.handleOnInput, onPaste: _this2.handleOnPaste, onFocus: function onFocus(e) {
            _this2.setState({ activeInput: i2 });
            e.target.select();
          }, onBlur: function onBlur() {
            return _this2.setState({ activeInput: -1 });
          }, separator, inputStyle, focusStyle, isLastChild: i2 === numInputs - 1, isDisabled, disabledStyle, hasErrored, errorStyle, shouldAutoFocus, isInputNum, isInputSecure, className, "data-cy": dataCy && "".concat(dataCy, "-").concat(i2), "data-testid": dataTestId && "".concat(dataTestId, "-").concat(i2) }));
        };
        for (var i = 0; i < numInputs; i++) {
          _loop(i);
        }
        return inputs;
      });
      return _this2;
    }
    _createClass(OtpInput3, [{ key: "render", value: function render() {
      var containerStyle = this.props.containerStyle;
      return _react["default"].createElement("div", { style: Object.assign({ display: "flex" }, isStyleObject(containerStyle) && containerStyle), className: !isStyleObject(containerStyle) ? containerStyle : "" }, this.renderInputs());
    } }]);
    return OtpInput3;
  }(_react.Component);
  _defineProperty(OtpInput2, "defaultProps", { numInputs: 4, onChange: function onChange(otp) {
    return console.log(otp);
  }, isDisabled: false, shouldAutoFocus: false, value: "", isInputSecure: false });
  var _default = OtpInput2;
  exports["default"] = _default;
})(lib);
var OtpInput = /* @__PURE__ */ getDefaultExportFromCjs(lib);
class CodeInput extends React__default.Component {
  constructor(props) {
    super(props);
    this.onCodeChange = (value) => {
      this.setState({ code: value });
    };
    this.onRememberDeviceChange = () => {
      this.setState((prevState) => ({
        rememberDevice: !prevState.rememberDevice
      }));
    };
    this.submit = () => {
      const { factor } = this.props;
      const { code, rememberDevice } = this.state;
      this.props.onSubmit({ code, factor, rememberDevice });
    };
    this.onKeyDown = (event) => {
      if (event.key !== "Enter" || this.state.code.length < this.props.codeLength)
        return;
      this.submit();
    };
    this.state = {
      code: "",
      rememberDevice: true
    };
  }
  componentDidMount() {
    window.addEventListener("keydown", this.onKeyDown);
  }
  componentWillUnmount() {
    window.removeEventListener("keydown", this.onKeyDown);
  }
  render() {
    const { codeLength, isSubmitting, onTryAnother, helperText } = this.props;
    const { code, rememberDevice } = this.state;
    return /* @__PURE__ */ React__default.createElement(React__default.Fragment, null, /* @__PURE__ */ React__default.createElement(OtpInput, {
      value: code,
      onChange: this.onCodeChange,
      numInputs: codeLength,
      className: "otpInput",
      containerStyle: "otpInputContainer",
      focusStyle: "otpInput__focus",
      shouldAutoFocus: true,
      isDisabled: isSubmitting
    }), helperText, /* @__PURE__ */ React__default.createElement("div", {
      className: "rememberDeviceContainer"
    }, /* @__PURE__ */ React__default.createElement(Checkbox, {
      isChecked: rememberDevice,
      onChange: this.onRememberDeviceChange,
      label: t("twoFAPage.checkbox.rememberDevice")
    }), !!onTryAnother && /* @__PURE__ */ React__default.createElement("span", {
      className: "tryAnother",
      onClick: onTryAnother
    }, /* @__PURE__ */ React__default.createElement(Trans, {
      i18nKey: "twoFAPage.tryAnother"
    }, "Try another way"))), /* @__PURE__ */ React__default.createElement(Button, {
      loadingIndicator: "SPINNER",
      className: "continueButton btn btn-primary",
      onClick: this.submit,
      disabled: code.length < codeLength,
      isLoading: isSubmitting
    }, t("UpgradeHeadlessAccountPage.UpgradeHeadlessAccountPage.continue")));
  }
}
const MethodOption = (props) => {
  const { icon, description, onClick } = props;
  return /* @__PURE__ */ React__default.createElement("div", {
    className: "methodOption",
    onClick
  }, icon, /* @__PURE__ */ React__default.createElement("p", null, description));
};
const PageContent = (props) => {
  const { title, alert, withAlert, description, children, onDismissAlert } = props;
  return /* @__PURE__ */ React__default.createElement(React__default.Fragment, null, /* @__PURE__ */ React__default.createElement("div", {
    className: "titleWrapper"
  }, /* @__PURE__ */ React__default.createElement("p", {
    className: "title"
  }, title), !!alert && withAlert && /* @__PURE__ */ React__default.createElement(Alert, {
    type: alert.type,
    onDismiss: onDismissAlert,
    className: "text-left"
  }, alert.element), /* @__PURE__ */ React__default.createElement("p", {
    className: "description"
  }, description)), children);
};
const MFA_PAGE_STORAGE_KEY = "mfaPage";
const AUTHENTICATOR_CODE_LENGTH = 6;
const BACKUP_CODE_LENGTH = 8;
const EMAIL_CODE_LENGTH = 6;
const MFA_ERROR_TYPE = mod.enum(["invalid_code", "invalid_factor", "invalid_mfa_token", "code_expired"]);
const MFAError = mod.object({
  error: mod.string(),
  error_description: mod.string()
});
const getDisplayedError = (error) => {
  var _a;
  try {
    if (ErrorHelper.isAxiosError(error)) {
      const errorResponse = MFAError.parse((_a = error == null ? void 0 : error.response) == null ? void 0 : _a.data);
      switch (errorResponse.error) {
        case MFA_ERROR_TYPE.Enum.invalid_code:
          return /* @__PURE__ */ React__default.createElement(Trans, {
            i18nKey: "twoFAPage.error.invalidCode"
          }, "Sorry, the code you entered is invalid. Please try again.");
        case MFA_ERROR_TYPE.Enum.code_expired:
          return /* @__PURE__ */ React__default.createElement(Trans, {
            i18nKey: "twoFAPage.error.codeExpired"
          }, "Sorry, the code you entered is expired. Please try again.");
        case MFA_ERROR_TYPE.Enum.invalid_factor:
        case MFA_ERROR_TYPE.Enum.invalid_mfa_token:
          return /* @__PURE__ */ React__default.createElement(Trans, {
            i18nKey: "twoFAPage.error.invalidFactor"
          }, "Failed to complete the request. Please click the back to login button below, and try logging in again.");
      }
    }
    throw error;
  } catch (e) {
    return /* @__PURE__ */ React__default.createElement(CommonError, {
      error
    });
  }
};
class TwoFactorAuthentication extends React__default.Component {
  constructor(props) {
    super(props);
    this.changePage = (page) => {
      this.setState({ page });
      sessionStorage.setItem(MFA_PAGE_STORAGE_KEY, page);
    };
    this.onTryAnother = () => {
      this.changePage(TWOFA_PAGE.enum.options);
      this.setState({ alert: null });
    };
    this.dismissAlert = () => {
      this.setState({ alert: null });
    };
    this.submitCode = async (param) => {
      if (this.state.isLoading)
        return;
      try {
        this.setState({ isLoading: true });
        const result = await this.userManager.verify2FA(param);
        if (result) {
          this.appState.refreshSession(result.access_token, result.refresh_token);
          await this.appState.refreshUser();
          this.userManager.removeMFAData();
          if (this.userManager.state.isLinkingAccount) {
            headerAlertsQueue.push({
              type: AlertType.success,
              element: /* @__PURE__ */ React__default.createElement(Trans, {
                i18nKey: "LinkPlatformAccountPage.notification.accountLinked"
              }, "Account linked")
            });
            this.userManager.setState({ isLinkingAccount: false });
          }
        }
      } catch (error) {
        console.error(error);
        if (ErrorHelper.isAxiosNetworkError(error)) {
          headerAlertsQueue.push({
            type: AlertType.danger,
            element: t("CommonError.networkError")
          });
          return;
        }
        const displayedError = getDisplayedError(error);
        this.setState({ alert: { type: AlertType.danger, element: displayedError } });
      } finally {
        this.setState({ isLoading: false });
      }
    };
    this.requestEmailCode = async (isResend) => {
      if (this.state.isLoading)
        return;
      try {
        this.setState({ isLoading: true });
        await this.userManager.request2FAEmailCode({ factor: "email" });
        if (isResend) {
          this.setState({ alert: { type: AlertType.success, element: t("twoFAPage.email.resend.success") } });
        }
        this.changePage(TWOFA_PAGE.enum.email);
      } catch (error) {
        if (ErrorHelper.isAxiosNetworkError(error)) {
          headerAlertsQueue.push({
            type: AlertType.danger,
            element: t("CommonError.networkError")
          });
          return;
        }
        this.setState({ alert: { type: AlertType.danger, element: /* @__PURE__ */ React__default.createElement(CommonError, {
          error
        }) } });
      } finally {
        this.setState({ isLoading: false });
      }
    };
    this.getCodeLength = (factor) => {
      switch (factor) {
        case TWOFA_PAGE.enum.backupCode:
          return BACKUP_CODE_LENGTH;
        case TWOFA_PAGE.enum.authenticator:
          return AUTHENTICATOR_CODE_LENGTH;
        default:
          return EMAIL_CODE_LENGTH;
      }
    };
    this.renderHelperTextEmail = () => {
      return /* @__PURE__ */ React__default.createElement("div", {
        className: "mt-3 text-[13px]"
      }, /* @__PURE__ */ React__default.createElement("span", null, t("AccountPasswordSecurity.2fa.emailModal.helperText")), /* @__PURE__ */ React__default.createElement("span", {
        className: "ml-1 cursor-pointer text-blue-50",
        onClick: () => this.requestEmailCode(true)
      }, t("AccountPasswordSecurity.2fa.emailModal.resendBtn")));
    };
    this.renderCodeInput = (factor, helperText) => {
      var _a;
      const factors = ((_a = this.userManager.state.mfaData) == null ? void 0 : _a.factors) || [];
      return /* @__PURE__ */ React__default.createElement(CodeInput, {
        onTryAnother: factors.length > 1 ? this.onTryAnother : void 0,
        codeLength: this.getCodeLength(factor),
        factor,
        onSubmit: this.submitCode,
        isSubmitting: this.state.isLoading,
        helperText
      });
    };
    this.resetMFADataAndLogout = () => {
      sessionStorage.removeItem(MFA_PAGE_STORAGE_KEY);
      this.userManager.removeMFAData();
      this.appState.logout();
      if (!DesktopChecker.isDesktopApp()) {
        this.appState.state.appHistory.push(LoginPath.Login.link);
      }
    };
    this.state = {
      page: null,
      isLoading: false,
      alert: null
    };
    this.appState = Ctx.getAppState();
    this.userManager = this.appState.userAppManager;
  }
  componentDidMount() {
    var _a;
    UIEvent.updateBackground(`url(${bgCommon})`);
    const defaultFactor = (_a = this.userManager.state.mfaData) == null ? void 0 : _a.defaultFactor;
    const storedPage = sessionStorage.getItem(MFA_PAGE_STORAGE_KEY);
    this.setState({ page: storedPage || defaultFactor || TWOFA_PAGE.enum.options });
  }
  render() {
    var _a;
    const factors = ((_a = this.userManager.state.mfaData) == null ? void 0 : _a.factors) || [];
    const { alert, page } = this.state;
    return /* @__PURE__ */ React__default.createElement("div", {
      className: "twoFAPage"
    }, /* @__PURE__ */ React__default.createElement(Alerts, {
      className: "twoFAAlert"
    }), /* @__PURE__ */ React__default.createElement("div", {
      className: "twoFAContainer"
    }, /* @__PURE__ */ React__default.createElement("div", {
      className: "flex justify-center"
    }, /* @__PURE__ */ React__default.createElement("img", {
      src: logo,
      loading: "lazy"
    })), /* @__PURE__ */ React__default.createElement("div", {
      className: "twoFAForm"
    }, page === TWOFA_PAGE.enum.authenticator && /* @__PURE__ */ React__default.createElement(PageContent, {
      title: t("twoFAPage.authenticator.title"),
      description: /* @__PURE__ */ React__default.createElement(Trans, {
        i18nKey: "twoFAPage.authenticator.description"
      }, "Please enter the security code from your authenticator app.", /* @__PURE__ */ React__default.createElement("a", {
        href: UrlConstants.DOCS_FAQ_URL,
        target: "_blank",
        rel: "noreferrer"
      }, "Learn more")),
      withAlert: true,
      alert,
      onDismissAlert: this.dismissAlert
    }, this.renderCodeInput(TWOFA_PAGE.enum.authenticator)), page === TWOFA_PAGE.enum.backupCode && /* @__PURE__ */ React__default.createElement(PageContent, {
      title: t("twoFAPage.backupCode.title"),
      description: /* @__PURE__ */ React__default.createElement(Trans, {
        i18nKey: "twoFAPage.backupCode.description"
      }, "Please enter one of your backup codes to continue.", /* @__PURE__ */ React__default.createElement("a", {
        href: UrlConstants.DOCS_FAQ_URL,
        target: "_blank",
        rel: "noreferrer"
      }, "Learn more")),
      withAlert: true,
      alert,
      onDismissAlert: this.dismissAlert
    }, this.renderCodeInput(TWOFA_PAGE.enum.backupCode)), page === TWOFA_PAGE.enum.email && /* @__PURE__ */ React__default.createElement(PageContent, {
      title: t("twoFAPage.email.title"),
      description: /* @__PURE__ */ React__default.createElement(Trans, {
        i18nKey: "twoFAPage.email.description"
      }, "To continue, please enter the verification code we\u2019ve sent to your email at", /* @__PURE__ */ React__default.createElement("strong", null, { email: this.userManager.getEmailUserFromMfaData() }), ".", /* @__PURE__ */ React__default.createElement("a", {
        href: "https://docs.accelbyte.io/faq/faq.html",
        target: "_blank",
        rel: "noreferrer"
      }, "Learn more")),
      withAlert: true,
      alert: this.state.alert,
      onDismissAlert: this.dismissAlert
    }, this.renderCodeInput(TWOFA_PAGE.enum.email, this.renderHelperTextEmail())), page === TWOFA_PAGE.enum.options && /* @__PURE__ */ React__default.createElement(PageContent, {
      title: t("twoFAPage.verify.title"),
      description: t("twoFAPage.verify.description")
    }, !!alert && /* @__PURE__ */ React__default.createElement(Alert, {
      type: alert.type,
      onDismiss: this.dismissAlert,
      className: "text-left"
    }, alert.element), factors.includes(TWOFA_PAGE.enum.authenticator) && /* @__PURE__ */ React__default.createElement(MethodOption, {
      icon: /* @__PURE__ */ React__default.createElement(AuthAppIcon, null),
      description: t("twoFAPage.verify.authApp.description"),
      onClick: () => this.changePage(TWOFA_PAGE.enum.authenticator)
    }), factors.includes(TWOFA_PAGE.enum.backupCode) && /* @__PURE__ */ React__default.createElement(MethodOption, {
      icon: /* @__PURE__ */ React__default.createElement(BackupCodeIcon, null),
      description: t("twoFAPage.verify.backupCode.description"),
      onClick: () => this.changePage(TWOFA_PAGE.enum.backupCode)
    }), factors.includes(TWOFA_PAGE.enum.email) && /* @__PURE__ */ React__default.createElement(MethodOption, {
      icon: /* @__PURE__ */ React__default.createElement(EmailIcon, null),
      description: t("twoFAPage.verify.email.description"),
      onClick: () => this.requestEmailCode(false)
    }))), /* @__PURE__ */ React__default.createElement("div", {
      className: "backContainer"
    }, /* @__PURE__ */ React__default.createElement("button", {
      onClick: this.resetMFADataAndLogout
    }, /* @__PURE__ */ React__default.createElement(Trans, {
      i18nKey: "twoFAPage.backToLogin"
    }, "Back to Login")))));
  }
}
export { TwoFactorAuthentication as default };
