import { x as getCurrentLanguage, V as VerificationCodeContext, y as validationOutdatedModalEvent, E as ErrorHelper, h as AlertType, i as CommonError, T as Trans, K as Env, a as Ctx, k as UIEvent, l as bgCommon, aU as LegalHelper, t, j as Alert, f as Button, L as Loading, w as LoadingSize, v as LoginPath, I as InputValidationOutdatedModal } from "./index.js";
import { L as LanguageSelector, H as HeaderLogoContainer } from "./LinkPlatformAccountPage.js";
import React__default from "react";
import { E as EmailVerificationForm, U as UpgradeHeadlessAccountForm } from "./EmailVerificationForm.js";
import "./validator.js";
import "./dateFns.js";
import "./reactPlayer.js";
import "react-router-dom";
import "./reactSlick.js";
import "./Tabs.js";
import "./CommonError.js";
import "./starBgGradient.js";
import "./CommonError2.js";
import "./InputPassword.js";
import "./Checkbox.js";
const logoContainer = "logoContainer _logoContainer_5a919";
const headlessAccountPage = "headlessAccountPage _headlessAccountPage_a873b";
const headlessAccountPageContainer = "headlessAccountPageContainer _headlessAccountPageContainer_c57f8";
const headlessAccountPageContainerForm = "headlessAccountPageContainerForm _headlessAccountPageContainerForm_eed6b";
const contentWrapper = "contentWrapper _contentWrapper_fc1b2";
const formWrapper = "formWrapper _formWrapper_f06a6";
const alert = "alert _alert_ae490";
const passwordValidation = "passwordValidation _passwordValidation_37aeb";
const flexCol = "flexCol _flexCol_c3b0e";
const passwordMismatch = "passwordMismatch _passwordMismatch_e1817";
const title = "title _title_95dc9";
const description = "description _description_380a1";
const resendCode = "resendCode _resendCode_a33c1";
const tabs = "tabs _tabs_7ea05";
const tab = "tab _tab_ba66f";
const active = "active _active_ea7b8";
const label = "label _label_9c194";
const input = "input _input_7d10b";
const select = "select _select_e3757";
const datePicker = "datePicker _datePicker_283fa";
const agreementList = "agreementList _agreementList_4d5e8";
const agreementItem = "agreementItem _agreementItem_4b481";
const text = "text _text_0d91a";
const optional = "optional _optional_fe247";
const changePage = "changePage _changePage_13e94";
const backContainer = "backContainer _backContainer_fa637";
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
};
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 (email = this.state.email) => {
      try {
        if (!email)
          return;
        await this.verificationManager.sendVerificationCode(email, VerificationCodeContext.enum.upgradeHeadlessAccount);
        this.setState({ email }, 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.onReload = () => {
      this.setState({ alert: null });
      this.fetchValidations();
    };
    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.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();
  }
  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" && /* @__PURE__ */ React__default.createElement(EmailVerificationForm, {
      styles,
      onRequestVerificationCode: this.requestVerificationCode,
      isRequesting: isRequestingVerificationCode
    }), 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, isVerifying, styles }
    })))), /* @__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 };
