import { A as AccountMainSection, b as AccountMainSectionHeader, a as AccountMainSectionBody } from "./AccountMainSection.js";
import { a3 as Dialog, t, a4 as DialogBody, h as AlertType, j as Alert, T as Trans, a5 as DialogFooter, f as Button, a as Ctx, x as getCurrentLanguage, K as Env, i as CommonError, y as validationOutdatedModalEvent, E as ErrorHelper, H as translateServiceError, aF as InputValidationHelper, V as VerificationCodeContext, g as AccPath, ac as EligibleUser, aH as ValidateableInputField, aC as FormGroup, J as InputGroup, aP as FormGroupInfo, aQ as FormGroupStyles, aB as Validation, aR as ValidateLengthErrorType, aS as ValidateRegexErrorType, aA as FormGroupError, L as Loading, w as LoadingSize } from "./index.js";
import React__default from "react";
import { Link } from "react-router-dom";
import { C as CommonEntryGroup, a as CommonEntryGroupLabel, b as CommonEntryGroupInput } from "./CommonEntryGroup.js";
import "./reactSlick.js";
import "./dateFns.js";
import "./validator.js";
import "./reactPlayer.js";
const dialogBody = "dialogBody _dialogBody_c3b51";
const dialogFooter = "dialogFooter _dialogFooter_d5e9c";
var styles$1 = {
  dialogBody,
  dialogFooter
};
const ChangeEmailDialog = (props) => {
  const { isRequestingVerificationCode, onClose, onSendVerification, onDismissAlert, alert } = props;
  return /* @__PURE__ */ React__default.createElement(Dialog, {
    title: t("AccountMyProfilePage.dialog.changeEmail.title"),
    isOpen: true
  }, /* @__PURE__ */ React__default.createElement(DialogBody, {
    className: styles$1.dialogBody
  }, alert && alert.type === AlertType.danger && /* @__PURE__ */ React__default.createElement("div", {
    className: "mb-3"
  }, /* @__PURE__ */ React__default.createElement(Alert, {
    type: alert.type,
    className: "profilePageAlerts",
    onDismiss: onDismissAlert
  }, alert.element)), /* @__PURE__ */ React__default.createElement(Trans, {
    i18nKey: "AccountMyProfilePage.dialog.changeEmail.content"
  }, /* @__PURE__ */ React__default.createElement("p", null, "You will need a verification code to make this change."), /* @__PURE__ */ React__default.createElement("p", null, "Click the button below to receive an email containing your code."))), /* @__PURE__ */ React__default.createElement(DialogFooter, {
    className: styles$1.dialogFooter
  }, /* @__PURE__ */ React__default.createElement("button", {
    onClick: () => onClose(),
    className: "btn big btn-ghost btnVerification"
  }, /* @__PURE__ */ React__default.createElement(Trans, {
    i18nKey: "AccountMyProfilePage.dialog.cancel"
  }, "CANCEL")), /* @__PURE__ */ React__default.createElement(Button, {
    loadingIndicator: "SPINNER",
    onClick: () => onSendVerification(),
    className: "btn big btn-primary btnCancel",
    disabled: isRequestingVerificationCode,
    isLoading: isRequestingVerificationCode
  }, /* @__PURE__ */ React__default.createElement(Trans, {
    i18nKey: "AccountMyProfilePage.dialog.sendVerification"
  }, "Send Verification"))));
};
const profilePage = "profilePage _profilePage_fd25b";
var styles = {
  profilePage
};
class ProfilePage extends React__default.Component {
  constructor(props) {
    super(props);
    this.initializeProfilePage = async () => {
      await this.userManager.fetchOrCreateUserProfile();
      if (this.userManager.state.errorFetchingProfile !== null) {
        this.setErrorAlert(this.userManager.state.errorFetchingProfile);
      }
      if (this.appState.miscAppManager.state.countries.length === 0) {
        await this.appState.miscAppManager.fetchCountries();
      }
      if (Ctx.getInputValidationManager().state.validations.length === 0) {
        await Ctx.getInputValidationManager().fetchValidations(getCurrentLanguage());
      }
      this.populateUserAndUserProfileFromLogic();
    };
    this.isDisplayNameDisabled = () => Env.IS_DISABLE_DISPLAY_NAME;
    this.isUserNameDisabled = () => Env.IS_DISABLE_USERNAME;
    this.populateUserFromLogic = () => {
      const { user: user2 } = this.userManager.state;
      if (user2) {
        const isDisplayNameEmpty = this.isDisplayNameDisabled() || user2.displayName === "";
        const isUserNameEmpty = this.isUserNameDisabled() || user2.userName === "";
        this.setState({
          displayName: isDisplayNameEmpty ? null : user2.displayName,
          userName: isUserNameEmpty || !user2.userName ? null : user2.userName
        });
      }
    };
    this.populateUserProfileFromLogic = () => {
      const { userProfile } = this.userManager.state;
      this.setState({
        zipCode: userProfile && userProfile.zipCode ? userProfile.zipCode : null
      });
    };
    this.populateUserAndUserProfileFromLogic = () => {
      this.populateUserFromLogic();
      this.populateUserProfileFromLogic();
    };
    this.setErrorAlert = (error) => {
      this.setState({
        alert: {
          type: AlertType.danger,
          element: /* @__PURE__ */ React__default.createElement(CommonError, {
            error
          })
        }
      });
    };
    this.notifyUpdateSuccess = () => {
      this.setState({
        alert: {
          type: AlertType.success,
          element: /* @__PURE__ */ React__default.createElement(Trans, {
            i18nKey: "AccountMyProfilePage.updateSuccess"
          }, "Your profile has been updated!")
        }
      });
    };
    this.notifyUpdateError = async (error) => {
      if (await Ctx.getInputValidationManager().isInputValidationError(error)) {
        validationOutdatedModalEvent.openValidationOutdatedModal();
        this.setState({ alert: null });
        return;
      }
      const errorCode = ErrorHelper.extractServiceErrorCode(error);
      if (errorCode) {
        this.setState({
          alert: {
            type: AlertType.danger,
            element: (() => {
              switch (errorCode) {
                case 10130:
                  return /* @__PURE__ */ React__default.createElement(Trans, {
                    i18nKey: "UpdateUser.error.updateErrorUnderage"
                  }, "You are below the required age");
                case 10177:
                  return /* @__PURE__ */ React__default.createElement(Trans, {
                    i18nKey: "UpdateUser.error.updateErrorConflict"
                  }, "The username has been taken. Please choose another");
                default:
                  return translateServiceError(errorCode) || /* @__PURE__ */ React__default.createElement(Trans, {
                    i18nKey: "UpdateUser.error.updateError"
                  }, "Failed to update your account information. Please try again.");
              }
            })()
          }
        });
      } else {
        this.setErrorAlert(error);
      }
    };
    this.isProfileChanged = () => {
      const { user: user2 } = this.userManager.state;
      const { userProfile } = this.userManager.state;
      const { displayName, userName, zipCode } = this.state;
      if (user2 !== null) {
        if (displayName !== null && user2.displayName !== displayName.trim()) {
          return true;
        }
        if (userName !== null && user2.userName !== userName.trim()) {
          return true;
        }
        if (zipCode !== null && userProfile && userProfile.zipCode !== zipCode.trim()) {
          return true;
        }
      }
      return false;
    };
    this.onChangeDisplayName = (event) => {
      const displayName = event.target.value;
      const { validations } = Ctx.getInputValidationManager().state;
      this.validation.set("displayName", InputValidationHelper.validateDisplayName(displayName, this.isUserNameDisabled(), validations));
      this.setState({ displayName });
    };
    this.onChangeZipCode = (event) => {
      const zipCode = event.target.value;
      this.setState({ zipCode });
    };
    this.onChangeUserName = (event) => {
      const userName = event.target.value;
      const { validations } = Ctx.getInputValidationManager().state;
      this.validation.set("userName", InputValidationHelper.validateUserName(userName, validations));
      this.setState({ userName });
    };
    this.openChangeEmailDialog = () => {
      this.setState({ isChangeEmailDialogOpen: true });
      this.appState.verificationManager.setState({ isRequestVerificationCodeSuccess: null });
    };
    this.closeChangeEmailDialog = () => this.setState({ isChangeEmailDialogOpen: false });
    this.onSubmit = async (event, displayName, userName, zipCode) => {
      event.preventDefault();
      const { params, userProfileParams } = this.getParams(displayName, userName, zipCode);
      try {
        await Promise.all([this.userManager.updateUser(params), this.userManager.updateUserProfile(userProfileParams)]);
        this.notifyUpdateSuccess();
      } catch (error) {
        this.notifyUpdateError(this.userManager.state.updateError);
      }
    };
    this.onSendVerificationCode = async () => {
      const { user: user2 } = this.userManager.state;
      if (!user2)
        return;
      try {
        await this.appState.verificationManager.sendVerificationCode(user2.emailAddress, VerificationCodeContext.enum.UpdateEmailAddress);
        this.appState.state.appHistory.replace(AccPath.ChangeEmail.makePath());
      } catch (error) {
        const { requestVerificationCodeError } = this.appState.verificationManager.state;
        this.setErrorAlert(requestVerificationCodeError);
      }
    };
    this.getCountryNameByCountryId = (countryId) => {
      const { countries } = this.appState.miscAppManager.state;
      if (!countries)
        return countryId;
      const userCountry = countries.find((country) => country.code === countryId);
      if (userCountry)
        return userCountry.name || countryId;
      return countryId;
    };
    this.renderFormEditProfile = () => {
      const { user: user2 } = this.userManager.state;
      if (!EligibleUser.safeParse(user2).success || !user2)
        return;
      const displayName = this.state.displayName !== null ? this.state.displayName : user2.displayName || "";
      const isDisplayNameValid = this.isUserNameDisabled() ? displayName.length > 0 : true;
      const userName = this.state.userName !== null ? this.state.userName : user2.userName || "";
      const zipCode = this.state.zipCode || "";
      const isUserNameValid = this.isUserNameDisabled() || userName.length > 0;
      const { validations } = Ctx.getInputValidationManager().state;
      const usernameProps = InputValidationHelper.getValidationByKey(ValidateableInputField.enum.username, validations);
      const displayNameProps = InputValidationHelper.getValidationByKey(ValidateableInputField.enum.displayName, validations);
      const isUpdating = this.userManager.state.isUpdating || this.userManager.state.isFetchingUser;
      const isSaveBtnDisabled = isUpdating || !isDisplayNameValid || !isUserNameValid || !this.isProfileChanged() || !this.validation.isAllValid();
      const contactSupportEmail = Env.CONTACT_SUPPORT_EMAIL;
      return /* @__PURE__ */ React__default.createElement("form", {
        onSubmit: (event) => {
          if (displayName !== null && userName !== null && zipCode !== null) {
            this.onSubmit(event, displayName, userName, zipCode);
          }
        }
      }, /* @__PURE__ */ React__default.createElement("div", {
        className: "formInputContainer"
      }, !this.isUserNameDisabled() && /* @__PURE__ */ React__default.createElement(CommonEntryGroup, null, /* @__PURE__ */ React__default.createElement(CommonEntryGroupLabel, null, /* @__PURE__ */ React__default.createElement(Trans, {
        i18nKey: "AccountMyProfilePage.form.userName.label"
      }, "Username")), /* @__PURE__ */ React__default.createElement(CommonEntryGroupInput, null, /* @__PURE__ */ React__default.createElement(FormGroup, {
        className: "formGroup",
        hasError: userName === ""
      }, /* @__PURE__ */ React__default.createElement(InputGroup, {
        type: "text",
        value: userName,
        name: "userName",
        disabled: isUpdating,
        className: "inputGroup",
        onChange: this.onChangeUserName
      }), this.renderUserNameError(this.validation.get("userName"), {
        min: usernameProps && usernameProps.minLength,
        max: usernameProps && usernameProps.maxLength
      }), /* @__PURE__ */ React__default.createElement(FormGroupInfo, null, InputValidationHelper.getValidationDescription(ValidateableInputField.enum.username, validations).join(". "))))), !this.isDisplayNameDisabled() && /* @__PURE__ */ React__default.createElement(CommonEntryGroup, null, /* @__PURE__ */ React__default.createElement(CommonEntryGroupLabel, null, /* @__PURE__ */ React__default.createElement(Trans, {
        i18nKey: "AccountMyProfilePage.form.displayName"
      }, "Display name")), /* @__PURE__ */ React__default.createElement(CommonEntryGroupInput, null, /* @__PURE__ */ React__default.createElement(FormGroup, {
        className: "formGroup",
        hasError: displayName === ""
      }, /* @__PURE__ */ React__default.createElement(InputGroup, {
        type: "text",
        value: displayName,
        name: "displayName",
        disabled: isUpdating,
        className: "inputGroup",
        onChange: this.onChangeDisplayName
      }), this.renderDisplayNameError(this.validation.get("displayName"), {
        min: displayNameProps && displayNameProps.minLength,
        max: displayNameProps && displayNameProps.maxLength
      }), /* @__PURE__ */ React__default.createElement(FormGroupInfo, null, InputValidationHelper.getValidationDescription(ValidateableInputField.enum.displayName, validations).join(". "))))), /* @__PURE__ */ React__default.createElement(CommonEntryGroup, {
        className: FormGroupStyles.pseudoMarginBottom
      }, /* @__PURE__ */ React__default.createElement(CommonEntryGroupLabel, null, /* @__PURE__ */ React__default.createElement(Trans, {
        i18nKey: "AccountMyProfilePage.form.emailAddress"
      }, "Email address")), /* @__PURE__ */ React__default.createElement(CommonEntryGroupInput, {
        className: "emailFormContainer"
      }, /* @__PURE__ */ React__default.createElement("div", null, user2.emailAddress), /* @__PURE__ */ React__default.createElement("button", {
        className: "btnChange",
        type: "button",
        onClick: this.openChangeEmailDialog
      }, /* @__PURE__ */ React__default.createElement(Trans, {
        i18nKey: "AccountMyProfilePage.form.changeEmail"
      }, "Change")))), /* @__PURE__ */ React__default.createElement(CommonEntryGroup, {
        className: FormGroupStyles.pseudoMarginBottom
      }, /* @__PURE__ */ React__default.createElement(CommonEntryGroupLabel, null, /* @__PURE__ */ React__default.createElement(Trans, {
        i18nKey: "AccountMyProfilePage.form.country"
      }, "Country")), /* @__PURE__ */ React__default.createElement(CommonEntryGroupInput, null, /* @__PURE__ */ React__default.createElement(FormGroup, null, /* @__PURE__ */ React__default.createElement(InputGroup, {
        type: "text",
        value: this.getCountryNameByCountryId(user2 && user2.country || ""),
        disabled: true,
        className: "countryForm"
      }), contactSupportEmail && /* @__PURE__ */ React__default.createElement(FormGroupInfo, null, /* @__PURE__ */ React__default.createElement(Trans, {
        i18nKey: "AccountMyProfilePage.form.changeCountryInfo"
      }, "Please contact our customer support at", " ", /* @__PURE__ */ React__default.createElement("a", {
        href: `mailto:${contactSupportEmail}`,
        className: "btnContactSupport"
      }, { contactSupportEmail }), " ", "to request a country change"))))), /* @__PURE__ */ React__default.createElement(CommonEntryGroup, {
        className: FormGroupStyles.pseudoMarginBottom
      }, /* @__PURE__ */ React__default.createElement(CommonEntryGroupLabel, null, /* @__PURE__ */ React__default.createElement(Trans, {
        i18nKey: "AccountMyProfilePage.form.zipCode.label"
      }, "ZIP Code")), /* @__PURE__ */ React__default.createElement(CommonEntryGroupInput, null, /* @__PURE__ */ React__default.createElement(FormGroup, null, /* @__PURE__ */ React__default.createElement(InputGroup, {
        type: "text",
        value: zipCode,
        onChange: this.onChangeZipCode,
        placeholder: t("AccountMyProfilePage.form.zipCode.placeholder"),
        disabled: isUpdating,
        className: "inputGroup"
      }), /* @__PURE__ */ React__default.createElement(FormGroupInfo, null, /* @__PURE__ */ React__default.createElement(Trans, {
        i18nKey: "AccountMyProfilePage.form.zipCode.tooltip"
      }, "We need your ZIP code to calculate the sales tax for your purchase.")))))), /* @__PURE__ */ React__default.createElement("div", {
        className: "divider"
      }), /* @__PURE__ */ React__default.createElement("div", {
        className: "btnContainer"
      }, /* @__PURE__ */ React__default.createElement(Button, {
        loadingIndicator: "SPINNER",
        type: "submit",
        className: "btn btn-primary",
        disabled: isSaveBtnDisabled,
        isLoading: isUpdating
      }, /* @__PURE__ */ React__default.createElement(Trans, {
        i18nKey: "AccountMyProfilePage.form.saveChanges"
      }, "Save changes"))));
    };
    this.appState = Ctx.getAppState();
    const user = this.appState.getUser();
    this.validation = new Validation();
    this.validation.listen(() => this.setState({}));
    this.userManager = this.appState.userAppManager;
    const userProfileState = this.userManager.state.userProfile;
    this.state = {
      displayName: (user == null ? void 0 : user.displayName) || null,
      userName: (user == null ? void 0 : user.userName) || null,
      isChangeEmailDialogOpen: false,
      alert: null,
      zipCode: (userProfileState == null ? void 0 : userProfileState.zipCode) || null
    };
    Ctx.getInputValidationManager().subscribe(() => this.setState({}));
  }
  async componentDidMount() {
    await this.initializeProfilePage();
    const locationState = Ctx.getAppState().state.appHistory.location.state;
    if ((locationState == null ? void 0 : locationState.updateEmailStatus) === "success") {
      this.setState({
        alert: {
          type: AlertType.success,
          element: /* @__PURE__ */ React__default.createElement(Trans, {
            i18nKey: "NewEmailVerificationPage.verified"
          }, "Congratulations! Your email has been updated.")
        }
      });
      window.history.replaceState({}, "");
    }
  }
  getParams(displayName, userName, zipCode) {
    const { user, userProfile } = this.userManager.state;
    const params = {};
    const userProfileParams = {};
    if (user) {
      if (displayName !== user.displayName) {
        params.displayName = displayName;
      }
      if (!!userName && userName !== user.userName) {
        params.userName = userName;
      }
      if (!userProfile || zipCode !== userProfile.zipCode) {
        userProfileParams.zipCode = zipCode;
      }
    }
    return { params, userProfileParams };
  }
  renderDisplayNameError(errorType, params = {}) {
    if (!errorType)
      return null;
    const displayNameErrorMap = {
      [ValidateLengthErrorType.empty]: /* @__PURE__ */ React__default.createElement(Trans, {
        i18nKey: "AccountMyProfilePage.form.displayNameEmptyError"
      }, "The display name cannot be empty."),
      [ValidateLengthErrorType.lessThanLengthLimit]: /* @__PURE__ */ React__default.createElement(Trans, {
        i18nKey: "AccountMyProfilePage.form.lessThanLengthLimit"
      }, "Your display name must contain at least ", { DISPLAY_NAME_MIN_LIMIT: params.min }, " characters"),
      [ValidateLengthErrorType.exceedLengthLimit]: /* @__PURE__ */ React__default.createElement(Trans, {
        i18nKey: "AccountMyProfilePage.form.displayNameExceedLimit"
      }, "Your display name must not exceed ", { MAX_DISPLAY_NAME_LENGTH: params.max }, " characters"),
      [ValidateRegexErrorType.invalidFormat]: /* @__PURE__ */ React__default.createElement(Trans, {
        i18nKey: "AccountMyProfilePage.form.displayNameInvalidFormat"
      }, "Please enter a valid display name format")
    };
    return /* @__PURE__ */ React__default.createElement(FormGroupError, null, displayNameErrorMap[errorType]);
  }
  renderUserNameError(errorType, params = {}) {
    if (!errorType)
      return null;
    const userNameErrorMap = {
      [ValidateLengthErrorType.empty]: /* @__PURE__ */ React__default.createElement(Trans, {
        i18nKey: "AccountMyProfilePage.form.userName.emptyError"
      }, "The username cannot be empty"),
      [ValidateLengthErrorType.lessThanLengthLimit]: /* @__PURE__ */ React__default.createElement(Trans, {
        i18nKey: "AccountMyProfilePage.form.userName.lessThanLengthLimit"
      }, "Your username must contain at least ", { MIN_USERNAME_LENGTH: params.min }, " characters"),
      [ValidateLengthErrorType.exceedLengthLimit]: /* @__PURE__ */ React__default.createElement(Trans, {
        i18nKey: "AccountMyProfilePage.form.userName.exceedLimit"
      }, "Your username must not exceed ", { MAX_USERNAME_LENGTH: params.max }, " characters"),
      [ValidateRegexErrorType.invalidFormat]: /* @__PURE__ */ React__default.createElement(Trans, {
        i18nKey: "AccountMyProfilePage.form.userName.invalidFormat"
      }, "Please enter a valid username format")
    };
    return /* @__PURE__ */ React__default.createElement(FormGroupError, null, userNameErrorMap[errorType]);
  }
  render() {
    const { isFetchingProfile, errorFetchingProfile } = this.userManager.state;
    const { isRequestingVerificationCode } = this.appState.verificationManager.state;
    const { alert, isChangeEmailDialogOpen } = this.state;
    return /* @__PURE__ */ React__default.createElement(AccountMainSection, {
      className: styles.profilePage
    }, /* @__PURE__ */ React__default.createElement(AccountMainSectionHeader, {
      className: "mainHeader"
    }, /* @__PURE__ */ React__default.createElement(Trans, {
      i18nKey: "AccountMyProfilePage.title"
    }, "My Profile"), /* @__PURE__ */ React__default.createElement(Link, {
      to: AccPath.ProfileHistory.makePath(),
      className: "btnSeeAccountHistory"
    }, /* @__PURE__ */ React__default.createElement(Trans, {
      i18nKey: "AccountMyProfilePage.link.seeAccountHistory"
    }, "See account history"))), /* @__PURE__ */ React__default.createElement(AccountMainSectionBody, null, !isFetchingProfile && alert && !isChangeEmailDialogOpen && /* @__PURE__ */ React__default.createElement("div", null, /* @__PURE__ */ React__default.createElement(Alert, {
      type: alert.type,
      className: "profilePageAlerts",
      onDismiss: () => {
        this.setState({ alert: null });
      }
    }, alert.element), errorFetchingProfile && /* @__PURE__ */ React__default.createElement(Button, {
      className: "btn btn-primary btnReload",
      onClick: this.initializeProfilePage
    }, /* @__PURE__ */ React__default.createElement(Trans, {
      i18nKey: "Common.reload"
    }, "Reload"))), isFetchingProfile && /* @__PURE__ */ React__default.createElement(Loading, {
      className: LoadingSize.medium
    }), !isFetchingProfile && !errorFetchingProfile && this.renderFormEditProfile(), isChangeEmailDialogOpen && /* @__PURE__ */ React__default.createElement(ChangeEmailDialog, {
      isRequestingVerificationCode,
      onClose: this.closeChangeEmailDialog,
      onSendVerification: this.onSendVerificationCode,
      onDismissAlert: () => this.setState({ alert: null }),
      alert
    })));
  }
}
export { ProfilePage as default };
