import { AccountMainSection as T, AccountMainSectionHeader as w, AccountMainSectionBody as G } from "./accelbyte-widgets122.mjs";
import { Alert as O } from "./accelbyte-widgets123.mjs";
import { Button as I } from "./accelbyte-widgets107.mjs";
import { CommonError as B } from "./accelbyte-widgets124.mjs";
import { FormGroup as M, FormGroupInfo as S, FormGroupStyles as D, FormGroupError as V } from "./accelbyte-widgets263.mjs";
import { InputGroup as A } from "./accelbyte-widgets229.mjs";
import { Loading as H, LoadingSize as R } from "./accelbyte-widgets136.mjs";
import { getCurrentLanguage as Y, t as k } from "./accelbyte-widgets58.mjs";
import { Ctx as m } from "./accelbyte-widgets33.mjs";
import { Env as L } from "./accelbyte-widgets108.mjs";
import { VerificationCodeContext as q } from "./accelbyte-widgets139.mjs";
import { AlertType as v } from "./accelbyte-widgets128.mjs";
import { AccPath as K } from "./accelbyte-widgets34.mjs";
import { ErrorHelper as Z } from "./accelbyte-widgets120.mjs";
import { translateServiceError as j } from "@accelbyte/error-translator";
import { InputValidationHelper as p, EligibleUser as X, ValidateableInputField as U } from "@accelbyte/sdk-iam";
import e from "react";
import { Trans as i } from "react-i18next";
import { Link as W } from "react-router-dom";
import { CommonEntryGroup as g, CommonEntryGroupLabel as f, CommonEntryGroupInput as y } from "./accelbyte-widgets266.mjs";
import { validationOutdatedModalEvent as $ } from "./accelbyte-widgets141.mjs";
import { ChangeEmailDialog as J } from "./accelbyte-widgets286.mjs";
import Q from "./accelbyte-widgets287.mjs";
import { mockZipCode as ee, mockUser as te } from "./accelbyte-widgets209.mjs";
import { Tooltip as ae } from "./accelbyte-widgets288.mjs";
import { ValidateLengthErrorType as d } from "./accelbyte-widgets289.mjs";
import { ValidateRegexErrorType as F } from "./accelbyte-widgets290.mjs";
import { Validation as re } from "./accelbyte-widgets269.mjs";
class Fe extends e.Component {
  constructor(s) {
    super(s), this.initializeProfilePage = async () => {
      await this.userManager.fetchOrCreateUserProfile(), this.userManager.state.errorFetchingProfile !== null && this.setErrorAlert(this.userManager.state.errorFetchingProfile), this.appState.miscAppManager.state.countries.length === 0 && await this.appState.miscAppManager.fetchCountries(), m.getInputValidationManager().state.validations.length === 0 && await m.getInputValidationManager().fetchValidations(Y()), this.populateUserAndUserProfileFromLogic();
    }, this.isDisplayNameDisabled = () => L.IS_DISABLE_DISPLAY_NAME, this.isUserNameDisabled = () => L.IS_DISABLE_USERNAME, this.populateUserFromLogic = () => {
      const { user: t } = this.userManager.state;
      if (t) {
        const a = this.isDisplayNameDisabled() || t.displayName === "", r = this.isUserNameDisabled() || t.userName === "";
        this.setState({
          displayName: a ? null : t.displayName,
          userName: r || !t.userName ? null : t.userName
        });
      }
    }, this.populateUserProfileFromLogic = () => {
      const { userProfile: t } = this.userManager.state;
      this.setState({
        zipCode: t && t.zipCode ? t.zipCode : null
      });
    }, this.populateUserAndUserProfileFromLogic = () => {
      this.populateUserFromLogic(), this.populateUserProfileFromLogic();
    }, this.setErrorAlert = (t) => {
      this.setState({
        alert: {
          type: v.danger,
          element: /* @__PURE__ */ e.createElement(B, { error: t })
        }
      });
    }, this.notifyUpdateSuccess = () => {
      this.setState({
        alert: {
          type: v.success,
          element: /* @__PURE__ */ e.createElement(i, { i18nKey: "AccountMyProfilePage.updateSuccess" }, "Your profile has been updated!")
        }
      });
    }, this.notifyUpdateError = async (t) => {
      if (await m.getInputValidationManager().isInputValidationError(t)) {
        $.openValidationOutdatedModal(), this.setState({ alert: null });
        return;
      }
      const a = Z.extractServiceErrorCode(t);
      a ? this.setState({
        alert: {
          type: v.danger,
          element: (() => {
            switch (a) {
              case 10130:
                return /* @__PURE__ */ e.createElement(i, { i18nKey: "UpdateUser.error.updateErrorUnderage" }, "You are below the required age");
              case 10177:
                return /* @__PURE__ */ e.createElement(i, { i18nKey: "UpdateUser.error.updateErrorConflict" }, "The username has been taken. Please choose another");
              default:
                return j(a) || /* @__PURE__ */ e.createElement(i, { i18nKey: "UpdateUser.error.updateError" }, "Failed to update your account information. Please try again.");
            }
          })()
        }
      }) : this.setErrorAlert(t);
    }, this.isProfileChanged = () => {
      const { user: t } = this.userManager.state, { userProfile: a } = this.userManager.state, { displayName: r, userName: o, zipCode: u } = this.state;
      return !!(t !== null && (r !== null && t.displayName !== r.trim() || o !== null && t.userName !== o.trim() || u !== null && a && a.zipCode !== u.trim()));
    }, this.onChangeDisplayName = (t) => {
      const a = t.target.value, { validations: r } = m.getInputValidationManager().state;
      this.validation.set("displayName", p.validateDisplayName(a, this.isUserNameDisabled(), r)), this.setState({ displayName: a });
    }, this.onChangeZipCode = (t) => {
      const a = t.target.value;
      this.setState({ zipCode: a });
    }, this.onChangeUserName = (t) => {
      const a = t.target.value, { validations: r } = m.getInputValidationManager().state;
      this.validation.set("userName", p.validateUserName(a, r)), this.setState({ userName: a });
    }, this.openChangeEmailDialog = () => {
      this.setState({ isChangeEmailDialogOpen: !0 }), this.appState.verificationManager.setState({ isRequestVerificationCodeSuccess: null });
    }, this.closeChangeEmailDialog = () => this.setState({ isChangeEmailDialogOpen: !1 }), this.onSubmit = async (t, a, r, o) => {
      t.preventDefault();
      const { params: u, userProfileParams: c } = this.getParams(a, r, o);
      try {
        await Promise.all([this.userManager.updateUser(u), this.userManager.updateUserProfile(c)]), this.notifyUpdateSuccess();
      } catch {
        this.notifyUpdateError(this.userManager.state.updateError);
      }
    }, this.onSendVerificationCode = async () => {
      const { user: t } = this.userManager.state;
      if (t)
        try {
          await this.appState.verificationManager.sendVerificationCode(t.emailAddress, q.enum.UpdateEmailAddress), this.appState.state.appHistory.replace(K.ChangeEmail.makePath());
        } catch {
          const { requestVerificationCodeError: r } = this.appState.verificationManager.state;
          this.setErrorAlert(r);
        }
    }, this.getCountryNameByCountryId = (t) => {
      const { countries: a } = this.appState.miscAppManager.state;
      if (!a)
        return t;
      const r = a.find((o) => o.code === t);
      return r && r.name || t;
    }, this.renderFormEditProfile = () => {
      const { user: t } = this.userManager.state, a = this.props.isPreviewMode, r = a ? te : t;
      if (!X.safeParse(r).success || !r)
        return;
      const o = this.state.displayName !== null ? this.state.displayName : r.displayName || "", u = this.isUserNameDisabled() ? o.length > 0 : !0, c = this.state.userName !== null ? this.state.userName : r.userName || "", E = a ? ee : this.state.zipCode || "", x = this.isUserNameDisabled() || c.length > 0, { validations: N } = m.getInputValidationManager().state, P = p.getValidationByKey(U.enum.username, N), C = p.getValidationByKey(U.enum.displayName, N), h = this.userManager.state.isUpdating || this.userManager.state.isFetchingUser, _ = h || !u || !x || !this.isProfileChanged() || !this.validation.isAllValid(), b = L.CONTACT_SUPPORT_EMAIL;
      return /* @__PURE__ */ e.createElement(
        "form",
        {
          onSubmit: (z) => {
            o !== null && c !== null && E !== null && this.onSubmit(z, o, c, E);
          }
        },
        /* @__PURE__ */ e.createElement("div", { className: "formInputContainer" }, !this.isUserNameDisabled() && /* @__PURE__ */ e.createElement(g, null, /* @__PURE__ */ e.createElement(f, null, /* @__PURE__ */ e.createElement(i, { i18nKey: "AccountMyProfilePage.form.userName.label" }, "Username")), /* @__PURE__ */ e.createElement(y, null, /* @__PURE__ */ e.createElement(M, { className: "formGroup", hasError: c === "" }, /* @__PURE__ */ e.createElement(
          A,
          {
            type: "text",
            value: c,
            name: "userName",
            disabled: h,
            className: "inputGroup",
            onChange: this.onChangeUserName,
            readOnly: a
          }
        ), this.renderUserNameError(this.validation.get("userName"), {
          min: P && P.minLength,
          max: P && P.maxLength
        }), /* @__PURE__ */ e.createElement(S, null, p.getValidationDescription(U.enum.username, N).join(". "))))), !this.isDisplayNameDisabled() && /* @__PURE__ */ e.createElement(g, null, /* @__PURE__ */ e.createElement(f, null, /* @__PURE__ */ e.createElement(i, { i18nKey: "AccountMyProfilePage.form.displayName" }, "Display name")), /* @__PURE__ */ e.createElement(y, null, /* @__PURE__ */ e.createElement(M, { className: "formGroup", hasError: o === "" }, /* @__PURE__ */ e.createElement(
          A,
          {
            type: "text",
            value: o,
            name: "displayName",
            disabled: h,
            className: "inputGroup",
            onChange: this.onChangeDisplayName,
            readOnly: a
          }
        ), this.renderDisplayNameError(this.validation.get("displayName"), {
          min: C && C.minLength,
          max: C && C.maxLength
        }), /* @__PURE__ */ e.createElement(S, null, p.getValidationDescription(U.enum.displayName, N).join(". "))))), /* @__PURE__ */ e.createElement(g, { className: D.pseudoMarginBottom }, /* @__PURE__ */ e.createElement(f, null, /* @__PURE__ */ e.createElement(i, { i18nKey: "AccountMyProfilePage.form.emailAddress" }, "Email address")), /* @__PURE__ */ e.createElement(y, { className: "emailFormContainer" }, /* @__PURE__ */ e.createElement(ae, { text: r.emailAddress, showOnlyOnEllipsis: !0 }, /* @__PURE__ */ e.createElement("div", null, r.emailAddress)), /* @__PURE__ */ e.createElement("button", { className: "btnChange", type: "button", onClick: a ? void 0 : this.openChangeEmailDialog }, /* @__PURE__ */ e.createElement(i, { i18nKey: "AccountMyProfilePage.form.changeEmail" }, "Change")))), /* @__PURE__ */ e.createElement(g, { className: D.pseudoMarginBottom }, /* @__PURE__ */ e.createElement(f, null, /* @__PURE__ */ e.createElement(i, { i18nKey: "AccountMyProfilePage.form.country" }, "Country")), /* @__PURE__ */ e.createElement(y, null, /* @__PURE__ */ e.createElement(M, null, /* @__PURE__ */ e.createElement(
          A,
          {
            type: "text",
            value: this.getCountryNameByCountryId(r && r.country || ""),
            disabled: !0,
            className: "countryForm",
            readOnly: a
          }
        ), b && /* @__PURE__ */ e.createElement(S, null, /* @__PURE__ */ e.createElement(i, { i18nKey: "AccountMyProfilePage.form.changeCountryInfo" }, "Please contact our customer support at", " ", /* @__PURE__ */ e.createElement("a", { href: `mailto:${b}`, className: "btnContactSupport" }, { contactSupportEmail: b }), " ", "to request a country change"))))), /* @__PURE__ */ e.createElement(g, { className: D.pseudoMarginBottom }, /* @__PURE__ */ e.createElement(f, null, /* @__PURE__ */ e.createElement(i, { i18nKey: "AccountMyProfilePage.form.zipCode.label" }, "ZIP Code")), /* @__PURE__ */ e.createElement(y, null, /* @__PURE__ */ e.createElement(M, null, /* @__PURE__ */ e.createElement(
          A,
          {
            type: "text",
            value: E,
            onChange: this.onChangeZipCode,
            placeholder: k("AccountMyProfilePage.form.zipCode.placeholder"),
            disabled: h,
            className: "inputGroup",
            readOnly: a
          }
        ), /* @__PURE__ */ e.createElement(S, null, /* @__PURE__ */ e.createElement(i, { i18nKey: "AccountMyProfilePage.form.zipCode.tooltip" }, "We need your ZIP code to calculate the sales tax for your purchase.")))))),
        /* @__PURE__ */ e.createElement("div", { className: "divider" }),
        /* @__PURE__ */ e.createElement("div", { className: "btnContainer" }, /* @__PURE__ */ e.createElement(I, { loadingIndicator: "SPINNER", type: "submit", className: "btn btn-primary", disabled: _, isLoading: h }, /* @__PURE__ */ e.createElement(i, { i18nKey: "AccountMyProfilePage.form.saveChanges" }, "Save changes")))
      );
    }, this.appState = m.getAppState();
    const n = this.appState.getUser();
    this.validation = new re(), this.validation.listen(() => this.setState({})), this.userManager = this.appState.userAppManager;
    const l = this.userManager.state.userProfile;
    this.state = {
      displayName: (n == null ? void 0 : n.displayName) || null,
      userName: (n == null ? void 0 : n.userName) || null,
      isChangeEmailDialogOpen: !1,
      alert: null,
      zipCode: (l == null ? void 0 : l.zipCode) || null
    }, m.getInputValidationManager().subscribe(() => this.setState({}));
  }
  async componentDidMount() {
    if (this.props.isPreviewMode)
      return;
    await this.initializeProfilePage();
    const s = m.getAppState().state.appHistory.location.state;
    (s == null ? void 0 : s.updateEmailStatus) === "success" && (this.setState({
      alert: {
        type: v.success,
        element: /* @__PURE__ */ e.createElement(i, { i18nKey: "NewEmailVerificationPage.verified" }, "Congratulations! Your email has been updated.")
      }
    }), window.history.replaceState({}, ""));
  }
  getParams(s, n, l) {
    const { user: t, userProfile: a } = this.userManager.state, r = {}, o = {};
    return t && (s !== t.displayName && (r.displayName = s), n && n !== t.userName && (r.userName = n), (!a || l !== a.zipCode) && (o.zipCode = l)), { params: r, userProfileParams: o };
  }
  renderDisplayNameError(s, n = {}) {
    if (!s)
      return null;
    const l = {
      [d.enum.empty]: /* @__PURE__ */ e.createElement(i, { i18nKey: "AccountMyProfilePage.form.displayNameEmptyError" }, "The display name cannot be empty."),
      [d.enum.lessThanLengthLimit]: /* @__PURE__ */ e.createElement(i, { i18nKey: "AccountMyProfilePage.form.lessThanLengthLimit" }, "Your display name must contain at least ", { DISPLAY_NAME_MIN_LIMIT: n.min }, " characters"),
      [d.enum.exceedLengthLimit]: /* @__PURE__ */ e.createElement(i, { i18nKey: "AccountMyProfilePage.form.displayNameExceedLimit" }, "Your display name must not exceed ", { MAX_DISPLAY_NAME_LENGTH: n.max }, " characters"),
      [F.enum.invalidFormat]: /* @__PURE__ */ e.createElement(i, { i18nKey: "AccountMyProfilePage.form.displayNameInvalidFormat" }, "Please enter a valid display name format")
    };
    return /* @__PURE__ */ e.createElement(V, null, l[s]);
  }
  renderUserNameError(s, n = {}) {
    if (!s)
      return null;
    const l = {
      [d.enum.empty]: /* @__PURE__ */ e.createElement(i, { i18nKey: "AccountMyProfilePage.form.userName.emptyError" }, "The username cannot be empty"),
      [d.enum.lessThanLengthLimit]: /* @__PURE__ */ e.createElement(i, { i18nKey: "AccountMyProfilePage.form.userName.lessThanLengthLimit" }, "Your username must contain at least ", { MIN_USERNAME_LENGTH: n.min }, " characters"),
      [d.enum.exceedLengthLimit]: /* @__PURE__ */ e.createElement(i, { i18nKey: "AccountMyProfilePage.form.userName.exceedLimit" }, "Your username must not exceed ", { MAX_USERNAME_LENGTH: n.max }, " characters"),
      [F.enum.invalidFormat]: /* @__PURE__ */ e.createElement(i, { i18nKey: "AccountMyProfilePage.form.userName.invalidFormat" }, "Please enter a valid username format")
    };
    return /* @__PURE__ */ e.createElement(V, null, l[s]);
  }
  render() {
    const { isFetchingProfile: s, errorFetchingProfile: n } = this.userManager.state, { isRequestingVerificationCode: l } = this.appState.verificationManager.state, { alert: t, isChangeEmailDialogOpen: a } = this.state;
    return /* @__PURE__ */ e.createElement(T, { className: Q.profilePage }, /* @__PURE__ */ e.createElement(w, { className: "mainHeader" }, /* @__PURE__ */ e.createElement(i, { i18nKey: "AccountMyProfilePage.title" }, "My Profile"), /* @__PURE__ */ e.createElement(W, { to: K.ProfileHistory.makePath(), className: "btnSeeAccountHistory" }, /* @__PURE__ */ e.createElement(i, { i18nKey: "AccountMyProfilePage.link.seeAccountHistory" }, "See account history"))), /* @__PURE__ */ e.createElement(G, null, !s && t && !a && /* @__PURE__ */ e.createElement("div", null, /* @__PURE__ */ e.createElement(
      O,
      {
        type: t.type,
        className: "profilePageAlerts",
        onDismiss: () => {
          this.setState({ alert: null });
        }
      },
      t.element
    ), n && /* @__PURE__ */ e.createElement(I, { className: "btn btn-primary btnReload", onClick: this.initializeProfilePage }, /* @__PURE__ */ e.createElement(i, { i18nKey: "Common.reload" }, "Reload"))), s && /* @__PURE__ */ e.createElement(H, { className: R.medium }), !s && !n && this.renderFormEditProfile(), a && /* @__PURE__ */ e.createElement(
      J,
      {
        isRequestingVerificationCode: l,
        onClose: this.closeChangeEmailDialog,
        onSendVerification: this.onSendVerificationCode,
        onDismissAlert: () => this.setState({ alert: null }),
        alert: t
      }
    )));
  }
}
export {
  Fe as default
};
