'use client';
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.FormBuilderV2 = void 0;
const tslib_1 = require("tslib");
const jsx_runtime_1 = require("react/jsx-runtime");
const React = tslib_1.__importStar(require("react"));
const helpers_1 = require("@dnd-kit/helpers");
const react_1 = require("@dnd-kit/react");
const icons_1 = require("@gravity-ui/icons");
const uikit_1 = require("@gravity-ui/uikit");
const CanvasContentContext_1 = require("./CanvasContentContext.js");
const Canvas_1 = require("./components/Canvas/Canvas.js");
const ContentTab_1 = require("./components/ContentTab/ContentTab.js");
const DragOverlayPreview_1 = require("./components/DragOverlayPreview/DragOverlayPreview.js");
const Inspector_1 = require("./components/Inspector/Inspector.js");
const Palette_1 = require("./components/Palette/Palette.js");
const ResizeHandle_1 = require("./components/ResizeHandle/ResizeHandle.js");
const SchemaPopup_1 = require("./components/SchemaPopup/SchemaPopup.js");
const FormContext_1 = require("./hooks/FormContext.js");
const cn_1 = require("./utils/cn.js");
const dragData_1 = require("./utils/dragData.js");
const fieldGroups_1 = require("./utils/fieldGroups.js");
const fieldTree_1 = require("./utils/fieldTree.js");
const stripIds_1 = require("./utils/stripIds.js");
const b = (0, cn_1.formBuilderV2Cn)('main');
const PALETTE_MIN = 160;
const PALETTE_MAX = 400;
const PALETTE_DEFAULT = 220;
const INSPECTOR_MIN = 270;
const INSPECTOR_MAX = 560;
const INSPECTOR_DEFAULT = 320;
const FormBuilderShell = ({ className, density }) => {
    const [mode, setMode] = React.useState('edit');
    const [canvasContent, setCanvasContent] = React.useState({});
    const [templateContent, setTemplateContent] = React.useState({});
    const [paletteWidth, setPaletteWidth] = React.useState(PALETTE_DEFAULT);
    const [inspectorWidth, setInspectorWidth] = React.useState(INSPECTOR_DEFAULT);
    const [schemaPopupOpen, setSchemaPopupOpen] = React.useState(false);
    const schemaButtonRef = React.useRef(null);
    const isCompact = density === 'compact';
    const { formFields, setAllFields, addField, addFieldToSection, insertFieldBefore, insertFieldAfter, moveFieldToSection, } = (0, FormContext_1.useFormContext)();
    const schema = React.useMemo(() => (0, stripIds_1.stripIds)(formFields), [formFields]);
    const handleDragEnd = React.useCallback((event) => {
        if (event.canceled)
            return;
        const { source, target } = event.operation;
        if (!source)
            return;
        const paletteData = (0, dragData_1.isPaletteData)(source.data) ? source.data : null;
        const isPaletteDrag = paletteData !== null || String(source.id).startsWith(Palette_1.PALETTE_DRAGGABLE_PREFIX);
        if (isPaletteDrag) {
            const type = paletteData?.type;
            if (!type)
                return;
            if (!target) {
                addField(type);
                return;
            }
            if ((0, dragData_1.isSectionDropData)(target.data)) {
                addFieldToSection(target.data.sectionId, type);
                return;
            }
            if (String(target.id) === String(source.id)) {
                addField(type);
                return;
            }
            const dropAfter = (0, dragData_1.isDropAfter)(event.operation.position?.current?.y, target.shape?.center?.y);
            if (dropAfter) {
                insertFieldAfter(String(target.id), type);
            }
            else {
                insertFieldBefore(String(target.id), type);
            }
            return;
        }
        if (target && (0, dragData_1.isSectionDropData)(target.data)) {
            moveFieldToSection(String(source.id), target.data.sectionId);
            return;
        }
        const groups = (0, fieldGroups_1.buildGroupsMap)(formFields);
        const nextGroups = (0, helpers_1.move)(groups, event);
        const nextFields = (0, fieldGroups_1.applyGroupsMap)(nextGroups);
        setAllFields(nextFields);
    }, [
        addField,
        addFieldToSection,
        formFields,
        insertFieldBefore,
        insertFieldAfter,
        moveFieldToSection,
        setAllFields,
    ]);
    const gridStyle = {
        '--fb2-palette-w': `${paletteWidth}px`,
        '--fb2-inspector-w': `${inspectorWidth}px`,
    };
    return ((0, jsx_runtime_1.jsx)("div", { className: b({ compact: density === 'compact' }, className), children: (0, jsx_runtime_1.jsxs)(CanvasContentContext_1.CanvasContentProvider, { content: canvasContent, setContent: setCanvasContent, templateContent: templateContent, setTemplateContent: setTemplateContent, children: [(0, jsx_runtime_1.jsxs)("div", { className: b('toolbar'), children: [(0, jsx_runtime_1.jsx)(uikit_1.SegmentedRadioGroup, { size: "m", value: mode, onUpdate: setMode, options: [
                                {
                                    value: 'edit',
                                    content: ((0, jsx_runtime_1.jsxs)("span", { className: b('toolbar-option'), children: [(0, jsx_runtime_1.jsx)(uikit_1.Icon, { data: icons_1.Pencil, size: 14 }), "Edit"] })),
                                },
                                {
                                    value: 'preview',
                                    content: ((0, jsx_runtime_1.jsxs)("span", { className: b('toolbar-option'), children: [(0, jsx_runtime_1.jsx)(uikit_1.Icon, { data: icons_1.Eye, size: 14 }), "Preview"] })),
                                },
                            ] }), (0, jsx_runtime_1.jsxs)(uikit_1.Button, { ref: schemaButtonRef, view: "outlined", size: "m", onClick: () => setSchemaPopupOpen((prev) => !prev), children: [(0, jsx_runtime_1.jsx)(uikit_1.Icon, { data: icons_1.Code, size: 14 }), "Schema"] }), (0, jsx_runtime_1.jsx)(SchemaPopup_1.SchemaPopup, { schema: schema, onApply: setAllFields, open: schemaPopupOpen, onOpenChange: setSchemaPopupOpen, anchorElement: schemaButtonRef.current })] }), mode === 'edit' ? ((0, jsx_runtime_1.jsxs)(react_1.DragDropProvider, { onDragEnd: handleDragEnd, children: [(0, jsx_runtime_1.jsxs)("div", { className: b('visual'), style: gridStyle, children: [(0, jsx_runtime_1.jsx)("aside", { className: b('palette'), children: (0, jsx_runtime_1.jsx)(Palette_1.Palette, {}) }), !isCompact && ((0, jsx_runtime_1.jsx)(ResizeHandle_1.ResizeHandle, { value: paletteWidth, min: PALETTE_MIN, max: PALETTE_MAX, direction: "left", onChange: setPaletteWidth })), (0, jsx_runtime_1.jsx)("main", { className: b('canvas'), children: (0, jsx_runtime_1.jsx)(Canvas_1.Canvas, {}) }), (0, jsx_runtime_1.jsx)(ResizeHandle_1.ResizeHandle, { value: inspectorWidth, min: INSPECTOR_MIN, max: INSPECTOR_MAX, direction: "right", onChange: setInspectorWidth }), (0, jsx_runtime_1.jsx)("aside", { className: b('inspector'), children: (0, jsx_runtime_1.jsx)(Inspector_1.Inspector, {}) })] }), (0, jsx_runtime_1.jsx)(react_1.DragOverlay, { dropAnimation: null, children: (source) => {
                                if (!source)
                                    return null;
                                if ((0, dragData_1.isPaletteData)(source.data)) {
                                    return (0, jsx_runtime_1.jsx)(DragOverlayPreview_1.DragOverlayPreview, { type: source.data.type });
                                }
                                const field = (0, fieldTree_1.findFieldById)(formFields, String(source.id));
                                if (!field)
                                    return null;
                                return (0, jsx_runtime_1.jsx)(DragOverlayPreview_1.DragOverlayPreview, { type: field.type, field: field });
                            } })] })) : ((0, jsx_runtime_1.jsx)(ContentTab_1.ContentTab, {}))] }) }));
};
const FormBuilderV2 = ({ className, formFields, onChange, density = 'full', }) => {
    return ((0, jsx_runtime_1.jsx)(FormContext_1.FormProvider, { formFields: formFields, onChange: onChange, children: (0, jsx_runtime_1.jsx)(FormBuilderShell, { className: className, density: density }) }));
};
exports.FormBuilderV2 = FormBuilderV2;
//# sourceMappingURL=FormBuilderV2.js.map
