/**
 * KRA - Responsive Hook
 * Detect device type based on screen width
 */
import { useState, useEffect, useCallback } from 'react';
import { useModel } from '@umijs/max';

const MOBILE_WIDTH = 992;

type DeviceType = 'mobile' | 'desktop';

export function useResponsive(immediate = true) {
  const [device, setDevice] = useState<DeviceType>('desktop');
  const [isMobile, setIsMobile] = useState(false);

  const queryDevice = useCallback((): DeviceType => {
    const rect = document.body.getBoundingClientRect();
    return rect.width - 1 < MOBILE_WIDTH ? 'mobile' : 'desktop';
  }, []);

  const handleResize = useCallback(() => {
    if (!document.hidden) {
      const deviceType = queryDevice();
      setDevice(deviceType);
      setIsMobile(deviceType === 'mobile');
    }
  }, [queryDevice]);

  useEffect(() => {
    if (immediate) {
      handleResize();
    }

    let timeoutId: NodeJS.Timeout;
    const debouncedResize = () => {
      clearTimeout(timeoutId);
      timeoutId = setTimeout(handleResize, 100);
    };

    window.addEventListener('resize', debouncedResize);
    return () => {
      window.removeEventListener('resize', debouncedResize);
      clearTimeout(timeoutId);
    };
  }, [immediate, handleResize]);

  return { device, isMobile };
}

export default useResponsive;
