<!-- Barrage.vue 优化版 -->
<template>
  <div
    ref="containerRef"
    class="barrage-root"
    :class="{ 'barrage-lite': liteAnimations, 'barrage-paused': isBarragePaused }"
  >
    <div
      v-for="(track, index) in visibleTracks"
      :key="index"
      class="barrage-track"
      :style="{ top: `calc(${index} * 16vw)` }"
    >
      <div
        v-for="item in track"
        :key="item.id"
        class="barrage-item"
        style="
          position: absolute;
          border-radius: 26px;
          padding: 4px;
          display: flex;
          align-items: center;
          gap: 4px;
          backdrop-filter: blur(1px);
        "
        :style="getBarrageStyle(item)"
        @animationend="handleAnimationEnd(item.id)"
      >
        <img
          :src="item.avatar || ''"
          alt=""
          class="barrage-avatar"
          style="
            width: 10vw;
            border-radius: 50%;
            display: block;
            aspect-ratio: 1/1;
            object-fit: cover;
          "
          loading="lazy"
          decoding="async"
          @error="handleAvatarImageError"
        />
        <div
          class="barrage-text"
          style="
            font-weight: 700;
            background-clip: text;
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
            background-image: linear-gradient(
              180deg,
              #fff9a9 26.92%,
              #ed7d0a 52.08%,
              #fffab5 73.08%
            );
          "
        >
          {{ item.text }}
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { computed, onMounted, onUnmounted, ref, watch } from 'vue'
import { useI18n } from 'vue-i18n'
import { handleAvatarImageError } from '@/utils/image/imageHandler.js'
import { shouldUseLiteAnimations } from '@/utils/performanceMode.js'

const { locale, t } = useI18n()

const props = defineProps({
  barrageList: {
    type: Array,
    required: true,
    default: () => [],
  },
  speed: {
    type: Number,
    default: 80,
  },
  maxItems: {
    type: Number,
    default: 4,
  },
  loopInterval: {
    type: Number,
    default: 2000,
  },
})

const tracks = ref([[], []])
const containerRef = ref(null)
const idCounter = ref(0)
const currentIndex = ref(0)
const isBarragePaused = ref(false)
const liteAnimations = shouldUseLiteAnimations()
const visibleTracks = computed(() => tracks.value)
// 低端机保留一定并发空间，避免长弹幕还没滑完就因为上限过低被后续弹幕挤掉。
const effectiveMaxItems = computed(() => (liteAnimations ? Math.min(props.maxItems, 2) : props.maxItems))
const effectiveLoopInterval = computed(() =>
  liteAnimations ? Math.max(props.loopInterval, 6000) : props.loopInterval,
)

let barrageInterval = null
let viewportObserver = null
let isPageVisible = typeof document === 'undefined' ? true : !document.hidden
let isInViewport = true

function barrageText(item) {
  const params = { nickname: item.nickname, prizeName: item.prizeName }
  return item.prizeType === 'GOLD' || item.prizeType === 'MONEY'
    ? t('barrage_won_prize', params)
    : t('barrage_won_the_prize', params)
}

function getBarrageStyle(item) {
  const isRTL = locale.value === 'ar'

  return {
    animationDuration: `${item.duration}s`,
    animationDelay: `${item.delay}s`,
    border: item.prizeType === 'MONEY' ? '1px solid #FFF1B2' : '1px solid #BAD0FF',
    background:
      item.prizeType === 'MONEY'
        ? 'linear-gradient(270deg, rgba(255, 222, 77, 0.65) 0%, rgba(117, 95, 0, 0.20) 93.75%)'
        : 'linear-gradient(270deg, rgba(103, 152, 255, 0.65) 0%, rgba(32, 77, 173, 0.20) 93.75%)',
    ...(isRTL
      ? {
          right: '0',
          left: 'auto',
          transform: 'translateX(-100vw)',
        }
      : {
          left: '0',
          right: 'auto',
          transform: 'translateX(100vw)',
        }),
  }
}

function generateBarrageProps(item) {
  const text = barrageText(item)

  return {
    text,
    duration: Math.max(8 - text.length * 0.2, 5) * (100 / props.speed),
    startPos: Math.floor(Math.random() * 21) - 10,
  }
}

function addToTrack(item) {
  const trackIndex = tracks.value.reduce(
    (minIndex, track, index) => (track.length < tracks.value[minIndex].length ? index : minIndex),
    0,
  )

  if (tracks.value[trackIndex].length < effectiveMaxItems.value) {
    tracks.value[trackIndex].push({
      ...item,
      id: idCounter.value++,
      delay: liteAnimations ? 0 : Math.random() * 4,
      ...generateBarrageProps(item),
    })
  }
}

function handleAnimationEnd(id) {
  tracks.value.forEach((track) => {
    const index = track.findIndex((item) => item.id === id)
    if (index !== -1) {
      track.splice(index, 1)
    }
  })
}

function getNextBarrage() {
  if (props.barrageList.length === 0) {
    return null
  }

  const item = props.barrageList[currentIndex.value]
  currentIndex.value = (currentIndex.value + 1) % props.barrageList.length
  return { ...item }
}

function canRunBarrage() {
  return !isBarragePaused.value && isPageVisible && isInViewport && props.barrageList.length > 0
}

function stopBarrage(clearTracks = false) {
  if (barrageInterval) {
    clearInterval(barrageInterval)
    barrageInterval = null
  }

  if (clearTracks) {
    tracks.value = [[], []]
  }
}

function startBarrage() {
  if (!canRunBarrage() || barrageInterval) {
    return
  }

  barrageInterval = setInterval(() => {
    const nextBarrage = getNextBarrage()
    if (nextBarrage) {
      addToTrack(nextBarrage)
    }
  }, effectiveLoopInterval.value)
}

function restartBarrage(clearTracks = false) {
  stopBarrage(clearTracks)
  startBarrage()
}

function pauseBarrage(clearTracks = false) {
  isBarragePaused.value = true
  stopBarrage(clearTracks)
}

function resumeBarrage() {
  isBarragePaused.value = false
  startBarrage()
}

function handleVisibilityChange() {
  isPageVisible = !document.hidden
  if (isPageVisible && isInViewport) {
    resumeBarrage()
    return
  }

  pauseBarrage(false)
}

function setupViewportObserver() {
  if (typeof IntersectionObserver === 'undefined' || !containerRef.value) {
    return
  }

  viewportObserver = new IntersectionObserver(
    ([entry]) => {
      isInViewport = entry?.isIntersecting !== false
      if (isInViewport && isPageVisible) {
        resumeBarrage()
        return
      }

      pauseBarrage(false)
    },
    { rootMargin: '80px 0px', threshold: 0 },
  )
  viewportObserver.observe(containerRef.value)
}

onMounted(() => {
  if (typeof document !== 'undefined') {
    document.addEventListener('visibilitychange', handleVisibilityChange)
  }

  setupViewportObserver()
  startBarrage()
})

onUnmounted(() => {
  stopBarrage(true)
  if (typeof document !== 'undefined') {
    document.removeEventListener('visibilitychange', handleVisibilityChange)
  }
  if (viewportObserver) {
    viewportObserver.disconnect()
    viewportObserver = null
  }
})

watch(
  [() => props.barrageList, () => locale.value],
  () => {
    currentIndex.value = 0
    if (props.barrageList.length === 0) {
      stopBarrage(true)
      return
    }

    restartBarrage(false)
  },
  { deep: false },
)
</script>

<style scoped>
.barrage-root {
  position: relative;
  width: 100%;
  height: 32vw;
  overflow: hidden;
  pointer-events: none;
}

.barrage-track {
  position: absolute;
  width: 100%;
  height: 50px;
}

.barrage-item {
  position: absolute;
  display: flex;
  align-items: center;
  gap: 4px;
  padding: 4px;
  border-radius: 26px;
  backdrop-filter: blur(1px);
  contain: layout paint style;
  will-change: transform;
  animation: moveLeft linear forwards;
}

.barrage-lite .barrage-item {
  will-change: auto;
}

.barrage-paused .barrage-item {
  animation-play-state: paused;
}

.barrage-avatar {
  width: 10vw;
  border-radius: 50%;
  display: block;
  aspect-ratio: 1/1;
  object-fit: cover;
}

.barrage-text {
  font-weight: 700;
  background-image: linear-gradient(180deg, #fff9a9 26.92%, #ed7d0a 52.08%, #fffab5 73.08%);
  background-clip: text;
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
}

@keyframes moveLeft {
  0% {
    transform: translateX(100vw);
  }

  100% {
    transform: translateX(-100%);
  }
}

[dir='rtl'] .barrage-item {
  animation: moveRight linear forwards;
}

@keyframes moveRight {
  0% {
    transform: translateX(-100vw);
  }

  100% {
    transform: translateX(100%);
  }
}

@media screen and (max-width: 360px) {
  * {
    font-size: 10px;
  }
}

@media screen and (min-width: 360px) {
  * {
    font-size: 14px;
  }
}

@media screen and (min-width: 768px) {
  * {
    font-size: 24px;
  }
}

@media screen and (min-width: 1024px) {
  * {
    font-size: 32px;
  }
}
</style>
