import { lazy as j } from "react";
import l from "lodash/padStart";
import { colors as w, getDIDMotifInfo as x } from "@arcblock/did-motif";
import { mergeAllThemeOptions as Ke } from "@blocklet/theme";
import I from "lodash/isNil";
import E from "lodash/omitBy";
import v from "p-retry";
import m from "js-cookie";
import O from "color-convert";
import a from "dayjs";
import "dayjs/locale/zh-cn";
import U from "dayjs/plugin/utc";
import F from "dayjs/plugin/timezone";
import A from "dayjs/plugin/relativeTime";
import P from "dayjs/plugin/updateLocale";
import R from "dayjs/plugin/localizedFormat";
import W from "semver";
import { DID_PREFIX as L, BLOCKLET_SERVICE_PATH_PREFIX as C } from "./constant.js";
import b from "../package.json.js";
import { getFederatedEnabled as M } from "./federated.js";
let u = null;
const _ = /^(\d{1,3}\.){3}\d{1,3}(:\d+)?$/, z = /* @__PURE__ */ new Set(["co", "com", "net", "org", "gov", "edu", "ac"]), N = /* @__PURE__ */ new Set(["uk", "au", "cn", "nz", "za", "in", "br", "mx", "fr", "it", "ca"]);
function B(e) {
  if (!e)
    return !1;
  const t = e.split(".");
  if (t.length < 2) return !1;
  const o = t[t.length - 2], n = t[t.length - 1];
  return z.has(o) && N.has(n);
}
function ye() {
  const { host: e } = window.location;
  if (!e || _.test(e))
    return "";
  const o = e.split(":")[0].split(".");
  if (o.length === 1)
    return "";
  if (o.length > 2) {
    const n = o.slice(-2).join(".");
    if (B(n))
      return `.${o.slice(-3).join(".")}`;
  }
  return `.${o.slice(-2).join(".")}`;
}
function Ie(e) {
  return e.replace(/^\?/, "").split("&").map((t) => t.split("=")).filter(([t]) => !!t).reduce((t, o) => {
    const n = o[0], i = decodeURIComponent(o[1]) || !0;
    return t[n] = i, t;
  }, {});
}
function be(e = {}) {
  return new URLSearchParams(e).toString();
}
function De(e = 1) {
  let t = e;
  typeof t == "number" && (t = { expireInDays: t }), t.path === void 0 && (t.path = "/"), t.expireInDays || (t.expireInDays = 1);
  const o = {
    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 o.domain, o;
}
const Se = (e) => e.color ? e.color : e.dark ? e.theme.palette.common.white : e.theme.palette.text.primary, ke = (e) => e.background ? e.background : e.dark ? e.theme.palette.common.black : e.theme.palette.common.white;
function Ve(e, t, o = []) {
  const n = Object.assign({}, e), i = t.defaultProps || {};
  return Object.keys(i).forEach((r) => {
    typeof n[r] == "string" && n[r].indexOf("::prop::") === 0 && (n[r] = i[r]);
  }), Array.isArray(o) && o.forEach((r) => {
    if (typeof n[r] == "string")
      try {
        n[r] = JSON.parse(n[r]);
      } catch {
      }
  }), Object.keys(n).forEach((r) => {
    typeof n[r] == "string" && n[r].indexOf("::prop::") === 0 && (n[r] = "");
  }), n;
}
function $e(e = 2017) {
  const t = (/* @__PURE__ */ new Date()).getFullYear();
  return `${t}` == `${e}` ? `© ArcBlock ${t}` : `© ArcBlock ${e} - ${t}`;
}
const Te = () => typeof Intl == "object" && typeof Intl.DateTimeFormat == "function" && typeof Intl.DateTimeFormat().resolvedOptions == "function" ? Intl.DateTimeFormat().resolvedOptions().timeZone : "", je = (e) => {
  let t = 0;
  for (let n = 0; n < e.length; n++)
    t = e.charCodeAt(n) + ((t << 5) - t);
  let o = "#";
  for (let n = 0; n < 3; n++) {
    const i = t >> n * 8 & 255;
    o += `00${i.toString(16)}`.substr(-2);
  }
  return o;
}, xe = (e) => {
  const t = Math.round(e / 1e3), o = Math.floor(t / 3600), n = Math.floor((t - o * 3600) / 60), i = t % 60;
  return `${l(o, 2, "0")}:${l(n, 2, "0")}:${l(i, 2, "0")}`;
};
function X(e) {
  u = e;
}
function Ee() {
  return u;
}
const D = (e) => (t, { locale: o, tz: n, isUtc: i } = {}) => {
  if (u === null && (a.extend(R), a.extend(U), a.extend(F), a.extend(P), a.extend(A), 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 年"
    }
  }), X(a)), I(t) || t === "")
    return "-";
  let r = u(t);
  return n && (r = r.tz(n)), i && (r = r.utc()), typeof o < "u" && (r = r.locale(o)), r.format(e);
};
function ve(e, { locale: t = "en", tz: o } = {}) {
  return D("ll")(e, { locale: t, tz: o });
}
function Oe(e, {
  locale: t = "en",
  tz: o,
  isUtc: n = !1,
  format: i = "lll"
} = {}) {
  return D(i)(e, { locale: t, tz: o, isUtc: n });
}
function K() {
  const e = window?.ABT_DEV || window.ABT;
  return e && typeof e.open == "function" ? e : null;
}
function Ue({
  webWalletUrl: e,
  action: t = "login",
  locale: o = "en",
  url: n,
  windowFeatures: i,
  appInfo: r,
  memberAppInfo: f
}) {
  const h = K();
  if (h)
    return h.open({
      action: t,
      locale: o,
      url: encodeURIComponent(n),
      appInfo: {
        ...r
      },
      memberAppInfo: {
        ...f
      }
    }), { type: "extension" };
  const S = {
    toolbar: "no",
    location: "no",
    status: "no",
    menubar: "no",
    scrollbars: "yes",
    resizable: "yes",
    // iphone 8plus size
    width: 414,
    height: 736
  }, k = `${e}?action=${t}&locale=${o}&url=${encodeURIComponent(n)}`, c = Object.assign({}, S, i), V = (s) => s.innerWidth || s.document.documentElement.clientWidth || s.document.body.clientWidth;
  if (!("left" in c)) {
    const s = V(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 $ = Object.keys(c).map((s) => `${s}=${c[s]}`).join(",");
  return window.open(k, "targetWindow", $), { type: "web" };
}
const Fe = (e) => e && Number(e) >= 12 ? `${Number(e)}px` : "inherit", J = (e) => {
  const t = e.replace(L, "");
  return !!/^(0x)?[0-9a-f]{40}$/i.test(t);
}, Q = (e, t) => {
  if (!t)
    return e;
  try {
    const o = new URL(e, window.location.origin);
    return Object.keys(t).forEach((n) => {
      o.searchParams.set(n, String(t[n]));
    }), o.origin === window.location.origin ? o.pathname + o.search : o.href;
  } catch {
    return e;
  }
}, Ae = (e, t = 48) => e && (e.indexOf(C) >= 0 ? Q(e, {
  imageFilter: "resize",
  w: t,
  h: t
}) : e), Pe = (e = 0) => new Promise((t) => {
  setTimeout(() => {
    t();
  }, e);
}), Re = (e) => /^https?:\/\//.test(e), p = "vid", g = "__visitor_id", Y = () => 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
  });
}, We = () => {
  let e = localStorage.getItem(g);
  if (e && (localStorage.removeItem(g), y(e)), !Y()) {
    if (!M())
      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 n = 0; n < 16; n++)
              t[n] = Math.floor(Math.random() * 256);
          const o = Array.from(t).map((n) => n.toString(16).padStart(2, "0"));
          e = [
            o.slice(0, 4).join(""),
            o.slice(4, 6).join(""),
            o.slice(6, 8).join(""),
            o.slice(8, 10).join(""),
            o.slice(10, 16).join("")
          ].join("-");
        }
      } catch {
        e = `${Date.now()}-${Math.random().toString(36).substring(2, 15)}`;
      }
    e && y(e);
  }
}, Le = (e) => {
  if (J(e)) {
    const t = Uint8Array.from(
      e.slice(2).match(/.{1,2}/g).map((o) => parseInt(o, 16))
    ).slice(0, 8).reduce((o, n) => o + n, 0) % w.length;
    return w[t];
  }
  try {
    return x(e)?.color;
  } catch {
    return null;
  }
}, Ce = (e, t, o = {}) => {
  const { fallbackLocale: n = "en", defaultValue: i = "unknown" } = o;
  if (typeof e == "string")
    return e;
  let r;
  return t && (r = e[t]), (!r || typeof r != "string") && (r = e[n]), (!r || typeof r != "string") && (r = i), r;
}, Me = (e) => j(
  () => v(
    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 }
  )
), _e = (e) => E(e, I);
function ze(e, t = 1) {
  const [o, n, i] = O.hex.rgb(e);
  return `rgba(${o}, ${n}, ${i}, ${t})`;
}
const G = () => window.blocklet?.serverVersion || "", H = () => b.version, Z = () => (b.dependencies?.["@blocklet/js-sdk"]).replace(/^[\^~>=<]+/, ""), d = (e, t) => {
  const o = (r) => {
    const f = r.match(/^(\d+\.\d+\.\d+(?:-[^-]+?-\d{8}))/);
    return f ? f[1] : r;
  }, n = o(e), i = o(t);
  return n === i && e !== t ? !1 : W.gte(n, i);
}, Ne = () => {
  if (process.env.NODE_ENV === "development")
    return !0;
  const e = G(), t = H(), o = Z();
  if (!e || !t || !o)
    return !1;
  const n = d(t, "3.1.29"), i = d(e, "1.16.49-beta-20250822-070545-6d3344cc"), r = d(o, "1.16.49-beta-20250822-070545-6d3344cc");
  return n && i && r;
};
export {
  Q as appendParams,
  _e as cleanedObj,
  d as compareVersions,
  Ke as deepmergeAll,
  K as detectWalletExtension,
  We as ensureVisitorId,
  ve as formatToDate,
  Oe as formatToDatetime,
  xe as formatUptime,
  ke as getBackground,
  Se as getColor,
  De as getCookieOptions,
  $e as getCopyright,
  Le as getDIDColor,
  Ee as getDateTool,
  Fe as getFontSize,
  Z as getJsSdkVersion,
  G as getServerVersion,
  Te as getTimezone,
  Ce as getTranslation,
  Ae as getUserAvatar,
  H as getUxPackageVersion,
  Y as getVisitorId,
  ze as hexToRgba,
  J as isEthereumDid,
  Ne as isSupportFollow,
  B as isTwoSegmentTLD,
  Re as isUrl,
  Me as lazyRetry,
  Ve as mergeProps,
  Ue as openWebWallet,
  Ie as parseQuery,
  ye as resolveRootDomain,
  X as setDateTool,
  y as setVisitorId,
  Pe as sleep,
  je as str2color,
  be as stringifyQuery
};
