import { Buffer as a } from "buffer";
import h from "tweetnacl-sealedbox-js";
import { isUrl as U, getCookieOptions as A, getVisitorId as E } from "@arcblock/ux/lib/Util";
import { getVisitorId as Ue, setVisitorId as Ae } from "@arcblock/ux/lib/Util";
import c from "js-cookie";
import l from "lodash/isNil";
import T from "lodash/isString";
import m from "lodash/isUndefined";
import { createAxios as P, getBlockletSDK as x } from "@blocklet/js-sdk";
import { withQuery as L } from "ufo";
import { isValid as w, isFromPublicKey as S } from "@arcblock/did";
import { getSafeUrl as C } from "@arcblock/ux/lib/Util/security";
import { createDebug as u, createLogger as I } from "@arcblock/ux/lib/Util/logger";
import N from "./package.json.js";
import { DID_CONNECT_URL_PARAMS_NAME as f, DEFAULT_WINDOW_TIMEOUT as D } from "./constant.js";
import { NotOpenError as W } from "./error.js";
export * from "@arcblock/ux/lib/Util/wallet";
const { version: O } = N, re = u("did-connect"), oe = u("did-connect:tmp"), te = u("did-connect:tmp-interval"), ne = I("did-connect");
function b(e) {
  return (e + "===".slice((e.length + 3) % 4)).replace(/-/g, "+").replace(/_/g, "/");
}
function _(e) {
  return e.replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, "");
}
const se = (e) => _(window.btoa(e)), ie = (e) => window.atob(b(e)), ae = (e) => {
  const o = new URL(e), r = decodeURIComponent(o.searchParams.get("url"));
  return new URL(r).searchParams.get("_t_");
}, R = (e, o) => {
  let r = o?.publisher;
  if (!r) {
    if (e?.agentDid)
      return e.agentDid;
    r = e?.publisher;
  }
  return r ? r.replace("did:abt:", "") : globalThis.blocklet?.appPid || globalThis.blocklet?.appId || globalThis.env?.appId || "";
}, z = (e) => {
  const o = {
    connected_did: e.did || "",
    connected_pk: e.pk || "",
    connected_app: R(e.appInfo, e.memberAppInfo)
  };
  return e?.connectedWallet?.os && (o.connected_wallet_os = e.connectedWallet.os), o;
}, ce = (e, o = !1) => {
  if (!e) return;
  o || (e = z(e));
  const r = A({
    expireInDays: 7,
    returnDomain: !1
  });
  !l(e.connected_did) && !l(e.connected_pk) && w(e.connected_did) && S(e.connected_did, e.connected_pk) && (c.set("connected_did", e.connected_did, r), c.set("connected_pk", e.connected_pk, r)), !l(e.connected_app) && w(e.connected_app) && c.set("connected_app", e.connected_app, r), e.connected_wallet_os && c.set("connected_wallet_os", e.connected_wallet_os, r);
}, pe = (e) => _(a.from(e).toString("base64")), d = (e) => Uint8Array.from(a.from(b(e), "base64")), le = (e, o, r) => {
  const t = h.open(
    Uint8Array.from(a.from(e, "base64")),
    d(o),
    d(r)
  );
  return JSON.parse(a.from(t).toString("utf8"));
}, de = (e, o) => a.from(h.seal(Uint8Array.from(a.from(e)), d(o))).toString("base64"), ue = (e, o = "_t_") => {
  const r = new URL(e), t = {
    baseUrl: r.origin,
    prefix: r.pathname.replace(/\/auth$/, ""),
    token: r.searchParams.get(o) || ""
  };
  if (!t.baseUrl)
    throw new Error("Invalid next workflow: origin empty");
  if (!t.token)
    throw new Error("Invalid next workflow: token not found");
  return t;
}, g = (e, o) => {
  let r = e.message;
  const { response: t } = e;
  return t && (r = t.data?.error || t.data?.message || t.data || o, r = typeof r == "object" ? o : r), r;
}, me = (e, o, r) => {
  if (!e)
    return e;
  if (!e.name)
    return g(e, o);
  switch (e.name) {
    case "NotAllowedError":
      return r ? r("webauthn.error.canceled") : "Authentication was canceled";
    case "SecurityError":
      return r ? r("webauthn.error.security") : "A security error occurred during authentication";
    case "NotSupportedError":
      return r ? r("webauthn.error.notSupported") : "This browser does not support passkey authentication";
    case "AbortError":
      return r ? r("webauthn.error.aborted") : "Authentication was aborted";
    default:
      return console.warn("Unhandled WebAuthn error type:", e.name), g(e, o);
  }
}, M = (e) => {
  const o = {}, r = U(e) ? e : window.location.href;
  if (r) {
    const { hostname: t, protocol: n, port: s } = new URL(r);
    o["x-real-hostname"] = t, o["x-real-port"] = s, o["x-real-protocol"] = n.endsWith(":") ? n.substring(0, n.length - 1) : n;
  }
  return o;
}, we = (e = {}, { lazy: o = !1, lazyTime: r = 300 } = {}) => {
  const t = {
    ...M(e.baseURL),
    ...e.headers,
    "x-did-connect-version": O
  }, n = P(
    {
      ...e,
      headers: t
    },
    { lazy: o, lazyTime: r }
  );
  return n.interceptors.request.use((s) => {
    const i = E();
    return i && (s.headers["x-blocklet-visitor-id"] = i), s;
  }), n;
}, fe = (e = 0) => new Promise((o) => {
  setTimeout(() => {
    o();
  }, e);
});
function ge() {
  if (typeof window > "u")
    return null;
  const e = window.navigator.languages && window.navigator.languages[0] || window.navigator.language || window.navigator.browserLanguage || window.navigator.userLanguage || window.navigator.systemLanguage || null;
  return {
    "zh-CN": "zh",
    "zh-TW": "zh",
    zh: "zh",
    en: "en"
  }[e] || "en";
}
function he(e, o) {
  return [void 0, null, ""].includes(e) ? o : e / 86400;
}
async function be() {
  const e = window.location.href;
  try {
    const o = new URL(e), r = o.searchParams.get(f);
    if (r) {
      o.searchParams.delete(f);
      const t = JSON.parse(a.from(r, "base64").toString("utf-8"));
      if (T(t.forceConnected) && m(t.sourceAppPid)) {
        const s = await x().user.getUserPublicInfo({ did: t.forceConnected });
        m(s?.sourceAppPid) || (t.sourceAppPid = s.sourceAppPid);
      }
      return {
        params: t,
        url: o.href
      };
    }
  } catch {
    console.warn("Failed to decode did-connect url params");
  }
  return {
    params: null,
    url: e
  };
}
const _e = (e, { width: o = 680, height: r = 720, name: t = "did-connect:popup", offsetX: n = 0, offsetY: s = 0 } = {}) => {
  const i = C(e, { allowDomains: null }), v = window.screenX + (window.innerWidth - o) / 2 + n, k = window.screenY + (window.innerHeight - r) / 2 + s, y = [
    `left=${v}`,
    `top=${k}`,
    `width=${o}`,
    `height=${r}`,
    "resizable=no",
    // not working
    "scrollbars=yes",
    "status=yes",
    "popup=yes"
  ], p = window.open("", t, y.join(","));
  if (p === null)
    throw new W();
  return p.location.href = L(i, {
    // NOTICE: 携带当前页面的 origin，用于在 popup 中通过该参数判断是否可以发送 postMessage，即使该参数被伪造，最终也只有该域名能接收到消息，所以没有关系
    opener: window.location.origin
  }), p;
}, ve = (e) => new Promise((o, r) => {
  let t, n;
  const s = ({ data: i }) => {
    if (i && i.type === "authorization_response") {
      if (i?.error) {
        console.error(i.error);
        return;
      }
      setTimeout(() => {
        e.popup?.close(), clearTimeout(n), clearInterval(t), window.removeEventListener("message", s, !1);
      }, e.closeTimeout || 0), o(i);
    }
  };
  n = setTimeout(
    () => {
      clearInterval(t), r(new Error("Timeout")), window.removeEventListener("message", s, !1);
    },
    (e.timeoutInSeconds || D) * 1e3
  ), t = setInterval(() => {
    e.popup?.closed && (clearInterval(t), clearTimeout(n), window.removeEventListener("message", s, !1), r(new Error("Popup closed")));
  }, 1e3), window.addEventListener("message", s);
});
export {
  we as createAxios,
  re as debug,
  oe as debugTmp,
  te as debugTmpInterval,
  ie as decodeConnectUrl,
  d as decodeKey,
  be as decodeUrlParams,
  le as decrypt,
  se as encodeConnectUrl,
  pe as encodeKey,
  de as encrypt,
  he as formatCacheTtl,
  g as getApiErrorMessage,
  R as getAppId,
  ge as getBrowserLang,
  z as getConnectedInfo,
  M as getExtraHeaders,
  Ue as getVisitorId,
  me as getWebAuthnErrorMessage,
  ne as logger,
  _e as openPopup,
  ue as parseNextWorkflow,
  ae as parseTokenFromConnectUrl,
  ve as runPopup,
  Ae as setVisitorId,
  fe as sleep,
  ce as updateConnectedInfo,
  O as version
};
