<template>
  <div class="w-full overflow-x-auto" v-bind="$attrs" ref="containerRef" @click="onContainerClick">
    <div class="flex items-center" ref="contentRef">
      <div
        v-for="(item, index) in items"
        :key="item.name"
        class="text-36px leading-50px cursor-pointer flex items-center"
        :class="item.value === activeKey ? 'text-#fff' : 'text-#aebfc5'"
        @click="handleClick(item.value)"
      >
        <span :style="styles">{{ item.name }}</span>
        <div
          v-if="index < items.length - 1"
          class="w-2px h-[1em] bg-#aebfc5 mx-10px"
          :style="gap ? `margin-left: ${gap}px;margin-right: ${gap}px` : ''"
        ></div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { defineProps, defineEmits, ref } from 'vue';

const props = defineProps<{
  items: { name: string; value: string }[];
  defaultValue?: string;
  active?: string;
  styles?: string;
  gap?: number;
}>();

const activeKey = ref(props.active || props.defaultValue);
// ref
const containerRef = ref<HTMLDivElement | null>(null);
const contentRef = ref<HTMLDivElement | null>(null);

const emit = defineEmits<(e: 'update:active', value: string) => void>();

const handleClick = (value: string) => {
  activeKey.value = value;
  emit('update:active', value);
};

// 点击自动滚动
const onContainerClick = (e: MouseEvent) => {
  if (!containerRef.value || !contentRef.value) return;

  const { width, left } = containerRef.value.getBoundingClientRect();
  const clickX = e.clientX - left;
  if (clickX < width / 2) {
    // left
    containerRef.value.scrollTo(0, 0);
  } else {
    // right
    const scrollLeft = contentRef.value.clientWidth - width;
    if (scrollLeft > 0) {
      containerRef.value.scrollTo(scrollLeft, 0);
    }
  }
};
</script>

