/*
 * 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";
export const useColumnVisibility = ({
  allColumns,
  onColumnVisibilityChanged
}) => {
  const [columnVisibility, setColumnVisibility] = useState(() => getColumnVisibilityState(allColumns));
  const [columnOrder, setColumnOrder] = useState(() => getColumnOrder(allColumns));

  // TODO: Explore other ways to respond to props changes for controlled mode
  useEffect(() => {
    setColumnVisibility(getColumnVisibilityState(allColumns));
  }, [allColumns]);
  useEffect(() => {
    setColumnOrder(getColumnOrder(allColumns));
  }, [allColumns]);
  const onColumnVisibilityChange = useCallback(updaterOrValue => {
    setColumnVisibility(prev => {
      const newState = typeof updaterOrValue === "function" ? updaterOrValue(prev) : updaterOrValue;
      if (onColumnVisibilityChanged) {
        const changes = Object.entries(newState).map(([columnId, isVisible]) => ({
          columnId,
          isVisible
        }));
        onColumnVisibilityChanged(changes);
      }
      return newState;
    });
  }, [onColumnVisibilityChanged]);
  const onColumnOrderChange = useCallback(updaterOrValue => {
    setColumnOrder(prev => {
      const newState = typeof updaterOrValue === "function" ? updaterOrValue(prev) : updaterOrValue;
      return newState;
    });
  }, []);
  return {
    columnVisibility,
    onColumnVisibilityChange,
    columnOrder,
    onColumnOrderChange
  };
};
const getColumnVisibilityState = allColumns => {
  return allColumns.reduce((acc, col) => {
    const colId = col.id ?? col.accessorKey;
    if (colId) {
      return {
        ...acc,
        [colId]: col.meta?.isVisible !== false
      };
    }
    return acc;
  }, {});
};
const getColumnOrder = allColumns => {
  return allColumns.map(col => col.id ?? col.accessorKey).filter(id => id != null);
};
//# sourceMappingURL=useColumnVisibility.js.map