/*
 * 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, useEffect, useState } from "react";
import { SELECTION_COLUMN_ID } from "../utils/constants.js";
export const useColumnPinning = ({
  columnDefinitions,
  hasSelectionColumn,
  onColumnsPinnedChanged
}) => {
  const [columnPinning, setColumnPinning] = useState({
    left: [],
    right: []
  });

  // Update column pinning when columnDefinitions change
  useEffect(() => {
    const defaultState = getColumnPinningStateFromColumnDefs(columnDefinitions);
    const selectionCol = hasSelectionColumn ? [SELECTION_COLUMN_ID] : [];
    setColumnPinning({
      left: [...selectionCol, ...(defaultState.left ?? [])],
      right: [...(defaultState.right ?? [])]
    });
  }, [columnDefinitions, hasSelectionColumn]);
  const onColumnPinningChange = useCallback(updater => {
    setColumnPinning(prev => {
      const newPinning = typeof updater === "function" ? updater(prev) : updater;
      if (onColumnsPinnedChanged) {
        const newStates = convertColumnPinningStateToArray(newPinning);
        const stateWithoutSelectionCol = newStates.filter(state => state.columnId !== SELECTION_COLUMN_ID);
        onColumnsPinnedChanged(stateWithoutSelectionCol);
      }
      return newPinning;
    });
  }, [onColumnsPinnedChanged]);
  return {
    columnPinning,
    onColumnPinningChange
  };
};
const getColumnPinningStateFromColumnDefs = columnDefinitions => {
  if (!columnDefinitions) {
    return {};
  }
  const columnPinningState = columnDefinitions.reduce((acc, {
    locator,
    pinned
  }) => {
    const colKey = locator.id.toString();
    if (!(pinned != null && pinned !== "none")) {
      return acc;
    }
    if (pinned === "left") {
      return {
        ...acc,
        left: [...(acc.left ?? []), colKey]
      };
    }
    return {
      ...acc,
      right: [...(acc.right ?? []), colKey]
    };
  }, {
    left: [],
    right: []
  });
  return columnPinningState;
};

/**
 * Converts ColumnPinningState to array format for the callback
 */
function convertColumnPinningStateToArray(pinningState) {
  return [...(pinningState.left ?? []).map(columnId => ({
    columnId,
    pinned: "left"
  })), ...(pinningState.right ?? []).map(columnId => ({
    columnId,
    pinned: "right"
  }))];
}
//# sourceMappingURL=useColumnPinning.js.map