import { round as W, debounce as z } from "es-toolkit";
import { get as V } from "es-toolkit/compat";
import { toValue as u, ref as A, reactive as R, computed as p, watch as q, effectScope as J, nextTick as C, readonly as w } from "vue";
import { DECIMAL_PRECISION as Y, DEBOUNCE as G } from "./constants.js";
import { t as v } from "./locale.js";
import { i as h } from "./isDefined-DzVx0B6k.js";
function H(e) {
  const t = e.replace(/^\//, ""), r = "data/attributes/";
  if (t.startsWith(r))
    return t.slice(r.length).split("/").filter(Boolean).join(".");
  const s = t.split("/").filter(Boolean);
  return s.length ? s.join(".") : e;
}
function K(e) {
  var r;
  const t = {};
  for (const s of e) {
    const i = (r = s.source) == null ? void 0 : r.pointer;
    if (!i)
      continue;
    const a = s.detail || s.title || "";
    if (!a)
      continue;
    const g = H(i);
    t[g] = a;
  }
  return t;
}
function ae(e = {}) {
  return {
    name: "email",
    validator(t) {
      return !h(t) || typeof t == "string" && /^\S+@\S+\.\S+$/.test(t);
    },
    message: e.message || v("ll.validation.email")
  };
}
function ue(e) {
  return {
    name: "maxLength",
    validator(t) {
      const r = u(e.max), s = u(t);
      if (!h(s))
        return !0;
      let i = String(s);
      return e.trim && (i = i.trim()), i.length <= r;
    },
    message: e.message || (() => v("ll.validation.maxLength", { max: String(u(e.max)) }))
  };
}
function ce(e) {
  return {
    name: "maxValue",
    validator(t) {
      const r = u(e.max);
      return !h(t) || Number(t) <= r;
    },
    message: e.message || (() => v("ll.validation.maxValue", { max: String(u(e.max)) }))
  };
}
function le(e) {
  return {
    name: "minLength",
    validator(t) {
      const r = u(e.min), s = u(t);
      if (!h(s))
        return !0;
      let i = String(s);
      return e.trim && (i = i.trim()), i.length >= r;
    },
    message: e.message || (() => v("ll.validation.minLength", { min: String(u(e.min)) }))
  };
}
function me(e) {
  return {
    name: "minValue",
    validator(t) {
      const r = u(e.min);
      return !h(t) || Number(t) >= r;
    },
    message: e.message || (() => v("ll.validation.minValue", { min: String(u(e.min)) }))
  };
}
function fe(e) {
  return {
    name: "pattern",
    validator(t) {
      const r = u(t);
      return !h(r) || e.regex.test(String(r));
    },
    message: () => {
      if (typeof e.message != "string" || !e.message.trim())
        throw new Error(
          'The "pattern" ruleFactory requires a custom message informing the user of the required pattern.'
        );
      return e.message;
    }
  };
}
function de(e = {}) {
  return {
    name: "positiveNumber",
    validator(t) {
      return !h(t) || Number(t) > 0;
    },
    message: e.message || v("ll.validation.positiveNumber")
  };
}
function he(e = {}) {
  return {
    name: "price",
    validator(t) {
      const r = Number(t);
      return !h(t) || r !== 1 / 0 && r >= 0 && r === W(r, Y.CURRENCY);
    },
    message: e.message || v("ll.validation.price")
  };
}
function ge(e = {}) {
  return {
    name: "required",
    validator(t) {
      return h(typeof t == "string" ? t.trim() : t);
    },
    message: e.message || v("ll.validation.required")
  };
}
function pe(e = {}) {
  return {
    name: "wholeNumber",
    validator(t) {
      return !h(t) || Number.isInteger(Number(t)) && Number(t) >= 0;
    },
    message: e.message || v("ll.validation.wholeNumber")
  };
}
const Q = "api";
let U = null;
function ve(e) {
  U = e;
}
function k(e) {
  return typeof e != "object" || e === null || !("validator" in e) ? !1 : typeof Reflect.get(e, "validator") == "function";
}
function X(e) {
  return Array.isArray(e) && e.every(k);
}
function I(e, t = "") {
  if (e === null || typeof e != "object")
    return [];
  if (Array.isArray(e)) {
    if (e.length === 0)
      return t ? [t] : [];
    const s = e[0];
    if (k(s))
      return t ? [t] : [];
    const i = [];
    for (let a = 0; a < e.length; a++) {
      const g = t === "" ? String(a) : `${t}.${a}`;
      i.push(...I(e[a], g));
    }
    return i;
  }
  const r = [];
  for (const s of Object.keys(e)) {
    const i = e[s], a = t === "" ? s : `${t}.${s}`;
    r.push(...I(i, a));
  }
  return r;
}
function be({
  rules: e,
  values: t
}) {
  const r = A({}), s = R({}), i = /* @__PURE__ */ new Map(), a = p(() => I(u(e)).sort());
  function g(n) {
    const o = i.get(n);
    if (o && (o.cancelDebounced(), o.stop(), o.stopFieldScope(), i.delete(n)), s[n] && delete s[n], r.value[n]) {
      const c = { ...r.value };
      delete c[n], r.value = c;
    }
  }
  function F(n) {
    if (s[n])
      return;
    const o = A(V(u(t), n)), c = () => {
      o.value = V(u(t), n);
    }, d = U ?? G.FAST, l = d > 0 ? z(c, d) : null, y = () => {
      l ? l() : c();
    }, M = () => {
      l && l.cancel(), c();
    }, j = () => {
      l && l.cancel();
    }, N = q(
      () => V(u(t), n),
      () => {
        y();
      },
      // With the debounce off, `flush: 'sync'` makes the watch run on the same tick as
      // the source mutation. Vue's default async flush would add a microtask of lag,
      // which defeats turning the debounce off.
      d === 0 ? { flush: "sync" } : void 0
    ), L = J(), O = L.run(
      () => Z({
        fieldName: n,
        fieldValue: o,
        flush: M,
        getApiError: () => r.value[n] || "",
        getRules: () => {
          const $ = V(u(e), n);
          return X($) ? $ : [];
        }
      })
    );
    if (!O) {
      N(), j(), L.stop();
      return;
    }
    i.set(n, {
      stop: N,
      cancelDebounced: j,
      flushDebounced: M,
      stopFieldScope: () => L.stop()
    }), s[n] = O;
  }
  q(
    a,
    (n, o) => {
      const c = o ?? [], d = new Set(n), l = new Set(c);
      for (const y of c)
        d.has(y) || g(y);
      for (const y of n)
        l.has(y) || F(y);
    },
    { immediate: !0 }
  );
  const b = p(() => Object.values(s)), S = p(() => b.value.some((n) => n.errors.length > 0)), T = p(() => b.value.some((n) => n.isTouched)), x = p(() => b.value.filter((n) => n.isDirty)), m = async function({ preventScroll: n } = {}) {
    if (b.value.forEach((o) => {
      o.setTouched(!1), o.setTouched(!0);
    }), await C(), S.value && !n) {
      const o = Object.entries(s).find(([, l]) => l.errorMessage), c = (o == null ? void 0 : o[0]) || "", d = document == null ? void 0 : document.querySelector(`[name="${c}"]`);
      d && d.scrollIntoView({ behavior: "smooth" });
    }
    return !S.value;
  }, f = function(n) {
    var o;
    return ((o = s[n]) == null ? void 0 : o.errorMessage) || "";
  }, D = function(n) {
    if (!s[n])
      throw new Error(`In touch: fieldName "${n}" does not exist in the validation fields.`);
    s[n].setTouched();
  }, E = async function() {
    await C(), b.value.forEach((n) => {
      n.setTouched(!1);
    });
  }, _ = function(n) {
    b.value.forEach((o) => {
      o.setInitialValue(V(n, o.name));
    });
  };
  function B(n) {
    const o = K(n), c = a.value, d = {};
    for (const l of c)
      o[l] && (d[l] = o[l]);
    r.value = d;
  }
  function P(n) {
    if (n) {
      const o = { ...r.value };
      delete o[n], r.value = o;
    } else
      r.value = {};
  }
  return R({
    validate: m,
    getError: f,
    touch: D,
    setAllUntouched: E,
    setInitialValues: _,
    setApiErrors: B,
    clearApiErrors: P,
    flush: function(n) {
      var o;
      n !== void 0 ? (o = i.get(n)) == null || o.flushDebounced() : i.forEach((c) => c.flushDebounced());
    },
    fields: s,
    dirtyFields: x,
    hasErrors: S,
    someTouched: T
  });
}
function Z({
  fieldName: e,
  fieldValue: t,
  getRules: r,
  flush: s,
  getApiError: i
}) {
  const a = A(t.value), g = A(!1), F = p(() => (t.value ?? "") !== (a.value ?? "")), b = p(() => g.value ? r().map((f) => ({
    fieldName: e,
    ruleName: f.name,
    isValid: f.validator(t.value),
    message: typeof f.message == "function" ? f.message(t.value) : f.message
  })) : []), S = p(() => {
    const m = i(), f = m !== "" ? [{ ruleName: Q, message: m }] : [], D = b.value.filter((E) => !E.isValid).map((E) => ({
      ruleName: E.ruleName,
      message: E.message
    }));
    return [...f, ...D];
  });
  function T(m = !0) {
    s(), g.value = m;
  }
  function x(m) {
    a.value = m;
  }
  return R({
    name: e,
    currentValue: w(t),
    initialValue: w(a),
    isTouched: w(g),
    isDirty: w(F),
    errorMessage: p(() => {
      var m, f;
      return ((f = (m = S.value) == null ? void 0 : m[0]) == null ? void 0 : f.message) || "";
    }),
    errors: S,
    setInitialValue: x,
    setTouched: T
  });
}
export {
  be as default,
  ae as email,
  h as isDefined,
  ue as maxLength,
  ce as maxValue,
  le as minLength,
  me as minValue,
  fe as pattern,
  de as positiveNumber,
  he as price,
  ge as required,
  ve as setUseValidationDebounceMs,
  pe as wholeNumber
};
//# sourceMappingURL=useValidation.js.map
