import { jsx as q, Fragment as G } from "react/jsx-runtime";
import { capitalizeFirstLetter as x } from "./index-string-helpers.js";
import { validInput as v } from "./index-valid-input.js";
import { extractSetErrorsFromConfig as J } from "./index-extract-set-errors-from-config.js";
import K, { useRef as Q, useState as i, useEffect as p } from "react";
const Z = (b) => {
  const {
    children: S,
    childConfig: s,
    formConfig: l,
    idx: E,
    onChange: V,
    onBlur: D,
    childAdded: o,
    childRemoved: I,
    formConfigKey: A = "formconfig"
  } = b, P = Q(null), [R, H] = i([]), [N, L] = i(!1), [M, O] = i(!1), [f, B] = i("");
  p(() => {
    w(s);
  }, [s]), p(() => {
    const e = s.stateFieldName;
    if (e && f) {
      const t = {
        name: e,
        isValid: v(s),
        hasChanges: c(s),
        childFormConfig: s
      };
      V && V(t);
    }
  }, [f]), p(() => () => {
    I && I(s);
  }, []), p(() => {
    o && o(s);
  }, [s]);
  const $ = (e) => {
    var r;
    const t = e.stateFieldName;
    if (e && t) {
      e._inputRef = P, e.errors = R, e.setErrors = H, e.hasError = N, e.setHasError = L, e.isDirty = M, e.setIsDirty = O;
      const y = `set${x(t)}`, a = `set${x(t)}inArray`, n = l && l[t], z = n && l[t].reducer ? l[t].reducer : {}, _ = (n && l[t].slice) ?? {}, d = _[y], k = _[a];
      let u = z[t];
      E !== void 0 && (u = u[E], e.arrayPosition = E), e && (r = e.valueMappers) != null && r.toPrimitive && (u = e.valueMappers.toPrimitive(u)), e.stateValue = u, e.setStateValue = d, e.setStateValueArray = k, e.setStateValue && e.setStateValue(u);
    }
  }, c = (e) => {
    let t = !1;
    return e && e.getValue && e.getInitialValue && e.setIsDirty && (e.getValue() != e.getInitialValue() ? (t = !0, e.setIsDirty(!0)) : (t = !1, e.setIsDirty(!1))), t;
  }, j = (e) => {
    const t = e._onChange, r = e._onBlur, y = e.stateFieldName;
    e && y && (e._onChange = (a) => {
      a && t && t(a);
      const n = {
        name: y,
        isValid: v(e, e.validateOn === "blur"),
        hasChanges: c(e),
        childFormConfig: e
      };
      V && V(n);
    }, e._onBlur = (a) => {
      if (e.validateOn !== "blur")
        return;
      a && r && r(a);
      const n = {
        name: y,
        isValid: v(e),
        hasChanges: c(e),
        childFormConfig: e
      };
      D && D(n);
    });
  }, w = (e) => {
    const t = J(e);
    B(t || "");
  };
  if ($(s), j(s), K.isValidElement(S)) {
    const e = {};
    return e[A] = s, K.cloneElement(S, e);
  }
  return q(G, {
    children: S
  });
};
export {
  Z as FormElement
};
