import { Loading as w, LoadingSize as f } from "./accelbyte-widgets136.mjs";
import { UrlUtils as u } from "./accelbyte-widgets90.mjs";
import s from "react";
import { withRouter as A } from "react-router-dom";
import { LinkedFormPanel as T } from "./accelbyte-widgets314.mjs";
import { LinkFormPanel as d } from "./accelbyte-widgets315.mjs";
import { Ctx as L } from "./accelbyte-widgets33.mjs";
import { TwitchDropReclaimPage as U } from "./accelbyte-widgets316.mjs";
import { TwitchDropValidateStatus as o, TwitchErrorCode as R } from "./accelbyte-widgets317.mjs";
import { LinkedPlatformId as g } from "./accelbyte-widgets239.mjs";
import { Env as S } from "./accelbyte-widgets108.mjs";
import { IamUserAuthorizationClient as I } from "@accelbyte/sdk-iam";
const E = "AB-Twitch_drops-claim-game_client_id";
class y extends s.Component {
  constructor(i) {
    super(i), this.fetchLinkedTwitchAccount = async (t) => {
      try {
        await this.linkTwitchManager.fetchLinkedTwitchAccount(t.userId);
      } catch (e) {
        console.error(e);
      }
    }, this.exchangeTwitchAuthTokenToABToken = async (t) => {
      const e = this.appState.getUser();
      if (t && e)
        try {
          const a = sessionStorage.getItem(E) || "", { response: n } = await this.linkedAccountManager.exchageTwitchPlatformTokentoABToken(g.Enum.twitch, a, {
            platform_token: t,
            client_id: a,
            createHeadless: !1,
            skipSetCookie: !0
          });
          if (n != null && n.data) {
            let c = "";
            n.data.namespace === S.NAMESPACE ? c = n.data.user_id : n.data.platform_user_id && (c = (await this.linkedAccountManager.getLinkedAccountByPlatformUserId(
              g.Enum.twitch,
              n.data.platform_user_id
            )).userId), this.setState({
              validateStatus: c === e.userId ? o.SUCCESS : o.FAILED,
              retryStatus: !0
            });
          } else
            this.setState({
              validateStatus: o.FAILED
            });
        } catch {
          this.setState({
            validateStatus: o.FAILED
          });
        } finally {
          this.appState.state.appHistory.replace(this.getPathname());
        }
    }, this.isReclaim = () => new URLSearchParams(location.search).get("step") === "reclaim" || new URLSearchParams(location.search).get("state") === "reclaim", this.getTwitchAuthToken = () => new URLSearchParams(location.search).get("code"), this.getRequestId = () => new URLSearchParams(location.search).get("requestId"), this.requestStatus = async (t) => {
      const e = this.appState.getUser();
      if (t && e)
        try {
          const a = await this.linkedAccountManager.requestStatus(t);
          this.validateTwitchAccount(a == null ? void 0 : a.error);
        } catch (a) {
          this.validateTwitchAccount(a);
        } finally {
          this.appState.state.appHistory.replace(this.getPathname());
        }
    }, this.validateTwitchAccount = (t) => {
      this.setState({
        validateStatus: (t == null ? void 0 : t.errorCode) === R.TWITCH_ACCOUNT_ALREADY_LINKED ? o.SUCCESS : o.FAILED
      });
    }, this.linkAccount = (t = !1, e, a) => {
      const n = u.getRedirectUrl(this.appState.sdkOptions.redirectURI, this.getPathname());
      this.linkTwitchManager.getTwitchURL(n, a || this.appState.sdkOptions.clientId, e).then((c) => {
        if (c)
          if (t) {
            const r = new URL(c);
            r.searchParams.set("force_verify", "true"), e && r.searchParams.set("redirect_uri", u.getRedirectUrl(S.REDIRECT_URL, "/twitch-drops/claim?step=reclaim")), window.location.href = r.toString();
          } else
            window.location.href = c;
      });
    }, this.getPathname = () => this.props.location.pathname + (this.isReclaim() ? "?state=reclaim" : ""), this.state = {
      validateStatus: this.getTwitchAuthToken() ? o.VALIDATING : null,
      retryStatus: !1
    }, this.appState = L.getAppState(), this.linkTwitchManager = this.appState.linkTwitchManager, this.linkTwitchManager.subscribe(() => this.setState({})), this.linkedAccountManager = this.appState.linkAccountManager, this.linkedAccountManager.subscribe(() => this.setState({}));
  }
  async componentDidMount() {
    const i = this.appState.getUser();
    if (!i) {
      this.tryLogin();
      return;
    }
    const t = this.getTwitchAuthToken();
    t && this.exchangeTwitchAuthTokenToABToken(t);
    const e = this.getRequestId();
    e && !t && this.requestStatus(e), this.linkTwitchManager.state.linkedTwitchAccount || this.fetchLinkedTwitchAccount(i);
  }
  tryLogin() {
    const i = new I(this.appState.getSdk()).createLoginURL(
      this.props.location.pathname + this.props.location.search
    );
    window.location.replace(i);
  }
  componentWillUnmount() {
    this.linkedAccountManager.setState({ error: null, accountConflictInformation: null });
  }
  render() {
    const { linkedTwitchAccount: i, isFetchingToken: t, isFetchingLoginURL: e, isFetchingLinkedTwitchAccount: a, isFetchingConfigs: n } = this.linkTwitchManager.state, { isFetchingProfile: c, userProfile: r } = this.appState.userAppManager.state, { isLinking: k, error: m, accountConflictInformation: p } = this.linkedAccountManager.state, l = k || a || t || c || n, h = this.appState.getUser();
    return /* @__PURE__ */ s.createElement(s.Fragment, null, l && /* @__PURE__ */ s.createElement(w, { className: f.tall }), !this.isReclaim() && !l && h && /* @__PURE__ */ s.createElement(s.Fragment, null, i ? /* @__PURE__ */ s.createElement(T, { className: this.props.className }) : /* @__PURE__ */ s.createElement(
      d,
      {
        user: h,
        avatarURL: (r == null ? void 0 : r.avatarUrl) ?? "",
        onLink: this.linkAccount,
        isLoading: e,
        error: m,
        accountConflictInformation: p,
        className: this.props.className
      }
    )), this.isReclaim() && !l && h && /* @__PURE__ */ s.createElement(s.Fragment, null, i ? /* @__PURE__ */ s.createElement(
      U,
      {
        displayName: (i == null ? void 0 : i.displayName) ?? "",
        validateStatus: this.state.validateStatus,
        retryStatus: this.state.retryStatus,
        onLink: this.linkAccount,
        className: this.props.className
      }
    ) : /* @__PURE__ */ s.createElement(
      d,
      {
        user: h,
        avatarURL: (r == null ? void 0 : r.avatarUrl) ?? "",
        onLink: this.linkAccount,
        isLoading: e,
        error: m,
        accountConflictInformation: p,
        className: this.props.className
      }
    )));
  }
}
const O = A(y);
export {
  O as TwitchDropPage
};
