/**
 * useResponsiveSpacing Hook
 * 响应式间距 - 根据断点返回对应的间距值
 */

import { useMemo } from 'react';
import { useWindowDimensions } from './useScreenSize';
import { getFineBreakpoint } from './useBreakpoint';
import type { FineBreakpointKey } from './types';

const breakpointOrder: FineBreakpointKey[] = ['4xl', '3xl', '2xl', 'xl', 'lg', 'md', 'sm', 'xs'];

const defaultConfig: Record<FineBreakpointKey, number> = {
  xs: 8,
  sm: 8,
  md: 12,
  lg: 16,
  xl: 20,
  '2xl': 24,
  '3xl': 32,
  '4xl': 40,
};

/**
 * 响应式间距 Hook
 * 
 * @param spacingConfig - 间距配置
 * @returns 当前断点对应的间距值
 * 
 * @example
 * const gap = useResponsiveSpacing({ xs: 8, md: 16, lg: 24 });
 */
export function useResponsiveSpacing(
  spacingConfig: Partial<Record<FineBreakpointKey, number>> = {}
): number {
  const { width } = useWindowDimensions();
  const fineBreakpoint = getFineBreakpoint(width);
  
  return useMemo(() => {
    const config = { ...defaultConfig, ...spacingConfig };
    const currentIndex = breakpointOrder.indexOf(fineBreakpoint);
    
    for (let i = currentIndex; i < breakpointOrder.length; i++) {
      const bp = breakpointOrder[i];
      if (config[bp] !== undefined) {
        return config[bp];
      }
    }
    
    return defaultConfig.xs;
  }, [fineBreakpoint, spacingConfig]);
}

export default useResponsiveSpacing;
