"use client";
'use strict';

Object.defineProperty(exports, '__esModule', { value: true });

const jsxRuntime = require('react/jsx-runtime');
const form = require('../form.cjs');
const React = require('react');
const reactHookForm = require('react-hook-form');
const button = require('../button.cjs');
const utils = require('../../lib/utils.cjs');
const zod = require('@hookform/resolvers/zod');
const object = require('./fields/object.cjs');
const helpers = require('./helpers.cjs');

function _interopDefaultCompat (e) { return e && typeof e === 'object' && 'default' in e ? e.default : e; }

const React__default = /*#__PURE__*/_interopDefaultCompat(React);

function AutoFormSubmit({
  children,
  className,
  disabled
}) {
  return /* @__PURE__ */ jsxRuntime.jsx(button.Button, { type: "submit", disabled, className, children: children ?? "Submit" });
}
function AutoForm({
  formSchema,
  values: valuesProp,
  onValuesChange: onValuesChangeProp,
  onParsedValuesChange,
  onSubmit: onSubmitProp,
  fieldConfig,
  children,
  className,
  dependencies
}) {
  const objectFormSchema = helpers.getObjectFormSchema(formSchema);
  const defaultValues = helpers.getDefaultValues(objectFormSchema, fieldConfig);
  const form$1 = reactHookForm.useForm({
    // Cast to any to handle Zod v4 type compatibility with @hookform/resolvers
    resolver: zod.zodResolver(formSchema),
    defaultValues: defaultValues ?? void 0,
    values: valuesProp
  });
  function onSubmit(values) {
    const parsedValues = formSchema.safeParse(values);
    if (parsedValues.success) {
      onSubmitProp?.(parsedValues.data, form$1);
    }
  }
  React__default.useEffect(() => {
    const subscription = form$1.watch((values) => {
      onValuesChangeProp?.(values, form$1);
      const parsedValues = formSchema.safeParse(values);
      if (parsedValues.success) {
        onParsedValuesChange?.(parsedValues.data, form$1);
      }
    });
    return () => subscription.unsubscribe();
  }, [form$1, formSchema, onValuesChangeProp, onParsedValuesChange]);
  const renderChildren = typeof children === "function" ? children(form$1.formState) : children;
  return /* @__PURE__ */ jsxRuntime.jsx("div", { className: "w-full", children: /* @__PURE__ */ jsxRuntime.jsx(form.Form, { ...form$1, children: /* @__PURE__ */ jsxRuntime.jsxs(
    "form",
    {
      onSubmit: (e) => {
        form$1.handleSubmit(onSubmit)(e);
      },
      className: utils.cn("space-y-5", className),
      children: [
        /* @__PURE__ */ jsxRuntime.jsx(
          object,
          {
            schema: objectFormSchema,
            form: form$1,
            dependencies,
            fieldConfig
          }
        ),
        renderChildren
      ]
    }
  ) }) });
}

exports.AutoFormSubmit = AutoFormSubmit;
exports.default = AutoForm;
