import { useState, useEffect } from 'react';

// 定义设备类型枚举
export enum DeviceType {
  MOBILE = 'mobile',    // 手机
  TABLET = 'tablet',    // 平板
  DESKTOP = 'desktop'   // 桌面端
}

// 定义屏幕断点
const BREAKPOINTS = {
  MOBILE: 480,    // 0-480px 为手机
  TABLET: 1024,   // 481-1024px 为平板
  DESKTOP: 1025   // 1025px 及以上为桌面端
};

export function useDeviceType() {
  const [deviceType, setDeviceType] = useState<DeviceType>(DeviceType.DESKTOP);
  const [windowSize, setWindowSize] = useState({
    width: typeof window !== 'undefined' ? window.innerWidth : 0,
    height: typeof window !== 'undefined' ? window.innerHeight : 0
  });

  useEffect(() => {
    /** 
     * 根据窗口宽度判断设备类型
     */
    const getDeviceType = (width: number): DeviceType => {
      if (width <= BREAKPOINTS.MOBILE) return DeviceType.MOBILE;
      if (width <= BREAKPOINTS.TABLET) return DeviceType.TABLET;
      return DeviceType.DESKTOP;
    };

    /**
     * 处理窗口大小变化
     */
    const handleResize = () => {
      const width = window.innerWidth;
      const height = window.innerHeight;
      
      setWindowSize({ width, height });
      setDeviceType(getDeviceType(width));
    };

    // 初始化设备类型
    handleResize();

    // 添加窗口大小变化监听
    window.addEventListener('resize', handleResize);

    // 清理监听器
    return () => {
      window.removeEventListener('resize', handleResize);
    };
  }, []);

  return {
    deviceType,
    windowSize,
    isMobile: deviceType === DeviceType.MOBILE,
    isTablet: deviceType === DeviceType.TABLET,
    isDesktop: deviceType === DeviceType.DESKTOP
  };
}