/* ================================================================
   d 分享/栏目弹层
================================================================ */
document.addEventListener('DOMContentLoaded', function() {
  
  const shareButtons = document.querySelectorAll('.tags .tag');
  
  shareButtons.forEach(function(button) {
    if (button.textContent.trim() === '收藏分享') {
      
      button.style.cursor = 'pointer';
      
      button.addEventListener('click', function(e) {
        
        if (!button.hasAttribute('href')) {
          e.preventDefault();
          
          const isWechat = /MicroMessenger/i.test(navigator.userAgent);
          
          if (isWechat) {
            showWechatShareTip();
          } else {
            showShareUrl();
          }
        }
      });
    }
  });

  const categoryButtons = document.querySelectorAll('.tags .tag');
  
  categoryButtons.forEach(function(button) {
    if (button.textContent.trim() === '全部栏目') {
      
      button.style.cursor = 'pointer';
      
      button.addEventListener('click', function(e) {
        
        if (!button.hasAttribute('href')) {
          e.preventDefault();
          showCategoryPopup();
        }
      });
    }
  });
});


function showWechatShareTip() {
  
  if (document.querySelector('.share-overlay')) {
    return;
  }
  
  const overlay = document.createElement('div');
  overlay.className = 'share-overlay';
  overlay.style.cssText = `
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.7);
    z-index: 9999;
    display: flex;
    justify-content: center;
    align-items: center;
    flex-direction: column;
  `;
  
  const tipContainer = document.createElement('div');
  tipContainer.className = 'share-tip-container';
  tipContainer.style.cssText = `
    color: white;
    text-align: center;
    padding: 20px;
    max-width: 80%;
  `;
  
  const arrow = document.createElement('div');
  arrow.innerHTML = '↗&#65039;';
  arrow.style.cssText = `
    position: absolute;
    top: 20px;
    right: 40px;
    font-size: 40px;
    color: white;
  `;
  
  const tipText = document.createElement('p');
  tipText.textContent = '请点击微信右上角的···按钮，然后选择"收藏"或"转发给朋友"';
  tipText.style.cssText = `
    font-size: 16px;
    margin-bottom: 20px;
  `;
  
  const closeButton = document.createElement('button');
  closeButton.textContent = '我知道了';
  closeButton.style.cssText = `
    padding: 8px 16px;
    background-color: #07C160;
    color: white;
    border: none;
    border-radius: 4px;
    font-size: 14px;
    cursor: pointer;
  `;
  
  closeButton.addEventListener('click', function() {
    document.body.removeChild(overlay);
  });
  
  overlay.addEventListener('click', function(e) {
    if (e.target === overlay) {
      document.body.removeChild(overlay);
    }
  });
  
  tipContainer.appendChild(tipText);
  tipContainer.appendChild(closeButton);
  overlay.appendChild(arrow);
  overlay.appendChild(tipContainer);
  
  document.body.appendChild(overlay);
}


function showShareUrl() {
  
  if (document.querySelector('.share-overlay')) {
    return;
  }

  
  var WECHAT_DOMAIN = 'http://y.fzps.org';
  
  var currentUrl = window.location.href;
  var wechatUrl  = WECHAT_DOMAIN + window.location.pathname + window.location.search + window.location.hash;

  const overlay = document.createElement('div');
  overlay.className = 'share-overlay';
  overlay.style.cssText = `
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.7);
    z-index: 9999;
    display: flex;
    justify-content: center;
    align-items: center;
  `;
  
  const container = document.createElement('div');
  container.className = 'share-url-container';
  container.style.cssText = `
    background-color: white;
    padding: 20px;
    border-radius: 8px;
    max-width: 90%;
    width: 300px;
  `;
  
  const title = document.createElement('h3');
  title.textContent = '分享链接';
  title.style.cssText = `
    margin-top: 0;
    margin-bottom: 16px;
    font-size: 18px;
    text-align: center;
  `;
  
  const urlInput = document.createElement('input');
  urlInput.type = 'text';
  urlInput.value = currentUrl;
  urlInput.readOnly = true;
  urlInput.style.cssText = `
    width: 100%;
    padding: 8px;
    box-sizing: border-box;
    border: 1px solid #ccc;
    border-radius: 4px;
    margin-bottom: 16px;
  `;
  
  /* 复制按钮 */
  const copyButton = document.createElement('button');
  copyButton.textContent = '点此复制网址保存';
  copyButton.style.cssText = `
    width: 100%;
    padding: 10px;
    background-color: #1677ff;
    color: white;
    border: none;
    border-radius: 4px;
    font-size: 14px;
    cursor: pointer;
    margin-bottom: 10px;
  `;

  /* 专用复制 */
  const wechatCopyButton = document.createElement('button');
  wechatCopyButton.textContent = '点此复制微信可用网址';
  wechatCopyButton.style.cssText = `
    width: 100%;
    padding: 10px;
    background-color: #e53935;
    color: white;
    border: none;
    border-radius: 4px;
    font-size: 14px;
    cursor: pointer;
    margin-bottom: 10px;
  `;

  const closeButton = document.createElement('button');
  closeButton.textContent = '关闭';
  closeButton.style.cssText = `
    width: 100%;
    padding: 10px;
    background-color: #f5f5f5;
    color: #333;
    border: none;
    border-radius: 4px;
    font-size: 14px;
    cursor: pointer;
  `;

  /* 通用复制函数 */
  function copyText(text, btn, successMsg, resetMsg, resetDelay) {
    /* 优先用现代 Clipboard API，降级用 execCommand */
    if (navigator.clipboard && navigator.clipboard.writeText) {
      navigator.clipboard.writeText(text).then(function() {
        btn.textContent = successMsg;
        setTimeout(function() { btn.textContent = resetMsg; }, resetDelay);
      }).catch(function() { fallbackCopy(text, btn, successMsg, resetMsg, resetDelay); });
    } else {
      fallbackCopy(text, btn, successMsg, resetMsg, resetDelay);
    }
  }
  function fallbackCopy(text, btn, successMsg, resetMsg, resetDelay) {
    var tmp = document.createElement('input');
    tmp.value = text;
    tmp.style.cssText = 'position:fixed;top:-9999px;left:-9999px;opacity:0';
    document.body.appendChild(tmp);
    tmp.focus(); tmp.select();
    try { document.execCommand('copy'); } catch(e) {}
    document.body.removeChild(tmp);
    btn.textContent = successMsg;
    setTimeout(function() { btn.textContent = resetMsg; }, resetDelay);
  }

  copyButton.addEventListener('click', function() {
    copyText(currentUrl, copyButton,
      '复制成功，请粘贴到备忘录保存或粘贴给朋友',
      '点此复制网址保存', 8000);
  });

  wechatCopyButton.addEventListener('click', function() {
    copyText(wechatUrl, wechatCopyButton,
      '复制成功，请粘贴到微信聊天窗口',
      '点此复制微信可用网址', 8000);
  });
  
  closeButton.addEventListener('click', function() {
    document.body.removeChild(overlay);
  });
  
  overlay.addEventListener('click', function(e) {
    if (e.target === overlay) {
      document.body.removeChild(overlay);
    }
  });
  
  container.appendChild(title);
  container.appendChild(urlInput);
  container.appendChild(copyButton);
  container.appendChild(wechatCopyButton);
  container.appendChild(closeButton);
  overlay.appendChild(container);
  
  document.body.appendChild(overlay);
}


function showCategoryPopup() {
  
  if (document.querySelector('.category-overlay')) {
    return;
  }
  
  const overlay = document.createElement('div');
  overlay.className = 'category-overlay';
  overlay.style.cssText = `
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.7);
    z-index: 9999;
    display: flex;
    justify-content: center;
    align-items: center;
    padding: 20px;
    box-sizing: border-box;
  `;
  
  const container = document.createElement('div');
  container.className = 'category-container';
  container.style.cssText = `
    background-color: white;
    border-radius: 12px;
    max-width: 90%;
    width: 360px;
    max-height: 70vh;
    box-shadow: 0 10px 25px rgba(0, 0, 0, 0.2);
    overflow: hidden;
    display: flex;
    flex-direction: column;
  `;
  
  const header = document.createElement('div');
  header.className = 'category-header';
  header.style.cssText = `
    padding: 16px 20px;
    border-bottom: 1px solid #eaeaea;
    display: flex;
    justify-content: space-between;
    align-items: center;
    background-color: #f9f9f9;
  `;
  
  const title = document.createElement('h3');
  title.textContent = '栏目导航';
  title.style.cssText = `
    margin: 0;
    font-size: 16px;
    color: #333;
    font-weight: 600;
  `;
  
  const closeBtn = document.createElement('button');
  closeBtn.textContent = '关闭';
  closeBtn.style.cssText = `
    background: none;
    border: 1px solid #ddd;
    font-size: 13px;
    color: #666;
    cursor: pointer;
    padding: 4px 12px;
    border-radius: 12px;
    line-height: 1.6;
    font-family: inherit;
  `;
  
  closeBtn.addEventListener('click', function() {
    document.body.removeChild(overlay);
  });
  
  const content = document.createElement('div');
  content.className = 'category-content';
  content.style.cssText = `
    padding: 20px;
    overflow-y: auto;
    flex: 1;
  `;
  
  const categoryData = [{
    title: '佛菩萨圣号',
  links: [
    {name: '阿弥陀佛圣号', url: '/b1.htm'},
    {name: '观音菩萨圣号', url: '/b2.htm'},
    {name: '地藏菩萨圣号', url: '/b3.htm'},
    {name: '释迦牟尼佛圣号', url: '/b4.htm'},
    {name: '药师佛圣号', url: '/b5.htm'},
    {name: '东林佛号唱诵', url: '/b84.htm'},
    {name: '开松老和尚佛号', url: '/b91.htm'}
  ]
},{
  title: '咒语',
  links: [
    {name: '药师咒', url: '/b10.htm'},
    {name: '准提咒', url: '/b11.htm'},
    {name: '文殊菩萨心咒', url: '/b38.htm'},
    {name: '大悲咒', url: '/b6.htm'},
    {name: '楞严咒', url: '/b7.htm'},
    {name: '六字大明咒', url: '/b8.htm'},
    {name: '往生咒', url: '/b9.htm'},
    {name: '地藏菩萨灭定业真言', url: '/b98.htm'}
  ]
},{
  title: '歌曲',
  links: [
    {name: '许俊华歌曲', url: '/b100.htm'},
    {name: '齐豫歌曲', url: '/b101.htm'},
    {name: '传愿法师歌曲', url: '/b102.htm'},
    {name: '孟庭苇歌曲', url: '/b103.htm'},
    {name: '心悦法师歌曲', url: '/b104.htm'},
    {name: '龚玥歌曲', url: '/b105.htm'},
    {name: '陈振国歌曲', url: '/b106.htm'},
    {name: '周亮歌曲', url: '/b107.htm'},
    {name: '耀一法师歌曲', url: '/b23.htm'},
    {name: '黄慧音歌曲', url: '/b24.htm'},
    {name: '黄帅歌曲', url: '/b25.htm'},
    {name: '慧普法师歌曲', url: '/b26.htm'},
    {name: '童声歌曲', url: '/b27.htm'},
    {name: '印良法师歌曲', url: '/b28.htm'},
    {name: '印能法师歌曲', url: '/b29.htm'},
    {name: '则旭法师歌曲', url: '/b30.htm'},
    {name: '桑吉平措歌曲', url: '/b39.htm'},
    {name: '怀静法师歌曲', url: '/b42.htm'},
    {name: '乔安舞歌曲', url: '/b51.htm'},
    {name: '柯佩磊歌曲', url: '/b52.htm'},
    {name: '李佳宁歌曲', url: '/b53.htm'},
    {name: '李文发歌曲', url: '/b54.htm'},
    {name: '门盛法师歌曲', url: '/b55.htm'},
    {name: '宗铄法师歌曲', url: '/b58.htm'},
    {name: '果慧法师歌曲', url: '/b88.htm'},
    {name: '衍祥法师歌曲', url: '/b89.htm'},
    {name: '莲歌子歌曲', url: '/b92.htm'},
    {name: '李娜歌曲', url: '/b93.htm'},
    {name: '上官萍歌曲', url: '/b94.htm'},
    {name: '任静歌曲', url: '/b95.htm'},
    {name: '圣净法师歌曲', url: '/b96.htm'}
  ]
},{
  title: '佛菩萨',
  links: [
    {name: '阿弥陀佛', url: '/b108.htm'},
    {name: '观音菩萨', url: '/b109.htm'},
    {name: '地藏菩萨', url: '/b110.htm'},
    {name: '释迦牟尼佛', url: '/b111.htm'},
    {name: '弥勒菩萨', url: '/b112.htm'},
    {name: '药师佛', url: '/b113.htm'},
    {name: '文殊菩萨', url: '/b114.htm'},
    {name: '普贤菩萨', url: '/b115.htm'},
    {name: '八十八佛', url: '/b116.htm'}
  ]
},{
  title: '佛经念诵',
  links: [
    {name: '栴檀居士念诵', url: '/b117.htm'},
    {name: '莲唤居士念诵', url: '/b118.htm'},
    {name: '《阿弥陀经》念诵', url: '/b12.htm'},
    {name: '《地藏经》念诵', url: '/b13.htm'},
    {name: '《法华经》念诵', url: '/b14.htm'},
    {name: '《华严经》念诵', url: '/b15.htm'},
    {name: '《金刚经》念诵', url: '/b16.htm'},
    {name: '《楞严经》念诵', url: '/b17.htm'},
    {name: '《普门品》念诵', url: '/b18.htm'},
    {name: '《无量寿经》念诵', url: '/b19.htm'},
    {name: '《心经》念诵', url: '/b20.htm'},
    {name: '《药师经》念诵', url: '/b21.htm'},
    {name: '早晚课', url: '/b22.htm'},
    {name: '《普贤行愿品》念诵', url: '/b37.htm'},
    {name: '《涅槃经》念诵', url: '/b40.htm'},
    {name: '慧律法师念诵', url: '/b43.htm'},
    {name: '仁炟法师唱诵', url: '/b46.htm'},
    {name: '聆志居士佛经念诵', url: '/b47.htm'},
    {name: '善音居士佛经念诵', url: '/b48.htm'},
    {name: '妙喜居士佛经念诵', url: '/b49.htm'},
    {name: '慧平法师佛经念诵', url: '/b50.htm'},
    {name: '佛光山唱诵', url: '/b86.htm'},
    {name: '法鼓山唱诵', url: '/b87.htm'},
    {name: '文殊讲堂唱诵', url: '/b90.htm'}
  ]
},{
  title: '唱诵',
  links: [
    {name: '道明法师唱诵', url: '/b31.htm'},
    {name: '隆根长老唱诵', url: '/b32.htm'},
    {name: '瑜伽焰口', url: '/b33.htm'},
    {name: '宗谛法师唱诵', url: '/b34.htm'},
    {name: '大悲忏', url: '/b35.htm'},
    {name: '梁皇宝忏唱诵', url: '/b36.htm'}
  ]
},{
  title: '偈赞',
  links: [
    {name: '心安禅寺唱诵', url: '/b41.htm'},
    {name: '宗泽法师唱诵', url: '/b44.htm'},
    {name: '华严字母唱诵', url: '/b45.htm'},
    {name: '明谷法师唱诵', url: '/b56.htm'},
    {name: '文殊院上江腔梵呗', url: '/b57.htm'},
    {name: '晨钟暮鼓', url: '/b85.htm'},
    {name: '水陆法会', url: '/b97.htm'},
    {name: '忏悔', url: '/b99.htm'}
  ]
},{
  title: '法师讲座',
  links: [
    {name: '大安法师讲座', url: '/jz59.htm'},
    {name: '道证法师讲座', url: '/jz60.htm'},
    {name: '宏海法师讲座', url: '/jz61.htm'},
    {name: '惠空法师讲座', url: '/jz62.htm'},
    {name: '慧律法师讲座', url: '/jz63.htm'},
    {name: '界诠法师讲座', url: '/jz64.htm'},
    {name: '净界法师讲座', url: '/jz65.htm'},
    {name: '梦参老和尚讲座', url: '/jz66.htm'},
    {name: '妙华法师讲座', url: '/jz67.htm'},
    {name: '显明法师讲座', url: '/jz68.htm'},
    {name: '智海长老讲座', url: '/jz69.htm'},
    {name: '慧律法师第一义谛', url: '/jz70.htm'},
    {name: '慧律法师楞伽经', url: '/jz71.htm'},
    {name: '梦参老和尚华严经', url: '/jz72.htm'},
    {name: '大安法师问答', url: '/jz74.htm'},
    {name: '慧律法师楞严经', url: '/jz75.htm'},
    {name: '印光大师讲座', url: '/jz76.htm'},
    {name: '慧律法师华严经', url: '/jz77.htm'},
    {name: '慧律法师圆觉经', url: '/jz78.htm'}
  ]
},{
  title: '佛经开示',
  links: [
    {name: '地藏经讲座', url: '/jz73.htm'},
    {name: '阿弥陀经讲座', url: '/jz79.htm'},
    {name: '楞严经讲座', url: '/jz80.htm'},
    {name: '金刚经讲座', url: '/jz81.htm'},
    {name: '临终讲座', url: '/jz82.htm'},
    {name: '心经讲座', url: '/jz83.htm'}
  ]
}];

  categoryData.forEach(function(category, index) {
    const categoryTitle = document.createElement('div');
    categoryTitle.className = 'category-title';
    categoryTitle.style.cssText = `
      font-weight: bold;
      font-size: 15px;
      color: #333;
      margin-bottom: 10px;
      margin-top: ${index > 0 ? '20px' : '0'};
    `;
    categoryTitle.textContent = category.title;
    content.appendChild(categoryTitle);
    
    const linkContainer = document.createElement('div');
    linkContainer.className = 'category-links';
    linkContainer.style.cssText = `
      display: flex;
      flex-wrap: wrap;
      gap: 15px;
      margin-bottom: 5px;
      padding-bottom: 15px;
      border-bottom: ${index < categoryData.length - 1 ? '1px dashed #eaeaea' : 'none'};
    `;
    
    category.links.forEach(function(link) {
      const linkElem = document.createElement('a');
      linkElem.href = link.url;
      linkElem.textContent = link.name;
      linkElem.style.cssText = `
        text-decoration: none;
        color: #555;
        padding: 6px 12px;
        background-color: #f5f5f5;
        border-radius: 15px;
        font-size: 12px;
        transition: all 0.2s ease;
        display: inline-block;
      `;
      
      linkElem.addEventListener('mouseover', function() {
        this.style.backgroundColor = '#e9e9e9';
        this.style.color = '#222';
      });
      
      linkElem.addEventListener('mouseout', function() {
        this.style.backgroundColor = '#f5f5f5';
        this.style.color = '#555';
      });
      
      linkContainer.appendChild(linkElem);
    });
    
    content.appendChild(linkContainer);
  });
  
  header.appendChild(title);
  header.appendChild(closeBtn);
  container.appendChild(header);
  container.appendChild(content);
  overlay.appendChild(container);
  
  overlay.addEventListener('click', function(e) {
    if (e.target === overlay) {
      document.body.removeChild(overlay);
    }
  });
  
  document.body.appendChild(overlay);
}






window.addEventListener("load", function () {

    /* -------------------------  ------------------------- */
    var commentInputBox = document.getElementById("commentInputBox");
	var commentForm = document.getElementById("commentForm");
	var textarea = document.getElementById("content");          
	var contentDisplay = document.getElementById("contentDisplay"); 
    var usernameInput = document.getElementById("username");
    var parentInput = document.getElementById("parent_id");
    var replyInfo = document.getElementById("replyInfo");
    var replyUserSpan = document.getElementById("replyUser");
    var cancelReplyLink = document.getElementById("cancelReplyLink");
    var sendBtn = document.getElementById("sendBtn");
    var cancelFormBtn = document.getElementById("cancelFormBtn");
    var sendSuccessBox = document.getElementById("sendSuccess");
    var commentsBox = document.getElementById("comments");
    var loadMoreBtn = document.getElementById("loadMore");
    var likeArea = document.getElementById("likeArea");

    /* -------------------------  ------------------------- */
    function ajax(url, method, callback) {
        var xhr = new XMLHttpRequest();
        xhr.open(method, url, true);
        xhr.onreadystatechange = function () {
            if (xhr.readyState === 4 && xhr.status === 200) {
                callback(JSON.parse(xhr.responseText));
            }
        };
        xhr.send();
    }

    /* ------------------------- 保存 ------------------------- */
    if (usernameInput) {
        var saved = localStorage.getItem("comment_username");
        if (saved) usernameInput.value = saved;
    }

    /* -------------------------  ------------------------- */
    fetch(API + "/tj?id=" + PAGE_ID, {
        method: "POST",
        headers: {"Content-Type": "application/x-www-form-urlencoded"},
        body:
            "screen=" + encodeURIComponent(window.screen.width + "x" + window.screen.height) +
            "&ref=" + encodeURIComponent(document.referrer) +
            "&url=" + encodeURIComponent(location.href) +
            "&title=" + encodeURIComponent(document.title)
    });
	
	
	/* ------------------------- uv ------------------------- */
	
var uvEl = document.getElementById('uvc');
if (uvEl) {
    fetch(API + '/wat?id=' + PAGE_ID)
        .then(function(r){ return r.json(); })
        .then(function(d){ uvEl.innerText = d.uv; });
}

    /* ------------------------- 输入框展开 ------------------------- */
    if (commentInputBox && commentForm && contentDisplay) {
    commentInputBox.onclick = function () {
        commentInputBox.style.display = "none";
        commentForm.style.display = "block";
        contentDisplay.focus();   
    };
}


    /* ------------------------- 自动高度 ------------------------- */
    if (contentDisplay) {
    contentDisplay.addEventListener("input", function () {
        this.style.height = "auto";
        this.style.height = this.scrollHeight + "px";
    });
}


    
    /* ------------------------- 表情 ------------------------- */
if (contentDisplay && textarea) {
    var emojis = document.querySelectorAll("#emojiBox img");
    for (var i = 0; i < emojis.length; i++) {
        emojis[i].onclick = function () {
            var code = this.getAttribute("data-code"); 
            var num = code.replace("emoji_", "");

            
            contentDisplay.innerHTML += '<img src="/em/' + num + '.png" class="emoji">';

            
            textarea.value += "[" + code + "]";
        };
    }
}

/* ------------------------- 粘贴文本 ------------------------- */
if (contentDisplay) {
    contentDisplay.addEventListener("paste", function (e) {
        e.preventDefault();

        var text = (e.clipboardData || window.clipboardData).getData("text");

        
        document.execCommand("insertText", false, text);
    });
}



/* -------------------------  ------------------------- */
if (contentDisplay && textarea) {
    contentDisplay.addEventListener("input", function () {
        var clone = contentDisplay.cloneNode(true);

        
        var imgs = clone.querySelectorAll("img.emoji");
        for (var i = 0; i < imgs.length; i++) {
            var src = imgs[i].getAttribute("src");
            var num = src.match(/\/(\d+)\.png$/)[1];
            var text = document.createTextNode("[emoji_" + num + "]");
            imgs[i].parentNode.replaceChild(text, imgs[i]);
        }

        
        var pureText = clone.textContent || clone.innerText;

        
        textarea.value = pureText;
    });
}




    /* ------------------------- 点赞 ------------------------- */
var likeOriginalHTML = likeArea ? likeArea.innerHTML : '';
var likeProcessing = false; /* 防重复点击 */

function restoreLikeBtn(count) {
    var area = document.getElementById('likeArea');
    if (!area) return;
    area.innerHTML = likeOriginalHTML;
    var span = document.getElementById('likeCount');
    if (span) span.innerText = count;
    area.classList.add('liked'); /* 点击当次变红，刷新后自然消失 */
}

function loadLikeCount() {
    ajax(API + '/getlike?id=' + PAGE_ID, 'GET', function (d) {
        var span = document.getElementById('likeCount');
        if (span) span.innerText = d.count;
    });
}
loadLikeCount();

if (likeArea) {
    likeArea.onclick = function () {
        if (likeProcessing) return; /* 防连续点击 */
        likeProcessing = true;

        ajax(API + '/like?id=' + PAGE_ID, 'POST', function (d) {
            likeProcessing = false;
            var area = document.getElementById('likeArea');
            var count = d.count;

            if (d.status === 'liked') {
                /* 后台判断此 IP 已赞过：只弹提示，不变红，不动数字 */
                var tip = document.createElement('span');
                tip.className = 'like-plus';
                tip.innerText = '已赞过';
                tip.style.cssText = 'left:50%;top:0;transform:translateX(-50%);white-space:nowrap;';
                area.appendChild(tip);
                setTimeout(function () {
                    if (tip.parentNode) tip.parentNode.removeChild(tip);
                }, 1200);
                return;
            }

            /* 正常点赞：+1 动画，1秒后恢复大拇指样式并变红 */
            var plus = document.createElement('span');
            plus.className = 'like-plus';
            plus.innerText = '+1';
            plus.style.cssText = 'left:50%;top:0;transform:translateX(-50%);';
            area.appendChild(plus);
            setTimeout(function () {
                if (plus.parentNode) plus.parentNode.removeChild(plus);
            }, 800);
            setTimeout(function () {
                restoreLikeBtn(count);
            }, 1000);
        });
    };
}

    /* ------------------------- 加载 ------------------------- */
    var allComments = [];
    var showCount = 5;

    function loadComments() {
        if (!commentsBox) return;

        fetch(API + "/comments?id=" + PAGE_ID)
            .then(function (r) { return r.json(); })
            .then(function (list) {
                allComments = list || [];  // 防止接口返回 null 导致报错
                renderComments();
            })
            .catch(function () {
                allComments = [];  // 请求异常时也兜底为空数组
                renderComments();
            });
    }

    /* ------------------------- 渲染 ------------------------- */
    function renderComments() {
        if (!commentsBox) return;
        if (!Array.isArray(allComments)) allComments = [];  // 兜底，确保是数组

        var map = {};
        for (var i = 0; i < allComments.length; i++) {
            allComments[i].children = [];
            map[allComments[i].id] = allComments[i];
        }

        var roots = [];
        for (var j = 0; j < allComments.length; j++) {
            var c = allComments[j];
            if (c.parent_id && map[c.parent_id]) {
                map[c.parent_id].children.push(c);
            } else {
                roots.push(c);
            }
        }

        var displayRoots = roots.slice(0, showCount);

        function renderTree(nodes) {
            var html = "";

            for (var k = 0; k < nodes.length; k++) {
                var c = nodes[k];

                
               var content = c.content;

for (var i = 1; i <= 20; i++) {
    var key = "[emoji_" + i + "]";
    var img = '<img src="/em/' + i + '.png" class="emoji">';
    content = content.split(key).join(img);
}



              html +=
    '<div class="comment-box">' +
        '<b>' + c.username + '</b>' +
(c.pinned ? '<span class="pinned">置顶</span>' : '') +
'<div style="margin:8px 0">' + content + '</div>' +
        '<div style="display:-webkit-flex;display:flex;-webkit-align-items:center;align-items:center;-webkit-justify-content:space-between;justify-content:space-between;margin-top:8px">' +
            '<div style="display:-webkit-flex;display:flex;-webkit-align-items:center;align-items:center;gap:12px">' +
                '<span style="font-size:12px;color:#888">' + c.time + '</span>' +
                '<span class="reply-btn" data-id="' + c.id + '" data-user="' + c.username.replace(/"/g, '&quot;') + '">回复</span>' +
            '</div>' +
            '<div class="like-btn" data-id="' + c.id + '">' +
                '<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M20.84 4.61a5.5 5.5 0 0 0-7.78 0L12 5.67l-1.06-1.06a5.5 5.5 0 0 0-7.78 7.78l1.06 1.06L12 21.23l7.78-7.78 1.06-1.06a5.5 5.5 0 0 0 0-7.78z"/></svg>' +
                c.likes +
            '</div>' +
        '</div>' +
        (c.children.length ? '<div class="comment-children">' + renderTree(c.children) + '</div>' : '') +
    '</div>';
					
					
					
            }

            return html;
        }

        commentsBox.innerHTML = renderTree(displayRoots);
var plSection = document.querySelector('.pl-section');
if (plSection) {
    if (roots.length > 0) {
        plSection.style.borderTop = 'none';
        plSection.style.borderBottom = 'none';
    } else {
        plSection.style.borderTop = '';
        plSection.style.borderBottom = '';
    }
}

        
        if (loadMoreBtn) {
            loadMoreBtn.style.display = roots.length > showCount ? "block" : "none";
        }

        /* 点赞 */
        var likeBtns = commentsBox.querySelectorAll(".like-btn");
        for (var a = 0; a < likeBtns.length; a++) {
            likeBtns[a].onclick = function () {
                var id = this.getAttribute("data-id");
                var self = this;

                fetch(API + "/comment_like?id=" + id, { method: "POST" })
                    .then(function (r) { return r.json(); })
                    .then(function (d) {
                        self.innerHTML = '<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" ><path d="M20.84 4.61a5.5 5.5 0 0 0-7.78 0L12 5.67l-1.06-1.06a5.5 5.5 0 0 0-7.78 7.78l1.06 1.06L12 21.23l7.78-7.78 1.06-1.06a5.5 5.5 0 0 0 0-7.78z"/></svg>' + d.count;
                    });
            };
        }

        /* 回复 */
        var replyBtns = commentsBox.querySelectorAll(".reply-btn");
        for (var b = 0; b < replyBtns.length; b++) {
            replyBtns[b].onclick = function () {
                var id = this.getAttribute("data-id");
                var user = this.getAttribute("data-user");
                setReply(id, user);
            };
        }
    }

    /* ------------------------- 展开 ------------------------- */
    if (loadMoreBtn) {
        loadMoreBtn.onclick = function () {
            showCount += 8; 
            renderComments();
        };
    }

    /* ------------------------- 回复 ------------------------- */
    function setReply(id, username) {
        parentInput.value = id;
        replyUserSpan.innerText = username;
        replyInfo.style.display = "block";

        if (commentInputBox) commentInputBox.style.display = "none";
        commentForm.style.display = "block";

        commentForm.scrollIntoView({ behavior: "smooth" });
        textarea.focus();
    }

    if (cancelReplyLink) {
        cancelReplyLink.onclick = function () {
            parentInput.value = 0;
            replyInfo.style.display = "none";
        };
    }

    /* ------------------------- 取消 ------------------------- */
    if (cancelFormBtn) {
        cancelFormBtn.onclick = function () {
            textarea.value = "";
            textarea.style.height = "80px";
            parentInput.value = 0;
            replyInfo.style.display = "none";
            commentForm.style.display = "none";

            if (commentInputBox) commentInputBox.style.display = "block";
        };
    }

    /* ------------------------- 发送 ------------------------- */
    if (sendBtn) {
        sendBtn.onclick = function () {
            var username = usernameInput.value.trim();
            var content = textarea.value.trim();
            var parent = parentInput.value;

            if (!content) return alert("留言内容不能为空");
            if (content.length > 200) return alert("内容不能超过 200 字");
            if (username.length > 15) return alert("用户名不能超过 15 个字");

            if (!username) {
                username = "佛弟子" + Math.floor(10000 + Math.random() * 90000);
                usernameInput.value = username;
            }

            localStorage.setItem("comment_username", username);

            fetch(API + "/pl?id=" + PAGE_ID, {
                method: "POST",
                headers: {"Content-Type": "application/x-www-form-urlencoded"},
                body:
                    "username=" + encodeURIComponent(username) +
                    "&content=" + encodeURIComponent(content) +
                    "&parent_id=" + parent
            })
                .then(function (r) { return r.text(); })
                .then(function (t) {
    if (t === "too_fast") return alert("您评论太快了，请稍后再试");
    if (t === "too_long") return alert("不能超过 200 字");

    // 清空
    contentDisplay.innerHTML = "";
    textarea.value = "";
    contentDisplay.style.height = "80px";

    parentInput.value = 0;
    replyInfo.style.display = "none";
    commentForm.style.display = "none";
    if (commentInputBox) commentInputBox.style.display = "block";

    if (sendSuccessBox) {
        sendSuccessBox.innerText = "发送成功，留言将在审核后显示";
        sendSuccessBox.style.opacity = 1;
        setTimeout(function () {
            sendSuccessBox.style.opacity = 0;
        }, 5000);
    }

    var successBox = document.getElementById('sendSuccess');
if (successBox) {
    successBox.innerText = '发送成功，留言将在审核后显示';
    successBox.style.opacity = 1;
    setTimeout(function() {
        successBox.style.opacity = 0;
    }, 5000);
}
loadComments();
});

        };
    }

    /* ------------------------- 初始化 ------------------------- */
    loadComments();
});