<template>
  <div class="w-full bg-transparent">
    <div class="w-full overflow-x-auto [scrollbar-width:none] [-ms-overflow-style:none] [&::-webkit-scrollbar]:hidden"
      :scroll-left="scrollLeft" scroll-with-animation="true" @scroll="handleScroll">
      <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" @tap="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 font-medium text-[#808c99]/90 z-10 px-1 leading-none', modelValue === idx ? 'text-[#0b0b0b] font-bold' : '']">
                {{ tab.label }}
              </span>
              <img v-if="modelValue === idx && (isZhiNian ? indicatorSrcB : indicatorSrc)"
                :src="isZhiNian ? indicatorSrcB : indicatorSrc"
                class="absolute -bottom-[6px] left-1/2 -translate-x-1/2 w-[56px] h-auto z-[1]" />
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { getCurrentInstance, 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 instance = getCurrentInstance();

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

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

const scrollLeft = ref(0);
let currentScrollLeft = 0;

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

const handleScroll = (e) => {
  currentScrollLeft = e.detail?.scrollLeft || 0;
};

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

  const activeIndex = props.modelValue;
  if (activeIndex < 0 || activeIndex >= props.tabs.length) return;
  if (!instance || typeof uni === "undefined" || !uni.createSelectorQuery) return;

  const query = uni.createSelectorQuery().in(instance);
  query.select(".tabs-scroll").boundingClientRect();
  query.select(".tabs-scroll").scrollOffset();
  query.select(`#${getTabId(activeIndex)}`).boundingClientRect();
  query.exec((res) => {
    const [scrollRect, scrollOffset, activeRect] = res || [];
    if (!scrollRect || !activeRect) return;

    const currentLeft = scrollOffset?.scrollLeft ?? currentScrollLeft;
    const targetScrollLeft =
      currentLeft +
      activeRect.left - scrollRect.left -
      (scrollRect.width - activeRect.width) / 2;

    scrollLeft.value = Math.max(0, targetScrollLeft);
  });
};

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

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

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

</script>
