'use client';
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import * as React from 'react';
import { move } from '@dnd-kit/helpers';
import { DragDropProvider, DragOverlay } from '@dnd-kit/react';
import { Code, Eye, Pencil } from '@gravity-ui/icons';
import { Button, Icon, SegmentedRadioGroup } from '@gravity-ui/uikit';
import { CanvasContentProvider } from "./CanvasContentContext.js";
import { Canvas } from "./components/Canvas/Canvas.js";
import { ContentTab } from "./components/ContentTab/ContentTab.js";
import { DragOverlayPreview } from "./components/DragOverlayPreview/DragOverlayPreview.js";
import { Inspector } from "./components/Inspector/Inspector.js";
import { PALETTE_DRAGGABLE_PREFIX, Palette } from "./components/Palette/Palette.js";
import { ResizeHandle } from "./components/ResizeHandle/ResizeHandle.js";
import { SchemaPopup } from "./components/SchemaPopup/SchemaPopup.js";
import { FormProvider, useFormContext } from "./hooks/FormContext.js";
import { formBuilderV2Cn } from "./utils/cn.js";
import { isDropAfter, isPaletteData, isSectionDropData } from "./utils/dragData.js";
import { applyGroupsMap, buildGroupsMap } from "./utils/fieldGroups.js";
import { findFieldById } from "./utils/fieldTree.js";
import { stripIds } from "./utils/stripIds.js";
import './FormBuilderV2.css';
const b = 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, } = useFormContext();
    const schema = React.useMemo(() => stripIds(formFields), [formFields]);
    const handleDragEnd = React.useCallback((event) => {
        if (event.canceled)
            return;
        const { source, target } = event.operation;
        if (!source)
            return;
        const paletteData = isPaletteData(source.data) ? source.data : null;
        const isPaletteDrag = paletteData !== null || String(source.id).startsWith(PALETTE_DRAGGABLE_PREFIX);
        if (isPaletteDrag) {
            const type = paletteData?.type;
            if (!type)
                return;
            if (!target) {
                addField(type);
                return;
            }
            if (isSectionDropData(target.data)) {
                addFieldToSection(target.data.sectionId, type);
                return;
            }
            if (String(target.id) === String(source.id)) {
                addField(type);
                return;
            }
            const dropAfter = 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 && isSectionDropData(target.data)) {
            moveFieldToSection(String(source.id), target.data.sectionId);
            return;
        }
        const groups = buildGroupsMap(formFields);
        const nextGroups = move(groups, event);
        const nextFields = applyGroupsMap(nextGroups);
        setAllFields(nextFields);
    }, [
        addField,
        addFieldToSection,
        formFields,
        insertFieldBefore,
        insertFieldAfter,
        moveFieldToSection,
        setAllFields,
    ]);
    const gridStyle = {
        '--fb2-palette-w': `${paletteWidth}px`,
        '--fb2-inspector-w': `${inspectorWidth}px`,
    };
    return (_jsx("div", { className: b({ compact: density === 'compact' }, className), children: _jsxs(CanvasContentProvider, { content: canvasContent, setContent: setCanvasContent, templateContent: templateContent, setTemplateContent: setTemplateContent, children: [_jsxs("div", { className: b('toolbar'), children: [_jsx(SegmentedRadioGroup, { size: "m", value: mode, onUpdate: setMode, options: [
                                {
                                    value: 'edit',
                                    content: (_jsxs("span", { className: b('toolbar-option'), children: [_jsx(Icon, { data: Pencil, size: 14 }), "Edit"] })),
                                },
                                {
                                    value: 'preview',
                                    content: (_jsxs("span", { className: b('toolbar-option'), children: [_jsx(Icon, { data: Eye, size: 14 }), "Preview"] })),
                                },
                            ] }), _jsxs(Button, { ref: schemaButtonRef, view: "outlined", size: "m", onClick: () => setSchemaPopupOpen((prev) => !prev), children: [_jsx(Icon, { data: Code, size: 14 }), "Schema"] }), _jsx(SchemaPopup, { schema: schema, onApply: setAllFields, open: schemaPopupOpen, onOpenChange: setSchemaPopupOpen, anchorElement: schemaButtonRef.current })] }), mode === 'edit' ? (_jsxs(DragDropProvider, { onDragEnd: handleDragEnd, children: [_jsxs("div", { className: b('visual'), style: gridStyle, children: [_jsx("aside", { className: b('palette'), children: _jsx(Palette, {}) }), !isCompact && (_jsx(ResizeHandle, { value: paletteWidth, min: PALETTE_MIN, max: PALETTE_MAX, direction: "left", onChange: setPaletteWidth })), _jsx("main", { className: b('canvas'), children: _jsx(Canvas, {}) }), _jsx(ResizeHandle, { value: inspectorWidth, min: INSPECTOR_MIN, max: INSPECTOR_MAX, direction: "right", onChange: setInspectorWidth }), _jsx("aside", { className: b('inspector'), children: _jsx(Inspector, {}) })] }), _jsx(DragOverlay, { dropAnimation: null, children: (source) => {
                                if (!source)
                                    return null;
                                if (isPaletteData(source.data)) {
                                    return _jsx(DragOverlayPreview, { type: source.data.type });
                                }
                                const field = findFieldById(formFields, String(source.id));
                                if (!field)
                                    return null;
                                return _jsx(DragOverlayPreview, { type: field.type, field: field });
                            } })] })) : (_jsx(ContentTab, {}))] }) }));
};
export const FormBuilderV2 = ({ className, formFields, onChange, density = 'full', }) => {
    return (_jsx(FormProvider, { formFields: formFields, onChange: onChange, children: _jsx(FormBuilderShell, { className: className, density: density }) }));
};
//# sourceMappingURL=FormBuilderV2.js.map
