import { aE as validateAlphanumeric, T as Trans, aF as ValidateAlphaNumericErrorType, aG as FormGroupError, a_ as MAX_SHORT_TEXT_LENGTH, aI as FormGroup, J as InputGroup, t, K as Env, aL as InputValidationHelper, aY as ValidateRegexErrorType, aX as ValidateLengthErrorType, a$ as LegalHelper, b0 as LegalUtils, a as Ctx, aH as Validation, aN as ValidateableInputField, aM as PasswordConstraint, f as Button, x as getCurrentLanguage, V as VerificationCodeContext, y as validationOutdatedModalEvent, E as ErrorHelper, h as AlertType, i as CommonError, k as UIEvent, l as bgCommon, b1 as ValidateEmailErrorType, aT as CommonValidationErrorType, j as Alert, L as Loading, w as LoadingSize, v as LoginPath, I as InputValidationOutdatedModal } from "./index.js";
import { V as ValidateDisplayNameErrorType, L as LanguageSelector, H as HeaderLogoContainer } from "./LinkPlatformAccountPage.js";
import React__default from "react";
import { C as Checkbox } from "./Checkbox.js";
import { I as InputGroupPassword } from "./InputPassword.js";
import "./dateFns.js";
import "./validator.js";
import "./reactPlayer.js";
import "react-router-dom";
import "./reactSlick.js";
import "./Tabs.js";
import "./CommonError.js";
import "./starBgGradient.js";
import "./CommonError2.js";
const logoContainer = "logoContainer _logoContainer_07abf";
const headlessAccountPage = "headlessAccountPage _headlessAccountPage_fc4c2";
const headlessAccountPageContainer = "headlessAccountPageContainer _headlessAccountPageContainer_d677c";
const headlessAccountPageContainerForm = "headlessAccountPageContainerForm _headlessAccountPageContainerForm_b0707";
const contentWrapper = "contentWrapper _contentWrapper_70cc1";
const formWrapper = "formWrapper _formWrapper_56a6a";
const alert = "alert _alert_9e219";
const passwordValidation = "passwordValidation _passwordValidation_7b708";
const flexCol = "flexCol _flexCol_28462";
const passwordMismatch = "passwordMismatch _passwordMismatch_2a7aa";
const title = "title _title_540b1";
const description = "description _description_82f64";
const resendCode = "resendCode _resendCode_89835";
const tabs = "tabs _tabs_556dd";
const tab = "tab _tab_7c33e";
const active = "active _active_e075d";
const label = "label _label_49131";
const input = "input _input_1c241";
const select = "select _select_8541f";
const datePicker = "datePicker _datePicker_6f316";
const agreementList = "agreementList _agreementList_b9517";
const agreementItem = "agreementItem _agreementItem_48371";
const text = "text _text_d0edc";
const optional = "optional _optional_99291";
const changePage = "changePage _changePage_71454";
const backContainer = "backContainer _backContainer_eee44";
var styles = {
  logoContainer,
  headlessAccountPage,
  headlessAccountPageContainer,
  headlessAccountPageContainerForm,
  contentWrapper,
  formWrapper,
  alert,
  passwordValidation,
  flexCol,
  passwordMismatch,
  title,
  description,
  resendCode,
  tabs,
  tab,
  active,
  label,
  input,
  select,
  datePicker,
  agreementList,
  agreementItem,
  text,
  optional,
  changePage,
  backContainer
};
class UpgradeHeadlessVerification extends React__default.Component {
  constructor(props) {
    super(props);
    this.refreshComponent = () => this.setState({});
    this.onVerificationCodeChange = (event) => {
      const verificationCode = event.target.value.toString().toUpperCase();
      const trimSpaceOnPastedVerificationCode = !this.state.isPasteVerificationCode ? verificationCode : verificationCode.replace(/\s/g, "");
      this.props.validation.set("verificationCode", validateAlphanumeric(trimSpaceOnPastedVerificationCode));
      this.props.onChangeVerificationCode(trimSpaceOnPastedVerificationCode);
      this.setState({ isPasteVerificationCode: false });
    };
    this.onPasteVerificationCode = () => {
      this.setState({ isPasteVerificationCode: true });
    };
    this.renderVerificationCodeError = (errorType) => {
      if (!errorType)
        return null;
      switch (errorType) {
        case ValidateAlphaNumericErrorType.empty:
          return /* @__PURE__ */ React__default.createElement(FormGroupError, null, /* @__PURE__ */ React__default.createElement(Trans, {
            i18nKey: "UpgradeHeadlessAccountPage.UpgradeHeadlessAccountForm.verifyCodeError.empty"
          }, "You must enter your verification code"));
        case ValidateAlphaNumericErrorType.exceedLengthLimit:
          return /* @__PURE__ */ React__default.createElement(FormGroupError, null, /* @__PURE__ */ React__default.createElement(Trans, {
            i18nKey: "UpgradeHeadlessAccountPage.UpgradeHeadlessAccountForm.verifyCodeError.ExceedLimit"
          }, "Verification code must not exceed ", { MAX_SHORT_TEXT_LENGTH }, " characters"));
        case ValidateAlphaNumericErrorType.invalidFormat:
          return /* @__PURE__ */ React__default.createElement(FormGroupError, null, /* @__PURE__ */ React__default.createElement(Trans, {
            i18nKey: "UpgradeHeadlessAccountPage.UpgradeHeadlessAccountForm.verifyCodeError.invalidFormat"
          }, "Please enter a valid verification code"));
        default:
          return /* @__PURE__ */ React__default.createElement(Trans, {
            i18nKey: "CommonError.unknownError"
          }, "Something went wrong. Please contact support for assistance.");
      }
    };
    this.state = {
      isPasteVerificationCode: false
    };
  }
  componentDidMount() {
    this.props.validation.listen(this.refreshComponent);
  }
  componentWillUnmount() {
    this.props.validation.unlisten(this.refreshComponent);
  }
  render() {
    const { isRequestingVerificationCode, onRequestVerificationCode, verificationCode, onChangePage, validation } = this.props;
    return /* @__PURE__ */ React__default.createElement(React__default.Fragment, null, /* @__PURE__ */ React__default.createElement(FormGroup, {
      className: styles.formGroup
    }, /* @__PURE__ */ React__default.createElement("div", {
      className: styles.label
    }, /* @__PURE__ */ React__default.createElement(Trans, {
      i18nKey: "UpgradeHeadlessAccountPage.UpgradeHeadlessAccountForm.verificationCode"
    }, "Verification Code")), /* @__PURE__ */ React__default.createElement(InputGroup, {
      type: "text",
      value: verificationCode || "",
      className: styles.input,
      placeholder: t("UpgradeHeadlessAccountPage.UpgradeHeadlessAccountForm.placeholder.verificationCodePlaceholder"),
      onChange: this.onVerificationCodeChange,
      onPaste: this.onPasteVerificationCode
    }), this.renderVerificationCodeError(validation.get("verificationCode")), /* @__PURE__ */ React__default.createElement("div", {
      className: styles.resendCode
    }, /* @__PURE__ */ React__default.createElement(Trans, {
      i18nKey: "UpgradeHeadlessAccountPage.UpgradeHeadlessAccountForm.didntReceiveEmail"
    }, "Didn't receive the email?"), isRequestingVerificationCode && /* @__PURE__ */ React__default.createElement("span", null, /* @__PURE__ */ React__default.createElement(Trans, {
      i18nKey: "UpgradeHeadlessAccountPage.UpgradeHeadlessAccountForm.requestingCode"
    }, " Requesting...")), !isRequestingVerificationCode && /* @__PURE__ */ React__default.createElement("span", {
      onClick: () => onRequestVerificationCode && onRequestVerificationCode()
    }, /* @__PURE__ */ React__default.createElement(Trans, {
      i18nKey: "UpgradeHeadlessAccountPage.UpgradeHeadlessAccountForm.resend"
    }, "Click here to resend"))), /* @__PURE__ */ React__default.createElement("div", {
      className: styles.resendCode
    }, /* @__PURE__ */ React__default.createElement(Trans, {
      i18nKey: "UpgradeHeadlessAccountPage.UpgradeHeadlessAccountForm.enterWrongEmail"
    }, "Entered the wrong email? "), /* @__PURE__ */ React__default.createElement("span", {
      onClick: () => onChangePage && onChangePage()
    }, /* @__PURE__ */ React__default.createElement(Trans, {
      i18nKey: "UpgradeHeadlessAccountPage.UpgradeHeadlessAccountForm.clickToChange"
    }, "Click here to change")))));
  }
}
class UpgradeHeadlessAccountForm extends React__default.Component {
  constructor(props) {
    super(props);
    this.updatePolicies = () => {
      const { policies } = this.props;
      if (!policies)
        return;
      this.setState({
        requiredPolicies: policies.filter((policy) => policy.isMandatory),
        optionalPolicies: policies.filter((policy) => !policy.isMandatory)
      });
    };
    this.isDisplayNameDisabled = () => Env.IS_DISABLE_DISPLAY_NAME;
    this.isUserNameDisabled = () => Env.IS_DISABLE_USERNAME;
    this.onChangeDisplayName = (event) => {
      const displayName = event.target.value;
      const { validations } = this.props.inputValidationManager.state;
      this.validation.set("displayName", InputValidationHelper.validateDisplayName(displayName, this.isUserNameDisabled(), validations));
      this.setState({ displayName });
    };
    this.onChangeUsername = (event) => {
      const username = event.target.value;
      const { validations } = this.props.inputValidationManager.state;
      this.validation.set("username", InputValidationHelper.validateUserName(username, validations));
      this.setState({ username });
    };
    this.onPasswordChange = (event) => {
      const password = event.target.value;
      const { validations } = this.props.inputValidationManager.state;
      this.validation.set("password", InputValidationHelper.validatePassword(password, validations));
      this.setState({
        password
      });
    };
    this.onVerificationCodeChange = (verificationCode) => {
      this.setState({ verificationCode });
    };
    this.renderPasswordError = ({ min, max } = {}) => {
      const errorType = this.validation.get("password");
      if (!errorType)
        return null;
      switch (errorType) {
        case ValidateLengthErrorType.empty:
          return /* @__PURE__ */ React__default.createElement(FormGroupError, null, t("UpgradeHeadlessAccountPage.UpgradeHeadlessAccountForm.form.passwordEmptyError"));
        case ValidateLengthErrorType.lessThanLengthLimit:
          return /* @__PURE__ */ React__default.createElement(FormGroupError, null, t("UpgradeHeadlessAccountPage.UpgradeHeadlessAccountForm.form.passwordLessThanLengthLimit", { PASSWORD_MIN_LIMIT: min }));
        case ValidateLengthErrorType.exceedLengthLimit:
          return /* @__PURE__ */ React__default.createElement(FormGroupError, null, t("UpgradeHeadlessAccountPage.UpgradeHeadlessAccountForm.form.passwordExceedLimit", { PASSWORD_MAX_LENGTH: max }));
        case ValidateRegexErrorType.invalidFormat:
          return /* @__PURE__ */ React__default.createElement(FormGroupError, null, t("UpgradeHeadlessAccountPage.UpgradeHeadlessAccountForm.form.passwordInvalidFormat"));
        default:
          return t("CommonError.unknownError");
      }
    };
    this.renderMinimumAgeCheckbox = () => {
      const { reachMinimumAge } = this.state;
      const { age } = this.userManager.state.ageRestriction;
      if (!age)
        return;
      return /* @__PURE__ */ React__default.createElement("div", {
        className: styles.agreementList
      }, /* @__PURE__ */ React__default.createElement("div", {
        className: styles.agreementItem
      }, /* @__PURE__ */ React__default.createElement(Checkbox, {
        isChecked: reachMinimumAge,
        onChange: () => {
          this.setState({ reachMinimumAge: !reachMinimumAge });
        }
      }), /* @__PURE__ */ React__default.createElement("div", {
        className: styles.text
      }, /* @__PURE__ */ React__default.createElement(Trans, {
        i18nKey: "UpgradeHeadlessAccountPage.UpgradeHeadlessAccountForm.minimumAge"
      }, "I confirm that I am ", { age }, " years of age or older."))));
    };
    this.renderRequiredPolicies = () => {
      const { requiredPolicies, isRequiredPolicyAccepted } = this.state;
      if (!requiredPolicies.length)
        return;
      return /* @__PURE__ */ React__default.createElement("div", {
        className: styles.agreementList
      }, /* @__PURE__ */ React__default.createElement("div", {
        className: styles.agreementItem
      }, /* @__PURE__ */ React__default.createElement(Checkbox, {
        isChecked: isRequiredPolicyAccepted,
        onChange: () => {
          this.setState({ isRequiredPolicyAccepted: !isRequiredPolicyAccepted });
        }
      }), /* @__PURE__ */ React__default.createElement("div", {
        className: styles.text
      }, t("UpgradeHeadlessAccountPage.UpgradeHeadlessAccountForm.tos.haveRead"), requiredPolicies.map((policy, index) => {
        const legalUri = LegalHelper.createLegalURL(LegalUtils.getLegalUrl(), policy.localizedPolicyVersionId);
        return /* @__PURE__ */ React__default.createElement(React__default.Fragment, null, index === requiredPolicies.length - 1 && requiredPolicies.length > 1 && t("UpgradeHeadlessAccountPage.UpgradeHeadlessAccountForm.tos.and"), /* @__PURE__ */ React__default.createElement("span", {
          key: index
        }, /* @__PURE__ */ React__default.createElement("a", {
          href: legalUri,
          target: "_blank",
          rel: "noreferrer"
        }, policy.policyName)), requiredPolicies.length !== 1 && index !== requiredPolicies.length - 1 && index !== requiredPolicies.length - 2 ? ", " : " ");
      }))));
    };
    this.renderOptionalPolicies = () => {
      const { optionalPolicies, acceptedOptionalPolicyIdMap } = this.state;
      if (!optionalPolicies || !optionalPolicies.length)
        return null;
      return optionalPolicies.map((policy) => {
        const legalUri = LegalHelper.createLegalURL(LegalUtils.getLegalUrl(), policy.localizedPolicyVersionId);
        return /* @__PURE__ */ React__default.createElement("div", {
          className: styles.agreementList,
          key: policy.policyId
        }, /* @__PURE__ */ React__default.createElement("div", {
          className: styles.agreementItem
        }, /* @__PURE__ */ React__default.createElement(Checkbox, {
          isChecked: acceptedOptionalPolicyIdMap.get(policy.policyId),
          onChange: () => {
            this.onClickOptionalPolicyCheckbox(policy);
          }
        }), /* @__PURE__ */ React__default.createElement("span", {
          className: `${styles.text} ${styles.optional}`
        }, /* @__PURE__ */ React__default.createElement(Trans, {
          i18nKey: "linkPlatformAccountPage.LinkNewAccount.optional"
        }, "[Optional]")), /* @__PURE__ */ React__default.createElement("div", {
          className: styles.text
        }, policy.policyName, /* @__PURE__ */ React__default.createElement("a", {
          href: legalUri,
          target: "_blank",
          rel: "noreferrer"
        }, /* @__PURE__ */ React__default.createElement(Trans, {
          i18nKey: "UpgradeHeadlessAccountPage.UpgradeHeadlessAccountPage.learnMore"
        }, "Learn more.")))));
      });
    };
    this.onClickOptionalPolicyCheckbox = (policy) => {
      const { acceptedOptionalPolicyIdMap } = this.state;
      acceptedOptionalPolicyIdMap.set(policy.policyId, !acceptedOptionalPolicyIdMap.get(policy.policyId));
      this.setState({ acceptedOptionalPolicyIdMap });
    };
    this.onClickContinue = () => {
      const { isRequiredPolicyAccepted, requiredPolicies, acceptedOptionalPolicyIdMap } = this.state;
      const acceptedPolicyIds = [];
      if (isRequiredPolicyAccepted) {
        for (const policy of requiredPolicies) {
          acceptedPolicyIds.push(policy.policyId);
        }
      }
      acceptedOptionalPolicyIdMap.forEach((value, key) => {
        if (value)
          acceptedPolicyIds.push(key);
      });
      this.props.onContinue({
        ...this.state,
        acceptedPolicyIds,
        reachMinimumAge: true
      });
    };
    this.state = {
      verificationCode: "",
      displayName: "",
      username: "",
      password: "",
      requiredPolicies: [],
      optionalPolicies: [],
      isRequiredPolicyAccepted: false,
      reachMinimumAge: false,
      acceptedOptionalPolicyIdMap: /* @__PURE__ */ new Map()
    };
    this.userManager = Ctx.getAppState().userAppManager;
    this.validation = new Validation();
    this.validation.listen(() => this.setState({}));
  }
  componentDidMount() {
    const { country } = this.props.user;
    this.userManager.getAgeRestrictionByCountry(country);
    this.updatePolicies();
  }
  componentDidUpdate(prevProps) {
    const { policies } = this.props;
    if (JSON.stringify(policies) === JSON.stringify(prevProps.policies))
      return;
    this.updatePolicies();
  }
  renderDisplayNameError(errorType, params = {}) {
    if (!errorType)
      return null;
    switch (errorType) {
      case ValidateLengthErrorType.empty:
        return /* @__PURE__ */ React__default.createElement(FormGroupError, null, t("AccountMyProfilePage.form.displayNameEmptyError"));
      case ValidateLengthErrorType.lessThanLengthLimit:
        return /* @__PURE__ */ React__default.createElement(FormGroupError, null, t("AccountMyProfilePage.form.lessThanLengthLimit", { DISPLAY_NAME_MIN_LIMIT: params.min }));
      case ValidateLengthErrorType.exceedLengthLimit:
        return /* @__PURE__ */ React__default.createElement(FormGroupError, null, t("AccountMyProfilePage.form.displayNameExceedLimit", { MAX_DISPLAY_NAME_LENGTH: params.max }));
      case ValidateRegexErrorType.invalidFormat:
        return /* @__PURE__ */ React__default.createElement(FormGroupError, null, t("AccountMyProfilePage.form.displayNameInvalidFormat"));
      default:
        return t("CommonError.unknownError");
    }
  }
  renderUserNameError(errorType, params = {}) {
    if (!errorType)
      return null;
    switch (errorType) {
      case ValidateLengthErrorType.empty:
        return /* @__PURE__ */ React__default.createElement(FormGroupError, null, /* @__PURE__ */ React__default.createElement(Trans, {
          i18nKey: "AccountMyProfilePage.form.userName.emptyError"
        }, "The username cannot be empty"));
      case ValidateLengthErrorType.lessThanLengthLimit:
        return /* @__PURE__ */ React__default.createElement(FormGroupError, null, /* @__PURE__ */ React__default.createElement(Trans, {
          i18nKey: "AccountMyProfilePage.form.userName.lessThanLengthLimit"
        }, "Your username must contain at least ", { MIN_USERNAME_LENGTH: params.min }, " characters"));
      case ValidateLengthErrorType.exceedLengthLimit:
        return /* @__PURE__ */ React__default.createElement(FormGroupError, null, /* @__PURE__ */ React__default.createElement(Trans, {
          i18nKey: "AccountMyProfilePage.form.userName.exceedLimit"
        }, "Your username must not exceed ", { MAX_USERNAME_LENGTH: params.max }, " characters"));
      case ValidateRegexErrorType.invalidFormat:
        return /* @__PURE__ */ React__default.createElement(FormGroupError, null, /* @__PURE__ */ React__default.createElement(Trans, {
          i18nKey: "AccountMyProfilePage.form.userName.invalidFormat"
        }, "Please enter a valid username format"));
      default:
        return /* @__PURE__ */ React__default.createElement(Trans, {
          i18nKey: "CommonError.unknownError"
        }, "Something went wrong. Please contact administrator.");
    }
  }
  render() {
    const { user, onChangePage, inputValidationManager, onRequestVerificationCode, isRequestingVerificationCode, isUpgradingUser } = this.props;
    const { validations } = inputValidationManager.state;
    const { displayName, username, password, requiredPolicies, isRequiredPolicyAccepted, reachMinimumAge, verificationCode } = this.state;
    const { countryName, age } = this.userManager.state.ageRestriction;
    const usernameProps = InputValidationHelper.getValidationByKey(ValidateableInputField.enum.username, validations);
    const displayNameProps = InputValidationHelper.getValidationByKey(ValidateableInputField.enum.displayName, validations);
    const passwordProps = InputValidationHelper.getValidationByKey(ValidateableInputField.enum.password, validations);
    const isDisplayNameValid = this.isUserNameDisabled() ? displayName.length > 0 : true;
    const isUserNameValid = this.isUserNameDisabled() || username.length > 0;
    const isVerificationCodeNotEmpy = verificationCode.length > 0;
    const isSubmitButtonEnabled = this.validation.isAllValid() && (isRequiredPolicyAccepted || requiredPolicies.length === 0) && (reachMinimumAge || !age) && password.length > 0 && isDisplayNameValid && isUserNameValid && isVerificationCodeNotEmpy;
    if (!user)
      return;
    return /* @__PURE__ */ React__default.createElement("div", null, /* @__PURE__ */ React__default.createElement(UpgradeHeadlessVerification, {
      ...{ verificationCode, onChangePage, isRequestingVerificationCode, onRequestVerificationCode },
      onChangeVerificationCode: this.onVerificationCodeChange,
      validation: this.validation
    }), /* @__PURE__ */ React__default.createElement("hr", null), /* @__PURE__ */ React__default.createElement(FormGroup, null, /* @__PURE__ */ React__default.createElement("div", {
      className: styles.label
    }, t("UpgradeHeadlessAccountPage.UpgradeHeadlessAccountForm.country")), /* @__PURE__ */ React__default.createElement(InputGroup, {
      type: "text",
      value: countryName || user.country,
      disabled: true,
      className: styles.input
    })), !this.isUserNameDisabled() && /* @__PURE__ */ React__default.createElement(FormGroup, null, /* @__PURE__ */ React__default.createElement("div", {
      className: styles.label
    }, /* @__PURE__ */ React__default.createElement("div", null, t("UpgradeHeadlessAccountPage.UpgradeHeadlessAccountForm.userName")), /* @__PURE__ */ React__default.createElement("div", null, username.length, "/", usernameProps == null ? void 0 : usernameProps.maxLength)), /* @__PURE__ */ React__default.createElement(InputGroup, {
      className: styles.input,
      value: username,
      onChange: this.onChangeUsername,
      placeholder: t("UpgradeHeadlessAccountPage.UpgradeHeadlessAccountForm.placeholder.userName"),
      disabled: !!this.props.inputValidationManager.state.fetchError,
      popoverContent: /* @__PURE__ */ React__default.createElement(PasswordConstraint, {
        descriptions: InputValidationHelper.getValidationDescription(ValidateableInputField.enum.username, validations)
      }),
      maxLength: usernameProps == null ? void 0 : usernameProps.maxLength
    }), this.renderUserNameError(this.validation.get("username"), {
      min: usernameProps && usernameProps.minLength,
      max: usernameProps && usernameProps.maxLength
    })), !this.isDisplayNameDisabled() && /* @__PURE__ */ React__default.createElement(FormGroup, null, /* @__PURE__ */ React__default.createElement("div", {
      className: styles.label
    }, /* @__PURE__ */ React__default.createElement("div", null, `${t("UpgradeHeadlessAccountPage.UpgradeHeadlessAccountForm.displayName")} ${t("UpgradeHeadlessAccountPage.UpgradeHeadlessAccountForm.tos.optional")}`), /* @__PURE__ */ React__default.createElement("div", null, displayName.length, "/", displayNameProps == null ? void 0 : displayNameProps.maxLength)), /* @__PURE__ */ React__default.createElement(InputGroup, {
      className: styles.input,
      value: displayName,
      onChange: this.onChangeDisplayName,
      placeholder: t("UpgradeHeadlessAccountPage.UpgradeHeadlessAccountForm.placeholder.displayName"),
      popoverContent: /* @__PURE__ */ React__default.createElement(PasswordConstraint, {
        descriptions: InputValidationHelper.getValidationDescription(ValidateableInputField.enum.displayName, validations)
      }),
      maxLength: displayNameProps == null ? void 0 : displayNameProps.maxLength
    }), this.renderDisplayNameError(this.validation.get("displayName"), {
      min: displayNameProps && displayNameProps.minLength,
      max: displayNameProps && displayNameProps.maxLength
    })), /* @__PURE__ */ React__default.createElement(FormGroup, null, /* @__PURE__ */ React__default.createElement("div", {
      className: styles.label
    }, /* @__PURE__ */ React__default.createElement("div", null, t("UpgradeHeadlessAccountPage.UpgradeHeadlessAccountForm.password")), /* @__PURE__ */ React__default.createElement("div", null, password.length, "/", passwordProps == null ? void 0 : passwordProps.maxLength)), /* @__PURE__ */ React__default.createElement(InputGroupPassword, {
      className: styles.input,
      value: password,
      placeholder: t("UpgradeHeadlessAccountPage.UpgradeHeadlessAccountForm.placeholder.password"),
      togglePassword: true,
      onChange: this.onPasswordChange,
      popoverContent: /* @__PURE__ */ React__default.createElement(PasswordConstraint, {
        descriptions: InputValidationHelper.getValidationDescription(ValidateableInputField.enum.password, validations)
      }),
      maxLength: passwordProps == null ? void 0 : passwordProps.maxLength,
      hasStrengthMeter: !this.validation.get("password") && !!password
    }), this.renderPasswordError({
      min: passwordProps && passwordProps.minLength,
      max: passwordProps && passwordProps.maxLength
    })), /* @__PURE__ */ React__default.createElement(FormGroup, null, this.renderMinimumAgeCheckbox(), this.renderRequiredPolicies(), this.renderOptionalPolicies()), /* @__PURE__ */ React__default.createElement(Button, {
      loadingIndicator: "SPINNER",
      className: "btn btn-primary w-full uppercase",
      onClick: () => this.onClickContinue(),
      disabled: !isSubmitButtonEnabled || isUpgradingUser,
      isLoading: isUpgradingUser
    }, t("UpgradeHeadlessAccountPage.UpgradeHeadlessAccountForm.continue")));
  }
}
const REGISTRATION_EMAIL_STORAGE_KEY = "registration_email";
class UpgradeHeadlessAccountPage extends React__default.Component {
  constructor(props) {
    super(props);
    this.fetchValidations = async () => {
      this.inputValidationManager.fetchValidations(getCurrentLanguage()).catch((error) => {
        this.setErrorAlert(error);
      });
    };
    this.requestVerificationCode = async () => {
      const { email } = this.state;
      try {
        if (!email)
          return;
        await this.verificationManager.sendVerificationCode(email, VerificationCodeContext.enum.upgradeHeadlessAccount);
        this.redirectToOtherData();
      } catch (error) {
        const { requestVerificationCodeError } = this.verificationManager.state;
        if (requestVerificationCodeError)
          this.setErrorAlert(requestVerificationCodeError);
      }
    };
    this.setErrorAlert = async (error) => {
      if (await this.inputValidationManager.isInputValidationError(error)) {
        validationOutdatedModalEvent.openValidationOutdatedModal();
        this.setState({ alert: null });
        return;
      }
      const errorCode = ErrorHelper.extractServiceErrorCode(error);
      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");
              default:
                return /* @__PURE__ */ React__default.createElement(CommonError, {
                  error
                });
            }
          })()
        }
      });
    };
    this.upgradeHeadlessError = (error) => {
      this.setErrorAlert(error);
      window.scrollTo({ top: 0, behavior: "smooth" });
    };
    this.dismissAlert = () => {
      this.setState({ alert: null });
    };
    this.redirectToOtherData = () => {
      sessionStorage.setItem(REGISTRATION_EMAIL_STORAGE_KEY, this.state.email);
      this.setState({
        step: "otherData",
        alert: {
          type: AlertType.success,
          element: /* @__PURE__ */ React__default.createElement(Trans, {
            i18nKey: "ChangeEmailPage.verifyCodeForm.codeSent"
          }, "A verification code has been sent to your email")
        }
      });
    };
    this.onEmailChange = (event) => {
      const email = event.target.value.toString().toLocaleLowerCase();
      const { validations } = this.inputValidationManager.state;
      this.validation.set("email", InputValidationHelper.validateEmail(email, validations));
      this.setState({ email });
    };
    this.onFormSubmit = (event) => {
      event.preventDefault();
      const { email } = this.state;
      if (!this.validation.get("email") && email) {
        this.requestVerificationCode();
      }
    };
    this.onReload = () => {
      this.setState({ alert: null });
      this.fetchValidations();
    };
    this.renderHeadlessVerifyAccount = () => {
      const { email } = this.state;
      const { isRequestingVerificationCode } = this.verificationManager.state;
      const { validations } = this.inputValidationManager.state;
      return /* @__PURE__ */ React__default.createElement("form", {
        onSubmit: this.onFormSubmit,
        noValidate: true
      }, /* @__PURE__ */ React__default.createElement(FormGroup, null, /* @__PURE__ */ React__default.createElement("div", {
        className: styles.label
      }, /* @__PURE__ */ React__default.createElement(Trans, {
        i18nKey: "UpgradeHeadlessAccountPage.UpgradeHeadlessAccountPage.email"
      }, "Email")), /* @__PURE__ */ React__default.createElement(InputGroup, {
        type: "email",
        className: styles.input,
        value: email,
        placeholder: t("UpgradeHeadlessAccountPage.UpgradeHeadlessAccountPage.placeholder.email"),
        onChange: this.onEmailChange,
        popoverContent: /* @__PURE__ */ React__default.createElement(PasswordConstraint, {
          descriptions: InputValidationHelper.getValidationDescription(ValidateableInputField.enum.email, validations)
        })
      }), this.renderEmailError(this.validation.get("email"))), /* @__PURE__ */ React__default.createElement(Button, {
        loadingIndicator: "SPINNER",
        disabled: !!this.validation.get("email") || !email,
        className: "btn btn-primary w-full uppercase",
        onClick: this.requestVerificationCode,
        isLoading: isRequestingVerificationCode
      }, /* @__PURE__ */ React__default.createElement(Trans, {
        i18nKey: "UpgradeHeadlessAccountPage.UpgradeHeadlessAccountPage.continue"
      }, "CONTINUE")));
    };
    this.onChangePage = () => {
      this.setState({ step: "email", email: "" });
      this.resetSessionStorage();
    };
    this.onContinue = async ({
      password,
      displayName,
      username,
      reachMinimumAge,
      verificationCode,
      acceptedPolicyIds
    }) => {
      const { email } = this.state;
      const user = this.appState.getUser();
      const country = !!user && !!user.country ? user.country : "";
      try {
        await this.linkAccountsManager.upgradeHeadlessAccount({
          displayName,
          password,
          username,
          country,
          reachMinimumAge,
          emailAddress: email,
          code: verificationCode
        }, Env.IS_DISABLE_USERNAME);
        await this.bulkAcceptPolicies(acceptedPolicyIds);
        this.resetSessionStorage();
        const tokenResponse = await this.appState.userAppManager.refreshToken();
        if (tokenResponse) {
          this.appState.refreshSession(tokenResponse.access_token, tokenResponse.refresh_token);
        }
        await this.appState.refreshUser();
      } catch (error) {
        this.setErrorAlert(error);
      }
    };
    this.getEligibilities = (policyIds) => {
      const eligibilities = [];
      const { displayedPolicies } = this.state;
      for (const displayedPolicy of displayedPolicies) {
        eligibilities.push({
          policyId: displayedPolicy.policyId,
          policyVersionId: displayedPolicy.policyVersionId,
          localizedPolicyVersionId: displayedPolicy.localizedPolicyVersionId,
          isAccepted: policyIds.includes(displayedPolicy.policyId)
        });
      }
      return eligibilities;
    };
    this.bulkAcceptPolicies = async (policyIds) => {
      const user = this.appState.getUser();
      const acceptedPolicies = this.getEligibilities(policyIds);
      if (acceptedPolicies && user) {
        await this.legalManager.bulkAcceptPolicies(acceptedPolicies);
      }
    };
    this.state = {
      email: "",
      alert: null,
      displayedPolicies: [],
      step: "email"
    };
    this.appState = Ctx.getAppState();
    this.validation = new Validation();
    this.validation.listen(() => this.setState({}));
    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() {
    UIEvent.updateBackground(`url(${bgCommon})`);
    const user = this.appState.getUser();
    if (user) {
      this.legalManager.fetchPoliciesList(user.country).then(() => {
        const { policiesByCountry } = this.legalManager.state;
        this.setState({
          displayedPolicies: LegalHelper.convertPoliciesToDisplayedPolicies(policiesByCountry || [], Env.NAMESPACE)
        });
      }).catch((error) => {
        this.setErrorAlert(error);
      });
    }
    this.fetchValidations();
    const savedEmail = sessionStorage.getItem(REGISTRATION_EMAIL_STORAGE_KEY);
    this.setState({ email: savedEmail || "" });
    if (savedEmail) {
      this.setState({ step: "otherData" });
    }
  }
  componentWillUnmount() {
    UIEvent.updateBackground(null);
    this.resetSessionStorage();
  }
  renderEmailError(errorType) {
    if (!errorType)
      return null;
    const { validations } = this.inputValidationManager.state;
    const emailProps = InputValidationHelper.getValidationByKey(ValidateableInputField.enum.email, validations);
    const displayNameErrorMap = {
      [ValidateEmailErrorType.empty]: /* @__PURE__ */ React__default.createElement(Trans, {
        i18nKey: "UpgradeHeadlessAccountPage.UpgradeHeadlessAccountPage.emailError.empty"
      }, "You must enter a new email address"),
      [ValidateEmailErrorType.lessThanLengthLimit]: /* @__PURE__ */ React__default.createElement(Trans, {
        i18nKey: "UpgradeHeadlessAccountPage.UpgradeHeadlessAccountPage.emailError.lessThanLengthLimit"
      }, "Email must not less than ", { MIN_EMAIL_LENGTH: emailProps == null ? void 0 : emailProps.minLength }, " characters"),
      [ValidateEmailErrorType.exceedLengthLimit]: /* @__PURE__ */ React__default.createElement(Trans, {
        i18nKey: "UpgradeHeadlessAccountPage.UpgradeHeadlessAccountPage.emailError.ExceedLimit"
      }, "Email must not exceed ", { MAX_EMAIL_LENGTH: emailProps == null ? void 0 : emailProps.maxLength }, " characters"),
      [ValidateDisplayNameErrorType.invalidFormat]: /* @__PURE__ */ React__default.createElement(Trans, {
        i18nKey: "UpgradeHeadlessAccountPage.UpgradeHeadlessAccountPage.emailError.InvalidFormat"
      }, "Please provide a valid Email format"),
      [CommonValidationErrorType.containsForbiddenWords]: /* @__PURE__ */ React__default.createElement(Trans, {
        i18nKey: "UpgradeHeadlessAccountPage.UpgradeHeadlessAccountPage.emailError.containsForbiddenWords"
      }, "Email contains prohibited word or use blocked domain")
    };
    return /* @__PURE__ */ React__default.createElement(FormGroupError, null, displayNameErrorMap[errorType]);
  }
  resetSessionStorage() {
    sessionStorage.removeItem(REGISTRATION_EMAIL_STORAGE_KEY);
  }
  render() {
    const { displayedPolicies, alert: alert2, step, email } = this.state;
    const user = this.appState.getUser();
    const { isRequestingVerificationCode, isVerifying } = this.verificationManager.state;
    const { isUpgradingHeadlessAccount } = this.linkAccountsManager.state;
    const { isAccepting } = this.legalManager.state;
    const { isFetching, fetchError, validations } = this.inputValidationManager.state;
    const publisherName = t("Common.publisherName");
    return /* @__PURE__ */ React__default.createElement("div", {
      className: styles.headlessAccountPage
    }, /* @__PURE__ */ React__default.createElement(LanguageSelector, {
      className: "fixed top-0 right-0 mt-8 mr-8"
    }), /* @__PURE__ */ React__default.createElement("div", {
      className: styles.headlessAccountPageContainer
    }, /* @__PURE__ */ React__default.createElement(HeaderLogoContainer, null), /* @__PURE__ */ React__default.createElement("div", {
      className: styles.headlessAccountPageContainerForm
    }, /* @__PURE__ */ React__default.createElement("div", {
      className: styles.contentWrapper
    }, /* @__PURE__ */ React__default.createElement("div", {
      className: styles.title
    }, step === "email" && /* @__PURE__ */ React__default.createElement(Trans, {
      i18nKey: "UpgradeHeadlessAccountPage.UpgradeHeadlessAccountPage.title"
    }, "Upgrade to Full Account"), step === "otherData" && /* @__PURE__ */ React__default.createElement(Trans, {
      i18nKey: "UpgradeHeadlessAccountPage.UpgradeHeadlessAccountForm.title"
    }, "Finish Account Setup")), /* @__PURE__ */ React__default.createElement("div", {
      className: styles.description
    }, step === "email" && /* @__PURE__ */ React__default.createElement(Trans, {
      i18nKey: "UpgradeHeadlessAccountPage.UpgradeHeadlessAccountPage.description"
    }, "Enter your email address below to start creating your ", { publisherName }, " account"), step === "otherData" && /* @__PURE__ */ React__default.createElement(Trans, {
      i18nKey: "UpgradeHeadlessAccountPage.UpgradeHeadlessAccountForm.description"
    }, "Enter the verification code we\u2019ve sent to your email at ", /* @__PURE__ */ React__default.createElement("strong", null, { email }), ", and complete the form below"))), /* @__PURE__ */ React__default.createElement("div", {
      className: styles.formWrapper
    }, !!alert2 && /* @__PURE__ */ React__default.createElement("div", {
      className: styles.alert
    }, /* @__PURE__ */ React__default.createElement(Alert, {
      type: alert2.type,
      onDismiss: this.dismissAlert
    }, alert2.element), !!fetchError && /* @__PURE__ */ React__default.createElement(Button, {
      className: "btn btn-primary mt-4 w-full",
      onClick: this.onReload
    }, /* @__PURE__ */ React__default.createElement(Trans, {
      i18nKey: "Common.reload"
    }, "Reload"))), step === "email" && this.renderHeadlessVerifyAccount(), step === "otherData" && /* @__PURE__ */ React__default.createElement("div", null, validations.length <= 0 && isFetching && /* @__PURE__ */ React__default.createElement(Loading, {
      className: LoadingSize.medium
    }), validations.length > 0 && !fetchError && user && /* @__PURE__ */ React__default.createElement(UpgradeHeadlessAccountForm, {
      onChangePage: this.onChangePage,
      onContinue: this.onContinue,
      onRequestVerificationCode: this.requestVerificationCode,
      policies: displayedPolicies,
      isUpgradingUser: isUpgradingHeadlessAccount || isAccepting,
      inputValidationManager: this.inputValidationManager,
      ...{ isRequestingVerificationCode, user, email, isVerifying }
    })))), /* @__PURE__ */ React__default.createElement("div", {
      className: styles.backContainer
    }, /* @__PURE__ */ React__default.createElement("button", {
      onClick: () => {
        this.resetSessionStorage();
        this.appState.logout(LoginPath.Login.link);
      }
    }, /* @__PURE__ */ React__default.createElement(Trans, {
      i18nKey: "UpgradeHeadlessAccountPage.UpgradeHeadlessAccountPage.logout"
    }, "Back to Login"))), /* @__PURE__ */ React__default.createElement(InputValidationOutdatedModal, null)));
  }
}
export { UpgradeHeadlessAccountPage as default };
