/**
 * 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 { pkg } from "../../settings.js";
import useNestedRowExpander from "./useNestedRowExpander.js";
import { useEffect } from "react";
//#region src/components/Datagrid/useNestedRows.ts
var import_classnames = /* @__PURE__ */ __toESM(require_classnames());
const blockClass = `${pkg.prefix}--datagrid`;
const useNestedRows = (hooks) => {
	useNestedRowExpander(hooks);
	const useInstance = (instance) => {
		useEffect(() => {
			const { rows } = instance;
			const defaultExpandedRows = rows.filter((row) => row?.original?.defaultExpanded);
			if (defaultExpandedRows?.length) defaultExpandedRows.map((defaultExpandedRow) => {
				if (!defaultExpandedRow?.isExpanded && !defaultExpandedRow?.hasExpanded) {
					defaultExpandedRow?.toggleRowExpanded?.();
					defaultExpandedRow.hasExpanded = true;
					return;
				}
			});
		}, [instance, instance.rows]);
		useEffect(() => {
			const { rows, initialState } = instance;
			const { expandedRowIds } = initialState;
			if (expandedRowIds) Object.keys(expandedRowIds).forEach((key) => {
				const row = rows.filter((r) => r.id.toString() === key.toString() || r.original?.id?.toString() === key.toString());
				if (row.length && key.toString() === row[0].id.toString() || row.length && key.toString() === row[0].original?.id?.toString()) row[0].toggleRowExpanded();
			});
		}, [instance]);
		const marginLeft = 24;
		const getRowProps = (props, { row }) => {
			return [props, { className: (0, import_classnames.default)({
				[`${blockClass}__carbon-nested-row`]: row.depth > 0,
				[`${blockClass}__carbon-row-expanded`]: row.isExpanded
			}) }];
		};
		const getRowStyles = (props, { row }) => [props, { style: { paddingLeft: `${row.depth > 1 ? marginLeft * 2 + (row.depth - 1) * (marginLeft + marginLeft / 3) : row.depth === 1 ? marginLeft * 2 : 0}px` } }];
		const getIndentation = (depth) => 32 * depth + 16;
		const getCellProps = (props, { cell, instance }) => {
			const isFirstCell = instance.columns.findIndex((c) => c.id === cell.column.id) === 0;
			return [props, { style: {
				marginRight: isFirstCell && cell.row.depth > 0 && parseInt(props.style.width, 10) <= getIndentation(cell.row.depth) + 50 ? `${parseInt(props.style.width, 10) - (getIndentation(cell.row.depth) + 50)}px` : "",
				width: isFirstCell && cell.row.depth > 0 ? parseInt(props.style.width, 10) - getIndentation(cell.row.depth) : props.style.width
			} }];
		};
		Object.assign(instance, { withNestedRows: true });
		hooks.getRowProps.push(getRowProps);
		hooks.getRowProps.push(getRowStyles);
		hooks.getCellProps.push(getCellProps);
	};
	hooks.useInstance.push(useInstance);
};
//#endregion
export { useNestedRows as default };
