/**
 * HuSNS Mobile Theme - defaultpro
 * 移动端主题脚本 - 模块化设计
 */

(function() {
    'use strict';

    var baseUrl = document.body.dataset.baseUrl || '';
    var isLoggedIn = false;
    var currentUserId = null;
    var currentPostId = null;
    var currentCommentId = null;
    var uploadedImages = [];

    // 初始化
    init();

    function init() {
        checkLoginStatus();
        bindEvents();
        loadUnreadCount();
    }

    // 检查登录状态
    function checkLoginStatus() {
        var userAvatar = document.querySelector('.m-post-item .m-post-header a img') || 
                         document.querySelector('.user-avatar');
        isLoggedIn = !!userAvatar;
    }

    // 绑定事件
    function bindEvents() {
        // 下拉刷新
        bindPullToRefresh();
        
        // 发布按钮
        var publishBtn = document.getElementById('publishBtn');
        if (publishBtn) {
            publishBtn.addEventListener('click', function() {
                if (!isLoggedIn) {
                    showPopup('loginPopup');
                } else {
                    showPopup('publishPopup');
                }
            });
        }

        // 登录按钮
        var loginBtn = document.getElementById('loginBtn');
        if (loginBtn) {
            loginBtn.addEventListener('click', handleLogin);
        }

        // 注册按钮
        var regBtn = document.getElementById('regBtn');
        if (regBtn) {
            regBtn.addEventListener('click', handleRegister);
        }

        // 发布提交
        var pubSubmitBtn = document.getElementById('pubSubmitBtn');
        if (pubSubmitBtn) {
            pubSubmitBtn.addEventListener('click', handlePublish);
        }

        // 转发提交
        var repostSubmitBtn = document.getElementById('repostSubmitBtn');
        if (repostSubmitBtn) {
            repostSubmitBtn.addEventListener('click', handleRepost);
        }

        // 图片上传
        var pubImageInput = document.getElementById('pubImageInput');
        if (pubImageInput) {
            pubImageInput.addEventListener('change', handleImageSelect);
        }

        // 点赞
        document.querySelectorAll('[data-action="like"]').forEach(function(btn) {
            btn.addEventListener('click', handleLike);
        });

        // 收藏
        document.querySelectorAll('[data-action="favorite"]').forEach(function(btn) {
            btn.addEventListener('click', handleFavorite);
        });

        // 评论按钮
        document.querySelectorAll('[data-action="comment"]').forEach(function(btn) {
            btn.addEventListener('click', function(e) {
                e.preventDefault();
                var postId = this.dataset.id;
                openCommentPopup(postId);
            });
        });

        // 转发按钮
        document.querySelectorAll('[data-action="repost"]').forEach(function(btn) {
            btn.addEventListener('click', function() {
                var postId = this.dataset.id;
                openRepostPopup(postId);
            });
        });

        // 点击弹窗背景关闭
        document.querySelectorAll('.popup-overlay').forEach(function(overlay) {
            overlay.addEventListener('click', function(e) {
                if (e.target === this) {
                    hidePopup(this.id);
                }
            });
        });
    }

    // ============ 登录注册 ============

    function handleLogin() {
        var username = document.getElementById('loginUsername').value.trim();
        var password = document.getElementById('loginPassword').value;

        if (!username || !password) {
            showToast('请填写用户名和密码');
            return;
        }

        var btn = document.getElementById('loginBtn');
        btn.disabled = true;
        btn.textContent = '登录中...';

        fetch(baseUrl + '/mobileApi/login', {
            method: 'POST',
            headers: {'Content-Type': 'application/json'},
            credentials: 'same-origin',
            body: JSON.stringify({username, password})
        })
        .then(function(res) { return res.json(); })
        .then(function(data) {
            if (data.code === 0) {
                hidePopup('loginPopup');
                showToast('登录成功');
                location.reload();
            } else {
                showToast(data.message || '登录失败');
            }
        })
        .catch(function() {
            showToast('网络错误');
        })
        .finally(function() {
            btn.disabled = false;
            btn.textContent = '登录';
        });
    }

    function handleRegister() {
        var username = document.getElementById('regUsername').value.trim();
        var email = document.getElementById('regEmail').value.trim();
        var password = document.getElementById('regPassword').value;

        if (!username || !email || !password) {
            showToast('请填写完整信息');
            return;
        }

        var btn = document.getElementById('regBtn');
        btn.disabled = true;
        btn.textContent = '注册中...';

        fetch(baseUrl + '/mobileApi/register', {
            method: 'POST',
            headers: {'Content-Type': 'application/json'},
            credentials: 'same-origin',
            body: JSON.stringify({username, email, password})
        })
        .then(function(res) { return res.json(); })
        .then(function(data) {
            if (data.code === 0) {
                hidePopup('registerPopup');
                showPopup('loginPopup');
                showToast('注册成功，请登录');
            } else {
                showToast(data.message || '注册失败');
            }
        })
        .catch(function() {
            showToast('网络错误');
        })
        .finally(function() {
            btn.disabled = false;
            btn.textContent = '注册';
        });
    }

    // ============ 发布动态 ============

    function handlePublish() {
        var content = document.getElementById('pubContent').value.trim();

        if (!content && uploadedImages.length === 0) {
            showToast('请输入内容或上传图片');
            return;
        }

        var btn = document.getElementById('pubSubmitBtn');
        btn.disabled = true;
        btn.textContent = '发布中...';

        fetch(baseUrl + '/mobileApi/publish', {
            method: 'POST',
            headers: {'Content-Type': 'application/json'},
            credentials: 'same-origin',
            body: JSON.stringify({
                content: content,
                images: uploadedImages
            })
        })
        .then(function(res) { return res.json(); })
        .then(function(data) {
            if (data.code === 0) {
                hidePopup('publishPopup');
                document.getElementById('pubContent').value = '';
                document.getElementById('pubImagesPreview').innerHTML = '';
                uploadedImages = [];
                showToast('发布成功');
                location.reload();
            } else {
                showToast(data.message || '发布失败');
            }
        })
        .catch(function() {
            showToast('网络错误');
        })
        .finally(function() {
            btn.disabled = false;
            btn.textContent = '发布';
        });
    }

    function triggerImageUpload() {
        document.getElementById('pubImageInput').click();
    }

    function handleImageSelect(e) {
        var files = e.target.files;
        if (!files.length) return;

        var preview = document.getElementById('pubImagesPreview');

        Array.from(files).forEach(function(file) {
            if (uploadedImages.length >= 9) {
                showToast('最多上传9张图片');
                return;
            }

            var formData = new FormData();
            formData.append('file', file);

            fetch(baseUrl + '/mobileApi/uploadImage', {
                method: 'POST',
                credentials: 'same-origin',
                body: formData
            })
            .then(function(res) { return res.json(); })
            .then(function(data) {
                if (data.code === 0) {
                    uploadedImages.push(data.data.path);
                    var img = document.createElement('img');
                    img.src = data.data.url;
                    preview.appendChild(img);
                } else {
                    showToast(data.message || '图片上传失败');
                }
            })
            .catch(function() {
                showToast('网络错误');
            });
        });

        e.target.value = '';
    }

    function insertTopic() {
        var textarea = document.getElementById('pubContent');
        var content = textarea.value;
        var cursor = textarea.selectionStart;
        textarea.value = content.substring(0, cursor) + '##' + content.substring(cursor);
        textarea.focus();
    }

    // ============ 评论 ============

    function openCommentPopup(postId) {
        currentPostId = postId;
        showPopup('commentPopup');
        loadComments(postId);
    }

    function loadComments(postId) {
        var list = document.getElementById('commentPopupList');
        list.innerHTML = '<div style="text-align:center;padding:20px;color:#999;">加载中...</div>';

        fetch(baseUrl + '/mobileApi/comments?post_id=' + postId, {credentials: 'same-origin'})
        .then(function(res) { return res.json(); })
        .then(function(data) {
            if (data.code === 0) {
                renderComments(data.data.items);
            } else {
                list.innerHTML = '<div style="text-align:center;padding:20px;color:#999;">加载失败</div>';
            }
        })
        .catch(function() {
            list.innerHTML = '<div style="text-align:center;padding:20px;color:#999;">网络错误</div>';
        });
    }

    function renderComments(comments) {
        var list = document.getElementById('commentPopupList');
        
        if (!comments || comments.length === 0) {
            list.innerHTML = '<div style="text-align:center;padding:40px;color:#999;">暂无评论</div>';
            return;
        }

        var html = '';
        comments.forEach(function(comment) {
            html += '<div class="comment-item" data-id="' + comment.id + '">';
            html += '<div class="comment-header">';
            html += '<img class="comment-avatar" src="' + (comment.avatar || '/templates/defaultpro/images/avatar_default.png') + '" alt="">';
            html += '<div class="comment-info">';
            html += '<div class="comment-name">' + escapeHtml(comment.username) + '</div>';
            html += '<div class="comment-time">' + comment.time_ago + '</div>';
            html += '</div>';
            html += '</div>';
            html += '<div class="comment-content">' + comment.content + '</div>';
            html += '<div class="comment-actions">';
            html += '<span class="comment-action" onclick="window.mobileApp.replyComment(' + comment.id + ', \'' + escapeHtml(comment.username) + '\')">回复</span>';
            html += '</div>';

            // 楼中楼回复
            if (comment.replies && comment.replies.length > 0) {
                html += '<div class="comment-replies">';
                comment.replies.forEach(function(reply) {
                    html += '<div class="reply-item">';
                    html += '<span class="reply-user">' + escapeHtml(reply.username) + '</span>';
                    if (reply.reply_to) {
                        html += '<span class="reply-to"> 回复 @' + escapeHtml(reply.reply_to) + '</span>';
                    }
                    html += '<div class="reply-content">' + reply.content + '</div>';
                    html += '</div>';
                });
                html += '</div>';
            }

            html += '</div>';
        });

        list.innerHTML = html;
    }

    window.mobileApp = {
        replyComment: function(commentId, username) {
            currentCommentId = commentId;
            var input = document.getElementById('commentInput');
            input.placeholder = '回复 @' + username + '...';
            input.focus();
        }
    };

    function submitComment() {
        var input = document.getElementById('commentInput');
        var content = input.value.trim();

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

        var params = {post_id: currentPostId, content: content};
        if (currentCommentId) {
            params.reply_id = currentCommentId;
        }

        fetch(baseUrl + '/mobileApi/comment', {
            method: 'POST',
            headers: {'Content-Type': 'application/json'},
            credentials: 'same-origin',
            body: JSON.stringify(params)
        })
        .then(function(res) { return res.json(); })
        .then(function(data) {
            if (data.code === 0) {
                input.value = '';
                input.placeholder = '发表评论...';
                currentCommentId = null;
                loadComments(currentPostId);
                showToast('评论成功');
            } else {
                showToast(data.message || '评论失败');
            }
        })
        .catch(function() {
            showToast('网络错误');
        });
    }

    // ============ 转发 ============

    function openRepostPopup(postId) {
        if (!isLoggedIn) {
            showPopup('loginPopup');
            return;
        }

        currentPostId = postId;
        showPopup('repostPopup');

        // 获取原动态信息
        var postItem = document.querySelector('.m-post-item[data-id="' + postId + '"]');
        if (postItem) {
            var username = postItem.querySelector('.m-post-username')?.textContent || '';
            var content = postItem.querySelector('.m-post-content')?.textContent || '';
            content = content.substring(0, 100) + (content.length > 100 ? '...' : '');
            document.getElementById('repostOriginal').innerHTML = '@' + username + ': ' + content;
        }
    }

    function handleRepost() {
        var content = document.getElementById('repostContent').value.trim();

        var btn = document.getElementById('repostSubmitBtn');
        btn.disabled = true;
        btn.textContent = '转发中...';

        fetch(baseUrl + '/mobileApi/repost', {
            method: 'POST',
            headers: {'Content-Type': 'application/json'},
            credentials: 'same-origin',
            body: JSON.stringify({
                post_id: currentPostId,
                content: content
            })
        })
        .then(function(res) { return res.json(); })
        .then(function(data) {
            if (data.code === 0) {
                hidePopup('repostPopup');
                document.getElementById('repostContent').value = '';
                showToast('转发成功');
            } else {
                showToast(data.message || '转发失败');
            }
        })
        .catch(function() {
            showToast('网络错误');
        })
        .finally(function() {
            btn.disabled = false;
            btn.textContent = '转发';
        });
    }

    // ============ 点赞 ============

    function handleLike() {
        if (!isLoggedIn) {
            showPopup('loginPopup');
            return;
        }

        var btn = this;
        var postId = btn.dataset.id;
        var isLiked = btn.classList.contains('liked');
        var icon = btn.querySelector('.m-action-icon');
        var count = btn.querySelector('.m-action-count');
        var currentCount = parseInt(count.textContent) || 0;

        var likeUrl = isLiked ? baseUrl + '/mobileApi/unlike' : baseUrl + '/mobileApi/like';
        fetch(likeUrl, {
            method: 'POST',
            headers: {'Content-Type': 'application/json'},
            credentials: 'same-origin',
            body: JSON.stringify({id: postId})
        })
        .then(function(res) { return res.json(); })
        .then(function(data) {
            if (data.code === 0) {
                btn.classList.toggle('liked');
                icon.className = 'm-action-icon ' + (isLiked ? 'fa-regular fa-heart' : 'fa-solid fa-heart');
                icon.style.color = isLiked ? '' : '#ff4d4f';
                count.textContent = data.data ? data.data.likes : (isLiked ? currentCount - 1 : currentCount + 1);
            } else {
                showToast(data.message || '操作失败');
            }
        })
        .catch(function() {});
    }

    // ============ 收藏 ============

    function handleFavorite() {
        if (!isLoggedIn) {
            showPopup('loginPopup');
            return;
        }

        var btn = this;
        var postId = btn.dataset.id;
        var isFavorited = btn.classList.contains('favorited');
        var icon = btn.querySelector('.m-action-icon');

        var favUrl = isFavorited ? baseUrl + '/mobileApi/unfavorite' : baseUrl + '/mobileApi/favorite';
        fetch(favUrl, {
            method: 'POST',
            headers: {'Content-Type': 'application/json'},
            credentials: 'same-origin',
            body: JSON.stringify({id: postId})
        })
        .then(function(res) { return res.json(); })
        .then(function(data) {
            if (data.code === 0) {
                btn.classList.toggle('favorited');
                icon.className = 'm-action-icon ' + (isFavorited ? 'fa-regular fa-star' : 'fa-solid fa-star');
                icon.style.color = isFavorited ? '' : '#ffad1f';
            } else {
                showToast(data.message || '操作失败');
            }
        })
        .catch(function() {});
    }

    // ============ 未读消息 ============

    function loadUnreadCount() {
        fetch(baseUrl + '/mobileApi/userInfo', {credentials: 'same-origin'})
        .then(function(res) { return res.json(); })
        .then(function(data) {
            if (data.code === 0 && data.data && data.data.logged_in && data.data.stats && data.data.stats.unread_count > 0) {
                var badge = document.querySelector('.unread-badge');
                if (badge) {
                    badge.style.display = 'block';
                    badge.textContent = data.data.stats.unread_count > 99 ? '99+' : data.data.stats.unread_count;
                }
            }
        })
        .catch(function() {});
    }

    // ============ 弹窗控制 ============

    window.showPopup = function(id) {
        var popup = document.getElementById(id);
        if (popup) {
            popup.classList.add('show');
            document.body.style.overflow = 'hidden';
        }
    };

    window.hidePopup = function(id) {
        var popup = document.getElementById(id);
        if (popup) {
            popup.classList.remove('show');
            document.body.style.overflow = '';
        }
    };

    window.switchPopup = function(hideId, showId) {
        hidePopup(hideId);
        setTimeout(function() {
            showPopup(showId);
        }, 100);
    };

    // ============ 工具函数 ============

    function showToast(message) {
        var existing = document.querySelector('.toast');
        if (existing) existing.remove();

        var toast = document.createElement('div');
        toast.className = 'toast';
        toast.textContent = message;
        document.body.appendChild(toast);

        setTimeout(function() {
            toast.remove();
        }, 2000);
    }

    function escapeHtml(text) {
        var div = document.createElement('div');
        div.textContent = text;
        return div.innerHTML;
    }

    // 图片预览
    document.addEventListener('click', function(e) {
        if (e.target.classList.contains('m-post-image')) {
            var modal = document.createElement('div');
            modal.className = 'm-image-modal';
            modal.innerHTML = '<img src="' + e.target.src + '">';
            modal.addEventListener('click', function() {
                this.remove();
            });
            document.body.appendChild(modal);
            modal.classList.add('show');
        }
    });

    // ============ App 全局对象 ============
    // 下拉刷新
    function bindPullToRefresh() {
        var startY = 0;
        var refreshThreshold = 100;
        var isRefreshing = false;
        var refreshElement = document.createElement('div');
        refreshElement.className = 'm-pull-refresh';
        refreshElement.innerHTML = '<div class="m-pull-refresh-content">下拉刷新</div>';
        document.body.insertBefore(refreshElement, document.body.firstChild);
        
        document.addEventListener('touchstart', function(e) {
            if (window.scrollY === 0 && !isRefreshing) {
                startY = e.touches[0].clientY;
            }
        });
        
        document.addEventListener('touchmove', function(e) {
            if (window.scrollY === 0 && !isRefreshing && e.touches[0].clientY > startY) {
                var pullDistance = e.touches[0].clientY - startY;
                if (pullDistance > 0) {
                    e.preventDefault();
                    var refreshHeight = Math.min(pullDistance * 0.5, refreshThreshold);
                    refreshElement.style.height = refreshHeight + 'px';
                    if (refreshHeight >= refreshThreshold) {
                        refreshElement.querySelector('.m-pull-refresh-content').textContent = '松开刷新';
                    } else {
                        refreshElement.querySelector('.m-pull-refresh-content').textContent = '下拉刷新';
                    }
                }
            }
        });
        
        document.addEventListener('touchend', function(e) {
            if (window.scrollY === 0 && !isRefreshing) {
                var pullDistance = e.changedTouches[0].clientY - startY;
                if (pullDistance * 0.5 >= refreshThreshold) {
                    isRefreshing = true;
                    refreshElement.style.height = refreshThreshold + 'px';
                    refreshElement.querySelector('.m-pull-refresh-content').textContent = '刷新中...';
                    
                    // 模拟刷新操作
                    setTimeout(function() {
                        location.reload();
                    }, 1000);
                } else {
                    // 回弹效果
                    refreshElement.style.height = '0px';
                }
            }
        });
    }

    var App = window.App || {};

    App.baseUrl = baseUrl;

    App.renderPostCard = function(post) {
        var html = '<div class="m-post-item" data-id="' + post.id + '">';
        html += '<div class="m-post-header">';
        html += '<a href="' + baseUrl + '/mobile/user?id=' + post.user_id + '">';
        html += '<img class="m-post-avatar" src="' + (post.avatar || '/templates/defaultpro/images/avatar_default.png') + '" alt="">';
        html += '</a>';
        html += '<div class="m-post-user-info">';
        html += '<a href="' + baseUrl + '/mobile/user?id=' + post.user_id + '" class="m-post-username">' + escapeHtml(post.username) + '</a>';
        html += '<div class="m-post-time">' + (post.time_ago || '') + '</div>';
        html += '</div>';
        html += '</div>';
        html += '<a href="' + baseUrl + '/mobile/detail?id=' + post.id + '" style="text-decoration:none;color:inherit;">';
        html += '<div class="m-post-content">' + (post.content || '') + '</div>';
        if (post.images && post.images.length > 0) {
            var gridClass = 'single';
            if (post.images.length === 2) gridClass = 'double';
            else if (post.images.length === 3) gridClass = 'triple';
            else if (post.images.length === 4) gridClass = 'quad';
            else if (post.images.length > 4) gridClass = 'many';
            html += '<div class="m-post-images ' + gridClass + '">';
            post.images.slice(0, 9).forEach(function(img) {
                html += '<img class="m-post-image" src="' + img + '" alt="" loading="lazy" decoding="async">';
            });
            html += '</div>';
        }
        html += '</a>';
        html += '<div class="m-post-actions">';
        html += '<button class="m-action-btn ' + (post.is_liked ? 'liked' : '') + '" data-action="like" data-id="' + post.id + '">';
        html += '<i class="m-action-icon ' + (post.is_liked ? 'fa-solid fa-heart' : 'fa-regular fa-heart') + '"' + (post.is_liked ? ' style="color:#ff4d4f;"' : '') + '></i>';
        html += '<span class="m-action-count">' + post.likes + '</span>';
        html += '</button>';
        html += '<a href="' + baseUrl + '/mobile/detail?id=' + post.id + '" class="m-action-btn" data-action="comment" data-id="' + post.id + '">';
        html += '<i class="m-action-icon fa-regular fa-comment"></i>';
        html += '<span class="m-action-count">' + post.comments + '</span>';
        html += '</a>';
        html += '<button class="m-action-btn ' + (post.is_favorited ? 'favorited' : '') + '" data-action="favorite" data-id="' + post.id + '">';
        html += '<i class="m-action-icon ' + (post.is_favorited ? 'fa-solid fa-star' : 'fa-regular fa-star') + '"' + (post.is_favorited ? ' style="color:#ffad1f;"' : '') + '></i>';
        html += '</button>';
        html += '</div>';
        html += '</div>';
        return html;
    };

    window.App = App;

})();
