import m from "dayjs";
import { ref as v, watch as M, onBeforeUnmount as h } from "vue";
import { formatDuration as p } from "./utils.mjs";
function r(n, u) {
  const e = Math.abs(n - u), t = {
    diffMs: e,
    type: n < u ? "ago" : "late",
    diffFormatted: p(e)
  };
  return e < 60 * 1e3 ? (t.unit = "s", t.count = Math.round(e / 1e3)) : e < 3600 * 1e3 ? (t.unit = "m", t.count = Math.round(e / (60 * 1e3))) : e < 1440 * 60 * 1e3 ? (t.unit = "h", t.count = Math.round(e / (3600 * 1e3))) : e < 720 * 60 * 60 * 1e3 ? (t.unit = "d", t.count = Math.round(e / (1440 * 60 * 1e3))) : e < 365 * 24 * 60 * 60 * 1e3 ? (t.unit = "M", t.count = Math.round(e / (720 * 60 * 60 * 1e3))) : (t.unit = "y", t.count = Math.round(e / 365 / (1440 * 60 * 1e3))), t;
}
function o(n) {
  return m(n).valueOf();
}
let g = 1;
function w() {
  return g++;
}
const i = /* @__PURE__ */ new Map();
let s, f;
function b(n, u) {
  i.set(n, u), i.size && !f && (clearInterval(s), s = setInterval(() => {
    f = !0;
    const e = Date.now();
    i.forEach((t) => {
      t.interval && Math.abs(e - t.updated - t.interval) < 50 && (t.timeAgo.value = r(t.ts, e), t.updated = e);
    });
  }, 5e3));
}
function I(n) {
  i.delete(n), i.size || (clearInterval(s), f = !1);
}
const D = (n, u, e) => {
  const t = w(), a = v(
    r(o(n.value), o(u))
  ), l = {
    ts: o(n.value),
    timeAgo: a,
    interval: e.value,
    updated: Date.now()
  };
  return M(
    () => n.value,
    (d) => {
      const c = o(d);
      l.ts = c, a.value = r(c, o(u));
    }
  ), b(t, l), h(() => {
    I(t);
  }), a;
};
export {
  D as default,
  w as getId,
  r as getTimeAgo,
  b as subscribe,
  I as unsubscribe
};
