import * as React from "react";
import React__default from "react";
import { T as Trans, h as AlertType, i as CommonError, a as Ctx, t, j as Alert, f as Button, aU as LegalHelper, K as Env, x as getCurrentLanguage, V as VerificationCodeContext, y as validationOutdatedModalEvent, E as ErrorHelper, L as Loading, w as LoadingSize, N as ButtonStyle, a3 as Dialog, a4 as DialogBody, a5 as DialogFooter, g as AccPath, aw as UserHelper, ba as LoginIcon, b4 as ProfileImage, al as IamHelper, F as FeUtils, k as UIEvent, l as bgCommon, D as DesktopChecker } from "./index.js";
import { L as LanguageSelector, H as HeaderLogoContainer } from "./LinkPlatformAccountPage.js";
import { c as classNames } from "./reactSlick.js";
import { O as OtpInput } from "./index2.js";
import { a as TabStyles, T as Tabs } from "./Tabs.js";
import { E as EmailVerificationForm, U as UpgradeHeadlessAccountForm } from "./EmailVerificationForm.js";
import { a as Radio } from "./Radio.js";
import { W as WarningIcon } from "./WarningIcon.js";
import "./validator.js";
import "./dateFns.js";
import "./reactPlayer.js";
import "react-router-dom";
import "./CommonError.js";
import "./starBgGradient.js";
import "./CommonError2.js";
import "./InputPassword.js";
import "./Checkbox.js";
const oneTimeLinkAccountPage = "oneTimeLinkAccountPage _oneTimeLinkAccountPage_47f42";
const languageSelector = "languageSelector _languageSelector_b914e";
const container = "container _container_8d365";
const pickProgression = "pickProgression _pickProgression_1b39f";
const form = "form _form_c149b";
const title = "title _title_a54f2";
const description = "description _description_5ca5b";
const label = "label _label_8440c";
const input = "input _input_4f7e0";
const resendCode = "resendCode _resendCode_99fc7";
const agreementList = "agreementList _agreementList_95794";
const agreementItem = "agreementItem _agreementItem_f0390";
const text = "text _text_6a3ed";
const optional = "optional _optional_f5aba";
const sectionTitle = "sectionTitle _sectionTitle_71188";
const warningTip = "warningTip _warningTip_9aa5a";
const warningIcon = "warningIcon _warningIcon_5973e";
const accountDetails = "accountDetails _accountDetails_f87f0";
const accountDetailsPlatformName = "accountDetailsPlatformName _accountDetailsPlatformName_f242a";
const accountDetailsEmail = "accountDetailsEmail _accountDetailsEmail_71d70";
const progressionTable = "progressionTable _progressionTable_94199";
const noSession = "noSession _noSession_32e77";
const loginIcon = "loginIcon _loginIcon_c4515";
const withSession = "withSession _withSession_87376";
const withSessionAvatar = "withSessionAvatar _withSessionAvatar_9e881";
const withSessionUserName = "withSessionUserName _withSessionUserName_b2811";
const withSessionEmail = "withSessionEmail _withSessionEmail_dfc42";
const desktop = "desktop _desktop_d0b1c";
var styles = {
  oneTimeLinkAccountPage,
  languageSelector,
  container,
  pickProgression,
  form,
  title,
  description,
  label,
  input,
  resendCode,
  agreementList,
  agreementItem,
  text,
  optional,
  sectionTitle,
  warningTip,
  warningIcon,
  accountDetails,
  accountDetailsPlatformName,
  accountDetailsEmail,
  progressionTable,
  noSession,
  loginIcon,
  withSession,
  withSessionAvatar,
  withSessionUserName,
  withSessionEmail,
  desktop
};
const ONE_TIME_CODE_LENGTH = 8;
const EXPIRED_ONE_TIME_ERROR_CODE = 10205;
const EXPIRED_CODE_MESSAGE = "code is expired";
class OneTimeCodeForm extends React.Component {
  constructor(props) {
    super(props);
    this.onCodeChange = (value) => {
      this.setState({ code: value });
    };
    this.dismissAlert = () => {
      this.setState({ alert: null });
    };
    this.getDisplayedAlert = (isInvalid, isExpired) => {
      if (isExpired)
        return /* @__PURE__ */ React.createElement(Trans, {
          i18nKey: "LinkAccountWithOneTimeCodePage.oneTimeCodeForm.error.expired"
        }, "Sorry, the code you entered has expired. Please try again.");
      if (isInvalid)
        return /* @__PURE__ */ React.createElement(Trans, {
          i18nKey: "LinkAccountWithOneTimeCodePage.oneTimeCodeForm.error.invalid"
        }, "Sorry, the code you entered is invalid. Please try again.");
      return null;
    };
    this.onSubmit = async () => {
      const oauthApi = this.appState.getSdk().IAM.OAuth();
      const { isSubmitting, code } = this.state;
      try {
        if (isSubmitting)
          return;
        this.setState({ isSubmitting: true });
        const result = await oauthApi.validateOneTimeLinkCode({ oneTimeLinkCode: code });
        if (result.error)
          throw result.error;
        const { valid, expired: isExpired } = result.response.data;
        const isInvalid = !valid;
        if (isInvalid || isExpired) {
          this.setState({
            isSubmitting: false,
            alert: {
              type: AlertType.danger,
              element: this.getDisplayedAlert(isInvalid, isExpired)
            }
          });
          return;
        }
        this.props.onContinue(this.state.code);
      } catch (error) {
        console.error(error);
        this.setState({
          isSubmitting: false,
          alert: {
            type: AlertType.danger,
            element: /* @__PURE__ */ React.createElement(CommonError, {
              error
            })
          }
        });
      }
    };
    this.state = {
      code: "",
      isSubmitting: false,
      alert: null
    };
    this.appState = Ctx.getAppState();
  }
  render() {
    const { code, isSubmitting, alert } = this.state;
    const publisherName = t("Common.publisherName");
    return /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement("div", {
      className: "text-center"
    }, /* @__PURE__ */ React.createElement("p", {
      className: styles.title
    }, /* @__PURE__ */ React.createElement(Trans, {
      i18nKey: "LinkAccountWithOneTimeCodePage.title"
    }, "Link to an ", { publisherName }, " Account")), /* @__PURE__ */ React.createElement("p", {
      className: styles.description
    }, /* @__PURE__ */ React.createElement(Trans, {
      i18nKey: "LinkAccountWithOneTimeCodePage.oneTimeCodeForm.desc"
    }, "Enter the code on your device to continue.")), !!alert && /* @__PURE__ */ React.createElement(Alert, {
      type: alert.type,
      onDismiss: this.dismissAlert,
      className: "mt-5 text-left"
    }, alert.element)), /* @__PURE__ */ React.createElement(OtpInput, {
      value: code,
      onChange: this.onCodeChange,
      numInputs: ONE_TIME_CODE_LENGTH,
      className: "otpInput",
      containerStyle: "otpInputContainer my-5",
      focusStyle: "otpInput__focus",
      shouldAutoFocus: true,
      isDisabled: isSubmitting
    }), /* @__PURE__ */ React.createElement(Button, {
      loadingIndicator: "SPINNER",
      className: "btn btn-primary w-full py-2 px-0",
      onClick: this.onSubmit,
      disabled: code.length < ONE_TIME_CODE_LENGTH,
      isLoading: isSubmitting
    }, t("common.continue")));
  }
}
class SuccessMessage extends React.Component {
  constructor(props) {
    super(props);
  }
  render() {
    const { isUpgradeToFull, platformName } = this.props;
    const publisherName = t("Common.publisherName");
    return /* @__PURE__ */ React.createElement("div", {
      className: "text-center"
    }, /* @__PURE__ */ React.createElement("p", {
      className: styles.title
    }, /* @__PURE__ */ React.createElement(Trans, {
      i18nKey: "LinkAccountWithOneTimeCodePage.success.title"
    }, "Success!")), /* @__PURE__ */ React.createElement("p", {
      className: classNames(styles.description, "mb-4")
    }, isUpgradeToFull && /* @__PURE__ */ React.createElement(Trans, {
      i18nKey: "LinkAccountWithOneTimeCodePage.success.isUpgrade.desc"
    }, "You have upgraded to a full ", { publisherName }, " account."), !isUpgradeToFull && /* @__PURE__ */ React.createElement(Trans, {
      i18nKey: "LinkAccountWithOneTimeCodePage.success.isLink.desc"
    }, "Your ", { platformName }, " account has been linked with your full ", { publisherName }, " account.")), /* @__PURE__ */ React.createElement("p", {
      className: styles.description
    }, /* @__PURE__ */ React.createElement(Trans, {
      i18nKey: "LinkAccountWithOneTimeCodePage.success.desc2"
    }, "The screen on your device will refresh shortly. You can close this window.")));
  }
}
class RestartMessage extends React.Component {
  constructor(props) {
    super(props);
  }
  render() {
    const { onRestart } = this.props;
    return /* @__PURE__ */ React.createElement(Button, {
      loadingIndicator: "SPINNER",
      className: "btn btn-primary mt-6 w-full py-2 px-0",
      onClick: onRestart
    }, /* @__PURE__ */ React.createElement(Trans, {
      i18nKey: "LinkAccountWithOneTimeCodePage.selectLinkMode.restart.button"
    }, "Input Verification Code"));
  }
}
const CommonTitle = () => {
  const publisherName = t("Common.publisherName");
  return /* @__PURE__ */ React__default.createElement("div", {
    className: "text-center"
  }, /* @__PURE__ */ React__default.createElement("p", {
    className: styles.title
  }, /* @__PURE__ */ React__default.createElement(Trans, {
    i18nKey: "LinkAccountWithOneTimeCodePage.title"
  }, "Link to an ", { publisherName }, " Account")), /* @__PURE__ */ React__default.createElement("p", {
    className: styles.description
  }, /* @__PURE__ */ React__default.createElement(Trans, {
    i18nKey: "LinkAccountWithOneTimeCodePage.selectLinkMode.desc"
  }, "Link an existing ", { publisherName }, " account or upgrade to a full account to save your game progress.")));
};
class UpgradeToFullAccount extends React.Component {
  constructor(props) {
    super(props);
    this.fetchPolicies = () => {
      const user = this.appState.getUser();
      if (!user)
        return;
      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 = async () => {
      this.inputValidationManager.fetchValidations(getCurrentLanguage()).catch((error) => {
        this.setErrorAlert(error);
      });
    };
    this.redirectToOtherData = () => {
      this.setState({
        step: "otherData",
        alert: {
          type: AlertType.success,
          element: t("ChangeEmailPage.verifyCodeForm.codeSent")
        }
      });
      this.props.onHideTitle();
    };
    this.requestVerificationCode = async (email = this.state.email) => {
      const { step, isRequestingVerificationCode, alreadyRefreshToken } = this.state;
      const { oneTimeLinkCode } = this.props;
      const isInEmailStep = step === "email";
      const oauthApi = this.appState.getSdk().IAM.OAuth();
      try {
        if (!email || isRequestingVerificationCode)
          return;
        this.setState({ isRequestingVerificationCode: true });
        this.verificationManager.setState({ requestVerificationCodeError: null });
        if (isInEmailStep && !alreadyRefreshToken) {
          const tokenExhangeResult = await oauthApi.exchangeTokenByOneTimeLinkCode({ oneTimeLinkCode, client_id: Env.CLIENT_ID });
          if (tokenExhangeResult.error)
            throw tokenExhangeResult.error;
          const { access_token: accessToken, refresh_token: refreshToken } = tokenExhangeResult.response.data;
          this.setState({ alreadyRefreshToken: true });
          this.appState.refreshSession(accessToken, refreshToken);
        }
        await this.verificationManager.sendVerificationCode(email, VerificationCodeContext.enum.upgradeHeadlessAccount);
        await this.appState.refreshUser();
        if (isInEmailStep) {
          this.fetchPolicies();
        }
        this.setState({ email, isRequestingVerificationCode: false }, this.redirectToOtherData);
      } catch (error) {
        const { requestVerificationCodeError } = this.verificationManager.state;
        this.setState({ isRequestingVerificationCode: false });
        if (requestVerificationCodeError) {
          this.setErrorAlert(requestVerificationCodeError);
          return;
        }
        console.error(error);
        this.setErrorAlert(error);
      }
    };
    this.setErrorAlert = async (error) => {
      var _a;
      if (await this.inputValidationManager.isInputValidationError(error)) {
        validationOutdatedModalEvent.openValidationOutdatedModal();
        this.setState({ alert: null });
        return;
      }
      const { oneTimeLinkCode, onHideTitle } = this.props;
      const errorDescription = ErrorHelper.isAxiosError(error) ? (_a = error.response) == null ? void 0 : _a.data.error_description : "";
      const isCodeExpired = errorDescription == null ? void 0 : errorDescription.includes(EXPIRED_CODE_MESSAGE);
      const errorCode = ErrorHelper.extractServiceErrorCode(error);
      if (isCodeExpired) {
        onHideTitle();
        this.setState({
          step: "shouldRestart",
          alert: {
            type: AlertType.danger,
            element: oneTimeLinkCode.length === ONE_TIME_CODE_LENGTH ? t("LinkAccountWithOneTimeCodePage.error.expired") : t("LinkAccountWithOneTimeCodePage.error.invalid")
          }
        });
        return;
      }
      this.setState({
        alert: {
          type: AlertType.danger,
          element: (() => {
            switch (errorCode) {
              case 10130:
                return t("UpdateUser.error.updateErrorUnderage");
              default:
                return /* @__PURE__ */ React.createElement(CommonError, {
                  error
                });
            }
          })()
        }
      });
    };
    this.dismissAlert = () => {
      this.setState({ alert: null });
    };
    this.onReload = () => {
      this.setState({ alert: null });
      this.fetchValidations();
    };
    this.onGoBackToEmail = () => {
      this.setState({ step: "email", email: "" });
      this.props.onShowTitle();
    };
    this.onCompleteProcess = async ({
      password,
      displayName,
      username,
      reachMinimumAge,
      verificationCode,
      acceptedPolicyIds
    }) => {
      const { email } = this.state;
      const user = this.appState.getUser();
      const country = (user == null ? void 0 : user.country) || "";
      try {
        await this.linkAccountsManager.upgradeHeadlessAccount({
          displayName,
          password,
          username,
          country,
          reachMinimumAge,
          emailAddress: email,
          code: verificationCode
        }, Env.IS_DISABLE_USERNAME);
        await this.bulkAcceptPolicies(acceptedPolicyIds);
        const tokenResponse = await this.appState.userAppManager.refreshToken();
        if (tokenResponse) {
          this.appState.refreshSession(tokenResponse.access_token, tokenResponse.refresh_token);
        }
        this.appState.refreshUser();
        this.setState({ alert: null, step: "success" });
      } catch (error) {
        this.setErrorAlert(error);
      }
    };
    this.getEligibilities = (policyIds) => {
      const eligibilities = [];
      const { displayedPolicies } = this.state;
      for (const displayedPolicy of displayedPolicies) {
        const { policyId, policyVersionId, localizedPolicyVersionId } = displayedPolicy;
        eligibilities.push({
          policyId,
          policyVersionId,
          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",
      isRequestingVerificationCode: false,
      alreadyRefreshToken: false
    };
    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() {
    this.fetchValidations();
  }
  render() {
    const { displayedPolicies, alert, step, email, isRequestingVerificationCode } = this.state;
    const { isFetchingUser, user } = this.appState.getUserManager().state;
    const { isVerifying } = this.verificationManager.state;
    const { isUpgradingHeadlessAccount } = this.linkAccountsManager.state;
    const { isAccepting } = this.legalManager.state;
    const { isFetching, fetchError, validations } = this.inputValidationManager.state;
    const shouldRestart = step === "shouldRestart";
    return /* @__PURE__ */ React.createElement(React.Fragment, null, step === "otherData" && /* @__PURE__ */ React.createElement("div", {
      className: "mb-6 text-center"
    }, /* @__PURE__ */ React.createElement("p", {
      className: styles.title
    }, /* @__PURE__ */ React.createElement(Trans, {
      i18nKey: "LinkAccountWithOneTimeCodePage.selectLinkMode.tab.upgradeToFull"
    }, "Upgrade to Full Account")), /* @__PURE__ */ React.createElement("p", {
      className: styles.description
    }, /* @__PURE__ */ React.createElement(Trans, {
      i18nKey: "UpgradeHeadlessAccountPage.UpgradeHeadlessAccountForm.description"
    }, "Enter the verification code we\u2019ve sent to your email at ", /* @__PURE__ */ React.createElement("strong", null, { email }), ", and complete the form below"))), shouldRestart && /* @__PURE__ */ React.createElement(CommonTitle, null), !!alert && /* @__PURE__ */ React.createElement("div", {
      className: classNames("mb-4", shouldRestart ? "mt-5" : "mt-[-8px]")
    }, /* @__PURE__ */ React.createElement(Alert, {
      type: alert.type,
      onDismiss: this.dismissAlert
    }, alert.element), !!fetchError && /* @__PURE__ */ React.createElement(Button, {
      className: "btn btn-primary mt-4 w-full",
      onClick: this.onReload
    }, t("Common.reload"))), step === "email" && /* @__PURE__ */ React.createElement(EmailVerificationForm, {
      styles,
      onRequestVerificationCode: this.requestVerificationCode,
      isRequesting: isRequestingVerificationCode
    }), step === "otherData" && /* @__PURE__ */ React.createElement(React.Fragment, null, validations.length <= 0 && isFetching && /* @__PURE__ */ React.createElement(Loading, {
      className: LoadingSize.medium
    }), validations.length > 0 && !fetchError && user && /* @__PURE__ */ React.createElement(UpgradeHeadlessAccountForm, {
      onChangePage: this.onGoBackToEmail,
      onContinue: this.onCompleteProcess,
      onRequestVerificationCode: this.requestVerificationCode,
      policies: displayedPolicies,
      isUpgradingUser: isUpgradingHeadlessAccount || isAccepting || isFetchingUser,
      inputValidationManager: this.inputValidationManager,
      ...{ isRequestingVerificationCode, user, email, isVerifying, styles }
    }), /* @__PURE__ */ React.createElement(Button, {
      buttonStyle: ButtonStyle.NONE,
      onClick: this.onGoBackToEmail,
      className: "absolute bottom-0 left-1/2 mb-24 -translate-x-2/4"
    }, t("common.back"))), step === "success" && /* @__PURE__ */ React.createElement(SuccessMessage, {
      isUpgradeToFull: true
    }), step === "shouldRestart" && /* @__PURE__ */ React.createElement(RestartMessage, {
      onRestart: this.props.onRestart
    }));
  }
}
class LinkAccountDialog extends React__default.Component {
  constructor(props) {
    super(props);
  }
  render() {
    const { onConfirm, onCancel, isConfirming } = this.props;
    return /* @__PURE__ */ React__default.createElement(Dialog, {
      title: /* @__PURE__ */ React__default.createElement("span", {
        className: "font-body"
      }, /* @__PURE__ */ React__default.createElement(Trans, {
        i18nKey: "LinkAccountWithOneTimeCodePage.pickProgression.modal.title"
      }, "Link an Account")),
      isOpen: true
    }, /* @__PURE__ */ React__default.createElement(DialogBody, null, /* @__PURE__ */ React__default.createElement("p", {
      className: "text-sm text-[color:rgb(var(--od-rgb-text),0.65)]"
    }, /* @__PURE__ */ React__default.createElement(Trans, {
      i18nKey: "LinkAccountWithOneTimeCodePage.pickProgression.modal.message"
    }, "Are you sure want to continue to link your account?"))), /* @__PURE__ */ React__default.createElement(DialogFooter, null, /* @__PURE__ */ React__default.createElement("div", {
      className: "flex justify-end"
    }, /* @__PURE__ */ React__default.createElement(Button, {
      className: "btn btn-ghost mr-2 uppercase",
      buttonStyle: ButtonStyle.NONE,
      onClick: onCancel
    }, t("Common.cancel")), /* @__PURE__ */ React__default.createElement(Button, {
      className: "btn btn-primary uppercase",
      isLoading: isConfirming,
      disabled: isConfirming,
      onClick: onConfirm
    }, t("common.yes")))));
  }
}
class AccountDetails extends React.Component {
  render() {
    const { platformName, userName, email } = this.props;
    return /* @__PURE__ */ React.createElement("div", {
      className: styles.accountDetails
    }, /* @__PURE__ */ React.createElement("p", {
      className: styles.accountDetailsPlatformName
    }, /* @__PURE__ */ React.createElement(Trans, {
      i18nKey: "LinkAccountWithOneTimeCodePage.pickProgression.accountDetails.name"
    }, { platformName }, " Account")), /* @__PURE__ */ React.createElement("p", {
      className: "text-2sm"
    }, userName), /* @__PURE__ */ React.createElement("p", {
      className: classNames(styles.accountDetailsEmail, !email && "italic")
    }, email || /* @__PURE__ */ React.createElement(Trans, {
      i18nKey: "LinkAccountWithOneTimeCodePage.pickProgression.accountDetails.noEmail"
    }, "no email registered")));
  }
}
class PickProgression extends React.Component {
  constructor(props) {
    super(props);
    this.toggleConfirmDialog = () => {
      this.setState((prevState) => ({ isConfirmDialogOpen: !prevState.isConfirmDialogOpen }));
    };
    this.chooseGame = (game) => {
      this.setState((prevState) => {
        const { chosenGames } = prevState;
        chosenGames.set(game, true);
        return { chosenGames };
      });
    };
    this.unchooseGame = (game) => {
      this.setState((prevState) => {
        const { chosenGames } = prevState;
        chosenGames.set(game, false);
        return { chosenGames };
      });
    };
    this.onConfirm = async () => {
      const userApi = this.appState.getSdk().IAM.User();
      const { isConfirming, chosenGames } = this.state;
      const { oneTimeLinkCode, onError, onSuccess } = this.props;
      try {
        if (isConfirming)
          return;
        this.setState({ isConfirming: true });
        const result = await userApi.linkWithProgression({
          oneTimeLinkCode,
          chosenNamespaces: [...chosenGames.keys()].filter((game) => chosenGames.get(game))
        });
        if (result.error)
          throw result.error;
        this.setState({ isConfirmDialogOpen: false, isConfirming: false });
        onSuccess();
      } catch (error) {
        this.setState({ isConfirming: false });
        console.error(error);
        onError(error);
      }
    };
    this.onLinkWithAnotherAccount = () => {
      const { createLoginURL } = this.appState.getSdk().IAM.UserAuthorization();
      const { oneTimeLinkCode } = this.props;
      const returnPath = AccPath.LinkAccountWithOneTimeCode.makePath(void 0, { oneTimeLinkCode });
      const loginURL = createLoginURL(returnPath, void 0, oneTimeLinkCode);
      window.location.replace(loginURL);
    };
    this.renderAccountDetailsSection = () => {
      const { platformName, headlessAccount, currentAccount } = this.props;
      return /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement("p", {
        className: styles.sectionTitle
      }, /* @__PURE__ */ React.createElement(Trans, {
        i18nKey: "LinkAccountWithOneTimeCodePage.pickProgression.accountDetails.title"
      }, "Account Details")), /* @__PURE__ */ React.createElement("div", {
        className: "xs:grid-cols-2 mb-6 grid gap-6"
      }, /* @__PURE__ */ React.createElement(AccountDetails, {
        platformName,
        userName: (headlessAccount == null ? void 0 : headlessAccount.userName) || (headlessAccount == null ? void 0 : headlessAccount.displayName) || ""
      }), /* @__PURE__ */ React.createElement(AccountDetails, {
        platformName: t("Common.companyName"),
        userName: (currentAccount == null ? void 0 : currentAccount.userName) || (currentAccount == null ? void 0 : currentAccount.displayName) || "",
        email: (currentAccount == null ? void 0 : currentAccount.email) || ""
      })), /* @__PURE__ */ React.createElement("hr", null));
    };
    this.renderGamesTable = () => {
      const { chosenGames } = this.state;
      const { currentAccount, headlessAccount } = this.props;
      const linkedGames = ((headlessAccount == null ? void 0 : headlessAccount.linkedGames) || []).concat((currentAccount == null ? void 0 : currentAccount.linkedGames) || []);
      return /* @__PURE__ */ React.createElement("div", {
        className: styles.progressionTable
      }, /* @__PURE__ */ React.createElement("table", null, /* @__PURE__ */ React.createElement("thead", null, /* @__PURE__ */ React.createElement("tr", null, /* @__PURE__ */ React.createElement("th", null, /* @__PURE__ */ React.createElement(Trans, {
        i18nKey: "LinkAccountWithOneTimeCodePage.pickProgression.table.game"
      }, "Game")), /* @__PURE__ */ React.createElement("th", null, /* @__PURE__ */ React.createElement(Trans, {
        i18nKey: "LinkAccountWithOneTimeCodePage.pickProgression.table.migrate"
      }, "Migrate to Full Account?")))), /* @__PURE__ */ React.createElement("tbody", null, [...new Set(linkedGames)].map((game) => {
        const isGameChosen = chosenGames.get(game);
        return /* @__PURE__ */ React.createElement("tr", {
          key: game
        }, /* @__PURE__ */ React.createElement("td", null, game), /* @__PURE__ */ React.createElement("td", {
          className: "flex items-center"
        }, /* @__PURE__ */ React.createElement(Radio, {
          label: t("common.yes"),
          className: "mr-6",
          checked: isGameChosen,
          onClick: () => this.chooseGame(game)
        }), /* @__PURE__ */ React.createElement(Radio, {
          label: t("common.no"),
          checked: isGameChosen === false,
          onClick: () => this.unchooseGame(game)
        })));
      }))));
    };
    this.renderGamesSection = () => {
      const { platformName } = this.props;
      const publisherName = t("Common.publisherName");
      return /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement("p", {
        className: styles.sectionTitle
      }, /* @__PURE__ */ React.createElement(Trans, {
        i18nKey: "LinkAccountWithOneTimeCodePage.pickProgression.games.title"
      }, { platformName }, " Games")), /* @__PURE__ */ React.createElement("p", {
        className: classNames(styles.description, "!mt-1 mb-6")
      }, /* @__PURE__ */ React.createElement(Trans, {
        i18nKey: "LinkAccountWithOneTimeCodePage.pickProgression.games.desc"
      }, "You have game progression data in your ", { platformName }, " account for the following games. For each game, please select whether or not you'd like to migrate your progress to your ", { publisherName }, " account.")), /* @__PURE__ */ React.createElement("div", {
        className: styles.warningTip
      }, /* @__PURE__ */ React.createElement(WarningIcon, {
        defaultColor: false,
        className: styles.warningIcon
      }), /* @__PURE__ */ React.createElement("p", null, /* @__PURE__ */ React.createElement(Trans, {
        i18nKey: "LinkAccountWithOneTimeCodePage.pickProgression.games.warning"
      }, "If you choose to migrate your progress, your ", { publisherName }, " account progress will be replaced with your", " ", { platformName }, " progress for that game."))), this.renderGamesTable(), /* @__PURE__ */ React.createElement("hr", null));
    };
    this.renderConfirmButton = () => {
      const { chosenGames } = this.state;
      const { currentAccount, headlessAccount } = this.props;
      const linkedGames = [...new Set(((headlessAccount == null ? void 0 : headlessAccount.linkedGames) || []).concat((currentAccount == null ? void 0 : currentAccount.linkedGames) || []))];
      const publisherName = t("Common.publisherName");
      const areAllGamesMarked = chosenGames.size === linkedGames.length;
      return /* @__PURE__ */ React.createElement("div", {
        className: "text-center"
      }, /* @__PURE__ */ React.createElement(Button, {
        loadingIndicator: "SPINNER",
        className: "btn btn-primary mx-auto mb-6 w-60 py-2",
        onClick: this.toggleConfirmDialog,
        disabled: !areAllGamesMarked
      }, t("Common.confirm")), /* @__PURE__ */ React.createElement("p", {
        className: styles.description
      }, /* @__PURE__ */ React.createElement(Trans, {
        i18nKey: "LinkAccountWithOneTimeCodePage.pickProgression.linkAnother.question"
      }, "Don't want to link to this existing account?")), /* @__PURE__ */ React.createElement(Button, {
        className: "text-2sm text-primary-60 mx-auto py-2",
        buttonStyle: ButtonStyle.NONE,
        onClick: this.onLinkWithAnotherAccount
      }, /* @__PURE__ */ React.createElement(Trans, {
        i18nKey: "LinkAccountWithOneTimeCodePage.pickProgression.linkAnother.action"
      }, "Link with another ", { publisherName }, " account")));
    };
    this.state = {
      chosenGames: /* @__PURE__ */ new Map(),
      isConfirmDialogOpen: false,
      isConfirming: false
    };
    this.appState = Ctx.getAppState();
  }
  render() {
    const { isConfirmDialogOpen, isConfirming } = this.state;
    return /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement("div", {
      className: styles.pickProgression
    }, this.renderAccountDetailsSection(), this.renderGamesSection(), this.renderConfirmButton()), isConfirmDialogOpen && /* @__PURE__ */ React.createElement(LinkAccountDialog, {
      isConfirming,
      onCancel: this.toggleConfirmDialog,
      onConfirm: this.onConfirm
    }));
  }
}
class LinkToExistingAccount extends React.Component {
  constructor(props) {
    super(props);
    this.dismissAlert = () => {
      this.setState({ alert: null });
    };
    this.onClickLogin = () => {
      const { createLoginURL } = this.appState.getSdk().IAM.UserAuthorization();
      const { oneTimeLinkCode } = this.props;
      const returnPath = AccPath.LinkAccountWithOneTimeCode.makePath(void 0, { oneTimeLinkCode });
      const loginURL = createLoginURL(returnPath, void 0, oneTimeLinkCode);
      window.location.replace(loginURL);
    };
    this.setErrorAlert = (error) => {
      const { oneTimeLinkCode, onHideTitle } = this.props;
      const errorCode = ErrorHelper.extractServiceErrorCode(error);
      if (errorCode === EXPIRED_ONE_TIME_ERROR_CODE) {
        onHideTitle();
        this.setState({ step: "shouldRestart" });
      }
      this.setState({
        alert: {
          type: AlertType.danger,
          element: (() => {
            switch (errorCode) {
              case EXPIRED_ONE_TIME_ERROR_CODE:
                return oneTimeLinkCode.length === ONE_TIME_CODE_LENGTH ? t("LinkAccountWithOneTimeCodePage.error.expired") : t("LinkAccountWithOneTimeCodePage.error.invalid");
              default:
                return /* @__PURE__ */ React.createElement(CommonError, {
                  error
                });
            }
          })()
        }
      });
    };
    this.onLinkToExisting = async () => {
      const userApi = this.appState.getSdk().IAM.User();
      const { oneTimeLinkCode, onHideTitle } = this.props;
      const { isLinking } = this.state;
      const publisherName = t("Common.publisherName");
      try {
        if (isLinking)
          return;
        this.setState({ isLinking: true });
        const result = await userApi.getLinkAccountByOneTimeCodeConflict({ oneTimeLinkCode });
        if (result.error)
          throw result.error;
        const { platformAlreadyLinked, platformLinkConflict, platformId, currentAccount, headlessAccount } = result.response.data;
        const platformName = UserHelper.getPlatformName(platformId);
        if (platformAlreadyLinked || platformLinkConflict) {
          this.setState({
            isLinking: false,
            alert: {
              type: AlertType.danger,
              element: /* @__PURE__ */ React.createElement(Trans, {
                i18nKey: "LinkAccountWithOneTimeCodePage.selectLinkMode.linkToExisting.conflict.message"
              }, "Unable to link this ", { publisherName }, " account. Because it has linked to other ", { platformName }, " account previously. Please use another ", { publisherName }, " account.")
            }
          });
          return;
        }
        onHideTitle();
        this.setState({ step: "pickProgression", progressionData: { currentAccount, headlessAccount, platformId } });
      } catch (error) {
        console.error(error);
        this.setState({ isLinking: false });
        this.setErrorAlert(error);
      }
    };
    this.onLinkWithProgressionSuccess = () => {
      this.setState({ alert: null, step: "success" });
    };
    this.renderNoSession = () => {
      const publisherName = t("Common.publisherName");
      return /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement("div", {
        className: styles.noSession
      }, /* @__PURE__ */ React.createElement(LoginIcon, {
        className: styles.loginIcon
      }), /* @__PURE__ */ React.createElement("p", {
        className: styles.description
      }, /* @__PURE__ */ React.createElement(Trans, {
        i18nKey: "LinkAccountWithOneTimeCodePage.selectLinkMode.linkToExisting.noSession.message"
      }, "There is no logged session, please login to your ", { publisherName }, " account to continue the account linking process."))), /* @__PURE__ */ React.createElement(Button, {
        className: "btn btn-primary mt-6 w-full py-2 px-0",
        onClick: this.onClickLogin
      }, t("Navigation.links.login")));
    };
    this.renderWithSession = () => {
      const { userProfile, user } = this.appState.getUserManager().state;
      const { isLinking } = this.state;
      const publisherName = t("Common.publisherName");
      if (!user)
        return null;
      return /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement("div", {
        className: styles.withSession
      }, /* @__PURE__ */ React.createElement(ProfileImage, {
        imageLink: (userProfile == null ? void 0 : userProfile.avatarUrl) || "",
        className: styles.withSessionAvatar
      }), /* @__PURE__ */ React.createElement("div", {
        className: "text-2sm ml-4"
      }, /* @__PURE__ */ React.createElement("p", {
        className: styles.withSessionUserName
      }, user.userName || user.displayName), /* @__PURE__ */ React.createElement("p", {
        className: styles.withSessionEmail
      }, user.emailAddress))), /* @__PURE__ */ React.createElement("div", {
        className: "mt-6 text-center"
      }, /* @__PURE__ */ React.createElement(Button, {
        className: "btn btn-primary mb-6 w-full py-2 px-0",
        onClick: this.onLinkToExisting,
        isLoading: isLinking
      }, /* @__PURE__ */ React.createElement(Trans, {
        i18nKey: "LinkAccountWithOneTimeCodePage.selectLinkMode.tab.linkToExisting"
      }, "Link to Existing Account")), /* @__PURE__ */ React.createElement("p", {
        className: styles.description
      }, /* @__PURE__ */ React.createElement(Trans, {
        i18nKey: "LinkAccountWithOneTimeCodePage.pickProgression.linkAnother.question"
      }, "Don't want to link to this existing account?")), /* @__PURE__ */ React.createElement(Button, {
        className: "text-2sm text-primary-60 mx-auto py-2",
        buttonStyle: ButtonStyle.NONE,
        onClick: this.onClickLogin
      }, /* @__PURE__ */ React.createElement(Trans, {
        i18nKey: "LinkAccountWithOneTimeCodePage.pickProgression.linkAnother.action"
      }, "Link with another ", { publisherName }, " account"))));
    };
    this.renderLinkAccountStep = () => {
      const { user } = this.appState.getUserManager().state;
      return user && !IamHelper.currentUserIsHeadlessAccount(user) ? this.renderWithSession() : this.renderNoSession();
    };
    this.state = {
      alert: null,
      isLinking: false,
      step: "linkAccount",
      progressionData: null
    };
    this.appState = Ctx.getAppState();
  }
  render() {
    const { oneTimeLinkCode, onRestart } = this.props;
    const { alert, step, progressionData } = this.state;
    const publisherName = t("Common.publisherName");
    const platformName = UserHelper.getPlatformName((progressionData == null ? void 0 : progressionData.platformId) || "");
    return /* @__PURE__ */ React.createElement(React.Fragment, null, step === "pickProgression" && /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement("div", {
      className: "mb-5 text-center"
    }, /* @__PURE__ */ React.createElement("p", {
      className: styles.title
    }, /* @__PURE__ */ React.createElement(Trans, {
      i18nKey: "LinkAccountWithOneTimeCodePage.pickProgression.title"
    }, "Choose Game Progression")), /* @__PURE__ */ React.createElement("p", {
      className: styles.description
    }, /* @__PURE__ */ React.createElement(Trans, {
      i18nKey: "LinkAccountWithOneTimeCodePage.pickProgression.desc"
    }, "Select the game progression you'd like to migrate from your ", { platformName }, " account to your ", { publisherName }, " ", "account."))), /* @__PURE__ */ React.createElement("hr", null)), step === "shouldRestart" && /* @__PURE__ */ React.createElement(CommonTitle, null), !!alert && /* @__PURE__ */ React.createElement(Alert, {
      type: alert.type,
      onDismiss: this.dismissAlert,
      className: classNames("mb-6 text-left", step === "shouldRestart" && "mt-5")
    }, alert.element), step === "linkAccount" && this.renderLinkAccountStep(), step === "pickProgression" && progressionData && /* @__PURE__ */ React.createElement(PickProgression, {
      platformName,
      oneTimeLinkCode,
      currentAccount: progressionData == null ? void 0 : progressionData.currentAccount,
      headlessAccount: progressionData == null ? void 0 : progressionData.headlessAccount,
      onSuccess: this.onLinkWithProgressionSuccess,
      onError: this.setErrorAlert
    }), step === "success" && /* @__PURE__ */ React.createElement(SuccessMessage, {
      isUpgradeToFull: false,
      platformName
    }), step === "shouldRestart" && /* @__PURE__ */ React.createElement(RestartMessage, {
      onRestart
    }));
  }
}
const TabButton = ({ isActive, onClick, label: label2 }) => /* @__PURE__ */ React__default.createElement(Button, {
  className: classNames(TabStyles.tab, isActive && TabStyles.active),
  buttonStyle: ButtonStyle.NONE,
  onClick
}, label2);
class SelectLinkMode extends React.Component {
  constructor(props) {
    super(props);
    this.showTitleAndTabs = () => {
      this.setState({ areTitleAndTabsHidden: false });
    };
    this.hideTitleAndTabs = () => {
      this.setState({ areTitleAndTabsHidden: true });
    };
    this.changeTab = (tab) => {
      this.setState({ selectedTab: tab });
    };
    this.state = {
      areTitleAndTabsHidden: false,
      selectedTab: "linkToExisting"
    };
  }
  render() {
    const { areTitleAndTabsHidden, selectedTab } = this.state;
    const { oneTimeLinkCode, onRestart } = this.props;
    return /* @__PURE__ */ React.createElement(React.Fragment, null, !areTitleAndTabsHidden && /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement(CommonTitle, null), /* @__PURE__ */ React.createElement("div", {
      className: "my-6"
    }, /* @__PURE__ */ React.createElement(Tabs, null, /* @__PURE__ */ React.createElement(TabButton, {
      isActive: selectedTab === "linkToExisting",
      onClick: () => this.changeTab("linkToExisting"),
      label: /* @__PURE__ */ React.createElement(Trans, {
        i18nKey: "LinkAccountWithOneTimeCodePage.selectLinkMode.tab.linkToExisting"
      }, "Link to Existing Account")
    }), /* @__PURE__ */ React.createElement(TabButton, {
      isActive: selectedTab === "upgradeToFull",
      onClick: () => this.changeTab("upgradeToFull"),
      label: /* @__PURE__ */ React.createElement(Trans, {
        i18nKey: "LinkAccountWithOneTimeCodePage.selectLinkMode.tab.upgradeToFull"
      }, "Upgrade to Full Account")
    })))), selectedTab === "upgradeToFull" && /* @__PURE__ */ React.createElement(UpgradeToFullAccount, {
      onHideTitle: this.hideTitleAndTabs,
      onShowTitle: this.showTitleAndTabs,
      onRestart,
      oneTimeLinkCode
    }), selectedTab === "linkToExisting" && /* @__PURE__ */ React.createElement(LinkToExistingAccount, {
      onHideTitle: this.hideTitleAndTabs,
      onRestart,
      oneTimeLinkCode
    }));
  }
}
class LinkAccountWithOneTimeCodePage extends React.Component {
  constructor(props) {
    super(props);
    this.onRestart = () => {
      this.setState({ step: "oneTimeCode" });
      this.appState.state.appHistory.replace(AccPath.LinkAccountWithOneTimeCode.link);
    };
    this.goToSelectLinkModeStep = (oneTimeLinkCode) => {
      this.setState({ oneTimeLinkCode, step: "selectLinkMode" });
    };
    this.renderContent = () => {
      const { step, oneTimeLinkCode } = this.state;
      switch (step) {
        case "oneTimeCode":
          return /* @__PURE__ */ React.createElement(OneTimeCodeForm, {
            onContinue: this.goToSelectLinkModeStep
          });
        case "selectLinkMode":
          return /* @__PURE__ */ React.createElement(SelectLinkMode, {
            oneTimeLinkCode,
            onRestart: this.onRestart
          });
        default:
          return null;
      }
    };
    this.state = {
      step: "oneTimeCode",
      oneTimeLinkCode: ""
    };
    this.appState = Ctx.getAppState();
  }
  componentDidMount() {
    const { appHistory } = this.appState.state;
    const searchParams = FeUtils.getSearchParamsObject(appHistory);
    const oneTimeLinkCode = searchParams.get("oneTimeLinkCode");
    if (oneTimeLinkCode) {
      this.setState({ oneTimeLinkCode, step: "selectLinkMode" });
    }
    UIEvent.updateBackground(`url(${bgCommon})`);
  }
  componentWillUnmount() {
    UIEvent.updateBackground(null);
  }
  render() {
    return /* @__PURE__ */ React.createElement("div", {
      className: classNames(styles.oneTimeLinkAccountPage, { [styles.desktop]: DesktopChecker.isDesktopApp() })
    }, /* @__PURE__ */ React.createElement(LanguageSelector, {
      className: styles.languageSelector
    }), /* @__PURE__ */ React.createElement("div", {
      className: classNames(styles.container)
    }, /* @__PURE__ */ React.createElement(HeaderLogoContainer, null), /* @__PURE__ */ React.createElement("div", {
      className: styles.form
    }, this.renderContent())));
  }
}
export { LinkAccountWithOneTimeCodePage as default };
