/**
 * HuSNS - defaultpro Theme Mobile JS
 * 移动端交互逻辑模块
 * 
 * 复用 mobile 主题的组件逻辑，适配 defaultpro 主题
 */

var HuSNS = window.HuSNS || {};

/**
 * 移动端工具函数
 */
HuSNS.Mobile = {
    // 检测是否为移动设备
    isMobile: function() {
        return /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) 
            || window.innerWidth < 768;
    },
    
    // 震动反馈
    vibrate: function(duration) {
        if (navigator.vibrate) {
            navigator.vibrate(duration);
        }
    },
    
    // 显示 Toast
    showToast: function(message, duration) {
        duration = duration || 2000;
        var toast = document.createElement('div');
        toast.className = 'mobile-toast';
        toast.textContent = message;
        document.body.appendChild(toast);
        
        setTimeout(function() { toast.classList.add('show'); }, 10);
        setTimeout(function() {
            toast.classList.remove('show');
            setTimeout(function() { toast.remove(); }, 300);
        }, duration);
    },
    
    // 检查登录状态
    isLoggedIn: function() {
        return document.body.dataset.userId && document.body.dataset.userId > 0;
    },
    
    // 生成 API URL
    url: function(path) {
        var base = window.API_BASE_URL || '';
        return base + '/?r=' + path;
    }
};

/**
 * 帖子操作模块
 */
HuSNS.PostActions = {
    // 初始化帖子操作事件
    init: function() {
        var self = this;
        
        // 点赞按钮事件
        document.addEventListener('click', function(e) {
            var btn = e.target.closest('.moment-action[data-action="like"], .action-btn.like-btn');
            if (btn) {
                self.handleLike(btn, e);
            }
        });
        
        // 更多菜单按钮
        document.addEventListener('click', function(e) {
            var btn = e.target.closest('.moment-more, .more-btn');
            if (btn) {
                self.toggleDropdown(btn, e);
            }
        });
        
        // 点击其他地方关闭菜单
        document.addEventListener('click', function(e) {
            if (!e.target.closest('.moment-more, .more-btn, .moment-dropdown, .action-more-menu')) {
                self.closeAllDropdowns();
            }
        });
    },
    
    // 处理点赞
    handleLike: function(btn, e) {
        e.stopPropagation();
        
        var postId = btn.dataset.id;
        var isLiked = btn.classList.contains('liked');
        var countEl = btn.querySelector('.moment-action-count, .action-count');
        var currentCount = parseInt(countEl?.textContent) || 0;
        
        // 震动反馈
        HuSNS.Mobile.vibrate(10);
        
        // 乐观更新 UI
        btn.classList.toggle('liked');
        if (countEl) {
            countEl.textContent = isLiked ? Math.max(0, currentCount - 1) : currentCount + 1;
        }
        
        // 点赞动画效果
        if (!isLiked) {
            btn.style.transform = 'scale(1.2)';
            setTimeout(function() { btn.style.transform = ''; }, 150);
        }
        
        // API 调用
        var csrfToken = document.querySelector('meta[name="csrf-token"]')?.content || 
                       document.querySelector('input[name="csrf_token"]')?.value || '';
        
        fetch(BASE_URL + '/?r=post/like', {
            method: 'POST',
            headers: {'Content-Type': 'application/x-www-form-urlencoded'},
            body: 'post_id=' + postId + '&csrf_token=' + csrfToken
        })
        .then(function(r) { return r.json(); })
        .then(function(data) {
            if (data.code !== 0) {
                // 失败回滚
                btn.classList.toggle('liked');
                if (countEl) {
                    countEl.textContent = currentCount || '';
                }
                HuSNS.Mobile.showToast(data.message || '操作失败');
            }
        })
        .catch(function() {
            // 网络错误回滚
            btn.classList.toggle('liked');
            if (countEl) {
                countEl.textContent = currentCount || '';
            }
            HuSNS.Mobile.showToast('网络错误');
        });
    },
    
    // 切换下拉菜单
    toggleDropdown: function(btn, e) {
        e.stopPropagation();
        var dropdown = btn.querySelector('.moment-dropdown, .action-more-menu');
        if (!dropdown) return;
        
        // 关闭其他菜单
        document.querySelectorAll('.moment-dropdown.show, .action-more-menu.show').forEach(function(d) {
            if (d !== dropdown) d.classList.remove('show');
        });
        
        dropdown.classList.toggle('show');
    },
    
    // 关闭所有下拉菜单
    closeAllDropdowns: function() {
        document.querySelectorAll('.moment-dropdown.show, .action-more-menu.show').forEach(function(d) {
            d.classList.remove('show');
        });
    },
    
    // 删除帖子
    deletePost: function(postId) {
        if (!confirm('确定要删除这条动态吗？')) return;
        
        var csrfToken = document.querySelector('meta[name="csrf-token"]')?.content || 
                       document.querySelector('input[name="csrf_token"]')?.value || '';
        
        fetch(BASE_URL + '/?r=post/delete', {
            method: 'POST',
            headers: {'Content-Type': 'application/x-www-form-urlencoded'},
            body: 'id=' + postId + '&csrf_token=' + csrfToken
        })
        .then(function(r) { return r.json(); })
        .then(function(result) {
            if (result.code === 0) {
                var card = document.querySelector('.moment-card[data-id="' + postId + '"], .post[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.Mobile.showToast('删除成功');
            } else {
                HuSNS.Mobile.showToast(result.message || '删除失败');
            }
        })
        .catch(function() {
            HuSNS.Mobile.showToast('删除失败');
        });
    },
    
    // 收藏帖子
    favoritePost: function(postId, isFavorited) {
        var csrfToken = document.querySelector('meta[name="csrf-token"]')?.content || 
                       document.querySelector('input[name="csrf_token"]')?.value || '';
        
        var apiUrl = isFavorited ? BASE_URL + '/?r=post/unfavorite' : BASE_URL + '/?r=post/favorite';
        
        fetch(apiUrl, {
            method: 'POST',
            headers: {'Content-Type': 'application/x-www-form-urlencoded'},
            body: 'post_id=' + postId + '&csrf_token=' + csrfToken
        })
        .then(function(r) { return r.json(); })
        .then(function(result) {
            if (result.code === 0) {
                HuSNS.Mobile.showToast(isFavorited ? '已取消收藏' : '已收藏');
                location.reload();
            } else {
                HuSNS.Mobile.showToast(result.message || '操作失败');
            }
        })
        .catch(function() {
            HuSNS.Mobile.showToast('操作失败');
        });
    }
};

/**
 * 图片查看器
 */
HuSNS.ImageViewer = {
    init: function() {
        var self = this;
        
        document.addEventListener('click', function(e) {
            var img = e.target.closest('.moment-img, .post-images img');
            if (img && !e.target.closest('.action-btn, .moment-action')) {
                var images = [];
                var gallery = img.closest('.moment-images, .post-images');
                
                if (gallery) {
                    gallery.querySelectorAll('img').forEach(function(gImg) {
                        images.push({
                            src: gImg.src,
                            alt: gImg.alt || ''
                        });
                    });
                } else {
                    images.push({ src: img.src, alt: img.alt || '' });
                }
                
                var index = images.findIndex(function(i) { return i.src === img.src; });
                self.open(images, index >= 0 ? index : 0);
            }
        });
    },
    
    open: function(images, startIndex) {
        var currentIndex = startIndex;
        var total = images.length;
        
        var overlay = document.createElement('div');
        overlay.className = 'image-viewer-overlay show';
        overlay.innerHTML = 
            '<div class="image-viewer-container">' +
                '<div class="image-viewer-swiper">' +
                    images.map(function(img, i) {
                        return '<div class="image-viewer-slide" style="display:' + (i === startIndex ? 'flex' : 'none') + ';">' +
                            '<img src="' + img.src + '" alt="' + img.alt + '" class="image-viewer-image">' +
                        '</div>';
                    }).join('') +
                '</div>' +
                '<button class="image-viewer-close" onclick="HuSNS.ImageViewer.close()">×</button>' +
                (total > 1 ? '<span class="image-viewer-indicator">' + (startIndex + 1) + '/' + total + '</span>' : '') +
                (total > 1 ? '<button class="image-viewer-nav image-viewer-prev" onclick="HuSNS.ImageViewer.prev()">‹</button>' : '') +
                (total > 1 ? '<button class="image-viewer-nav image-viewer-next" onclick="HuSNS.ImageViewer.next()">›</button>' : '') +
            '</div>';
        
        document.body.appendChild(overlay);
        
        // 点击背景关闭
        overlay.addEventListener('click', function(e) {
            if (e.target === overlay) {
                this.close();
            }
        }.bind(this));
        
        this.overlay = overlay;
        this.images = images;
        this.total = total;
        this.currentIndex = currentIndex;
    },
    
    prev: function() {
        this.currentIndex = (this.currentIndex - 1 + this.total) % this.total;
        this.updateSlide();
    },
    
    next: function() {
        this.currentIndex = (this.currentIndex + 1) % this.total;
        this.updateSlide();
    },
    
    updateSlide: function() {
        var slides = this.overlay.querySelectorAll('.image-viewer-slide');
        slides.forEach(function(slide, i) {
            slide.style.display = i === this.currentIndex ? 'flex' : 'none';
        }.bind(this));
        
        var indicator = this.overlay.querySelector('.image-viewer-indicator');
        if (indicator) {
            indicator.textContent = (this.currentIndex + 1) + '/' + this.total;
        }
    },
    
    close: function() {
        if (this.overlay) {
            this.overlay.classList.remove('show');
            setTimeout(function() {
                if (this.overlay && this.overlay.parentNode) {
                    this.overlay.parentNode.removeChild(this.overlay);
                }
            }.bind(this), 300);
        }
    }
};

/**
 * 无限滚动
 */
HuSNS.InfiniteScroll = {
    isLoading: false,
    currentPage: 1,
    
    init: function(options) {
        options = options || {};
        var url = options.url || '';
        var container = options.container || '#postList';
        var loadMore = options.loadMore || '.load-more-btn';
        
        if (!url) return;
        
        this.url = url;
        this.container = container;
        this.loadMore = loadMore;
        
        // 加载更多按钮
        var btn = document.querySelector(loadMore);
        if (btn) {
            btn.addEventListener('click', function() {
                this.loadMore();
            }.bind(this));
        }
    },
    
    loadMore: function() {
        if (this.isLoading) return;
        this.isLoading = true;
        
        var btn = document.querySelector(this.loadMore);
        if (btn) {
            btn.textContent = '加载中...';
            btn.disabled = true;
        }
        
        fetch(this.url + '&page=' + (this.currentPage + 1))
            .then(function(r) { return r.text(); })
            .then(function(html) {
                var parser = new DOMParser();
                var doc = parser.parseFromString(html, 'text/html');
                var newPosts = doc.querySelectorAll('.moment-card, .post');
                
                if (newPosts.length > 0) {
                    var container = document.querySelector(this.container);
                    if (container) {
                        newPosts.forEach(function(post) {
                            container.insertAdjacentHTML('beforeend', post.outerHTML);
                        });
                    }
                    this.currentPage++;
                }
                
                // 更新或移除加载更多按钮
                var newLoadMore = doc.querySelector(this.loadMore);
                if (btn) {
                    if (newLoadMore) {
                        btn.innerHTML = newLoadMore.innerHTML;
                        btn.disabled = false;
                    } else {
                        btn.remove();
                    }
                }
            }.bind(this))
            .catch(function() {
                if (btn) {
                    btn.textContent = '加载失败，点击重试';
                    btn.disabled = false;
                }
            })
            .finally(function() {
                this.isLoading = false;
            }.bind(this));
    }
};

// 初始化移动端功能
document.addEventListener('DOMContentLoaded', function() {
    // 初始化帖子操作
    HuSNS.PostActions.init();
    
    // 初始化图片查看器
    HuSNS.ImageViewer.init();
});

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