import { useReactive as y, useMemoizedFn as I } from "ahooks";
import { getFederatedEnabled as w, getMaster as h, getConfig as L } from "@arcblock/ux/lib/Util/federated";
import b from "lodash/noop";
import { loginFederatedMaster as n } from "../libs/federated.js";
const s = {
  zh: {
    notFoundFederatedInfo: "未发现统一登录的信息",
    autoLoginFederatedFailed: "自动登录统一登录账号失败",
    manualLoginFederatedFailed: "手动登录统一登录账号失败"
  },
  en: {
    notFoundFederatedInfo: "No federated login info detected",
    autoLoginFederatedFailed: "Auto login federated account failed",
    manualLoginFederatedFailed: "Manual login federated account failed"
  }
};
function k({ locale: a, handleLoginResult: i, login: f, handleRefreshUser: u }) {
  const F = y({
    federatedMaster: null
  }), g = w(), l = h(), m = L(), c = I(
    async (d = b, p = {}, t = {}) => {
      typeof t == "string" && (t = { origin: t });
      let { mode: r = "auto", ...M } = p;
      if (t.mode && (r = t.mode), r === "auto") {
        if (!g)
          throw new Error(s[a].notFoundFederatedInfo);
        try {
          const e = await n({ appId: globalThis.blocklet.appId }, { fetchToken: !1 });
          i({ ...e, encrypted: !1 }), await u({ showProgress: !0 }), d();
        } catch (e) {
          const o = e?.response ? e.response?.data : e?.message;
          d(o || s[a].autoLoginFederatedFailed);
        }
      } else if (r === "manual")
        try {
          f(
            async () => {
              await n(
                // FIXME: @zhanghan 当 connect 组件使用不同的 baseUrl 时，不应该直接从 window.blocklet 去取值
                { appId: globalThis.blocklet.appId, onlyWriteCookie: !0 }
              ), d();
            },
            { ...M },
            t
          );
        } catch (e) {
          const o = e?.response ? e.response?.data : e?.message;
          d(o || s[a].autoLoginFederatedFailed);
        }
    },
    [u, f, a, i]
  );
  return {
    master: l,
    config: m,
    federatedMaster: F.federatedMaster,
    federatedEnabled: g,
    loginFederated: c,
    loginFederatedMaster: n
  };
}
export {
  k as default
};
