import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import * as React from 'react';
import { generateChildrenPathFromArray } from "../../utils/index.js";
import { DragContext } from "./DragContext.js";
import { Item } from "./TreeItem.js";
import { editorCn } from "../../utils/cn.js";
import './TreeContent.css';
const b = editorCn('tree-content');
export const TreeContent = ({ blockTree, selectedBlockPath, reorderBlock, onCopy, onDelete, onSelect, }) => {
    const { draggedItem, setDraggedItem, hidePreview, showPreview } = React.useContext(DragContext);
    const handleFirstPositionDrop = React.useCallback((e) => {
        e.preventDefault();
        e.stopPropagation();
        try {
            const data = e.dataTransfer.getData('application/json');
            if (data) {
                const dragItem = JSON.parse(data);
                // Reorder to the first position by using [0] as destination
                // and 'prepend' as position
                reorderBlock(dragItem.path, [0], 'prepend');
                // Reset drag context
                setDraggedItem(null);
                hidePreview();
            }
        }
        catch (error) {
            // eslint-disable-next-line no-console
            console.error('Error parsing drag data:', error);
        }
    }, [reorderBlock, hidePreview, setDraggedItem]);
    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';
        // Show preview element at this position
        const rect = e.currentTarget.getBoundingClientRect();
        if (draggedItem) {
            showPreview(rect, draggedItem);
        }
    }, [draggedItem, showPreview]);
    const renderTree = (items, parentPathArray) => {
        return items.map(({ type, treeTitle, children }, index) => {
            let blockPathArray;
            if (parentPathArray) {
                blockPathArray = [...parentPathArray, index];
            }
            else {
                blockPathArray = [index];
            }
            const blockPath = generateChildrenPathFromArray(blockPathArray);
            return (_jsx(Item, { type: type, treeTitle: treeTitle, onCopy: onCopy, onDelete: onDelete, onSelect: onSelect, onReorder: reorderBlock, path: blockPathArray, selected: selectedBlockPath === blockPath, children: children && (_jsx("div", { className: b('children'), children: renderTree(children, blockPathArray) })) }, index));
        });
    };
    return (_jsxs("div", { className: b(), children: [_jsx("div", { className: b('drop-zone'), onDragOver: handleDragOver, onDragLeave: hidePreview, onDrop: handleFirstPositionDrop }), _jsx("div", { children: renderTree(blockTree) })] }));
};
//# sourceMappingURL=TreeContent.js.map
