import { jsxs as q, Fragment as D, jsx as n } from "react/jsx-runtime";
import { useRef as I, useEffect as L, useImperativeHandle as M } from "react";
import z from "lodash/trim";
import e from "prop-types";
import k from "js-cookie";
import { CircularProgress as B } from "@mui/material";
import { Icon as S } from "@iconify/react";
import { getCookieOptions as H } from "@arcblock/ux/lib/Util";
import { useMemoizedFn as v } from "ahooks";
import V from "@iconify-icons/material-symbols/passkey-rounded";
import $ from "@iconify-icons/material-symbols/person-add-rounded";
import G from "lodash/noop";
import { mergeSx as K } from "@arcblock/ux/lib/Util/style";
import { usePasskey as N } from "./context.js";
import { logger as W, getWebAuthnErrorMessage as Y } from "../utils.js";
import J from "../Connect/components/login-item/login-method-item.js";
import Q from "./dialog.js";
import { VERIFY_CODE_LENGTH as w } from "./constants.js";
function x({ action: d, onClick: c, title: s, state: f, dense: l = !1, icon: u, ...m }) {
  return /* @__PURE__ */ n(
    J,
    {
      ...m,
      icon: f[d] ? /* @__PURE__ */ n(
        B,
        {
          size: "1em",
          sx: {
            color: "inherit",
            "& svg": {
              transform: "scale(0.75)"
            }
          }
        }
      ) : u,
      iconScale: 1,
      title: s,
      onClick: c,
      sx: K(l ? { p: 1, backgroundColor: "transparent" } : {}, m?.sx)
    }
  );
}
x.propTypes = {
  action: e.string.isRequired,
  onClick: e.func.isRequired,
  title: e.string.isRequired,
  state: e.object.isRequired,
  dense: e.bool,
  icon: e.any.isRequired
};
function U({
  ref: d = null,
  action: c,
  behavior: s = "none",
  onSuccess: f,
  onError: l,
  extraParams: u = {},
  createButtonText: m = "",
  createMode: T = "register",
  dense: P = !1,
  slotProps: R = {},
  sx: b = {},
  mode: h = "normal",
  onClick: E = G,
  isLatest: j = !1
}) {
  const p = I(""), C = I(null), { t: i, loginPasskey: O, logoutPasskey: _, passkeyState: o } = N(), A = v(async (a = "") => {
    try {
      o.verifying = !0, o.error = "", a || (o.verifyingStatus = "");
      const r = await O({
        ...u,
        action: c,
        credentialId: a
      }), t = H({ expireInDays: 7 });
      k.remove("connected_did", t), k.remove("connected_pk", t), k.remove("connected_wallet_os", t), o.verifying = !1, r?.sessionToken && (await f({ ...r, encrypted: !1 }, (F) => F), o.verifyingStatus = "succeed");
    } catch (r) {
      W.error("Failed to verify passkey", r);
      const t = Y(r, i("verifyPasskeyFailed"), i);
      o.verifying = !1, o.error = t, o.verifyingStatus = "error", await _(), l(new Error(t));
    }
  }), y = v(
    (a) => {
      if (!o.sent) return;
      a.preventDefault();
      const r = z(a.clipboardData.getData("text/plain").slice(0, w));
      if (!/^\d+$/.test(r)) return;
      o.code = r.padEnd(w, " ");
      const t = document.getElementById(`code-input-${r.length}`);
      t && t.focus();
    },
    [o]
  );
  L(() => (document.addEventListener("paste", y), () => {
    document.removeEventListener("paste", y);
  }), [y]);
  const g = v(() => {
    p.current === "verifying" ? A() : p.current === "creating" && C.current.open();
  });
  return M(d, () => ({
    click: g
  })), s === "none" ? null : /* @__PURE__ */ q(D, { children: [
    ["both", "only-existing"].includes(s) ? /* @__PURE__ */ n(
      x,
      {
        isLatest: j,
        t: i,
        action: "verifying",
        state: o,
        title: i("usePasskey"),
        onClick: () => {
          p.current = "verifying", g(), E();
        },
        dense: P,
        slotProps: R,
        sx: b,
        mode: h,
        icon: /* @__PURE__ */ n(S, { icon: V, fontSize: "1em" })
      }
    ) : null,
    ["both", "only-new"].includes(s) ? /* @__PURE__ */ q(D, { children: [
      /* @__PURE__ */ n(
        x,
        {
          t: i,
          action: "creating",
          state: o,
          title: m || i("createPasskey"),
          onClick: () => {
            p.current = "creating", g(), E();
          },
          dense: P,
          slotProps: R,
          sx: b,
          mode: h,
          icon: /* @__PURE__ */ n(S, { icon: $, fontSize: "1em" })
        }
      ),
      /* @__PURE__ */ n(
        Q,
        {
          ref: C,
          action: c,
          createMode: T,
          extraParams: u,
          onSuccess: f,
          onError: l
        }
      )
    ] }) : null
  ] });
}
U.propTypes = {
  action: e.string.isRequired,
  onSuccess: e.func.isRequired,
  onError: e.func.isRequired,
  behavior: e.oneOf(["none", "both", "only-existing", "only-new"]),
  createButtonText: e.string,
  createMode: e.string,
  extraParams: e.object,
  dense: e.bool,
  slotProps: e.object,
  sx: e.oneOfType([e.object, e.array]),
  mode: e.oneOf(["simple", "normal"]),
  onClick: e.func,
  ref: e.any,
  isLatest: e.bool
};
export {
  U as default
};
