import { DesktopChecker as r, Accelbyte as w } from "@accelbyte/sdk";
import { ConfigKeys as n, AppName as A } from "./accelbyte-widgets78.mjs";
import { Ctx as E } from "./accelbyte-widgets33.mjs";
import { Env as d } from "./accelbyte-widgets108.mjs";
import { FeatureFlags as C, FeatureFlagsImpl as I } from "./accelbyte-widgets57.mjs";
import { DBKeys as o, DesktopDB as D, WebDB as y } from "./accelbyte-widgets150.mjs";
import { AccPath as c } from "./accelbyte-widgets34.mjs";
import { GlobalPath as m } from "./accelbyte-widgets104.mjs";
import { LoginPath as U } from "./accelbyte-widgets35.mjs";
import { DownloadManagerState as F } from "./accelbyte-widgets240.mjs";
import { FetchConfigsUtils as L } from "./accelbyte-widgets241.mjs";
import { ErrorHelper as f } from "./accelbyte-widgets120.mjs";
import { GameHelper as b } from "./accelbyte-widgets205.mjs";
import { SSRHelper as T } from "./accelbyte-widgets242.mjs";
import { GameAppManager as v } from "./accelbyte-widgets243.mjs";
import { GdprAppManager as R } from "./accelbyte-widgets244.mjs";
import { InputValidationAppManager as _ } from "./accelbyte-widgets245.mjs";
import { LegalAppManager as G } from "./accelbyte-widgets246.mjs";
import { LinkConflictAccountManager as O } from "./accelbyte-widgets247.mjs";
import { LinkedAccountsAppManager as P } from "./accelbyte-widgets248.mjs";
import { LinkTwitchAppManager as H } from "./accelbyte-widgets249.mjs";
import { MiscAppManager as N } from "./accelbyte-widgets250.mjs";
import { PaymentMethodsAppManager as x } from "./accelbyte-widgets251.mjs";
import { UserAppManager as B } from "./accelbyte-widgets252.mjs";
import { UserVerificationManager as V } from "./accelbyte-widgets253.mjs";
import { WalletAppManager as W } from "./accelbyte-widgets254.mjs";
import { Container as K } from "unstated";
import { SettingsState as j } from "./accelbyte-widgets255.mjs";
import { IamHelper as Y } from "@accelbyte/sdk-iam";
import { LegalHelper as J } from "@accelbyte/sdk-legal";
import { TemplateConfig as Z } from "./accelbyte-widgets116.mjs";
class Dt extends K {
  constructor({ sdkOptions: p, basePath: u }) {
    super(), this.markAuthCodeExchangeTrialDone = () => {
      this.setState({ authCodeExchangeTried: !0 });
    }, this.markLauncherAsUpdated = () => {
      this.setState({ launcherIsUpdated: !0 });
    }, this.resetLauncherUpdateState = () => {
      this.setState({ launcherIsUpdated: !1 });
    }, this.getSdk = () => this.sdk, this.getUserManager = () => this.userAppManager, this.getLegalManager = () => this.legalAppManager, this.getGameState = () => this.gameManager, this.getDownloadManagerStateV2 = () => {
    }, this.getWalletManager = () => this.walletAppManager, this.getUser = () => this.userAppManager.state.user, this.getSettingsState = () => this.settingsState, this.getInputValidationManager = () => this.inputValidationAppManager, this.getGdprManager = () => this.gdprAppManager, this.getPersistDB = () => this.db, this.clear = () => {
      this.gdprAppManager.clear(), this.inputValidationAppManager.clear(), this.legalAppManager.clear(), this.linkConflictAccountManager.clear(), this.linkAccountManager.clear(), this.miscAppManager.clear(), this.paymentMethodManager.clear(), this.userAppManager.clear(), this.verificationManager.clear(), this.walletAppManager.clear(), this.gameManager.clear(), this.setState({ error: null, isSessionExpired: !1 });
      for (const t of Object.keys(o))
        t !== o.SETTINGS && this.db.delete(t);
    }, this.getFeatureFlags = () => this.getPersistDB().get(o.FEATURE_FLAGS), this.getDefaultAvatarsList = () => {
      var t;
      return (t = this.state.discovery) == null ? void 0 : t.avatarsList.data.value;
    }, this.getLauncherDownloadLink = () => {
      var t;
      return (t = this.getConfig(n.LAUNCHER_DOWNLOAD_LINK_CONFIG)) == null ? void 0 : t.data.value;
    }, this.getPPConfig = () => this.state.config, this.getCustomHeader = () => {
      var t;
      return (t = this.getConfig(n.HEADER_CUSTOMIZATION)) == null ? void 0 : t.data;
    }, this.getLauncherUpdateUrl = () => {
      var t;
      return (t = this.getConfig(n.LAUNCHER_UPDATE_URL_CONFIG)) == null ? void 0 : t.data.value;
    }, this.getPageConfig = (t, s) => {
      var a;
      const e = (a = this.getConfig(n.PAGE_CONFIG)) == null ? void 0 : a.data[t];
      if (!s)
        return e;
      if (e)
        return e[s];
    }, this.getGameId = () => {
      var t;
      return ((t = this.state.discovery) == null ? void 0 : t.appId.data.value) || "";
    }, this.getMetaData = () => {
      var t;
      return (t = this.getConfig(n.META_DATA)) == null ? void 0 : t.data;
    }, this.getCompanyLogo = (t) => {
      var a, i, l, h, g, M, S, k;
      const e = ((a = this.getConfig(n.LOGO_VARIANT)) == null ? void 0 : a.data[t]) ?? ((h = (l = (i = this.state.discovery) == null ? void 0 : i.companyLogo) == null ? void 0 : l.data) == null ? void 0 : h.defaultIndex);
      return (k = (S = (M = (g = this.state.discovery) == null ? void 0 : g.companyLogo) == null ? void 0 : M.data) == null ? void 0 : S.images[e]) == null ? void 0 : k.url;
    }, this.isSingleGame = () => {
      var t;
      return ((t = this.state.discovery) == null ? void 0 : t.templateConfig.data.value) === Z.SINGLE;
    }, this.getFooterConfig = () => {
      var t;
      return (t = this.getConfig(n.FOOTER)) == null ? void 0 : t.data.value;
    }, this.getSupportEmail = () => {
      var t;
      return (t = this.getConfig(n.SUPPORT_EMAIL)) == null ? void 0 : t.data.value;
    }, this.getHomepagePPConfig = () => this.getConfig(n.HOMEPAGE) ? this.getConfig(n.HOMEPAGE).data : null, this.getSocialLinks = (t) => t ? this.getAllSocialLinks().filter((s) => s.apps.includes(t)) : this.getAllSocialLinks(), this.getCopyrightText = () => {
      var t;
      return ((t = this.state.discovery) == null ? void 0 : t.copyright.data.value) || "";
    }, this.getAllSocialLinks = () => {
      var t;
      return ((t = this.state.discovery) == null ? void 0 : t.socialLinks.data.value) ?? [];
    }, this.getBrandName = () => {
      var t;
      return ((t = this.state.discovery) == null ? void 0 : t.brandName.data.value) || "";
    }, this.getGlobalPageConfigFromDiscovery = () => {
      var t;
      return (t = this.state.discovery) == null ? void 0 : t.globalPageConfig;
    }, this.fetchDiscovery = async (t, s) => {
      const e = await L.fetchDiscovery({
        sdk: this.sdk,
        appName: t,
        widgetOptions: s,
        useConfigService: !!d.CONF_SERVER
      });
      let a;
      switch (t) {
        case A.PP:
        case A.WIDGET:
          a = { ...e == null ? void 0 : e.ppFeatureFlags.data, ...e == null ? void 0 : e.experimentalFeatureFlags.data };
          break;
        case A.LAUNCHER:
          a = {
            ...e == null ? void 0 : e.launcherFeatureFlags.data,
            ...e == null ? void 0 : e.experimentalFeatureFlags.data,
            ...e == null ? void 0 : e.supportFeatureFlags.data
          };
          break;
      }
      this.setState({
        discovery: e
      }), a && JSON.stringify(a) !== this.featureFlagsManager.toString() && (this.featureFlagsManager.setFlags(a), await this.db.set(o.FEATURE_FLAGS, a));
    }, this.setConfig = (t) => {
      this.setState({ config: t });
    }, this.fetchConfigs = async (t, s, e = !0) => {
      const a = await L.fetchConfigs({
        sdk: this.sdk,
        appName: t,
        discoveryData: this.state.discovery,
        widgetOptions: s,
        useConfigService: !!d.CONF_SERVER
      });
      e && await this.db.set(o.APP_CONFIG, a), await this.setState({
        config: a
      });
    }, this.refreshSession = (t, s) => {
      !this.db || !r.isDesktopApp() || (s && t && (this.db.set(o.ACCESS_TOKEN, t), this.db.set(o.REFRESH_TOKEN, s)), this.sdk.refreshTokens(t, s));
    }, this.showLauncherTerminationModal = () => {
      this.setState({ showLauncherTerminationModal: !0 });
    }, this.hideLauncherTerminationModal = () => {
      this.setState({ showLauncherTerminationModal: !1 });
    }, this.initSdk = (t) => {
      var e, a, i;
      const s = w.SDK({
        options: { ...t },
        config: {
          withCredentials: !r.isDesktopApp()
        },
        onEvents: {
          onSessionExpired: this.clearSession,
          onGetUserSession: this.refreshSession,
          onUserEligibilityChange: this.fetchAllUserInformation,
          onError: this.onError
        }
      });
      return (e = this.db) != null && e.getAccessToken() && s.refreshTokens((a = this.db) == null ? void 0 : a.getAccessToken(), (i = this.db) == null ? void 0 : i.getRefreshToken()), s;
    }, this.refreshUI = () => {
      this.setState({ forceUIRefresh: !this.state.forceUIRefresh });
    }, this.clearSession = () => {
      if (!r.isDesktopApp()) {
        const { user: t } = this.userAppManager.state, { deletionMark: s } = this.getGdprManager().state;
        t && (s ? this.state.appHistory.push(U.Logout.link) : this.setState({ isSessionExpired: !0 }));
      }
      r.isDesktopApp() && (this.clear(), this.refreshSession(void 0, void 0), this.refreshUI(), this.setState({ isSessionExpired: !0 }));
    }, this.fetchCurrentUserGdprDeletionStatus = async () => {
      const { user: t } = this.getUserManager().state;
      if (t != null && t.userId)
        try {
          await this.gdprAppManager.fetchGdprDeletionStatus(t.userId);
        } catch (s) {
          console.error(s);
        }
    }, this.fetchAllUserInformation = async () => {
      const t = E.hasFeature(C.isLegalEnabled);
      try {
        await Promise.allSettled([this.getUserManager().fetchCurrentUserInformation(), this.getLegalManager().fetchUnsignedPolicies()]);
        const { user: s } = this.getUserManager().state;
        if (Y.currentUserIsEligible(s)) {
          const { eligibilities: e } = this.legalAppManager.state, a = (e == null ? void 0 : e.length) === 0;
          (!t && !e || a) && (s != null && s.userId) && (await this.gdprAppManager.fetchGdprDeletionStatus(s.userId), await this.getUserManager().fetchOrCreateUserProfile());
        }
      } catch (s) {
        console.error(s);
      }
    }, this.refreshUser = async () => {
      const t = [
        c.UpgradeAccount.link,
        m.PromptLegal.link,
        c.AccountDeletionSuccess.link,
        c.EmailVerification.link,
        c.ChangeEmail.link,
        c.TwoFA.link
      ];
      await this.fetchAllUserInformation(), await this.refreshWallet(), this.getUserManager().state.user || this.legalAppManager.clear();
      const e = this.state.appHistory.location.pathname;
      r.isDesktopApp() && (b.loadGameInfo(), t.find((a) => a === e) && this.state.appHistory.replace(m.Home.link));
    }, this.refreshWallet = async () => {
      const t = this.getUser();
      !t || !E.hasFeature(C.isVirtualCurrencyVisible) || await this.walletAppManager.fetchWallet(t.userId, d.WALLET_VIRTUAL_CURRENCY_CODE);
    }, this.updateUserCustomAttribute = async (t, s) => {
      try {
        const e = await this.linkAccountManager.getLinkedAccountByPlatformId(t, s);
        e == null || delete e.displayName, e == null || delete e.emailAddress, e == null || delete e.platformUserId;
        const a = {
          [s]: e
        };
        await this.userAppManager.updateCustomAttributes(t, a);
      } catch (e) {
        console.error(e);
      }
    }, this.logout = async (t) => {
      var s;
      if (r.isDesktopApp()) {
        const { gameEntitlementsRecord: e } = this.gameManager.state, a = e && Object.keys(e);
        (s = this.downloadManagerState) == null || s.stopAllDownload(a);
        const i = this.getPersistDB().getAccessToken();
        await this.userAppManager.revoke({ token: i }), this.clear(), this.refreshSession(void 0, void 0), this.state.appHistory.replace(t || U.Login.link);
      }
      r.isDesktopApp() || (await this.userAppManager.logout(), this.clear(), this.state.appHistory.replace(t || m.Home.link));
    }, this.onError = async (t) => {
      var a, i, l;
      if (f.isAxiosNetworkError(t) || f.isLoginSessionExpired(t)) {
        const { errorFetchingUser: h } = this.userAppManager.state;
        if (f.isAxiosServerError(h)) {
          this.setState({ error: h });
          return;
        }
        this.setState({ error: t });
      }
      const { eligibilities: s } = this.legalAppManager.state, e = J.currentUserIsBlockedByLegal(s);
      if (f.isAxiosError(t) && ((a = t.response) == null ? void 0 : a.status) === 403 && !e) {
        if ((l = (i = t.response) == null ? void 0 : i.config.url) == null ? void 0 : l.includes("/admin"))
          return;
        const g = await this.userAppManager.refreshToken();
        g && (this.refreshSession(g.access_token, g.refresh_token), await this.fetchAllUserInformation());
      }
    }, this.clearError = () => {
      this.setState({ error: null });
    }, this.state = {
      authCodeExchangeTried: !1,
      appHistory: T.createHistory(u || d.PLAYER_PORTAL_BASE_URL),
      forceUIRefresh: !1,
      config: {},
      error: null,
      showLauncherTerminationModal: !1,
      launcherIsUpdated: !1,
      isSessionExpired: !1,
      discovery: void 0
    }, this.osSettings = r.isDesktopApp() ? Device.osSettings : { get: {} }, this.db = r.isDesktopApp() ? new D(Device.desktopStorage) : new y(), this.sdkOptions = p, this.sdk = this.initSdk(p), this.legalAppManager = new G(this.sdk), this.legalAppManager.subscribe(() => this.refreshUI()), this.userAppManager = new B(this.sdk), this.userAppManager.subscribe(() => this.refreshUI()), this.verificationManager = new V(this.sdk), this.gameManager = new v(this.sdk, r.isDesktopApp() ? this.db : void 0), r.isDesktopApp() && (this.settingsState = new j(this.db, this.osSettings), this.settingsState.subscribe(() => {
      this.refreshUI();
    }), this.downloadManagerState = new F()), this.walletAppManager = new W(this.sdk), this.inputValidationAppManager = new _(this.sdk), this.gdprAppManager = new R(this.sdk), this.gdprAppManager.subscribe(() => this.refreshUI()), this.linkConflictAccountManager = new O(this.sdk), this.linkAccountManager = new P(this.sdk), this.miscAppManager = new N(this.sdk), this.paymentMethodManager = new x(this.sdk), this.linkTwitchManager = new H(this.sdk), this.featureFlagsManager = new I(this.db.get(o.FEATURE_FLAGS));
  }
  getConfig(p) {
    var u;
    return p ? (u = this.state.config) == null ? void 0 : u[p] : this.state.config;
  }
}
export {
  Dt as AppState
};
