import { authorize as k, refresh as d } from "../../node_modules/@frontify/frontify-authenticator/dist/index.es.es.js";
import r, { useRef as f, useEffect as u } from "react";
import { useUploaderStore as D } from "../../state/uploaderStore.es.js";
import { LoadingCircle as E, LoadingCircleSize as g, LoadingCircleStyle as h } from "../../node_modules/@frontify/fondue/dist/components/LoadingCircle/LoadingCircle.es.es.js";
import { Text as w } from "../../node_modules/@frontify/fondue/dist/typography/Text/Text.es.es.js";
import "./Authentication.es2.js";
import { useOAuthStore as x } from "../../state/oAuthStore.es.js";
import { useAssetUploadStore as b } from "../../state/assetUploadStore.es.js";
const R = ({ onSuccess: i }) => {
  const c = f(null), { domain: a, clientId: l, scopes: p } = x((e) => ({
    domain: e.domain,
    clientId: e.clientId,
    scopes: e.scopes
  })), {
    token: t,
    setToken: s,
    tokenExpirationDate: n,
    setTokenExpirationDate: m
  } = D((e) => ({
    setToken: e.setToken,
    token: e.token,
    setTokenExpirationDate: e.setTokenExpirationDate,
    tokenExpirationDate: e.tokenExpirationDate
  })), { onError: T } = b((e) => ({ onError: e.onError }));
  return u(() => {
    (async () => {
      if (!(t && !!n && n > new Date().setTime(new Date().getTime())) || a !== (t == null ? void 0 : t.bearerToken.domain)) {
        const o = await k({ domain: a, clientId: l, scopes: p });
        s(o), m(new Date().setTime(new Date().getTime() + o.bearerToken.expiresIn)), i();
      } else if (t && !!n && n < new Date().setTime(new Date().getTime()) && a === t.bearerToken.domain) {
        const o = await d(t);
        s(o), m(new Date().setTime(new Date().getTime() + o.bearerToken.expiresIn)), console.debug("Token Refresh"), i();
      } else
        console.debug("Token Valid"), i();
    })().catch((o) => T(o));
  }, []), /* @__PURE__ */ r.createElement("div", {
    ref: c,
    className: "authentication__container"
  }, /* @__PURE__ */ r.createElement(w, {
    as: "p",
    size: "small"
  }, "Awaiting authentication..."), /* @__PURE__ */ r.createElement(E, {
    size: g.Medium,
    style: h.Progress
  }));
};
export {
  R as Authentication
};
//# sourceMappingURL=Authentication.es.js.map
