import { DisplayEmailValidationError as M } from "./accelbyte-widgets372.mjs";
import { Alert as V } from "./accelbyte-widgets123.mjs";
import { Button as E } from "./accelbyte-widgets107.mjs";
import { CommonError as P } from "./accelbyte-widgets124.mjs";
import { FormGroup as w } from "./accelbyte-widgets263.mjs";
import { InputGroup as N } from "./accelbyte-widgets229.mjs";
import { PasswordConstraint as b } from "./accelbyte-widgets265.mjs";
import { Loading as k, LoadingSize as I } from "./accelbyte-widgets136.mjs";
import { getCurrentLanguage as R, t as L } from "./accelbyte-widgets58.mjs";
import { Ctx as F } from "./accelbyte-widgets33.mjs";
import { Env as T } from "./accelbyte-widgets108.mjs";
import { AlertType as A } from "./accelbyte-widgets128.mjs";
import { AuthType as q } from "./accelbyte-widgets239.mjs";
import { REGISTRATION_LINK_ACCOUNT_EMAIL_STORAGE_KEY as y } from "./accelbyte-widgets175.mjs";
import { ErrorHelper as D } from "./accelbyte-widgets120.mjs";
import * as e from "react";
import { Trans as o } from "react-i18next";
import { validationOutdatedModalEvent as K, InputValidationOutdatedModal as U } from "./accelbyte-widgets141.mjs";
import { redirectAfterSuccessLinkAccount as B } from "./accelbyte-widgets364.mjs";
import l from "./accelbyte-widgets373.mjs";
import { LinkNewAccountForm as O } from "./accelbyte-widgets374.mjs";
import { LegalHelper as _ } from "@accelbyte/sdk-legal";
import { InputValidationHelper as S, ValidateableInputField as C } from "@accelbyte/sdk-iam";
import { Validation as x } from "./accelbyte-widgets269.mjs";
class ht extends e.Component {
  constructor(c) {
    super(c), this.getCountryRelatedData = async () => {
      var t;
      try {
        this.setState({ isFetchingRequiredData: !0 }), await this.appState.miscAppManager.fetchCountries(), await this.appState.userAppManager.getCurrentLocationCountry();
        const i = (t = this.appState.userAppManager.state.currentCountryLocation) == null ? void 0 : t.countryCode;
        await this.getPoliciesAndAgeRestrictionByCountry(i);
      } finally {
        this.setState({ isFetchingRequiredData: !1 });
      }
    }, this.getInputValidations = () => {
      this.inputValidationManager.fetchValidations(R()).then(() => {
        const { fetchError: t } = this.inputValidationManager.state;
        t && this.setErrorAlert(t);
      });
    }, this.getPoliciesAndAgeRestrictionByCountry = async (t) => {
      t && (await this.appState.userAppManager.getAgeRestrictionByCountry(t), this.legalManager.fetchPoliciesList(t).then(() => {
        const { policiesByCountry: i } = this.legalManager.state;
        this.setState({
          displayedPolicies: _.convertPoliciesToDisplayedPolicies(i || [], T.NAMESPACE)
        });
      }));
    }, this.requestVerificationCode = async () => {
      const { email: t } = this.state;
      t && this.verificationManager.sendNewUserVerificationCode(t).then(() => {
        const { isRequestVerificationCodeSuccess: i } = this.verificationManager.state;
        i && this.redirectToRegistrationForm();
      }).catch((i) => {
        this.setErrorAlert(i);
      });
    }, this.setErrorAlert = async (t) => {
      if (await this.inputValidationManager.isInputValidationError(t)) {
        K.openValidationOutdatedModal(), this.setState({ alert: null });
        return;
      }
      const i = D.extractServiceErrorCode(t);
      this.setState({
        alert: {
          type: A.danger,
          element: (() => {
            switch (i) {
              case 10130:
                return /* @__PURE__ */ e.createElement(o, { i18nKey: "UpdateUser.error.updateErrorUnderage" }, "You are below the required age");
              case 10152:
                return /* @__PURE__ */ e.createElement(o, { i18nKey: "User.verifyCode.invalid" }, "Verification code is either been used or not valid anymore.");
              default:
                return /* @__PURE__ */ e.createElement(P, { error: t });
            }
          })()
        }
      });
    }, this.linkPlatformAccountError = (t) => {
      this.setErrorAlert(t), window.scrollTo({ top: 0, behavior: "smooth" });
    }, this.dismissAlert = () => {
      this.setState({ alert: null });
    }, this.redirectToRegistrationForm = () => {
      sessionStorage.setItem(y, this.state.email), this.setState({
        step: "registrationForm",
        alert: {
          type: A.success,
          element: /* @__PURE__ */ e.createElement(o, { i18nKey: "ChangeEmailPage.verifyCodeForm.codeSent" }, "A verification code has been sent to your email")
        }
      }), this.props.onContinueToRegistrationForm(!0);
    }, this.onEmailChange = (t) => {
      const i = t.target.value.toString().toLocaleLowerCase(), { validations: n } = this.inputValidationManager.state;
      this.validation.set("email", S.validateEmail(i, n)), this.setState({ email: i });
    }, this.onFormSubmit = (t) => {
      t.preventDefault();
      const { email: i } = this.state;
      !this.validation.get("email") && i && this.requestVerificationCode();
    }, this.onReload = () => {
      this.setState({ alert: null }), this.getInputValidations();
    }, this.renderLinkNewVerifyAccount = () => {
      const { email: t } = this.state, { isPreviewMode: i } = this.props, { isRequestingVerificationCode: n } = this.verificationManager.state, { validations: a } = this.inputValidationManager.state, r = S.getValidationByKey(C.enum.email, a);
      return /* @__PURE__ */ e.createElement("form", { onSubmit: this.onFormSubmit, noValidate: !0 }, /* @__PURE__ */ e.createElement(w, null, /* @__PURE__ */ e.createElement("div", { className: l.label }, /* @__PURE__ */ e.createElement(o, { i18nKey: "linkPlatformAccountPage.LinkNewAccount.email" }, "Email")), /* @__PURE__ */ e.createElement(
        N,
        {
          type: "email",
          className: l.input,
          value: t,
          placeholder: L("linkPlatformAccountPage.LinkNewAccount.placeholder.email"),
          onChange: this.onEmailChange,
          popoverContent: /* @__PURE__ */ e.createElement(
            b,
            {
              descriptions: S.getValidationDescription(C.enum.email, a)
            }
          )
        }
      ), M(this.validation.get("email"), {
        minLength: r == null ? void 0 : r.minLength,
        maxLength: r == null ? void 0 : r.maxLength
      })), /* @__PURE__ */ e.createElement(
        E,
        {
          loadingIndicator: "SPINNER",
          disabled: !i && (!!this.validation.get("email") || !t),
          className: "btn btn-primary w-full uppercase",
          onClick: i ? void 0 : this.requestVerificationCode,
          isLoading: n
        },
        /* @__PURE__ */ e.createElement(o, { i18nKey: "linkPlatformAccountPage.LinkNewAccount.continue" }, "CONTINUE")
      ));
    }, this.onChangePage = () => {
      this.setState({ step: "email", email: "", alert: null }), this.props.onContinueToRegistrationForm(!1), this.resetSessionStorage();
    }, this.onContinue = async ({
      password: t,
      displayName: i,
      username: n,
      acceptedPolicyIds: a,
      reachMinimumAge: r,
      verificationCode: u,
      country: h
    }) => {
      const { email: d } = this.state, { linkingToken: m, clientId: p, platformId: g } = this.props, f = this.getEligibilities(a);
      try {
        this.setState({ isSubmitting: !0 });
        const s = await this.linkAccountsManager.linkNewPlatformAccount({
          linkingToken: m,
          clientId: p,
          userAccountParams: {
            authType: q.enum.EMAILPASSWD,
            displayName: i,
            password: t,
            username: n,
            country: h.value,
            reachMinimumAge: r,
            emailAddress: d,
            code: u,
            acceptedPolicies: f
          },
          refreshSession: this.appState.refreshSession
        });
        s.user_id && (this.resetSessionStorage(), await this.appState.refreshUser(), await this.appState.updateUserCustomAttribute(s.user_id, g), B(this.appState.state.appHistory));
      } catch (s) {
        this.linkPlatformAccountError(s);
      } finally {
        this.setState({ isSubmitting: !1 });
      }
    }, this.getEligibilities = (t) => {
      const i = [], { displayedPolicies: n } = this.state;
      for (const a of n)
        i.push({
          policyId: a.policyId,
          policyVersionId: a.policyVersionId,
          localizedPolicyVersionId: a.localizedPolicyVersionId,
          isAccepted: t.includes(a.policyId)
        });
      return i;
    }, this.onChangeCountry = (t) => {
      this.getPoliciesAndAgeRestrictionByCountry(t.value);
    }, this.state = {
      email: "",
      alert: null,
      displayedPolicies: [],
      step: "email",
      isFetchingRequiredData: !1,
      isSubmitting: !1
    }, this.validation = new x(), this.validation.listen(() => this.setState({})), this.appState = F.getAppState(), this.linkAccountsManager = this.appState.linkAccountManager, this.linkAccountsManager.subscribe(() => this.setState({})), this.verificationManager = this.appState.verificationManager, this.verificationManager.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.getInputValidations(), this.getCountryRelatedData();
    const c = sessionStorage.getItem(y);
    this.setState({ email: c || "" }), c && this.setState({ step: "registrationForm" });
  }
  componentWillUnmount() {
    this.resetSessionStorage();
  }
  resetSessionStorage() {
    sessionStorage.removeItem(y);
  }
  render() {
    const { platformId: c } = this.props, { displayedPolicies: t, alert: i, step: n, email: a, isSubmitting: r } = this.state, { isRequestingVerificationCode: u, isVerifying: h } = this.verificationManager.state, { isFetching: d, fetchError: m, validations: p } = this.inputValidationManager.state, { error: g } = this.linkAccountsManager.state, { countries: f } = this.appState.miscAppManager.state, { currentCountryLocation: s } = this.appState.userAppManager.state, v = {
      value: (s == null ? void 0 : s.countryCode) ?? "",
      label: (s == null ? void 0 : s.countryName) ?? ""
    };
    return /* @__PURE__ */ e.createElement(e.Fragment, null, /* @__PURE__ */ e.createElement("div", { className: l.linkNewAccountContainerForm }, /* @__PURE__ */ e.createElement("div", { className: l.contentWrapper }, n === "registrationForm" && /* @__PURE__ */ e.createElement(e.Fragment, null, /* @__PURE__ */ e.createElement("div", { className: l.title }, /* @__PURE__ */ e.createElement(o, { i18nKey: "linkPlatformAccountPage.LinkNewAccount.title" }, "Create your account")), /* @__PURE__ */ e.createElement("div", { className: l.description }, /* @__PURE__ */ e.createElement(o, { i18nKey: "linkPlatformAccountPage.LinkNewAccount.description" }, "Enter the verification code we’ve sent to your email at ", /* @__PURE__ */ e.createElement("strong", null, { email: a }), ", and complete the form below")))), /* @__PURE__ */ e.createElement("div", { className: l.formWrapper }, !!i && /* @__PURE__ */ e.createElement("div", { className: l.alert }, /* @__PURE__ */ e.createElement(V, { type: i.type, onDismiss: this.dismissAlert }, i.element), !!m && /* @__PURE__ */ e.createElement(E, { className: "btn btn-primary mt-4 w-full", onClick: this.onReload }, /* @__PURE__ */ e.createElement(o, { i18nKey: "Common.reload" }, "Reload"))), n === "email" && this.renderLinkNewVerifyAccount(), n === "registrationForm" && /* @__PURE__ */ e.createElement("div", null, p.length <= 0 && d || this.state.isFetchingRequiredData && /* @__PURE__ */ e.createElement(k, { className: I.medium }), p.length > 0 && !m && !this.state.isFetchingRequiredData && /* @__PURE__ */ e.createElement(
      O,
      {
        onChangePage: this.onChangePage,
        onContinue: this.onContinue,
        onChangeCountry: this.onChangeCountry,
        onRequestVerificationCode: this.requestVerificationCode,
        policies: t,
        isLinkingUser: r,
        inputValidationManager: this.inputValidationManager,
        countries: f,
        currentCountry: v,
        ageRestriction: this.appState.userAppManager.state.ageRestriction,
        linkNewPlatformAccountError: g,
        isRequestingVerificationCode: u,
        email: a,
        isVerifying: h,
        platformId: c
      }
    )))), /* @__PURE__ */ e.createElement(U, null));
  }
}
export {
  ht as LinkNewAccount
};
