import { isDefined as h } from "@scalar/oas-utils/helpers";
import { isConfigurationWithSources as y } from "@scalar/types/api-reference";
import S from "github-slugger";
import { computed as v, ref as A, watch as b } from "vue";
const w = "api", g = new S(), C = (t) => t ? (Array.isArray(t) ? t : [t]).flatMap((u) => {
  if (y(u)) {
    const { sources: a, ...r } = u;
    return (a == null ? void 0 : a.map((m) => ({ ...r, ...m }))) ?? [];
  }
  return [u];
}).map((u, a) => u && I(u, a)).filter(h) : [], I = (t, s = 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 g.reset(), e.title ? {
      ...e,
      slug: e.slug || g.slug(e.title),
      title: e.title
    } : e.slug ? {
      ...e,
      title: e.slug
    } : {
      ...e,
      slug: `api-${s + 1}`,
      title: `API #${s + 1}`
    };
}, P = ({
  configuration: t,
  initialIndex: s,
  isIntersectionEnabled: e,
  hash: u,
  hashPrefix: a
}) => {
  const r = v(() => C(t.value)), f = A((() => {
    if (typeof window > "u")
      return typeof s == "number" ? s : 0;
    const n = new URL(window.location.href).searchParams.get(w);
    if (n) {
      const o = r.value.findIndex((d) => d.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 s == "number" ? s : 0;
  })()), p = v(() => {
    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 b(
    f,
    (c) => {
      var i, d;
      if (typeof window > "u" || r.value.length === 1)
        return;
      const n = new URL(window.location.href), l = r.value[c], o = (l == null ? void 0 : l.slug) ?? c.toString();
      n.searchParams.set(w, o), n.hash = "", window.history.replaceState({}, "", n.toString()), u.value = "", a.value = "", e.value = !1, typeof window < "u" && window.scrollTo({ top: 0, behavior: "instant" }), (d = (i = p.value).onDocumentSelect) == null || d.call(i);
    },
    { flush: "sync" }
  ), {
    selectedConfiguration: p,
    availableDocuments: r,
    selectedDocumentIndex: f,
    isIntersectionEnabled: e,
    hash: u,
    hashPrefix: a
  };
};
export {
  C as normalizeConfigurations,
  P as useMultipleDocuments
};
