import { A as O, b as R, a as k } from "./AccountMainSection-4c35f8d7.mjs";
import { D as H, t as w, p as Y, h as f, j as z, T as i, q, f as _, a as m, V as Z, E as U, i as j, W, y as X, Z as $, aH as d, X as J, g as I, w as Q, aJ as A, aF as S, $ as b, aT as v, aU as L, aE as ee, aV as p, aW as F, aD as K, L as te, R as ae } from "./index-162fd1aa.mjs";
import e from "react";
import { Link as ie } from "react-router-dom";
import { C as h, a as y, b as E } from "./CommonEntryGroup-868b943b.mjs";
import { t as re, m as ne } from "./MockVars-1cf2eb0a.mjs";
import "./reactSlick-cb4a2d39.mjs";
import "./dateFns-2367ee5b.mjs";
import "./reactPlayer-2f69f369.mjs";
import "./validator-61879ab7.mjs";
const se = "dialogBody _dialogBody_fd89c", oe = "dialogFooter _dialogFooter_6bff5", x = {
  dialogBody: se,
  dialogFooter: oe
}, le = (V) => {
  const { isRequestingVerificationCode: n, onClose: s, onSendVerification: l, onDismissAlert: t, alert: a } = V;
  return /* @__PURE__ */ e.createElement(H, { title: w("AccountMyProfilePage.dialog.changeEmail.title"), isOpen: !0 }, /* @__PURE__ */ e.createElement(Y, { className: x.dialogBody }, a && a.type === f.danger && /* @__PURE__ */ e.createElement("div", { className: "mb-3" }, /* @__PURE__ */ e.createElement(z, { type: a.type, className: "profilePageAlerts", onDismiss: t }, a.element)), /* @__PURE__ */ e.createElement(i, { i18nKey: "AccountMyProfilePage.dialog.changeEmail.content" }, /* @__PURE__ */ e.createElement("p", null, "You will need a verification code to make this change."), /* @__PURE__ */ e.createElement("p", null, "Click the button below to receive an email containing your code."))), /* @__PURE__ */ e.createElement(q, { className: x.dialogFooter }, /* @__PURE__ */ e.createElement("button", { onClick: () => s(), className: "btn big btn-ghost btnVerification" }, /* @__PURE__ */ e.createElement(i, { i18nKey: "AccountMyProfilePage.dialog.cancel" }, "CANCEL")), /* @__PURE__ */ e.createElement(
    _,
    {
      loadingIndicator: "SPINNER",
      onClick: () => l(),
      className: "btn big btn-primary btnCancel",
      disabled: n,
      isLoading: n
    },
    /* @__PURE__ */ e.createElement(i, { i18nKey: "AccountMyProfilePage.dialog.sendVerification" }, "Send Verification")
  )));
}, me = "profilePage _profilePage_d6729", ce = {
  profilePage: me
};
class Ce extends e.Component {
  constructor(n) {
    super(n), 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(Z()), this.populateUserAndUserProfileFromLogic();
    }, this.isDisplayNameDisabled = () => U.IS_DISABLE_DISPLAY_NAME, this.isUserNameDisabled = () => U.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: f.danger,
          element: /* @__PURE__ */ e.createElement(j, { error: t })
        }
      });
    }, this.notifyUpdateSuccess = () => {
      this.setState({
        alert: {
          type: f.success,
          element: /* @__PURE__ */ e.createElement(i, { i18nKey: "AccountMyProfilePage.updateSuccess" }, "Your profile has been updated!")
        }
      });
    }, this.notifyUpdateError = async (t) => {
      if (await m.getInputValidationManager().isInputValidationError(t)) {
        W.openValidationOutdatedModal(), this.setState({ alert: null });
        return;
      }
      const a = X.extractServiceErrorCode(t);
      a ? this.setState({
        alert: {
          type: f.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 $(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", d.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", d.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, J.enum.UpdateEmailAddress), this.appState.state.appHistory.replace(I.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 ? ne : t;
      if (!Q.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 || "", N = a ? re : this.state.zipCode || "", B = this.isUserNameDisabled() || c.length > 0, { validations: P } = m.getInputValidationManager().state, C = d.getValidationByKey(A.enum.username, P), M = d.getValidationByKey(A.enum.displayName, P), g = this.userManager.state.isUpdating || this.userManager.state.isFetchingUser, T = g || !u || !B || !this.isProfileChanged() || !this.validation.isAllValid(), D = U.CONTACT_SUPPORT_EMAIL;
      return /* @__PURE__ */ e.createElement(
        "form",
        {
          onSubmit: (G) => {
            o !== null && c !== null && N !== null && this.onSubmit(G, o, c, N);
          }
        },
        /* @__PURE__ */ e.createElement("div", { className: "formInputContainer" }, !this.isUserNameDisabled() && /* @__PURE__ */ e.createElement(h, null, /* @__PURE__ */ e.createElement(y, null, /* @__PURE__ */ e.createElement(i, { i18nKey: "AccountMyProfilePage.form.userName.label" }, "Username")), /* @__PURE__ */ e.createElement(E, null, /* @__PURE__ */ e.createElement(S, { className: "formGroup", hasError: c === "" }, /* @__PURE__ */ e.createElement(
          b,
          {
            type: "text",
            value: c,
            name: "userName",
            disabled: g,
            className: "inputGroup",
            onChange: this.onChangeUserName,
            readOnly: a
          }
        ), this.renderUserNameError(this.validation.get("userName"), {
          min: C && C.minLength,
          max: C && C.maxLength
        }), /* @__PURE__ */ e.createElement(v, null, d.getValidationDescription(A.enum.username, P).join(". "))))), !this.isDisplayNameDisabled() && /* @__PURE__ */ e.createElement(h, null, /* @__PURE__ */ e.createElement(y, null, /* @__PURE__ */ e.createElement(i, { i18nKey: "AccountMyProfilePage.form.displayName" }, "Display name")), /* @__PURE__ */ e.createElement(E, null, /* @__PURE__ */ e.createElement(S, { className: "formGroup", hasError: o === "" }, /* @__PURE__ */ e.createElement(
          b,
          {
            type: "text",
            value: o,
            name: "displayName",
            disabled: g,
            className: "inputGroup",
            onChange: this.onChangeDisplayName,
            readOnly: a
          }
        ), this.renderDisplayNameError(this.validation.get("displayName"), {
          min: M && M.minLength,
          max: M && M.maxLength
        }), /* @__PURE__ */ e.createElement(v, null, d.getValidationDescription(A.enum.displayName, P).join(". "))))), /* @__PURE__ */ e.createElement(h, { className: L.pseudoMarginBottom }, /* @__PURE__ */ e.createElement(y, null, /* @__PURE__ */ e.createElement(i, { i18nKey: "AccountMyProfilePage.form.emailAddress" }, "Email address")), /* @__PURE__ */ e.createElement(E, { className: "emailFormContainer" }, /* @__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(h, { className: L.pseudoMarginBottom }, /* @__PURE__ */ e.createElement(y, null, /* @__PURE__ */ e.createElement(i, { i18nKey: "AccountMyProfilePage.form.country" }, "Country")), /* @__PURE__ */ e.createElement(E, null, /* @__PURE__ */ e.createElement(S, null, /* @__PURE__ */ e.createElement(
          b,
          {
            type: "text",
            value: this.getCountryNameByCountryId(r && r.country || ""),
            disabled: !0,
            className: "countryForm",
            readOnly: a
          }
        ), D && /* @__PURE__ */ e.createElement(v, null, /* @__PURE__ */ e.createElement(i, { i18nKey: "AccountMyProfilePage.form.changeCountryInfo" }, "Please contact our customer support at", " ", /* @__PURE__ */ e.createElement("a", { href: `mailto:${D}`, className: "btnContactSupport" }, { contactSupportEmail: D }), " ", "to request a country change"))))), /* @__PURE__ */ e.createElement(h, { className: L.pseudoMarginBottom }, /* @__PURE__ */ e.createElement(y, null, /* @__PURE__ */ e.createElement(i, { i18nKey: "AccountMyProfilePage.form.zipCode.label" }, "ZIP Code")), /* @__PURE__ */ e.createElement(E, null, /* @__PURE__ */ e.createElement(S, null, /* @__PURE__ */ e.createElement(
          b,
          {
            type: "text",
            value: N,
            onChange: this.onChangeZipCode,
            placeholder: w("AccountMyProfilePage.form.zipCode.placeholder"),
            disabled: g,
            className: "inputGroup",
            readOnly: a
          }
        ), /* @__PURE__ */ e.createElement(v, 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(_, { loadingIndicator: "SPINNER", type: "submit", className: "btn btn-primary", disabled: T, isLoading: g }, /* @__PURE__ */ e.createElement(i, { i18nKey: "AccountMyProfilePage.form.saveChanges" }, "Save changes")))
      );
    }, this.appState = m.getAppState();
    const s = this.appState.getUser();
    this.validation = new ee(), this.validation.listen(() => this.setState({})), this.userManager = this.appState.userAppManager;
    const l = this.userManager.state.userProfile;
    this.state = {
      displayName: (s == null ? void 0 : s.displayName) || null,
      userName: (s == null ? void 0 : s.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 n = m.getAppState().state.appHistory.location.state;
    (n == null ? void 0 : n.updateEmailStatus) === "success" && (this.setState({
      alert: {
        type: f.success,
        element: /* @__PURE__ */ e.createElement(i, { i18nKey: "NewEmailVerificationPage.verified" }, "Congratulations! Your email has been updated.")
      }
    }), window.history.replaceState({}, ""));
  }
  getParams(n, s, l) {
    const { user: t, userProfile: a } = this.userManager.state, r = {}, o = {};
    return t && (n !== t.displayName && (r.displayName = n), s && s !== t.userName && (r.userName = s), (!a || l !== a.zipCode) && (o.zipCode = l)), { params: r, userProfileParams: o };
  }
  renderDisplayNameError(n, s = {}) {
    if (!n)
      return null;
    const l = {
      [p.empty]: /* @__PURE__ */ e.createElement(i, { i18nKey: "AccountMyProfilePage.form.displayNameEmptyError" }, "The display name cannot be empty."),
      [p.lessThanLengthLimit]: /* @__PURE__ */ e.createElement(i, { i18nKey: "AccountMyProfilePage.form.lessThanLengthLimit" }, "Your display name must contain at least ", { DISPLAY_NAME_MIN_LIMIT: s.min }, " characters"),
      [p.exceedLengthLimit]: /* @__PURE__ */ e.createElement(i, { i18nKey: "AccountMyProfilePage.form.displayNameExceedLimit" }, "Your display name must not exceed ", { MAX_DISPLAY_NAME_LENGTH: s.max }, " characters"),
      [F.invalidFormat]: /* @__PURE__ */ e.createElement(i, { i18nKey: "AccountMyProfilePage.form.displayNameInvalidFormat" }, "Please enter a valid display name format")
    };
    return /* @__PURE__ */ e.createElement(K, null, l[n]);
  }
  renderUserNameError(n, s = {}) {
    if (!n)
      return null;
    const l = {
      [p.empty]: /* @__PURE__ */ e.createElement(i, { i18nKey: "AccountMyProfilePage.form.userName.emptyError" }, "The username cannot be empty"),
      [p.lessThanLengthLimit]: /* @__PURE__ */ e.createElement(i, { i18nKey: "AccountMyProfilePage.form.userName.lessThanLengthLimit" }, "Your username must contain at least ", { MIN_USERNAME_LENGTH: s.min }, " characters"),
      [p.exceedLengthLimit]: /* @__PURE__ */ e.createElement(i, { i18nKey: "AccountMyProfilePage.form.userName.exceedLimit" }, "Your username must not exceed ", { MAX_USERNAME_LENGTH: s.max }, " characters"),
      [F.invalidFormat]: /* @__PURE__ */ e.createElement(i, { i18nKey: "AccountMyProfilePage.form.userName.invalidFormat" }, "Please enter a valid username format")
    };
    return /* @__PURE__ */ e.createElement(K, null, l[n]);
  }
  render() {
    const { isFetchingProfile: n, errorFetchingProfile: s } = this.userManager.state, { isRequestingVerificationCode: l } = this.appState.verificationManager.state, { alert: t, isChangeEmailDialogOpen: a } = this.state;
    return /* @__PURE__ */ e.createElement(O, { className: ce.profilePage }, /* @__PURE__ */ e.createElement(R, { className: "mainHeader" }, /* @__PURE__ */ e.createElement(i, { i18nKey: "AccountMyProfilePage.title" }, "My Profile"), /* @__PURE__ */ e.createElement(ie, { to: I.ProfileHistory.makePath(), className: "btnSeeAccountHistory" }, /* @__PURE__ */ e.createElement(i, { i18nKey: "AccountMyProfilePage.link.seeAccountHistory" }, "See account history"))), /* @__PURE__ */ e.createElement(k, null, !n && t && !a && /* @__PURE__ */ e.createElement("div", null, /* @__PURE__ */ e.createElement(
      z,
      {
        type: t.type,
        className: "profilePageAlerts",
        onDismiss: () => {
          this.setState({ alert: null });
        }
      },
      t.element
    ), s && /* @__PURE__ */ e.createElement(_, { className: "btn btn-primary btnReload", onClick: this.initializeProfilePage }, /* @__PURE__ */ e.createElement(i, { i18nKey: "Common.reload" }, "Reload"))), n && /* @__PURE__ */ e.createElement(te, { className: ae.medium }), !n && !s && this.renderFormEditProfile(), a && /* @__PURE__ */ e.createElement(
      le,
      {
        isRequestingVerificationCode: l,
        onClose: this.closeChangeEmailDialog,
        onSendVerification: this.onSendVerificationCode,
        onDismissAlert: () => this.setState({ alert: null }),
        alert: t
      }
    )));
  }
}
export {
  Ce as default
};
