import { useRef as k, useCallback as y } from "../../external/.pnpm/preact@10.28.2/node_modules/preact/hooks/dist/hooks.module.js";
function R(s, u) {
  const o = u.split(".");
  let i = s;
  for (const t of o) {
    if (i == null) return;
    i = i[t];
  }
  return i;
}
function M(s, u, o) {
  if (!u)
    return;
  const i = u.split("."), t = i.pop();
  let l = s;
  for (let c = 0; c < i.length; c++) {
    const _ = i[c];
    if (typeof l[_] != "object" || l[_] === null) {
      const p = i[c + 1];
      l[_] = p !== void 0 && /^\d+$/.test(p) ? [] : {};
    }
    l = l[_];
  }
  l[t] = o;
}
function E(s) {
  if (s == null || typeof s != "object")
    return s;
  if (Array.isArray(s)) return s.filter((o) => o !== "" && o !== null);
  const u = {};
  for (const [o, i] of Object.entries(s))
    if (!(i === "" || i === null || i === void 0))
      if (typeof i == "object" && !Array.isArray(i)) {
        const t = E(i);
        Object.keys(t).length > 0 && (u[o] = t);
      } else
        u[o] = i;
  return u;
}
function b(s, u = "") {
  const o = {};
  for (const i in s)
    if (Object.prototype.hasOwnProperty.call(s, i)) {
      const t = s[i], l = u ? `${u}.${i}` : i;
      t && typeof t == "object" && !Array.isArray(t) && !(t instanceof Date) && !(t instanceof File) && !(t instanceof FileList) ? Object.assign(o, b(t, l)) : o[l] = t;
    }
  return o;
}
async function q(s, u, o) {
  if (u) {
    if (u.required && (s == null || s === "" || Array.isArray(s) && s.length === 0))
      return { type: "required", message: typeof u.required == "string" ? u.required : o.get("common.errors.fieldRequired") };
    if (u.validate)
      try {
        const i = await u.validate(s);
        if (!i.valid)
          return { message: i.message, type: "validation" };
      } catch (i) {
        return console.error("A custom validation function threw an error:", i), { type: "validation", message: "Validation error occurred" };
      }
  }
}
function K(s) {
  const { defaultValues: u = {}, i18n: o } = s, i = k();
  if (!i.current) {
    const e = {
      _values: /* @__PURE__ */ new Map(),
      _errors: /* @__PURE__ */ new Map(),
      _touched: /* @__PURE__ */ new Map(),
      _dirty: /* @__PURE__ */ new Map(),
      _subscribers: /* @__PURE__ */ new Set(),
      _validationCounters: /* @__PURE__ */ new Map(),
      _fieldRules: /* @__PURE__ */ new Map(),
      _options: s,
      _defaultValues: u,
      _isSubmitting: !1,
      _computedErrors: {},
      _computedTouchedFields: {},
      _computedDirtyFields: {},
      subscribe: (r) => (e._subscribers.add(r), () => e._subscribers.delete(r)),
      notify: () => {
        e._subscribers.forEach((r) => r());
      },
      setValue: (r, n, f) => {
        const v = R(e._defaultValues, r), V = n !== v;
        e._values.set(r, n), f?.shouldDirty !== !1 && (e._dirty.set(r, V), V ? e._computedDirtyFields[r] = !0 : delete e._computedDirtyFields[r]), f?.shouldTouch && (e._touched.set(r, !0), e._computedTouchedFields[r] = !0);
        const a = e._options.mode || "onBlur";
        f?.shouldValidate !== !1 && (a === "onInput" || a === "all" || f?.shouldValidate) && F({ control: e, name: r, value: n, rules: e._fieldRules.get(r), i18n: o }), e.notify();
      },
      setTouched: (r, n) => {
        e._touched.set(r, n), n ? e._computedTouchedFields[r] = !0 : delete e._computedTouchedFields[r], e.notify();
      },
      getValue: (r) => e._values.get(r),
      getFieldState: (r) => ({
        error: e._errors.get(r),
        isTouched: e._touched.get(r) || !1,
        isDirty: e._dirty.get(r) || !1
      }),
      getFormState: () => {
        const n = !(Object.keys(e._computedErrors).length > 0) && !e._isSubmitting;
        return {
          dirtyFields: e._computedDirtyFields,
          touchedFields: e._computedTouchedFields,
          isSubmitting: e._isSubmitting,
          isValid: n,
          errors: e._computedErrors
        };
      },
      register: (r, n) => (e._fieldRules.set(r, n), () => {
        e._fieldRules.delete(r), e._validationCounters.delete(r);
      }),
      trigger: async (r) => {
        const n = r ? Array.isArray(r) ? r : [r] : Array.from(e._values.keys());
        let f = !1;
        n.forEach((a) => {
          e._touched.has(a) || (e._touched.set(a, !0), e._computedTouchedFields[a] = !0, f = !0);
        }), f && e.notify();
        const v = n.map(async (a) => {
          const O = e._values.get(a), m = e._fieldRules.get(a);
          return m && await F({ control: e, name: a, value: O, rules: m, i18n: o }), !e._errors.has(a);
        });
        return (await Promise.all(v)).every((a) => a);
      }
    }, d = b(u);
    Object.entries(d).forEach(([r, n]) => {
      e._values.set(r, n);
    }), i.current = e;
  }
  const t = i.current, l = t._computedErrors, c = t._computedDirtyFields, _ = t._computedTouchedFields, w = !(Object.keys(l).length > 0) && !t._isSubmitting, S = {
    dirtyFields: c,
    touchedFields: _,
    isSubmitting: t._isSubmitting,
    isValid: w,
    errors: l
  }, T = y(
    (e, d, r) => {
      t.setValue(e, d, r);
    },
    [t]
  ), g = y(
    (e) => {
      if (e)
        return t._values.get(e);
      const d = {};
      return t._values.forEach((r, n) => {
        M(d, n, r);
      }), d;
    },
    [t]
  ), A = y(() => t._values, [t]), D = y(
    (e) => {
      const d = e || t._defaultValues;
      e && (t._defaultValues = e), t._values.clear(), t._errors.clear(), t._touched.clear(), t._dirty.clear(), t._validationCounters.clear(), t._computedErrors = {}, t._computedTouchedFields = {}, t._computedDirtyFields = {};
      const r = b(d);
      Object.entries(r).forEach(([n, f]) => {
        t._values.set(n, f);
      }), t._isSubmitting = !1, t.notify();
    },
    [t]
  ), h = y(
    async (e) => t.trigger(e),
    [t]
  ), C = y(
    (e, d) => async (r) => {
      r && r.preventDefault && r.preventDefault(), t._isSubmitting = !0, t.notify();
      try {
        if (await h()) {
          const f = E(g());
          await e(f);
        } else d && d(t._computedErrors);
      } finally {
        t._isSubmitting = !1, t.notify();
      }
    },
    [t, h, g]
  );
  return {
    control: t,
    handleSubmit: C,
    setValue: T,
    getValues: g,
    getValueMap: A,
    reset: D,
    formState: S,
    trigger: h
  };
}
async function F({
  control: s,
  i18n: u,
  name: o,
  value: i,
  rules: t
}) {
  const l = (s._validationCounters.get(o) || 0) + 1;
  s._validationCounters.set(o, l);
  try {
    const c = await q(i, t, u);
    s._validationCounters.get(o) === l && (c ? (s._errors.set(o, c), s._computedErrors[o] = c) : (s._errors.delete(o), delete s._computedErrors[o]), s.notify());
  } catch {
    if (s._validationCounters.get(o) === l) {
      const c = { type: "validation", message: "Validation error" };
      s._errors.set(o, c), s._computedErrors[o] = c, s.notify();
    }
  }
}
export {
  R as getNestedValue,
  M as setNestedValue,
  K as useForm,
  F as validateFieldWithRaceConditionHandling
};
