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