import { computed as g, toValue as l, watch as h, onBeforeUnmount as T } from "vue";
const p = 5 * 1e3, M = 60 * 1e3, E = () => {
  let t = null;
  const e = () => {
    t && (clearTimeout(t), t = null);
  };
  return {
    clear: e,
    schedule: (s, c) => {
      e(), t = setTimeout(s, c);
    }
  };
}, V = (t) => {
  let e = t;
  return {
    reset: () => {
      e = t;
    },
    backoff: () => {
      e = Math.min(e * 2, M);
    },
    get: () => e
  };
}, k = (t) => t.flatMap(([e]) => e), w = ({
  documentName: t,
  store: e,
  initialTimeout: u = p
}) => {
  const s = g(() => {
    const r = l(e), o = l(t);
    return !r || !o ? null : r.workspace.documents[o];
  }), c = E(), a = V(u), f = () => {
    a.reset(), c.schedule(i, a.get());
  }, d = () => {
    a.backoff(), c.schedule(i, a.get());
  }, i = async () => {
    const r = l(e), o = l(t), m = s.value?.["x-scalar-original-source-url"];
    if (!r || !o || !m)
      return;
    const n = await r.rebaseDocument({
      name: o,
      url: m
    });
    n?.ok ? (await n.applyChanges({ resolvedConflicts: k(n.conflicts) }), f()) : n?.ok === !1 && n.type === "NO_CHANGES_DETECTED" ? f() : d();
  };
  h(
    [() => s.value?.["x-scalar-original-source-url"], () => s.value?.["x-scalar-watch-mode"]],
    ([r, o = !1]) => {
      if (!l(e)) {
        c.clear();
        return;
      }
      if (c.clear(), !r || !o) {
        a.reset();
        return;
      }
      c.schedule(i, a.get());
    },
    { immediate: !0 }
  ), T(() => {
    c.clear();
  });
};
export {
  w as useDocumentWatcher
};
