<script setup>
import { t } from '@/locale'

const props = defineProps({
  notifications: {
    type: Array,
    default: () => [],
  },
  interval: {
    type: Number,
    default: 3000,
  },
  top: {
    type: String,
    default: '0px',
  },
})

const currentIndex = ref(0)
const isTransitioning = ref(false)
let carouselTimer = null

// 获取下一个索引
function getNextIndex() {
  return (currentIndex.value + 1) % props.notifications.length
}

// 切换到下一个通知
function switchToNext() {
  if (props.notifications.length <= 1)
    return

  isTransitioning.value = true

  // 立即切换到下一个索引
  currentIndex.value = getNextIndex()

  // 动画完成后重置过渡状态
  setTimeout(() => {
    isTransitioning.value = false
  }, 500)
}

// 启动轮播
function startCarousel() {
  if (props.notifications.length <= 1)
    return

  carouselTimer = setInterval(switchToNext, props.interval)
}

// 停止轮播
function stopCarousel() {
  if (carouselTimer) {
    clearInterval(carouselTimer)
    carouselTimer = null
  }
}

// 重启轮播
function restartCarousel() {
  stopCarousel()
  currentIndex.value = 0
  isTransitioning.value = false

  nextTick(() => {
    startCarousel()
  })
}

// 监听数据变化
watch(() => props.notifications, restartCarousel, { deep: true })
watch(() => props.interval, restartCarousel)

// 生命周期
onMounted(() => {
  startCarousel()
})

onUnmounted(() => {
  stopCarousel()
})

// 暴露方法
defineExpose({
  start: startCarousel,
  stop: stopCarousel,
  restart: restartCarousel,
})
</script>

<template>
  <view
    v-if="notifications.length > 0"
    class="absolute left-24rpx h-56rpx w-70% overflow-hidden rounded-full"
    :style="{ top }"
  >
    <view
      v-for="(notification, index) in notifications"
      :key="`${notification.id}-${index}`"
      class="absolute inset-0 flex items-center justify-start rounded-full bg-#000000/60 py-8rpx pl-8rpx pr-14rpx transition-all duration-500 ease-out"
      :style="{
        opacity: index === currentIndex ? 1 : 0,
        transform: index === currentIndex
          ? 'translateY(0)'
          : (isTransitioning && index === (currentIndex - 1 + notifications.length) % notifications.length
            ? 'translateY(-100%)'
            : 'translateY(100%)'),
        zIndex: index === currentIndex ? 2 : 1,
      }"
    >
      <wd-img width="40rpx" round height="40rpx" :src="notification.headPic" />
      <text class="ml-12rpx flex-1 truncate text-24rpx text-white">
        {{ t('productDetail.notification.message', {
          name: notification.name,
          action: notification.kId === 0 ? t('productDetail.notification.opened') : t('productDetail.notification.joined'),
          time: notification.time,
        }) }}
      </text>
    </view>
  </view>
</template>
