import { jsx as y } from "react/jsx-runtime";
import { createContext as x, use as k, useState as h, useRef as A, useEffect as R, useCallback as b } from "react";
import j from "lodash/get";
import i from "js-cookie";
import S from "./browser-lang.js";
import { translate as U } from "./util.js";
import { getCookieOptions as D, resolveRootDomain as E } from "../Util/index.js";
const l = "nf_lang", F = (e, o = window.location.href) => {
  const t = new URL(o).searchParams.get("locale");
  return e.find((c) => c.code === t) ? t : null;
}, O = (e, o = window.location.href) => {
  const t = new URL(o);
  t.searchParams.has("locale") && (t.searchParams.set("locale", e), window.history.replaceState({}, "", t.href));
}, d = (e = []) => {
  const o = {
    languages: e.map((t) => t.code),
    // 取 languages 首个元素的 code 值, 如果不存在则取 'en'
    fallback: e?.[0]?.code || "en"
  };
  return F(e) || i.get(l) || S(o);
}, z = (e) => {
  const o = D();
  if (!o.domain) {
    const t = E();
    t && i.remove(l, { path: o.path || "/", domain: t });
  }
  i.set(l, e, o), O(e);
}, N = (e) => {
  const o = j(window, "blocklet.languages");
  return Array.isArray(o) && o.length ? o : Array.isArray(e) && e.length ? e : [
    { code: "en", name: "English" },
    { code: "zh", name: "简体中文" }
  ];
}, g = x(null), { Provider: _, Consumer: M } = g;
function Q({
  children: e,
  locale: o = void 0,
  fallbackLocale: t = void 0,
  translations: c,
  onLoadingTranslation: p = void 0,
  languages: L = [],
  ...P
}) {
  const s = N(L);
  let [n, v] = h(o || d(s));
  const m = A(t || ""), [, C] = h(0), u = (r) => {
    v(r), z(r);
  };
  if (R(() => {
    const r = o || d(s);
    r !== n && u(r);
  }, [o]), n && c[n] && typeof c[n] == "function") {
    const r = n;
    try {
      Promise.resolve(c[r]()).then((a) => {
        a && typeof a == "object" && (c[r] = a, C((f) => f > 999 ? 0 : f + 1));
      });
    } catch (a) {
      console.error(a);
    }
    p?.(r, s), n = m.current;
  } else
    m.current = n;
  const w = b(
    (r, a) => U(c, r, n, t, a),
    [c, n, t]
  );
  return /* @__PURE__ */ y(_, { value: { locale: n, changeLocale: u, t: w, languages: s, ...P }, children: e });
}
function T() {
  return k(g);
}
export {
  M as LocaleConsumer,
  g as LocaleContext,
  Q as LocaleProvider,
  d as getLocale,
  z as setLocale,
  T as useLocaleContext
};
