/**
 * 가상 스크롤링을 적용한 선박 목록 컴포넌트
 * 1000척 이상의 대용량 데이터 렌더링 최적화
 */
import React, { useMemo } from 'react';
import VesselItem from './VesselItem';
import { useVirtualScroll } from './hooks/useVirtualScroll';

const VirtualVesselList = ({
  vessels,
  selectedVesselIds = new Set(),
  onDragStart,
  onDragEnd,
  onMouseEnterVessel,
  onMouseLeaveVessel,
  onToggleSelection,
  onShowVesselDetail,
  onContextMenu,
  containerHeight = 300,
  itemHeight = 40, // VesselItem의 대략적인 높이
}) => {
  const { containerRef, scrollElementRef, handleScroll, visibleItems, totalHeight, offsetY, startIndex, endIndex } =
    useVirtualScroll({
      items: vessels,
      itemHeight,
      containerHeight,
      overscan: 5,
    });

  // 성능 최적화를 위한 메모이제이션
  const renderedItems = useMemo(() => {
    return visibleItems.map((vessel) => (
      <div
        key={vessel.vesselId}
        style={{
          position: 'absolute',
          top: `${vessel.index * itemHeight}px`,
          left: 0,
          right: 0,
          height: `${itemHeight}px`,
          width: '100%',
        }}
      >
        <VesselItem
          vessel={vessel}
          index={vessel.index}
          isDragDisabled={false}
          isSelected={selectedVesselIds.has(vessel.vesselId)}
          onDragStart={onDragStart}
          onDragEnd={onDragEnd}
          onMouseEnterVessel={onMouseEnterVessel}
          onMouseLeaveVessel={onMouseLeaveVessel}
          onToggleSelection={onToggleSelection}
          onShowVesselDetail={onShowVesselDetail}
          onContextMenu={onContextMenu}
        />
      </div>
    ));
  }, [
    visibleItems,
    itemHeight,
    selectedVesselIds,
    onDragStart,
    onDragEnd,
    onMouseEnterVessel,
    onMouseLeaveVessel,
    onToggleSelection,
    onShowVesselDetail,
    onContextMenu,
  ]);

  if (vessels.length === 0) {
    return null; // 빈 상태는 상위 컴포넌트에서 처리
  }

  return (
    <div
      ref={scrollElementRef}
      className="virtual-vessel-list"
      style={{
        height: containerHeight,
        overflow: 'auto',
        position: 'relative',
      }}
      onScroll={handleScroll}
    >
      {/* 가상 컨테이너 (전체 높이 유지) */}
      <div
        style={{
          height: totalHeight,
          position: 'relative',
          width: '100%',
        }}
      >
        {/* 실제 렌더링되는 아이템들 */}
        {renderedItems}
      </div>
    </div>
  );
};

export default React.memo(VirtualVesselList);
