"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const tslib_1 = require("tslib");
const jsx_runtime_1 = require("react/jsx-runtime");
const React = tslib_1.__importStar(require("react"));
const lodash_1 = require("lodash");
const Fields_1 = tslib_1.__importDefault(require("./components/Fields/Fields.js"));
const cn_1 = require("./utils/cn.js");
const fields_1 = require("./utils/fields.js");
const b = (0, cn_1.formGeneratorCn)('generator');
const FormGenerator = ({ blockConfig, contentConfig, onUpdate, onUpdateByKey, className, }) => {
    const contentRef = React.useRef(contentConfig);
    // Sync during render (not in useEffect) so that onDataUpdate calls within the same
    // effects batch all build on top of each other. If we synced in useEffect, it would
    // run *after* child effects, resetting any accumulated changes made by onDataUpdate.
    contentRef.current = contentConfig;
    const onDataUpdate = React.useCallback((key, value, options) => {
        if (!onUpdate && !onUpdateByKey) {
            return;
        }
        const newContentConfig = (0, lodash_1.cloneDeep)(contentRef.current ?? {});
        const removeAt = options?.removeArrayItemAt;
        if (typeof removeAt === 'number') {
            const arr = (0, fields_1.getValueByPath)(newContentConfig, key);
            if (Array.isArray(arr) && removeAt >= 0 && removeAt < arr.length) {
                arr.splice(removeAt, 1);
            }
        }
        else if (options?.unset) {
            (0, lodash_1.unset)(newContentConfig, key);
        }
        else {
            (0, lodash_1.set)(newContentConfig, key, value);
        }
        contentRef.current = newContentConfig;
        if (onUpdateByKey) {
            onUpdateByKey(key, value);
        }
        if (onUpdate) {
            onUpdate(newContentConfig);
        }
    }, [onUpdate, onUpdateByKey]);
    return ((0, jsx_runtime_1.jsx)("div", { className: b(null, className), children: (0, jsx_runtime_1.jsx)(Fields_1.default, { fields: blockConfig, content: contentConfig, onUpdate: onDataUpdate }) }));
};
exports.default = FormGenerator;
//# sourceMappingURL=FormGenerator.js.map
