import { useState, useEffect } from 'react';

export type Breakpoint = 'mobile' | 'tablet' | 'desktop' | 'large';

interface ResponsiveState {
  breakpoint: Breakpoint;
  isMobile: boolean;
  isTablet: boolean;
  isDesktop: boolean;
  isLarge: boolean;
  width: number;
  height: number;
}

// 断点定义
const BREAKPOINTS = {
  mobile: 640,   // sm: 640px
  tablet: 768,   // md: 768px
  desktop: 1024, // lg: 1024px
  large: 1280,   // xl: 1280px
};

export function useResponsive(): ResponsiveState {
  const [state, setState] = useState<ResponsiveState>({
    breakpoint: 'desktop',
    isMobile: false,
    isTablet: false,
    isDesktop: true,
    isLarge: false,
    width: typeof window !== 'undefined' ? window.innerWidth : 1024,
    height: typeof window !== 'undefined' ? window.innerHeight : 768,
  });

  useEffect(() => {
    const handleResize = () => {
      const width = window.innerWidth;
      const height = window.innerHeight;

      let breakpoint: Breakpoint;
      if (width < BREAKPOINTS.mobile) {
        breakpoint = 'mobile';
      } else if (width < BREAKPOINTS.tablet) {
        breakpoint = 'tablet';
      } else if (width < BREAKPOINTS.large) {
        breakpoint = 'desktop';
      } else {
        breakpoint = 'large';
      }

      setState({
        breakpoint,
        isMobile: width < BREAKPOINTS.tablet,
        isTablet: width >= BREAKPOINTS.mobile && width < BREAKPOINTS.desktop,
        isDesktop: width >= BREAKPOINTS.tablet,
        isLarge: width >= BREAKPOINTS.large,
        width,
        height,
      });
    };

    // 初始检测
    handleResize();

    // 监听窗口变化
    window.addEventListener('resize', handleResize);
    return () => window.removeEventListener('resize', handleResize);
  }, []);

  return state;
}

// 便捷 hook：仅返回是否是移动端
export function useIsMobile(): boolean {
  const { isMobile } = useResponsive();
  return isMobile;
}

// 便捷 hook：仅返回是否是桌面端
export function useIsDesktop(): boolean {
  const { isDesktop } = useResponsive();
  return isDesktop;
}
