/**
 * 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 { pkg } from "../../../../../settings.js";
import { includesResourceKey } from "../../../../DataSpreadsheet/utils/handleMultipleKeys.js";
import { getFocusableElements } from "../../../../../global/js/utils/getFocusableElements.js";

//#region src/components/Datagrid/Datagrid/addons/InlineEdit/handleMultipleKeys.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 blockClass = `${pkg.prefix}--datagrid`;
const handleMultipleKeys = ({ usingMac, keysPressedList, dispatch, activeCellId, instance }) => {
	if (includesResourceKey(keysPressedList, usingMac) && keysPressedList.includes("Home")) {
		const scrollElement = document.querySelector(`#${instance.tableId} .${pkg.prefix}--datagrid__table-container`);
		scrollElement.scrollTop = 0;
		scrollElement.scrollLeft = 0;
		dispatch({
			type: "UPDATE_ACTIVE_CELL_ID",
			payload: "column-0-row-0"
		});
	}
	if (includesResourceKey(keysPressedList, usingMac) && keysPressedList.includes("End")) {
		const totalVisibleColumns = instance.visibleColumns.filter((item) => item.id !== "spacer").length;
		const totalRows = instance.rows?.length;
		const lastCellDataId = `column-${totalVisibleColumns - 1}-row-${totalRows - 1}`;
		const lastCellElement = document.querySelector(`#${instance.tableId} .${blockClass}__table-with-inline-edit [data-cell-id="${activeCellId}"]`);
		const scrollElement = document.querySelector(`#${instance.tableId} .${pkg.prefix}--datagrid__table-container`);
		scrollElement.scrollTop = scrollElement.scrollHeight;
		scrollElement.scrollLeft = scrollElement.scrollWidth;
		if (lastCellElement) dispatch({
			type: "UPDATE_ACTIVE_CELL_ID",
			payload: lastCellDataId
		});
		else setTimeout(() => {
			dispatch({
				type: "UPDATE_ACTIVE_CELL_ID",
				payload: lastCellDataId
			});
		}, 250);
	}
	if ((keysPressedList.includes("ShiftLeft") || keysPressedList.includes("ShiftRight")) && keysPressedList.includes("Tab")) {
		dispatch({
			type: "REMOVE_GRID_ACTIVE_FOCUS",
			payload: activeCellId
		});
		const datagridFocusableElements = getFocusableElements(document.querySelector(`#${instance.tableId}`));
		const indexOfTable = datagridFocusableElements.findIndex((item) => item instanceof HTMLTableElement);
		if (indexOfTable && Number.isFinite(indexOfTable)) datagridFocusableElements[indexOfTable]?.focus();
	}
};

//#endregion
export { handleMultipleKeys };