import { useEffect } from 'react';
import { useAppDispatch } from '../hooks';
import { setWindowSize } from '../windowSize/windowSizeSlice';

export const useWindowSize = () => {
  const dispatch = useAppDispatch();

  useEffect(() => {
    // Handler to dispatch window size
    const handleResize = () => {
      dispatch(
        setWindowSize({
          width: window.innerWidth,
          height: window.innerHeight,
        })
      );
    };

    // Set initial size on mount
    handleResize();

    // Add resize event listener
    window.addEventListener('resize', handleResize);

    // Cleanup on unmount
    return () => window.removeEventListener('resize', handleResize);
  }, [dispatch]);
};
