/**
 * 用户关注和文章收藏功能
 * 提供关注/取消关注、收藏/取消收藏的前端交互
 */

(function() {
    'use strict';

    // 获取CSRF Token
    function getCookie(name) {
        let cookieValue = null;
        if (document.cookie && document.cookie !== '') {
            const cookies = document.cookie.split(';');
            for (let i = 0; i < cookies.length; i++) {
                const cookie = cookies[i].trim();
                if (cookie.substring(0, name.length + 1) === (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }

    // 社交功能类
    class SocialFeatures {
        constructor() {
            this.csrfToken = getCookie('csrftoken');
            this.init();
        }

        init() {
            // 绑定关注按钮
            this.bindFollowButtons();
            // 绑定收藏按钮
            this.bindFavoriteButtons();
            // 绑定点赞按钮
            this.bindLikeButtons();
        }

        // ==================== 关注功能 ====================

        bindFollowButtons() {
            const followButtons = document.querySelectorAll('.btn-follow');
            followButtons.forEach(button => {
                button.addEventListener('click', (e) => {
                    e.preventDefault();
                    const userId = button.dataset.userId;
                    const isFollowing = button.dataset.following === 'true';

                    if (isFollowing) {
                        this.unfollowUser(userId, button);
                    } else {
                        this.followUser(userId, button);
                    }
                });
            });
        }

        followUser(userId, button) {
            fetch('/blog/api/follow/', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-CSRFToken': this.csrfToken
                },
                credentials: 'same-origin',
                body: JSON.stringify({ user_id: userId })
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    button.textContent = '已关注';
                    button.dataset.following = 'true';
                    button.classList.remove('btn-primary');
                    button.classList.add('btn-secondary');
                    this.showMessage(data.message, 'success');
                    this.updateFollowCount(data.following_count);
                } else {
                    this.showMessage(data.message, 'error');
                }
            })
            .catch(error => {
                console.error('关注失败:', error);
                this.showMessage('关注失败，请重试', 'error');
            });
        }

        unfollowUser(userId, button) {
            fetch('/blog/api/unfollow/', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-CSRFToken': this.csrfToken
                },
                credentials: 'same-origin',
                body: JSON.stringify({ user_id: userId })
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    button.textContent = '关注';
                    button.dataset.following = 'false';
                    button.classList.remove('btn-secondary');
                    button.classList.add('btn-primary');
                    this.showMessage(data.message, 'success');
                    this.updateFollowCount(data.following_count);
                } else {
                    this.showMessage(data.message, 'error');
                }
            })
            .catch(error => {
                console.error('取消关注失败:', error);
                this.showMessage('取消关注失败，请重试', 'error');
            });
        }

        updateFollowCount(count) {
            const countElement = document.querySelector('#following-count');
            if (countElement) {
                countElement.textContent = count;
            }
        }

        // ==================== 收藏功能 ====================

        bindFavoriteButtons() {
            const favoriteButtons = document.querySelectorAll('.btn-favorite');
            favoriteButtons.forEach(button => {
                button.addEventListener('click', (e) => {
                    e.preventDefault();
                    const articleId = button.dataset.articleId;
                    const isFavorited = button.dataset.favorited === 'true';

                    if (isFavorited) {
                        this.unfavoriteArticle(articleId, button);
                    } else {
                        this.favoriteArticle(articleId, button);
                    }
                });
            });
        }

        favoriteArticle(articleId, button) {
            fetch('/blog/api/favorite/', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-CSRFToken': this.csrfToken
                },
                credentials: 'same-origin',
                body: JSON.stringify({ article_id: articleId })
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    button.innerHTML = '★ 已收藏';
                    button.dataset.favorited = 'true';
                    button.classList.add('favorited');
                    this.showMessage(data.message, 'success');
                    this.updateFavoriteCount(data.favorite_count);
                } else {
                    this.showMessage(data.message, 'error');
                }
            })
            .catch(error => {
                console.error('收藏失败:', error);
                this.showMessage('收藏失败，请重试', 'error');
            });
        }

        unfavoriteArticle(articleId, button) {
            fetch('/blog/api/unfavorite/', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-CSRFToken': this.csrfToken
                },
                credentials: 'same-origin',
                body: JSON.stringify({ article_id: articleId })
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    button.innerHTML = '☆ 收藏';
                    button.dataset.favorited = 'false';
                    button.classList.remove('favorited');
                    this.showMessage(data.message, 'success');
                    this.updateFavoriteCount(data.favorite_count);
                } else {
                    this.showMessage(data.message, 'error');
                }
            })
            .catch(error => {
                console.error('取消收藏失败:', error);
                this.showMessage('取消收藏失败，请重试', 'error');
            });
        }

        updateFavoriteCount(count) {
            const countElement = document.querySelector('#favorite-count');
            if (countElement) {
                countElement.textContent = count;
            }
        }

        // ==================== 点赞功能 ====================

        bindLikeButtons() {
            const likeButtons = document.querySelectorAll('.btn-like');
            likeButtons.forEach(button => {
                button.addEventListener('click', (e) => {
                    e.preventDefault();
                    const articleId = button.dataset.articleId;
                    const isLiked = button.dataset.liked === 'true';

                    if (isLiked) {
                        this.unlikeArticle(articleId, button);
                    } else {
                        this.likeArticle(articleId, button);
                    }
                });
            });
        }

        likeArticle(articleId, button) {
            fetch('/blog/api/like/', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-CSRFToken': this.csrfToken
                },
                credentials: 'same-origin',
                body: JSON.stringify({ article_id: articleId })
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    button.innerHTML = '👍 ' + data.like_count;
                    button.dataset.liked = 'true';
                    button.classList.add('liked');
                    this.showMessage(data.message, 'success');
                    this.updateLikeCount(data.like_count, button);
                } else {
                    this.showMessage(data.message, 'error');
                }
            })
            .catch(error => {
                console.error('点赞失败:', error);
                this.showMessage('点赞失败，请重试', 'error');
            });
        }

        unlikeArticle(articleId, button) {
            fetch('/blog/api/unlike/', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-CSRFToken': this.csrfToken
                },
                credentials: 'same-origin',
                body: JSON.stringify({ article_id: articleId })
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    button.innerHTML = '👍 ' + data.like_count;
                    button.dataset.liked = 'false';
                    button.classList.remove('liked');
                    this.showMessage(data.message, 'success');
                    this.updateLikeCount(data.like_count, button);
                } else {
                    this.showMessage(data.message, 'error');
                }
            })
            .catch(error => {
                console.error('取消点赞失败:', error);
                this.showMessage('取消点赞失败，请重试', 'error');
            });
        }

        updateLikeCount(count, button) {
            // 更新按钮显示的点赞数
            const countSpan = button.querySelector('.like-count');
            if (countSpan) {
                countSpan.textContent = count;
            }
        }

        // ==================== 工具方法 ====================

        showMessage(message, type) {
            // 创建或获取消息提示元素
            let messageBox = document.querySelector('#social-message');
            if (!messageBox) {
                messageBox = document.createElement('div');
                messageBox.id = 'social-message';
                messageBox.style.cssText = 'position: fixed; top: 20px; right: 20px; padding: 15px 20px; ' +
                    'border-radius: 5px; box-shadow: 0 2px 10px rgba(0,0,0,0.2); ' +
                    'font-size: 14px; z-index: 9999; display: none;';
                document.body.appendChild(messageBox);
            }

            const colors = {
                'success': '#4CAF50',
                'error': '#F44336',
                'info': '#2196F3'
            };

            messageBox.textContent = message;
            messageBox.style.background = colors[type] || '#f0f0f0';
            messageBox.style.color = '#fff';
            messageBox.style.display = 'block';

            setTimeout(() => {
                messageBox.style.display = 'none';
            }, 3000);
        }
    }

    // 自动初始化
    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', function() {
            window.socialFeatures = new SocialFeatures();
        });
    } else {
        window.socialFeatures = new SocialFeatures();
    }

})();
