import * as t from "react";
import M from "classnames";
import { AlertType as u } from "./accelbyte-widgets128.mjs";
import { Ctx as k } from "./accelbyte-widgets33.mjs";
import { Env as g } from "./accelbyte-widgets108.mjs";
import { ErrorHelper as A } from "./accelbyte-widgets120.mjs";
import { VerificationCodeContext as V } from "./accelbyte-widgets139.mjs";
import { getCurrentLanguage as T, t as h } from "./accelbyte-widgets58.mjs";
import { Alert as R } from "./accelbyte-widgets123.mjs";
import { Button as C, ButtonStyle as b } from "./accelbyte-widgets107.mjs";
import { CommonError as P } from "./accelbyte-widgets124.mjs";
import { Loading as U, LoadingSize as v } from "./accelbyte-widgets136.mjs";
import { Trans as y } from "react-i18next";
import { LegalHelper as L } from "@accelbyte/sdk-legal";
import { Iam as N } from "@accelbyte/sdk-iam";
import { validationOutdatedModalEvent as q } from "./accelbyte-widgets141.mjs";
import m from "./accelbyte-widgets182.mjs";
import { UpgradeHeadlessAccountForm as x } from "./accelbyte-widgets163.mjs";
import { EmailVerificationForm as _ } from "./accelbyte-widgets165.mjs";
import { SuccessMessage as w } from "./accelbyte-widgets523.mjs";
import { EXPIRED_CODE_MESSAGE as I, ONE_TIME_CODE_LENGTH as D } from "./accelbyte-widgets353.mjs";
import { RestartMessage as F } from "./accelbyte-widgets524.mjs";
import { CommonTitle as O } from "./accelbyte-widgets357.mjs";
class pe extends t.Component {
  constructor(d) {
    super(d), this.fetchPolicies = () => {
      const e = this.appState.getUser();
      e && this.legalManager.fetchPoliciesList(e.country).then(() => {
        const { policiesByCountry: i } = this.legalManager.state;
        this.setState({
          displayedPolicies: L.convertPoliciesToDisplayedPolicies(i || [], g.NAMESPACE)
        });
      }).catch((i) => {
        this.setErrorAlert(i);
      });
    }, this.fetchValidations = async () => {
      this.inputValidationManager.fetchValidations(T()).catch((e) => {
        this.setErrorAlert(e);
      });
    }, this.redirectToOtherData = () => {
      this.setState({
        step: "otherData",
        alert: {
          type: u.success,
          element: h("ChangeEmailPage.verifyCodeForm.codeSent")
        }
      }), this.props.onHideTitle();
    }, this.requestVerificationCode = async (e = this.state.email) => {
      const { step: i, isRequestingVerificationCode: s, alreadyRefreshToken: a } = this.state, { oneTimeLinkCode: c } = this.props, r = i === "email", o = N.OAuth20ExtensionApi(this.appState.getSdk());
      try {
        if (!e || s)
          return;
        if (this.setState({ isRequestingVerificationCode: !0 }), this.verificationManager.setState({ requestVerificationCodeError: null }), r && !a) {
          const n = await o.postLinkTokenExchange({
            oneTimeLinkCode: c,
            client_id: g.CLIENT_ID
          }), { access_token: p, refresh_token: l } = n;
          this.setState({ alreadyRefreshToken: !0 }), this.appState.refreshSession(p, l);
        }
        await this.verificationManager.sendVerificationCode(e, V.enum.upgradeHeadlessAccount), await this.appState.refreshUser(), r && this.fetchPolicies(), this.setState({ email: e, isRequestingVerificationCode: !1 }, this.redirectToOtherData);
      } catch (n) {
        const { requestVerificationCodeError: p } = this.verificationManager.state;
        if (this.setState({ isRequestingVerificationCode: !1 }), p) {
          this.setErrorAlert(p);
          return;
        }
        console.error(n), this.setErrorAlert(n);
      }
    }, this.setErrorAlert = async (e) => {
      var o;
      if (await this.inputValidationManager.isInputValidationError(e)) {
        q.openValidationOutdatedModal(), this.setState({ alert: null });
        return;
      }
      const { oneTimeLinkCode: i, onHideTitle: s } = this.props, a = A.isAxiosError(e) ? (o = e.response) == null ? void 0 : o.data.error_description : "", c = a == null ? void 0 : a.includes(I), r = A.extractServiceErrorCode(e);
      if (c) {
        s(), this.setState({
          step: "shouldRestart",
          alert: {
            type: u.danger,
            element: i.length === D ? h("LinkAccountWithOneTimeCodePage.error.expired") : h("LinkAccountWithOneTimeCodePage.error.invalid")
          }
        });
        return;
      }
      this.setState({
        alert: {
          type: u.danger,
          element: (() => {
            switch (r) {
              case 10130:
                return h("UpdateUser.error.updateErrorUnderage");
              default:
                return /* @__PURE__ */ t.createElement(P, { error: e });
            }
          })()
        }
      });
    }, this.dismissAlert = () => {
      this.setState({ alert: null });
    }, this.onReload = () => {
      this.setState({ alert: null }), this.fetchValidations();
    }, this.onGoBackToEmail = () => {
      this.setState({ step: "email", email: "" }), this.props.onShowTitle();
    }, this.onCompleteProcess = async ({
      password: e,
      displayName: i,
      username: s,
      reachMinimumAge: a,
      verificationCode: c,
      acceptedPolicyIds: r
    }) => {
      const { email: o } = this.state, n = this.appState.getUser(), p = (n == null ? void 0 : n.country) || "";
      try {
        await this.linkAccountsManager.upgradeHeadlessAccount(
          {
            displayName: i,
            password: e,
            username: s,
            country: p,
            reachMinimumAge: a,
            emailAddress: o,
            code: c
          },
          g.IS_DISABLE_USERNAME
        ), await this.bulkAcceptPolicies(r);
        const l = await this.appState.userAppManager.refreshToken();
        l && this.appState.refreshSession(l.access_token, l.refresh_token), this.appState.refreshUser(), this.setState({ alert: null, step: "success" });
      } catch (l) {
        this.setErrorAlert(l);
      }
    }, this.getEligibilities = (e) => {
      const i = [], { displayedPolicies: s } = this.state;
      for (const a of s) {
        const { policyId: c, policyVersionId: r, localizedPolicyVersionId: o } = a;
        i.push({
          policyId: c,
          policyVersionId: r,
          localizedPolicyVersionId: o,
          isAccepted: e.includes(a.policyId)
        });
      }
      return i;
    }, this.bulkAcceptPolicies = async (e) => {
      const i = this.appState.getUser(), s = this.getEligibilities(e);
      s && i && await this.legalManager.bulkAcceptPolicies(s);
    }, this.state = {
      email: "",
      alert: null,
      displayedPolicies: [],
      step: "email",
      isRequestingVerificationCode: !1,
      alreadyRefreshToken: !1
    }, this.appState = k.getAppState(), this.verificationManager = this.appState.verificationManager, this.verificationManager.subscribe(() => this.setState({})), this.linkAccountsManager = this.appState.linkAccountManager, this.linkAccountsManager.subscribe(() => this.setState({})), this.legalManager = this.appState.legalAppManager, this.legalManager.subscribe(() => this.setState({})), this.inputValidationManager = this.appState.inputValidationAppManager, this.inputValidationManager.subscribe(() => this.setState({}));
  }
  componentDidMount() {
    this.fetchValidations();
  }
  render() {
    const { displayedPolicies: d, alert: e, step: i, email: s, isRequestingVerificationCode: a } = this.state, { isFetchingUser: c, user: r } = this.appState.getUserManager().state, { isVerifying: o } = this.verificationManager.state, { isUpgradingHeadlessAccount: n } = this.linkAccountsManager.state, { isAccepting: p } = this.legalManager.state, { isFetching: l, fetchError: f, validations: E } = this.inputValidationManager.state, S = i === "shouldRestart";
    return /* @__PURE__ */ t.createElement(t.Fragment, null, i === "otherData" && /* @__PURE__ */ t.createElement("div", { className: "mb-6 text-center" }, /* @__PURE__ */ t.createElement("p", { className: m.title }, /* @__PURE__ */ t.createElement(y, { i18nKey: "LinkAccountWithOneTimeCodePage.selectLinkMode.tab.upgradeToFull" }, "Upgrade to Full Account")), /* @__PURE__ */ t.createElement("p", { className: m.description }, /* @__PURE__ */ t.createElement(y, { i18nKey: "UpgradeHeadlessAccountPage.UpgradeHeadlessAccountForm.description" }, "Enter the verification code we’ve sent to your email at ", /* @__PURE__ */ t.createElement("strong", null, { email: s }), ", and complete the form below"))), S && /* @__PURE__ */ t.createElement(O, null), !!e && /* @__PURE__ */ t.createElement("div", { className: M("mb-4", S ? "mt-5" : "mt-[-8px]") }, /* @__PURE__ */ t.createElement(R, { type: e.type, onDismiss: this.dismissAlert }, e.element), !!f && /* @__PURE__ */ t.createElement(C, { className: "btn btn-primary mt-4 w-full", onClick: this.onReload }, h("Common.reload"))), i === "email" && /* @__PURE__ */ t.createElement(
      _,
      {
        styles: m,
        onRequestVerificationCode: this.requestVerificationCode,
        isRequesting: a
      }
    ), i === "otherData" && /* @__PURE__ */ t.createElement(t.Fragment, null, E.length <= 0 && l && /* @__PURE__ */ t.createElement(U, { className: v.medium }), E.length > 0 && !f && r && /* @__PURE__ */ t.createElement(
      x,
      {
        onChangePage: this.onGoBackToEmail,
        onContinue: this.onCompleteProcess,
        onRequestVerificationCode: this.requestVerificationCode,
        policies: d,
        isUpgradingUser: n || p || c,
        inputValidationManager: this.inputValidationManager,
        isRequestingVerificationCode: a,
        user: r,
        email: s,
        isVerifying: o,
        styles: m
      }
    ), /* @__PURE__ */ t.createElement(
      C,
      {
        buttonStyle: b.NONE,
        onClick: this.onGoBackToEmail,
        className: "absolute bottom-0 left-1/2 mb-24 -translate-x-2/4"
      },
      h("common.back")
    )), i === "success" && /* @__PURE__ */ t.createElement(w, { isUpgradeToFull: !0 }), i === "shouldRestart" && /* @__PURE__ */ t.createElement(F, { onRestart: this.props.onRestart }));
  }
}
export {
  pe as UpgradeToFullAccount
};
