import { jsx as l, jsxs as po } from "react/jsx-runtime";
import n from "prop-types";
import { Box as A } from "@mui/material";
import { LOGIN_PROVIDER as e, LOGIN_PROVIDER_ICON_SIZE as E, LOGIN_PROVIDER_NAME as uo } from "@arcblock/ux/lib/Util/constant";
import { checkSameProtocol as go, getWebWalletUrl as ho } from "@arcblock/ux/lib/Util/wallet";
import b from "lodash/noop";
import { useMemoizedFn as a, useCreation as fo } from "ahooks";
import O from "js-cookie";
import { detectWalletExtension as yo, getCookieOptions as Lo } from "@arcblock/ux/lib/Util";
import { useRef as w, useEffect as J } from "react";
import { mergeSx as Io } from "@arcblock/ux/lib/Util/style";
import Ao from "@arcblock/ux/lib/DIDConnect/provider-icon";
import { GA_LAST_LOGIN_METHOD as y } from "@arcblock/ux/lib/withTracker/constant";
import { translate as Eo } from "@arcblock/ux/lib/Locale/util";
import bo from "@arcblock/ux/lib/Empty";
import { useBrowser as xo } from "@arcblock/react-hooks";
import Co from "./mobile-login-item.js";
import Po from "./web-login-item.js";
import Mo from "./login-method-item.js";
import vo from "./wallet-login-options.js";
import { useOAuth as _o } from "../../../OAuth/context.js";
import { useStateContext as Oo } from "../../contexts/state.js";
import { getAppId as wo, logger as Wo, getApiErrorMessage as To } from "../../../utils.js";
import ko from "./passkey-login-item.js";
import { usePasskey as So } from "../../../Passkey/context.js";
import "../../../Passkey/actions.js";
import Ro from "../../plugins/email/index.js";
import jo from "../../assets/locale.js";
function No({
  onSuccess: W = b,
  onError: T = b,
  size: m = "small",
  tokenState: t,
  webWalletUrl: x = ho(),
  tokenKey: k,
  passkeyBehavior: S = "none",
  onReset: C = b,
  providerList: p = [],
  slotProps: X = {},
  disableSwitchApp: P = !1,
  forceUpdate: z = b,
  magicToken: R = void 0,
  baseUrl: Q = "/",
  customItems: oo = [],
  qrcode: eo = null,
  hideQRCode: d = !1
}) {
  const M = w(null), v = w(null), j = w(null), no = go(x), N = yo(), u = xo(), { loginOAuth: to, logoutOAuth: ro, t: io, oauthState: s } = _o(), { passkeyState: D } = So(), {
    extraParams: F,
    locale: B,
    connectState: i,
    plugins: G,
    setPlugins: lo,
    setSelectedPlugin: so,
    getPlugin: U,
    showWalletOptions: f,
    setShowWalletOptions: L,
    lastLoginMethod: g
  } = Oo(), I = a((o, r = {}) => Eo(jo, o, B, "en", r)), q = a(async (o) => {
    localStorage.setItem(y, o.provider), t.reset(), s.reset({
      status: "scanned"
    }), D.reset(), i.chooseMethod = o.provider;
    const r = F?.sourceAppPid;
    try {
      s.loading = !0, s.status = "scanned";
      const c = await to(o, {
        action: t.action,
        ...F
      }), h = Lo({ returnDomain: !1 });
      O.remove("connected_did", h), O.remove("connected_pk", h), O.remove("connected_wallet_os", h), c?.sessionToken && (await W(
        {
          ...c,
          encrypted: !1
        },
        (mo) => mo,
        {
          sourceAppPid: r,
          connected_app: wo(t.appInfo, t.memberAppInfo)
        }
      ), s.loading = !1, s.status = "succeed");
    } catch (c) {
      Wo.error(`Failed login OAuth: ${o.provider}`, c);
      const h = To(c, io("loginOAuthFailed"));
      s.loading = !1, s.error = h, s.status = "error", await ro({ provider: o.provider }), T(new Error(h));
    }
  }), K = a(async () => {
    t.reset(), await C(), t.status = "created", i.chooseMethod = "wallet";
  }), V = a(async () => {
    localStorage.setItem(y, e.WALLET), t.reset(), await C(), t.status = "created", i.chooseMethod = "wallet";
    const o = M.current?.connect;
    i.retryConnect = () => {
      o(K);
    };
  }), Y = a(() => {
    localStorage.setItem(y, e.WALLET), t.status = "scanned", i.chooseMethod = "wallet-web";
    const o = v.current.connect;
    i.retryConnect = async () => {
      await C(), t.error = "", t.status = "scanned", o();
    };
  }), co = a(() => {
    L(!1);
  }), _ = fo(() => p.length === 1 && p[0].provider === e.WALLET, [p]);
  J(() => {
    d && _ && !u.mobile.any && !f && L(!0);
  }, [d, _, u.mobile.any, L, f]);
  const H = p.some((o) => o.provider === e.EMAIL), Z = Ro({ baseUrl: Q }), ao = a(() => {
    if (R && p.some((o) => o.name === e.EMAIL) && G.some((o) => o.name === e.EMAIL)) {
      const o = U(e.EMAIL);
      o.state.status === "idle" && (localStorage.setItem(y, e.EMAIL), o.state.reset(), o.state.magicToken = R, i.chooseMethod = e.EMAIL, so(o), z());
    }
  });
  J(() => {
    const o = [];
    if (H) {
      const r = U(e.EMAIL);
      r && r.baseUrl === Z.baseUrl ? o.push(r) : o.push(Z);
    }
    lo(o), i.retryConnect = K, setTimeout(() => {
      ao();
    }, 100);
  }, [H]);
  const $ = p.map((o) => {
    if (o.provider === e.WALLET)
      return u.mobile.any && !f ? /* @__PURE__ */ l(
        Co,
        {
          t: I,
          isLatest: g && g === e.WALLET,
          ref: M,
          tokenState: t,
          sx: [m === "small" ? { p: 1 } : { p: 2 }],
          locale: B,
          tokenKey: k,
          disableSwitchApp: P,
          onClick: V
        },
        e.WALLET
      ) : d || !d && (no || N) && (!u.mobile.any || N) ? /* @__PURE__ */ l(
        Po,
        {
          t: I,
          isLatest: g && g === e.WALLET,
          ref: v,
          tokenState: t,
          webWalletUrl: x,
          sx: [m === "small" ? { p: 1 } : { p: 2 }],
          disableSwitchApp: P,
          autoConnect: !d,
          onClick: () => {
            d ? L(!0) : Y();
          }
        },
        e.WALLET
      ) : null;
    if (o.provider === e.PASSKEY)
      return S === "none" ? null : /* @__PURE__ */ l(
        ko,
        {
          ref: j,
          onSuccess: W,
          onError: T,
          tokenState: t,
          behavior: S,
          sx: [m === "small" ? { p: 1 } : { p: 2 }],
          onClick: () => {
            localStorage.setItem(y, e.PASSKEY);
            const r = j.current.connect;
            i.chooseMethod = "passkey", i.retryConnect = () => {
              D.verifying = !0, i.chooseMethod = "passkey", r();
            };
          },
          slotProps: {
            icon: {
              sx: {
                fontSize: E,
                "& svg": {
                  fontSize: E,
                  width: "1em",
                  height: "1em"
                }
              }
            }
          }
        },
        e.PASSKEY
      );
    if (o.provider === e.EMAIL) {
      const r = G.find((c) => c.name === e.EMAIL);
      return r ? r?.renderListItem({
        key: r.name,
        sx: [m === "small" ? { p: 1 } : { p: 2 }]
        // forceUpdate,
      }) : null;
    }
    return o.type === "oauth" ? /* @__PURE__ */ l(
      Mo,
      {
        t: I,
        isLatest: g && g === o.provider,
        title: uo[o.provider],
        icon: /* @__PURE__ */ l(
          Ao,
          {
            provider: o.provider,
            sx: {
              transform: "scale(0.95)",
              width: E,
              height: E,
              color: "text.primary"
            }
          }
        ),
        onClick: () => {
          q(o), i.retryConnect = () => {
            q(o);
          };
        },
        sx: [m === "small" ? { p: 1.2 } : { p: 2 }]
      },
      o.provider
    ) : null;
  }).filter(Boolean);
  return /* @__PURE__ */ l(A, { className: "did-connect__choose", sx: Io({ flex: 1 }, X?.root?.sx), children: /* @__PURE__ */ l(
    A,
    {
      sx: {
        display: "flex",
        flexDirection: "column",
        gap: 2
      },
      children: /* @__PURE__ */ po(
        A,
        {
          sx: [
            {
              display: "flex",
              flexDirection: "column",
              ...f && !u.mobile.any ? { alignItems: "center", gap: 0 } : { gap: 1.5 }
            }
          ],
          children: [
            f && !u.mobile.any ? /* @__PURE__ */ l(
              vo,
              {
                qrcode: eo,
                tokenState: t,
                webWalletUrl: x,
                size: m,
                disableSwitchApp: P,
                tokenKey: k,
                walletLoginRef: M,
                webLoginRef: v,
                onMobileLoginClick: V,
                onWebLoginClick: Y,
                onBack: _ ? void 0 : co
              }
            ) : /* @__PURE__ */ l(
              A,
              {
                sx: {
                  display: "grid",
                  gridTemplateColumns: "repeat(12, 1fr)",
                  gap: 1.5,
                  ".arc-login-item:nth-child(-n+3)": {
                    gridColumn: "span 12"
                  },
                  // 当登录项大于等于 5 时，第三个登录项增加一个 marginBottom，用于分割独占一行的和一行多个的登录项
                  ".arc-login-item:nth-child(3):nth-last-child(n+3)": {
                    mb: 1
                  },
                  ".arc-login-item:nth-child(4):last-child": {
                    gridColumn: "span 12"
                  },
                  ".arc-login-item:nth-child(4):nth-last-child(2), .arc-login-item:nth-child(4):nth-last-child(2), .arc-login-item:nth-child(4):nth-last-child(2) ~ .arc-login-item": {
                    gridColumn: "span 6",
                    justifyContent: "center",
                    ".arc-login-item__body, .other-item-icon": {
                      display: "none"
                    }
                  },
                  ".arc-login-item:nth-child(4):nth-last-child(3), .arc-login-item:nth-child(4):nth-last-child(3) ~ .arc-login-item": {
                    justifyContent: "center",
                    gridColumn: "span 4",
                    ".arc-login-item__body, .other-item-icon": {
                      display: "none"
                    }
                  },
                  ".arc-login-item:nth-child(4):nth-last-child(4), .arc-login-item:nth-child(4):nth-last-child(4) ~ .arc-login-item": {
                    gridColumn: "span 3",
                    justifyContent: "center",
                    ".arc-login-item__body, .other-item-icon": {
                      display: "none"
                    }
                  },
                  "&:has(.arc-login-item:nth-child(8)) .arc-login-item:nth-child(n+4)": {
                    gridColumn: "span 3",
                    justifyContent: "center",
                    ".arc-login-item__body, .other-item-icon": {
                      display: "none"
                    }
                  }
                },
                children: $.length > 0 ? $ : /* @__PURE__ */ l(
                  bo,
                  {
                    className: "arc-login-item",
                    sx: {
                      ".empty-content": {
                        textAlign: "center"
                      }
                    },
                    children: I("noAuthenticationProvider")
                  }
                )
              }
            ),
            oo.map((o) => o || null)
          ]
        }
      )
    }
  ) });
}
No.propTypes = {
  onSuccess: n.func,
  onError: n.func,
  size: n.oneOf(["small", "normal", "large"]),
  tokenState: n.object.isRequired,
  webWalletUrl: n.string,
  tokenKey: n.string.isRequired,
  passkeyBehavior: n.oneOf(["none", "both", "only-existing", "only-new"]),
  onReset: n.func,
  providerList: n.array,
  slotProps: n.object,
  disableSwitchApp: n.bool,
  forceUpdate: n.func,
  magicToken: n.string,
  baseUrl: n.string,
  customItems: n.arrayOf(n.node),
  qrcode: n.node,
  hideQRCode: n.bool
};
export {
  No as default
};
