import { jsx as t, jsxs as b, Fragment as He } from "react/jsx-runtime";
import { use as Ve, useRef as ce, useState as Ye, useEffect as le } from "react";
import e from "prop-types";
import { Box as i, Skeleton as Ge, Divider as Ke } from "@mui/material";
import { useUpdate as Qe, useSize as Xe, useCreation as u, useMount as ue, useMemoizedFn as F, useDebounceFn as Je, usePrevious as Ze, useUpdateEffect as $e } from "ahooks";
import C from "lodash/noop";
import et from "lodash/isUndefined";
import tt from "@arcblock/ux/lib/CloseButton";
import { DID_CONNECT_MEDIUM_WIDTH as N, LOGIN_PROVIDER_NAME as ot, DID_CONNECT_SMALL_WIDTH as rt, OAUTH_PROVIDER as j, LOGIN_PROVIDER as nt } from "@arcblock/ux/lib/Util/constant";
import it from "@arcblock/ux/lib/QRCode";
import { DIDConnectFooter as st } from "@arcblock/ux/lib/DIDConnect";
import { useTheme as at } from "@arcblock/ux/lib/Theme";
import ct from "@arcblock/ux/lib/DIDConnect/provider-icon";
import "@fontsource/lexend/400.css";
import "@fontsource/lexend/600.css";
import { SessionContext as lt } from "../Session/context.js";
import { StateProvider as ut, useStateContext as dt } from "./contexts/state.js";
import ft from "./components/login-item/connect-provider-list.js";
import mt from "./components/auto-height.js";
import pt from "./hooks/token.js";
import { useOAuth as ht } from "../OAuth/context.js";
import bt from "./components/connect-status.js";
import { usePasskey as gt } from "../Passkey/context.js";
import { CHECK_STATUS_INTERVAL as xt, API_DID_PREFIX as Ct, BUSY_STATUS as w, DEFAULT_TIMEOUT as yt } from "../constant.js";
import "../utils.js";
import St from "./components/did-connect-title.js";
import kt from "./components/download-tips.js";
import wt from "./hooks/provider-list.js";
import It from "./hooks/auth-url.js";
import { getWalletDid as vt } from "../User/use-did.js";
import Pt from "./fallback-connect.js";
import { getWebWalletUrl as _t } from "@arcblock/ux/lib/Util/wallet";
function de({
  hideCloseButton: y = !1,
  mode: p = "dialog",
  action: I,
  baseUrl: g = "",
  checkFn: v,
  checkInterval: P = xt,
  checkTimeout: _ = yt * 1e3,
  prefix: D = Ct,
  tokenKey: B = "_t_",
  locale: q = "en",
  encKey: fe = "_ek_",
  autoConnect: me = !0,
  forceConnected: H = !0,
  saveConnect: pe = !0,
  useSocket: he = !0,
  allowWallet: V = !0,
  provider: be = "",
  messages: d = {},
  passkeyBehavior: Y = "none",
  webWalletUrl: ge = _t(),
  enabledConnectTypes: xe = ["web", "mobile", ...Object.keys(j)],
  extraContent: G = null,
  disableSwitchApp: T = !1,
  magicToken: K = void 0,
  customItems: Ce = [],
  onClose: O = C,
  onError: Q = C,
  onSuccess: R = C,
  onRecreateSession: X = C,
  setColor: ye = C
}) {
  const A = at(), J = Qe(), Se = Ve(lt), ke = vt(Se?.session?.user), {
    t: Z,
    staticState: we,
    connectState: s,
    extraParams: Ie,
    currentAppInfo: ve,
    currentAppColor: W,
    // 插件相关
    selectedPlugin: a,
    blocklet: $,
    masterBlocklet: Pe,
    showWalletOptions: f,
    setShowWalletOptions: _e,
    lastLoginMethod: De
  } = dt(), { state: o, generate: ee, cancelWhenScanned: Te } = pt({
    action: I,
    baseUrl: g,
    checkFn: v,
    checkInterval: P,
    checkTimeout: _,
    extraParams: Ie,
    prefix: D,
    onError: Q,
    onSuccess: R,
    locale: q,
    tokenKey: B,
    encKey: fe,
    autoConnect: me,
    forceConnected: H === !0 ? ke || !0 : H,
    saveConnect: pe,
    useSocket: he,
    provider: be
  }), z = ce(!1), te = ce(null), x = Xe(te), oe = u(() => x ? x.width < N - 50 : !0, [x, x?.width]), [re, Oe] = Ye(!1);
  ue(() => {
    Oe(x?.width < N - 50);
  });
  const { oauthState: c, setBaseUrl: Re } = ht(), { passkeyState: l, setTargetAppPid: Ae } = gt();
  ue(() => {
    Re(g), Ae($?.appPid), o.reset(), c.reset(), l.reset();
  }), le(() => {
    ye(W);
  }, [W]);
  const We = u(() => ({
    confirm: d.confirm,
    success: d.success,
    error: a?.state?.error || o.error || l.error || c.error || ""
  }), [
    d.confirm,
    d.success,
    o.error,
    c.error,
    l.error,
    a?.state?.error
  ]), S = u(() => w.includes(l.status) || w.includes(c.status) || w.includes(o.status) || w.includes(a?.state?.computedStatus), [o.status, c.status, l.status, a?.state?.computedStatus]), ne = F(async () => {
    X(), c.reset(), l.reset(), await ee(!1);
  }), ze = F(() => {
    s?.retryConnect();
  }), Ee = F(() => {
    X(), c.reset(), l.reset(), a?.state?.reset(), we.current.cancelCount++, Te();
  }), { run: Le } = Je(
    () => {
      z.current || o.status === "timeout" && (z.current = !0, o.reset(), ne(), z.current = !1);
    },
    { leading: !0, trailing: !1 }
  );
  le(Le, [o.status]);
  const Me = u(() => ot[s.chooseMethod] || "DID Wallet", [s.chooseMethod]), { providerList: Ue, hideQRCode: m, hideChooseList: r, loadingProviderList: Fe } = wt({
    action: o.action,
    sourceAppPid: s?.sourceAppPid,
    allowWallet: V,
    passkeyBehavior: Y,
    mode: p,
    blocklet: s?.sourceAppPid ? Pe : $,
    isSmallView: oe,
    lastLoginMethod: De
  }), Ne = Ze(s?.sourceAppPid);
  $e(() => {
    et(Ne) || ee();
  }, [s?.sourceAppPid]);
  const n = (k) => {
    const h = A.spacing(k);
    return parseInt(h, 10);
  }, je = u(() => y ? null : /* @__PURE__ */ t(
    tt,
    {
      onClose: O,
      sx: {
        position: "absolute",
        right: 14,
        top: 14
      }
    }
  ), [y, O]), Be = /* @__PURE__ */ t(
    i,
    {
      sx: {
        flex: 1,
        display: S ? "flex" : "none",
        alignItems: "center",
        justifyContent: "center"
      },
      children: /* @__PURE__ */ t(i, { children: /* @__PURE__ */ t(
        bt,
        {
          status: a?.state?.computedStatus || c.status || l.status || o.status,
          nextWorkflow: o.nextWorkflow,
          mfaCode: o.mfaCode,
          onCancel: Ee,
          onRetry: ze,
          onClose: O,
          messages: We,
          locale: q,
          className: "did-connect__auth-status auth-status",
          loadingIcon: s.chooseMethod ? /* @__PURE__ */ t(ct, { provider: s.chooseMethod, sx: { color: "text.primary" } }) : null,
          chooseMethod: Me,
          hideRetry: s.chooseMethod === "email",
          hideBack: !!K
        }
      ) })
    }
  ), ie = It({ disableSwitchApp: T, tokenState: o }), E = u(() => {
    const k = A.mode === "dark" ? A.palette.grey[600] : "white";
    let h = r ? 240 - n(3) * 2 : 196 - n(2) * 2, U = r ? 3 : 2;
    return f && (U = 1, h += n(U) * 2), /* @__PURE__ */ t(
      i,
      {
        className: "did-connect__qrcode",
        sx: {
          p: U,
          width: (r ? 240 : 196) + n(1) * 2,
          height: (r ? 240 : 196) + n(1) * 2
        },
        children: o.url ? /* @__PURE__ */ t(
          it,
          {
            data: ie,
            size: h,
            sx: {
              width: h + n(1) * 2,
              height: h + n(1) * 2,
              flex: 1,
              backgroundColor: k,
              p: 1,
              fontSize: 0,
              textAlign: "center",
              boxSizing: "border-box",
              borderRadius: 1,
              border: "1px solid",
              borderColor: "divider"
            },
            config: {
              backgroundOptions: {
                color: k
              }
            }
          }
        ) : /* @__PURE__ */ t(
          Ge,
          {
            animation: "wave",
            variant: "rectangular",
            sx: {
              position: "absolute",
              left: n(2) + 1,
              right: n(2) + 1,
              top: n(2) + 1,
              bottom: n(2) + 1,
              borderRadius: 1,
              zIndex: 1,
              width: "auto",
              height: "auto"
            }
          }
        )
      }
    );
  }, [ie, r, f]), qe = u(() => r ? "column-reverse" : !m && re ? "column" : "row", [r, re, m]), se = u(() => E ? /* @__PURE__ */ t(
    i,
    {
      sx: {
        display: "flex",
        alignItems: "center",
        overflowX: "auto",
        overflowY: "visible",
        maxWidth: "100%",
        margin: "auto"
      },
      children: /* @__PURE__ */ b(
        i,
        {
          sx: {
            fontSize: 0,
            position: "relative",
            ...f ? {
              mt: r ? 4 : 2.5,
              mb: 0
            } : {
              mb: r ? 4 : 2.5,
              mt: 0
            }
          },
          children: [
            E,
            /* @__PURE__ */ b(
              i,
              {
                sx: {
                  position: "absolute",
                  color: "text.secondary",
                  fontSize: 12,
                  zIndex: 1,
                  whiteSpace: "nowrap",
                  ...f ? {
                    top: r ? -8 : -4,
                    transform: "translateY(-100%)"
                  } : {
                    bottom: r ? -8 : -4,
                    transform: "translateY(100%)"
                  },
                  left: 0,
                  right: 0,
                  textAlign: "center"
                },
                children: [
                  Z("scanWithWallet1"),
                  " ",
                  /* @__PURE__ */ t(kt, {}),
                  " ",
                  Z("scanWithWallet2")
                ]
              }
            )
          ]
        }
      )
    }
  ) : null, [E, r, f]), L = /* @__PURE__ */ b(
    i,
    {
      className: "did-connect__body",
      sx: {
        display: "flex",
        flexDirection: qe,
        justifyContent: "center",
        alignItems: "stretch",
        flex: 1,
        gap: !m && oe ? 0 : 1.5,
        overflow: "visible",
        px: r ? 2 : 0
      },
      children: [
        !S && !m ? /* @__PURE__ */ b(He, { children: [
          se,
          r ? null : /* @__PURE__ */ t(i, { children: /* @__PURE__ */ t(
            Ke,
            {
              orientation: "vertical",
              sx: {
                fontSize: 12,
                color: "text.hint",
                "&::before, &::after": {
                  borderColor: "divider"
                }
              },
              children: "or"
            }
          ) })
        ] }) : null,
        /* @__PURE__ */ b(
          i,
          {
            sx: {
              display: "flex",
              flex: 1
            },
            children: [
              Be,
              /* @__PURE__ */ t(
                ft,
                {
                  slotProps: {
                    root: {
                      sx: [S ? { display: "none" } : {}]
                    }
                  },
                  allowWallet: V,
                  size: m && p !== "dialog" ? "normal" : "small",
                  tokenState: o,
                  hideQRCode: m,
                  messages: d,
                  tokenKey: B,
                  onSuccess: R,
                  passkeyBehavior: Y,
                  webWalletUrl: ge,
                  extraContent: G,
                  enabledConnectTypes: xe,
                  onReset: ne,
                  disableSwitchApp: T,
                  forceUpdate: J,
                  magicToken: K,
                  baseUrl: g,
                  customItems: Ce,
                  providerList: Ue,
                  qrcode: se
                }
              )
            ]
          }
        )
      ]
    }
  );
  let M = L;
  a ? M = a.renderPlaceholder({
    fallback: L,
    forceUpdate: J,
    onSuccess: R,
    onError: Q
  }) : M = L;
  const ae = m || S ? rt : N;
  return Fe ? /* @__PURE__ */ t(Pt, {}) : /* @__PURE__ */ b(
    i,
    {
      ref: te,
      className: "did-connect__root",
      sx: {
        backgroundColor: "background.default",
        display: "flex",
        flexDirection: "column",
        height: "100%",
        position: "relative",
        maxWidth: "100%",
        width: (
          // eslint-disable-next-line no-nested-ternary
          p === "drawer" ? "100%" : f ? ae - 20 : ae
        ),
        transition: "width 0.2s ease-in-out",
        margin: "auto",
        p: 3,
        pb: 0,
        gap: 2.5
      },
      children: [
        /* @__PURE__ */ t(i, { "data-did-auth-url": o.url, sx: { display: "none" } }),
        /* @__PURE__ */ t(
          St,
          {
            title: d.title,
            description: d.scan,
            extraContent: G,
            disableSwitchApp: T,
            showWalletOptions: f,
            onBack: () => _e(!1)
          }
        ),
        /* @__PURE__ */ t(mt, { initHeight: 72, children: M }),
        /* @__PURE__ */ t(st, { currentAppInfo: ve, currentAppColor: W }),
        je
      ]
    }
  );
}
de.propTypes = {
  mode: e.oneOf(["dialog", "drawer", "page"]),
  action: e.string.isRequired,
  baseUrl: e.string,
  checkFn: e.func.isRequired,
  checkInterval: e.number,
  checkTimeout: e.number,
  // extraParams: PropTypes.object, // 需要使用 useStateContext 中导出的
  prefix: e.string,
  messages: e.object,
  tokenKey: e.string,
  locale: e.oneOf(["en", "zh", ""]),
  encKey: e.string,
  autoConnect: e.bool,
  forceConnected: e.oneOfType([e.bool, e.string]),
  saveConnect: e.bool,
  useSocket: e.bool,
  extraContent: e.any,
  passkeyBehavior: e.oneOf(["none", "both", "only-existing", "only-new"]),
  enabledConnectTypes: e.arrayOf(e.oneOf(["web", "mobile", ...Object.keys(j)])),
  webWalletUrl: e.string,
  allowWallet: e.bool,
  provider: e.oneOf([nt.WALLET, ...Object.keys(j), ""]),
  hideCloseButton: e.bool,
  disableSwitchApp: e.bool,
  onClose: e.func,
  onError: e.func,
  onSuccess: e.func,
  onRecreateSession: e.func,
  setColor: e.func,
  magicToken: e.string,
  customItems: e.arrayOf(e.node)
};
function Dt({ testOnlyBorderColor: y = void 0, ...p }) {
  const { checkFn: I, extraParams: g = {}, blocklet: v, masterBlocklet: P, action: _, locale: D = "en" } = p;
  if (typeof I != "function")
    throw new Error("Cannot initialize did connect component without a fetchFn");
  return /* @__PURE__ */ t(
    ut,
    {
      blocklet: v,
      masterBlocklet: P,
      action: _,
      locale: D,
      extraParams: g,
      testOnlyBorderColor: y,
      sx: {
        position: "relative",
        width: "100%",
        height: "100%",
        lineHeight: 1.2,
        color: "grey.700",
        "&, & *, & *:before, & *:after": {
          fontFamily: "Lexend",
          // 保持跟 DID Wallet 一致
          boxSizing: "border-box"
        }
      },
      children: /* @__PURE__ */ t(de, { ...p })
    }
  );
}
Dt.propTypes = {
  checkFn: e.func.isRequired,
  extraParams: e.object,
  blocklet: e.object.isRequired,
  masterBlocklet: e.object,
  action: e.string.isRequired,
  locale: e.string,
  testOnlyBorderColor: e.string
};
export {
  Dt as default
};
