<template>
  <div class="w-full bg-transparent ">
    <div ref="tabsScrollRef"
      class="tabs-scroll w-full  overflow-x-auto scrollbar-none [-ms-overflow-style:none] [&::-webkit-scrollbar]:hidden">
      <div class="flex items-end h-[50px] gap-4 flex-nowrap px-3">
        <div v-for="(tab, idx) in tabs" :key="idx" :id="getTabId(idx)"
          class="relative inline-flex items-center justify-center h-[50px] shrink-0" @click="handleSwitch(tab, idx)">
          <div class="relative flex items-center justify-center h-[50px]">
            <div class="relative inline-flex items-center justify-center">
              <span
                :class="['relative text-base z-10 leading-none', modelValue === idx ? 'text-[#0b0b0b] font-bold' : 'font-medium text-[#808c99]/90']">
                {{ tab.label }}
              </span>
              <img v-if="modelValue === idx && (isZhiNian ? indicatorSrcB : indicatorSrc)"
                :src="isZhiNian ? indicatorSrc : indicatorSrcB"
                class="absolute -bottom-[6px] left-1/2 -translate-x-1/2 w-[56px] h-auto z-[1]" />
            </div>
          </div>
        </div>
        <div class="w-px h-[50px] shrink-0"></div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { nextTick, onMounted, ref, watch } from "vue";
import { isZhiNian } from "@/constants/base";
import indicatorSrc from "./images/selected_tabs_icon.png";
import indicatorSrcB from "./images/selected_tabs_icon_b.png";

const props = defineProps({
  modelValue: { type: Number, default: 0 },
  tabs: {
    type: Array,
    default: () => [],
  },
});

const emit = defineEmits(['update:modelValue', 'change']);

const tabsScrollRef = ref(null);

const getTabId = (idx) => `find-tab-${idx}`;

const centerActiveTab = async () => {
  await nextTick();

  const activeIndex = props.modelValue;
  if (activeIndex < 0 || activeIndex >= props.tabs.length) return;

  const scrollEl = tabsScrollRef.value;
  const activeEl = scrollEl?.querySelector(`#${getTabId(activeIndex)}`);
  if (!scrollEl || !activeEl) return;

  const scrollRect = scrollEl.getBoundingClientRect();
  const activeRect = activeEl.getBoundingClientRect();
  const maxScrollLeft = Math.max(0, scrollEl.scrollWidth - scrollEl.clientWidth);
  const targetScrollLeft =
    scrollEl.scrollLeft +
    activeRect.left - scrollRect.left -
    (scrollRect.width - activeRect.width) / 2;
  const nextScrollLeft = Math.min(Math.max(0, targetScrollLeft), maxScrollLeft);

  scrollEl.scrollTo({
    left: nextScrollLeft,
    behavior: "smooth",
  });
};

const handleSwitch = (tab, idx) => {
  emit('update:modelValue', idx);
  emit('change', { tab, idx });
};

watch(
  () => [props.modelValue, props.tabs.length],
  () => {
    centerActiveTab();
  }
);

onMounted(() => {
  centerActiveTab();
});

</script>
