/**
 * 分享弹窗逻辑
 */

(function() {
    'use strict';

    // 分享相关状态
    const shareState = {
        postId: 0,
        postUrl: '',
        postContent: '',
        postTitle: ''
    };

    /**
     * 打开分享弹窗
     */
    window.openShareModal = function(options) {
        shareState.postId = options.postId || 0;
        shareState.postUrl = options.url || window.location.href;
        shareState.postContent = options.content || '';
        shareState.postTitle = options.title || '';

        // 更新预览内容
        const shareText = document.getElementById('shareText');
        const shareUrl = document.getElementById('shareUrl');

        if (shareText) {
            shareText.textContent = shareState.postContent || shareState.postTitle || '分享内容';
        }

        if (shareUrl) {
            shareUrl.textContent = shareState.postUrl;
        }

        openModal('shareModal');
    };

    /**
     * 分享到微信
     */
    window.shareToWechat = function() {
        closeModal('shareModal');
        // 检查是否在微信内
        if (isWeChat()) {
            // 在微信内，使用微信分享API
            showToast('请点击右上角分享到微信');
        } else {
            // 在外部浏览器，复制链接
            copyLink();
        }
    };

    /**
     * 分享到朋友圈
     */
    window.shareToMoments = function() {
        closeModal('shareModal');
        if (isWeChat()) {
            showToast('请点击右上角分享到朋友圈');
        } else {
            copyLink();
        }
    };

    /**
     * 分享到QQ
     */
    window.shareToQQ = function() {
        closeModal('shareModal');
        const url = `https://connect.qq.com/widget/shareqq/index.html?url=${encodeURIComponent(shareState.postUrl)}&title=${encodeURIComponent(shareState.postTitle)}&summary=${encodeURIComponent(shareState.postContent)}`;
        window.open(url, '_blank');
    };

    /**
     * 分享到QQ空间
     */
    window.shareToQzone = function() {
        closeModal('shareModal');
        const url = `https://sns.qzone.qq.com/cgi-bin/qzshare/cgi_qzshare_onekey?url=${encodeURIComponent(shareState.postUrl)}&title=${encodeURIComponent(shareState.postTitle)}&summary=${encodeURIComponent(shareState.postContent)}`;
        window.open(url, '_blank');
    };

    /**
     * 分享到微博
     */
    window.shareToWeibo = function() {
        closeModal('shareModal');
        const url = `https://service.weibo.com/share/share.php?url=${encodeURIComponent(shareState.postUrl)}&title=${encodeURIComponent(shareState.postContent)}`;
        window.open(url, '_blank');
    };

    /**
     * 复制链接
     */
    window.shareToCopy = function() {
        closeModal('shareModal');
        copyLink();
    };

    /**
     * 复制链接到剪贴板
     */
    function copyLink() {
        navigator.clipboard.writeText(shareState.postUrl).then(() => {
            showToast('链接已复制到剪贴板');
        }).catch(err => {
            console.error('复制失败:', err);
            showToast('复制失败，请手动复制');
        });
    }

    /**
     * 检查是否在微信内
     */
    function isWeChat() {
        const userAgent = navigator.userAgent.toLowerCase();
        return userAgent.includes('micromessenger');
    }

    /**
     * 举报内容
     */
    window.reportContent = function() {
        closeModal('shareModal');
        openModal('reportModal');
    };

    /**
     * 提交举报
     */
    window.submitReport = async function() {
        const reason = document.querySelector('input[name="reportReason"]:checked')?.value;
        const detail = document.getElementById('reportDetail')?.value?.trim();

        if (!reason) {
            showToast('请选择举报原因');
            return;
        }

        const submitBtn = document.getElementById('reportSubmit');
        if (submitBtn) submitBtn.disabled = true;

        try {
            const data = {
                post_id: shareState.postId,
                reason: reason,
                detail: detail
            };

            const baseUrl = window.HuSNS_User?.baseUrl || window.location.origin;
            const response = await fetch(baseUrl + '/?r=mobileApi/reportPost', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(data),
                credentials: 'include'
            });

            const result = await response.json();

            if (result.code === 0) {
                showToast('举报已提交，感谢您的反馈');
                closeModal('reportModal');
            } else {
                showToast(result.message || '举报失败');
            }
        } catch (error) {
            showToast('网络错误，请稍后重试');
            console.error('Report error:', error);
        } finally {
            if (submitBtn) submitBtn.disabled = false;
        }
    };

    /**
     * 发送私信
     */
    window.submitMessage = async function() {
        const userInfo = document.getElementById('messageUserInfo');
        const userId = userInfo?.dataset.userId;
        const content = document.getElementById('messageInput')?.value?.trim();

        console.log('submitMessage - userId:', userId);
        console.log('submitMessage - content:', content);

        if (!userId) {
            showToast('用户信息错误，请重新选择用户');
            return;
        }

        if (!content) {
            showToast('请输入私信内容');
            return;
        }

        const submitBtn = document.getElementById('messageSubmit');
        if (submitBtn) submitBtn.disabled = true;

        try {
            const baseUrl = window.HuSNS_User?.baseUrl || window.location.origin;
            const data = {
                user_id: userId,
                content: content
            };

            const response = await fetch(`${baseUrl}/?r=mobileApi/sendMessage`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(data)
            });

            console.log('Response status:', response.status);
            
            const text = await response.text();
            console.log('Response text:', text);
            
            let result;
            try {
                result = JSON.parse(text);
            } catch (e) {
                showToast('服务器返回格式错误');
                console.error('JSON parse error:', e);
                return;
            }

            console.log('Response result:', result);

            if (result.code === 0) {
                showToast('私信发送成功');
                closeModal('messageModal');
                // 清空输入
                const input = document.getElementById('messageInput');
                if (input) input.value = '';
            } else {
                showToast(result.message || '发送失败');
            }
        } catch (error) {
            showToast('网络错误，请稍后重试');
            console.error('Send message error:', error);
        } finally {
            if (submitBtn) submitBtn.disabled = false;
        }
    };

    /**
     * 打开私信弹窗
     * 支持两种调用方式：
     * 1. openMessageModal(user) - 接收一个对象参数
     * 2. openMessageModal(userId, username, avatar, bio) - 接收四个独立参数
     */
    window.openMessageModal = function(userId, username, avatar, bio) {
        const userAvatar = document.getElementById('messageUserAvatar');
        const userName = document.getElementById('messageUserName');
        const userBio = document.getElementById('messageUserBio');
        const userInfo = document.getElementById('messageUserInfo');

        // 兼容两种调用方式
        if (typeof userId === 'object') {
            // 调用方式1: openMessageModal(user)
            const user = userId;
            userId = user.id;
            username = user.name || user.username;
            avatar = user.avatar;
            bio = user.bio;
        }

        const baseUrl = window.HuSNS_User?.baseUrl || window.location.origin;
        const defaultAvatar = `${baseUrl}/templates/mobile/images/avatar_default.png`;

        if (userAvatar) userAvatar.src = avatar || defaultAvatar;
        if (userName) userName.textContent = username || '';
        if (userBio) userBio.textContent = bio || '';
        if (userInfo) userInfo.dataset.userId = userId;

        // 清空输入
        const input = document.getElementById('messageInput');
        if (input) input.value = '';

        openModal('messageModal');
    };

    /**
     * 提交转发
     */
    window.submitRepost = async function() {
        const postId = shareState.postId;
        const addComment = document.getElementById('repostAddComment')?.checked;
        const content = document.getElementById('repostInput')?.value?.trim();

        if (!postId) {
            showToast('参数错误');
            return;
        }

        const submitBtn = document.querySelector('.repost-submit-btn');
        if (submitBtn) submitBtn.disabled = true;

        try {
            const data = {
                post_id: postId,
                add_comment: addComment,
                content: content || ''
            };

            const response = await fetch('/api/post/repost', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(data)
            });

            const result = await response.json();

            if (result.status === 'success') {
                showToast('转发成功');
                closeModal('repostModal');
                // 刷新页面
                setTimeout(() => {
                    window.location.reload();
                }, 1500);
            } else {
                showToast(result.message || '转发失败');
            }
        } catch (error) {
            showToast('网络错误，请稍后重试');
            console.error('Repost error:', error);
        } finally {
            if (submitBtn) submitBtn.disabled = false;
        }
    };

    /**
     * 打开转发弹窗
     */
    window.openRepostModal = function(options) {
        shareState.postId = options.postId || 0;
        shareState.postContent = options.content || '';

        // 更新预览
        const previewCard = document.getElementById('repostPreviewCard');
        if (previewCard) {
            previewCard.innerHTML = `
                <div class="repost-author">
                    <img src="${options.authorAvatar || '/images/avatar_default.png'}" class="comment-avatar">
                    <span class="repost-author-name">${options.authorName || ''}</span>
                </div>
                <div class="repost-content">${options.content || ''}</div>
            `;
        }

        // 清空输入
        const input = document.getElementById('repostInput');
        if (input) input.value = '';

        openModal('repostModal');
    };

    /**
     * 初始化分享弹窗
     */
    function initShareModal() {
        // 添加分享按钮事件
        const shareActions = document.querySelectorAll('.share-action');
        shareActions.forEach(action => {
            const onClick = action.getAttribute('onclick');
            if (onClick) {
                action.addEventListener('click', function() {
                    const funcName = onClick.match(/^(\w+)/)?.[1];
                    if (funcName && typeof window[funcName] === 'function') {
                        window[funcName]();
                    }
                });
            }
        });

        // 添加举报按钮事件
        const reportBtn = document.querySelector('.share-extra-action[onclick="reportContent()"]');
        if (reportBtn) {
            reportBtn.addEventListener('click', reportContent);
        }

        // 添加举报提交按钮事件
        const reportSubmit = document.getElementById('reportSubmit');
        if (reportSubmit) {
            reportSubmit.addEventListener('click', submitReport);
        }

        // 添加私信提交按钮事件
        const messageSubmit = document.getElementById('messageSubmit');
        if (messageSubmit) {
            messageSubmit.addEventListener('click', submitMessage);
        }

        // 添加转发提交按钮事件
        const repostSubmit = document.querySelector('.repost-submit-btn');
        if (repostSubmit) {
            repostSubmit.addEventListener('click', submitRepost);
        }
    }

    // 页面加载完成后初始化
    document.addEventListener('DOMContentLoaded', initShareModal);
})();
