/**
 * useColumnCount 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: 1,
  sm: 1,
  md: 2,
  lg: 3,
  xl: 4,
  '2xl': 4,
  '3xl': 5,
  '4xl': 6,
};

/**
 * 根据容器宽度计算合适的列数
 * 
 * @param columnConfig - 列数配置
 * @returns 列数
 * 
 * @example
 * const columns = useColumnCount({
 *   xs: 1,
 *   sm: 2,
 *   md: 3,
 *   lg: 4
 * });
 */
export function useColumnCount(
  columnConfig: Partial<Record<FineBreakpointKey, number>> = {}
): number {
  const { width } = useWindowDimensions();
  const fineBreakpoint = getFineBreakpoint(width);
  
  return useMemo(() => {
    const config = { ...defaultConfig, ...columnConfig };
    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 1;
  }, [fineBreakpoint, columnConfig]);
}

export default useColumnCount;
