/**
 * HuSNS - 帖子操作API模块
 * 处理帖子的各种交互操作
 */

var HuSNS = window.HuSNS || {};

/**
 * 初始化帖子操作事件监听
 */
HuSNS.initPostActions = function() {
    // 点赞功能由 app-layout.js 统一处理，此处不再重复绑定
    
    // 评论按钮
    document.addEventListener('click', function(e) {
        var btn = e.target.closest('.comment-btn');
        if (btn) {
            var postId = parseInt(btn.dataset.postId);
            var commentCount = parseInt(btn.querySelector('.moment-action-count').textContent) || 0;
            if (typeof openCommentModal === 'function') {
                openCommentModal(postId, null, commentCount);
            }
        }
    });
    
    // 举报提交
    HuSNS.initReportSubmit();
};

/**
 * 处理点赞
 * @param {HTMLElement} likeBtn - 点赞按钮元素
 * @param {Event} e - 事件对象
 */
HuSNS.handleLike = function(likeBtn, e) {
    e = e || window.event;
    e.stopPropagation();
    
    var postId = likeBtn.dataset.postId;
    var wasLiked = likeBtn.classList.contains('liked');
    var countElement = likeBtn.querySelector('.moment-action-count');
    var currentCount = parseInt(countElement.textContent) || 0;
    
    // 震动反馈
    HuSNS.vibrate(10);
    
    // 乐观更新UI
    likeBtn.classList.toggle('liked');
    
    // 更新图标
    var iconEl = likeBtn.querySelector('.moment-action-icon .iconify');
    if (iconEl) {
        iconEl.setAttribute('data-icon', wasLiked ? 'mdi:heart-outline' : 'mdi:heart');
    }
    
    if (wasLiked) {
        countElement.textContent = currentCount > 0 ? currentCount - 1 : '';
    } else {
        countElement.textContent = currentCount + 1;
        likeBtn.style.transform = 'scale(1.2)';
        setTimeout(function() { likeBtn.style.transform = ''; }, 150);
    }
    
    // API调用 - 取消点赞调用unlike，点赞调用like
    var baseUrl = window.API_BASE_URL || '';
    var action = wasLiked ? 'unlike' : 'like';
    var apiUrl = baseUrl + '/?r=mobileApi/' + action;
    fetch(apiUrl, {
        method: 'POST',
        credentials: 'include',
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
        body: 'id=' + encodeURIComponent(postId)
    })
    .then(function(response) { return response.json(); })
    .then(function(data) {
        if (data.code !== 0) {
            // 失败回滚 - 使用原始状态 wasLiked
            if (wasLiked) {
                likeBtn.classList.add('liked');
            } else {
                likeBtn.classList.remove('liked');
            }
            if (iconEl) {
                iconEl.setAttribute('data-icon', wasLiked ? 'mdi:heart' : 'mdi:heart-outline');
            }
            countElement.textContent = currentCount || '';
            HuSNS.showToast(data.msg || data.message || '操作失败');
        }
    })
    .catch(function() {
        // 网络错误回滚 - 使用原始状态 wasLiked
        if (wasLiked) {
            likeBtn.classList.add('liked');
        } else {
            likeBtn.classList.remove('liked');
        }
        if (iconEl) {
            iconEl.setAttribute('data-icon', wasLiked ? 'mdi:heart' : 'mdi:heart-outline');
        }
        countElement.textContent = currentCount || '';
    });
};

/**
 * 切换下拉菜单
 * @param {HTMLElement} btn - 菜单按钮
 * @param {Event} event - 事件对象
 */
HuSNS.toggleDropdown = function(btn, event) {
    event.stopPropagation();
    var dropdown = btn.querySelector('.moment-dropdown');
    var isOpen = dropdown.classList.contains('show');
    
    // 关闭其他菜单
    document.querySelectorAll('.moment-dropdown.show').forEach(function(d) {
        if (d !== dropdown) d.classList.remove('show');
    });
    
    dropdown.classList.toggle('show');
};

// 点击其他地方关闭下拉菜单
document.addEventListener('click', function(e) {
    if (!e.target.closest('.moment-more-btn')) {
        document.querySelectorAll('.moment-dropdown.show').forEach(function(d) {
            d.classList.remove('show');
        });
    }
});

/**
 * 转发帖子
 * @param {number} postId - 帖子ID
 */
HuSNS.repostPost = function(postId) {
    // 关闭下拉菜单
    document.querySelectorAll('.moment-dropdown.show').forEach(function(d) { d.classList.remove('show'); });
    
    var card = document.querySelector('.moment-card[data-id="' + postId + '"]');
    if (card) {
        var contentEl = card.querySelector('.moment-content');
        var usernameEl = card.querySelector('.moment-username');
        var postData = {
            post_id: postId,
            username: usernameEl ? usernameEl.textContent : '',
            content: contentEl ? contentEl.textContent.substring(0, 100) : ''
        };
        if (typeof openRepostModal === 'function') {
            openRepostModal(postId, postData);
        }
    } else {
        if (typeof openRepostModal === 'function') {
            openRepostModal(postId, { post_id: postId, content: '' });
        }
    }
};

/**
 * 编辑帖子
 * @param {number} postId - 帖子ID
 */
HuSNS.editPost = function(postId) {
    window.location.href = HuSNS.url('mobile/publish&edit=' + postId);
};

/**
 * 删除帖子
 * @param {number} postId - 帖子ID
 */
HuSNS.deletePost = function(postId) {
    if (confirm('确定要删除这条动态吗？')) {
        fetch(HuSNS.url('mobileApi/deletePost'), {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ post_id: postId })
        })
        .then(function(res) { return res.json(); })
        .then(function(result) {
            if (result.code === 0) {
                var card = document.querySelector('.moment-card[data-id="' + postId + '"]');
                if (card) {
                    card.style.transition = 'all 0.3s';
                    card.style.opacity = '0';
                    card.style.transform = 'translateX(-100%)';
                    setTimeout(function() { card.remove(); }, 300);
                }
                HuSNS.showToast('删除成功');
            } else {
                HuSNS.showToast(result.message || '删除失败');
            }
        })
        .catch(function() {
            HuSNS.showToast('删除失败');
        });
    }
    // 关闭下拉菜单
    document.querySelectorAll('.moment-dropdown.show').forEach(function(d) { d.classList.remove('show'); });
};

/**
 * 举报帖子
 * @param {number} postId - 帖子ID
 */
HuSNS.reportPost = function(postId) {
    window.currentReportPostId = postId;
    if (typeof openModal === 'function') {
        openModal('reportModal');
    }
    // 关闭下拉菜单
    document.querySelectorAll('.moment-dropdown.show').forEach(function(d) { d.classList.remove('show'); });
};

/**
 * 初始化举报提交
 */
HuSNS.initReportSubmit = function() {
    var reportSubmit = document.getElementById('reportSubmit');
    if (!reportSubmit) return;
    
    // 防止重复绑定
    if (reportSubmit.dataset.bound === 'true') return;
    reportSubmit.dataset.bound = 'true';
    
    reportSubmit.addEventListener('click', function() {
        var selectedReason = document.querySelector('input[name="reportReason"]:checked');
        var detailEl = document.getElementById('reportDetail');
        var detail = detailEl ? detailEl.value.trim() : '';
        
        if (!selectedReason) {
            HuSNS.showToast('请选择举报原因');
            return;
        }
        
        var reason = selectedReason.value;
        var postId = window.currentReportPostId;
        
        // 检查登录
        if (!HuSNS.isLoggedIn()) {
            HuSNS.showToast('请先登录');
            if (typeof closeModal === 'function') closeModal('reportModal');
            if (typeof openLoginModal === 'function') openLoginModal();
            return;
        }
        
        // 检查是否已举报（本地缓存）
        var reports = JSON.parse(localStorage.getItem('user_reports') || '[]');
        if (reports.includes(postId)) {
            HuSNS.showToast('您已经举报过该内容');
            if (typeof closeModal === 'function') closeModal('reportModal');
            return;
        }
        
        // 显示加载状态
        reportSubmit.disabled = true;
        reportSubmit.textContent = '提交中...';
        
        // 调用后端API提交举报
        fetch(HuSNS.url('mobileApi/reportPost'), {
            method: 'POST',
            credentials: 'include',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({
                post_id: postId,
                reason: reason,
                detail: detail
            })
        })
        .then(function(res) { return res.json(); })
        .then(function(result) {
            if (result.code === 0) {
                // 保存本地记录
                reports.push(postId);
                localStorage.setItem('user_reports', JSON.stringify(reports));
                
                HuSNS.showToast('举报成功，感谢您的反馈');
                if (typeof closeModal === 'function') closeModal('reportModal');
                
                // 清空表单
                document.querySelectorAll('input[name="reportReason"]').forEach(function(r) { r.checked = false; });
                if (detailEl) detailEl.value = '';
            } else {
                HuSNS.showToast(result.message || '举报失败');
            }
        })
        .catch(function() {
            HuSNS.showToast('举报失败，请重试');
        })
        .finally(function() {
            reportSubmit.disabled = false;
            reportSubmit.textContent = '提交举报';
        });
    });
};

/**
 * 收藏/取消收藏帖子
 * @param {number} postId - 帖子ID
 * @param {boolean} isFavorited - 是否已收藏
 */
HuSNS.favoritePost = function(postId, isFavorited) {
    var apiUrl = isFavorited 
        ? HuSNS.url('mobileApi/unfavorite')
        : HuSNS.url('mobileApi/favorite');
    
    var formData = new FormData();
    formData.append('id', postId);
    
    fetch(apiUrl, {
        method: 'POST',
        body: formData
    })
    .then(function(res) { return res.json(); })
    .then(function(result) {
        if (result.code === 0) {
            HuSNS.showToast(isFavorited ? '已取消收藏' : '已收藏');
            location.reload();
        } else {
            HuSNS.showToast(result.message || '操作失败');
        }
    })
    .catch(function() {
        HuSNS.showToast('操作失败');
    });
    
    document.querySelectorAll('.moment-dropdown.show').forEach(function(d) { d.classList.remove('show'); });
};

/**
 * 置顶/取消置顶帖子
 * @param {number} postId - 帖子ID
 * @param {number} isPinned - 是否已置顶
 */
HuSNS.togglePinPost = function(postId, isPinned) {
    fetch(HuSNS.url('mobileApi/setTop'), {
        method: 'POST',
        credentials: 'include',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ post_id: postId })
    })
    .then(function(res) { return res.json(); })
    .then(function(result) {
        if (result.code === 0) {
            HuSNS.showToast(result.message || (result.data && result.data.is_pinned ? '置顶成功' : '已取消置顶'));
            setTimeout(function() { window.location.reload(); }, 1000);
        } else {
            HuSNS.showToast(result.message || '操作失败');
        }
    })
    .catch(function() {
        HuSNS.showToast('操作失败');
    });
    
    document.querySelectorAll('.moment-dropdown.show').forEach(function(d) { d.classList.remove('show'); });
};

/**
 * 加精/取消加精帖子
 * @param {number} postId - 帖子ID
 * @param {number} isFeatured - 是否已加精
 */
HuSNS.toggleFeaturePost = function(postId, isFeatured) {
    fetch(HuSNS.url('mobileApi/setEssence'), {
        method: 'POST',
        credentials: 'include',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ post_id: postId })
    })
    .then(function(res) { return res.json(); })
    .then(function(result) {
        if (result.code === 0) {
            HuSNS.showToast(result.message || (result.data && result.data.is_featured ? '加精成功' : '已取消加精'));
            setTimeout(function() { window.location.reload(); }, 1000);
        } else {
            HuSNS.showToast(result.message || '操作失败');
        }
    })
    .catch(function() {
        HuSNS.showToast('操作失败');
    });
    
    document.querySelectorAll('.moment-dropdown.show').forEach(function(d) { d.classList.remove('show'); });
};

/**
 * 分享弹窗（需外部实现openShareModal）
 */
HuSNS.openShareModal = function(url, text) {
    if (typeof openShareModal === 'function') {
        openShareModal(url, text);
    }
};

// 页面加载时初始化
document.addEventListener('DOMContentLoaded', function() {
    HuSNS.initPostActions();
});

// 全局暴露
window.HuSNS = HuSNS;