import { type SyntheticEvent, useRef } from 'react';

export const useSelectionRange = () => {
  const selection = useRef<{
    selectionStart: number | null;
    selectionEnd: number | null;
  }>();

  const handleSelect = (e: SyntheticEvent<HTMLInputElement>) => {
    const input = e.target as HTMLInputElement;
    const { selectionStart, selectionEnd } = input;
    selection.current = { selectionStart, selectionEnd };
  };
  const handleSelectionBlur = () => {
    selection.current = undefined;
  };

  /* eslint-disable react-hooks/refs */
  return {
    selection: selection.current,
    handleSelect,
    handleSelectionBlur,
  };
  /* eslint-enable react-hooks/refs */
};
