/**
 * Copyright IBM Corp. 2020, 2026
 *
 * This source code is licensed under the Apache-2.0 license found in the
 * LICENSE file in the root directory of this source tree.
 */

import { __toESM } from "../../../_virtual/_rolldown/runtime.js";
import { require_classnames } from "../../../node_modules/classnames/index.js";
import uuidv4 from "../../../global/js/utils/uuidv4.js";
import { HIERARCHICAL_VARIANT, NON_HIERARCHICAL_VARIANT, blockClass, focusThisField, manageTabIndexAndFocus } from "../utils/util.js";
import { ConditionBuilderContext, getEmptyState } from "../ConditionBuilderContext/ConditionBuilderProvider.js";
import { useTranslations } from "../utils/useTranslations.js";
import { ConditionBuilderItem } from "../ConditionBuilderItem/ConditionBuilderItem.js";
import { ItemOption } from "../ConditionBuilderItem/ConditionBuilderItemOption/ItemOption.js";
import { useDataConfigs } from "../utils/useDataConfigs.js";
import ConditionConnector from "../ConditionBuilderConnector/ConditionConnector.js";
import ConditionBlock from "../ConditionBlock/ConditionBlock.js";
import ConditionPreview from "../ConditionPreview/ConditionPreview.js";
import React, { Fragment, useContext, useEffect, useRef, useState } from "react";
import PropTypes from "prop-types";

//#region src/components/ConditionBuilder/ConditionGroupBuilder/ConditionGroupBuilder.tsx
/**
* Copyright IBM Corp. 2024
*
* This source code is licensed under the Apache-2.0 license found in the
* LICENSE file in the root directory of this source tree.
*/
var import_classnames = /* @__PURE__ */ __toESM(require_classnames());
const ConditionGroupBuilder = ({ group, aria, onRemove, onChange, className }) => {
	const [conditionBuilderGroupText, conditionText, conditionBuilderText] = useTranslations([
		"conditionBuilderGroupText",
		"conditionText",
		"conditionBuilderText"
	]);
	const { statementConfig } = useDataConfigs();
	const { variant, conditionBuilderRef, statementConfigCustom } = useContext(ConditionBuilderContext);
	const [showConditionPreview, setShowConditionPreview] = useState(-1);
	const [showConditionSubGroupPreview, setShowConditionSubGroupPreview] = useState(-1);
	useState(false);
	const conditionBuilderContentRef = useRef(null);
	const scrollParentRef = useRef(null);
	useEffect(() => {
		if (typeof conditionBuilderRef !== "function" && conditionBuilderRef?.current) scrollParentRef.current = getScrollableParent(conditionBuilderRef.current);
	}, [conditionBuilderRef]);
	useEffect(() => {
		const parent = scrollParentRef.current;
		let atBottom = false;
		if (parent instanceof Window || parent === document.body || parent === document.documentElement) atBottom = window.innerHeight + window.scrollY >= document.body.scrollHeight;
		else if (scrollParentRef.current) {
			const parent = scrollParentRef.current;
			atBottom = parent.scrollTop + parent.clientHeight >= parent.scrollHeight;
		}
		if ((showConditionPreview || showConditionSubGroupPreview) && atBottom) scrollParentRef.current?.scrollBy(0, -1);
	}, [showConditionPreview, showConditionSubGroupPreview]);
	const getScrollableParent = (element) => {
		while (element && element !== document.body) {
			const overflowY = getComputedStyle(element).overflowY;
			if ((overflowY === "auto" || overflowY === "scroll" || overflowY === "overlay") && element.scrollHeight > element.clientHeight) return element;
			element = element.parentElement;
		}
		return window;
	};
	const onRemoveHandler = (conditionId, evt, conditionIndex) => {
		if (group && group.conditions && group.conditions.length > 1) {
			if (variant == HIERARCHICAL_VARIANT) handleFocusOnCloseHierarchical(evt);
			else handleFocusOnClose(evt, conditionIndex);
			if (!checkGroupHaveCondition(group.conditions, conditionId)) {
				const allConditions = group?.conditions?.reduce((acc, condition) => {
					const _condition = condition;
					if (_condition.conditions) return acc.concat(_condition.conditions);
					return acc;
				}, []);
				onChange?.({
					...group,
					conditions: allConditions
				});
			} else {
				const filteredConditions = group.conditions.filter((condition) => conditionId !== condition.id);
				if ((filteredConditions?.[0]).conditions) {
					const firstFilteredConditions = filteredConditions[0];
					filteredConditions.splice(0, 1, ...firstFilteredConditions?.conditions);
				}
				onChange?.({
					...group,
					conditions: filteredConditions
				});
			}
		} else onRemove?.(evt);
	};
	const checkGroupHaveCondition = (conditions, conditionId) => {
		return conditions.find((eachCondition) => {
			return !eachCondition.conditions && eachCondition.id !== conditionId;
		});
	};
	const onChangeHandler = (updatedCondition, conditionIndex) => {
		const updatedConditions = [
			...group?.conditions ? group.conditions.slice(0, conditionIndex) : [],
			updatedCondition,
			...group?.conditions ? group.conditions.slice(conditionIndex + 1) : []
		];
		onChange?.({
			...group,
			conditions: updatedConditions,
			id: group?.id ?? uuidv4()
		});
	};
	const addConditionHandler = (conditionIndex) => {
		const newCondition = {
			property: void 0,
			operator: "",
			value: "",
			popoverToOpen: "propertyField",
			id: uuidv4()
		};
		onChange?.({
			...group,
			conditions: [
				...group.conditions ? group.conditions.slice(0, conditionIndex + 1) : [],
				newCondition,
				...group.conditions ? group.conditions.slice(conditionIndex + 1) : []
			]
		});
	};
	const handleFocusOnClose = (e, conditionIndex) => {
		const currentGroupCloseButtons = e.currentTarget.closest(`.${blockClass}__group`)?.querySelectorAll("[data-name=\"closeCondition\"]");
		if (conditionIndex == currentGroupCloseButtons.length - 1) manageTabIndexAndFocus(currentGroupCloseButtons[conditionIndex - 1], conditionBuilderRef);
		else manageTabIndexAndFocus(currentGroupCloseButtons[conditionIndex + 1], conditionBuilderRef);
	};
	const handleFocusOnCloseHierarchical = (evt) => {
		const currentLevel = evt.currentTarget?.closest("[role=\"row\"]")?.getAttribute("aria-level");
		const currentPos = evt.currentTarget?.closest("[role=\"row\"]")?.getAttribute("aria-posinset");
		const nextElement = conditionBuilderContentRef.current?.querySelector(`[aria-level="${currentLevel}"][aria-posinset="${Number(currentPos) + 1}"]`);
		const prevElement = conditionBuilderContentRef.current?.querySelector(`[aria-level="${currentLevel}"][aria-posinset="${Number(currentPos) - 1}"]`);
		if (nextElement?.classList.contains(`${blockClass}__condition-block`)) manageTabIndexAndFocus(nextElement?.querySelector("[data-name=\"closeCondition\"]"), conditionBuilderRef);
		else if (prevElement?.classList.contains(`${blockClass}__condition-block`)) manageTabIndexAndFocus(prevElement?.querySelector("[data-name=\"closeCondition\"]"), conditionBuilderRef);
		else {
			const prevRows = conditionBuilderContentRef.current?.querySelectorAll(`[aria-level="${Number(currentLevel) - 1}"][role="row"]`);
			const nextRow = conditionBuilderContentRef.current?.querySelector(`[aria-level="${Number(currentLevel) + 1}"][role="row"]`);
			if (nextRow) {
				const rowIdentity = {
					ariaLevel: Number(nextRow.ariaLevel) - 1,
					ariaPosInSet: nextRow.ariaPosInSet
				};
				setTimeout(() => {
					const currentRowToFocus = conditionBuilderContentRef.current?.querySelector(`[role="row"][aria-level="${rowIdentity.ariaLevel}"][aria-posinset="${rowIdentity.ariaPosInSet}"]`);
					manageTabIndexAndFocus(currentRowToFocus?.querySelector("[data-name=\"closeCondition\"]"), conditionBuilderRef);
				}, 0);
			} else if (prevRows?.length && prevRows.length > 1) manageTabIndexAndFocus(prevRows[prevRows.length - 2]?.querySelector("[data-name=\"closeCondition\"]"), conditionBuilderRef);
		}
	};
	const addConditionSubGroupHandler = (conditionIndex) => {
		const newSubGroup = getEmptyState(statementConfigCustom).groups?.[0];
		onChange({
			...group,
			conditions: [
				...group.conditions ? group.conditions.slice(0, conditionIndex + 1) : [],
				newSubGroup,
				...group.conditions ? group.conditions.slice(conditionIndex + 1) : []
			]
		});
	};
	const isLastCondition = (conditionIndex, conditionArr) => {
		return conditionIndex + 1 >= conditionArr.length || conditionArr.length - 1 != conditionIndex && conditionArr[conditionIndex + 1].conditions;
	};
	const showConditionSubGroupPreviewHandler = (conditionIndex) => {
		setShowConditionSubGroupPreview(conditionIndex);
	};
	const hideConditionSubGroupPreviewHandler = () => {
		setShowConditionSubGroupPreview(-1);
	};
	const showConditionPreviewHandler = (conditionIndex) => {
		setShowConditionPreview(conditionIndex);
	};
	const hideConditionPreviewHandler = () => {
		setShowConditionPreview(-1);
	};
	const onStatementChangeHandler = (updatedStatement) => {
		const groupOperator = statementConfig.find((statement) => statement.id == updatedStatement)?.connector;
		onChange({
			...group,
			groupOperator,
			statement: updatedStatement
		});
	};
	const onConnectorOperatorChange = (op) => {
		onChange({
			...group,
			groupOperator: op
		});
	};
	const getNonHierarchicalVariant = () => {
		return /* @__PURE__ */ React.createElement("div", { className: `${className}  eachGroup` }, /* @__PURE__ */ React.createElement("div", {
			className: `${blockClass}__condition-wrapper`,
			role: "grid",
			"aria-label": conditionBuilderText
		}, group?.conditions?.map((eachCondition, conditionIndex) => /* @__PURE__ */ React.createElement("div", {
			key: eachCondition.id,
			className: `${blockClass}__group-wrapper`
		}, /* @__PURE__ */ React.createElement(ConditionBlock, {
			conjunction: conditionIndex > 0 ? group.groupOperator : void 0,
			aria: {
				level: aria.level + 1,
				posinset: conditionIndex + 1,
				setsize: group?.conditions?.length
			},
			isStatement: conditionIndex == 0,
			condition: eachCondition,
			group,
			conditionIndex,
			onChange: (updatedConditions) => {
				onChangeHandler(updatedConditions, conditionIndex);
			},
			addConditionHandler,
			onRemove: (e) => {
				onRemoveHandler(eachCondition.id, e, conditionIndex);
			},
			onConnectorOperatorChange,
			onStatementChange: onStatementChangeHandler,
			isLastCondition
		})))));
	};
	const getHierarchicalVariant = () => {
		return /* @__PURE__ */ React.createElement("div", {
			className: `${className} ${blockClass}__condition-wrapper`,
			role: aria.level === 1 ? "rowgroup" : void 0,
			"aria-label": aria.level == 1 ? conditionBuilderGroupText : void 0,
			ref: conditionBuilderContentRef
		}, /* @__PURE__ */ React.createElement("div", {
			tabIndex: 0,
			role: "row",
			"aria-level": aria.level,
			"aria-posinset": aria.posinset,
			"aria-setsize": aria.setsize
		}, /* @__PURE__ */ React.createElement(ConditionBuilderItem, {
			label: group.statement,
			title: conditionText,
			"data-name": "connectorField",
			popOverClassName: `${blockClass}__gap ${blockClass}__connector`,
			className: `${blockClass}__statement-button`
		}, /* @__PURE__ */ React.createElement(ItemOption, {
			conditionState: {
				value: group.statement,
				label: conditionText
			},
			onChange: (v, evt) => {
				focusThisField(evt, conditionBuilderRef);
				onStatementChangeHandler(v);
			},
			config: {
				options: statementConfig,
				isStatement: true
			}
		}))), group?.conditions?.map((eachCondition, conditionIndex) => /* @__PURE__ */ React.createElement(Fragment, { key: eachCondition.id }, eachCondition.conditions ? /* @__PURE__ */ React.createElement("div", { className: (0, import_classnames.default)(`${blockClass}__condition-block subgroup  ${blockClass}__gap`, { [`${blockClass}__gap-bottom`]: group && group.conditions && group.conditions.length < conditionIndex + 1 }, {}) }, /* @__PURE__ */ React.createElement(ConditionConnector, {
			className: `${blockClass}__gap ${blockClass}__gap-bottom ${blockClass}__groupConnector`,
			operator: group.groupOperator,
			"aria-hidden": true
		}), /* @__PURE__ */ React.createElement(ConditionGroupBuilder, {
			aria: {
				level: aria.level + 1,
				posinset: conditionIndex + 1,
				setsize: group.conditions?.length ?? 0
			},
			className: `${blockClass}__group`,
			group: eachCondition,
			onChange: (updatedConditions) => {
				onChangeHandler(updatedConditions, conditionIndex);
			},
			onRemove: (e) => {
				onRemoveHandler(eachCondition.id, e, conditionIndex);
			}
		})) : /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement(ConditionBlock, {
			conjunction: conditionIndex > 0 ? group.groupOperator : void 0,
			aria: {
				level: aria.level + 1,
				posinset: conditionIndex + 1,
				setsize: group.conditions?.length ?? 0
			},
			isStatement: false,
			condition: eachCondition,
			group,
			conditionIndex,
			addConditionHandler,
			addConditionSubGroupHandler,
			onChange: (updatedConditions) => {
				onChangeHandler(updatedConditions, conditionIndex);
			},
			onRemove: (e) => {
				onRemoveHandler(eachCondition.id, e, conditionIndex);
			},
			onConnectorOperatorChange,
			onStatementChange: onStatementChangeHandler,
			showConditionSubGroupPreviewHandler: () => {
				showConditionSubGroupPreviewHandler(conditionIndex);
			},
			hideConditionSubGroupPreviewHandler,
			showConditionPreviewHandler: () => {
				showConditionPreviewHandler(conditionIndex);
			},
			hideConditionPreviewHandler,
			isLastCondition
		})), conditionIndex === showConditionSubGroupPreview && /* @__PURE__ */ React.createElement(ConditionPreview, {
			previewType: "subGroup",
			group
		}), conditionIndex === showConditionPreview && /* @__PURE__ */ React.createElement(ConditionPreview, {
			previewType: "condition",
			group
		}))));
	};
	return /* @__PURE__ */ React.createElement(React.Fragment, null, variant == HIERARCHICAL_VARIANT && getHierarchicalVariant(), variant == NON_HIERARCHICAL_VARIANT && getNonHierarchicalVariant());
};
ConditionGroupBuilder.propTypes = {
	aria: PropTypes.object,
	className: PropTypes.string,
	group: PropTypes.object,
	onChange: PropTypes.func,
	onRemove: PropTypes.func
};

//#endregion
export { ConditionGroupBuilder as default };