/**
 * 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 { getSelectionAreaPoints } from "./getSelectionAreaPoints.js";
//#region src/components/DataSpreadsheet/utils/handleActiveCellInSelectionTab.js
/**
* Copyright IBM Corp. 2022, 2022
*
* 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 handleActiveCellInSelectionTab = ({ activeCellInsideSelectionArea, activeCellCoordinates, activeCellRef, selectionAreas, updateActiveCellCoordinates }) => {
	if (!activeCellInsideSelectionArea) return;
	const activeCellSelectionId = activeCellRef.current.getAttribute("data-selection-id");
	const activeCellIndexInSelectionAreas = selectionAreas.findIndex((item) => item.matcher === activeCellSelectionId);
	const selectionAreaToNavigate = selectionAreas[activeCellIndexInSelectionAreas];
	const { lowestColumnIndex, lowestRowIndex, greatestColumnIndex, greatestRowIndex } = getSelectionAreaPoints(selectionAreaToNavigate);
	if (activeCellCoordinates?.column < greatestColumnIndex) updateActiveCellCoordinates({
		updatedValue: { column: activeCellCoordinates?.column + 1 },
		optOutOfSelectionAreaUpdate: true
	});
	if (activeCellCoordinates?.column === greatestColumnIndex) {
		if (activeCellCoordinates?.row < greatestRowIndex) updateActiveCellCoordinates({
			updatedValue: {
				column: lowestColumnIndex,
				row: activeCellCoordinates?.row + 1
			},
			optOutOfSelectionAreaUpdate: true
		});
		if (activeCellCoordinates?.row === greatestRowIndex) {
			if (selectionAreas.length > 1) if (selectionAreas[activeCellIndexInSelectionAreas + 1]) {
				activeCellRef.current.setAttribute("data-selection-id", selectionAreas[activeCellIndexInSelectionAreas + 1].matcher);
				const nextSelectionArea = selectionAreas[activeCellIndexInSelectionAreas + 1];
				const { lowestColumnIndex, lowestRowIndex } = getSelectionAreaPoints(nextSelectionArea);
				updateActiveCellCoordinates({
					updatedValue: {
						column: lowestColumnIndex,
						row: lowestRowIndex
					},
					optOutOfSelectionAreaUpdate: true
				});
				return;
			} else {
				activeCellRef.current.setAttribute("data-selection-id", selectionAreas[0].matcher);
				const firstSelectionArea = selectionAreas[0];
				const { lowestColumnIndex, lowestRowIndex } = getSelectionAreaPoints(firstSelectionArea);
				updateActiveCellCoordinates({
					updatedValue: {
						column: lowestColumnIndex,
						row: lowestRowIndex
					},
					optOutOfSelectionAreaUpdate: true
				});
			}
			if (selectionAreas.length === 1) return updateActiveCellCoordinates({
				updatedValue: {
					column: lowestColumnIndex,
					row: lowestRowIndex
				},
				optOutOfSelectionAreaUpdate: true
			});
		}
	}
};
//#endregion
export { handleActiveCellInSelectionTab };
