"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.FieldPreview = void 0;
const tslib_1 = require("tslib");
const jsx_runtime_1 = require("react/jsx-runtime");
const React = tslib_1.__importStar(require("react"));
const uikit_1 = require("@gravity-ui/uikit");
const lodash_1 = require("lodash");
const constants_1 = require("../../../../form-generator-v2/components/constants.js");
const CanvasContentContext_1 = require("../../../CanvasContentContext.js");
const cn_1 = require("../../../utils/cn.js");
const b = (0, cn_1.formBuilderV2Cn)('canvas-card');
const isTemplateField = (field) => 'name' in field && typeof field.name === 'string' && field.name.includes('{{index}}');
const makeOnUpdate = (setContent) => (key, value, options) => {
    setContent((prev) => {
        const next = (0, lodash_1.cloneDeep)(prev);
        if (options?.unset) {
            (0, lodash_1.unset)(next, key);
        }
        else {
            (0, lodash_1.set)(next, key, value);
        }
        return next;
    });
};
const FieldPreview = ({ field }) => {
    const { content, setContent, templateContent, setTemplateContent } = (0, CanvasContentContext_1.useCanvasContent)();
    const onUpdateForContent = React.useMemo(() => makeOnUpdate(setContent), [setContent]);
    const onUpdateForTemplate = React.useMemo(() => makeOnUpdate(setTemplateContent), [setTemplateContent]);
    if (field.type === 'section') {
        return ((0, jsx_runtime_1.jsxs)("div", { className: b('section-header'), children: [(0, jsx_runtime_1.jsx)(uikit_1.Text, { variant: "subheader-2", children: field.title || 'Section' }), field.index ? ((0, jsx_runtime_1.jsxs)(uikit_1.Label, { theme: "info", size: "s", children: ["Array \u00B7 ", field.itemTitle ?? 'Item {{index}}'] })) : ((0, jsx_runtime_1.jsx)(uikit_1.Label, { theme: "unknown", size: "s", children: "Group" }))] }));
    }
    const Component = constants_1.componentMap[field.type];
    if (!Component) {
        return null;
    }
    const { when: _when, id: _id, ...fieldProps } = field;
    const useTemplate = isTemplateField(field);
    const widgetContent = useTemplate ? templateContent : content;
    const onUpdate = useTemplate ? onUpdateForTemplate : onUpdateForContent;
    return ((0, jsx_runtime_1.jsx)(Component, { ...fieldProps, content: widgetContent, onUpdate: onUpdate }));
};
exports.FieldPreview = FieldPreview;
//# sourceMappingURL=FieldPreview.js.map
