/**
 * 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 { useEffect } from "react";

//#region src/components/Datagrid/useFocusRowExpander.js
/**
* Copyright IBM Corp. 2023, 2023
*
* This source code is licensed under the Apache-2.0 license found in the
* LICENSE file in the root directory of this source tree.
*/
const useFocusRowExpander = ({ instance, lastExpandedRowIndex = 0, blockClass, activeElement }) => {
	useEffect(() => {
		if (!activeElement.classList.contains(`${blockClass}__row-expander`)) return;
		const tableId = instance?.tableId;
		const rowElements = document.querySelectorAll(`#${tableId} tbody tr`);
		const activeRow = Array.from(rowElements).filter((r) => {
			if (r.getAttribute("data-nested-row-id") === lastExpandedRowIndex) return r;
			return null;
		});
		if (activeRow.length) activeRow[0].querySelector(`.${blockClass}__row-expander`)?.focus();
	}, [
		instance?.tableId,
		instance?.expandedRows,
		lastExpandedRowIndex,
		blockClass,
		activeElement
	]);
};

//#endregion
export { useFocusRowExpander };