import { useCallback, useState, useRef, useEffect } from 'react';

interface UseAccessibilityMessageResult {
  accessibilityMessage: string;
  announce: (message: string) => void;
}

// Small helper for aria-live regions.
// Clears then sets the message so identical announcements can be re-read by some AT.
export const useAccessibilityMessage = (): UseAccessibilityMessageResult => {
  const [accessibilityMessage, setAccessibilityMessage] = useState('');
  const timeoutRef = useRef<number>();

  const announce = useCallback((message: string) => {
    setAccessibilityMessage('');
    
    if (timeoutRef.current) {
      window.clearTimeout(timeoutRef.current);
    }
    
    timeoutRef.current = window.setTimeout(() => {
      setAccessibilityMessage(message);
    }, 50);
  }, []);

  useEffect(() => {
    return () => {
      if (timeoutRef.current) window.clearTimeout(timeoutRef.current);
    };
  }, []);

  return { accessibilityMessage, announce };
};

export default useAccessibilityMessage;
