// 赞/踩系统
(function() {
    var container = document.getElementById('postReactions');
    var likeBtn = document.getElementById('likeBtn');
    var dislikeBtn = document.getElementById('dislikeBtn');
    var likesCountEl = document.getElementById('likesCount');
    if (!container || !likeBtn || !dislikeBtn) return;

    var postId = container.dataset.postId;

    // 页面加载时获取当前反应状态
    fetch('/api/posts/' + postId + '/reaction')
        .then(function(r) { return r.json(); })
        .then(function(d) {
            if (!d.success || !d.data) return;
            updateUI(d.data.reaction, d.data.likes_count);
        })
        .catch(function() {});

    function updateUI(reaction, count) {
        likeBtn.classList.remove('active');
        dislikeBtn.classList.remove('active');
        if (reaction === 'liked') likeBtn.classList.add('active');
        if (reaction === 'disliked') dislikeBtn.classList.add('active');
        if (typeof count === 'number') likesCountEl.textContent = count;
    }

    likeBtn.addEventListener('click', function() {
        likeBtn.disabled = true;
        fetch('/api/posts/' + postId + '/like', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json', 'X-CSRF-Token': getCSRFToken() }
        })
        .then(function(r) {
            if (r.status === 401) { window.location.href = '/auth/login?redirect=/posts/' + postId; return null; }
            return r.json();
        })
        .then(function(d) {
            likeBtn.disabled = false;
            if (!d) return;
            if (d.success) {
                updateUI(d.data.liked ? 'liked' : 'none', d.data.likes_count);
            } else {
                alert(d.message || '操作失败');
            }
        })
        .catch(function() { likeBtn.disabled = false; });
    });

    dislikeBtn.addEventListener('click', function() {
        dislikeBtn.disabled = true;
        fetch('/api/posts/' + postId + '/dislike', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json', 'X-CSRF-Token': getCSRFToken() }
        })
        .then(function(r) {
            if (r.status === 401) { window.location.href = '/auth/login?redirect=/posts/' + postId; return null; }
            return r.json();
        })
        .then(function(d) {
            dislikeBtn.disabled = false;
            if (!d) return;
            if (d.success) {
                updateUI(d.data.disliked ? 'disliked' : 'none');
            } else {
                alert(d.message || '操作失败');
            }
        })
        .catch(function() { dislikeBtn.disabled = false; });
    });
})();
