<!-- 告白墙弹幕 -->
<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;
          padding: 8px;
          display: flex;
          align-items: center;
          gap: 2vw;
          border-radius: 999px;
          border: 2px solid #fff;
          box-sizing: border-box;
          background: rgba(255, 255, 255, 0.28);
          backdrop-filter: blur(8px);
          -webkit-backdrop-filter: blur(8px);
        "
        :style="getBarrageStyle(item)"
        @animationend="handleAnimationEnd(item.id)"
      >
        <div
          class="avatar-pair"
          style="position: relative; display: flex; align-items: center; gap: 2vw"
        >
          <div
            v-if="!liteAnimations"
            class="couple-sign"
            style="
              position: absolute;
              inset: 0;
              display: flex;
              justify-content: center;
              align-items: center;
            "
          >
            <img
              v-smart-img
              :src="webpUrl('GeminiCoupleSign')"
              alt=""
              class="couple-sign-img"
              style="width: 5vw; display: block; object-fit: cover"
            />
          </div>

          <img
            :src="item.senderAvatar || ''"
            alt=""
            class="barrage-avatar"
            style="
              width: 8vw;
              border-radius: 50%;
              display: block;
              aspect-ratio: 1/1;
              object-fit: cover;
            "
            loading="lazy"
            decoding="async"
            @error="handleAvatarImageError"
          />
          <img
            :src="item.receiverAvatar || ''"
            alt=""
            class="barrage-avatar"
            style="
              width: 8vw;
              border-radius: 50%;
              display: block;
              aspect-ratio: 1/1;
              object-fit: cover;
            "
            loading="lazy"
            decoding="async"
            @error="handleAvatarImageError"
          />
        </div>

        <div style="white-space: nowrap; font-size: 1.2em; font-weight: 600; color: #2f1d89">
          {{ item.content }}
        </div>
      </div>
    </div>
  </div>
</template>

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

const { locale } = useI18n()

const webpUrl = (filename) => getWebpUrl('Ranking/Couple/webp/', filename)

const props = defineProps({
  barrageList: {
    type: Array,
    required: true,
    default: () => [],
  },
  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 getBarrageStyle(item) {
  const isRTL = locale.value === 'ar'

  return {
    animationDuration: `${item.duration}s`,
    animationDelay: `${item.delay}s`,
    ...(isRTL
      ? {
          right: '0',
          left: 'auto',
          transform: 'translateX(-100vw)',
        }
      : {
          left: '0',
          right: 'auto',
          transform: 'translateX(100vw)',
        }),
  }
}

function generateBarrageProps(item) {
  const textLength = String(item.content || '').length

  return {
    duration: Math.min(5 + textLength * 0.1, 10),
    startPos: 0,
  }
}

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: 0,
      ...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,
  () => {
    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: 2vw;
  box-sizing: border-box;
  padding: 8px;
  border: 2px solid #fff;
  border-radius: 999px;
  background: rgba(255, 255, 255, 0.28);
  backdrop-filter: blur(8px);
  -webkit-backdrop-filter: blur(8px);
  contain: layout paint style;
  will-change: transform;
  animation: moveLeft linear forwards;
}

.barrage-lite .barrage-item {
  gap: 1vw;
  padding: 6px;
  will-change: auto;
}

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

.avatar-pair {
  position: relative;
  display: flex;
  align-items: center;
  gap: 2vw;
}

.couple-sign {
  position: absolute;
  inset: 0;
  display: flex;
  justify-content: center;
  align-items: center;
}

.couple-sign-img {
  width: 5vw;
  display: block;
  object-fit: cover;
}

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

@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>
