import { c as d, d as F, P as w, i as P, Q as a, l as U, p as f, e as j, F as p, g as $, f as D, h as B, a as O, j as v, I as k, U as G, k as N, N as H, b as y, v as V, m as x, n as I, o as S } from "./chunks/cias-login.mjs";
import { getQueryParameter as g, removeQueryParametersForSeamlessRouter as M } from "@b2x/std/core/url.mjs";
import { initTranslations as z } from "@b2x/std/i18n.mjs";
import { createHttpClient as Q } from "@b2x/std/core/http.mjs";
import { storage as h } from "@b2x/std/core/storage.mjs";
import { tryCatch as W } from "@b2x/std/helpers/try-catch.mjs";
import { initializeStore as K } from "@seamless/store";
const J = d.createLogger("LOGGED_IN_CIAS");
async function q(e) {
  J.info("Logged in flow");
  let t = e;
  try {
    const i = await F();
    if (!await i.validate(e.jwe).then(() => !0).catch(() => !1)) {
      const o = await i.refreshToken(e.jwe), r = await i.fetchClaims(o);
      t = {
        jwe: o,
        claims: r,
        identityProvider: w.CIAS
      };
    }
  } catch (i) {
    if (await P()) {
      const n = new URL(window.location.origin);
      return n.searchParams.append(a.ERROR, i.id), U({ targetUrl: n.toString() });
    }
    throw t = {
      jwe: null,
      claims: null,
      identityProvider: null
    }, i;
  } finally {
    await f(t);
  }
}
const _ = d.createLogger("GET_FLOW");
async function X() {
  const e = g(a.FLOW), t = g(a.REGISTER), i = g(a.PROVIDER), n = g(a.ERROR), o = g(a.CIAS_ERROR);
  _.info("Flow, provider, error", e, i, n || o), M([
    a.FLOW,
    a.PROVIDER,
    a.ERROR,
    a.CIAS_ERROR,
    a.REGISTER
  ]);
  const r = await j.get(), l = [
    () => ie(n || o, i),
    () => Y(e, i),
    () => Z(e, i),
    () => ee(r),
    () => te(r),
    () => ne()
  ];
  for (const R of l) {
    const m = await R();
    if (m) {
      await m();
      break;
    }
  }
  return t ? p.REGISTER : e;
}
function Y(e, t) {
  if (e === p.LOGIN && t === w.CIAS)
    return D;
}
function Z(e, t) {
  if (e === p.LOGOUT && t === w.CIAS)
    return B;
}
function ee(e) {
  if (e?.jwe && e?.identityProvider === w.CIAS)
    return async () => await q(e);
}
async function te(e) {
  if (!e?.jwe && await P() && !window.location.pathname.includes("sales-mode"))
    return async () => O();
}
function ie(e, t) {
  if (e && t === w.CIAS) {
    const i = $(e);
    return async () => {
      throw await f({
        claims: null,
        identityProvider: null,
        jwe: null
      }), i;
    };
  }
}
function ne() {
  return _.info("Anonymous flow, publishing empty state"), async () => await f({
    claims: null,
    identityProvider: null,
    jwe: null
  });
}
async function oe(e) {
  const t = await v(), { t: i } = await z({
    distributionHash: "euw1-09971326e837bfe783b3ivp",
    country: t?.country,
    language: t?.language
  });
  return i(e) || e;
}
const E = d.createLogger("PUBLISH_ERROR");
async function ae(e) {
  E.error("Error occurred", e);
  let t = null;
  if (e instanceof k ? e.shouldNotify && (t = e) : t = new G(), t) {
    try {
      t.message = await oe(t.translationKey);
    } catch (o) {
      E.error("Error occurred while translating notification", o);
    }
    E.info("Setting error in legacy connection", t), N.setError(t);
    const { renderNotification: i } = await import(
      /* @vite-ignore */
      "@oneweb/notification"
    ), n = {
      message: t.message,
      theme: "light",
      variant: t.type.toLowerCase()
    };
    t.type !== H.ERROR && (n.lifetime = 2e4), i(n);
  }
}
const u = d.createLogger("trackUserData");
let L = null;
async function se(e) {
  L?.unsubscribe(), L = K().subscribe("B2XCORE_PROFILE", (t) => {
    if (u.info("Got active profile from PL", "flow:", e, t.activeProfile), !t?.activeProfile?.id) {
      u.info("No active profile found, skipping role tracking");
      return;
    }
    re(t.activeProfile, e);
  });
}
async function re(e, t) {
  let i = "not_set", n = "private";
  const o = "b2x.analytics.profileId", r = "analytics_user_md", l = y.state.isLoggedIn ? "logged_in" : "logged_out", R = h.session.get(o), m = h.session.get(r);
  if (`${e.id}__${l}` === R) {
    u.info("Profile didn't change, no need to track it");
    return;
  }
  if (e.businessType === "B2B" && (n = "business", e.id !== "DEFAULT_B2B")) {
    const [A, C] = await W(
      () => le(y.state.jwe, e.meId)
    );
    C && u.error("Failed to get company role", C), i = A || i;
  }
  const b = {
    loginState: l,
    context: n,
    role: i,
    loginStateDetail: ce(y.state, m, t)
  };
  h.session.set(r, b), h.session.set(o, `${e.id}__${l}`), window.dispatchEvent(new CustomEvent("analytics_user_md_change")), u.info("User data tracked successfully", b);
}
async function le(e, t) {
  const o = `https://${(await v()).stage === "PROD" ? "" : "int."}api.oneweb.mercedes-benz.com/iam/bff/`;
  return (await Q({ prefixUrl: o }).post("company-role", {
    headers: {
      "Content-Type": "application/json",
      Authorization: `Bearer ${e}`
    },
    body: JSON.stringify({ companyId: t })
  }).json().catch(() => ({
    companyRole: "not_set"
  }))).companyRole;
}
const c = {
  loggedIn: "logged_in",
  loggedOut: "logged_out",
  registered: "account_registered",
  guest: "guest"
};
function ce(e, t, i) {
  const n = t?.loginStateDetail;
  let o = c.loggedOut;
  return e.jwe ? i === p.REGISTER || n === c.registered ? o = c.registered : o = c.loggedIn : (!n || n === c.guest) && (o = c.guest), o;
}
const s = d.createLogger("AUTHENTICATION_BOOTSTRAP");
function T() {
  return s.info(`Bootstrapping authentication ${V} - ${x}`), X().then((e) => {
    se(e);
  }).catch(ae).finally(() => {
    ue(), ge(), fe();
  });
}
async function ge() {
  s.info("Handle visibility change"), y.state.jwe && document.addEventListener("visibilitychange", e);
  function e() {
    document.visibilityState === "visible" && (s.info("Visibility change to ", document.visibilityState), document.removeEventListener("visibilitychange", e), T());
  }
}
async function ue() {
  s.info("Handle login hash"), e(), window.addEventListener("hashchange", e);
  function e() {
    location.hash === "#login" && (s.info("Login hash detected, users login state is:", I.state.isLoggedIn), history.replaceState(null, "", window.location.pathname + window.location.search), I.state.isLoggedIn || (s.info("Triggering login since user is not logged in"), window.removeEventListener("hashchange", e), O()));
  }
}
function fe() {
  s.info("Handle event from other tabs"), S.subscribe("logout", async () => {
    s.info("Received logout event from other tab"), await f({
      jwe: null,
      claims: null,
      identityProvider: null
    });
  }), S.subscribe("login", async ({ payload: e }) => {
    s.info("Received login event from other tab"), await f(e);
  });
}
(async () => (await v()).runMode === "AUTHOR" || queueMicrotask(T))();
//# sourceMappingURL=bootstrap.mjs.map
