import { useState, useEffect } from 'react';

/**
 * Custom React hook to determine the current active device type based on the window's width.
 * It listens to the window resize event and updates the device type accordingly.
 *
 * Device types:
 * - 'mobile'  : width <= 767px.
 * - 'tablet'  : 768px <= width <= 1024px.
 * - 'desktop' : width > 1024px.
 *
 * @returns {string} The current device type ('mobile' | 'tablet' | 'desktop').
 */
const useActiveDevice = () => {

  // Get the current device type.
  const [ device, setDevice ] = useState( 'desktop' );

  // Update the device type.
  const updateDevice = () => {
    const width = window.innerWidth;
    if ( 767 >= width ) {
setDevice( 'mobile' );
} else if ( 1024 >= width ) {
setDevice( 'tablet' );
} else {
setDevice( 'desktop' );
}
  };

  // Update the device type on mount.
  useEffect( () => {
    updateDevice(); // on mount.
    window.addEventListener( 'resize', updateDevice );
    return () => window.removeEventListener( 'resize', updateDevice );
  }, []);

  // Return the current device type.
  return device;
};

export default useActiveDevice;
