<section
  th:fragment="recent-comments-widget"
  class="widget"
  th:with="
    commentsTitle=${item.comments_title ?: '最新评论'},
    commentsCount=${T(java.lang.Integer).parseInt(item.count ?: '5')},
    showReplies=${item.show_replies != null ? item.show_replies : true},
    replyCount=${T(java.lang.Integer).parseInt(item.reply_count ?: '3')},
    showAvatar=${item.show_avatar != null ? item.show_avatar : true},
    commentProvider=${theme.config.comment?.provider ?: 'halo'},
    twikooEnvId=${theme.config.comment?.twikoo?.env_id ?: ''},
    twikooCustomUrl=${theme.config.comment?.twikoo?.custom_js_url ?: '/themes/theme-clarity/assets/libs/twikoo/twikoo.min.js'}
  "
>
  <hgroup class="widget-title">
    <span class="title-text text-creative" th:text="${commentsTitle}">最新评论</span>
  </hgroup>
  <div class="widget-body widget-card recent-comments-widget">
    <!-- Halo 原生评论 -->
    <th:block th:if="${commentProvider == 'halo'}">
      <th:block th:with="comments = ${commentFinder.list(null, 1, commentsCount)}">
        <ul
          class="recent-comments-list"
          th:if="${not #lists.isEmpty(comments.items)}"
          th:data-max-length="50"
          th:data-show-replies="${showReplies}"
          th:data-reply-count="${replyCount}"
        >
          <li
            th:each="comment : ${comments.items}"
            class="recent-comment-item"
            th:data-comment-name="${comment.metadata.name}"
          >
            <div class="comment-header">
              <div class="comment-author-info">
                <img
                  th:if="${showAvatar and comment.owner != null and not #strings.isEmpty(comment.owner.avatar)}"
                  class="comment-avatar-img"
                  th:src="${comment.owner.avatar}"
                  th:alt="${comment.owner.displayName}"
                  loading="lazy"
                />
                <span
                  th:if="${showAvatar and (comment.owner == null or #strings.isEmpty(comment.owner.avatar))}"
                  class="comment-avatar-text"
                  th:text="${#strings.substring(comment.owner != null and not #strings.isEmpty(comment.owner.displayName) ? comment.owner.displayName : (comment.spec.owner != null ? comment.spec.owner.displayName : '匿名'), 0, 1)}"
                  >匿</span
                >
                <span
                  class="comment-author"
                  th:text="${comment.owner != null and not #strings.isEmpty(comment.owner.displayName) ? comment.owner.displayName : (comment.spec.owner != null ? comment.spec.owner.displayName : '匿名')}"
                  >评论者</span
                >
              </div>
              <time
                class="comment-time"
                th:datetime="${comment.metadata.creationTimestamp}"
                th:text="${#temporals.format(comment.metadata.creationTimestamp, 'MM-dd HH:mm')}"
                >时间</time
              >
            </div>
            <th:block th:if="${comment.spec.subjectRef != null}">
              <th:block th:if="${comment.spec.subjectRef.kind == 'SinglePage'}">
                <th:block th:with="singlePage = ${singlePageFinder.getByName(comment.spec.subjectRef.name)}">
                  <a class="comment-link" th:href="${singlePage.status.permalink} + '#comment'">
                    <script type="text/plain" class="comment-raw-content" th:utext="${comment.spec.content}"></script>
                    <div class="comment-content"></div>
                  </a>
                </th:block>
              </th:block>
              <th:block th:if="${comment.spec.subjectRef.kind == 'Post'}">
                <th:block th:with="post = ${postFinder.getByName(comment.spec.subjectRef.name)}">
                  <a class="comment-link" th:href="${post.status.permalink} + '#comment'">
                    <script type="text/plain" class="comment-raw-content" th:utext="${comment.spec.content}"></script>
                    <div class="comment-content"></div>
                  </a>
                </th:block>
              </th:block>
              <th:block th:if="${comment.spec.subjectRef.kind == 'Moment'}">
                <a class="comment-link" th:href="|/moments/${comment.spec.subjectRef.name}|+ '#comment'">
                  <script type="text/plain" class="comment-raw-content" th:utext="${comment.spec.content}"></script>
                  <div class="comment-content"></div>
                </a>
              </th:block>
              <!-- TODO 文档插件未完全适配评论插件 -->
              <th:block th:if="${comment.spec.subjectRef.kind == 'Doc'}">
                <a class="comment-link" href="/docs">
                  <script type="text/plain" class="comment-raw-content" th:utext="${comment.spec.content}"></script>
                  <div class="comment-content"></div>
                </a>
              </th:block>
              <!-- 图库照片评论 -->
              <th:block th:if="${comment.spec.subjectRef.kind == 'Photo'}">
                <a class="comment-link" th:href="|/photos/${comment.spec.subjectRef.name}| + '#comment'">
                  <script type="text/plain" class="comment-raw-content" th:utext="${comment.spec.content}"></script>
                  <div class="comment-content"></div>
                </a>
              </th:block>
              <!-- TODO 友链插件未适配评论插件 -->
              <th:block th:if="${comment.spec.subjectRef.kind == 'Plugin'}">
                <a class="comment-link" th:href="@{/links}+ '#comment'">
                  <script type="text/plain" class="comment-raw-content" th:utext="${comment.spec.content}"></script>
                  <div class="comment-content"></div>
                </a>
              </th:block>
            </th:block>
            <th:block th:if="${comment.spec.subjectRef == null}">
              <div class="comment-content-wrapper">
                <script type="text/plain" class="comment-raw-content" th:utext="${comment.spec.content}"></script>
                <div class="comment-content"></div>
              </div>
            </th:block>
            <div class="comment-replies" th:if="${showReplies and comment.status.replyCount > 0}">
              <th:block th:with="replies = ${commentFinder.listReply(comment.metadata.name, 1, replyCount)}">
                <div th:each="reply : ${replies.items}" class="reply-item">
                  <img
                    th:if="${showAvatar and reply.owner != null and not #strings.isEmpty(reply.owner.avatar)}"
                    class="reply-avatar-img"
                    th:src="${reply.owner.avatar}"
                    th:alt="${reply.owner.displayName}"
                    loading="lazy"
                  />
                  <span
                    th:if="${showAvatar and (reply.owner == null or #strings.isEmpty(reply.owner.avatar))}"
                    class="reply-avatar-text"
                    th:text="${#strings.substring(reply.owner != null and not #strings.isEmpty(reply.owner.displayName) ? reply.owner.displayName : (reply.spec.owner != null ? reply.spec.owner.displayName : '匿名'), 0, 1)}"
                    >匿</span
                  >
                  <span
                    class="reply-author"
                    th:text="${reply.owner != null and not #strings.isEmpty(reply.owner.displayName) ? reply.owner.displayName : (reply.spec.owner != null ? reply.spec.owner.displayName : '匿名')}"
                    >回复者</span
                  >
                  <script type="text/plain" class="reply-raw-content" th:utext="${reply.spec.content}"></script>
                  <span class="reply-content"></span>
                </div>
              </th:block>
            </div>
          </li>
        </ul>
        <div th:if="${#lists.isEmpty(comments.items)}" class="empty-tip">
          <span class="icon-[ph--chat-circle-dots-bold]"></span>
          暂无评论
        </div>
      </th:block>
    </th:block>

    <!-- Twikoo 评论 -->
    <th:block th:if="${commentProvider == 'twikoo' and not #strings.isEmpty(twikooEnvId)}">
      <ul
        class="recent-comments-list twikoo-recent-comments"
        th:data-env-id="${twikooEnvId}"
        th:data-page-size="${commentsCount}"
        th:data-max-length="50"
        th:data-show-avatar="${showAvatar}"
      >
        <!-- 内容由 JavaScript 动态加载 -->
      </ul>
      <div class="empty-tip twikoo-empty-tip" style="display: none">
        <span class="icon-[ph--chat-circle-dots-bold]"></span>
        暂无评论
      </div>
      <div class="twikoo-loading-tip">
        <span class="loading-spinner"></span>
        加载中...
      </div>
    </th:block>

    <!-- Twikoo 未配置提示 -->
    <th:block th:if="${commentProvider == 'twikoo' and #strings.isEmpty(twikooEnvId)}">
      <div class="empty-tip">
        <span class="icon-[ph--warning-bold]"></span>
        Twikoo 未配置
      </div>
    </th:block>

    <script>
      (function () {
        const widget = document.querySelector(".recent-comments-widget");
        if (!widget) return;

        const list = widget.querySelector(".recent-comments-list");
        if (!list) return;

        // Halo 原生评论处理
        if (!list.classList.contains("twikoo-recent-comments")) {
          const maxLength = parseInt(list.dataset.maxLength || "50", 10);
          const parser = new DOMParser();

          const run = () => {
            const items = list.querySelectorAll(".recent-comment-item");
            items.forEach((item) => {
              // 处理评论内容
              const rawScript = item.querySelector(".comment-raw-content");
              const contentDiv = item.querySelector(".comment-content");
              if (rawScript && contentDiv) {
                const raw = rawScript.textContent || rawScript.innerText || "";
                if (raw) {
                  const doc = parser.parseFromString(raw, "text/html");
                  let text = doc.body.textContent || doc.body.innerText || "";
                  text = text.trim();
                  if (text.length > maxLength) {
                    text = text.substring(0, maxLength) + "...";
                  }
                  contentDiv.textContent = text;
                }
              }

              // 处理回复内容
              const replyItems = item.querySelectorAll(".reply-item");
              replyItems.forEach((replyItem) => {
                const replyRawScript = replyItem.querySelector(".reply-raw-content");
                const replyContentSpan = replyItem.querySelector(".reply-content");
                if (replyRawScript && replyContentSpan) {
                  const raw = replyRawScript.textContent || replyRawScript.innerText || "";
                  if (raw) {
                    const doc = parser.parseFromString(raw, "text/html");
                    let text = doc.body.textContent || doc.body.innerText || "";
                    text = text.trim();
                    if (text.length > 30) {
                      text = text.substring(0, 30) + "...";
                    }
                    replyContentSpan.textContent = text;
                  }
                }
              });
            });
          };

          window.requestIdleCallback ? requestIdleCallback(run) : run();
          return;
        }

        // Twikoo 评论处理
        const envId = list.dataset.envId;
        const pageSize = parseInt(list.dataset.pageSize || "5", 10);
        const maxLength = parseInt(list.dataset.maxLength || "50", 10);
        const showAvatar = list.dataset.showAvatar === "true";
        const loadingTip = widget.querySelector(".twikoo-loading-tip");
        const emptyTip = widget.querySelector(".twikoo-empty-tip");

        const loadTwikooComments = async () => {
          try {
            // 动态加载 Twikoo JS
            await new Promise((resolve, reject) => {
              if (window.twikoo && window.twikoo.getRecentComments) {
                resolve();
                return;
              }
              const script = document.createElement("script");
              script.src = "[[${twikooCustomUrl}]]";
              script.async = true;
              script.onload = () => resolve();
              script.onerror = () => reject(new Error("Twikoo 脚本加载失败"));
              document.head.appendChild(script);
            });

            const comments = await window.twikoo.getRecentComments({
              envId: envId,
              pageSize: pageSize,
              includeReply: false,
            });

            if (loadingTip) {
              loadingTip.style.display = "none";
            }

            if (!comments || comments.length === 0) {
              if (emptyTip) {
                emptyTip.style.display = "flex";
              }
              return;
            }

            comments.forEach((comment) => {
              const li = document.createElement("li");
              li.className = "recent-comment-item";

              // 格式化时间
              const date = new Date(comment.created);
              const timeStr = `${String(date.getMonth() + 1).padStart(2, "0")}-${String(date.getDate()).padStart(2, "0")} ${String(date.getHours()).padStart(2, "0")}:${String(date.getMinutes()).padStart(2, "0")}`;

              // 使用 commentText 纯文本内容，无需手动去除 HTML
              let contentText = comment.commentText || "";
              contentText = contentText.trim();
              if (contentText.length > maxLength) {
                contentText = contentText.substring(0, maxLength) + "...";
              }

              // 构建评论链接
              const commentUrl = comment.url ? `${comment.url}#${comment.id}` : "#";

              // 头像（0.2.9+）
              let avatarHtml = "";
              if (showAvatar) {
                if (comment.avatar) {
                  avatarHtml = `<img class="comment-avatar-img" src="${comment.avatar}" alt="${comment.nick || ""}" loading="lazy">`;
                } else {
                  const firstChar = (comment.nick || "匿名").charAt(0);
                  avatarHtml = `<span class="comment-avatar-text">${firstChar}</span>`;
                }
              }

              li.innerHTML = `
                <div class="comment-header">
                  <div class="comment-author-info">
                    ${avatarHtml}
                    <span class="comment-author">${comment.nick || "匿名"}</span>
                  </div>
                  <time class="comment-time" datetime="${comment.created}">${timeStr}</time>
                </div>
                <a class="comment-link" href="${commentUrl}">
                  <div class="comment-content">${contentText}</div>
                </a>
              `;

              list.appendChild(li);
            });

            // Swup 使用事件委托处理动态创建的链接，无需重新绑定
          } catch (error) {
            console.error("加载 Twikoo 最新评论失败:", error);
            if (loadingTip) {
              loadingTip.style.display = "none";
            }
            if (emptyTip) {
              emptyTip.style.display = "flex";
              emptyTip.innerHTML = '<span class="icon-[ph--warning-bold]"></span> 加载失败';
            }
          }
        };

        // 延迟加载 Twikoo 评论
        window.requestIdleCallback ? requestIdleCallback(loadTwikooComments) : setTimeout(loadTwikooComments, 100);
      })();
    </script>
  </div>
</section>
