import { isDefined as S } from "@scalar/oas-utils/helpers";
import { isConfigurationWithSources as y } from "@scalar/types/api-reference";
import R from "github-slugger";
import { computed as g, ref as b, watch as A } from "vue";
const w = "api", h = new R(), C = (t) => t ? (Array.isArray(t) ? t : [t]).flatMap((u) => {
  if (y(u)) {
    const { sources: s, ...r } = u;
    return (s == null ? void 0 : s.map((m) => ({ ...r, ...m }))) ?? [];
  }
  return [u];
}).map((u, s) => u && I(u, s)).filter(S) : [], I = (t, a = 0) => {
  const e = {
    ...t,
    // @ts-expect-error this is before parsing so we transform the old style
    ...t.spec ?? {}
  };
  if (!(!(e != null && e.url) && !(e != null && e.content)))
    return h.reset(), e.title ? {
      ...e,
      slug: e.slug || h.slug(e.title),
      title: e.title
    } : e.slug ? {
      ...e,
      title: e.slug
    } : {
      ...e,
      slug: `api-${a + 1}`,
      title: `API #${a + 1}`
    };
}, T = ({
  configuration: t,
  initialIndex: a,
  isIntersectionEnabled: e,
  hash: u,
  hashPrefix: s
}) => {
  const r = g(() => C(t.value)), f = b((() => {
    if (typeof window > "u")
      return typeof a == "number" ? a : 0;
    const n = new URL(window.location.href).searchParams.get(w);
    if (n) {
      const o = r.value.findIndex((p) => p.slug === n);
      if (o !== -1)
        return o;
      const i = Number.parseInt(n, 10);
      if (!isNaN(i) && i >= 0 && i < r.value.length)
        return i;
    }
    const l = r.value.findIndex((o) => "default" in o && o.default === !0);
    return l !== -1 ? l : typeof a == "number" ? a : 0;
  })()), c = g(() => {
    var n, l;
    return t.value && y(t.value) ? {
      ...t.value,
      ...(l = (n = t.value) == null ? void 0 : n.sources) == null ? void 0 : l[f.value],
      ...r.value[f.value]
    } : {
      ...[t.value].flat()[f.value] ?? {},
      ...r.value[f.value]
    };
  });
  return A(
    f,
    (d) => {
      var i, p, v;
      if (typeof window > "u" || r.value.length === 1)
        return;
      const n = new URL(window.location.href), l = r.value[d];
      c.value.pathRouting && (n.pathname = ((i = c.value.pathRouting) == null ? void 0 : i.basePath) ?? "");
      const o = (l == null ? void 0 : l.slug) ?? d.toString();
      n.searchParams.set(w, o), n.hash = "", window.history.replaceState({}, "", n.toString()), u.value = "", s.value = "", e.value = !1, typeof window < "u" && window.scrollTo({ top: 0, behavior: "instant" }), (v = (p = c.value).onDocumentSelect) == null || v.call(p);
    },
    { flush: "sync" }
  ), {
    selectedConfiguration: c,
    availableDocuments: r,
    selectedDocumentIndex: f,
    isIntersectionEnabled: e,
    hash: u,
    hashPrefix: s
  };
};
export {
  C as normalizeConfigurations,
  T as useMultipleDocuments
};
