import { Form } from "../utilities/form/Form.mjs";
import { ConfigService } from "../configService/index.mjs";
import { NodeActionEnums, NodeActionTriggerEnums, TreeViewModeEnums } from "../enums/unitySystemEnums.mjs";
import { apiMutate } from "../utilities/useAxiosMutate.mjs";
import { pluralize } from "../utilities/input/StringUtilities.mjs";
import { FluentIconButton } from "../UI/inputs/buttons/FluentIconButton.mjs";
import { getSanitizedName } from "../utilities/entities/entityUtilities.mjs";
import { useActionStore } from "../stores/actionStore.mjs";
import { useInquiryStore, useSetInitialInquiryMenuVisibility } from "../stores/inquiryStore.mjs";
import { useShellStore } from "../stores/shellStore.mjs";
import { useActions } from "../hooks/useActions.mjs";
import { evaluateRule, mapRule } from "../utilities/rules/RuleUtilities.mjs";
import { getSearchIdentifiers, getSearchObject } from "../utilities/search/SearchUtilities.mjs";
import GroupNode from "../models/GroupNode.mjs";
import { collapseAllNodes, collectChildVaryingKeysByType, constructPreloadedTree, expandAllNodes, fetchCountsByType, fetchLazyChildren, findNodeByBusinessObjectKey, formatTreeMenuItem, getSearchValueString, keysByTypeToFilterArray, makeTreeStructure } from "../utilities/tree/TreeUtilities.mjs";
import { LayoutUnit } from "../layout/LayoutUnit.mjs";
import { useAxiosGet } from "../utilities/useAxiosGet.mjs";
import { PrimaryActionHeader } from "../UI/utilityDisplay/utilityHeader/PrimaryActionHeader.mjs";
import { useSetLocationState } from "../hooks/useSetLocationState.mjs";
import { PageContainer } from "../page/PageContainer/PageContainer.mjs";
import { OpenPage } from "../UI/templates/OpenPage.mjs";
import { useBuildEnvironment } from "../shell/ui/useBuildEnvironment.mjs";
import { executeQueryInstance } from "../udp/utilities/methodUtils.mjs";
import { ExecuteApiDialog } from "./ExecuteApiDialog.mjs";
import { InquiryAdvancedSearch } from "./search/InquiryAdvancedSearch.mjs";
import { InquiryDashboard } from "./dashboard/InquiryDashboard.mjs";
import { InquiryHeaderSecondary, InquiryHeaderSecondaryTarget } from "../utilities/utilityBar/InquiryHeaderSecondary.mjs";
import { InquiryNodeControls } from "./inquiryBar/InquiryNodeControls.mjs";
import { InquirySearchContainer } from "./search/InquirySearchContainer.mjs";
import { InquiryWrapper } from "./InquiryWrapper.mjs";
import { NodeDetails } from "./NodeDetails.mjs";
import { NodeLoader } from "../UI/feedback/NodeLoader.mjs";
import { NodeList } from "./NodeList.mjs";
import { RecentlyLoadedNodesTable } from "./dashboard/RecentlyLoadedNodesTable.mjs";
import { UdpTablist } from "../UI/fluent-web-components/UdpTablist.mjs";
import { UtilitySideBar } from "../UI/utilityDisplay/UtilitySideBar.mjs";
import { InquiryHeaderSecondaryAlertTarget } from "../utilities/utilityBar/InquiryHeaderSecondaryAlert.mjs";
import { PageActionWrapper } from "../actions/PageActionWrapper.mjs";
import { WorkflowTreeMenu } from "../workflow/menus/WorkflowTreeMenu.mjs";
import { UnitStateType } from "../enums/workflowEnums.mjs";
import { transformWorkflowPlayTree } from "../utilities/workflow/workflowUtilities.mjs";
import { WorkflowContent } from "../workflow/WorkflowContent.mjs";
import LoadingOverlay from "../UI/loading/LoadingOverlay.mjs";
import React, { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { Card, Collapse, Divider, LinearProgress, Typography, makeStyles } from "@material-ui/core";
import { useSnackbar } from "notistack";
import clsx from "clsx";
import { ChevronDownIcon, ChevronUpIcon, ClearIcon } from "@fluentui/react-icons";
import PropTypes from "prop-types";
import { useTranslation } from "react-i18next";
import { cloneDeep, orderBy } from "lodash-es";
import { v4 } from "uuid";
import { DndProvider } from "react-dnd";
import { HTML5Backend } from "react-dnd-html5-backend";
//#region src/inquiry/InquiryContainer.jsx
const useStyles = makeStyles((theme) => ({
	root: {
		display: "flex",
		height: ({ appRibbonSpace }) => `calc(100vh - ${appRibbonSpace + 56}px)`
	},
	mainWrapper: { padding: theme.spacing(2) },
	children: { height: "calc(100vh - 150px)" },
	searchContainerRoot: { height: "calc(100vh - 140px)" },
	nodeListRoot: {
		height: (props) => `calc(100vh - ${props.shellHidden ? "120px" : "176px"})`,
		overflowX: "hidden"
	},
	nodeListRootLoaded: {
		height: (props) => props.tree?.isPreloaded ? "calc(100vh - 140px)" : `calc(100vh - ${props.shellHidden ? "130px" : "184px"})`,
		overflowX: "hidden"
	},
	tabRoot: {
		width: "100%",
		minWidth: 0
	},
	workflowTablist: {
		width: "100%",
		display: "block",
		"& udp-fluent-tablist": { width: "100%" }
	},
	nodeListRootLoading: { height: "calc(100vh - 108px)" },
	chevronButtons: {
		display: "flex",
		justifyContent: "center",
		zIndex: theme.zIndex.appBar
	},
	chevronButtonClosed: {
		position: "absolute",
		left: "50%",
		top: 14,
		marginLeft: -13,
		zIndex: theme.zIndex.appBar
	},
	entityHeader: {
		position: "relative",
		zIndex: theme.zIndex.appBar,
		boxShadow: "0px 2px 1px -1px rgba(0, 0, 0, 0.2), 0px 1px 1px 0px rgba(0, 0, 0, 0.14), 0px 3px 3px 0px rgba(0, 0, 0, 0.12)"
	},
	nodeHeader: { boxShadow: "0px 2px 1px -1px rgba(0, 0, 0, 0.2), 0px 1px 1px 0px rgba(0, 0, 0, 0.14), 0px 3px 3px 0px rgba(0, 0, 0, 0.12)" },
	content: {
		overflowY: "auto",
		height: "calc(100vh - 50px)"
	},
	workflowMenuContent: {
		marginTop: theme.spacing(1),
		height: ({ appRibbonSpace }) => `calc(100vh - ${appRibbonSpace + 120}px)`,
		overflowX: "hidden",
		paddingTop: theme.spacing(1)
	},
	workflowTreeLoader: {
		marginRight: theme.spacing(1),
		marginLeft: theme.spacing(1)
	}
}));
const WORKFLOW_MAX_NETWORK_CALLS = 50;
const getKeyIdentifier = (n) => n.isGroupNode ? n.properties?.label : n.nodeObj?.businessObjectKey;
const InquiryContainer = (props) => {
	const { catalogObjects, executeQueryAdHoc, executeQueryWithParameters, executeGetDetailedTree, executeAddRecentlyLoadedNodes, initialSearchValue, litnHistory, litnHistoryLoading, pageId, pageData, pageLoading, pageError, productId, promotedEntities, apiCatalogId, setPageId, tree, treeId, treeLoading, treeError, user, autoCollapseNav = true, containerId = "" } = props;
	const shellHidden = useShellStore((state) => state.shellHidden);
	const buildEnv = useBuildEnvironment();
	const classes = useStyles({
		shellHidden,
		...props,
		appRibbonSpace: buildEnv ? 25 : 0
	});
	const { t } = useTranslation();
	const { enqueueSnackbar } = useSnackbar();
	const [refreshing, setRefreshing] = useState(false);
	const [nodeLoaded, setNodeLoaded] = useState(false);
	const [searchValue, setSearchValue] = useState(initialSearchValue || "");
	const [clearSearchStr, setClearSearchStr] = useState(false);
	const [inSearch, setInSearch] = useState(false);
	const [selectedSearchRows, setSelectedSearchRows] = useState(null);
	const [menuList, setMenuList] = useState([]);
	const [menuLoading, setMenuLoading] = useState(false);
	const [selectedNode, setSelectedNode] = useState(null);
	const [selectedMenuIndex, setSelectedMenuIndex] = useState(null);
	const [disableMoveToTop, setDisableMoveToTop] = useState(true);
	const [nodeHistory, setNodeHistory] = useState([]);
	const [expandAllClicked, setExpandAllClicked] = useState(false);
	const [tabValue, setTabValue] = useState(0);
	const [selectedPageId, setSelectedPageId] = useState(null);
	const [nodesRequested, setNodesRequested] = useState([]);
	const [sidebarTabValue, setSidebarTabValue] = useState(0);
	const [advancedSearchItems, setAdvancedSearchItems] = useState([]);
	const [isAdvancedSearch, setIsAdvancedSearch] = useState(false);
	const [entityValue, setEntityValue] = useState("");
	const [treeViewMode, setTreeViewMode] = useState(TreeViewModeEnums.Classic);
	const [advancedSearchEntityValue, setAdvancedSearchEntityValue] = useState("");
	const [moveToTopLoading, setMoveToTopLoading] = useState(false);
	const [promotedMethodsToExecute, setPromotedMethodsToExecute] = useState([]);
	const [executeApiDialogOpen, setExecuteApiDialogOpen] = useState(false);
	const [executeApiData, setExecuteApiData] = useState(null);
	const [executeApiProgress, setExecuteApiProgress] = useState(false);
	const [isPreloaded, setIsPreloaded] = useState(false);
	const [headerTitle, setHeaderTitle] = useState("");
	const [sidebarExpanded, setSidebarExpanded] = useState(true);
	const [primaryExpanded, setPrimaryExpanded] = useState(false);
	const [secondaryExpanded, setSecondaryExpanded] = useState(false);
	const [showToggle1, setShowToggle1] = useState(false);
	const [showToggle2, setShowToggle2] = useState(false);
	const [utilitySideBarWidth, setUtilitySideBarWidth] = useState(288);
	const [refreshNodeHeaderPageData, setRefreshNodeHeaderPageData] = useState(null);
	const [refreshPageHeaderPageData, setRefreshPageHeaderPageData] = useState(null);
	const [dragAndDropLoading, setDragAndDropLoading] = useState(false);
	const [inquiryWorkflowTabValue, setInquiryWorkflowTabValue] = useState(1);
	const [workflowMenuItemsList, setWorkflowMenuItemsList] = useState([]);
	const [selectedWorkflowNode, setSelectedWorkflowNode] = useState(null);
	const [reloadWorkflowFromPage, setReloadWorkflowFromPage] = useState(false);
	const [getWorkflowPlayErrorCount, setGetWorkflowPlayErrorCount] = useState(0);
	const [getWorkflowInitializedCount, setGetWorkflowInitializedCount] = useState(0);
	const [workflowInitialized, setWorkflowInitialized] = useState(false);
	const [workflow, setWorkflow] = useState(null);
	useSetInitialInquiryMenuVisibility();
	const inquiryMenuHidden = useInquiryStore((state) => state.inquiryMenuHidden);
	const { setActionPanels, setShowInquiryHeaderActions, setMenuListState, setInquiryParams, closeAllSplitScreens } = useActions();
	const setSelectedNodeForStore = useActionStore((state) => state.setSelectedNode);
	const setHideActions = useActionStore((state) => state.setHideActions);
	const setInquiryTitleHeader = useInquiryStore((state) => state.setInquiryToolbarTitle);
	const setNavigationExpanded = useShellStore((state) => state.setNavigationExpanded);
	const setSubHeaderActionHasChildren = useShellStore((state) => state.setSubHeaderActionHasChildren);
	const inquiryTitle = useInquiryStore((state) => state.title);
	const workflowMap = useInquiryStore((state) => state.workflowMap);
	const setWorkflowMap = useInquiryStore((state) => state.setWorkflowMap);
	const workflowStarting = useInquiryStore((state) => state.workflowStarting);
	const setLocationState = useSetLocationState();
	const [{ data: explorePageData, loading: explorePageLoading }] = useAxiosGet(ConfigService.tenantV1ApiUrl, `page/${tree?.explorePageId}`, {}, !!!tree?.explorePageId, false);
	const orderBySequence = (list) => {
		return orderBy(list, ["sequenceNo"], ["asc"]);
	};
	const selectedTree = useMemo(() => menuList[selectedMenuIndex] ?? null, [menuList, selectedMenuIndex]);
	const inquiryWorkflow = useMemo(() => {
		if (workflowMap) return workflowMap[containerId || 0];
	}, [workflowMap, containerId]);
	const nodeHeaderPageIdToLoad = useMemo(() => {
		const nodeHeaderPages = selectedNode?.properties?.nodeHeaderPages;
		if (!nodeHeaderPages) return null;
		const orderedNodeHeaderPages = orderBySequence(nodeHeaderPages);
		let nodeHeaderPageId = null;
		for (let i = 0; i < orderedNodeHeaderPages.length; i++) {
			const nodeHeaderPage = orderedNodeHeaderPages[i];
			if (nodeHeaderPage?.propertyMapping && nodeHeaderPage?.jsonLogic) if (evaluateRule(mapRule(nodeHeaderPage?.propertyMapping, nodeHeaderPage?.jsonLogic), selectedNode.nodeObj, null, false)) {
				nodeHeaderPageId = nodeHeaderPage.page?.pageId;
				break;
			} else continue;
			else {
				nodeHeaderPageId = nodeHeaderPage.page?.pageId;
				break;
			}
		}
		return nodeHeaderPageId;
	}, [selectedNode]);
	const pageHeaderPageIdToLoad = useMemo(() => {
		if (!selectedPageId) return null;
		const matchingTab = selectedNode?.properties?.tabs?.find((tab) => tab.page?.pageId === selectedPageId);
		if (!matchingTab) return null;
		const pageHeaderPages = matchingTab?.pageHeaderPages;
		if (!pageHeaderPages) return null;
		const orderedPageHeaderPages = orderBySequence(pageHeaderPages);
		let pageHeaderPageId = null;
		for (let i = 0; i < orderedPageHeaderPages.length; i++) {
			const pageHeaderPage = orderedPageHeaderPages[i];
			if (pageHeaderPage?.propertyMapping && pageHeaderPage?.jsonLogic) if (evaluateRule(mapRule(pageHeaderPage?.propertyMapping, pageHeaderPage?.jsonLogic), selectedNode.nodeObj, null, false)) {
				pageHeaderPageId = pageHeaderPage.page?.pageId;
				break;
			} else continue;
			else {
				pageHeaderPageId = pageHeaderPage.page?.pageId;
				break;
			}
		}
		return pageHeaderPageId;
	}, [selectedNode, selectedPageId]);
	const [{ data: nodeHeaderPageData, loading: nodeHeaderPageLoading }] = useAxiosGet(ConfigService.tenantV1ApiUrl, `page/${nodeHeaderPageIdToLoad}`, {}, !!!nodeHeaderPageIdToLoad, false);
	const [{ data: pageHeaderPageData, loading: pageHeaderPageLoading }] = useAxiosGet(ConfigService.tenantV1ApiUrl, `page/${pageHeaderPageIdToLoad}`, {}, !!!pageHeaderPageIdToLoad, false);
	const [{ data: workflowPlay, loading: workflowPlayLoading, error: workflowPlayError }, reloadWorkflow] = useAxiosGet(ConfigService.builderV1ApiUrl, `workflow/play/${inquiryWorkflow?.currentWorkflowPlayId}`, {}, !!!inquiryWorkflow?.currentWorkflowPlayId, false);
	const [{ data: users }] = useAxiosGet(ConfigService.securityV1ApiUrl, `users?tenantId=${user?.currentTenantId || ""}`, {}, !!!inquiryWorkflow?.inWorkflowMode && !!!user?.currentTenantId);
	const [{ data: groups }] = useAxiosGet(ConfigService.tenantV1ApiUrl, `groups?tenantId=${user?.currentTenantId || ""}&productId=${ConfigService.config.UNITY_PRODUCT_ID}`, {}, !!!inquiryWorkflow?.inWorkflowMode && !!!user?.currentTenantId);
	const handleReloadWorkflow = useCallback(async () => {
		setReloadWorkflowFromPage(true);
		if (inquiryWorkflow?.currentWorkflowPlayId) await reloadWorkflow();
		setReloadWorkflowFromPage(false);
	}, [reloadWorkflow, inquiryWorkflow]);
	const handleSelectedWorkflowNode = useCallback(async (node, menuIndex) => {
		if (node.isSelectable) {
			setSelectedWorkflowNode(node);
			await handleReloadWorkflow();
		}
	}, [handleReloadWorkflow]);
	const searchItems = useMemo(() => {
		if (!tree) return [];
		return tree.treeStructure.reduce((items, node) => {
			let item = null;
			const entityAttributes = (catalogObjects?.find((co) => co.catalogObjectName === node.properties.catalogReturnObject))?.properties || null;
			const searchFilterElements = node.properties?.searchFilterElements;
			if (searchFilterElements) searchFilterElements.forEach((element) => element.searchValue = searchValue);
			if (!node.parentId) item = {
				apiMethodInstance: tree.apiMethodInstance,
				apiMethodId: tree.apiMethodInstance.apiMethodId,
				columns: entityAttributes || node.properties.searchTableColumns,
				searchFilterElements,
				id: `${v4()}-${searchValue}`,
				catalogReturnObject: node.properties.catalogReturnObject,
				treeStructure: tree.treeStructure,
				associatedInquiryTree: null
			};
			else {
				const associatedInquiryTree = node.properties?.associatedInquiryTree;
				if (associatedInquiryTree && node.properties?.isPrimarySearch) item = {
					apiMethodInstance: associatedInquiryTree.apiMethodInstance,
					apiMethodId: associatedInquiryTree.apiMethodInstance?.apiMethodId,
					columns: entityAttributes || node.properties.searchTableColumns,
					searchFilterElements,
					id: `${v4()}-${searchValue}`,
					catalogReturnObject: node.properties.catalogReturnObject,
					treeStructure: associatedInquiryTree.treeStructure,
					associatedInquiryTree
				};
			}
			if (item) items.push(item);
			return items;
		}, []);
	}, [
		tree,
		searchValue,
		catalogObjects
	]);
	const entitySearchItems = useMemo(() => {
		if (!searchItems) return [];
		if (!entityValue?.value) return searchItems;
		else return searchItems.filter((item) => item.catalogReturnObject === entityValue.value);
	}, [searchItems, entityValue]);
	const getLoadedNodeObject = useCallback((apiMethodId, queryPayload, nodeLabel, catalogReturnObject, treeStructureId) => {
		const loadedNode = {
			productId,
			inquiryTreeId: treeId,
			userId: user.id,
			apiMethodId,
			nodeDetails: {},
			queryPayload: {}
		};
		loadedNode.nodeDetails = {
			nodeLabel,
			catalogReturnObject,
			treeStructureId
		};
		loadedNode.queryPayload = queryPayload;
		return loadedNode;
	}, [
		treeId,
		user,
		productId
	]);
	const setAppNavigationExpanded = useCallback((value) => {
		if (autoCollapseNav) setNavigationExpanded(value);
	}, [autoCollapseNav, setNavigationExpanded]);
	const loadNodes = useCallback((searchRows) => {
		if (searchRows && Object.keys(searchRows).length) {
			setSidebarTabValue(0);
			setNodeLoaded(true);
			setInSearch(false);
			setMenuLoading(true);
			const catalogObjectKeys = Object.keys(searchRows);
			const promises = [];
			const searchObjList = [];
			const loadedNodesList = [];
			const nodesRequestedArr = [];
			catalogObjectKeys.forEach((key) => {
				const searchObj = searchRows[key];
				const currentSearchTree = searchObj?.treeStructure.find((tree) => tree?.properties?.catalogReturnObject === key);
				const lazyLoad = !!currentSearchTree?.properties?.lazyLoad;
				const rows = searchObj.rows;
				const searchIdentifier = searchObj.searchIdentifier;
				const apiMethodId = searchObj.apiMethodId;
				const associatedInquiryTree = searchObj?.associatedInquiryTree;
				rows.forEach((row) => {
					const filterElements = [];
					searchIdentifier.split(",").forEach((si) => {
						const formattedPropertyName = si.charAt(0).toUpperCase() + si.slice(1);
						filterElements.push({
							searchField: formattedPropertyName,
							searchValue: row[si] ?? "",
							searchOperator: "="
						});
					});
					const searchObject = getSearchObject(filterElements, 1, 50, !lazyLoad);
					const data = { data: searchObject };
					promises.push(executeQueryAdHoc(data, apiMethodId));
					nodesRequestedArr.push(nodesRequestedArr.length + 1);
					searchObjList.push({
						searchObject,
						apiMethodId,
						treeStructure: searchObj.treeStructure,
						catalogReturnObject: key,
						associatedInquiryTree,
						wasLazyLoaded: lazyLoad,
						menuTree: currentSearchTree
					});
				});
			});
			setNodesRequested(nodesRequestedArr);
			Promise.all(promises).then((responses) => {
				const updatedMenuList = menuList.slice();
				responses.forEach((response, index) => {
					if (response.status === 200) {
						if (response?.data?.pageList?.length) {
							const treeStructure = makeTreeStructure(searchObjList[index].treeStructure, "id", "parentId");
							const displayTree = formatTreeMenuItem(response.data.pageList[0], treeStructure, catalogObjects, promotedEntities, searchObjList[index].associatedInquiryTree, searchObjList[index].wasLazyLoaded);
							if (displayTree && !Array.isArray(displayTree) && Object.keys(displayTree).length) {
								updatedMenuList.push(displayTree);
								loadedNodesList.push(getLoadedNodeObject(searchObjList[index].apiMethodId, searchObjList[index].searchObject, displayTree?.properties?.nodeLabel, searchObjList[index].catalogReturnObject, treeStructure.id));
								if (index === 0) {
									displayTree.properties.searchValue = getSearchValueString(response.data.pageList[0], displayTree?.properties?.searchIdentifier);
									if (selectedNode) {
										const updatedNodeHistory = nodeHistory.map((node) => node);
										updatedNodeHistory.push(selectedNode);
										setNodeHistory(updatedNodeHistory);
									}
									setActionPanels(displayTree?.properties.panels, containerId);
									setSelectedNode(displayTree);
								}
							}
						}
					}
				});
				if (menuList.length) setSelectedMenuIndex(menuList.length);
				else setSelectedMenuIndex(0);
				executeAddRecentlyLoadedNodes({ data: loadedNodesList });
				setAppNavigationExpanded(false);
				setMenuList(updatedMenuList);
				setSelectedSearchRows(null);
				setMenuLoading(false);
				setNodesRequested([]);
				setSearchValue("");
				setClearSearchStr(true);
			});
		}
	}, [
		menuList,
		executeQueryAdHoc,
		catalogObjects,
		selectedNode,
		nodeHistory,
		getLoadedNodeObject,
		executeAddRecentlyLoadedNodes,
		promotedEntities,
		setActionPanels,
		setAppNavigationExpanded,
		containerId
	]);
	const handleCloseWorkflow = useCallback(() => {
		setWorkflowMap({ [containerId || 0]: {
			inWorkflowMode: false,
			currentWorkflowPlayId: ""
		} });
		setHideActions(false);
		setSelectedWorkflowNode(null);
		setWorkflowMenuItemsList([]);
		setInquiryWorkflowTabValue(1);
		setGetWorkflowPlayErrorCount(0);
		setGetWorkflowInitializedCount(0);
		setWorkflowInitialized(false);
		setWorkflow(null);
	}, [
		setWorkflowMap,
		containerId,
		setHideActions
	]);
	const handleRemoveMenuItem = useCallback((menus) => {
		const updatedMenuList = menus ?? menuList.slice();
		updatedMenuList.splice(selectedMenuIndex, 1);
		setMenuList(updatedMenuList);
		setDisableMoveToTop(true);
		if (updatedMenuList?.length) {
			const newSelectedNode = updatedMenuList[0];
			setActionPanels(newSelectedNode?.properties.panels, containerId);
			setSelectedNode(newSelectedNode);
			setSelectedMenuIndex(0);
		} else {
			setActionPanels([], containerId);
			setSelectedNode(null);
			setSelectedMenuIndex(null);
			setNodeLoaded(false);
			closeAllSplitScreens();
			handleCloseWorkflow();
		}
	}, [
		menuList,
		selectedMenuIndex,
		setActionPanels,
		closeAllSplitScreens,
		containerId,
		handleCloseWorkflow
	]);
	const handleRecentlyLoadedNodeClick = useCallback(async (loadedNode, additionalAction = () => {}) => {
		setNodeLoaded(true);
		setMenuLoading(true);
		setSidebarTabValue(0);
		setNodesRequested([1]);
		const data = { data: loadedNode?.queryPayload };
		const currentTreeStructureArr = tree.treeStructure.filter((node) => loadedNode?.nodeDetails?.catalogReturnObject === node.properties.catalogReturnObject);
		const currentTree = currentTreeStructureArr.find((t) => {
			if (t?.properties?.associatedInquiryTree?.treeStructure) return t?.properties?.associatedInquiryTree?.treeStructure.find((n) => n.id === loadedNode?.nodeDetails?.treeStructureId);
			else return false;
		}) || currentTreeStructureArr[0];
		if (currentTree) if (currentTree.properties?.associatedInquiryTree) {
			const associatedTree = (currentTree.properties.associatedInquiryTree?.treeStructure).find((node) => node.id === loadedNode?.nodeDetails?.treeStructureId);
			data.data.eagerLoad = !associatedTree?.properties?.lazyLoad;
		} else data.data.eagerLoad = !currentTree?.properties?.lazyLoad;
		const apiMethodId = loadedNode?.apiMethodId;
		const response = await executeQueryAdHoc(data, apiMethodId).catch((e) => {
			console.error(e);
		});
		if (response?.status === 200 && loadedNode?.nodeDetails?.catalogReturnObject) {
			if (response?.data?.pageList?.length) {
				const matchingNode = tree?.treeStructure?.find((node) => node.properties.catalogReturnObject === loadedNode?.nodeDetails?.catalogReturnObject);
				let nodeTreeStructure = tree?.treeStructure;
				if (matchingNode?.properties?.associatedInquiryTree) nodeTreeStructure = matchingNode?.properties?.associatedInquiryTree.treeStructure;
				const treeStructure = makeTreeStructure(nodeTreeStructure, "id", "parentId");
				const displayTree = formatTreeMenuItem(response.data.pageList[0], treeStructure, catalogObjects, promotedEntities, matchingNode?.properties?.associatedInquiryTree, !data.data.eagerLoad);
				if (displayTree && !Array.isArray(displayTree) && Object.keys(displayTree).length) {
					displayTree.properties.searchValue = getSearchValueString(response.data.pageList[0], displayTree?.properties?.searchIdentifier);
					if (selectedNode) {
						const updatedNodeHistory = nodeHistory.map((node) => node);
						updatedNodeHistory.push(selectedNode);
						setNodeHistory(updatedNodeHistory);
					}
					setActionPanels(displayTree?.properties.panels, containerId);
					setSelectedNode(displayTree);
					setAppNavigationExpanded(false);
					setMenuList([displayTree]);
				}
				setSelectedMenuIndex(0);
				setMenuLoading(false);
				setNodesRequested([]);
			}
		} else {
			setMenuLoading(false);
			enqueueSnackbar(t(`Unable to load entity`), {
				variant: "error",
				anchorOrigin: {
					vertical: "top",
					horizontal: "center"
				}
			});
		}
		additionalAction();
	}, [
		tree,
		executeQueryAdHoc,
		catalogObjects,
		promotedEntities,
		selectedNode,
		setActionPanels,
		nodeHistory,
		enqueueSnackbar,
		t,
		setAppNavigationExpanded,
		containerId
	]);
	const handleLoadNodes = useCallback(() => {
		loadNodes(selectedSearchRows);
	}, [selectedSearchRows, loadNodes]);
	const handleSingleNodeLoad = useCallback((searchRow) => {
		loadNodes(searchRow);
	}, [loadNodes]);
	const handleRowDoubleClick = useCallback((rowData, catalogReturnObject) => {
		const node = {};
		const searchItem = searchItems.find((item) => item.catalogReturnObject === catalogReturnObject);
		const identifiers = getSearchIdentifiers(catalogObjects, searchItem.catalogReturnObject) || [];
		node[searchItem.catalogReturnObject] = {
			rows: [rowData],
			apiMethodId: searchItem.apiMethodId,
			searchIdentifier: identifiers.toString(),
			treeStructure: searchItem.treeStructure
		};
		loadNodes(node);
	}, [
		loadNodes,
		searchItems,
		catalogObjects
	]);
	const clearNodes = useCallback(() => {
		setNodeLoaded(false);
		setMenuList([]);
		setActionPanels([], containerId);
		setSelectedNode(null);
		setSelectedMenuIndex(null);
		setNodeHistory([]);
		setTabValue(0);
		setSelectedPageId(null);
		setPageId(null);
		setHeaderTitle("");
		setNodesRequested([]);
		closeAllSplitScreens();
		handleCloseWorkflow();
	}, [
		setActionPanels,
		setPageId,
		closeAllSplitScreens,
		containerId,
		handleCloseWorkflow
	]);
	const handlePrimaryAction = useCallback(() => {
		handleLoadNodes();
	}, [handleLoadNodes]);
	const handleSearch = useCallback((event) => {
		if (event.key === "Enter") {
			setSearchValue(event.target.value);
			setIsAdvancedSearch(false);
			setInSearch(true);
		}
	}, []);
	const clearSearch = useCallback(() => {
		setInSearch(false);
		if (menuList.length > 0) setShowToggle2(true);
		setSearchValue("");
		setClearSearchStr(true);
		setSelectedSearchRows(null);
	}, [menuList]);
	const handleSelectedSearchRows = useCallback((objectName, rows, searchIdentifier, apiMethodId, treeStructure, associatedInquiryTree) => {
		let searchRows = cloneDeep(selectedSearchRows);
		if (!searchRows) searchRows = {};
		searchRows[objectName] = {
			rows,
			searchIdentifier,
			apiMethodId,
			treeStructure,
			associatedInquiryTree
		};
		setSelectedSearchRows(searchRows);
	}, [selectedSearchRows]);
	const handleSelectedNode = useCallback((newSelectedNode, menuIndex) => {
		setSelectedMenuIndex(menuIndex);
		setInSearch(false);
		if (newSelectedNode.properties.associatedTreeId) setDisableMoveToTop(false);
		else setDisableMoveToTop(true);
		if (selectedNode) {
			const updatedNodeHistory = nodeHistory?.map((node) => node) || [];
			updatedNodeHistory.push(selectedNode);
			setNodeHistory(updatedNodeHistory);
		}
		setActionPanels(newSelectedNode?.properties.panels, containerId);
		setSelectedNode(newSelectedNode);
	}, [
		selectedNode,
		setActionPanels,
		nodeHistory,
		containerId
	]);
	const constructMenuItemForDroppedNode = useCallback((loadPageNodeActions, targetNodeObj, sourceNodeObj, targetNodeEntityName, sourceNodeEntityName) => {
		const menuItem = {
			children: [],
			id: v4(),
			isExpanded: true,
			parentId: null,
			properties: {
				nodeLabel: "",
				tabs: [],
				searchValue: "",
				nodeSubLabel: null,
				defaultPageHeaderExpanded: "hidden",
				defaultNodeHeaderExpanded: "hidden",
				defaultIcon: {
					color: null,
					name: "BranchCompareIcon",
					type: null
				},
				nodeActions: loadPageNodeActions,
				isDroppedLoadedPageNode: true,
				existingPageLoadEntities: [sourceNodeEntityName]
			},
			inquiryParams: [targetNodeObj, sourceNodeObj],
			nodeObj: targetNodeObj
		};
		if (loadPageNodeActions?.length) loadPageNodeActions.forEach((nodeAction) => {
			if (nodeAction?.dragEntityName === sourceNodeEntityName) {
				const tabObj = {
					id: v4(),
					page: nodeAction.page,
					inquiryTreeRuleId: nodeAction.inquiryTreeRuleId || "",
					jsonLogic: nodeAction.jsonLogic || null,
					propertyIsCustomMapping: nodeAction.propertyIsCustomMapping || "",
					propertyMapping: nodeAction.propertyMapping || "",
					sequence: nodeAction.sequence || "1",
					requiredFieldMapping: nodeAction.parameters?.requiredFieldMapping || null
				};
				menuItem.properties.tabs.push(tabObj);
			}
		});
		let nodeLabel = "DnD Nodes";
		if (targetNodeEntityName === sourceNodeEntityName) nodeLabel = pluralize(getSanitizedName(targetNodeEntityName));
		else nodeLabel = `${getSanitizedName(targetNodeEntityName)}/${getSanitizedName(sourceNodeEntityName)}`;
		menuItem.properties.nodeLabel = nodeLabel;
		return menuItem;
	}, []);
	const loadPageForDroppedNode = useCallback((sourceNode, targetNode, loadPageNodeActions, targetNodeCatalogReturnObject, sourceNodeCatalogReturnObject) => {
		if (!targetNode?.properties?.isDroppedLoadedPageNode) {
			if (loadPageNodeActions.length) {
				setMoveToTopLoading(true);
				const pageMenuItem = constructMenuItemForDroppedNode(orderBySequence(loadPageNodeActions), targetNode?.nodeObj, sourceNode?.nodeObj, targetNodeCatalogReturnObject, sourceNodeCatalogReturnObject);
				const updatedMenuList = cloneDeep(menuList);
				updatedMenuList.unshift(pageMenuItem);
				setActionPanels(updatedMenuList[0]?.properties.panels, containerId);
				setSelectedNode(updatedMenuList[0]);
				setMenuList(updatedMenuList);
				setMoveToTopLoading(false);
			}
		} else if (targetNode?.properties?.isDroppedLoadedPageNode) {
			setMoveToTopLoading(true);
			const updatedMenuList = cloneDeep(menuList);
			const targetMenuItem = updatedMenuList.find((item) => item.id === targetNode.id);
			if (targetMenuItem) {
				const nodeLabel = targetMenuItem.properties?.nodeLabel;
				if (!nodeLabel.includes(sourceNodeCatalogReturnObject)) targetMenuItem.properties.nodeLabel = `${nodeLabel}/${getSanitizedName(sourceNodeCatalogReturnObject)}`;
				targetMenuItem.inquiryParams.push(sourceNode?.nodeObj);
				if (!targetNode?.properties?.existingPageLoadEntities?.includes(sourceNodeCatalogReturnObject) && loadPageNodeActions?.length) {
					targetMenuItem.properties.existingPageLoadEntities.push(sourceNodeCatalogReturnObject);
					loadPageNodeActions.forEach((nodeAction) => {
						if (nodeAction?.dragEntityName === sourceNodeCatalogReturnObject) {
							const tabObj = {
								id: v4(),
								page: nodeAction.page,
								inquiryTreeRuleId: nodeAction.inquiryTreeRuleId || "",
								jsonLogic: nodeAction.jsonLogic || null,
								propertyIsCustomMapping: nodeAction.propertyIsCustomMapping || "",
								propertyMapping: nodeAction.propertyMapping || "",
								sequence: nodeAction.sequence || "1",
								requiredFieldMapping: nodeAction.parameters?.requiredFieldMapping || null
							};
							targetMenuItem.properties.tabs.push(tabObj);
						}
					});
				}
				setActionPanels(targetMenuItem?.properties.panels, containerId);
				setSelectedNode(targetMenuItem);
			}
			setMenuList(updatedMenuList);
			setMoveToTopLoading(false);
		}
	}, [
		constructMenuItemForDroppedNode,
		menuList,
		setActionPanels,
		containerId
	]);
	const handleDroppedNodeForExecuteApi = useCallback(async (sourceNode, targetNode, executeApiNodeActions, sourceNodeType, targetNodeType, sourceNodeMenuIndex, targetNodeMenuIndex) => {
		setDragAndDropLoading(true);
		const apiMethodIds = executeApiNodeActions.map((eana) => eana.actionValue);
		const promotedMethods = await apiMutate(ConfigService.integrationV2ApiUrl, `apiMethod/listByApiCatalogIdAndIds/${apiCatalogId}`, { method: "post" }, { data: apiMethodIds });
		setDragAndDropLoading(false);
		const pmte = promotedMethods?.data ?? [];
		setExecuteApiData({
			source: sourceNode?.nodeObj,
			target: targetNode?.nodeObj,
			sourceNodeType,
			targetNodeType,
			sourceNodeMenuIndex,
			targetNodeMenuIndex
		});
		setPromotedMethodsToExecute(pmte);
		setExecuteApiDialogOpen(true);
	}, [apiCatalogId]);
	const handleCloseExecuteApiDialog = useCallback(() => {
		setExecuteApiData(null);
		setPromotedMethodsToExecute([]);
		setExecuteApiDialogOpen(false);
	}, []);
	const handleMenuTreesRefresh = useCallback(async (menuIndexes) => {
		if (!menuList.length) return;
		const updatedMenuList = menuList.slice();
		const promises = [];
		let apiMethodId = tree.apiMethodInstance.apiMethodId;
		let workingTree = tree;
		let assocInquiryTreeMap = {};
		let searchObjList = [];
		if (!menuIndexes?.length) menuIndexes = [selectedMenuIndex];
		menuIndexes.forEach((index) => {
			const menuTree = menuList[index];
			if (menuTree) {
				const { properties, associatedInquiryTree } = menuTree;
				const { filterElements } = properties;
				if (associatedInquiryTree) {
					apiMethodId = associatedInquiryTree.apiMethodInstance.apiMethodId;
					workingTree = associatedInquiryTree;
					assocInquiryTreeMap[index] = associatedInquiryTree;
				}
				const lazyLoad = !!workingTree?.properties?.lazyLoad;
				const data = { data: getSearchObject(filterElements, 1, 50, !lazyLoad) };
				promises.push(executeQueryAdHoc(data, apiMethodId));
				searchObjList.push({ wasLazyLoaded: lazyLoad });
			}
		});
		await Promise.all(promises.map((p) => p.catch((e) => e))).then((responses) => {
			responses.forEach((response, index) => {
				if (response.status === 200) {
					if (response?.data?.pageList?.length) {
						const treeStructure = makeTreeStructure(workingTree.treeStructure, "id", "parentId");
						const displayTree = formatTreeMenuItem(response.data.pageList[0], treeStructure, catalogObjects, promotedEntities, assocInquiryTreeMap[index], searchObjList[index].wasLazyLoaded);
						updatedMenuList[menuIndexes[index]] = displayTree;
					}
				}
			});
		});
		const currentSelectedTree = updatedMenuList[selectedMenuIndex];
		const selectedNodeSearchIdentifier = selectedNode.properties.searchIdentifier || [];
		setMenuList(updatedMenuList);
		if (selectedNodeSearchIdentifier) {
			const matchingNode = findNodeByBusinessObjectKey(currentSelectedTree, selectedNode.nodeObj?.businessObjectKey)?.node;
			setActionPanels(matchingNode?.properties.panels, containerId);
			setSelectedNode(matchingNode);
		} else setSelectedNode(selectedNode);
	}, [
		menuList,
		tree,
		selectedMenuIndex,
		catalogObjects,
		executeQueryAdHoc,
		selectedNode,
		promotedEntities,
		setActionPanels,
		containerId
	]);
	const expandedStateRef = useRef({});
	const handleExpandedChange = useCallback((menuIndex, stateMap) => {
		expandedStateRef.current[menuIndex] = stateMap;
	}, []);
	const restoreExpandedState = useCallback((node, stateMap) => {
		if (!node) return;
		const getStableKey = (n) => n.isGroupNode ? n.properties?.label : n.nodeObj?.businessObjectKey;
		const walk = (n) => {
			const key = getStableKey(n);
			if (key && stateMap.has(key)) n.isExpanded = stateMap.get(key);
			n.children?.forEach(walk);
		};
		if (Array.isArray(node)) node.forEach(walk);
		else walk(node);
	}, []);
	const treeNodeIds = useMemo(() => {
		if (!selectedTree) return null;
		const idMap = {};
		const stack = [selectedTree];
		while (stack.length) {
			const node = stack.pop();
			idMap[node.id] = node;
			node.children?.forEach((child) => stack.push(child));
		}
		return idMap;
	}, [selectedTree]);
	const getCriticalPath = useCallback((selectedTreeNode) => {
		if (!selectedTreeNode) return [];
		const path = [];
		let node = selectedTreeNode;
		const treeNodes = treeNodeIds;
		path.push(node);
		while (node.parentId) {
			node = treeNodes[node.parentId];
			path.push(node);
		}
		return path;
	}, [treeNodeIds]);
	const hasLazyLevelInStructure = useMemo(() => {
		return tree?.treeStructure?.some((level) => level.properties?.lazyLoad) ?? false;
	}, [tree?.treeStructure]);
	const fetchAndBuildDisplayTree = useCallback(async () => {
		if (!tree || !selectedTree) return null;
		const lazyLoad = tree.properties?.lazyLoad ?? false;
		const filterElements = selectedTree.properties?.filterElements;
		const associatedInquiryTree = selectedTree.associatedInquiryTree;
		const workingTree = selectedTree.associatedInquiryTree ?? tree;
		if (!workingTree.apiMethodInstance) return null;
		const apiMethodId = workingTree.apiMethodInstance.apiMethodId;
		const data = { data: getSearchObject(filterElements, 1, 50, !lazyLoad) };
		const response = tree?.isPreloaded && tree?.apiMethodInstance?.apiMethodInstanceId && selectedTree.isGroupNode ? await executeQueryInstance({ data: {} }, tree.apiMethodInstance.apiMethodInstanceId) : await executeQueryAdHoc(data, apiMethodId);
		if (response?.status !== 200 || !response?.data?.pageList?.length) return null;
		const treeStructure = makeTreeStructure(workingTree.treeStructure, "id", "parentId");
		let responseObj = response.data.pageList[0];
		if (selectedTree.isGroupNode) responseObj = response.data.pageList;
		return formatTreeMenuItem(responseObj, treeStructure, catalogObjects, promotedEntities, associatedInquiryTree, lazyLoad);
	}, [
		catalogObjects,
		executeQueryAdHoc,
		promotedEntities,
		selectedTree,
		tree
	]);
	const fetchAndMergeLazyNode = useCallback(async (currentNode, workingTree, context) => {
		let { currentCriticalPathNode, criticalPathBroken, survivingAncestor, criticalPathList } = context;
		const inclusionFilter = keysByTypeToFilterArray(collectChildVaryingKeysByType(currentNode, catalogObjects));
		const [res, totalsByType] = await Promise.all([fetchLazyChildren({
			node: currentNode,
			treeStructureArr: workingTree?.treeStructure || [],
			executeQueryAdHoc,
			catalogObjects,
			promotedEntities,
			pageNumber: 1,
			inclusionFilter
		}), fetchCountsByType(currentNode, executeQueryAdHoc)]);
		const isCriticalPathNode = currentNode.nodeObj?.businessObjectKey === currentCriticalPathNode?.nodeObj?.businessObjectKey;
		if (!criticalPathBroken && isCriticalPathNode && criticalPathList.length) {
			currentCriticalPathNode = criticalPathList.pop();
			const nextAncestorBok = currentCriticalPathNode?.nodeObj?.businessObjectKey;
			const present = res.children.some((c) => c.nodeObj?.businessObjectKey === nextAncestorBok);
			if (nextAncestorBok && !present) {
				criticalPathBroken = true;
				survivingAncestor = currentNode;
			}
		}
		const existingChildrenMap = /* @__PURE__ */ new Map();
		(currentNode.children || []).forEach((oldChild) => {
			if (oldChild?.isGroupNode) return;
			const type = oldChild.properties?.catalogReturnObject;
			const bok = oldChild.nodeObj?.businessObjectKey;
			if (type && bok) existingChildrenMap.set(`${type}_${bok}`, oldChild);
		});
		const mergedChildren = [];
		res.children.forEach((freshChild) => {
			const type = freshChild.properties?.catalogReturnObject;
			const bok = freshChild.nodeObj?.businessObjectKey;
			if (!type || !bok) return;
			const existingChild = existingChildrenMap.get(`${type}_${bok}`);
			if (existingChild) {
				existingChild.nodeObj = freshChild.nodeObj;
				existingChild.properties = freshChild.properties;
				mergedChildren.push(existingChild);
			} else mergedChildren.push(freshChild);
		});
		currentNode.children = [...(currentNode.children || []).filter((c) => c?.isGroupNode), ...mergedChildren];
		const localPhysicalCounts = {};
		currentNode.children.forEach((c) => {
			if (c?.isGroupNode) return;
			const type = c.properties?.catalogReturnObject;
			if (type) localPhysicalCounts[type] = (localPhysicalCounts[type] || 0) + 1;
		});
		const hasMore = Object.entries(totalsByType).some(([type, total]) => total > (localPhysicalCounts[type] || 0));
		const freshSeenByType = collectChildVaryingKeysByType(currentNode, catalogObjects);
		currentNode.completedLoadingChildren = true;
		currentNode.hasMoreChildren = hasMore;
		currentNode.seenChildKeysByType = freshSeenByType;
		currentNode.totalsByType = totalsByType;
		currentNode.isExpanded = true;
		if (res.errorRetrievingChildren) currentNode.errorRetrievingChildren = true;
		return {
			currentCriticalPathNode,
			criticalPathBroken,
			survivingAncestor,
			criticalPathList
		};
	}, [
		catalogObjects,
		executeQueryAdHoc,
		promotedEntities
	]);
	const doesRootExist = useCallback(async (displayTree, workingTree, isPreloadedRoot) => {
		const rootEntityType = displayTree?.properties?.catalogReturnObject;
		const rootApiMethodId = workingTree?.apiMethodInstance?.apiMethodId;
		if (displayTree?.isGroupNode || !rootEntityType || !rootApiMethodId || isPreloadedRoot) return true;
		const rootPk = getSearchIdentifiers(catalogObjects, rootEntityType)?.[0];
		const rootPkValue = rootPk ? displayTree?.nodeObj?.[rootPk] : null;
		if (!rootPk || rootPkValue == null) return true;
		return !!(await executeQueryAdHoc({ data: getSearchObject([{
			searchField: rootPk.charAt(0).toUpperCase() + rootPk.slice(1),
			searchValue: rootPkValue,
			searchOperator: "="
		}], 1, 1) }, rootApiMethodId).catch(() => null))?.data?.pageList?.length;
	}, [catalogObjects, executeQueryAdHoc]);
	const buildLazyDisplayTree = useCallback(async () => {
		const expandedKeys = expandedStateRef.current[selectedMenuIndex] ?? /* @__PURE__ */ new Map();
		const displayTree = cloneDeep(selectedTree);
		const workingTree = selectedTree.associatedInquiryTree ?? tree;
		if (!await doesRootExist(displayTree, workingTree, !!tree?.isPreloaded)) return {
			displayTree: null,
			survivingAncestor: null,
			rootDeleted: true
		};
		const criticalPathList = getCriticalPath(selectedNode);
		const queue = Array.isArray(displayTree) ? [...displayTree] : [displayTree];
		let pathContext = {
			currentCriticalPathNode: criticalPathList.pop(),
			criticalPathBroken: false,
			survivingAncestor: null,
			criticalPathList
		};
		while (queue.length) {
			const currentNode = queue.shift();
			if (!currentNode) continue;
			const key = getKeyIdentifier(currentNode);
			if (key && expandedKeys.get(key) && currentNode.properties?.lazyLoad) pathContext = await fetchAndMergeLazyNode(currentNode, workingTree, pathContext);
			currentNode.children?.forEach((child) => queue.push(child));
		}
		return {
			displayTree,
			survivingAncestor: pathContext.survivingAncestor,
			rootDeleted: false,
			criticalPathNode: pathContext.criticalPathNode
		};
	}, [
		doesRootExist,
		fetchAndMergeLazyNode,
		getCriticalPath,
		selectedMenuIndex,
		selectedNode,
		selectedTree,
		tree
	]);
	const handleMenuTreesRefreshFromPage = useCallback(async (updateAllPreloadedTreesOrMutationInfo = false) => {
		const updateAllPreloadedTrees = updateAllPreloadedTreesOrMutationInfo === true;
		if (!selectedNode || !selectedTree) return;
		setRefreshing(true);
		const { associatedInquiryTree } = selectedTree;
		let selectedNodeIndex = -1;
		const workingTree = associatedInquiryTree ?? tree;
		const expandedKeys = expandedStateRef.current[selectedMenuIndex] ?? /* @__PURE__ */ new Map();
		if (selectedTree.children.length > 0) selectedNodeIndex = selectedTree.children.indexOf(selectedNode);
		let displayTree = null;
		let survivingAncestor = null;
		let rootDeleted = false;
		let criticalPathNode = null;
		if (!hasLazyLevelInStructure) displayTree = await fetchAndBuildDisplayTree();
		else {
			const res = await buildLazyDisplayTree();
			displayTree = res.displayTree;
			survivingAncestor = res.survivingAncestor;
			rootDeleted = res.rootDeleted;
			criticalPathNode = res.criticalPathNode;
		}
		if (rootDeleted) {
			setMenuList((prevState) => {
				const updated = prevState.slice();
				updated.splice(selectedMenuIndex, 1);
				return updated;
			});
			setSelectedNode(null);
			setActionPanels([], containerId);
			setRefreshing(false);
			return;
		}
		restoreExpandedState(displayTree, expandedKeys);
		if (selectedTree.isGroupNode && selectedTree.children.length > 0) displayTree.forEach((childNode) => {
			childNode.parentGroupId = selectedTree.id;
			childNode.parentId = selectedTree.id;
			childNode.parentGroupName = selectedTree.properties.label;
		});
		const currentSelectedTree = displayTree;
		const selectedNodeSearchIdentifier = selectedNode.properties.searchIdentifier || "";
		setMenuList((prevState) => {
			const updatedMenuList = prevState.slice();
			if (updateAllPreloadedTrees && workingTree?.isPreloaded) updatedMenuList.forEach((menuItem) => {
				const newGroupId = v4();
				menuItem.id = newGroupId;
				menuItem.children?.forEach((childNode) => {
					childNode.parentGroupId = newGroupId;
					childNode.parentId = newGroupId;
				});
			});
			if (selectedTree.isGroupNode) {
				if (selectedTree.children.length > 0 && Array.isArray(displayTree)) updatedMenuList[selectedMenuIndex].children = displayTree;
				if (!updateAllPreloadedTrees) {
					const newGroupId = v4();
					updatedMenuList[selectedMenuIndex].id = newGroupId;
					updatedMenuList[selectedMenuIndex]?.children?.forEach((childNode) => {
						childNode.parentGroupId = newGroupId;
						childNode.parentId = newGroupId;
					});
				}
			} else if (!selectedTree.isGroupNode) updatedMenuList[selectedMenuIndex] = displayTree;
			return updatedMenuList;
		});
		if (survivingAncestor) {
			setSelectedNode(survivingAncestor);
			setActionPanels(survivingAncestor.properties?.panels, containerId);
		} else if (criticalPathNode) setSelectedNode(criticalPathNode);
		else if (selectedNodeSearchIdentifier) {
			let tree = currentSelectedTree;
			if (selectedTree.isGroupNode && selectedNodeIndex >= 0) tree = currentSelectedTree[selectedNodeIndex];
			const matchingNode = findNodeByBusinessObjectKey(tree, selectedNode.nodeObj?.businessObjectKey)?.node;
			setActionPanels(matchingNode?.properties.panels, containerId);
			setSelectedNode(matchingNode);
		} else if (selectedTree.isGroupNode && selectedNodeIndex >= 0) setSelectedNode(displayTree[selectedNodeIndex]);
		else setSelectedNode(selectedNode);
		setRefreshing(false);
	}, [
		selectedNode,
		selectedTree,
		tree,
		selectedMenuIndex,
		hasLazyLevelInStructure,
		restoreExpandedState,
		fetchAndBuildDisplayTree,
		buildLazyDisplayTree,
		setActionPanels,
		containerId
	]);
	const executeApiForDroppedNode = useCallback(async (value) => {
		setExecuteApiProgress(true);
		const { sourceNodeMenuIndex, targetNodeMenuIndex, ...apiData } = executeApiData;
		if ((await executeQueryWithParameters({ data: { requestBody: { ...apiData } } }, value?.apiMethod?.apiMethodId).catch((res) => {
			console.error(res);
		}))?.status === 200) {
			const menuIndexes = [sourceNodeMenuIndex];
			if (sourceNodeMenuIndex !== targetNodeMenuIndex) menuIndexes.push(targetNodeMenuIndex);
			handleMenuTreesRefresh(menuIndexes);
		}
		setExecuteApiProgress(false);
		handleCloseExecuteApiDialog();
	}, [
		executeQueryWithParameters,
		handleCloseExecuteApiDialog,
		executeApiData,
		handleMenuTreesRefresh
	]);
	const handleDroppedNode = useCallback((sourceNode, targetNode, sourceNodeMenuIndex, targetNodeMenuIndex) => {
		const sourceNodeCatalogReturnObject = sourceNode?.properties?.catalogReturnObject;
		const targetNodeCatalogReturnObject = targetNode?.properties?.catalogReturnObject;
		const targetNodeActions = targetNode?.properties?.nodeActions || [];
		const loadPageNodeActions = targetNodeActions.filter((nodeAction) => nodeAction.triggerType === NodeActionTriggerEnums.On_Node_Drop && nodeAction.actionTypeId === NodeActionEnums.Load_Inquiry_Page);
		const executeApiNodeActions = targetNodeActions.filter((nodeAction) => nodeAction.triggerType === NodeActionTriggerEnums.On_Node_Drop && nodeAction.actionTypeId === NodeActionEnums.Execute_Api && sourceNodeCatalogReturnObject === nodeAction?.dragEntityName);
		targetNodeActions.filter((nodeAction) => nodeAction.triggerType === NodeActionTriggerEnums.On_Node_Drop && nodeAction.actionTypeId === NodeActionEnums.Start_Workflow && sourceNodeCatalogReturnObject === nodeAction?.dragEntityName);
		if (targetNodeActions.some((tna) => tna.dragEntityName === sourceNodeCatalogReturnObject && tna.actionTypeId === NodeActionEnums.Execute_Api)) handleDroppedNodeForExecuteApi(sourceNode, targetNode, executeApiNodeActions, sourceNodeCatalogReturnObject, targetNodeCatalogReturnObject, sourceNodeMenuIndex, targetNodeMenuIndex);
		if (targetNodeActions.some((tna) => tna.dragEntityName === sourceNodeCatalogReturnObject && tna.actionTypeId === NodeActionEnums.Load_Inquiry_Page)) loadPageForDroppedNode(sourceNode, targetNode, loadPageNodeActions, targetNodeCatalogReturnObject, sourceNodeCatalogReturnObject);
	}, [loadPageForDroppedNode, handleDroppedNodeForExecuteApi]);
	const handleMoveToTop = useCallback(async () => {
		if (!selectedNode) return;
		const associatedTreeId = selectedNode.properties.associatedTreeId;
		if (!associatedTreeId) return;
		setMenuLoading(true);
		setMoveToTopLoading(true);
		let associatedInquiryTree = selectedNode.properties.associatedInquiryTree;
		if (!associatedInquiryTree) {
			const detailedTreeResponse = await executeGetDetailedTree(associatedTreeId);
			if (detailedTreeResponse.status === 200) associatedInquiryTree = detailedTreeResponse.data;
		}
		const lazyLoad = !!associatedInquiryTree?.properties?.lazyLoad;
		const filterElements = selectedNode.properties.filterElements;
		const apiMethodId = associatedInquiryTree.apiMethodInstance.apiMethodId;
		const searchObject = getSearchObject(filterElements, 1, 50, !lazyLoad);
		const data = { data: searchObject };
		const loadedNodesList = [];
		const response = await executeQueryAdHoc(data, apiMethodId).catch((res) => {
			enqueueSnackbar(t(`Unable to move to top: ${res?.response?.data}`), {
				variant: "error",
				anchorOrigin: {
					vertical: "top",
					horizontal: "center"
				}
			});
		});
		if (response?.status === 200) {
			if (response?.data?.pageList?.length) {
				const updatedMenuList = menuList.slice();
				const treeStructure = makeTreeStructure(associatedInquiryTree.treeStructure, "id", "parentId");
				const displayTree = formatTreeMenuItem(response.data.pageList[0], treeStructure, catalogObjects, promotedEntities, associatedInquiryTree, lazyLoad);
				loadedNodesList.push(getLoadedNodeObject(apiMethodId, searchObject, displayTree?.properties?.nodeLabel, displayTree?.properties?.catalogReturnObject, treeStructure.id));
				if (displayTree && !Array.isArray(displayTree) && Object.keys(displayTree).length) {
					displayTree.properties.searchValue = getSearchValueString(response.data.pageList[0], displayTree?.properties?.searchIdentifier);
					if (selectedNode) {
						const updatedNodeHistory = nodeHistory.map((node) => node);
						updatedNodeHistory.push(selectedNode);
						setNodeHistory(updatedNodeHistory);
					}
					setActionPanels(displayTree?.properties.panels, containerId);
					setSelectedNode(displayTree);
					executeAddRecentlyLoadedNodes({ data: loadedNodesList });
					updatedMenuList[selectedMenuIndex] = displayTree;
					setMenuList(updatedMenuList);
				}
				setDisableMoveToTop(true);
			}
		}
		setMenuLoading(false);
		setMoveToTopLoading(false);
	}, [
		selectedNode,
		executeQueryAdHoc,
		executeGetDetailedTree,
		menuList,
		catalogObjects,
		promotedEntities,
		getLoadedNodeObject,
		setActionPanels,
		executeAddRecentlyLoadedNodes,
		selectedMenuIndex,
		nodeHistory,
		containerId,
		enqueueSnackbar,
		t
	]);
	const handleExpandAll = useCallback(async () => {
		const treeStructureArr = tree?.treeStructure || [];
		const currentMenuList = cloneDeep(menuList);
		for (const rootTree of currentMenuList) {
			if (rootTree.properties?.lazyLoad && !rootTree.completedLoadingChildren && rootTree.lazyLoadChildrenArr?.length) {
				rootTree.children = [];
				const promises = rootTree.lazyLoadChildrenArr.map((searchMethod) => executeQueryAdHoc({ data: searchMethod.data }, searchMethod.apiMethodId).catch(() => null));
				const responses = await Promise.all(promises);
				responses.forEach((response, index) => {
					const searchMethod = rootTree.lazyLoadChildrenArr[index];
					if (response?.status === 200 && response?.data?.pageList?.length) {
						const childTree = treeStructureArr.find((ts) => ts.properties.catalogReturnObject === searchMethod.catalogReturnObject);
						if (childTree) response.data.pageList.forEach((item) => {
							const displayTree = formatTreeMenuItem(item, childTree, catalogObjects, promotedEntities, null, true);
							displayTree.parentId = rootTree.id;
							rootTree.children.push(displayTree);
						});
					}
				});
				rootTree.completedLoadingChildren = true;
				rootTree.currentChildPage = 1;
				rootTree.hasMoreChildren = responses.some((response, index) => {
					const pageSize = rootTree.lazyLoadChildrenArr[index]?.pageSize || 50;
					return response?.data?.total > pageSize;
				});
			}
			expandAllNodes(rootTree, true);
		}
		setMenuList(currentMenuList);
		setExpandAllClicked(!expandAllClicked);
	}, [
		expandAllClicked,
		menuList,
		tree,
		executeQueryAdHoc,
		catalogObjects,
		promotedEntities
	]);
	const handleCollapseAll = useCallback(() => {
		setMenuList((prevState) => {
			const updatedMenuList = cloneDeep(prevState);
			updatedMenuList.forEach((tree) => {
				collapseAllNodes(tree);
			});
			return updatedMenuList;
		});
	}, []);
	const inquiryTabList = useMemo(() => {
		if (!selectedNode || !selectedNode?.properties?.tabs) return [];
		const tabList = [];
		orderBySequence(selectedNode.properties.tabs).forEach((tab) => {
			if (tab?.propertyMapping && tab?.jsonLogic) {
				if (!evaluateRule(mapRule(tab?.propertyMapping, tab?.jsonLogic), selectedNode.nodeObj, null, false)) return;
			}
			let label = "";
			if (tab?.displayName && tab?.displayName.trim()) label = tab?.displayName.trim();
			else if (tab?.page?.name && tab?.page?.name.trim()) label = tab?.page?.name.trim();
			const page = {
				label,
				icon: null,
				pageId: tab?.page?.pageId || null,
				trees: tab?.trees || [],
				requiredFieldMapping: tab?.requiredFieldMapping || {},
				queryId: tab?.queryId || "",
				queryParamMapping: tab?.queryParamMapping || null
			};
			tabList.push(page);
		});
		setSelectedPageId(tabList[0]?.pageId);
		return tabList;
	}, [selectedNode]);
	const inquiryFluentTabList = useMemo(() => inquiryTabList.map((tab, index) => ({
		id: String(index),
		label: tab.label
	})), [inquiryTabList]);
	const inquiryWorkflowFluentTabList = useMemo(() => [{
		id: "0",
		label: t("Inquiry")
	}, {
		id: "1",
		label: t("Workflow")
	}], [t]);
	const handlePageChange = useCallback((value) => {
		if (Number.isNaN(value)) return;
		setTabValue(value);
		if (selectedPageId !== inquiryTabList[value]?.pageId) setSelectedPageId(inquiryTabList[value]?.pageId);
	}, [inquiryTabList, selectedPageId]);
	const handleFluentInquiryTabChange = useCallback((e) => {
		handlePageChange(Number(e.detail));
	}, [handlePageChange]);
	const handleLoadingSpecificNode = useCallback(async (obj) => {
		setMenuLoading(true);
		setNodesRequested([1]);
		const currentTabValue = inquiryTabList?.length ? inquiryTabList[tabValue] : null;
		let error = false;
		let errorMessage = t(`Unable to load entity`);
		if (!obj?.businessObjectKey) {
			error = true;
			errorMessage = `Unable to load entity: No Business Object Key`;
		} else if (!currentTabValue?.trees?.length) {
			error = true;
			errorMessage = `Unable to load entity: No Trees Configured for Tab`;
		}
		if (error) {
			setMenuLoading(false);
			setNodesRequested([]);
			enqueueSnackbar(errorMessage, {
				variant: "error",
				anchorOrigin: {
					vertical: "top",
					horizontal: "center"
				}
			});
			return;
		}
		const fullyQualifiedName = obj.businessObjectKey.split("|")[0];
		const sanitizedName = getSanitizedName(fullyQualifiedName);
		const catObjName = catalogObjects.find((domain) => domain.catalogObjectName === fullyQualifiedName) ? fullyQualifiedName : sanitizedName;
		const matchingTabValueTree = currentTabValue.trees.find((tabTree) => tabTree.catalogReturnObject === catObjName);
		if (!matchingTabValueTree) {
			setMenuLoading(false);
			setNodesRequested([]);
			enqueueSnackbar(t(`Unable to load entity: Incorrect tree(s) configured for Node trying to load`), {
				variant: "error",
				anchorOrigin: {
					vertical: "top",
					horizontal: "center"
				}
			});
			return;
		}
		let nodeTree = null;
		const detailedTreeResponse = await executeGetDetailedTree(matchingTabValueTree.treeId);
		if (detailedTreeResponse.status === 200) nodeTree = detailedTreeResponse.data;
		else {
			setMenuLoading(false);
			setNodesRequested([]);
			enqueueSnackbar(t(`Unable to load entity: Tree for item failed to load`), {
				variant: "error",
				anchorOrigin: {
					vertical: "top",
					horizontal: "center"
				}
			});
			return;
		}
		if (!nodeTree) {
			setMenuLoading(false);
			setNodesRequested([]);
			enqueueSnackbar(t(`Unable to load entity: Tree for item failed to load`), {
				variant: "error",
				anchorOrigin: {
					vertical: "top",
					horizontal: "center"
				}
			});
			return;
		}
		const searchIdentifiers = getSearchIdentifiers(catalogObjects, catObjName);
		const filterElements = [];
		const searchValues = [];
		searchIdentifiers.forEach((searchIdentifier) => {
			const searchField = searchIdentifier ? searchIdentifier.charAt(0).toUpperCase() + searchIdentifier.slice(1) : "";
			filterElements.push({
				searchField,
				searchOperator: "=",
				searchValue: obj[searchIdentifier] ?? ""
			});
			searchValues.push(obj[searchIdentifier]);
		});
		const apiMethodId = nodeTree.apiMethodInstance.apiMethodId;
		const lazyLoad = !!nodeTree?.properties?.lazyLoad;
		const searchResponse = await executeQueryAdHoc({ data: getSearchObject(filterElements, 1, 50, !lazyLoad) }, apiMethodId);
		if (searchResponse.status === 200) {
			if (searchResponse?.data?.pageList?.length) {
				const treeStructure = makeTreeStructure(nodeTree.treeStructure, "id", "parentId");
				const displayTree = formatTreeMenuItem(searchResponse.data.pageList[0], treeStructure, catalogObjects, promotedEntities, nodeTree, lazyLoad);
				setMenuList((prevState) => [...prevState, displayTree]);
				setNodesRequested([]);
				setMenuLoading(false);
			}
		}
	}, [
		inquiryTabList,
		tabValue,
		catalogObjects,
		enqueueSnackbar,
		t,
		executeGetDetailedTree,
		executeQueryAdHoc,
		promotedEntities
	]);
	const handleSideBarValueChange = useCallback((value) => {
		setSidebarTabValue(value);
	}, []);
	const handleAdvancedSearchClick = useCallback((values, selectedSearchOperators, entity, lookupPropertyNames) => {
		setIsAdvancedSearch(true);
		setInSearch(true);
		const foundSearchItem = searchItems.find((item) => item.catalogReturnObject === entity);
		const searchFilterElements = [];
		Object.keys(values).filter((field) => field.startsWith(`${getSanitizedName(entity)}:`)).forEach((searchField) => {
			const filterElement = {
				searchField: "",
				searchOperator: "",
				searchValue: ""
			};
			const configuredSearchField = searchField.replace(`${getSanitizedName(entity)}:`, "");
			filterElement.searchField = configuredSearchField.charAt(0).toUpperCase() + configuredSearchField.slice(1);
			filterElement.searchOperator = selectedSearchOperators && selectedSearchOperators[configuredSearchField]?.value || "=";
			if (configuredSearchField.includes(":between") || !values[searchField]) return;
			if (filterElement.searchOperator === "BETWEEN") {
				let fromValue = values[searchField] instanceof Date ? values[searchField].toISOString() : values[searchField];
				let toValue = values[`${searchField}:between`] instanceof Date ? values[`${searchField}:between`].toISOString() : values[`${searchField}:between`];
				filterElement.searchValue = `${fromValue}${toValue ? `,${toValue}` : ""}`;
			} else filterElement.searchValue = values[searchField] instanceof Date ? values[searchField].toISOString() : values[searchField];
			if (lookupPropertyNames.includes(configuredSearchField)) filterElement.searchValue = values[searchField]["value"];
			searchFilterElements.push(filterElement);
		});
		foundSearchItem.searchFilterElements = searchFilterElements;
		setAdvancedSearchItems([foundSearchItem]);
	}, [searchItems]);
	const entityList = useMemo(() => {
		if (!searchItems?.length) return [];
		return searchItems.reduce((entities, item) => {
			if (item.catalogReturnObject) entities.push({
				label: getSanitizedName(item.catalogReturnObject),
				value: item.catalogReturnObject
			});
			return entities;
		}, []);
	}, [searchItems]);
	const secondaryButtons = useMemo(() => {
		if (inSearch) return [{
			component: ClearIcon,
			label: "Clear Search",
			click: clearSearch,
			id: 1
		}];
		return [];
	}, [clearSearch, inSearch]);
	const pageHeightOffSet = useMemo(() => {
		let offset = 0;
		if (primaryExpanded) offset = offset + 180;
		if (secondaryExpanded) offset = offset + 270;
		if (selectedNode?.properties?.tabs?.length > 1) offset = offset + 44;
		return offset;
	}, [
		primaryExpanded,
		secondaryExpanded,
		selectedNode
	]);
	const onTreeViewModeChange = useCallback(() => {
		if (treeViewMode === TreeViewModeEnums.Classic) setTreeViewMode(TreeViewModeEnums.Compact);
		else if (treeViewMode === TreeViewModeEnums.Compact) setTreeViewMode(TreeViewModeEnums.Classic);
	}, [treeViewMode]);
	const selectedNodeChildren = useMemo(() => {
		if (!!!selectedNode?.children?.length) return [];
		return selectedNode?.children?.filter((child) => !(child instanceof GroupNode));
	}, [selectedNode]);
	const udpPageWidgetParams = useMemo(() => {
		const currentTabValue = inquiryTabList?.length ? inquiryTabList[tabValue] : null;
		return {
			pageId: currentTabValue?.pageId || "",
			entityName: selectedNode?.properties?.catalogReturnObject,
			contentId: selectedNode?.properties?.searchValue,
			nodeObj: selectedNode?.nodeObj,
			nodeId: selectedNode?.id,
			manytoManyNodeObjKey: selectedNode?.properties?.joiningEntityCatalogObjectKey,
			parentNodeObj: selectedNode?.parentNode?.nodeObj,
			parentGroupName: selectedNode?.parentGroupName,
			inquiryParams: selectedNode?.inquiryParams,
			inquiryNodeProperties: selectedNode?.properties,
			refreshTree: handleMenuTreesRefreshFromPage,
			loadInquiryNode: handleLoadingSpecificNode,
			requiredFieldsMap: currentTabValue?.requiredFieldMapping || {},
			displayLoadNodeButton: !!currentTabValue?.trees?.length,
			nodeChildren: selectedNodeChildren,
			catalogObjects,
			queryId: currentTabValue?.queryId,
			queryParamMapping: currentTabValue?.queryParamMapping,
			refreshNodeHeaderData: refreshNodeHeaderPageData,
			refreshPageHeaderData: refreshPageHeaderPageData,
			inquiryContainerId: containerId
		};
	}, [
		inquiryTabList,
		selectedNode,
		catalogObjects,
		handleMenuTreesRefreshFromPage,
		handleLoadingSpecificNode,
		tabValue,
		selectedNodeChildren,
		refreshNodeHeaderPageData,
		refreshPageHeaderPageData,
		containerId
	]);
	const pageWidgetParams = useMemo(() => {
		const currentTabValue = inquiryTabList?.length ? inquiryTabList[tabValue] : null;
		return {
			pageId: currentTabValue?.pageId || "",
			entityName: selectedNode?.properties?.catalogReturnObject,
			contentId: selectedNode?.properties?.searchValue,
			nodeObj: selectedNode?.nodeObj,
			nodeId: selectedNode?.id,
			manytoManyNodeObjKey: selectedNode?.properties?.joiningEntityCatalogObjectKey,
			parentNodeObj: selectedNode?.parentNode?.nodeObj,
			parentGroupName: selectedNode?.parentGroupName,
			inquiryParams: selectedNode?.inquiryParams,
			inquiryNodeProperties: selectedNode?.properties,
			heightOffset: pageHeightOffSet,
			refreshTree: handleMenuTreesRefreshFromPage,
			loadInquiryNode: handleLoadingSpecificNode,
			requiredFieldsMap: currentTabValue?.requiredFieldMapping || {},
			displayLoadNodeButton: !!currentTabValue?.trees?.length,
			nodeChildren: selectedNodeChildren,
			catalogObjects,
			queryId: currentTabValue?.queryId,
			queryParamMapping: currentTabValue?.queryParamMapping,
			refreshNodeHeaderData: refreshNodeHeaderPageData,
			refreshPageHeaderData: refreshPageHeaderPageData,
			inquiryContainerId: containerId
		};
	}, [
		inquiryTabList,
		selectedNode,
		catalogObjects,
		handleMenuTreesRefreshFromPage,
		handleLoadingSpecificNode,
		pageHeightOffSet,
		tabValue,
		selectedNodeChildren,
		refreshNodeHeaderPageData,
		refreshPageHeaderPageData,
		containerId
	]);
	const pageContainer = useMemo(() => {
		return /* @__PURE__ */ React.createElement(PageContainer, {
			user,
			key: selectedNode?.properties?.searchValue,
			pageData,
			pageLoading,
			widgetParams: pageData?.isUdpPage ? udpPageWidgetParams : pageWidgetParams,
			disableMargins: true
		});
	}, [
		user,
		pageData,
		pageLoading,
		udpPageWidgetParams,
		selectedNode,
		pageWidgetParams
	]);
	const handleSidebarExpandClick = useCallback(() => {
		setSidebarExpanded((expanded) => !expanded);
	}, []);
	useEffect(() => {
		setSubHeaderActionHasChildren(false);
	}, [setSubHeaderActionHasChildren]);
	useEffect(() => {
		clearNodes();
		clearSearch();
	}, [treeId]);
	useEffect(() => {
		if (inSearch) {
			setHeaderTitle("");
			setPrimaryExpanded(false);
			setSecondaryExpanded(false);
			setShowToggle1(false);
			setShowToggle2(false);
		} else if (!inSearch && selectedNode) {
			setHeaderTitle(selectedNode?.isGroupNode ? selectedNode.properties?.label : selectedNode.properties?.headerTitle);
			if (!selectedNode.properties?.defaultNodeHeaderExpanded || selectedNode.properties?.defaultNodeHeaderExpanded === "hidden") {
				setShowToggle1(false);
				setPrimaryExpanded(false);
			} else {
				setShowToggle1(true);
				setPrimaryExpanded(selectedNode.properties?.defaultNodeHeaderExpanded ? selectedNode.properties?.defaultNodeHeaderExpanded === "expanded" : false);
			}
			if (!selectedNode.properties?.defaultPageHeaderExpanded || selectedNode.properties?.defaultPageHeaderExpanded === "hidden") {
				setShowToggle2(false);
				setSecondaryExpanded(false);
			} else {
				setShowToggle2(true);
				setSecondaryExpanded(selectedNode.properties?.defaultPageHeaderExpanded ? selectedNode.properties?.defaultPageHeaderExpanded === "expanded" : true);
			}
		}
	}, [inSearch, selectedNode]);
	useEffect(() => {
		if (!nodeLoaded) {
			setHeaderTitle("");
			setShowToggle1(false);
			setShowToggle2(false);
			setPrimaryExpanded(false);
			setSecondaryExpanded(false);
		}
	}, [nodeLoaded]);
	useEffect(() => {
		if (!sidebarExpanded) setSidebarTabValue(0);
	}, [sidebarExpanded]);
	useEffect(() => {
		if (setPageId) if (selectedNode) if (selectedNode?.properties?.tabs?.length > 1) setPageId(selectedPageId || null);
		else {
			const pageTabs = selectedNode?.properties?.tabs;
			if (pageTabs?.[0]) setPageId(pageTabs[0].page?.pageId || null);
			else setPageId(null);
		}
		else setPageId(null);
	}, [
		setPageId,
		selectedNode,
		selectedPageId
	]);
	useEffect(() => {
		if (initialSearchValue) {
			setIsAdvancedSearch(false);
			setInSearch(true);
			setSearchValue(initialSearchValue);
		}
	}, [initialSearchValue]);
	useEffect(() => {
		setTabValue(0);
	}, [selectedNode]);
	useEffect(() => {
		if (inSearch) setShowInquiryHeaderActions(false);
		else setShowInquiryHeaderActions(true);
	}, [inSearch, setShowInquiryHeaderActions]);
	useEffect(() => {
		setInquiryParams({
			selectedNode,
			selectedNodeParent: selectedNode?.parentNode,
			refreshTree: handleMenuTreesRefresh
		}, containerId);
	}, [
		selectedNode,
		handleMenuTreesRefresh,
		setInquiryParams,
		containerId
	]);
	useEffect(() => {
		setMenuListState({
			menuList,
			handleRemoveMenuItem,
			selectedMenuIndex
		});
	}, [
		setMenuListState,
		menuList,
		handleRemoveMenuItem,
		selectedMenuIndex
	]);
	useEffect(() => {
		if (tree) {
			const getPreloadedTree = async () => {
				setMenuLoading(true);
				setNodesRequested([1]);
				const response = await executeQueryInstance({ data: {} }, tree.apiMethodInstance?.apiMethodInstanceId);
				if (response.status === 200) {
					if (response?.data?.pageList?.length) {
						const preloadedList = constructPreloadedTree(makeTreeStructure(cloneDeep(tree.treeStructure), "id", "parentId"), response.data.pageList, catalogObjects);
						setMenuList(preloadedList || []);
						if (preloadedList?.length) {
							setSelectedNode(preloadedList[0]);
							setSelectedMenuIndex(0);
						}
						setAppNavigationExpanded(false);
					}
				}
				setMenuLoading(false);
				setNodesRequested([]);
			};
			if (tree) {
				const topNode = tree?.treeStructure?.find((node) => !node.parentId);
				setInquiryTitleHeader(topNode?.properties?.inquiryTitle || "");
			}
			setIsPreloaded(tree.isPreloaded);
			if (tree.isPreloaded) {
				setNodeLoaded(true);
				getPreloadedTree();
			}
		}
	}, [
		tree,
		setAppNavigationExpanded,
		catalogObjects
	]);
	useEffect(() => {
		setSelectedNodeForStore(selectedNode || null);
	}, [selectedNode, setSelectedNodeForStore]);
	useEffect(() => {
		if (workflowPlay) setWorkflow(workflowPlay);
	}, [workflowPlay]);
	useEffect(() => {
		if (workflow) setSelectedWorkflowNode((prevNode) => {
			if (!!prevNode) {
				const foundNode = workflow.workflowPlayNode?.children?.find((child) => child.id === prevNode.id);
				if (!!foundNode) {
					const updatedNode = { ...prevNode };
					updatedNode.properties.state = foundNode.state;
					return updatedNode;
				} else return prevNode;
			}
		});
	}, [workflow]);
	useEffect(() => {
		if (workflow) {
			if (!workflowInitialized) {
				let initialized = false;
				if (workflow.workflowPlayNode?.children?.length) {
					if (workflow.workflowPlayNode.children[0].state !== UnitStateType.Initial) {
						initialized = true;
						setWorkflowInitialized(true);
					}
				}
				if (!initialized && getWorkflowInitializedCount < WORKFLOW_MAX_NETWORK_CALLS && inquiryWorkflow?.currentWorkflowPlayId) {
					const timer = setTimeout(async () => {
						await reloadWorkflow();
						setGetWorkflowInitializedCount((prevCount) => prevCount + 1);
					}, 1e3);
					return () => clearTimeout(timer);
				}
				if (getWorkflowInitializedCount === WORKFLOW_MAX_NETWORK_CALLS) enqueueSnackbar(t(`Unable to initialize workflow`), {
					variant: "error",
					anchorOrigin: {
						vertical: "top",
						horizontal: "center"
					}
				});
			}
			if (workflowInitialized) {
				const list = [];
				const updatedMenu = transformWorkflowPlayTree(workflow.workflowPlayNode);
				if (updatedMenu) list.push(updatedMenu);
				setWorkflowMenuItemsList(list);
			}
		}
	}, [
		workflow,
		workflowInitialized,
		reloadWorkflow,
		getWorkflowInitializedCount,
		inquiryWorkflow,
		enqueueSnackbar,
		t
	]);
	useEffect(() => {
		if (inquiryWorkflow?.inWorkflowMode && inquiryWorkflowTabValue === 1) setHideActions(true);
		else if (inquiryWorkflow?.inWorkflowMode && inquiryWorkflowTabValue === 0) setHideActions(false);
	}, [
		setHideActions,
		inquiryWorkflowTabValue,
		inquiryWorkflow
	]);
	useEffect(() => {
		if (!selectedWorkflowNode) {
			const menu = workflowMenuItemsList[0];
			if (menu) {
				const firstSelectableMenuItem = menu?.children?.find((item) => item.isSelectable);
				setSelectedWorkflowNode(firstSelectableMenuItem || null);
				if (autoCollapseNav) setNavigationExpanded(false);
			}
		}
	}, [
		workflowMenuItemsList,
		selectedWorkflowNode,
		setNavigationExpanded,
		autoCollapseNav
	]);
	useEffect(() => {
		if (!!workflowPlayError && getWorkflowPlayErrorCount < WORKFLOW_MAX_NETWORK_CALLS && inquiryWorkflow?.currentWorkflowPlayId) {
			const timer = setTimeout(() => {
				reloadWorkflow();
				setGetWorkflowPlayErrorCount((prevCount) => prevCount + 1);
			}, 1e3);
			return () => clearTimeout(timer);
		}
		if (getWorkflowPlayErrorCount === WORKFLOW_MAX_NETWORK_CALLS) enqueueSnackbar(t(`Unable to load workflow`), {
			variant: "error",
			anchorOrigin: {
				vertical: "top",
				horizontal: "center"
			}
		});
	}, [
		workflowPlayError,
		reloadWorkflow,
		getWorkflowPlayErrorCount,
		enqueueSnackbar,
		t,
		inquiryWorkflow
	]);
	useEffect(() => {
		setLocationState({ label: t(inquiryTitle) || t("Inquiry") });
	}, [
		setLocationState,
		t,
		inquiryTitle
	]);
	return /* @__PURE__ */ React.createElement(DndProvider, { backend: HTML5Backend }, /* @__PURE__ */ React.createElement(LoadingOverlay, { open: workflowStarting }), /* @__PURE__ */ React.createElement("div", {
		key: treeId,
		className: classes.root
	}, !inquiryMenuHidden && /* @__PURE__ */ React.createElement(UtilitySideBar, {
		title: t(inquiryTitle) || t("Inquiry"),
		isUsingChildren: true,
		resizable: true,
		removePadding: true,
		removeTopLayoutUnit: true,
		onUtilitySidebarToggleExpandClick: handleSidebarExpandClick,
		collapsedWidth: 78,
		handleResize: (width) => setUtilitySideBarWidth(width),
		hideTitleBar: inquiryWorkflow?.inWorkflowMode
	}, (moveToTopLoading || dragAndDropLoading || refreshing) && /* @__PURE__ */ React.createElement(LinearProgress, null), sidebarTabValue === 0 && /* @__PURE__ */ React.createElement(React.Fragment, null, inquiryWorkflow?.inWorkflowMode && /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement("div", { className: classes.workflowTablist }, /* @__PURE__ */ React.createElement(UdpTablist, {
		activeId: String(inquiryWorkflowTabValue),
		tabList: inquiryWorkflowFluentTabList,
		onTabChange: (e) => setInquiryWorkflowTabValue(Number(e.detail))
	})), /* @__PURE__ */ React.createElement(Divider, null)), (!inquiryWorkflow?.inWorkflowMode || inquiryWorkflow?.inWorkflowMode && inquiryWorkflowTabValue === 0) && /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement(InquiryNodeControls, {
		remove: () => handleRemoveMenuItem(null),
		moveToTop: handleMoveToTop,
		expandAll: handleExpandAll,
		collapseAll: handleCollapseAll,
		clearAll: clearNodes,
		switchTreeViewMode: onTreeViewModeChange,
		treeViewMode,
		changeSideBarView: handleSideBarValueChange,
		handleKeyDown: handleSearch,
		disableMoveToTop,
		entityList,
		entityValue,
		setEntityValue,
		hiddenControls: sidebarExpanded ? isPreloaded ? ["remove", "clearAll"] : [] : isPreloaded ? [
			"remove",
			"expandAll",
			"clearAll",
			"collapseAll"
		] : [
			"remove",
			"expandAll",
			"clearAll",
			"collapseAll"
		],
		showControls: !treeLoading && !treeError && nodeLoaded,
		showSearch: !treeLoading && !treeError,
		defaultValue: initialSearchValue,
		clearSearchStr,
		setClearSearchStr,
		isPreloadedTree: isPreloaded,
		treeLoading
	}, !treeLoading && treeError && /* @__PURE__ */ React.createElement("div", { style: {
		marginLeft: 4,
		marginBottom: 12
	} }, /* @__PURE__ */ React.createElement(LayoutUnit, { unit: "nudge" }), /* @__PURE__ */ React.createElement(Typography, null, "Error getting tree data from tree id"))), /* @__PURE__ */ React.createElement(NodeList, {
		menuItemsList: menuList,
		onSelectNode: handleSelectedNode,
		onDropNode: handleDroppedNode,
		selectedNodeId: selectedNode?.id ?? "",
		selectedNodeParentId: selectedNode?.parentId ?? "",
		expandAllClicked,
		classes: { root: !treeLoading ? nodeLoaded ? classes.nodeListRootLoaded : classes.nodeListRoot : classes.nodeListRootLoading },
		menuLoading,
		nodesRequested,
		sidebarExpanded,
		executeQueryAdHoc,
		catalogObjects,
		promotedEntities,
		treeStructureArr: tree?.treeStructure || [],
		setMenuList,
		treeViewMode: treeViewMode || TreeViewModeEnums.Classic,
		onExpandedChange: handleExpandedChange
	}))), sidebarTabValue === 1 && /* @__PURE__ */ React.createElement(InquiryAdvancedSearch, {
		entityList,
		entityValue: advancedSearchEntityValue,
		setEntityValue: setAdvancedSearchEntityValue,
		onSubmit: handleAdvancedSearchClick,
		currentNodeCatalogReturnObject: selectedNode?.properties?.catalogReturnObject,
		changeSideBarView: handleSideBarValueChange,
		catalogObjects,
		tree,
		executeQueryWithParameters
	}), inquiryWorkflow?.inWorkflowMode && inquiryWorkflowTabValue === 1 && /* @__PURE__ */ React.createElement("div", {
		className: classes.workflowMenuContent,
		key: inquiryWorkflow?.currentWorkflowPlayId
	}, workflowMenuItemsList?.length > 0 && (!workflowPlayLoading || reloadWorkflowFromPage) && workflowMenuItemsList.map((workflowMenuItems, index) => /* @__PURE__ */ React.createElement("div", {
		key: workflowMenuItems.id,
		className: classes.nodeContainer
	}, /* @__PURE__ */ React.createElement(WorkflowTreeMenu, {
		menuItems: workflowMenuItems,
		onSelectNode: handleSelectedWorkflowNode,
		menuIndex: index,
		selectedNodeId: selectedWorkflowNode?.id,
		selectedNodeParentId: selectedWorkflowNode?.parentId,
		sidebarExpanded,
		treeViewMode: TreeViewModeEnums.Classic
	}))), (workflowPlayLoading || workflowPlayError || !workflowInitialized) && !reloadWorkflowFromPage && /* @__PURE__ */ React.createElement("div", { className: classes.workflowTreeLoader }, /* @__PURE__ */ React.createElement(NodeLoader, { loading: workflowPlayLoading || workflowPlayError || !workflowInitialized })))), /* @__PURE__ */ React.createElement(OpenPage, {
		disableGutters: true,
		style: {
			position: "relative",
			top: 0,
			width: `calc(100% - ${utilitySideBarWidth}px)`
		}
	}, /* @__PURE__ */ React.createElement(Form, {
		onSubmit: executeApiForDroppedNode,
		key: promotedMethodsToExecute
	}, /* @__PURE__ */ React.createElement(ExecuteApiDialog, {
		open: executeApiDialogOpen,
		handleCloseDialog: handleCloseExecuteApiDialog,
		apiMethods: promotedMethodsToExecute,
		progress: executeApiProgress
	})), /* @__PURE__ */ React.createElement("div", { className: classes.content }, (!inquiryWorkflow?.inWorkflowMode || inquiryWorkflow?.inWorkflowMode && inquiryWorkflowTabValue === 0) && /* @__PURE__ */ React.createElement(InquiryWrapper, {
		nodeLoaded: false,
		collapsedWidth: 32
	}, (inSearch || nodeLoaded) && /* @__PURE__ */ React.createElement(Card, { square: true }, /* @__PURE__ */ React.createElement(PrimaryActionHeader, {
		key: `${selectedNode?.id}-${inSearch}`,
		title: headerTitle,
		buttonLabel: "Load",
		single: true,
		secondaryButtons,
		handleClick: handlePrimaryAction,
		hidePAB: nodeLoaded && !inSearch,
		allowAdditionalTitleComponent: true,
		additionalComponentId: containerId
	})), !!selectedNode && /* @__PURE__ */ React.createElement(Card, {
		square: true,
		className: classes.nodeHeader
	}, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement(Collapse, {
		in: primaryExpanded,
		timeout: "auto"
	}, nodeHeaderPageIdToLoad && showToggle1 ? /* @__PURE__ */ React.createElement(PageContainer, {
		user,
		key: nodeHeaderPageIdToLoad,
		pageData: nodeHeaderPageData,
		pageLoading: nodeHeaderPageLoading,
		widgetParams: {
			nodeObj: selectedNode?.nodeObj,
			nodeId: selectedNode?.id,
			selectedNode,
			setRefreshNodeHeaderPageData,
			inquiryContainerId: containerId
		},
		disableMargins: true,
		loadingHeight: 32,
		autoHeight: true
	}) : /* @__PURE__ */ React.createElement(NodeDetails, { node: selectedNode })), showToggle1 && /* @__PURE__ */ React.createElement("div", { className: clsx(primaryExpanded ? classes.chevronButtons : classes.chevronButtonClosed) }, /* @__PURE__ */ React.createElement(FluentIconButton, {
		onClick: () => setPrimaryExpanded(!primaryExpanded),
		icon: primaryExpanded ? ChevronUpIcon : ChevronDownIcon
	}))), /* @__PURE__ */ React.createElement(Divider, null), /* @__PURE__ */ React.createElement(Collapse, {
		in: secondaryExpanded,
		timeout: "auto"
	}, /* @__PURE__ */ React.createElement("div", { className: classes.inquiryHeader }, pageHeaderPageIdToLoad && showToggle2 ? /* @__PURE__ */ React.createElement(PageContainer, {
		user,
		key: pageHeaderPageIdToLoad,
		pageData: pageHeaderPageData,
		pageLoading: pageHeaderPageLoading,
		widgetParams: {
			nodeObj: selectedNode?.nodeObj,
			nodeId: selectedNode?.id,
			selectedNode,
			setRefreshPageHeaderPageData,
			inquiryContainerId: containerId
		},
		disableMargins: true,
		loadingHeight: 32,
		autoHeight: true
	}) : /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement(InquiryHeaderSecondaryTarget, { className: classes.actions }), /* @__PURE__ */ React.createElement(InquiryHeaderSecondaryAlertTarget, { className: classes.actions })))), selectedNode?.properties?.tabs?.length > 1 && !inSearch ? /* @__PURE__ */ React.createElement("div", { className: classes.tabRoot }, /* @__PURE__ */ React.createElement(UdpTablist, {
		activeId: tabValue,
		tabList: inquiryFluentTabList,
		onTabChange: handleFluentInquiryTabChange
	})) : null), !!selectedNode && showToggle2 && /* @__PURE__ */ React.createElement(Card, {
		square: true,
		className: classes.entityHeader
	}, /* @__PURE__ */ React.createElement("div", { className: classes.chevronButtons }, /* @__PURE__ */ React.createElement(FluentIconButton, {
		onClick: () => setSecondaryExpanded(!secondaryExpanded),
		icon: secondaryExpanded ? ChevronUpIcon : ChevronDownIcon,
		className: classes.icon
	}))), !treeError && /* @__PURE__ */ React.createElement(PageActionWrapper, {
		forPageContainer: true,
		splitScreenStateKey: "pageContainerSplitScreen"
	}, /* @__PURE__ */ React.createElement("div", {
		className: classes.mainWrapper,
		style: { width: "100%" }
	}, inSearch ? /* @__PURE__ */ React.createElement(InquirySearchContainer, {
		searchItems: entitySearchItems,
		isAdvancedSearch,
		advancedSearchItems,
		setSelectedSearchRows: handleSelectedSearchRows,
		catalogObjects,
		loadSingleNode: handleSingleNodeLoad,
		onRowDoubleClick: handleRowDoubleClick,
		classes: { root: classes.searchContainerRoot },
		executeQueryAdHoc,
		apiMethodInstanceId: tree?.apiMethodInstance?.apiMethodInstanceId
	}) : !tree || !catalogObjects ? /* @__PURE__ */ React.createElement(LinearProgress, null) : !nodeLoaded && !tree?.isPreloaded ? tree?.explorePageId ? /* @__PURE__ */ React.createElement(PageContainer, {
		user,
		key: selectedNode?.properties?.searchValue,
		pageData: explorePageData,
		pageLoading: explorePageLoading,
		widgetParams: {
			tree,
			recentlyLoadedNodes: litnHistory,
			loading: litnHistoryLoading,
			onLoadedNodeClick: handleRecentlyLoadedNodeClick,
			tableHeight: "calc(100vh - 172px)",
			catalogObjects
		},
		disableMargins: true
	}) : /* @__PURE__ */ React.createElement(InquiryDashboard, {
		treeId,
		recentlyLoadedNodeOnClick: handleRecentlyLoadedNodeClick
	}, /* @__PURE__ */ React.createElement(RecentlyLoadedNodesTable, {
		recentlyLoadedNodes: litnHistory,
		loading: litnHistoryLoading,
		onLoadedNodeClick: handleRecentlyLoadedNodeClick,
		tableHeight: "calc(100vh - 172px)",
		tree
	})) : selectedNode?.properties?.tabs?.length > 0 && (selectedNode?.properties?.tabs?.length > 1 ? pageId && pageContainer : pageId ? pageContainer : null))), /* @__PURE__ */ React.createElement(InquiryHeaderSecondary, { secondExtended: true }, /* @__PURE__ */ React.createElement("div", { className: classes.information }, /* @__PURE__ */ React.createElement("div", { className: classes.summaryCard })))), inquiryWorkflow?.inWorkflowMode && inquiryWorkflowTabValue === 1 && /* @__PURE__ */ React.createElement(WorkflowContent, {
		selectedNode: selectedWorkflowNode,
		workflow,
		reloadWorkflow: handleReloadWorkflow,
		users,
		groups,
		handleClose: handleCloseWorkflow,
		inquiryPageParams: pageData?.isUdpPage ? udpPageWidgetParams : pageWidgetParams
	})))));
};
InquiryContainer.propTypes = {
	user: PropTypes.object,
	litnHistory: PropTypes.array,
	litnHistoryLoading: PropTypes.bool,
	tree: PropTypes.object,
	treeId: PropTypes.string,
	catalogObjects: PropTypes.array,
	executeQueryAdHoc: PropTypes.func,
	executeQueryWithParameters: PropTypes.func,
	executeGetDetailedTree: PropTypes.func,
	executeAddRecentlyLoadedNodes: PropTypes.func,
	treeLoading: PropTypes.bool,
	treeError: PropTypes.object,
	pageData: PropTypes.object,
	pageLoading: PropTypes.bool,
	pageError: PropTypes.object,
	setPageId: PropTypes.func,
	pageId: PropTypes.string,
	isValidWidget: PropTypes.func,
	productId: PropTypes.string,
	initialSearchValue: PropTypes.string,
	promotedEntities: PropTypes.array,
	apiCatalogId: PropTypes.string
};
//#endregion
export { InquiryContainer };

//# sourceMappingURL=InquiryContainer.mjs.map