import { Button as P } from "./accelbyte-widgets107.mjs";
import { CommonError as w } from "./accelbyte-widgets124.mjs";
import { FormGroupError as E, FormGroup as h } from "./accelbyte-widgets263.mjs";
import { InputGroup as y } from "./accelbyte-widgets229.mjs";
import { InputGroupPassword as S } from "./accelbyte-widgets264.mjs";
import L from "classnames";
import { t as g } from "./accelbyte-widgets58.mjs";
import { IpcChannels as N } from "./accelbyte-widgets148.mjs";
import { Ctx as R } from "./accelbyte-widgets33.mjs";
import { AlertType as C } from "./accelbyte-widgets128.mjs";
import { GlobalPath as b } from "./accelbyte-widgets104.mjs";
import { ErrorHelper as f } from "./accelbyte-widgets120.mjs";
import { UserHelper as A } from "./accelbyte-widgets277.mjs";
import { DesktopChecker as x } from "@accelbyte/sdk";
import { IamUserAuthorizationClient as v } from "@accelbyte/sdk-iam";
import e from "react";
import { Trans as a } from "react-i18next";
import k from "validator/lib/isEmpty.js";
import { redirectAfterSuccessLinkAccount as D } from "./accelbyte-widgets364.mjs";
import { ConfirmationLinkAccountDialog as T } from "./accelbyte-widgets365.mjs";
import { LinkAccountDeletionError as _ } from "./accelbyte-widgets366.mjs";
import { LinkBannedAccountError as I } from "./accelbyte-widgets367.mjs";
import { TokenExpiredDialogError as O } from "./accelbyte-widgets368.mjs";
import p from "./accelbyte-widgets369.mjs";
import { validateNotEmpty as U } from "./accelbyte-widgets370.mjs";
import { validateNumeric as K } from "./accelbyte-widgets371.mjs";
import { Validation as M } from "./accelbyte-widgets269.mjs";
import { CommonValidationErrorType as d } from "./accelbyte-widgets341.mjs";
const F = 100;
class he extends e.Component {
  constructor(n) {
    super(n), this.onEmailChange = (t) => {
      const o = t.target.value;
      this.validation.set("email", U(o)), this.setState({ email: t.target.value });
    }, this.onPasswordChange = (t) => {
      const o = t.target.value;
      this.validation.set("password", K(String(o.length), { max: F })), this.setState({ password: o });
    }, this.openConfirmationDialog = () => {
      this.validation.isAllValid() && this.setState({ dialogType: "CONFIRMATION" });
    }, this.openErrorLinkDeletionAccount = () => {
      this.setState({ dialogType: "LINK_DELETION_ACCOUNT_ERROR" });
    }, this.openTokenExpiredErrorDialog = () => {
      this.setState({ dialogType: "TOKEN_EXPIRED_ERROR" });
    }, this.openErrorLinkBannedUser = () => {
      this.setState({ dialogType: "BANNED_USER_ERROR" });
    }, this.closeDialog = () => {
      this.setState({ dialogType: null });
    }, this.forgotPassword = () => {
      const t = this.appState.getSdk(), o = new v(t).createForgotPasswordURL(), { onOpenForgotPassword: i } = this.props;
      i && i(), x.isDesktopApp() ? Device.send(N.OPEN_EXTERNAL, o) : window.location.replace(o);
    }, this.setErrorAlert = (t) => {
      var r, c, u;
      const { setAlert: o, platformId: i } = this.props, s = A.getPlatformName(i), m = f.extractServiceErrorCode(t), l = f.isAxiosError(t) && ((u = (c = (r = t == null ? void 0 : t.response) == null ? void 0 : r.data) == null ? void 0 : c.messageVariables) == null ? void 0 : u.remainingAttempt);
      o({
        type: C.danger,
        message: (() => {
          switch (m) {
            case 10197:
            case 20019:
              return l ? /* @__PURE__ */ e.createElement(a, { i18nKey: "linkPlatformAccountPage.LinkExistingAccount.invalidUsernamePasswordWithRemainingAttempt" }, "Invalid username, email, or password. You have ", { remainingAttempt: l }, " remaining login attempts before your account is locked.") : /* @__PURE__ */ e.createElement(a, { i18nKey: "linkPlatformAccountPage.LinkExistingAccount.invalidUsernamePassword" }, "Incorrect email, username or password.");
            case 10163:
              return /* @__PURE__ */ e.createElement(a, { i18nKey: "linkPlatformAccountPage.LinkExistingAccount.alreadyLinkedError" }, "This account is already linked with other ", { platformName: s }, " account. Please try to link with another account.");
            case 10200:
              return /* @__PURE__ */ e.createElement(a, { i18nKey: "linkPlatformAccountPage.LinkExistingAccount.unableToLink" }, "Unable to link this account. Because it has linked to other ", { platformName: s }, " account previously. Please use another account or create a new one instead.");
            case 20007:
              return /* @__PURE__ */ e.createElement(a, { i18nKey: "linkPlatformAccountPage.error.tooManyAttempt" }, "Multiple failed login attempts detected. Your account has been temporarily locked for security reasons.");
            default:
              return /* @__PURE__ */ e.createElement(w, { error: t });
          }
        })()
      });
    }, this.onRequired2FA = async (t) => {
      const o = this.appState.getUserManager(), i = this.appState.state.appHistory;
      await o.setState({ mfaData: t, isLinkingAccount: !0 }), i.replace(b.Home.link);
    }, this.onSubmit = async () => {
      if (!this.validation.isAllValid())
        return;
      const { email: t, password: o } = this.state, { linkingToken: i, clientId: s, platformId: m } = this.props, l = this.appState.state.appHistory;
      try {
        this.setState({ isSubmitting: !0 });
        const r = await this.linkedAccountsManager.linkExistingAccount({
          email: t,
          password: o,
          linkingToken: i,
          clientId: s,
          onTokenExpired: this.openTokenExpiredErrorDialog,
          onErrorLinkDeletion: this.openErrorLinkDeletionAccount,
          onErrorUserBanned: this.openErrorLinkBannedUser,
          onRequired2FA: this.onRequired2FA
        });
        r != null && r.user_id && (r != null && r.access_token) && (this.appState.refreshSession(r.access_token, r.refresh_token), await this.appState.updateUserCustomAttribute(r.user_id, m), await this.appState.refreshUser(), await D(l));
      } catch (r) {
        this.setErrorAlert(r), console.error(r), this.closeDialog();
      } finally {
        this.setState({ isSubmitting: !1 }), this.closeDialog();
      }
    }, this.state = {
      email: "",
      password: "",
      dialogType: null,
      isSubmitting: !1
    }, this.validation = new M(), this.validation.listen(() => this.setState({})), this.appState = R.getAppState(), this.linkedAccountsManager = this.appState.linkAccountManager;
  }
  renderPasswordError(n) {
    if (!n)
      return null;
    const t = {
      [d.enum.empty]: /* @__PURE__ */ e.createElement(a, { i18nKey: "linkPlatformAccountPage.LinkExistingAccount.PasswordError.empty" }, "Please input your password"),
      [d.enum.exceedMaximumValue]: /* @__PURE__ */ e.createElement(a, { i18nKey: "linkPlatformAccountPage.LinkExistingAccount.paswordTooLong" }, "Your password is too long")
    };
    return /* @__PURE__ */ e.createElement(E, null, t[n]);
  }
  renderEmailError(n) {
    if (!n)
      return null;
    const t = {
      [d.enum.empty]: /* @__PURE__ */ e.createElement(a, { i18nKey: "linkPlatformAccountPage.LinkExistingAccount.EmailOrUsernameFormError.empty" }, "Email or Username is required")
    };
    return /* @__PURE__ */ e.createElement(E, null, t[n]);
  }
  render() {
    const { email: n, password: t, dialogType: o, isSubmitting: i } = this.state, { platformId: s, backToLogin: m, isPreviewMode: l } = this.props, r = !this.validation.isAllValid() || k(n) || k(t);
    return /* @__PURE__ */ e.createElement(e.Fragment, null, /* @__PURE__ */ e.createElement(
      "form",
      {
        onSubmit: (c) => {
          c.preventDefault(), this.openConfirmationDialog();
        }
      },
      /* @__PURE__ */ e.createElement(h, null, /* @__PURE__ */ e.createElement("div", { className: p.label }, /* @__PURE__ */ e.createElement(a, { i18nKey: "linkPlatformAccountPage.LinkExistingAccount.formLabel.email" }, "Email")), /* @__PURE__ */ e.createElement(
        y,
        {
          type: "text",
          placeholder: g("linkPlatformAccountPage.placeholder.emailAddress"),
          disabled: !1,
          value: this.state.email,
          onChange: this.onEmailChange
        }
      ), this.renderEmailError(this.validation.get("email"))),
      /* @__PURE__ */ e.createElement(h, null, /* @__PURE__ */ e.createElement("div", { className: p.label }, /* @__PURE__ */ e.createElement(a, { i18nKey: "linkPlatformAccountPage.LinkExistingAccount.formLabel.password" }, "Password")), /* @__PURE__ */ e.createElement(
        S,
        {
          className: "mb-1 max-w-md",
          value: this.state.password,
          placeholder: g("linkPlatformAccountPage.placeholder.password"),
          togglePassword: !0,
          onChange: this.onPasswordChange
        }
      ), this.renderPasswordError(this.validation.get("password"))),
      /* @__PURE__ */ e.createElement("div", { className: L("mb-3 cursor-pointer text-right text-xs", p.linkLabel), onClick: this.forgotPassword }, /* @__PURE__ */ e.createElement(a, { i18nKey: "linkPlatformAccountPage.Forgotpassword" }, "Forgot password")),
      /* @__PURE__ */ e.createElement("div", { className: "flex flex-row" }, /* @__PURE__ */ e.createElement(
        P,
        {
          loadingIndicator: "SPINNER",
          disabled: !l && (r || i),
          isLoading: i,
          className: "btn big btn-primary w-full uppercase",
          type: "submit"
        },
        /* @__PURE__ */ e.createElement(a, { i18nKey: "EmailVerificationPage.continueButton" }, "CONTINUE")
      ))
    ), o === "CONFIRMATION" && /* @__PURE__ */ e.createElement(
      T,
      {
        onCancel: this.closeDialog,
        onConfirm: this.onSubmit,
        platformName: A.getPlatformName(s),
        isSubmitting: i
      }
    ), o === "LINK_DELETION_ACCOUNT_ERROR" && /* @__PURE__ */ e.createElement(_, { onClose: this.closeDialog }), o === "TOKEN_EXPIRED_ERROR" && /* @__PURE__ */ e.createElement(O, { onClose: m }), o === "BANNED_USER_ERROR" && /* @__PURE__ */ e.createElement(I, { onClose: this.closeDialog }));
  }
}
export {
  he as LinkExistingAccount
};
