<template>
  <div class="scroll-pane" ref="scrollContainer" @wheel.prevent="handleWheel">
    <div class="scroll-pane-wrapper" ref="wrap">
      <slot />
    </div>
  </div>
</template>

<script setup>
import {ref, watch, nextTick} from 'vue'

const props = defineProps({
  data: {
    type: Array,
    default: () => []
  }
})

const scrollContainer = ref(null)
const wrap = ref(null)

const handleWheel = (e) => {
  const delta = e.deltaX || e.deltaY
  if (wrap.value) {
    wrap.value.scrollLeft += delta > 0 ? 40 : -40
  }
}

// 核心修复：moveToTarget 方法
const moveToTarget = (tag) => {
  nextTick(() => {
    if (!wrap.value) return

    const container = wrap.value
    const activeTab = container.querySelector(`[data-path="${tag.path}"]`)

    if (!activeTab) return

    const offsetLeft = activeTab.offsetLeft
    const offsetWidth = activeTab.offsetWidth
    const scrollLeft = container.scrollLeft
    const containerWidth = container.offsetWidth

    if (offsetLeft < scrollLeft) {
      container.scrollLeft = offsetLeft
    } else if (offsetLeft + offsetWidth > scrollLeft + containerWidth) {
      container.scrollLeft = offsetLeft + offsetWidth - containerWidth
    }
  })
}

watch(
    () => props.data,
    () => {
      nextTick(() => {
        if (props.data && props.data.length > 0) {
          const lastTag = props.data[props.data.length - 1]
          moveToTarget(lastTag)
        }
      })
    },
    {deep: true}
)

defineExpose({
  moveToTarget
})
</script>

<style scoped>
.scroll-pane {
  position: relative;
  width: 100%;
  height: 100%;
  overflow: hidden;
}

.scroll-pane-wrapper {
  white-space: nowrap;
  overflow-x: auto;
  overflow-y: hidden;
  scrollbar-width: none;
  -ms-overflow-style: none;
}

.scroll-pane-wrapper::-webkit-scrollbar {
  display: none;
}
</style>