import { storage as w } from "./core/storage.mjs";
const C = (class o {
  static instance;
  translationsCache = /* @__PURE__ */ new Map();
  manifestCache = /* @__PURE__ */ new Map();
  static BASE_URL = "https://i18n.oneweb.mercedes-benz.com";
  static BASE_PHRASE_URL = `${this.BASE_URL}/projects/`;
  static isBrowser = typeof window < "u";
  constructor() {
  }
  static getInstance() {
    return o.instance ||= new o(), o.instance;
  }
  async fetchCrowdinManifest(t) {
    if (o.isBrowser && this.manifestCache.has(t)) return this.manifestCache.get(t);
    let a = `${o.BASE_URL}/${t}/manifest.json`;
    try {
      let s = await fetch(a);
      if (!s.ok) throw Error(`Error fetching Crowdin manifest: ${s.statusText}`);
      let e = await s.json(), n = { files: e.files, languages: e.languages, custom_languages: e.custom_languages, timestamp: e.timestamp, content: e.content };
      return o.isBrowser && this.manifestCache.set(t, n), n;
    } catch (s) {
      throw console.error(s), s;
    }
  }
  async buildCrowdinTranslationUrl(t, a, s) {
    let e = new URL(`${o.BASE_URL}/${a}${t}`);
    return e.searchParams.append("timestamp", s), e;
  }
  async fetchCrowdinTranslation(t, a, s) {
    if (!o.isBrowser) {
      let n = await this.buildCrowdinTranslationUrl(t, a, s);
      return await this.fetchTranslation(n);
    }
    this.translationsCache.has(a) || this.translationsCache.set(a, {});
    let e = this.translationsCache.get(a);
    if (!e[t]) {
      let n = await this.buildCrowdinTranslationUrl(t, a, s);
      e[t] = await this.fetchTranslation(n);
    }
    return e[t];
  }
  buildPhraseTranslationUrl(t, a, s, e) {
    let n = new URL(`${o.BASE_PHRASE_URL}${a}/locales/${t}/download`);
    return n.searchParams.append("file_format", s), e && Object.keys(e).forEach((i) => {
      n.searchParams.append(i, e[i]);
    }), n;
  }
  async fetchPhraseTranslation(t, a, s, e) {
    if (!o.isBrowser) {
      let i = this.buildPhraseTranslationUrl(t, a, s, e);
      return await this.fetchTranslation(i);
    }
    this.translationsCache.has(a) || this.translationsCache.set(a, {});
    let n = this.translationsCache.get(a);
    if (!n[t]) {
      let i = this.buildPhraseTranslationUrl(t, a, s, e);
      n[t] = await this.fetchTranslation(i);
    }
    return n[t];
  }
  async fetchTranslation(t) {
    try {
      let a = await fetch(t);
      if (!a.ok) throw Error(`Error fetching translation: ${a.statusText}`);
      return await a.json();
    } catch (a) {
      throw console.error(`Error fetching translation: ${a}`), a;
    }
  }
  async getFileTranslations(t, a, s) {
    let { content: e, timestamp: n } = await this.fetchCrowdinManifest(a);
    t = Array.isArray(t) ? t : [t];
    let i = {};
    for (let r of t) {
      if (e && !Object.values(e).some((h) => h.includes(r))) throw Error(`File ${r} not found in the manifest`);
      let c = await this.fetchCrowdinTranslation(r, a, n);
      s?.merge ? i = { ...i, ...c } : i[r] = c;
    }
    return i;
  }
  async getLocaleTranslations(t, a, s, e) {
    if (s) return this.fetchPhraseTranslation(t, a, s, e);
    let { languages: n, content: i, custom_languages: r, timestamp: c } = await this.fetchCrowdinManifest(a), h = this.findMatchingLocale(t, [...n, ...r ? Object.keys(r) : []]), u = i[h];
    if (u.length === 0) throw Error(`No translation files found for locale ${h}`);
    let f = {};
    return await Promise.all(u.map(async (m) => {
      let g = await this.fetchCrowdinTranslation(m, a, c);
      f = { ...f, ...g };
    })), f;
  }
  findMatchingLocale(t, a) {
    if (a.includes(t)) return t;
    if (a.includes(t.toLowerCase())) return t.toLowerCase();
    let [s] = t.split("-"), e = a.find((n) => n === s);
    if (!e) throw Error(`Locale ${t} not found in the manifest. Available languages: ${a.join(", ")}`);
    return e;
  }
}).getInstance();
function p(l, t, a, s) {
  return C.getLocaleTranslations(l, t, a, s);
}
const y = "b2x.iam.translations", T = 1440 * 60 * 1e3;
async function b(l) {
  const {
    distributionHash: t,
    projectName: a = l.distributionHash,
    country: s = l.country.toUpperCase(),
    language: e = l.language.toLowerCase()
  } = l, n = `${y}.${a}.${e}`, i = w.session.get(n, { data: null, timestamp: Date.now() });
  try {
    if (!i.data || $(i.timestamp)) {
      const r = await p(
        `${e}-${s}`,
        t
      );
      i.data = d(r), i.timestamp = Date.now(), w.session.set(n, i);
    }
  } catch {
    i.data = {};
  }
  return {
    exists: (r) => !!i.data[r],
    t: (r) => i.data[r] || r
  };
}
function $(l) {
  return Date.now() - l > T;
}
function d(l, t = "") {
  const a = {};
  for (const [s, e] of Object.entries(l)) {
    const n = t ? `${t}.${s}` : s;
    typeof e == "string" ? a[n] = e : typeof e == "object" && e !== null && Object.assign(a, d(e, n));
  }
  return a;
}
export {
  b as initTranslations
};
