/**
 * HuSNS Mobile Home Page - defaultpro
 * 移动端首页专用脚本
 * @version 4.1.0
 */

(function() {
    'use strict';

    var HomeApp = {
        config: {
            baseUrl: '',
            pageSize: 15,
            currentPage: 1,
            currentTab: 'all',
            loading: false,
            hasMore: true
        },

        init: function(baseUrl) {
            this.config.baseUrl = baseUrl || '';
            this.syncTabFromDOM();
            this.bindEvents();
            this.loadPosts();
        },

        syncTabFromDOM: function() {
            var activeTab = document.querySelector('.m-tab.active');
            if (activeTab && activeTab.dataset.tab) {
                this.config.currentTab = activeTab.dataset.tab;
            }
        },

        bindEvents: function() {
            var self = this;
            
            document.querySelectorAll('.m-tab[data-tab]').forEach(function(tab) {
                tab.addEventListener('click', function(e) {
                    e.preventDefault();
                    self.switchTab(this);
                });
            });

            var loadMoreBtn = document.getElementById('loadMoreBtn');
            if (loadMoreBtn) {
                loadMoreBtn.addEventListener('click', function(e) {
                    e.preventDefault();
                    self.loadMore();
                });
            }
            
            // 事件委托处理点赞和收藏
            document.addEventListener('click', function(e) {
                var btn = e.target.closest('[data-action="like"]');
                if (btn) {
                    e.preventDefault();
                    self.handleLike(btn);
                    return;
                }
                
                btn = e.target.closest('[data-action="favorite"]');
                if (btn) {
                    e.preventDefault();
                    self.handleFavorite(btn);
                    return;
                }
            });
        },

        switchTab: function(tabEl) {
            var newTab = tabEl.dataset.tab;
            if (newTab === this.config.currentTab) return;

            this.config.currentTab = newTab;
            this.config.currentPage = 1;
            this.config.hasMore = true;

            document.querySelectorAll('.m-tab').forEach(function(el) {
                el.classList.remove('active');
            });
            tabEl.classList.add('active');

            var container = document.getElementById('postList');
            if (container) {
                container.innerHTML = '<div class="loading-state"><div class="loading-spinner"></div>加载中...</div>';
            }

            this.loadPosts();
        },

        loadPosts: function(isLoadMore) {
            var self = this;
            
            if (this.config.loading) return;
            this.config.loading = true;

            if (!isLoadMore) {
                this.showLoading();
            }

            var url = this.config.baseUrl + '/mobileApi/posts?page=' + this.config.currentPage + '&tab=' + encodeURIComponent(this.config.currentTab);

            fetch(url, {
                method: 'GET',
                credentials: 'same-origin',
                headers: { 'X-Requested-With': 'XMLHttpRequest' }
            })
            .then(function(response) { return response.json(); })
            .then(function(data) {
                self.config.loading = false;
                self.hideLoading();

                if (data.code === 0) {
                    self.renderPosts(data.data.items || [], isLoadMore);
                    self.config.hasMore = data.data.pagination ? data.data.pagination.has_more : false;
                    self.updateLoadMoreButton();
                } else {
                    self.showError(data.message || '加载失败');
                }
            })
            .catch(function(error) {
                self.config.loading = false;
                self.hideLoading();
                self.showError('网络错误，请稍后重试');
            });
        },

        loadMore: function() {
            if (!this.config.hasMore || this.config.loading) return;
            this.config.currentPage++;
            this.loadPosts(true);
        },

        renderPosts: function(posts, isAppend) {
            var container = document.getElementById('postList');
            if (!container) return;

            if (!isAppend) {
                container.innerHTML = '';
            }

            if (posts.length === 0 && !isAppend) {
                container.innerHTML = '<div class="m-empty"><div class="m-empty-icon">📭</div><div class="m-empty-text">暂无内容</div></div>';
                return;
            }

            var html = '';
            var self = this;
            posts.forEach(function(post) {
                html += self.renderPostItem(post);
            });

            if (isAppend) {
                container.insertAdjacentHTML('beforeend', html);
            } else {
                container.innerHTML = html;
            }
        },

        renderPostItem: function(post) {
            var html = '<div class="m-post-item" data-id="' + post.id + '">' +
                '<div class="m-post-header">' +
                '<a href="' + this.config.baseUrl + '/mobile/user?id=' + post.user_id + '">' +
                '<img class="m-post-avatar" src="' + (post.avatar || '/templates/defaultpro/images/avatar_default.png') + '" alt="">' +
                '</a>' +
                '<div class="m-post-user-info">' +
                '<a href="' + this.config.baseUrl + '/mobile/user?id=' + post.user_id + '" class="m-post-username">' +
                this.escapeHtml(post.username) +
                '</a>' +
                '<div class="m-post-time">' + (post.time_ago || '') + '</div>' +
                '</div>' +
                '</div>' +
                '<a href="' + this.config.baseUrl + '/mobile/detail?id=' + post.id + '" style="text-decoration:none;color:inherit;">' +
                '<div class="m-post-content">' + post.content + '</div>';

            if (post.images && post.images.length > 0) {
                var imgCount = post.images.length;
                var gridClass = 'single';
                if (imgCount === 2) gridClass = 'double';
                else if (imgCount === 3) gridClass = 'triple';
                else if (imgCount === 4) gridClass = 'quad';
                else if (imgCount > 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">';
                });
                html += '</div>';
            }

            html += '</a>';

            // 转发预览
            if (post.is_repost && post.original_post) {
                var orig = post.original_post;
                html += '<div class="m-repost-preview">' +
                    '<a href="' + this.config.baseUrl + '/mobile/detail?id=' + orig.id + '" style="color:inherit;text-decoration:none;">' +
                    '@' + this.escapeHtml(orig.username) + ': ' + this.escapeHtml(orig.content).substring(0, 100) + '...' +
                    '</a></div>';
            }

            html += '<div class="m-post-actions">' +
                '<button class="m-action-btn ' + (post.is_liked ? 'liked' : '') + '" data-action="like" data-id="' + post.id + '">' +
                '<i class="m-action-icon ' + (post.is_liked ? 'fa-solid' : 'fa-regular') + ' fa-heart"' + (post.is_liked ? ' style="color:#ff4d4f;"' : '') + '></i>' +
                '<span class="m-action-count">' + (post.likes || 0) + '</span>' +
                '</button>' +
                '<a href="' + this.config.baseUrl + '/mobile/detail?id=' + post.id + '" class="m-action-btn" data-action="comment" data-id="' + post.id + '">' +
                '<i class="m-action-icon fa-regular fa-comment"></i>' +
                '<span class="m-action-count">' + (post.comments || 0) + '</span>' +
                '</a>' +
                '<button class="m-action-btn ' + (post.is_favorited ? 'favorited' : '') + '" data-action="favorite" data-id="' + post.id + '">' +
                '<i class="m-action-icon ' + (post.is_favorited ? 'fa-solid' : 'fa-regular') + ' fa-star"' + (post.is_favorited ? ' style="color:#ffad1f;"' : '') + '></i>' +
                '</button>' +
                '</div></div>';

            return html;
        },

        handleLike: function(btn) {
            var postId = btn.dataset.id;
            var isLiked = btn.classList.contains('liked');
            var url = isLiked ? this.config.baseUrl + '/mobileApi/unlike' : this.config.baseUrl + '/mobileApi/like';
            
            fetch(url, {
                method: 'POST',
                credentials: 'same-origin',
                headers: {'Content-Type': 'application/json'},
                body: JSON.stringify({id: postId})
            })
            .then(function(res) { return res.json(); })
            .then(function(data) {
                if (data.code === 0) {
                    btn.classList.toggle('liked');
                    var icon = btn.querySelector('i');
                    var count = btn.querySelector('.m-action-count');
                    if (isLiked) {
                        icon.className = 'm-action-icon fa-regular fa-heart';
                        icon.style.color = '';
                        count.textContent = Math.max(0, parseInt(count.textContent) - 1);
                    } else {
                        icon.className = 'm-action-icon fa-solid fa-heart';
                        icon.style.color = '#ff4d4f';
                        count.textContent = parseInt(count.textContent) + 1;
                    }
                }
            });
        },

        handleFavorite: function(btn) {
            var postId = btn.dataset.id;
            var isFavorited = btn.classList.contains('favorited');
            var url = isFavorited ? this.config.baseUrl + '/mobileApi/unfavorite' : this.config.baseUrl + '/mobileApi/favorite';
            
            fetch(url, {
                method: 'POST',
                credentials: 'same-origin',
                headers: {'Content-Type': 'application/json'},
                body: JSON.stringify({id: postId})
            })
            .then(function(res) { return res.json(); })
            .then(function(data) {
                if (data.code === 0) {
                    btn.classList.toggle('favorited');
                    var icon = btn.querySelector('i');
                    if (isFavorited) {
                        icon.className = 'm-action-icon fa-regular fa-star';
                        icon.style.color = '';
                    } else {
                        icon.className = 'm-action-icon fa-solid fa-star';
                        icon.style.color = '#ffad1f';
                    }
                }
            });
        },

        showLoading: function() {
            var container = document.getElementById('postList');
            if (container && container.children.length === 0) {
                container.innerHTML = '<div class="loading-state"><div class="loading-spinner"></div>加载中...</div>';
            }
        },

        hideLoading: function() {
            var loading = document.querySelector('.loading-state');
            if (loading) loading.remove();
        },

        showError: function(message) {
            var container = document.getElementById('postList');
            if (container) {
                container.innerHTML = '<div class="error-state">' + message + '<button onclick="location.reload()">重试</button></div>';
            }
        },

        updateLoadMoreButton: function() {
            var btn = document.getElementById('loadMoreBtn');
            if (btn) {
                btn.style.display = this.config.hasMore ? 'block' : 'none';
            }
        },

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

    // 初始化
    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', function() {
            var baseUrl = document.body.dataset.baseUrl || '';
            HomeApp.init(baseUrl);
        });
    } else {
        var baseUrl = document.body.dataset.baseUrl || '';
        HomeApp.init(baseUrl);
    }

    window.HomeApp = HomeApp;

})();
