import { jsx as H } from "react/jsx-runtime";
import { createPortal as j } from "react-dom";
import { useCreation as R, useMemoizedFn as g, useReactive as V, useDebounce as q } from "ahooks";
import { useRef as B, use as Q, useState as v, useImperativeHandle as X } from "react";
import z from "lodash/noop";
import T from "lodash/cloneDeep";
import S from "lodash/isFunction";
import J from "lodash/isUndefined";
import { joinURL as k, withQuery as M } from "ufo";
import K from "p-queue";
import { useTheme as N } from "@arcblock/ux/lib/Theme";
import { getCookieOptions as G } from "@arcblock/ux/lib/Util";
import A from "js-cookie";
import { useBrowser as W } from "@arcblock/react-hooks";
import { getFederatedEnabled as Y, getMaster as Z } from "@arcblock/ux/lib/Util/federated";
import { SessionContext as $ } from "../Session/context.js";
import { openPopup as ee, runPopup as oe, updateConnectedInfo as ne, getAppId as te } from "../utils.js";
import { API_DID_PREFIX as re, BLOCKLET_SERVICE_PATH_PREFIX as se } from "../constant.js";
import ce from "./index.js";
const b = 2e3;
function ie({ ref: P }) {
  const { api: _, session: s } = Q($), [c, I] = v({
    title: "DID Connect",
    scan: "Use follwing methods to complete this action",
    confirm: "Confirm in your account",
    success: "Success!"
  }), x = N(), F = {
    containerEl: null,
    popup: !0,
    checkFn: _?.get || z
  }, C = x?.transitions?.duration?.leavingScreen || 500, e = V({
    show: !1,
    ...T(F)
  }), o = q(e.show, {
    wait: C
  }), [i, O] = v({}), l = g(() => {
    const n = T(F);
    Object.keys(n).forEach((m) => {
      e[m] = n[m];
    });
  }), t = g(() => {
    e.show = !1, setTimeout(() => {
      l();
    }, C);
  }), E = g((n) => {
    const { containerEl: m, checkFn: a, popup: d, messages: f, ...h } = T(n);
    typeof a == "function" && (e.checkFn = a), d !== void 0 && (e.popup = d), f !== void 0 && I(f), m !== void 0 && (e.containerEl = m), O(h), e.show = !0;
  }), y = s.useOAuth(), p = g(async ({ provider: n, action: m, extraParams: a, onLogin: d }) => {
    const f = await y.loginOAuth(
      { provider: n },
      {
        action: m,
        ...a
      }
    ), h = G({ returnDomain: !1 });
    A.remove("connected_did", h), A.remove("connected_pk", h), A.remove("connected_wallet_os", h), d(
      {
        ...f,
        encrypted: !1
      },
      (w) => w
    );
  });
  X(P, () => ({
    open: E,
    loginOAuth: p,
    close: t
  }), [E, t, p]);
  const u = /* @__PURE__ */ H(
    ce,
    {
      open: e.show,
      popup: e.popup,
      messages: c,
      checkFn: e.checkFn,
      ...i
    }
  );
  return e.containerEl ? j(u, e.containerEl) : e.show || o ? u : null;
}
function xe() {
  const P = B(null), _ = W(), s = R(() => {
    const o = { concurrency: 1 };
    return _.arcSphere && delete o.concurrency, new K(o);
  }), c = g((...o) => {
    P.current?.close(...o);
  }), I = g(
    ({ onSuccess: o, onClose: i, onEnd: O, closeTimeout: l = b, ...t }, ...E) => {
      const y = () => new Promise((p) => {
        typeof o == "function" ? t.onSuccess = (...u) => {
          o(...u), setTimeout(() => {
            c(), p();
          }, l);
        } : t.onSuccess = () => {
          setTimeout(() => {
            c(), p();
          }, l);
        }, typeof i == "function" ? t.onClose = (...u) => {
          i(...u), c(), p(), s.clear();
        } : t.onClose = () => {
          c(), p(), s.clear();
        }, setTimeout(() => {
          P.current?.open(t, ...E);
        }, 300);
      });
      s.add(y);
    }
  ), x = g(
    (o = {}, { baseUrl: i, locale: O = "en", blocklet: l = globalThis?.blocklet, closeTimeout: t = b, popupOptions: E } = {}) => new Promise((y, p) => {
      const u = () => new Promise((n) => {
        (async () => {
          if (J(i)) {
            const r = Y(), U = Z();
            i = r ? U.appUrl : window.location.origin;
          }
          const { onSuccess: a, onClose: d, onError: f, custom: h = !1, ...w } = o;
          if (!w?.extraParams?.provider)
            throw S(f) && f("Must have extraParams.provider"), new Error("Must have extraParams.provider");
          w?.prefix || (w.prefix = window.location.origin + k(l?.prefix, re));
          const D = {
            params: btoa(encodeURIComponent(JSON.stringify(w))),
            appPid: l?.appPid,
            locale: O,
            disableClose: !0
            // 弹窗模式默认不允许关闭 DID Connect
          }, L = ee(
            h ? M(k(i, w.prefix), D) : M(k(i || "/", se, "/connect"), D),
            E
          );
          try {
            const r = await oe({ popup: L, closeTimeout: t });
            ne(
              {
                connected_app: te(),
                ...r?.options
              },
              !0
            ), S(a) ? (a({ ...r.response, encrypted: !1 }), c(), n()) : (c(), n()), y({ ...r.response, encrypted: !1 });
          } catch (r) {
            throw console.error(r), r.message === "Popup closed" ? S(d) ? (d(), n(), s.clear()) : (n(), s.clear()) : S(f) && f(r), r;
          }
        })().catch((a) => {
          n(), p(a);
        });
      });
      s.add(u);
    })
  ), F = (o) => {
    P.current.loginOAuth(o);
  }, C = R(() => /* @__PURE__ */ H(ie, { ref: P })), e = R(() => ({
    open: I,
    close: c,
    loginOAuth: F,
    openPopup: x,
    queue: s
  }));
  return {
    connectHolder: C,
    connectApi: e
  };
}
export {
  xe as default
};
