"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Item = void 0;
const tslib_1 = require("tslib");
const jsx_runtime_1 = require("react/jsx-runtime");
const icons_1 = require("@gravity-ui/icons");
const uikit_1 = require("@gravity-ui/uikit");
const React = tslib_1.__importStar(require("react"));
const cn_1 = require("../../utils/cn.js");
const DragContext_1 = require("./DragContext.js");
const b = (0, cn_1.editorCn)('tree-item');
const Item = ({ type, children, treeTitle, path, selected, onCopy, onDelete, onSelect, onReorder, }) => {
    const { draggedItem, setDraggedItem, showPreview, hidePreview } = React.useContext(DragContext_1.DragContext);
    const [isDragging, setIsDragging] = React.useState(false);
    const [isDragOver, setIsDragOver] = React.useState(false);
    const [mouseDownPos, setMouseDownPos] = React.useState(null);
    const itemRef = React.useRef(null);
    // Scroll into view when selected
    React.useEffect(() => {
        if (selected && itemRef.current) {
            itemRef.current.scrollIntoView({
                behavior: 'smooth',
                block: 'nearest',
            });
        }
    }, [selected]);
    const handleCopy = React.useCallback(() => {
        onCopy(path);
    }, [onCopy, path]);
    const handleDelete = React.useCallback(() => {
        onDelete(path);
    }, [onDelete, path]);
    const handleMouseDown = React.useCallback((e) => {
        setMouseDownPos({ x: e.clientX, y: e.clientY });
    }, []);
    const handleMouseUp = React.useCallback((e) => {
        if (mouseDownPos) {
            // Check if the mouse has moved significantly (dragging) or just a click
            const dx = Math.abs(e.clientX - mouseDownPos.x);
            const dy = Math.abs(e.clientY - mouseDownPos.y);
            // If the mouse hasn't moved much, consider it a click for selection
            if (dx < 5 && dy < 5) {
                e.stopPropagation();
                onSelect(path);
            }
        }
        setMouseDownPos(null);
    }, [mouseDownPos, onSelect, path]);
    const handleDragStart = React.useCallback((e) => {
        e.stopPropagation();
        const dragData = {
            path,
            type,
            treeTitle,
        };
        e.dataTransfer.setData('application/json', JSON.stringify(dragData));
        // eslint-disable-next-line no-not-accumulator-reassign/no-not-accumulator-reassign, no-param-reassign
        e.dataTransfer.effectAllowed = 'move';
        setIsDragging(true);
        // Update drag context
        setDraggedItem(dragData);
    }, [path, type, treeTitle, setDraggedItem]);
    const handleDragEnd = React.useCallback(() => {
        setIsDragging(false);
        // Reset drag context
        setDraggedItem(null);
        hidePreview();
    }, [setDraggedItem, hidePreview]);
    const handleDragOver = React.useCallback((e) => {
        e.preventDefault();
        e.stopPropagation();
        // eslint-disable-next-line no-not-accumulator-reassign/no-not-accumulator-reassign, no-param-reassign
        e.dataTransfer.dropEffect = 'move';
        setIsDragOver(true);
        const rect = e.currentTarget.getBoundingClientRect();
        if (draggedItem) {
            showPreview(rect, draggedItem);
        }
    }, [showPreview, draggedItem]);
    const handleDragLeave = React.useCallback(() => {
        setIsDragOver(false);
        hidePreview();
    }, [hidePreview]);
    const handleDrop = React.useCallback((e) => {
        e.preventDefault();
        e.stopPropagation();
        setIsDragOver(false);
        try {
            const data = e.dataTransfer.getData('application/json');
            if (data) {
                const dragItem = JSON.parse(data);
                if (dragItem.path.join(',') !== path.join(',')) {
                    onReorder(dragItem.path, path);
                    // Reset drag context
                    setDraggedItem(null);
                    hidePreview();
                }
            }
        }
        catch (error) {
            // eslint-disable-next-line no-console
            console.error('Error parsing drag data:', error);
        }
    }, [onReorder, path, setDraggedItem, hidePreview]);
    const handleChildrenFirstPositionDrop = React.useCallback((e) => {
        e.preventDefault();
        e.stopPropagation();
        try {
            const data = e.dataTransfer.getData('application/json');
            if (data) {
                const dragItem = JSON.parse(data);
                // Create a path for the first child position
                const firstChildPath = [...path, 0];
                // Reorder to the first position within children
                onReorder(dragItem.path, firstChildPath, 'prepend');
                // Reset drag context
                setDraggedItem(null);
                hidePreview();
            }
        }
        catch (error) {
            // eslint-disable-next-line no-console
            console.error('Error parsing drag data:', error);
        }
    }, [onReorder, path, setDraggedItem, hidePreview]);
    const handleDropZoneDragOver = (e) => {
        e.preventDefault();
        e.stopPropagation();
        // eslint-disable-next-line no-not-accumulator-reassign/no-not-accumulator-reassign, no-param-reassign
        e.dataTransfer.dropEffect = 'move';
        // Show preview element at this position
        const rect = e.currentTarget.getBoundingClientRect();
        if (draggedItem) {
            showPreview(rect, draggedItem);
        }
    };
    return ((0, jsx_runtime_1.jsxs)(uikit_1.Card, { ref: itemRef, className: b({
            selected,
            dragging: isDragging,
            'drag-over': isDragOver,
        }), onMouseDown: handleMouseDown, onMouseUp: handleMouseUp, draggable: true, onDragStart: handleDragStart, onDragEnd: handleDragEnd, onDragOver: handleDragOver, onDragLeave: handleDragLeave, onDrop: handleDrop, children: [(0, jsx_runtime_1.jsxs)("div", { className: b('main'), children: [(0, jsx_runtime_1.jsxs)("div", { className: b('text'), children: [(0, jsx_runtime_1.jsx)("div", { className: b('type'), children: type }), (0, jsx_runtime_1.jsx)("div", { className: b('title'), children: treeTitle })] }), (0, jsx_runtime_1.jsxs)("div", { className: b('buttons'), children: [(0, jsx_runtime_1.jsx)(uikit_1.Button, { view: "flat", size: "xs", onClick: handleCopy, children: (0, jsx_runtime_1.jsx)(uikit_1.Icon, { size: 12, data: icons_1.Copy }) }), (0, jsx_runtime_1.jsx)(uikit_1.Button, { view: "flat", size: "xs", onClick: handleDelete, children: (0, jsx_runtime_1.jsx)(uikit_1.Icon, { size: 12, data: icons_1.TrashBin }) })] })] }), children && ((0, jsx_runtime_1.jsxs)(React.Fragment, { children: [(0, jsx_runtime_1.jsx)("div", { className: b('children-drop-zone'), onDragOver: handleDropZoneDragOver, onDragLeave: hidePreview, onDrop: handleChildrenFirstPositionDrop }), children] }))] }));
};
exports.Item = Item;
//# sourceMappingURL=TreeItem.js.map
