// FE-OP003: 前端性能优化
import React from 'react';

// 懒加载组件
export const lazyLoadComponent = (component: () => Promise<any>) => {
  return React.lazy(component);
};

// 优化渲染性能
export const useOptimizedRender = (deps: any[]) => {
  return React.useMemo(() => deps, deps);
};

// 优化列表渲染
export const optimizeListRender = <T>(
  items: T[],
  renderItem: (item: T, index: number) => React.ReactNode,
  keyExtractor: (item: T) => string | number
) => {
  return items.map((item, index) => {
    const key = keyExtractor(item);
    return React.useMemo(() => renderItem(item, index), [item, index, renderItem]);
  });
};

// 虚拟滚动组件
export const VirtualList: React.FC<{
  items: any[];
  itemHeight: number;
  containerHeight: number;
  renderItem: (item: any, index: number) => React.ReactNode;
  keyExtractor: (item: any) => string | number;
}> = ({ items, itemHeight, containerHeight, renderItem, keyExtractor }) => {
  const [scrollTop, setScrollTop] = React.useState(0);
  
  const handleScroll = (e: React.UIEvent<HTMLDivElement>) => {
    setScrollTop(e.currentTarget.scrollTop);
  };
  
  const startIndex = Math.floor(scrollTop / itemHeight);
  const endIndex = Math.min(
    startIndex + Math.ceil(containerHeight / itemHeight) + 1,
    items.length
  );
  
  const visibleItems = items.slice(startIndex, endIndex);
  const offsetY = startIndex * itemHeight;
  
  return (
    <div
      style={{
        height: containerHeight,
        overflowY: 'auto',
        position: 'relative',
      }}
      onScroll={handleScroll}
    >
      <div
        style={{
          height: items.length * itemHeight,
          position: 'relative',
        }}
      >
        <div
          style={{
            position: 'absolute',
            top: offsetY,
            left: 0,
            right: 0,
          }}
        >
          {visibleItems.map((item, index) => {
            const actualIndex = startIndex + index;
            return (
              <div
                key={keyExtractor(item)}
                style={{
                  height: itemHeight,
                }}
              >
                {renderItem(item, actualIndex)}
              </div>
            );
          })}
        </div>
      </div>
    </div>
  );
};

// 导入非React工具函数
import {
  debounce,
  throttle,
  lazyLoadImage,
  memoize,
  batchProcess,
  preloadResource,
  measurePerformance
} from './PerformanceOptimization';

export {
  debounce,
  throttle,
  lazyLoadImage,
  memoize,
  batchProcess,
  preloadResource,
  measurePerformance
};

export default {
  debounce,
  throttle,
  lazyLoadComponent,
  lazyLoadImage,
  memoize,
  batchProcess,
  preloadResource,
  measurePerformance,
  useOptimizedRender,
  optimizeListRender,
  VirtualList,
};