import { useEffect, useState } from "react";
import { VisibilityState } from "@tanstack/react-table";
import {
  getColumnVisibility,
  setColumnVisibility,
} from "@/shared/utils/columnVisibilityStorage";

/**
 * Column visibility state that persists per table (keyed by `tableName`)
 * across refreshes and navigation. Falls back to `defaultVisibility` when
 * nothing has been saved yet.
 */
export const usePersistedColumnVisibility = (
  tableName: string,
  defaultVisibility: VisibilityState,
): [VisibilityState, React.Dispatch<React.SetStateAction<VisibilityState>>] => {
  const [columnVisibility, setColumnVisibilityState] =
    useState<VisibilityState>(
      () => getColumnVisibility(tableName) ?? defaultVisibility,
    );

  useEffect(() => {
    setColumnVisibility(tableName, columnVisibility);
  }, [tableName, columnVisibility]);

  return [columnVisibility, setColumnVisibilityState];
};
