import { addLastChild } from './addLastChild';
import { calculateParentSiblings } from './updateParentSibling';
export const addNewRow = (treeData, newNode, rootNode) => {
    const { sourceId, action, value = '', error = '', label, type, options, selectedOption, confirmIconTooltip, cancelIconTooltip, payloadSourceId, } = newNode;
    if (!sourceId || !action)
        return treeData;
    const convertedOptions = options?.map(option => ({
        label: option,
        value: option,
    }));
    const convertedSelectedOption = selectedOption
        ? { label: selectedOption, value: selectedOption }
        : undefined;
    const nodeMap = new Map(treeData.map(node => [node.key, node]));
    if (rootNode) {
        nodeMap.set(rootNode.key, rootNode);
    }
    const sourceNode = nodeMap.get(sourceId);
    if (!sourceNode)
        return treeData;
    let payloadSourceNode;
    if (payloadSourceId) {
        payloadSourceNode = nodeMap.get(payloadSourceId);
    }
    const updatedTreeData = [...treeData];
    const sourceIndex = treeData.findIndex(node => node.key === sourceId);
    // Create new node with proper parentId and hierarchy
    let newNodeParentId = null;
    let newNodeHierarchy = 0;
    switch (action) {
        case 'addAbove':
            newNodeParentId = sourceNode.parentId;
            newNodeHierarchy = sourceNode.hierarchy;
            break;
        case 'addBelow':
            newNodeParentId = payloadSourceNode?.parentId ?? sourceNode.parentId;
            newNodeHierarchy = payloadSourceNode?.hierarchy ?? sourceNode.hierarchy;
            break;
        case 'addInside':
            newNodeParentId = payloadSourceNode?.key ?? sourceNode.key;
            newNodeHierarchy =
                (payloadSourceNode?.hierarchy ?? sourceNode.hierarchy) + 1;
            break;
    }
    const newNodeBase = {
        hierarchy: newNodeHierarchy,
        parentId: newNodeParentId,
        sourceId: sourceNode.key,
        isNewNode: true,
        key: 'new-node',
        value,
        error,
        label,
        type,
        options: convertedOptions,
        selectedOption: convertedSelectedOption,
        confirmIconTooltip,
        cancelIconTooltip,
    };
    switch (action) {
        case 'addAbove':
            updatedTreeData.splice(sourceIndex, 0, newNodeBase);
            break;
        case 'addBelow':
            updatedTreeData.splice(sourceIndex + 1, 0, newNodeBase);
            break;
        case 'addInside':
            updatedTreeData.splice(sourceIndex + 1, 0, newNodeBase);
            break;
    }
    // Apply lastChild updates
    const treeWithLastChild = addLastChild(updatedTreeData);
    // Calculate parentSiblings for all nodes
    const treeWithParentSiblings = treeWithLastChild.map(node => ({
        ...node,
        parentSiblings: calculateParentSiblings(node, treeWithLastChild),
    }));
    return treeWithParentSiblings;
};
//# sourceMappingURL=addNewRow.js.map