/**
 * 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 { getNewSortOrder } from "./useSortableColumns.js";
import { useEffect, useState } from "react";
//#region src/components/Datagrid/useInitialColumnSort.js
/**
* Copyright IBM Corp. 2024, 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.
*/
const useInitialColumnSort = (instance) => {
	const [hasInitialSort, setHasInitialSort] = useState(false);
	useEffect(() => {
		const { initialState, headers, onSort, isTableSortable } = instance;
		const { sortableColumn } = initialState;
		if (headers.some((h) => h.isSorted) || hasInitialSort || !isTableSortable) return;
		if (sortableColumn) {
			const { id: columnId, order } = sortableColumn;
			if (order !== "ASC" && order !== "DESC") return;
			const { newSortDesc, newOrder } = getNewSortOrder(order);
			onSort?.(columnId, newOrder);
			instance.toggleSortBy(columnId, newSortDesc, false);
			setHasInitialSort(true);
		}
	}, [instance, hasInitialSort]);
};
//#endregion
export { useInitialColumnSort };
