"use client";

import { useState } from "react";
import {
  EMPTY_SELECTION,
  toggleRegistration,
  toggleSelectAll,
  type SelectableRegistration,
  type SelectionState,
} from "./registrationSelection";

/**
 * The three pieces of selection state, kept in one object so they cannot drift.
 *
 * Every rule is in `registrationSelection.ts`; this is only the React wrapper
 * around it, which is what makes those rules testable.
 */
export function useRegistrationSelection() {
  const [selection, setSelection] = useState<SelectionState>(EMPTY_SELECTION);

  return {
    selection,
    setSelection,
    selectedUsers: selection.selectedUsers,
    selectAll: selection.selectAll,
    clearSelection: () => setSelection(EMPTY_SELECTION),
    handleSelectAllChange: (rows: SelectableRegistration[]) =>
      setSelection(toggleSelectAll(rows, selection)),
    handleCheckboxChange: (
      userId: string | number,
      rows: SelectableRegistration[]
    ) => setSelection(toggleRegistration(userId, rows, selection)),
  };
}
