import { defineComponent, h } from 'vue'

export default defineComponent({
  name: 'VirtualList',
  props: {
    items: {
      type: Array,
      required: true
    },
    itemHeight: {
      type: Number,
      required: true
    },
    containerHeight: {
      type: Number,
      default: 600
    }
  },
  setup(props, { slots }) {
    const visibleStart = ref(0)
    const visibleEnd = ref(Math.ceil(props.containerHeight / props.itemHeight))

    const handleScroll = (e) => {
      const scrollTop = e.target.scrollTop
      visibleStart.value = Math.floor(scrollTop / props.itemHeight)
      visibleEnd.value = visibleStart.value + Math.ceil(props.containerHeight / props.itemHeight)
    }

    const visibleItems = computed(() => {
      return props.items.slice(visibleStart.value, visibleEnd.value)
    })

    return () => h('div', {
      style: { height: `${props.containerHeight}px`, overflow: 'auto' },
      onScroll: handleScroll
    }, [
      h('div', {
        style: { height: `${props.items.length * props.itemHeight}px`, position: 'relative' }
      }, visibleItems.value.map((item, idx) =>
        h('div', {
          key: visibleStart.value + idx,
          style: {
            position: 'absolute',
            top: `${(visibleStart.value + idx) * props.itemHeight}px`,
            height: `${props.itemHeight}px`
          }
        }, slots.default?.({ item, index: visibleStart.value + idx }))
      ))
    ])
  }
})
