import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import * as React from 'react';
import { useSortable } from '@dnd-kit/react/sortable';
import { Copy, TrashBin } from '@gravity-ui/icons';
import { Button, Card, Icon } from '@gravity-ui/uikit';
import { HTML } from "../../../components/index.js";
import { editorCn } from "../../utils/cn.js";
import './TreeItem.css';
const b = editorCn('tree-item');
const sortableConfig = {
    alignment: {
        x: 'start',
        y: 'center',
    },
    transition: null,
};
export function TreeItem({ item, sortableIndex, indentLeft, selected, type, treeTitle, path, onCopy, onDelete, onSelect, }) {
    const { depth, parentId, id } = item;
    const { ref, isDragSource, isDropTarget } = useSortable({
        ...sortableConfig,
        id,
        index: sortableIndex,
        data: {
            depth,
            parentId,
        },
    });
    const [mouseDownPos, setMouseDownPos] = React.useState(null);
    const itemRef = React.useRef(null);
    React.useLayoutEffect(() => {
        if (selected && itemRef.current) {
            itemRef.current.scrollIntoView({
                behavior: 'smooth',
                block: 'nearest',
            });
        }
    }, [selected]);
    const setNodeRef = React.useCallback((node) => {
        ref(node);
        itemRef.current =
            node;
    }, [ref]);
    const handleMouseDown = React.useCallback((e) => {
        setMouseDownPos({ x: e.clientX, y: e.clientY });
    }, []);
    const handleMouseUp = React.useCallback((e) => {
        if (mouseDownPos) {
            const dx = Math.abs(e.clientX - mouseDownPos.x);
            const dy = Math.abs(e.clientY - mouseDownPos.y);
            if (dx < 5 && dy < 5) {
                e.stopPropagation();
                onSelect(path);
            }
        }
        setMouseDownPos(null);
    }, [mouseDownPos, onSelect, path]);
    return (_jsx(Card, { ref: setNodeRef, className: b({
            selected,
            dragging: isDragSource,
            'drag-over': isDropTarget,
        }), style: { marginLeft: indentLeft }, onMouseDown: handleMouseDown, onMouseUp: handleMouseUp, children: _jsxs("div", { className: b('main'), children: [_jsxs("div", { className: b('text'), children: [_jsx("div", { className: b('type'), children: type }), _jsx(HTML, { className: b('title'), children: treeTitle })] }), _jsxs("div", { className: b('buttons'), children: [_jsx(Button, { view: "flat", size: "xs", onClick: () => onCopy(path), children: _jsx(Icon, { size: 12, data: Copy }) }), _jsx(Button, { view: "flat", size: "xs", onClick: () => onDelete(path), children: _jsx(Icon, { size: 12, data: TrashBin }) })] })] }) }));
}
//# sourceMappingURL=TreeItem.js.map
