import { t, T as Trans, f as Button, j as Alert, b5 as TWOFA_PAGE, aT 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, b6 as Alerts, b7 as logo, b8 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 { O as OtpInput } from "./index2.js";
import "./validator.js";
import "./dateFns.js";
import "./reactPlayer.js";
import "react-router-dom";
import "./reactSlick.js";
var _2FA = "";
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 };
