<template>
  <view class="comment-section" :class="[`comment-section--${variant}`]">
    <view class="comment-header">
      <view v-if="showTabs" class="comment-tabs">
        <text
          v-for="tab in tabs"
          :key="tab.value"
          class="comment-tab"
          :class="{ active: currentTab === tab.value }"
          @tap="switchTab(tab.value)"
        >
          {{ tab.label }}
        </text>
      </view>
      <view v-else class="comment-title-wrap">
        <text class="comment-title">{{ sectionTitle }}</text>
      </view>

      <view v-if="pillValue" class="header-pill" :class="pillTone ? `header-pill--${pillTone}` : ''">
        <text v-if="pillLabel" class="header-pill-label">{{ pillLabel }}</text>
        <text class="header-pill-value">{{ pillValue }}</text>
      </view>
    </view>

    <view v-if="allowCompose" class="compose-card">
      <view class="compose-tip">
        <text class="compose-title">{{ composeTitle }}</text>
        <text v-if="composeDesc" class="compose-desc">{{ composeDesc }}</text>
      </view>
      <view class="compose-box">
        <input
          class="compose-input"
          v-model="commentText"
          :disabled="sending"
          :placeholder="composePlaceholder"
          placeholder-class="compose-placeholder"
          confirm-type="send"
          @confirm="submitMainComment"
        />
        <button
          class="compose-send"
          :class="{ disabled: sending || !commentText.trim() }"
          :disabled="sending || !commentText.trim()"
          @tap="submitMainComment"
        >
          {{ sending ? composeSendingText : composeButtonText }}
        </button>
      </view>
    </view>

    <view class="comment-list">
      <view v-if="loading && !comments.length" class="comment-state">
        <text class="comment-state-title">{{ loadingTitle }}</text>
        <text class="comment-state-desc">{{ loadingDesc }}</text>
      </view>

      <view v-else-if="loadError && !comments.length" class="comment-state">
        <text class="comment-state-title">{{ errorTitle }}</text>
        <text class="comment-state-desc">{{ loadError }}</text>
        <button class="comment-state-btn" @tap="refreshComments">重新加载</button>
      </view>

      <view v-else-if="!comments.length" class="comment-state comment-state--empty">
        <view v-if="showEmptyVisual" class="comment-empty-visual">
          <view class="comment-empty-orbit orbit-1"></view>
          <view class="comment-empty-orbit orbit-2"></view>
          <view class="comment-empty-core">
            <text class="comment-empty-emoji">{{ emptyEmoji }}</text>
          </view>
        </view>
        <text class="comment-state-title">{{ emptyTitle }}</text>
        <text class="comment-state-desc">{{ emptyDesc }}</text>
        <text v-if="emptyTip" class="comment-state-tip">{{ emptyTip }}</text>
      </view>

      <CommentItem
        v-for="comment in comments"
        :key="comment.id"
        :comment="comment"
        :like-handler="likeHandler"
        :page-name="pageName"
        @need-login="emitNeedLogin"
        @like-change="handleCommentLikeChange"
        @reply="openReplyPopup"
        @toggle-replies="handleToggleReplies"
        @more-replies="handleLoadMoreReplies"
      />
    </view>

    <view v-if="comments.length" class="comment-footer">
      <text v-if="loading" class="comment-footer-text">{{ footerLoadingText }}</text>
      <text
        v-else-if="hasMore && loadMoreMode === 'click'"
        class="comment-footer-link"
        @tap="loadComments()"
      >
        {{ footerMoreText }}
      </text>
      <text v-else-if="loadMoreMode === 'scroll'" class="comment-footer-text">{{ footerHintText }}</text>
      <text v-else class="comment-footer-text">{{ footerDoneText }}</text>
    </view>

    <view
      v-if="replyPopupVisible"
      class="reply-popup-mask"
      @tap="closeReplyPopup"
    ></view>
    <view
      v-if="replyPopupVisible"
      class="reply-popup"
      :style="{ bottom: `${replyKeyboardHeight}px` }"
    >
      <view class="reply-popup-header">
        <view class="reply-popup-user">
          <text class="reply-popup-label">回复</text>
          <text class="reply-popup-name">@{{ replyTarget?.replyToName || "Ta" }}</text>
        </view>
        <text class="reply-popup-close" @tap="closeReplyPopup">取消</text>
      </view>
      <view class="reply-popup-input-wrap">
        <input
          class="reply-popup-input"
          v-model="replyContent"
          :focus="replyInputFocus"
          :disabled="sendingReply"
          :adjust-position="false"
          confirm-type="send"
          :placeholder="replyPlaceholder"
          placeholder-class="reply-popup-placeholder"
          @confirm="submitReplyComment"
        />
        <button
          class="reply-popup-send"
          :class="{ disabled: sendingReply || !replyContent.trim() }"
          :disabled="sendingReply || !replyContent.trim()"
          @tap="submitReplyComment"
        >
          {{ sendingReply ? replySendingText : replyButtonText }}
        </button>
      </view>
    </view>
  </view>
</template>

<script setup>
import { computed, nextTick, ref, watch } from "vue";
import { onUnmounted } from "vue";
import CommentItem from "@/components/CommentItem/CommentItem.vue";
import { useUserStore } from "@/stores/user";

const defaultTabs = [
  { label: "最热", value: "hot" },
  { label: "最新", value: "new" },
];

const props = defineProps({
  requestKey: {
    type: String,
    default: "",
  },
  visible: {
    type: Boolean,
    default: true,
  },
  variant: {
    type: String,
    default: "topic",
  },
  sectionTitle: {
    type: String,
    default: "评论区",
  },
  showTabs: {
    type: Boolean,
    default: true,
  },
  tabs: {
    type: Array,
    default: () => defaultTabs,
  },
  allowCompose: {
    type: Boolean,
    default: false,
  },
  composeTitle: {
    type: String,
    default: "说说你的看法",
  },
  composeDesc: {
    type: String,
    default: "",
  },
  composePlaceholder: {
    type: String,
    default: "写下你的观点...",
  },
  composeButtonText: {
    type: String,
    default: "发布",
  },
  composeSendingText: {
    type: String,
    default: "发送中",
  },
  replyButtonText: {
    type: String,
    default: "发送",
  },
  replySendingText: {
    type: String,
    default: "发送中",
  },
  pageName: {
    type: String,
    default: "rating_detail",
  },
  pillLabel: {
    type: String,
    default: "",
  },
  pillValue: {
    type: String,
    default: "",
  },
  pillTone: {
    type: String,
    default: "",
  },
  loadingTitle: {
    type: String,
    default: "评论加载中...",
  },
  loadingDesc: {
    type: String,
    default: "正在拉取大家的观点",
  },
  errorTitle: {
    type: String,
    default: "评论加载失败",
  },
  errorFallbackText: {
    type: String,
    default: "网络开了点小差，稍后重试",
  },
  emptyTitle: {
    type: String,
    default: "还没有评论",
  },
  emptyDesc: {
    type: String,
    default: "来发第一条评论，带动一下讨论气氛",
  },
  emptyTip: {
    type: String,
    default: "",
  },
  emptyEmoji: {
    type: String,
    default: "💬",
  },
  showEmptyVisual: {
    type: Boolean,
    default: false,
  },
  footerLoadingText: {
    type: String,
    default: "加载中...",
  },
  footerMoreText: {
    type: String,
    default: "查看更多评论",
  },
  footerDoneText: {
    type: String,
    default: "没有更多评论了",
  },
  footerHintText: {
    type: String,
    default: "上拉加载更多",
  },
  loadMoreMode: {
    type: String,
    default: "click",
  },
  showSuccessToast: {
    type: Boolean,
    default: true,
  },
  mainSuccessText: {
    type: String,
    default: "评论已发布",
  },
  replySuccessText: {
    type: String,
    default: "回复已发送",
  },
  listHandler: {
    type: Function,
    required: true,
  },
  repliesHandler: {
    type: Function,
    required: true,
  },
  publishHandler: {
    type: Function,
    required: true,
  },
  normalizeComment: {
    type: Function,
    required: true,
  },
  likeHandler: {
    type: Function,
    default: null,
  },
});

const emit = defineEmits(["need-login", "published"]);
const userStore = useUserStore();

const comments = ref([]);
const currentTab = ref(defaultTabs[0].value);
const currentPage = ref(1);
const hasMore = ref(true);
const loading = ref(false);
const sending = ref(false);
const sendingReply = ref(false);
const loadError = ref("");
const commentText = ref("");
const replyTarget = ref(null);
const replyPopupVisible = ref(false);
const replyInputFocus = ref(false);
const replyContent = ref("");
const replyKeyboardHeight = ref(0);

let keyboardHeightListener = null;

const isLoggedIn = computed(() => !!userStore.token || !!userStore.userInfo?.nickName);
const replyPlaceholder = computed(() => {
  return replyTarget.value?.replyToName ? `回复 @${replyTarget.value.replyToName}...` : "写下你的回复";
});

const parseListResponse = (res) => {
  const source = res?.data || res || {};
  const rawList =
    source.list ||
    source.records ||
    res?.list ||
    res?.records ||
    (Array.isArray(source) ? source : []);
  return Array.isArray(rawList) ? rawList : [];
};

const resolveHasMore = (res, list, page) => {
  const data = res?.data || res || {};
  const hasNext = data?.hasNext ?? res?.hasNext;
  if (typeof hasNext === "boolean") return hasNext;

  const total = Number(data?.totalCount ?? data?.total ?? res?.totalCount ?? res?.total ?? 0);
  if (total > 0) {
    const safeSize = Math.max(list.length, 1);
    return page * safeSize < total;
  }

  const pages = Number(data?.pages || res?.pages || 0);
  if (pages > 0) return page < pages;

  return list.length > 0;
};

const emitNeedLogin = () => {
  emit("need-login");
};

const ensureLogin = () => {
  if (isLoggedIn.value) return true;
  emitNeedLogin();
  return false;
};

const resetState = () => {
  comments.value = [];
  currentPage.value = 1;
  hasMore.value = true;
  loading.value = false;
  sending.value = false;
  sendingReply.value = false;
  loadError.value = "";
  commentText.value = "";
  closeReplyPopup();
};

const patchCommentItem = (commentId, updater) => {
  comments.value = comments.value.map((comment) => {
    if (comment.id !== commentId) return comment;
    return updater(comment);
  });
};

const loadComments = async ({ reset = false } = {}) => {
  if (!props.visible || !props.requestKey || loading.value) return;
  if (!reset && !hasMore.value) return;

  const page = reset ? 1 : currentPage.value;

  try {
    loading.value = true;
    loadError.value = "";
    const res = await props.listHandler({
      page,
      orderBy: currentTab.value,
    });
    const list = parseListResponse(res);
    const normalized = list.map((item) => props.normalizeComment(item));

    comments.value = reset ? normalized : [...comments.value, ...normalized];
    hasMore.value = resolveHasMore(res, list, page);
    currentPage.value = page + 1;
  } catch (error) {
    loadError.value = props.errorFallbackText;
  } finally {
    loading.value = false;
  }
};

const refreshComments = async () => {
  currentPage.value = 1;
  hasMore.value = true;
  await loadComments({ reset: true });
};

const loadMoreComments = async () => {
  if (loading.value || !hasMore.value) return;
  await loadComments();
};

const switchTab = (tab) => {
  if (currentTab.value === tab) return;
  currentTab.value = tab;
  refreshComments();
};

const submitMainComment = async () => {
  if (!ensureLogin()) return;
  const content = commentText.value.trim();
  if (!content || sending.value) return;

  try {
    sending.value = true;
    await props.publishHandler({
      content,
      mode: "comment",
      replyTarget: null,
    });
    if (props.showSuccessToast) {
      uni.showToast({ title: props.mainSuccessText, icon: "none" });
    }
    commentText.value = "";
    emit("published", {
      mode: "comment",
      content,
      replyTarget: null,
    });
    await refreshComments();
  } catch (error) {
    uni.showToast({ title: "发布失败", icon: "none" });
  } finally {
    sending.value = false;
  }
};

const openReplyPopup = async (payload) => {
  if (!ensureLogin()) return;
  replyTarget.value = payload;
  replyPopupVisible.value = true;
  await nextTick();
  replyInputFocus.value = false;
  await nextTick();
  replyInputFocus.value = true;
};

const closeReplyPopup = () => {
  replyPopupVisible.value = false;
  replyInputFocus.value = false;
  replyContent.value = "";
  replyTarget.value = null;
  replyKeyboardHeight.value = 0;
};

const submitReplyComment = async () => {
  if (!ensureLogin()) return;
  const content = replyContent.value.trim();
  if (!content || !replyTarget.value || sendingReply.value) return;

  try {
    sendingReply.value = true;
    await props.publishHandler({
      content,
      mode: "reply",
      replyTarget: replyTarget.value,
    });
    if (props.showSuccessToast) {
      uni.showToast({ title: props.replySuccessText, icon: "none" });
    }
    const publishedReplyTarget = replyTarget.value;
    closeReplyPopup();
    emit("published", {
      mode: "reply",
      content,
      replyTarget: publishedReplyTarget,
    });
    await refreshComments();
  } catch (error) {
    uni.showToast({ title: "回复失败", icon: "none" });
  } finally {
    sendingReply.value = false;
  }
};

const loadReplies = async (comment, page = 1) => {
  if (!comment?.id) return;

  patchCommentItem(comment.id, (item) => ({
    ...item,
    repliesLoading: true,
  }));

  try {
    const res = await props.repliesHandler({
      rootCommentId: comment.id,
      page,
    });
    const list = parseListResponse(res);
    const normalizedReplies = list.map((reply) => props.normalizeComment(reply, comment));
    const hasMoreReplies = resolveHasMore(res, list, page);

    patchCommentItem(comment.id, (item) => ({
      ...item,
      repliesLoading: false,
      repliesLoaded: true,
      repliesPage: page,
      repliesHasMore: hasMoreReplies,
      replies: page === 1 ? normalizedReplies : [...(item.replies || []), ...normalizedReplies],
    }));
  } catch (error) {
    patchCommentItem(comment.id, (item) => ({
      ...item,
      repliesLoading: false,
    }));
    uni.showToast({ title: "加载回复失败", icon: "none" });
  }
};

const handleToggleReplies = (comment) => {
  if (comment.repliesLoading || comment.repliesLoaded) return;
  loadReplies(comment, 1);
};

const handleLoadMoreReplies = (comment) => {
  if (comment.repliesLoading || !comment.repliesHasMore) return;
  loadReplies(comment, Number(comment.repliesPage || 1) + 1);
};

const handleCommentLikeChange = ({ id, parentId, isReply, isLiked, likes }) => {
  comments.value = comments.value.map((item) => {
    if (!isReply && item.id !== id) return item;
    if (isReply && item.id !== parentId) return item;

    if (isReply) {
      return {
        ...item,
        replies: (item.replies || []).map((reply) => {
          if (reply.id !== id) return reply;
          return {
            ...reply,
            isLiked,
            likes,
          };
        }),
      };
    }

    return {
      ...item,
      isLiked,
      likes,
    };
  });
};

watch(
  () => [props.requestKey, props.visible],
  ([requestKey, visible]) => {
    if (!requestKey || !visible) {
      resetState();
      return;
    }
    currentPage.value = 1;
    hasMore.value = true;
    comments.value = [];
    loadComments({ reset: true });
  },
  { immediate: true }
);

if (uni.onKeyboardHeightChange) {
  keyboardHeightListener = (res) => {
    replyKeyboardHeight.value = res?.height || 0;
  };
  uni.onKeyboardHeightChange(keyboardHeightListener);
}

onUnmounted(() => {
  if (uni.offKeyboardHeightChange && keyboardHeightListener) {
    uni.offKeyboardHeightChange(keyboardHeightListener);
  }
});

defineExpose({
  refreshComments,
  loadMoreComments,
});
</script>

<style lang="scss" scoped>
.comment-section {
  padding: 32rpx;
  border-radius: 32rpx;
  background: rgba(255, 255, 255, 0.94);
  border: 2rpx solid rgba(229, 232, 246, 0.92);
  box-shadow: 0 18rpx 42rpx rgba(87, 92, 145, 0.08);
}

.comment-section--topic {
  margin-top: 0;
}

.comment-section--pk {
  margin-top: 24rpx;
}

.comment-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 20rpx;
  margin-bottom: 28rpx;
}

.comment-tabs {
  display: flex;
  gap: 34rpx;
}

.comment-title-wrap {
  display: flex;
  align-items: center;
}

.comment-title {
  font-size: 32rpx;
  font-weight: 800;
  color: #1f2432;
}

.comment-tab {
  font-size: 30rpx;
  color: #8a90a0;
  font-weight: 600;
  padding-bottom: 10rpx;
  position: relative;
}

.comment-tab.active {
  color: #1f2432;
  font-weight: 800;
}

.comment-tab.active::after {
  content: "";
  position: absolute;
  left: 50%;
  bottom: 0;
  transform: translateX(-50%);
  width: 28rpx;
  height: 6rpx;
  border-radius: 999rpx;
  background: linear-gradient(90deg, #6557ff, #4d44f1);
}

.header-pill {
  flex-shrink: 0;
  display: inline-flex;
  align-items: center;
  gap: 8rpx;
  padding: 10rpx 18rpx;
  border-radius: 999rpx;
  background: rgba(92, 67, 245, 0.1);
}

.header-pill--right {
  background: rgba(255, 141, 95, 0.12);
}

.header-pill-label {
  font-size: 22rpx;
  color: #8a90a0;
}

.header-pill-value {
  font-size: 22rpx;
  font-weight: 700;
  color: #4d44f1;
}

.header-pill--right .header-pill-value {
  color: #ff7a45;
}

.compose-card {
  margin-bottom: 28rpx;
  padding: 24rpx;
  border-radius: 24rpx;
  background: linear-gradient(135deg, rgba(92, 67, 245, 0.08), rgba(92, 67, 245, 0.03));
}

.compose-tip {
  margin-bottom: 18rpx;
}

.compose-title {
  display: block;
  font-size: 28rpx;
  font-weight: 800;
  color: #202433;
}

.compose-desc {
  display: block;
  margin-top: 8rpx;
  font-size: 22rpx;
  color: #7b8191;
}

.compose-box {
  display: flex;
  align-items: center;
  gap: 16rpx;
}

.compose-input {
  flex: 1;
  height: 84rpx;
  padding: 0 26rpx;
  border-radius: 24rpx;
  background: #ffffff;
  font-size: 28rpx;
  color: #1f2432;
  box-sizing: border-box;
}

.compose-placeholder {
  color: #a0a6b5;
}

.compose-send {
  min-width: 132rpx;
  height: 84rpx;
  line-height: 84rpx;
  margin: 0;
  padding: 0 24rpx;
  border-radius: 24rpx;
  background: linear-gradient(135deg, #6557ff, #4d44f1);
  color: #fff;
  font-size: 26rpx;
  font-weight: 700;
}

.compose-send.disabled {
  opacity: 0.45;
}

.compose-send::after,
.comment-state-btn::after,
.reply-popup-send::after {
  border: none;
}

.comment-list {
  display: flex;
  flex-direction: column;
  min-height: 200rpx;
}

.comment-state {
  min-height: 260rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  text-align: center;
  color: #999;
  padding: 36rpx 24rpx;
  border-radius: 24rpx;
  background: #f8f9ff;
}

.comment-state--empty {
  background: linear-gradient(180deg, rgba(248, 249, 255, 0.92) 0%, rgba(255, 255, 255, 0.96) 100%);
}

.comment-empty-visual {
  position: relative;
  width: 176rpx;
  height: 176rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 24rpx;
}

.comment-empty-core {
  position: relative;
  z-index: 2;
  width: 112rpx;
  height: 112rpx;
  border-radius: 50%;
  background: linear-gradient(135deg, #ffffff 0%, #eef2ff 100%);
  box-shadow: 0 16rpx 34rpx rgba(99, 102, 241, 0.14);
  display: flex;
  align-items: center;
  justify-content: center;
}

.comment-empty-emoji {
  font-size: 50rpx;
}

.comment-empty-orbit {
  position: absolute;
  border-radius: 50%;
  border: 2rpx dashed rgba(99, 102, 241, 0.16);
}

.orbit-1 {
  inset: 12rpx;
}

.orbit-2 {
  inset: 32rpx;
  border-style: solid;
  border-color: rgba(129, 140, 248, 0.12);
}

.comment-state-title {
  display: block;
  font-size: 30rpx;
  color: #232734;
  font-weight: 800;
  margin-bottom: 12rpx;
}

.comment-state-desc {
  display: block;
  font-size: 24rpx;
  color: #8a90a0;
  line-height: 1.7;
}

.comment-state-tip {
  display: block;
  margin-top: 12rpx;
  font-size: 22rpx;
  color: #a0a6b5;
  line-height: 1.7;
}

.comment-state-btn {
  margin-top: 22rpx;
  height: 72rpx;
  line-height: 72rpx;
  padding: 0 30rpx;
  border-radius: 999rpx;
  background: #111827;
  color: #fff;
  font-size: 24rpx;
}

.comment-footer {
  padding-top: 20rpx;
  text-align: center;
}

.comment-footer-text {
  font-size: 22rpx;
  color: #9ca3af;
}

.comment-footer-link {
  font-size: 22rpx;
  font-weight: 700;
  color: #4f46e5;
}

.reply-popup-mask {
  position: fixed;
  inset: 0;
  background: rgba(15, 23, 42, 0.24);
  z-index: 998;
}

.reply-popup {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 999;
  padding: 24rpx 24rpx calc(env(safe-area-inset-bottom) + 24rpx);
  background: #ffffff;
  border-radius: 28rpx 28rpx 0 0;
  box-shadow: 0 -12rpx 36rpx rgba(15, 23, 42, 0.12);
}

.reply-popup-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 20rpx;
  margin-bottom: 20rpx;
}

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

.reply-popup-label {
  font-size: 24rpx;
  color: #6b7280;
}

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

.reply-popup-close {
  font-size: 24rpx;
  color: #8b8f98;
}

.reply-popup-input-wrap {
  display: flex;
  align-items: center;
  gap: 16rpx;
}

.reply-popup-input {
  flex: 1;
  height: 84rpx;
  padding: 0 28rpx;
  border-radius: 24rpx;
  background: #f4f6fb;
  font-size: 28rpx;
  color: #1f2937;
  box-sizing: border-box;
}

.reply-popup-placeholder {
  color: #9ca3af;
}

.reply-popup-send {
  min-width: 132rpx;
  height: 84rpx;
  line-height: 84rpx;
  margin: 0;
  padding: 0 24rpx;
  border-radius: 24rpx;
  background: linear-gradient(135deg, #111827 0%, #374151 100%);
  color: #ffffff;
  font-size: 26rpx;
  font-weight: 700;
}

.reply-popup-send.disabled {
  opacity: 0.45;
}
</style>
