import { lazy as V } from "react";
import l from "lodash/padStart";
import { colors as w, getDIDMotifInfo as j } from "@arcblock/did-motif";
import { mergeAllThemeOptions as qe } from "@blocklet/theme";
import I from "lodash/isNil";
import E from "lodash/omitBy";
import v from "lodash/mergeWith";
import O from "p-retry";
import m from "js-cookie";
import U from "color-convert";
import a from "dayjs";
import "dayjs/locale/zh-cn";
import A from "dayjs/plugin/utc";
import F from "dayjs/plugin/timezone";
import R from "dayjs/plugin/relativeTime";
import W from "dayjs/plugin/updateLocale";
import P from "dayjs/plugin/localizedFormat";
import L from "semver";
import { DID_PREFIX as C, BLOCKLET_SERVICE_PATH_PREFIX as M } from "./constant.js";
import b from "../package.json.js";
import { getFederatedEnabled as _ } from "./federated.js";
let u = null;
const N = /^(\d{1,3}\.){3}\d{1,3}(:\d+)?$/, z = /* @__PURE__ */ new Set(["co", "com", "net", "org", "gov", "edu", "ac"]), B = /* @__PURE__ */ new Set(["uk", "au", "cn", "nz", "za", "in", "br", "mx", "fr", "it", "ca"]);
function X(e) {
  if (!e)
    return !1;
  const t = e.split(".");
  if (t.length < 2) return !1;
  const r = t[t.length - 2], o = t[t.length - 1];
  return z.has(r) && B.has(o);
}
function be() {
  const { host: e } = window.location;
  if (!e || N.test(e))
    return "";
  const r = e.split(":")[0].split(".");
  if (r.length === 1)
    return "";
  if (r.length > 2) {
    const o = r.slice(-2).join(".");
    if (X(o))
      return `.${r.slice(-3).join(".")}`;
  }
  return `.${r.slice(-2).join(".")}`;
}
function Se(e) {
  return e.replace(/^\?/, "").split("&").map((t) => t.split("=")).filter(([t]) => !!t).reduce((t, r) => {
    const o = r[0], i = decodeURIComponent(r[1]) || !0;
    return t[o] = i, t;
  }, {});
}
function De(e = {}) {
  return new URLSearchParams(e).toString();
}
function $e(e = 1) {
  let t = e;
  typeof t == "number" && (t = { expireInDays: t }), t.path === void 0 && (t.path = "/"), t.expireInDays || (t.expireInDays = 1);
  const r = {
    expires: t.expireInDays,
    path: t.path,
    domain: t.domain || "",
    sameSite: t.sameSite || "Lax",
    // 允许自定义设置为 false，默认是 true
    secure: t.secure !== !1
  };
  return (typeof window > "u" || t.domain || t.returnDomain === !1) && t.returnDomain === !1 && delete r.domain, r;
}
const ke = (e) => e.color ? e.color : e.dark ? e.theme.palette.common.white : e.theme.palette.text.primary, xe = (e) => e.background ? e.background : e.dark ? e.theme.palette.common.black : e.theme.palette.common.white;
function Te(e, t, r = []) {
  const o = Object.assign({}, e), i = t.defaultProps || {};
  return Object.keys(i).forEach((n) => {
    typeof o[n] == "string" && o[n].indexOf("::prop::") === 0 && (o[n] = i[n]);
  }), Array.isArray(r) && r.forEach((n) => {
    if (typeof o[n] == "string")
      try {
        o[n] = JSON.parse(o[n]);
      } catch {
      }
  }), Object.keys(o).forEach((n) => {
    typeof o[n] == "string" && o[n].indexOf("::prop::") === 0 && (o[n] = "");
  }), o;
}
function Ve(e = 2017) {
  const t = (/* @__PURE__ */ new Date()).getFullYear();
  return `${t}` == `${e}` ? `© ArcBlock ${t}` : `© ArcBlock ${e} - ${t}`;
}
const je = () => typeof Intl == "object" && typeof Intl.DateTimeFormat == "function" && typeof Intl.DateTimeFormat().resolvedOptions == "function" ? Intl.DateTimeFormat().resolvedOptions().timeZone : "", Ee = (e) => {
  let t = 0;
  for (let o = 0; o < e.length; o++)
    t = e.charCodeAt(o) + ((t << 5) - t);
  let r = "#";
  for (let o = 0; o < 3; o++) {
    const i = t >> o * 8 & 255;
    r += `00${i.toString(16)}`.substr(-2);
  }
  return r;
}, ve = (e) => {
  const t = Math.round(e / 1e3), r = Math.floor(t / 3600), o = Math.floor((t - r * 3600) / 60), i = t % 60;
  return `${l(r, 2, "0")}:${l(o, 2, "0")}:${l(i, 2, "0")}`;
};
function J(e) {
  u = e;
}
function Oe() {
  return u;
}
const S = (e) => (t, { locale: r, tz: o, isUtc: i } = {}) => {
  if (u === null && (a.extend(P), a.extend(A), a.extend(F), a.extend(W), a.extend(R), a.updateLocale("zh-cn", {
    // copy with https://github.com/iamkun/dayjs/blob/dev/src/locale/zh-cn.js
    relativeTime: {
      future: "%s后",
      past: "%s前",
      s: "几秒",
      m: "1 分钟",
      mm: "%d 分钟",
      h: "1 小时",
      hh: "%d 小时",
      d: "1 天",
      dd: "%d 天",
      M: "1 个月",
      MM: "%d 个月",
      y: "1 年",
      yy: "%d 年"
    }
  }), J(a)), I(t) || t === "")
    return "-";
  let n = u(t);
  return o && (n = n.tz(o)), i && (n = n.utc()), typeof r < "u" && (n = n.locale(r)), n.format(e);
};
function Ue(e, { locale: t = "en", tz: r } = {}) {
  return S("ll")(e, { locale: t, tz: r });
}
function Ae(e, {
  locale: t = "en",
  tz: r,
  isUtc: o = !1,
  format: i = "lll"
} = {}) {
  return S(i)(e, { locale: t, tz: r, isUtc: o });
}
function K() {
  const e = window?.ABT_DEV || window.ABT;
  return e && typeof e.open == "function" ? e : null;
}
function Fe({
  webWalletUrl: e,
  action: t = "login",
  locale: r = "en",
  url: o,
  windowFeatures: i,
  appInfo: n,
  memberAppInfo: f
}) {
  const h = K();
  if (h)
    return h.open({
      action: t,
      locale: r,
      url: encodeURIComponent(o),
      appInfo: {
        ...n
      },
      memberAppInfo: {
        ...f
      }
    }), { type: "extension" };
  const D = {
    toolbar: "no",
    location: "no",
    status: "no",
    menubar: "no",
    scrollbars: "yes",
    resizable: "yes",
    // iphone 8plus size
    width: 414,
    height: 736
  }, $ = `${e}?action=${t}&locale=${r}&url=${encodeURIComponent(o)}`, c = Object.assign({}, D, i), k = (s) => s.innerWidth || s.document.documentElement.clientWidth || s.document.body.clientWidth;
  if (!("left" in c)) {
    const s = k(window.top || window), T = window.screenLeft || window.screenX;
    c.left = s + T - c.width;
  }
  if (!("top" in c)) {
    const s = window.screenTop || window.screenY;
    c.top = s;
  }
  const x = Object.keys(c).map((s) => `${s}=${c[s]}`).join(",");
  return window.open($, "targetWindow", x), { type: "web" };
}
const Re = (e) => e && Number(e) >= 12 ? `${Number(e)}px` : "inherit", Q = (e) => {
  const t = e.replace(C, "");
  return !!/^(0x)?[0-9a-f]{40}$/i.test(t);
}, Y = (e, t) => {
  if (!t)
    return e;
  try {
    const r = new URL(e, window.location.origin);
    return Object.keys(t).forEach((o) => {
      r.searchParams.set(o, String(t[o]));
    }), r.origin === window.location.origin ? r.pathname + r.search : r.href;
  } catch {
    return e;
  }
}, We = (e, t = 48) => e && (e.indexOf(M) >= 0 ? Y(e, {
  imageFilter: "resize",
  w: t,
  h: t
}) : e), Pe = (e = 0) => new Promise((t) => {
  setTimeout(() => {
    t();
  }, e);
}), Le = (e) => /^https?:\/\//.test(e), p = "vid", g = "__visitor_id", q = () => m.get(p) || localStorage.getItem(g), y = (e) => {
  e === null ? m.remove(p, {
    sameSite: "None",
    secure: !0
  }) : m.set(p, e, {
    sameSite: "None",
    secure: !0,
    expires: 365
  });
}, Ce = () => {
  let e = localStorage.getItem(g);
  if (e && (localStorage.removeItem(g), y(e)), !q()) {
    if (!_())
      try {
        if (window.crypto && typeof window.crypto.randomUUID == "function")
          e = window.crypto.randomUUID();
        else {
          const t = new Uint8Array(16);
          if (window.crypto && typeof window.crypto.getRandomValues == "function")
            window.crypto.getRandomValues(t);
          else
            for (let o = 0; o < 16; o++)
              t[o] = Math.floor(Math.random() * 256);
          const r = Array.from(t).map((o) => o.toString(16).padStart(2, "0"));
          e = [
            r.slice(0, 4).join(""),
            r.slice(4, 6).join(""),
            r.slice(6, 8).join(""),
            r.slice(8, 10).join(""),
            r.slice(10, 16).join("")
          ].join("-");
        }
      } catch {
        e = `${Date.now()}-${Math.random().toString(36).substring(2, 15)}`;
      }
    e && y(e);
  }
}, Me = (e) => {
  if (Q(e)) {
    const t = Uint8Array.from(
      e.slice(2).match(/.{1,2}/g).map((r) => parseInt(r, 16))
    ).slice(0, 8).reduce((r, o) => r + o, 0) % w.length;
    return w[t];
  }
  try {
    return j(e)?.color;
  } catch {
    return null;
  }
}, _e = (e, t, r = {}) => {
  const { fallbackLocale: o = "en", defaultValue: i = "unknown" } = r;
  if (typeof e == "string")
    return e;
  let n;
  return t && (n = e[t]), (!n || typeof n != "string") && (n = e[o]), (!n || typeof n != "string") && (n = i), n;
}, Ne = (e) => V(
  () => O(
    async () => {
      try {
        return await e();
      } catch (t) {
        throw t instanceof TypeError && !t.message.includes("Failed to fetch") ? t : t instanceof Error ? new Error(t.message) : new Error("Unknown error");
      }
    },
    // 只需要重试两次，加上原本的一次，总共三次
    { retries: 2 }
  )
), ze = (e) => E(e, I);
function Be(e, t = 1) {
  const [r, o, i] = U.hex.rgb(e);
  return `rgba(${r}, ${o}, ${i}, ${t})`;
}
const G = () => window.blocklet?.serverVersion || window.env?.serverVersion || "", H = () => b.version, Z = () => (b.dependencies?.["@blocklet/js-sdk"]).replace(/^[\^~>=<]+/, ""), d = (e, t) => {
  const r = (n) => {
    const f = n.match(/^(\d+\.\d+\.\d+(?:-[^-]+?-\d{8}))/);
    return f ? f[1] : n;
  };
  if (!e || !t)
    return !1;
  const o = r(e), i = r(t);
  if (o === i && e !== t)
    return !1;
  try {
    return L.gte(o, i);
  } catch {
    return !1;
  }
}, Xe = () => {
  if (process.env.NODE_ENV === "development")
    return !0;
  const e = G(), t = H(), r = Z();
  if (!e || !t || !r)
    return !1;
  const o = d(t, "3.1.29"), i = d(e, "1.16.49-beta-20250822-070545-6d3344cc"), n = d(r, "1.16.49-beta-20250822-070545-6d3344cc");
  return o && i && n;
}, Je = (e) => {
  const { response: t } = e;
  return t ? `Request failed: ${t.status} ${t.statusText}: ${JSON.stringify(t.data)}` : e.message || "Unknown error occurred";
}, Ke = (...e) => v({}, ...e, (t, r) => r === "" || r === null || r === void 0 ? t : r);
export {
  Y as appendParams,
  ze as cleanedObj,
  d as compareVersions,
  qe as deepmergeAll,
  K as detectWalletExtension,
  Ce as ensureVisitorId,
  Je as formatAxiosError,
  Ue as formatToDate,
  Ae as formatToDatetime,
  ve as formatUptime,
  xe as getBackground,
  ke as getColor,
  $e as getCookieOptions,
  Ve as getCopyright,
  Me as getDIDColor,
  Oe as getDateTool,
  Re as getFontSize,
  Z as getJsSdkVersion,
  G as getServerVersion,
  je as getTimezone,
  _e as getTranslation,
  We as getUserAvatar,
  H as getUxPackageVersion,
  q as getVisitorId,
  Be as hexToRgba,
  Q as isEthereumDid,
  Xe as isSupportFollow,
  X as isTwoSegmentTLD,
  Le as isUrl,
  Ne as lazyRetry,
  Ke as mergeIgnoreEmpty,
  Te as mergeProps,
  Fe as openWebWallet,
  Se as parseQuery,
  be as resolveRootDomain,
  J as setDateTool,
  y as setVisitorId,
  Pe as sleep,
  Ee as str2color,
  De as stringifyQuery
};
