var J = Object.defineProperty;
var V = (t, e, r) => e in t ? J(t, e, { enumerable: !0, configurable: !0, writable: !0, value: r }) : t[e] = r;
var S = (t, e, r) => V(t, typeof e != "symbol" ? e + "" : e, r);
const g = { BASE_URL: "/", DEV: !1, MODE: "production", PROD: !0, SSR: !1, VITE_AG_CHARTS_LICENSE_KEY: "Using_this_{AG_Charts}_Enterprise_key_{AG-125036}_in_excess_of_the_licence_granted_is_not_permitted___Please_report_misuse_to_legal@ag-grid.com___For_help_with_changing_this_key_please_contact_info@ag-grid.com___{Metabolic_Code}_is_granted_a_{Single_Application}_Developer_License_for_the_application_{Metabolic_Code}_only_for_{1}_Front-End_JavaScript_developer___All_Front-End_JavaScript_developers_working_on_{Metabolic_Code}_need_to_be_licensed___{Metabolic_Code}_has_been_granted_a_Deployment_License_Add-on_for_{1}_Production_Environment___This_key_works_with_{AG_Charts}_Enterprise_versions_released_before_{31_March_2027}____[v3]_[02]_MTgwNjQ0NzYwMDAwMA==4e5dbf88087527cd3b1cf09b0557ec38", VITE_METABOLIC_LMS_API_BASE_URL: "https://mc-api-us.metaboliccode.com", VITE_METABOLIC_LMS_FRONTEND_BASE_URL: "https://mc-lms.metaboliccode.com", VITE_METABOLIC_REPORT_PAGES_API_BASE_URL: "https://mc-api-us.metaboliccode.com", VITE_METABOLIC_REPORT_PAGES_API_BASE_URL_CA: "https://mc-api-ca.metaboliccode.com", VITE_METABOLIC_REPORT_PAGES_API_BASE_URL_US: "https://mc-api-us.metaboliccode.com" }, G = "https://mc-api-us.metaboliccode.com", W = "https://mc-api-us.metaboliccode.com", K = "https://mc-lms.metaboliccode.com";
function A(t) {
  const e = t == null ? void 0 : t.trim();
  return e || void 0;
}
function Q() {
  try {
    return A(
      "https://mc-api-us.metaboliccode.com"
    );
  } catch {
    return;
  }
}
function z() {
  try {
    return A(
      "https://mc-api-us.metaboliccode.com"
    );
  } catch {
    return;
  }
}
function Y() {
  try {
    return A("https://mc-api-us.metaboliccode.com");
  } catch {
    return;
  }
}
function Z() {
  try {
    return A(
      "https://mc-lms.metaboliccode.com"
    );
  } catch {
    return;
  }
}
const tt = Q(), y = z() ?? G, Rt = y, et = tt ?? y, rt = Y() ?? W, nt = Z() ?? K, ot = (() => {
  try {
    return g == null ? void 0 : g.VITE_METABOLIC_DASHBOARD_STUB_API_KEY;
  } catch {
    return;
  }
})();
function Lt(t) {
  return t === ot;
}
function U(t) {
  return t.replace(/\/+$/, "");
}
function st(t) {
  const e = t == null ? void 0 : t.trim().toUpperCase();
  return e != null && e.startsWith("CA-") ? "ca" : "us";
}
function it(t, e) {
  return st(t) === "ca", U(e.us || e.fallback || "");
}
function O(t) {
  return it(t, {
    fallback: et,
    us: y
  });
}
function at({
  apiKey: t,
  userId: e,
  questionnaireResponseId: r,
  headers: n
}) {
  if (!t && !e && !r && n == null) return;
  const o = new Headers(n ?? void 0);
  return t && o.set("X-Api-Key", t), e && o.set("X-User-Id", e), r && (o.set("X-Questionnaire-Response-Id", r), o.set("X-Appointment-Id", r)), o;
}
function ct(t, e) {
  const r = t.replace(/\/$/, ""), n = e.startsWith("/") ? e : `/${e}`;
  return `${r}${n}`;
}
function lt(t, e) {
  const r = ct(t || "", "/api/v1/report/exists");
  return e ? `${r}?report_id=${encodeURIComponent(e)}` : r;
}
function ut(t) {
  return t instanceof DOMException && t.name === "AbortError";
}
async function Mt(t) {
  const {
    reportId: e,
    headers: r,
    apiKey: n,
    userId: o,
    questionnaireResponseId: s,
    fetchImpl: i = globalThis.fetch.bind(globalThis),
    signal: a
  } = t, _ = O(n), d = lt(_, e), c = at({
    apiKey: n,
    userId: o,
    questionnaireResponseId: s,
    headers: r
  });
  let p;
  try {
    p = await i(d, { method: "GET", headers: c, signal: a });
  } catch (f) {
    throw ut(f) ? f : new Error(
      `Network error checking report availability: ${f instanceof Error ? f.message : String(f)}`,
      { cause: f }
    );
  }
  if (p.status === 404) return !1;
  const m = await p.text();
  let h;
  try {
    h = m ? JSON.parse(m) : null;
  } catch {
    h = m;
  }
  if (!p.ok) {
    const f = typeof h == "object" && h !== null && "error" in h && typeof h.error == "string" ? h.error : null;
    throw new Error(f ?? `Failed to check report availability (HTTP ${p.status})`);
  }
  if (h === null || typeof h != "object" || Array.isArray(h) || !("exists" in h) || typeof h.exists != "boolean")
    throw new Error("Unexpected response shape for /report/exists: missing boolean 'exists'");
  return h.exists;
}
const ht = {
  stealth_health: "/api/v1/webhooks/stealth_health",
  stealth_health_short_report: "/api/v1/webhooks/stealth_health/short_report",
  stealth_health_junction: "/api/v1/webhooks/stealth_health/junction"
};
function I(t) {
  return t.replace(/\/+$/, "");
}
function P(t) {
  const e = t.trim();
  if (!e)
    throw new Error("Metabolic Code API key is required.");
  return e;
}
function R(t) {
  return O(t);
}
function _t({
  apiKey: t,
  kind: e
}) {
  return `${I(R(t))}${ht[e]}`;
}
async function L({
  apiKey: t,
  kind: e,
  body: r,
  headers: n,
  fetchImpl: o = fetch,
  signal: s
}) {
  const i = P(t), a = new Headers(n);
  return a.set("Content-Type", "application/json"), a.set("X-Api-Key", i), o(_t({ apiKey: i, kind: e }), {
    method: "POST",
    headers: a,
    body: JSON.stringify(r),
    cache: "no-store",
    redirect: "manual",
    signal: s
  });
}
function k(t, e) {
  var n;
  const r = new Headers();
  return r.set("X-Api-Key", P(t)), r.set("X-User-Id", e.userId), (n = e.userEmail) != null && n.trim() && r.set("X-User-Email", e.userEmail.trim()), r;
}
async function w(t) {
  const e = await t.text();
  let r;
  try {
    r = e.trim() ? JSON.parse(e) : {};
  } catch {
    r = { raw: e.slice(0, 500) };
  }
  if (!t.ok) {
    const n = r && typeof r == "object" && "error" in r ? String(r.error) : `Metabolic Code request failed with HTTP ${t.status}.`;
    throw Object.assign(new Error(n), { status: t.status, body: r });
  }
  return r;
}
async function Ut({
  apiKey: t,
  patient: e,
  fetchImpl: r = fetch,
  signal: n
}) {
  const o = I(R(t)), s = await r(`${o}/api/v1/patient/progress`, {
    method: "GET",
    headers: k(t, e),
    cache: "no-store",
    signal: n
  });
  return w(s);
}
async function Ht({
  apiKey: t,
  patient: e,
  questionnaireResponseId: r,
  fetchImpl: n = fetch,
  signal: o
}) {
  const s = I(R(t)), i = new URL(`${s}/api/v1/patient/short_report_summary`);
  r != null && r.trim() && i.searchParams.set("questionnaire_response_id", r.trim());
  const a = await n(i.toString(), {
    method: "GET",
    headers: k(t, e),
    cache: "no-store",
    signal: o
  });
  return w(a);
}
function B(t) {
  return t.replace(/\/+$/, "");
}
function l(t) {
  if (typeof t != "string") return null;
  const e = t.trim();
  return e.length ? e : null;
}
function C(t) {
  const e = t.trim();
  if (!e)
    throw new Error("Metabolic Code API key is required.");
  return e;
}
function dt(t) {
  return t === "video" || t === "article" || t === "guide" || t === "webinar" ? t : "guide";
}
async function j(t) {
  const e = await t.json().catch(() => null);
  return e && typeof e == "object" ? e : null;
}
function x() {
  return B(rt);
}
function pt() {
  return B(nt);
}
function ft(t) {
  const e = l(t);
  if (!e)
    throw new Error("LMS launch token is required.");
  const r = new URL("/launch", pt());
  return r.searchParams.set("token", e), r.toString();
}
function mt(t) {
  const e = l(t.id), r = l(t.title), n = l(t.course_slug) ?? l(t.courseSlug), o = l(t.resource_key) ?? l(t.resourceKey) ?? e;
  return !e || !r || !n || !o ? null : {
    id: e,
    type: dt(t.type),
    title: r,
    category: l(t.category) ?? "Courses",
    categoryId: l(t.category_id) ?? l(t.categoryId) ?? "courses",
    excerpt: l(t.excerpt),
    thumbnailUrl: l(t.thumbnail_url) ?? l(t.thumbnailUrl),
    imageUrl: l(t.image_url) ?? l(t.imageUrl),
    url: null,
    isFeatured: !!(t.is_featured ?? t.isFeatured),
    launchType: "lms_course",
    courseSlug: n,
    resourceKey: o
  };
}
function Ot(t, e) {
  const r = /* @__PURE__ */ new Set(), n = [];
  for (const o of e)
    r.has(o.id) || (r.add(o.id), n.push(o));
  for (const o of t)
    r.has(o.id) || (r.add(o.id), n.push(o));
  return n;
}
async function Pt({
  apiKey: t,
  fetchImpl: e = fetch,
  signal: r
}) {
  const n = C(t), o = await e(`${x()}/api/v1/lms/partner_resources`, {
    method: "GET",
    headers: {
      Accept: "application/json",
      "X-Api-Key": n
    },
    cache: "no-store",
    signal: r
  });
  if (!o.ok) return [];
  const s = await j(o), i = s == null ? void 0 : s.resources;
  return Array.isArray(i) ? i.map(
    (a) => mt(a)
  ).filter((a) => a !== null) : [];
}
async function kt({
  apiKey: t,
  externalUserId: e,
  email: r,
  displayName: n,
  courseSlug: o,
  resourceKey: s,
  fetchImpl: i = fetch,
  signal: a
}) {
  var m;
  const _ = C(t), d = await i(`${x()}/api/v1/lms/partner_launches`, {
    method: "POST",
    headers: {
      Accept: "application/json",
      "Content-Type": "application/json",
      "X-Api-Key": _
    },
    cache: "no-store",
    signal: a,
    body: JSON.stringify({
      launch: {
        external_user_id: e,
        email: r,
        display_name: n,
        course_slug: o,
        resource_key: s
      }
    })
  }), c = await j(d);
  if (!d.ok) {
    const h = typeof (c == null ? void 0 : c.error) == "string" ? c.error : "lms_launch_failed";
    throw new Error(h);
  }
  const p = l(c == null ? void 0 : c.launch_token);
  if (!p) throw new Error("lms_launch_failed");
  return {
    launchUrl: ft(p),
    expiresAt: l(c == null ? void 0 : c.expires_at),
    courseTitle: l((m = c == null ? void 0 : c.course) == null ? void 0 : m.title)
  };
}
const N = "enroll.questionnaire.completed", $ = "metabolic_code.short_report.completed", X = "enroll.junction_order.created";
class H extends Error {
  constructor(r, n, o, s) {
    super(r);
    S(this, "status");
    S(this, "statusText");
    S(this, "body");
    this.name = "MetabolicStealthHealthRequestError", this.status = n, this.statusText = o, this.body = s;
  }
}
function Et(t) {
  return t.replace(/\/+$/, "");
}
function u(t) {
  return typeof t == "string" ? t.trim() : "";
}
function St(t) {
  return Object.fromEntries(Object.entries(t).filter(([, e]) => e !== void 0));
}
function v(t, e) {
  const r = u(t);
  if (!r)
    throw new Error("Stealth Health Functions base URL is required.");
  return `${Et(r)}/${e}`;
}
function At(t) {
  if (!t.trim()) return null;
  try {
    const e = JSON.parse(t);
    return e && typeof e == "object" && !Array.isArray(e) ? e : { raw: e };
  } catch {
    return null;
  }
}
async function D(t) {
  const e = await t.text(), r = At(e);
  if (!r)
    throw new H(
      `Firebase Function error: ${t.status} ${t.statusText}`,
      t.status || 500,
      t.statusText,
      e.slice(0, 200)
    );
  if (!t.ok) {
    const n = typeof r.error == "string" ? r.error : `Request failed (HTTP ${t.status}).`;
    throw new H(
      n,
      t.status,
      t.statusText,
      r
    );
  }
  return r;
}
async function wt({
  functionsBaseUrl: t,
  questionnaireResponseId: e,
  questionnaireId: r,
  enrollSlug: n,
  profileData: o,
  selectedMedication: s,
  partnerRef: i,
  whiteLabelDomain: a,
  fetchImpl: _ = fetch,
  signal: d
}) {
  const c = await _(
    v(t, "processQuestionnaireSubmission"),
    {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(
        St({
          questionnaireResponseId: e,
          questionnaireId: r,
          enrollSlug: u(n) || void 0,
          profileData: o,
          selectedMedication: s,
          partnerRef: i,
          whiteLabelDomain: a
        })
      ),
      signal: d
    }
  );
  return D(c);
}
async function Bt({
  functionsBaseUrl: t,
  body: e,
  fetchImpl: r = fetch,
  signal: n
}) {
  const o = await r(v(t, "createPatientLabOrder"), {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    cache: "no-store",
    body: e || "{}",
    signal: n
  });
  return D(o);
}
function T(t) {
  if (t == null || typeof t != "object") return t;
  if (typeof t.toDate == "function") {
    const e = t.toDate();
    return Number.isNaN(e.getTime()) ? null : e.toISOString();
  }
  return Array.isArray(t) ? t.map(T) : Object.fromEntries(
    Object.entries(t).map(([e, r]) => [
      e,
      T(r)
    ])
  );
}
function M(t) {
  var r;
  if (Array.isArray(t.slugs))
    return t.slugs.filter(
      (n) => typeof n == "string" && !!n.trim()
    );
  const e = (r = t.data) == null ? void 0 : r.slugs;
  return Array.isArray(e) ? e.filter((n) => typeof n == "string" && !!n.trim()) : [];
}
function E(t, e) {
  return u(t.slug) || u(e) || M(t)[0] || "";
}
function F({
  appointmentId: t,
  enrollPage: e,
  enrollSlug: r,
  questionnaireId: n,
  questionnaireResponseId: o,
  responseData: s,
  user: i,
  occurredAt: a = (/* @__PURE__ */ new Date()).toISOString()
}) {
  const _ = T(s), d = _.questionnaireSnapshot && typeof _.questionnaireSnapshot == "object" && !Array.isArray(_.questionnaireSnapshot) ? _.questionnaireSnapshot : {}, c = E(e, r);
  return {
    event: N,
    occurredAt: a,
    enrollPage: {
      id: e.id,
      slug: c,
      slugs: M(e)
    },
    appointment: { id: t },
    appointmentId: t,
    user: {
      id: i.uid,
      uid: i.uid,
      email: i.email,
      firstname: i.firstname,
      lastname: i.lastname,
      birthday: i.birthday,
      telephone: i.telephone
    },
    questionnaire: {
      id: n,
      title: typeof d.title == "string" ? d.title : "",
      version: typeof d.version == "number" ? d.version : null
    },
    response: {
      ..._,
      id: o,
      questionnaireId: n
    }
  };
}
async function Ct({
  apiKey: t,
  fetchImpl: e,
  signal: r,
  ...n
}) {
  const o = F(n);
  return L({
    apiKey: t,
    kind: "stealth_health",
    body: o,
    headers: {
      "User-Agent": "StealthHealth-EnrollWebhook/1.0",
      "X-StealthHealth-Event": N,
      "X-StealthHealth-Enroll-Slug": E(
        n.enrollPage,
        n.enrollSlug
      ),
      "X-StealthHealth-Appointment-Id": n.appointmentId,
      "X-StealthHealth-Questionnaire-Id": n.questionnaireId,
      "X-StealthHealth-Questionnaire-Response-Id": n.questionnaireResponseId
    },
    fetchImpl: e,
    signal: r
  });
}
function bt({
  submissionId: t,
  ...e
}) {
  const r = u(t) || e.questionnaireResponseId;
  return {
    ...F({
      ...e,
      appointmentId: r
    }),
    event: $,
    appointment: { id: r },
    appointmentId: r
  };
}
async function jt({
  apiKey: t,
  fetchImpl: e,
  signal: r,
  ...n
}) {
  const o = bt(n), s = typeof o.appointmentId == "string" ? o.appointmentId : n.questionnaireResponseId;
  return L({
    apiKey: t,
    kind: "stealth_health_short_report",
    body: o,
    headers: {
      "User-Agent": "StealthHealth-EnrollWebhook/1.0",
      "X-StealthHealth-Event": $,
      "X-StealthHealth-Enroll-Slug": E(
        n.enrollPage,
        n.enrollSlug
      ),
      "X-StealthHealth-Appointment-Id": s,
      "X-StealthHealth-Questionnaire-Id": n.questionnaireId,
      "X-StealthHealth-Questionnaire-Response-Id": n.questionnaireResponseId
    },
    fetchImpl: e,
    signal: r
  });
}
function b(t) {
  return t && typeof t == "object" && !Array.isArray(t) ? t : null;
}
function q(t, e) {
  return b(t == null ? void 0 : t[e]);
}
function gt(t) {
  const e = b(t), r = q(e, "order");
  return u(e == null ? void 0 : e.junctionOrderId) || u(e == null ? void 0 : e.junction_order_id) || u(e == null ? void 0 : e.orderId) || u(r == null ? void 0 : r.id);
}
function Tt(t) {
  const e = b(t), r = q(e, "order");
  return u(e == null ? void 0 : e.status) || u(e == null ? void 0 : e.junctionStatus) || u(e == null ? void 0 : e.labOrderStatus) || u(r == null ? void 0 : r.status);
}
function yt({
  enrollPage: t,
  requestBody: e,
  responseData: r,
  appointmentData: n,
  occurredAt: o = (/* @__PURE__ */ new Date()).toISOString()
}) {
  const s = b(r), i = u(s == null ? void 0 : s.appointmentId) || u(e == null ? void 0 : e.appointmentId), a = gt(r);
  if (!i || !a) return null;
  const _ = u(e == null ? void 0 : e.questionnaireResponseId) || u(n == null ? void 0 : n.questionnaireResponseId), d = Tt(r), c = E(t);
  return {
    event: X,
    occurredAt: o,
    enrollPage: {
      id: t.id,
      slug: c,
      slugs: M(t)
    },
    appointment: { id: i },
    appointmentId: i,
    ..._ ? { questionnaireResponseId: _ } : {},
    junctionOrder: {
      id: a,
      status: d || null
    },
    junctionOrderId: a,
    junctionStatus: d || null
  };
}
async function xt({
  apiKey: t,
  fetchImpl: e,
  signal: r,
  ...n
}) {
  const o = yt(n);
  if (!o) return null;
  const s = typeof o.questionnaireResponseId == "string" ? o.questionnaireResponseId : "", i = typeof o.appointmentId == "string" ? o.appointmentId : "", a = typeof o.junctionOrderId == "string" ? o.junctionOrderId : "";
  return L({
    apiKey: t,
    kind: "stealth_health_junction",
    body: o,
    headers: {
      "User-Agent": "StealthHealth-EnrollWebhook/1.0",
      "X-StealthHealth-Event": X,
      ...E(n.enrollPage) ? { "X-StealthHealth-Enroll-Slug": E(n.enrollPage) } : {},
      "X-StealthHealth-Appointment-Id": i,
      "X-StealthHealth-Junction-Order-Id": a,
      ...s ? { "X-StealthHealth-Questionnaire-Response-Id": s } : {}
    },
    fetchImpl: e,
    signal: r
  });
}
export {
  R as A,
  x as B,
  pt as C,
  Ot as D,
  st as E,
  mt as F,
  w as G,
  it as H,
  gt as I,
  Tt as J,
  Bt as K,
  wt as L,
  ot as M,
  N as S,
  rt as a,
  at as b,
  nt as c,
  et as d,
  Rt as e,
  y as f,
  O as g,
  H as h,
  Lt as i,
  $ as j,
  X as k,
  _t as l,
  ft as m,
  F as n,
  yt as o,
  bt as p,
  lt as q,
  Mt as r,
  kt as s,
  L as t,
  Ct as u,
  xt as v,
  jt as w,
  Pt as x,
  Ut as y,
  Ht as z
};
