<template>
  <view class="comment-item">
    <image class="c-avatar" :src="localComment.avatar" mode="aspectFill" />
    <view class="c-content-wrap">
      <view class="c-header">
        <view class="c-user-info">
          <text class="c-name">{{ localComment.name }}</text>
          <ActionBadge v-if="localComment.userAction" :action="localComment.userAction" />
          <view class="c-badge" v-if="localComment.badge">
            <text class="b-icon">{{ localComment.badgeIcon }}</text>
            <text class="b-text">{{ localComment.badge }}</text>
          </view>
        </view>
        <view class="c-like" @tap="handleLike()">
          <text class="like-icon" :class="{ 'is-liked': localComment.isLiked }"></text>
          <text class="like-count" :class="{ 'liked-text': localComment.isLiked }">{{ localComment.likes }}</text>
        </view>
      </view>

      <text class="c-time">{{ localComment.time }}</text>
      <text class="c-text">{{ localComment.content }}</text>

      <view class="c-actions">
        <text class="c-action-btn" @tap="emitReply(localComment)">回复</text>
        <text v-if="localComment.replyCount" class="c-action-count">{{ localComment.replyCount }} 条回复</text>
      </view>

      <view v-if="localComment.replies && localComment.replies.length" class="reply-panel">
        <view
          v-for="reply in localComment.replies"
          :key="reply.id"
          class="reply-item"
        >
          <image class="reply-avatar" :src="reply.avatar" mode="aspectFill" />
          <view class="reply-main">
            <view class="reply-head">
              <view class="reply-user-wrap">
                <text class="reply-name">{{ reply.name }}</text>
                <ActionBadge v-if="reply.userAction" :action="reply.userAction" />
              </view>
              <view class="c-like reply-like" @tap="handleLike(reply)">
                <text class="like-icon reply-like-icon" :class="{ 'is-liked': reply.isLiked }"></text>
                <text class="like-count" :class="{ 'liked-text': reply.isLiked }">{{ reply.likes }}</text>
              </view>
            </view>

            <text class="reply-time">{{ reply.time }}</text>
            <text class="reply-text">
              <text v-if="reply.replyToName" class="reply-at">@{{ reply.replyToName }} </text>{{ reply.content }}
            </text>

            <view class="reply-footer">
              <text class="reply-btn" @tap="emitReply(reply)">回复</text>
            </view>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { computed, ref, watch } from 'vue';
import ActionBadge from "@/components/ActionBadge/ActionBadge.vue";
import { topicItemCommentLike } from "@/api/topicItem";
import { useUserStore } from "@/stores/user";

const props = defineProps({
  comment: {
    type: Object,
    required: true,
    default: () => ({})
  }
});

const emit = defineEmits(['need-login', 'like-change', 'reply']);
const userStore = useUserStore();
const isLoggedIn = computed(() => !!userStore.token || !!userStore.userInfo?.nickName);

const buildReplyItem = (reply = {}) => ({
  ...reply,
  id: reply.id || '',
  name: reply.name || '匿名用户',
  avatar: reply.avatar || 'https://api.dicebear.com/7.x/avataaars/svg?seed=fallback',
  time: reply.time || '刚刚',
  content: reply.content || '',
  likes: Number(reply.likes || 0),
  isLiked: !!reply.isLiked,
  replyToName: reply.replyToName || '',
  parentCommentId: reply.parentCommentId || '',
  replyToCommentId: reply.replyToCommentId || '',
  userAction: reply.userAction || ''
});

const buildCommentState = (comment = {}) => ({
  ...comment,
  likes: Number(comment.likes || 0),
  isLiked: !!comment.isLiked,
  replyCount: Number(comment.replyCount || 0),
  replies: Array.isArray(comment.replies) ? comment.replies.map(buildReplyItem) : []
});

const localComment = ref(buildCommentState(props.comment));
const likingMap = ref({});

watch(
  () => props.comment,
  (newVal) => {
    localComment.value = buildCommentState(newVal || {});
  },
  { deep: true }
);

const emitReply = (target) => {
  emit('reply', {
    rootCommentId: localComment.value.id,
    parentCommentId: target.id === localComment.value.id ? localComment.value.id : (target.parentCommentId || localComment.value.id),
    replyToCommentId: target.id,
    replyToName: target.name,
    content: target.content
  });
};

const patchLikeState = (targetId, updater) => {
  if (targetId === localComment.value.id) {
    localComment.value = {
      ...localComment.value,
      ...updater(localComment.value)
    };
    return;
  }

  localComment.value = {
    ...localComment.value,
    replies: localComment.value.replies.map((reply) => {
      if (reply.id !== targetId) return reply;
      return {
        ...reply,
        ...updater(reply)
      };
    })
  };
};

const handleLike = async (target = null) => {
  if (!isLoggedIn.value) {
    emit('need-login');
    return;
  }

  const currentTarget = target || localComment.value;
  if (!currentTarget?.id || likingMap.value[currentTarget.id]) return;

  likingMap.value = {
    ...likingMap.value,
    [currentTarget.id]: true
  };

  const nextLiked = !currentTarget.isLiked;
  const nextLikes = nextLiked ? currentTarget.likes + 1 : Math.max(0, currentTarget.likes - 1);

  patchLikeState(currentTarget.id, () => ({
    isLiked: nextLiked,
    likes: nextLikes
  }));

  if (nextLiked) {
    uni.vibrateShort({ type: 'light' });
  }

  emit('like-change', {
    id: currentTarget.id,
    parentId: currentTarget.id === localComment.value.id ? '' : localComment.value.id,
    isReply: currentTarget.id !== localComment.value.id,
    isLiked: nextLiked,
    likes: nextLikes
  });

  try {
    await topicItemCommentLike({ commentId: currentTarget.id });
    uni.$trackRecord({
      eventName: 'like_comment',
      eventType: 'like',
      elementId: `comment_${currentTarget.id}`,
      elementContent: `评论项_${currentTarget.name}`,
      customParams: {
        comment: currentTarget.content,
        isReply: currentTarget.id !== localComment.value.id,
        page: 'rating_detail'
      }
    });
  } catch (error) {
    patchLikeState(currentTarget.id, () => ({
      isLiked: currentTarget.isLiked,
      likes: currentTarget.likes
    }));
    emit('like-change', {
      id: currentTarget.id,
      parentId: currentTarget.id === localComment.value.id ? '' : localComment.value.id,
      isReply: currentTarget.id !== localComment.value.id,
      isLiked: currentTarget.isLiked,
      likes: currentTarget.likes
    });
    uni.showToast({ title: '操作失败', icon: 'none' });
  } finally {
    const nextMap = { ...likingMap.value };
    delete nextMap[currentTarget.id];
    likingMap.value = nextMap;
  }
};
</script>

<style lang="scss" scoped>
.comment-item {
  display: flex;
  padding: 32rpx 0;
  position: relative;
  transition: background-color 0.2s;
}

.comment-item:active {
  background-color: #fafbfe;
}

.comment-item::after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 104rpx; /* 头像宽度(80) + 间距(24) */
  right: 0;
  height: 2rpx;
  background-color: #f0f2f7;
}

.c-avatar {
  width: 80rpx;
  height: 80rpx;
  border-radius: 50%;
  margin-right: 24rpx;
  background-color: #f5f6fa;
  flex-shrink: 0;
  border: 2rpx solid #f0f2f7;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.03);
}

.c-content-wrap {
  flex: 1;
}

.c-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 8rpx;
}

.c-user-info {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
}

.c-name {
  font-size: 30rpx;
  font-weight: 700; /* 减轻字重，显得更精致 */
  color: #1a1a1a;
  margin-right: 12rpx;
  font-family: -apple-system, BlinkMacSystemFont, 'Helvetica Neue', Helvetica, Segoe UI, Arial, Roboto, sans-serif;
}

.c-badge {
  display: flex;
  align-items: center;
  background: linear-gradient(90deg, #f5f6fa, #f0f2f7);
  padding: 4rpx 16rpx;
  border-radius: 100rpx;
  margin-left: 12rpx;
}

.b-icon { font-size: 20rpx; margin-right: 6rpx; }
.b-text { font-size: 20rpx; color: #666; font-weight: bold; }

.c-like {
  display: flex;
  align-items: center;
  color: #999;
  font-size: 24rpx;
  font-weight: 600;
  padding: 8rpx;
  margin: -8rpx; /* 增加点击区域 */
}

.like-icon {
  width: 32rpx;
  height: 32rpx;
  background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='%23999' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpath d='M14 9V5a3 3 0 0 0-3-3l-4 9v11h11.28a2 2 0 0 0 2-1.7l1.38-9a2 2 0 0 0-2-2.3zM7 22H4a2 2 0 0 1-2-2v-7a2 2 0 0 1 2-2h3'%3E%3C/path%3E%3C/svg%3E");
  background-size: cover;
  margin-right: 8rpx;
  transition: all 0.3s cubic-bezier(0.175, 0.885, 0.32, 1.275);
}

.like-icon.is-liked {
  background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='%23ff4d4f' stroke='%23ff4d4f' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpath d='M14 9V5a3 3 0 0 0-3-3l-4 9v11h11.28a2 2 0 0 0 2-1.7l1.38-9a2 2 0 0 0-2-2.3zM7 22H4a2 2 0 0 1-2-2v-7a2 2 0 0 1 2-2h3'%3E%3C/path%3E%3C/svg%3E");
  transform: scale(1.15);
}

.liked-text {
  color: #ff4d4f;
}

.c-like:active .like-icon {
  transform: scale(0.9);
}

.c-time {
  font-size: 22rpx;
  color: #a1a1a1;
  display: block;
  margin-bottom: 16rpx;
}

.c-text {
  font-size: 30rpx;
  color: #2c2c2c;
  line-height: 1.65;
  word-break: break-all;
}

.c-actions {
  display: flex;
  align-items: center;
  gap: 20rpx;
  margin-top: 16rpx;
}

.c-action-btn,
.reply-btn,
.c-action-count {
  font-size: 22rpx;
  color: #8b8f98;
}

.c-action-btn,
.reply-btn {
  font-weight: 600;
}

.reply-panel {
  margin-top: 20rpx;
  padding: 18rpx 18rpx 8rpx;
  border-radius: 24rpx;
  background: linear-gradient(180deg, #f6f7fb 0%, #f9fafc 100%);
}

.reply-item {
  display: flex;
  gap: 16rpx;
  padding-bottom: 18rpx;
}

.reply-avatar {
  width: 56rpx;
  height: 56rpx;
  border-radius: 50%;
  flex-shrink: 0;
  background: #eceff5;
}

.reply-main {
  flex: 1;
  min-width: 0;
}

.reply-head {
  display: flex;
  align-items: flex-start;
  justify-content: space-between;
  gap: 16rpx;
}

.reply-user-wrap {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 8rpx;
}

.reply-name {
  font-size: 24rpx;
  font-weight: 700;
  color: #111827;
}

.reply-time {
  display: block;
  margin: 6rpx 0 10rpx;
  font-size: 20rpx;
  color: #9ca3af;
}

.reply-text {
  font-size: 24rpx;
  line-height: 1.7;
  color: #30343b;
  word-break: break-all;
}

.reply-at {
  color: #4f46e5;
  font-weight: 600;
}

.reply-footer {
  margin-top: 10rpx;
}

.reply-like {
  margin: 0;
  padding: 0;
}

.reply-like-icon {
  width: 28rpx;
  height: 28rpx;
}
</style>
