import { lazy as x } from "react";
import l from "lodash/padStart";
import { colors as g, getDIDMotifInfo as E } from "@arcblock/did-motif";
import { mergeAllThemeOptions as vt } from "@blocklet/theme";
import y from "lodash/isNil";
import j from "lodash/omitBy";
import k from "p-retry";
import u 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 W from "dayjs/plugin/localizedFormat";
import { DID_PREFIX as L, BLOCKLET_SERVICE_PATH_PREFIX as P } from "./constant.js";
import { getFederatedEnabled as v } from "./federated.js";
let f = null;
const C = /^(\d{1,3}\.){3}\d{1,3}(:\d+)?$/, M = /* @__PURE__ */ new Set(["co", "com", "net", "org", "gov", "edu", "ac"]), V = /* @__PURE__ */ new Set(["uk", "au", "cn", "nz", "za", "in", "br", "mx", "fr", "it", "ca"]);
function _(t) {
  if (!t)
    return !1;
  const e = t.split(".");
  if (e.length < 2) return !1;
  const o = e[e.length - 2], n = e[e.length - 1];
  return M.has(o) && V.has(n);
}
function lt() {
  const { host: t } = window.location;
  if (!t || C.test(t))
    return "";
  const o = t.split(":")[0].split(".");
  if (o.length === 1)
    return "";
  if (o.length > 2) {
    const n = o.slice(-2).join(".");
    if (_(n))
      return `.${o.slice(-3).join(".")}`;
  }
  return `.${o.slice(-2).join(".")}`;
}
function ut(t) {
  return t.replace(/^\?/, "").split("&").map((e) => e.split("=")).filter(([e]) => !!e).reduce((e, o) => {
    const n = o[0], i = decodeURIComponent(o[1]) || !0;
    return e[n] = i, e;
  }, {});
}
function mt(t = {}) {
  return new URLSearchParams(t).toString();
}
function dt(t = 1) {
  let e = t;
  typeof e == "number" && (e = { expireInDays: e }), e.path === void 0 && (e.path = "/"), e.expireInDays || (e.expireInDays = 1);
  const o = {
    expires: e.expireInDays,
    path: e.path,
    domain: e.domain || "",
    sameSite: e.sameSite || "Lax",
    // 允许自定义设置为 false，默认是 true
    secure: e.secure !== !1
  };
  return (typeof window > "u" || e.domain || e.returnDomain === !1) && e.returnDomain === !1 && delete o.domain, o;
}
const pt = (t) => t.color ? t.color : t.dark ? t.theme.palette.common.white : t.theme.palette.text.primary, ht = (t) => t.background ? t.background : t.dark ? t.theme.palette.common.black : t.theme.palette.common.white;
function gt(t, e, o = []) {
  const n = Object.assign({}, t), i = e.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 wt(t = 2017) {
  const e = (/* @__PURE__ */ new Date()).getFullYear();
  return `${e}` == `${t}` ? `© ArcBlock ${e}` : `© ArcBlock ${t} - ${e}`;
}
const yt = () => typeof Intl == "object" && typeof Intl.DateTimeFormat == "function" && typeof Intl.DateTimeFormat().resolvedOptions == "function" ? Intl.DateTimeFormat().resolvedOptions().timeZone : "", It = (t) => {
  let e = 0;
  for (let n = 0; n < t.length; n++)
    e = t.charCodeAt(n) + ((e << 5) - e);
  let o = "#";
  for (let n = 0; n < 3; n++) {
    const i = e >> n * 8 & 255;
    o += `00${i.toString(16)}`.substr(-2);
  }
  return o;
}, bt = (t) => {
  const e = Math.round(t / 1e3), o = Math.floor(e / 3600), n = Math.floor((e - o * 3600) / 60), i = e % 60;
  return `${l(o, 2, "0")}:${l(n, 2, "0")}:${l(i, 2, "0")}`;
};
function z(t) {
  f = t;
}
function Dt() {
  return f;
}
const I = (t) => (e, { locale: o, tz: n, isUtc: i } = {}) => {
  if (f === null && (a.extend(W), 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 年"
    }
  }), z(a)), y(e) || e === "")
    return "-";
  let r = f(e);
  return n && (r = r.tz(n)), i && (r = r.utc()), typeof o < "u" && (r = r.locale(o)), r.format(t);
};
function $t(t, { locale: e = "en", tz: o } = {}) {
  return I("ll")(t, { locale: e, tz: o });
}
function Tt(t, {
  locale: e = "en",
  tz: o,
  isUtc: n = !1,
  format: i = "lll"
} = {}) {
  return I(i)(t, { locale: e, tz: o, isUtc: n });
}
function B() {
  const t = window?.ABT_DEV || window.ABT;
  return t && typeof t.open == "function" ? t : null;
}
function St({
  webWalletUrl: t,
  action: e = "login",
  locale: o = "en",
  url: n,
  windowFeatures: i,
  appInfo: r,
  memberAppInfo: p
}) {
  const h = B();
  if (h)
    return h.open({
      action: e,
      locale: o,
      url: encodeURIComponent(n),
      appInfo: {
        ...r
      },
      memberAppInfo: {
        ...p
      }
    }), { type: "extension" };
  const b = {
    toolbar: "no",
    location: "no",
    status: "no",
    menubar: "no",
    scrollbars: "yes",
    resizable: "yes",
    // iphone 8plus size
    width: 414,
    height: 736
  }, D = `${t}?action=${e}&locale=${o}&url=${encodeURIComponent(n)}`, c = Object.assign({}, b, i), $ = (s) => s.innerWidth || s.document.documentElement.clientWidth || s.document.body.clientWidth;
  if (!("left" in c)) {
    const s = $(window.top || window), S = window.screenLeft || window.screenX;
    c.left = s + S - c.width;
  }
  if (!("top" in c)) {
    const s = window.screenTop || window.screenY;
    c.top = s;
  }
  const T = Object.keys(c).map((s) => `${s}=${c[s]}`).join(",");
  return window.open(D, "targetWindow", T), { type: "web" };
}
const xt = (t) => t && Number(t) >= 12 ? `${Number(t)}px` : "inherit", N = (t) => {
  const e = t.replace(L, "");
  return !!/^(0x)?[0-9a-f]{40}$/i.test(e);
}, X = (t, e) => {
  if (!e)
    return t;
  try {
    const o = new URL(t, window.location.origin);
    return Object.keys(e).forEach((n) => {
      o.searchParams.set(n, String(e[n]));
    }), o.origin === window.location.origin ? o.pathname + o.search : o.href;
  } catch {
    return t;
  }
}, Et = (t, e = 48) => t && (t.indexOf(P) >= 0 ? X(t, {
  imageFilter: "resize",
  w: e,
  h: e
}) : t), jt = (t = 0) => new Promise((e) => {
  setTimeout(() => {
    e();
  }, t);
}), kt = (t) => /^https?:\/\//.test(t), m = "vid", d = "__visitor_id", K = () => u.get(m) || localStorage.getItem(d), w = (t) => {
  t === null ? u.remove(m, {
    sameSite: "None",
    secure: !0
  }) : u.set(m, t, {
    sameSite: "None",
    secure: !0,
    expires: 365
  });
}, Ot = () => {
  let t = localStorage.getItem(d);
  if (t && (localStorage.removeItem(d), w(t)), !K()) {
    if (!v())
      try {
        if (window.crypto && typeof window.crypto.randomUUID == "function")
          t = window.crypto.randomUUID();
        else {
          const e = new Uint8Array(16);
          if (window.crypto && typeof window.crypto.getRandomValues == "function")
            window.crypto.getRandomValues(e);
          else
            for (let n = 0; n < 16; n++)
              e[n] = Math.floor(Math.random() * 256);
          const o = Array.from(e).map((n) => n.toString(16).padStart(2, "0"));
          t = [
            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 {
        t = `${Date.now()}-${Math.random().toString(36).substring(2, 15)}`;
      }
    t && w(t);
  }
}, Ut = (t) => {
  if (N(t)) {
    const e = Uint8Array.from(
      t.slice(2).match(/.{1,2}/g).map((o) => parseInt(o, 16))
    ).slice(0, 8).reduce((o, n) => o + n, 0) % g.length;
    return g[e];
  }
  try {
    return E(t)?.color;
  } catch {
    return null;
  }
}, At = (t, e, o = {}) => {
  const { fallbackLocale: n = "en", defaultValue: i = "unknown" } = o;
  if (typeof t == "string")
    return t;
  let r;
  return e && (r = t[e]), (!r || typeof r != "string") && (r = t[n]), (!r || typeof r != "string") && (r = i), r;
}, Ft = (t) => x(
  () => k(
    async () => {
      try {
        return await t();
      } catch (e) {
        throw e instanceof TypeError && !e.message.includes("Failed to fetch") ? e : e instanceof Error ? new Error(e.message) : new Error("Unknown error");
      }
    },
    // 只需要重试两次，加上原本的一次，总共三次
    { retries: 2 }
  )
), Rt = (t) => j(t, y);
function Wt(t, e = 1) {
  const [o, n, i] = O.hex.rgb(t);
  return `rgba(${o}, ${n}, ${i}, ${e})`;
}
export {
  X as appendParams,
  Rt as cleanedObj,
  vt as deepmergeAll,
  B as detectWalletExtension,
  Ot as ensureVisitorId,
  $t as formatToDate,
  Tt as formatToDatetime,
  bt as formatUptime,
  ht as getBackground,
  pt as getColor,
  dt as getCookieOptions,
  wt as getCopyright,
  Ut as getDIDColor,
  Dt as getDateTool,
  xt as getFontSize,
  yt as getTimezone,
  At as getTranslation,
  Et as getUserAvatar,
  K as getVisitorId,
  Wt as hexToRgba,
  N as isEthereumDid,
  _ as isTwoSegmentTLD,
  kt as isUrl,
  Ft as lazyRetry,
  gt as mergeProps,
  St as openWebWallet,
  ut as parseQuery,
  lt as resolveRootDomain,
  z as setDateTool,
  w as setVisitorId,
  jt as sleep,
  It as str2color,
  mt as stringifyQuery
};
