<template>
	<div class="msg-bubble">
		<div class="msg-bubble-header">
			<div class="header-icon">
				<!-- <img src="./image1.png" alt="" /> -->
				<img src="./message-icon.svg" alt="" />
			</div>
			<div class="header-title">
				<slot name="title">{{ "社交媒体" }}</slot>
			</div>
			<!-- <div class="more" @click="handleToMoreNews">{{ "更多 +" }}</div> -->
		</div>
		<div class="msg-bubble-main" ref="scrollContainer" @mouseenter="pauseScroll" @mouseleave="resumeScroll">
			<div class="message-bubble" v-for="(item, index) in infiniteList" :key="index" @click="handleClickPerson(item)">
				<div class="avatar-container">
					<img :src="item[props.imageUrl] || avatarUser" :alt="item[props.name]" class="avatar" />
					<div class="avatar-containerOne" v-if="isRepublicanParty">
						<img src="./image2.png" alt="" class="avatar-imageOne" />
					</div>
					<div class="avatar-containerTwo" v-if="isUnitedStatesSenate">
						<img src="./image3.png" alt="" class="avatar-imageTwo" />
					</div>
				</div>
				<div class="bubble-container">
					<div class="bubble">
						<div class="bubble-header">
							<span class="name">{{ item[props.name] }}</span>
							<span class="meta">{{ item[props.time] }} · {{ item[props.source] }}</span>
						</div>
						<div class="bubble-content">
							{{ item[props.content] }}
						</div>
						<div class="triangle"></div>
					</div>
				</div>
			</div>
		</div>
	</div>
</template>

<script setup>
import { ref, computed, watch, nextTick, onMounted, onBeforeUnmount, onUnmounted } from "vue";
import avatarUser from "@/assets/images/avatar_user.png";

const emit = defineEmits(["click", "info-click"]);
const props = defineProps({
	isRepublicanParty: {
		type: Boolean,
		default: false
	},
	isUnitedStatesSenate: {
		type: Boolean,
		default: false
	},
	messageList: {
		type: Array,
		default: () => []
	},
	imageUrl: {
		type: String,
		default: "imageUrl"
	},
	name: {
		type: String,
		default: "name"
	},
	time: {
		type: String,
		default: "time"
	},
	source: {
		type: String,
		default: "source"
	},
	content: {
		type: String,
		default: "content"
	}
});

const formattedTime = computed(index => {
	const date = new Date(index);
	if (isNaN(date.getTime())) {
		return index; // 如果不是有效日期，返回原值
	}
	const year = date.getFullYear();
	const month = String(date.getMonth() + 1).padStart(2, "0");
	const day = String(date.getDate());
	const hours = String(date.getHours()).padStart(2, "0");
	const minutes = String(date.getMinutes()).padStart(2, "0");
	const seconds = String(date.getSeconds()).padStart(2, "0");
	// return `${year}年${month}月${day}日 ${hours}:${minutes}:${seconds}`;
	return `${month}月${day}日 ${hours}:${minutes}`;
});

const handleClickPerson = item => {
	emit("person-click", item);
};
const handleInfoClick = item => {
	emit("info-click", item);
};
const handleToMoreNews = item => {
	emit("more-click", item);
};

const scrollContainer = ref(null)
let timer = null
const currentIndex = ref(0)
// const itemHeight = ref(80) // 每条消息的高度，需要根据实际调整

// 计算当前显示的消息列表（只显示固定数量的消息）
const displayList = computed(() => {
	if(props.messageList.length < 4) {
		return props.messageList
	}
	// 确保 messageList 存在且有数据
	if (!props.messageList || !Array.isArray(props.messageList) || props.messageList.length === 0) {
		return []
	}

	const list = []
	const totalLength = props.messageList.length

	for (let i = 0; i < 3; i++) {
		// 计算当前索引，确保不会超出数组长度
		const index = (currentIndex.value + i) % totalLength
		const item = props.messageList[index]

		// 确保 item 存在再添加到列表
		if (item) {
			list.push(item)
		}
	}

	return list
})


const scrollSpeed = ref(30)
const autoStart = ref(true)
const copyCount = ref(3)

// 创建无限列表（复制多份）
const infiniteList = computed(() => {
  if (!displayList.value || displayList.value.length === 0) return []
  
  const result = []
  for (let i = 0; i < copyCount.value; i++) {
    result.push(...displayList.value)
  }
  return result
})

// 状态
let animationId = null
let lastTimestamp = 0
let isPaused = ref(false)
let isScrolling = ref(false)

// 滚动动画函数（使用 requestAnimationFrame）
const scrollAnimation = (timestamp) => {
  if (!scrollContainer.value || isPaused.value) {
    if (!isPaused.value) {
      animationId = requestAnimationFrame(scrollAnimation)
    }
    return
  }

  if (!lastTimestamp) {
    lastTimestamp = timestamp
    animationId = requestAnimationFrame(scrollAnimation)
    return
  }

  // 计算时间差（秒）
  const deltaTime = Math.min(0.033, (timestamp - lastTimestamp) / 1000) // 限制最大33ms
  if (deltaTime <= 0) {
    lastTimestamp = timestamp
    animationId = requestAnimationFrame(scrollAnimation)
    return
  }

  const container = scrollContainer.value
  const scrollHeight = container.scrollHeight
  const clientHeight = container.clientHeight
  
  // 计算滚动步长
  const step = scrollSpeed.value * deltaTime
  let newScrollTop = container.scrollTop + step
  
  // 检查是否滚动到底部
  const maxScrollTop = scrollHeight - clientHeight
  
  if (newScrollTop >= maxScrollTop - 1) {
    // 到达底部，无缝跳转到顶部
    container.scrollTop = 0
    // 重置时间戳避免跳跃
    lastTimestamp = timestamp
  } else {
    container.scrollTop = newScrollTop
  }
  
  lastTimestamp = timestamp
  animationId = requestAnimationFrame(scrollAnimation)
}

// 开始滚动
const startScroll = () => {
  if (animationId) {
    cancelAnimationFrame(animationId)
    animationId = null
  }
  if (isPaused.value) return
  
  lastTimestamp = 0
  isScrolling.value = true
  animationId = requestAnimationFrame(scrollAnimation)
}

// 停止滚动
const stopScroll = () => {
  if (animationId) {
    cancelAnimationFrame(animationId)
    animationId = null
  }
  lastTimestamp = 0
  isScrolling.value = false
}

// 暂停滚动
const pauseScroll = () => {
  if (isPaused.value) return
  isPaused.value = true
  stopScroll()
}

// 恢复滚动
const resumeScroll = () => {
  if (!isPaused.value) return
  isPaused.value = false
  if (autoStart.value) {
    startScroll()
  }
}

// 重置滚动位置（可选方法）
const resetScrollPosition = () => {
  if (scrollContainer.value) {
    scrollContainer.value.scrollTop = 0
  }
}

// 监听 displayList 变化
watch(
  () => displayList.value,
  async (newVal, oldVal) => {
    if (newVal && newVal.length > 0) {
      await nextTick()
      // 如果列表内容变化，重置滚动位置并重新开始
      if (scrollContainer.value) {
        const wasPaused = isPaused.value
        stopScroll()
        scrollContainer.value.scrollTop = 0
        if (!wasPaused && autoStart.value) {
          isPaused.value = false
          startScroll()
        }
      }
    }
  },
  { deep: true, immediate: false }
)

// 监听 scrollSpeed 变化
watch(
  () => scrollSpeed.value,
  () => {
    if (isScrolling.value && !isPaused.value) {
      // 重新启动滚动以应用新速度
      stopScroll()
      startScroll()
    }
  }
)

// 组件挂载
onMounted(async () => {
  await nextTick()
  if (autoStart.value && displayList.value && displayList.value.length > 0) {
    startScroll()
  }
})

// 组件卸载
onUnmounted(() => {
  stopScroll()
})

</script>

<style lang="scss" scoped>
.msg-bubble {
	width: 792px;
	height: 450px;
	border-radius: 10px;
	box-shadow: 0 0 20px 0 rgba(25, 69, 130, 0.1);
	background: rgba(255, 255, 255, 1);
	border: 1px solid rgb(234, 236, 238);

	.msg-bubble-header {
		width: 792px;
		height: 48px;
		border-bottom: 1px solid rgb(234, 236, 238);
		display: flex;
		box-sizing: border-box;
		position: relative;

		.header-icon {
			margin-left: 18px;
			margin-top: 14px;
			width: 24px;
			height: 24px;

			img {
				width: 100%;
				height: 100%;
			}
		}

		.header-title {
			width: 100%;
			margin-top: 11px;
			margin-left: 18px;
			height: 26px;
			color: rgb(5, 95, 194);
			font-family: "Source Han Sans CN";
			font-size: 20px;
			font-weight: 700;
			line-height: 26px;
			letter-spacing: 0px;
		}

		.more {
			width: 50px;
			height: 24px;
			position: absolute;
			top: 12px;
			right: 27px;
			color: rgb(5, 95, 194);
			font-family: "Source Han Sans CN";
			font-size: 16px;
			font-weight: 400;
			line-height: 24px;
			cursor: pointer;
			text-align: right;
		}
	}

	.msg-bubble-main {
		height: 402px;
		overflow: hidden;
		box-sizing: border-box;
		padding-bottom: 8px;
		padding-left: 21px;
		padding-top: 23px;

		.message-bubble {
			display: flex;
			max-width: 740px;
			margin-bottom: 15px;
			transition: transform 2s ease;
			/* 可选：添加平滑动画 */

			.avatar-container {
				flex-shrink: 0;
				flex-grow: 0;
				flex: 0;
				width: 42px;
				height: 42px;
				margin-right: 14.5px;
				cursor: pointer;
				position: relative;

				.avatar-containerOne,
				.avatar-containerTwo {
					display: inline-block;
					position: absolute;
				}

				.avatar-containerOne {
					left: 2px;
					top: 29px;

					.avatar-imageOne {
						width: 20px;
						height: 20px;
					}
				}

				.avatar-containerTwo {
					right: 2px;
					top: 29px;

					.avatar-imageTwo {
						width: 20px;
						height: 20px;
					}
				}

				.avatar {
					width: 42px;
					height: 42px;
					border-radius: 50%;
					object-fit: cover;
				}
			}

			.bubble-container {
				flex: 1;
				position: relative;

				.bubble {
					background-color: rgba(246, 250, 255, 1);
					border-radius: 12px;
					padding: 12px 12px;
					position: relative;
					border: 1px solid rgba(231, 243, 255, 1);

					/* box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1); */
					.bubble-header {
						display: flex;
						justify-content: space-between;
						align-items: center;
						margin-bottom: 5px;

						.name {
							color: rgb(59, 65, 75);
							font-family: "Source Han Sans CN";
							font-size: 16px;
							font-weight: 700;
							line-height: 24px;
							letter-spacing: 1px;
							text-align: left;
						}

						.meta {
							color: rgb(95, 101, 108);
							font-family: "Source Han Sans CN";
							font-size: 16px;
							font-weight: 400;
							line-height: 30px;
							letter-spacing: 0px;
							text-align: right;
						}
					}

					.bubble-content {
						color: rgba(59, 65, 75, 1);
						font-family: "Source Han Sans CN";
						font-size: 16px;
						font-weight: 400;
						line-height: 24px;
						letter-spacing: 0px;
						text-align: justify;
					}

					.triangle {
						position: absolute;
						left: -9px;
						/* 向左偏移1px，给描边留出空间 */
						top: 15px;
						width: 0;
						height: 0;
						/* 外层：描边颜色的三角形（比内层大1px） */
						border-top: 9px solid transparent;
						border-bottom: 9px solid transparent;
						border-right: 9px solid rgb(231, 243, 255);
					}

					/* 内层：原有颜色的三角形，覆盖在外层上面，模拟描边效果 */
					.triangle::after {
						content: "";
						position: absolute;
						top: -8px;
						/* 向上偏移1px，对齐中心 */
						left: 1px;
						/* 向右偏移1px，露出外层的描边 */
						width: 0;
						height: 0;
						border-top: 8px solid transparent;
						border-bottom: 8px solid transparent;
						border-right: 8px solid rgba(246, 250, 255, 1);
					}
				}
			}
		}
	}
}

// .msg-bubble-main {
//   height: 400px; /* 设置固定高度 */
//   overflow: hidden;
//   position: relative;
// }

// .message-bubble {
//   transition: transform 0.3s ease; /* 可选：添加平滑动画 */
//   height: 80px; /* 固定每条消息高度 */
//   margin-bottom: 10px; /* 消息之间的间距 */
// }

/* 响应式设计 */
@media (max-width: 768px) {
	.message-bubble {
		max-width: 100%;
	}

	.bubble-header {
		flex-direction: column;
		align-items: flex-start;
	}

	.meta {
		margin-top: 4px;
	}
}
</style>
