import { lazy as T } from "react";
import l from "lodash/padStart";
import { colors as w, getDIDMotifInfo as j } 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 A from "dayjs/plugin/timezone";
import F from "dayjs/plugin/relativeTime";
import R from "dayjs/plugin/updateLocale";
import P 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+)?$/, N = /* @__PURE__ */ new Set(["co", "com", "net", "org", "gov", "edu", "ac"]), z = /* @__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], r = t[t.length - 1];
  return N.has(o) && z.has(r);
}
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 r = o.slice(-2).join(".");
    if (B(r))
      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 r = o[0], i = decodeURIComponent(o[1]) || !0;
    return t[r] = i, t;
  }, {});
}
function be(e = {}) {
  return new URLSearchParams(e).toString();
}
function Se(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 De = (e) => e.color ? e.color : e.dark ? e.theme.palette.common.white : e.theme.palette.text.primary, $e = (e) => e.background ? e.background : e.dark ? e.theme.palette.common.black : e.theme.palette.common.white;
function ke(e, t, o = []) {
  const r = Object.assign({}, e), i = t.defaultProps || {};
  return Object.keys(i).forEach((n) => {
    typeof r[n] == "string" && r[n].indexOf("::prop::") === 0 && (r[n] = i[n]);
  }), Array.isArray(o) && o.forEach((n) => {
    if (typeof r[n] == "string")
      try {
        r[n] = JSON.parse(r[n]);
      } catch {
      }
  }), Object.keys(r).forEach((n) => {
    typeof r[n] == "string" && r[n].indexOf("::prop::") === 0 && (r[n] = "");
  }), r;
}
function Ve(e = 2017) {
  const t = (/* @__PURE__ */ new Date()).getFullYear();
  return `${t}` == `${e}` ? `© ArcBlock ${t}` : `© ArcBlock ${e} - ${t}`;
}
const xe = () => typeof Intl == "object" && typeof Intl.DateTimeFormat == "function" && typeof Intl.DateTimeFormat().resolvedOptions == "function" ? Intl.DateTimeFormat().resolvedOptions().timeZone : "", Te = (e) => {
  let t = 0;
  for (let r = 0; r < e.length; r++)
    t = e.charCodeAt(r) + ((t << 5) - t);
  let o = "#";
  for (let r = 0; r < 3; r++) {
    const i = t >> r * 8 & 255;
    o += `00${i.toString(16)}`.substr(-2);
  }
  return o;
}, je = (e) => {
  const t = Math.round(e / 1e3), o = Math.floor(t / 3600), r = Math.floor((t - o * 3600) / 60), i = t % 60;
  return `${l(o, 2, "0")}:${l(r, 2, "0")}:${l(i, 2, "0")}`;
};
function X(e) {
  u = e;
}
function Ee() {
  return u;
}
const S = (e) => (t, { locale: o, tz: r, isUtc: i } = {}) => {
  if (u === null && (a.extend(P), a.extend(U), a.extend(A), a.extend(R), a.extend(F), 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 n = u(t);
  return r && (n = n.tz(r)), i && (n = n.utc()), typeof o < "u" && (n = n.locale(o)), n.format(e);
};
function ve(e, { locale: t = "en", tz: o } = {}) {
  return S("ll")(e, { locale: t, tz: o });
}
function Oe(e, {
  locale: t = "en",
  tz: o,
  isUtc: r = !1,
  format: i = "lll"
} = {}) {
  return S(i)(e, { locale: t, tz: o, isUtc: r });
}
function J() {
  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: r,
  windowFeatures: i,
  appInfo: n,
  memberAppInfo: f
}) {
  const h = J();
  if (h)
    return h.open({
      action: t,
      locale: o,
      url: encodeURIComponent(r),
      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=${o}&url=${encodeURIComponent(r)}`, 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), x = window.screenLeft || window.screenX;
    c.left = s + x - c.width;
  }
  if (!("top" in c)) {
    const s = window.screenTop || window.screenY;
    c.top = s;
  }
  const V = Object.keys(c).map((s) => `${s}=${c[s]}`).join(",");
  return window.open($, "targetWindow", V), { type: "web" };
}
const Ae = (e) => e && Number(e) >= 12 ? `${Number(e)}px` : "inherit", K = (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((r) => {
      o.searchParams.set(r, String(t[r]));
    }), o.origin === window.location.origin ? o.pathname + o.search : o.href;
  } catch {
    return e;
  }
}, Fe = (e, t = 48) => e && (e.indexOf(C) >= 0 ? Q(e, {
  imageFilter: "resize",
  w: t,
  h: t
}) : e), Re = (e = 0) => new Promise((t) => {
  setTimeout(() => {
    t();
  }, e);
}), Pe = (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 r = 0; r < 16; r++)
              t[r] = Math.floor(Math.random() * 256);
          const o = Array.from(t).map((r) => r.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 (K(e)) {
    const t = Uint8Array.from(
      e.slice(2).match(/.{1,2}/g).map((o) => parseInt(o, 16))
    ).slice(0, 8).reduce((o, r) => o + r, 0) % w.length;
    return w[t];
  }
  try {
    return j(e)?.color;
  } catch {
    return null;
  }
}, Ce = (e, t, o = {}) => {
  const { fallbackLocale: r = "en", defaultValue: i = "unknown" } = o;
  if (typeof e == "string")
    return e;
  let n;
  return t && (n = e[t]), (!n || typeof n != "string") && (n = e[r]), (!n || typeof n != "string") && (n = i), n;
}, Me = (e) => T(
  () => 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 Ne(e, t = 1) {
  const [o, r, i] = O.hex.rgb(e);
  return `rgba(${o}, ${r}, ${i}, ${t})`;
}
const q = () => window.blocklet?.serverVersion || window.env?.serverVersion || "", G = () => b.version, H = () => (b.dependencies?.["@blocklet/js-sdk"]).replace(/^[\^~>=<]+/, ""), d = (e, t) => {
  const o = (n) => {
    const f = n.match(/^(\d+\.\d+\.\d+(?:-[^-]+?-\d{8}))/);
    return f ? f[1] : n;
  };
  if (!e || !t)
    return !1;
  const r = o(e), i = o(t);
  if (r === i && e !== t)
    return !1;
  try {
    return W.gte(r, i);
  } catch {
    return !1;
  }
}, ze = () => {
  if (process.env.NODE_ENV === "development")
    return !0;
  const e = q(), t = G(), o = H();
  if (!e || !t || !o)
    return !1;
  const r = d(t, "3.1.29"), i = d(e, "1.16.49-beta-20250822-070545-6d3344cc"), n = d(o, "1.16.49-beta-20250822-070545-6d3344cc");
  return r && i && n;
}, Be = (e) => {
  const { response: t } = e;
  return t ? `Request failed: ${t.status} ${t.statusText}: ${JSON.stringify(t.data)}` : e.message || "Unknown error occurred";
};
export {
  Q as appendParams,
  _e as cleanedObj,
  d as compareVersions,
  Ke as deepmergeAll,
  J as detectWalletExtension,
  We as ensureVisitorId,
  Be as formatAxiosError,
  ve as formatToDate,
  Oe as formatToDatetime,
  je as formatUptime,
  $e as getBackground,
  De as getColor,
  Se as getCookieOptions,
  Ve as getCopyright,
  Le as getDIDColor,
  Ee as getDateTool,
  Ae as getFontSize,
  H as getJsSdkVersion,
  q as getServerVersion,
  xe as getTimezone,
  Ce as getTranslation,
  Fe as getUserAvatar,
  G as getUxPackageVersion,
  Y as getVisitorId,
  Ne as hexToRgba,
  K as isEthereumDid,
  ze as isSupportFollow,
  B as isTwoSegmentTLD,
  Pe as isUrl,
  Me as lazyRetry,
  ke as mergeProps,
  Ue as openWebWallet,
  Ie as parseQuery,
  ye as resolveRootDomain,
  X as setDateTool,
  y as setVisitorId,
  Re as sleep,
  Te as str2color,
  be as stringifyQuery
};
