import { Accelbyte as ce, UrlHelper as fe, DesktopChecker as ue } from "@accelbyte/sdk";
import { L as me } from "./LoadingPage-a84c21af.mjs";
import t, { useState as I, useEffect as S, useRef as pe } from "react";
import { Trans as L, I18nextProvider as Ce } from "react-i18next";
import Se from "classnames";
import { B as ge } from "./Button-c97a7217.mjs";
import { D as he, a as ye, b as De } from "./Dialog-806d50a9.mjs";
import { S as be } from "./SSRHelper-8eb361ff.mjs";
import { Buffer as Pe } from "buffer";
import { i as Ee } from "./i18n-6228a4ed.mjs";
import { u as Ie, a as Le, b as xe, E as Ue, A as g, C as Ae, c as Ne } from "./FetchConfigsUtils-476a602b.mjs";
import { S as _e, C as h, a as Fe, b as Re, c as Be, w as He } from "./ConfigsUtils-dd5e59d2.mjs";
import { W as Te } from "./widget-ctx-5e46828e.mjs";
import { u as Ve, a as Ge } from "./useUserInfo-ad7006e5.mjs";
import { u as We, a as Me } from "./useAppState-80c04995.mjs";
import { u as de } from "./useDiscoveryConfigs-cf63cd60.mjs";
import { u as je } from "./useAppConfigs-0fb5df89.mjs";
import { LegalHelper as ze } from "@accelbyte/sdk-legal";
import { ToastContainer as Ke } from "react-toastify";
import "./ReactToastify-4ed993c7.mjs";
import "./Loading-9dff8957.mjs";
import "react-feather";
import "react-dom";
import "flat";
import "i18next";
import "date-fns";
import "./RouteUtils-f2d71427.mjs";
import "zod";
import "uuid";
import "axios";
import "@accelbyte/sdk-iam";
import "@accelbyte/sdk-basic";
import "@accelbyte/sdk-gdpr";
const Je = "btnClose _btnClose_46775", Ye = {
  btnClose: Je
}, $e = ({ isSessionExpired: n, onLogout: a }) => /* @__PURE__ */ t.createElement(he, { title: /* @__PURE__ */ t.createElement(L, { i18nKey: "SessionExpiredDialog.title" }, "Session expired"), isOpen: n }, /* @__PURE__ */ t.createElement(ye, null, /* @__PURE__ */ t.createElement(L, { i18nKey: "SessionExpiredDialog.bodyText" }, "Your session has expired. Please log in again.")), /* @__PURE__ */ t.createElement(De, null, /* @__PURE__ */ t.createElement(
  ge,
  {
    className: Se("btn btn-ghost", Ye.btnClose),
    onClick: () => {
      a();
    }
  },
  /* @__PURE__ */ t.createElement(L, { i18nKey: "SessionExpiredDialog.buttonAction" }, "Close")
)));
be.isSSR() || (window.Buffer = Pe);
const qe = ({ sdkOptions: n, sdkEvents: a, sdkToken: f, widgetOptions: e, onInitializeSDK: b, children: G, history: P, routes: x }) => {
  var B;
  const [y, W] = Ie(), [Qe, M] = Le(), [d, j] = I(!1), [z, K] = I(!1), [J, U] = I(!1), { mutations: Y } = Ve(), { state: $ } = We(), { state: A, mutations: q } = de(), { mutations: D } = je(), { mutations: N } = Ge(), { mutations: Q } = xe(), { clearSession: X, refreshSession: _, fetchAllUserInformation: E, refreshToken: Z, logout: v } = Me(), F = !d || !z;
  S(() => {
    if (y)
      return;
    const o = ce.SDK({
      options: n,
      config: {
        headers: { Authorization: f != null && f.accessToken ? `Bearer ${f.accessToken}` : "" }
      },
      onEvents: {
        onError: k,
        onSessionExpired: O,
        onGetUserSession: re,
        onUserEligibilityChange: ae
      }
    });
    f && o.refreshTokens(f.accessToken, f.refreshToken), W(o), M({
      ...n,
      redirectURI: fe.trimSlashFromStringEnd(n.redirectURI)
    }), b && b(o);
  }, [y, n, b]), S(() => {
    N.initHistory(P), x && Q.initRoutes(x);
  }, []), S(() => {
    N.setLocation(P.location);
  }, [JSON.stringify(P.location)]);
  const R = pe(void 0);
  S(() => {
    (async () => {
      if (e !== void 0 && R.current === e || y === void 0)
        return;
      const i = _e.safeParse(e == null ? void 0 : e.generalConfigs), C = i.success ? h.createDiscoveryConfigs(i.data) : e == null ? void 0 : e.generalConfigs, u = Fe.safeParse(e == null ? void 0 : e.playerPortalConfigs), c = u.success ? h.createPlayerPortalConfigs(u.data) : e == null ? void 0 : e.playerPortalConfigs, l = Re.safeParse(e == null ? void 0 : e.twitchDropConfigs), m = l.success ? h.createTwitchDropConfigs(l.data) : e == null ? void 0 : e.twitchDropConfigs, s = Be.safeParse(e == null ? void 0 : e.supportConfigs), r = s.success ? h.createSupportConfigs(s.data) : e == null ? void 0 : e.supportConfigs;
      try {
        Y.setDefaultMfaData(), await w(C, c, m, r);
      } catch (p) {
        console.error(p);
      } finally {
        K(!0), R.current = e;
      }
    })();
  }, [e, y]), S(() => {
    if (!A.flags)
      return;
    (async () => {
      try {
        await E();
      } finally {
        j(!0);
      }
    })();
  }, [(B = A.flags) == null ? void 0 : B.isLegalEnabled]);
  const w = async (o, i, C, u) => {
    var H, T;
    let c = !1, l = 0, m = null, s = i || null, r = o || null;
    const p = ue.isDesktopApp() ? g.LAUNCHER : g.WIDGET;
    for (; !c && l < 3; ) {
      const V = await q.fetchDiscoveryConfigs(o);
      r = ((H = V.data) == null ? void 0 : H.discoveryConfigData) || null, m = ((T = V.data) == null ? void 0 : T.flags) || null;
      const se = r == null ? void 0 : r.ppFeatureFlags.data.isTwitchDropEnabled, te = r == null ? void 0 : r.supportFeatureFlags.data.isPlayerPortalSupportVisible, ie = r == null ? void 0 : r.supportFeatureFlags.data.isLauncherSupportVisible, ne = p === g.WIDGET ? te : ie;
      r && (p === g.WIDGET && (s = (await D.fetchPlayerPortalConfigs(
        r,
        i
      )).data || null), p === g.LAUNCHER && (s = (await D.fetchLauncherConfigs(r, i)).data || null), se && await D.fetchTwitchDropConfigs(r, C), ne && await D.fetchSupportConfigs(r, u)), c = !!m && !!s && Object.keys(s).length > 0, l += 1, !c && l < 3 && await He(l * 5e3);
    }
    if (!m || !s || Object.keys(s).length === 0)
      throw new Ae(
        "Configuration errors were detected, application will not start. Please fix the configuration then try again.",
        p,
        Ne.INVALID_CONFIGS
      );
    r && s && h.injectCss(r, s.pageConfig);
  }, k = async (o) => {
    var u, c, l;
    const { eligibilities: i } = $, C = ze.currentUserIsBlockedByLegal(i);
    if (Ue.isAxiosError(o) && ((u = o.response) == null ? void 0 : u.status) === 403 && !C) {
      if ((l = (c = o.response) == null ? void 0 : c.config.url) == null ? void 0 : l.includes("/admin"))
        return;
      const s = await Z();
      s && (_(s.access_token, s.refresh_token), await E());
    }
    a != null && a.onError && a.onError(o);
  }, O = () => {
    X(ee), a != null && a.onSessionExpired && a.onSessionExpired();
  }, ee = () => {
    U(!0);
  }, re = (o, i) => {
    _(o, i), a != null && a.onGetUserSession && a.onGetUserSession(o, i);
  }, ae = () => {
    E(), a != null && a.onUserEligibilityChange && a.onUserEligibilityChange();
  }, oe = () => {
    U(!1), v();
  };
  return /* @__PURE__ */ t.createElement("div", { id: "app", className: "sdk-widget-app font-body" }, !F && G, F && /* @__PURE__ */ t.createElement(me, null), /* @__PURE__ */ t.createElement($e, { isSessionExpired: J, onLogout: oe }), /* @__PURE__ */ t.createElement(Ke, null));
}, Ar = (n) => /* @__PURE__ */ t.createElement(Ce, { i18n: Ee }, /* @__PURE__ */ t.createElement(
  Te.Provider,
  {
    value: {
      Link: n.Link,
      NavLink: n.NavLink
    }
  },
  /* @__PURE__ */ t.createElement(qe, { ...n })
));
export {
  Ar as SdkWidget
};
