/*
 * Copyright 2025 Palantir Technologies, Inc. All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import { useCallback, useMemo, useState } from "react";
export const useTableSorting = ({
  orderBy,
  defaultOrderBy,
  onOrderByChanged
}) => {
  // The sorting state in uncontrolled mode
  const [internalSorting, setInternalSorting] = useState(() => defaultOrderBy ? convertOrderByToSortingState(defaultOrderBy) : []);
  const isControlled = orderBy !== undefined;

  // Sorting state
  // If controlled mode, return the state from orderBy prop
  // If uncontrolled, return the internalSorting state
  const sortingState = useMemo(() => orderBy ? convertOrderByToSortingState(orderBy) : internalSorting, [orderBy, internalSorting]);
  const orderByState = useMemo(() => {
    const currentOrderBy = orderBy ? orderBy : convertSortingStateToOrderBy(internalSorting);
    return Object.fromEntries(currentOrderBy.map(({
      property,
      direction
    }) => [property, direction]));
  }, [orderBy, internalSorting]);
  const onSortingChange = useCallback(updater => {
    const newSorting = typeof updater === "function" ? updater(sortingState) : updater;

    // Update internal state if uncontrolled
    if (!isControlled) {
      setInternalSorting(newSorting);
    }
    if (onOrderByChanged) {
      const newOrderBy = convertSortingStateToOrderBy(newSorting);
      onOrderByChanged(newOrderBy);
    }
  }, [isControlled, sortingState, onOrderByChanged]);
  return {
    sorting: sortingState,
    orderByState,
    onSortingChange
  };
};
function convertOrderByToSortingState(orderBy) {
  return orderBy.map(({
    property,
    direction
  }) => ({
    id: property,
    desc: direction === "desc"
  }));
}
function convertSortingStateToOrderBy(sorting) {
  return sorting.map(({
    id,
    desc
  }) => ({
    property: id,
    direction: desc ? "desc" : "asc"
  }));
}
//# sourceMappingURL=useTableSorting.js.map