/**
 * 移动端布局相关JavaScript
 */

(function() {
    'use strict';

    // 全局变量
    window.MOBILE_APP = window.MOBILE_APP || {
        currentModal: null,
        isDarkMode: false,
        isLoading: false,
        config: {}
    };

    /**
     * 初始化应用
     */
    function initApp() {
        // 检测暗色模式
        detectDarkMode();
        
        // 添加触摸事件支持
        addTouchEvents();
        
        // 初始化懒加载
        initLazyLoad();
        
        // 设置页面标题
        setupPageTitle();
        
        // 添加键盘事件监听
        addKeyboardListeners();
        
        // 处理滚动事件
        handleScrollEvents();
        
        // 初始化下拉刷新
        initPullRefresh();
        
        // 设置页面数据
        setupPageData();
        
        // 处理页面可见性变化
        handleVisibilityChange();
        
        // 添加点击事件委托
        addClickDelegation();
        
        // 设置主题颜色
        setupThemeColor();
        
        // 初始化平滑滚动
        initSmoothScroll();
        
        // 处理WebView环境
        handleWebViewEnvironment();
        
        // 获取未读消息数量
        loadUnreadMessageCount();
    }

    /**
     * 获取未读消息数量并更新徽章
     */
    async function loadUnreadMessageCount() {
        if (!checkLogin()) return;
        
        try {
            const baseUrl = window.location.origin;
            const response = await fetch(`${baseUrl}/?r=mobileApi/getMessageUnreadCount`);
            const result = await response.json();
            
            if (result.code === 0 && result.data && result.data.unread_count !== undefined) {
                const badge = document.getElementById('messageBadge');
                if (badge) {
                    const count = parseInt(result.data.unread_count);
                    if (count > 0) {
                        badge.textContent = count > 99 ? '99+' : count.toString();
                        badge.style.display = 'inline-block';
                    } else {
                        badge.style.display = 'none';
                    }
                }
            }
        } catch (error) {
            console.error('Failed to load unread message count:', error);
        }
    }

    /**
     * 更新消息徽章数量
     * @param {number} count - 未读消息数量
     */
    window.updateMessageBadge = function(count) {
        const badge = document.getElementById('messageBadge');
        if (badge) {
            if (count > 0) {
                badge.textContent = count > 99 ? '99+' : count.toString();
                badge.style.display = 'inline-block';
            } else {
                badge.style.display = 'none';
            }
        }
    };

    /**
     * 检测护眼模式
     */
    function detectDarkMode() {
        // 首先检查 body 是否已经有 dark-mode class（PHP 端基于 cookie 设置的）
        const bodyHasDarkClass = document.body.classList.contains('dark-mode');
        
        // 检查localStorage中的设置
        const savedMode = localStorage.getItem('darkMode');
        if (savedMode !== null) {
            // localStorage 优先
            MOBILE_APP.isDarkMode = savedMode === 'true';
        } else if (bodyHasDarkClass) {
            // PHP 已设置，同步到 JS 变量和 localStorage
            MOBILE_APP.isDarkMode = true;
            localStorage.setItem('darkMode', 'true');
        } else {
            // 检查系统偏好
            MOBILE_APP.isDarkMode = window.matchMedia('(prefers-color-scheme: dark)').matches;
        }
        
        // 确保 class 与状态一致
        if (MOBILE_APP.isDarkMode && !bodyHasDarkClass) {
            document.body.classList.add('dark-mode');
        }
        
        // 监听系统主题变化
        window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', (e) => {
            if (!localStorage.getItem('darkMode')) {
                MOBILE_APP.isDarkMode = e.matches;
                if (MOBILE_APP.isDarkMode) {
                    document.body.classList.add('dark-mode');
                } else {
                    document.body.classList.remove('dark-mode');
                }
            }
        });
    }

    /**
     * 切换护眼模式
     */
    window.toggleDarkMode = function() {
        MOBILE_APP.isDarkMode = !MOBILE_APP.isDarkMode;
        
        if (MOBILE_APP.isDarkMode) {
            document.body.classList.add('dark-mode');
            // 同步设置 cookie
            document.cookie = 'theme=dark; path=/; max-age=2592000';
        } else {
            document.body.classList.remove('dark-mode');
            // 同步设置 cookie
            document.cookie = 'theme=light; path=/; max-age=2592000';
        }
        
        // 保存设置
        localStorage.setItem('darkMode', MOBILE_APP.isDarkMode.toString());
    };

    /**
     * 添加触摸事件支持
     */
    function addTouchEvents() {
        // 触摸事件处理
        let touchStartX = 0;
        let touchStartY = 0;
        
        document.addEventListener('touchstart', (e) => {
            touchStartX = e.touches[0].clientX;
            touchStartY = e.touches[0].clientY;
        }, { passive: true });
        
        document.addEventListener('touchend', (e) => {
            const touchEndX = e.changedTouches[0].clientX;
            const touchEndY = e.changedTouches[0].clientY;
            const deltaX = touchEndX - touchStartX;
            const deltaY = touchEndY - touchStartY;
            
            // 水平滑动超过50像素视为滑动操作
            if (Math.abs(deltaX) > 50 && Math.abs(deltaY) < 50) {
                // 可以在这里添加左右滑动的逻辑
            }
        }, { passive: true });
        
        // 阻止默认的触摸行为（如缩放）
        document.addEventListener('touchmove', (e) => {
            // 可以选择性地阻止某些元素的触摸移动
        }, { passive: false });
    }

    /**
     * 初始化懒加载
     */
    function initLazyLoad() {
        const lazyImages = document.querySelectorAll('img[data-src], img.lazy-img');
        
        const imageObserver = new IntersectionObserver((entries, observer) => {
            entries.forEach(entry => {
                if (entry.isIntersecting) {
                    const img = entry.target;
                    const src = img.dataset.src || img.getAttribute('data-src');
                    
                    if (src) {
                        img.src = src;
                        img.classList.add('lazy-loaded');
                    }
                    
                    observer.unobserve(img);
                }
            });
        }, {
            rootMargin: '50px 0px',
            threshold: 0.01
        });
        
        lazyImages.forEach(img => {
            imageObserver.observe(img);
        });
    }

    /**
     * 设置页面标题
     */
    function setupPageTitle() {
        const pageTitle = document.querySelector('.page-title');
        if (pageTitle) {
            document.title = pageTitle.textContent || 'HuSNS';
        }
    }

    /**
     * 添加键盘事件监听
     */
    function addKeyboardListeners() {
        // 监听回车事件
        document.addEventListener('keydown', (e) => {
            if (e.key === 'Enter') {
                // 可以在这里处理回车提交表单等逻辑
                const activeElement = document.activeElement;
                if (activeElement && activeElement.form) {
                    // 检查是否是多行输入
                    if (activeElement.tagName === 'TEXTAREA') {
                        return; // 允许textarea中的回车
                    }
                    activeElement.form.dispatchEvent(new Event('submit'));
                }
            }
        });
        
        // 监听键盘高度变化（移动端）
        window.addEventListener('resize', handleKeyboardResize);
    }

    /**
     * 处理键盘尺寸变化
     */
    function handleKeyboardResize() {
        // 可以在这里处理键盘弹出时的布局调整
        const keyboardHeight = window.innerHeight - document.documentElement.clientHeight;
        if (keyboardHeight > 0) {
            // 键盘已弹出
            document.body.style.paddingBottom = keyboardHeight + 'px';
        } else {
            document.body.style.paddingBottom = '';
        }
    }

    /**
     * 处理滚动事件
     */
    function handleScrollEvents() {
        let lastScrollTop = 0;
        
        window.addEventListener('scroll', () => {
            const scrollTop = window.pageYOffset || document.documentElement.scrollTop;
            
            // 检测上下滚动
            const isScrollingDown = scrollTop > lastScrollTop;
            
            // 可以在这里添加滚动相关的动画效果
            
            lastScrollTop = scrollTop;
        }, { passive: true });
    }

    /**
     * 初始化下拉刷新
     */
    function initPullRefresh() {
        const pullRefresh = document.querySelector('.pull-refresh');
        if (!pullRefresh) return;
        
        let startY = 0;
        let currentY = 0;
        let isPulling = false;
        
        pullRefresh.addEventListener('touchstart', (e) => {
            if (window.pageYOffset === 0) {
                startY = e.touches[0].clientY;
                isPulling = true;
            }
        }, { passive: true });
        
        pullRefresh.addEventListener('touchmove', (e) => {
            if (!isPulling) return;
            
            currentY = e.touches[0].clientY;
            const diff = currentY - startY;
            
            if (diff > 0 && window.pageYOffset === 0) {
                // 阻止默认行为以允许下拉
                e.preventDefault();
                
                const progress = Math.min(diff / 100, 1);
                const pullIndicator = document.querySelector('.pull-indicator');
                
                if (pullIndicator) {
                    pullIndicator.style.transform = `translateY(${diff}px)`;
                    pullIndicator.style.opacity = progress;
                    
                    if (progress >= 1) {
                        pullIndicator.textContent = '松开刷新';
                    } else {
                        pullIndicator.textContent = '下拉刷新';
                    }
                }
            }
        }, { passive: false });
        
        pullRefresh.addEventListener('touchend', () => {
            if (!isPulling) return;
            
            const diff = currentY - startY;
            
            if (diff > 100) {
                // 触发刷新
                triggerRefresh();
            }
            
            // 重置状态
            const pullIndicator = document.querySelector('.pull-indicator');
            if (pullIndicator) {
                pullIndicator.style.transform = 'translateY(0)';
                pullIndicator.style.opacity = '0';
            }
            
            isPulling = false;
        });
    }

    /**
     * 触发刷新
     */
    function triggerRefresh() {
        // 触发自定义刷新事件
        const refreshEvent = new CustomEvent('pullRefresh', {
            detail: { timestamp: Date.now() }
        });
        document.dispatchEvent(refreshEvent);
    }

    /**
     * 设置页面数据
     */
    function setupPageData() {
        // 获取页面数据属性
        const body = document.body;
        if (body) {
            MOBILE_APP.config.userId = body.dataset.userId || '';
            MOBILE_APP.config.pageType = body.dataset.pageType || '';
            MOBILE_APP.config.pageData = body.dataset.pageData ? JSON.parse(body.dataset.pageData) : {};
        }
    }

    /**
     * 处理页面可见性变化
     */
    function handleVisibilityChange() {
        document.addEventListener('visibilitychange', () => {
            if (document.hidden) {
                // 页面变为不可见
                // 可以暂停动画、视频等
            } else {
                // 页面变为可见，刷新未读消息数量
                loadUnreadMessageCount();
            }
        });
    }

    /**
     * 添加点击事件委托
     */
    function addClickDelegation() {
        document.addEventListener('click', (e) => {
            const target = e.target;
            
            // 处理返回按钮
            if (target.closest('.app-header-back')) {
                handleBackNavigation();
            }
            
            // 处理导航栏点击
            if (target.closest('.app-tabbar-item')) {
                handleTabbarClick(target.closest('.app-tabbar-item'));
            }
            
            // 处理卡片点击
            if (target.closest('.post-card')) {
                handlePostCardClick(target.closest('.post-card'));
            }
            
            // 处理点赞按钮点击
            if (target.closest('[data-action="like"]')) {
                handleLikeClick(target.closest('[data-action="like"]'));
            }
            
            // 处理收藏按钮点击
            if (target.closest('[data-action="favorite"]')) {
                handleFavoriteClick(target.closest('[data-action="favorite"]'));
            }
        });
    }
    
    /**
     * 处理点赞按钮点击（统一点赞系统）
     * 支持列表页和详情页两种按钮结构
     */
    function handleLikeClick(button) {
        const postId = button.dataset.id || button.dataset.postId;
        if (!postId) return;
        
        // 检查登录状态（支持多种检查方式）
        const isLogged = typeof checkLogin === 'function' ? checkLogin() : 
                        (typeof window.LOGGED_IN !== 'undefined' ? window.LOGGED_IN : false);
        if (!isLogged) {
            if (typeof openLoginModal === 'function') {
                openLoginModal();
            } else {
                showToast('请先登录');
            }
            return;
        }
        
        const isLiked = button.classList.contains('liked');
        // 支持列表页和详情页的两种类名
        const countElement = button.querySelector('.moment-action-count, .detail-action-count');
        const currentCount = parseInt(countElement?.textContent) || 0;
        
        // 先更新UI
        button.classList.toggle('liked');
        
        if (isLiked) {
            if (countElement) countElement.textContent = currentCount - 1;
            // 支持列表页和详情页的图标选择器
            const iconEl = button.querySelector('.moment-action-icon .iconify, .detail-action-icon, .iconify');
            if (iconEl && iconEl.tagName === 'SPAN') {
                // 列表页使用 iconify
                iconEl.setAttribute('data-icon', 'mdi:heart-outline');
            } else if (iconEl && iconEl.tagName === 'SVG') {
                // 详情页使用 SVG，修改 fill 属性
                iconEl.setAttribute('fill', 'currentColor');
            }
        } else {
            if (countElement) countElement.textContent = currentCount + 1;
            const iconEl = button.querySelector('.moment-action-icon .iconify, .detail-action-icon, .iconify');
            if (iconEl && iconEl.tagName === 'SPAN') {
                iconEl.setAttribute('data-icon', 'mdi:heart');
            } else if (iconEl && iconEl.tagName === 'SVG') {
                iconEl.setAttribute('fill', '#ff4757');
            }
        }
        
        // 调用API
        const baseUrl = window.BASE_URL || window.location.origin;
        const apiUrl = isLiked ? baseUrl + '/?r=mobileApi/unlike' : baseUrl + '/?r=mobileApi/like';
        
        fetch(apiUrl, {
            method: 'POST',
            credentials: 'include',
            headers: {'Content-Type': 'application/json'},
            body: JSON.stringify({id: postId})
        }).then(r => r.json()).then(data => {
            if (data.code !== 0) {
                // 失败回滚
                button.classList.toggle('liked');
                if (countElement) countElement.textContent = currentCount;
                const iconEl = button.querySelector('.moment-action-icon .iconify, .detail-action-icon, .iconify');
                if (iconEl && iconEl.tagName === 'SPAN') {
                    iconEl.setAttribute('data-icon', isLiked ? 'mdi:heart' : 'mdi:heart-outline');
                } else if (iconEl && iconEl.tagName === 'SVG') {
                    iconEl.setAttribute('fill', isLiked ? '#ff4757' : 'currentColor');
                }
                showToast(data.message || '操作失败');
            } else if (data.data && data.data.likes !== undefined && countElement) {
                // 成功时更新点赞数（确保与后端同步）
                countElement.textContent = data.data.likes;
            }
        }).catch(() => {
            // 网络错误回滚
            button.classList.toggle('liked');
            if (countElement) countElement.textContent = currentCount;
            const iconEl = button.querySelector('.moment-action-icon .iconify, .detail-action-icon, .iconify');
            if (iconEl && iconEl.tagName === 'SPAN') {
                iconEl.setAttribute('data-icon', isLiked ? 'mdi:heart' : 'mdi:heart-outline');
            } else if (iconEl && iconEl.tagName === 'SVG') {
                iconEl.setAttribute('fill', isLiked ? '#ff4757' : 'currentColor');
            }
            showToast('网络错误，请稍后重试');
        });
    }
    
    /**
     * 处理收藏按钮点击（统一收藏系统）
     */
    function handleFavoriteClick(button) {
        const postId = button.dataset.id || button.dataset.postId;
        if (!postId) return;
        
        const isFavorited = button.classList.contains('favorited');
        
        // 先更新UI
        button.classList.toggle('favorited');
        const iconEl = button.querySelector('.action-icon .iconify, .iconify');
        if (iconEl) {
            iconEl.setAttribute('data-icon', isFavorited ? 'mdi:star-outline' : 'mdi:star');
        }
        
        // 调用API
        const baseUrl = window.BASE_URL || window.location.origin;
        const apiUrl = isFavorited ? baseUrl + '/?r=mobileApi/unfavorite' : baseUrl + '/?r=mobileApi/favorite';
        
        fetch(apiUrl, {
            method: 'POST',
            credentials: 'include',
            headers: {'Content-Type': 'application/json'},
            body: JSON.stringify({id: postId})
        }).then(r => r.json()).then(data => {
            if (data.code !== 0) {
                // 失败回滚
                button.classList.toggle('favorited');
                if (iconEl) {
                    iconEl.setAttribute('data-icon', isFavorited ? 'mdi:star' : 'mdi:star-outline');
                }
                showToast(data.message || '操作失败');
            }
        }).catch(() => {
            // 网络错误回滚
            button.classList.toggle('favorited');
            if (iconEl) {
                iconEl.setAttribute('data-icon', isFavorited ? 'mdi:star' : 'mdi:star-outline');
            }
            showToast('网络错误，请稍后重试');
        });
    }

    /**
     * 处理返回导航
     */
    function handleBackNavigation() {
        if (window.history.length > 1) {
            window.history.back();
        } else {
            // 如果没有历史记录，跳转到首页
            window.location.href = '/';
        }
    }

    /**
     * 处理导航栏点击
     */
    function handleTabbarClick(item) {
        const href = item.getAttribute('href');
        // 跳过使用内联 onclick 的按钮（发布、消息、我的）
        if (item.hasAttribute('onclick')) {
            return;
        }
        if (href && href !== '#' && href !== 'javascript:void(0)') {
            window.location.href = href;
        }
    }

    /**
     * 处理帖子卡片点击
     */
    function handlePostCardClick(card) {
        const postId = card.dataset.postId;
        if (postId) {
            window.location.href = `/post/${postId}`;
        }
    }

    /**
     * 处理图片点击
     */
    function handleImageClick(img) {
        // 可以在这里添加图片预览功能
        const src = img.src;
        if (src) {
            // 创建图片预览弹窗
            createImagePreview(src);
        }
    }

    /**
     * 创建图片预览
     */
    function createImagePreview(src) {
        const previewOverlay = document.createElement('div');
        previewOverlay.className = 'image-preview-overlay';
        previewOverlay.style.cssText = `
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: rgba(0,0,0,0.9);
            display: flex;
            align-items: center;
            justify-content: center;
            z-index: 9999;
            cursor: zoom-out;
        `;
        
        const previewImg = document.createElement('img');
        previewImg.src = src;
        previewImg.style.cssText = `
            max-width: 90%;
            max-height: 90%;
            object-fit: contain;
            animation: fadeIn 0.2s ease;
        `;
        
        previewOverlay.appendChild(previewImg);
        document.body.appendChild(previewOverlay);
        
        // 点击关闭
        previewOverlay.addEventListener('click', () => {
            document.body.removeChild(previewOverlay);
        });
        
        // ESC键关闭
        const handleEsc = (e) => {
            if (e.key === 'Escape') {
                document.body.removeChild(previewOverlay);
                document.removeEventListener('keydown', handleEsc);
            }
        };
        document.addEventListener('keydown', handleEsc);
    }

    /**
     * 设置主题颜色
     */
    function setupThemeColor() {
        const themeColor = document.querySelector('meta[name="theme-color"]');
        if (themeColor) {
            if (MOBILE_APP.isDarkMode) {
                themeColor.setAttribute('content', '#1c1c1e');
            } else {
                themeColor.setAttribute('content', '#ffffff');
            }
        }
    }

    /**
     * 初始化平滑滚动
     */
    function initSmoothScroll() {
        // 添加平滑滚动行为
        document.documentElement.style.scrollBehavior = 'smooth';
        
        // 处理锚点链接
        document.querySelectorAll('a[href^="#"]').forEach(anchor => {
            anchor.addEventListener('click', function(e) {
                e.preventDefault();
                
                const targetId = this.getAttribute('href');
                if (targetId === '#') return;
                
                const targetElement = document.querySelector(targetId);
                if (targetElement) {
                    targetElement.scrollIntoView({
                        behavior: 'smooth',
                        block: 'start'
                    });
                }
            });
        });
    }

    /**
     * 处理WebView环境
     */
    function handleWebViewEnvironment() {
        // 检查是否在App内打开
        const isInApp = /(iPhone|iPad|iPod|Android)/i.test(navigator.userAgent) && 
                       !/Safari/i.test(navigator.userAgent);
        
        if (isInApp) {
            // 添加App内特定的样式和行为
            document.body.classList.add('in-app');
        }
        
        // 处理iOS的安全区域
        if (/iPad|iPhone|iPod/.test(navigator.userAgent) && !window.MSStream) {
            document.documentElement.classList.add('ios-device');
        }
    }

    /**
     * 显示加载指示器
     */
    window.showLoading = function() {
        if (MOBILE_APP.isLoading) return;
        
        MOBILE_APP.isLoading = true;
        const loadingIndicator = document.querySelector('.loading-indicator');
        
        if (loadingIndicator) {
            loadingIndicator.style.display = 'flex';
        }
    };

    /**
     * 隐藏加载指示器
     */
    window.hideLoading = function() {
        MOBILE_APP.isLoading = false;
        const loadingIndicator = document.querySelector('.loading-indicator');
        
        if (loadingIndicator) {
            loadingIndicator.style.display = 'none';
        }
    };

    /**
     * 显示Toast消息
     */
    window.showToast = function(message, duration = 2000) {
        // 移除已存在的toast
        const existingToast = document.querySelector('.toast-message');
        if (existingToast) {
            document.body.removeChild(existingToast);
        }
        
        const toast = document.createElement('div');
        toast.className = 'toast-message';
        toast.style.cssText = `
            position: fixed;
            bottom: 80px;
            left: 50%;
            transform: translateX(-50%);
            background: rgba(0,0,0,0.8);
            color: white;
            padding: 12px 20px;
            border-radius: 20px;
            font-size: 14px;
            z-index: 9999;
            animation: fadeInUp 0.2s ease;
            max-width: 80%;
            text-align: center;
        `;
        toast.textContent = message;
        
        document.body.appendChild(toast);
        
        setTimeout(() => {
            toast.style.animation = 'fadeOutDown 0.2s ease';
            setTimeout(() => {
                if (document.body.contains(toast)) {
                    document.body.removeChild(toast);
                }
            }, 200);
        }, duration);
    };

    /**
     * 格式化时间
     */
    window.formatTime = function(timestamp) {
        const now = Date.now();
        const diff = now - timestamp * 1000;
        
        const minute = 60 * 1000;
        const hour = 60 * minute;
        const day = 24 * hour;
        const week = 7 * day;
        
        if (diff < minute) {
            return '刚刚';
        } else if (diff < hour) {
            return `${Math.floor(diff / minute)}分钟前`;
        } else if (diff < day) {
            return `${Math.floor(diff / hour)}小时前`;
        } else if (diff < week) {
            return `${Math.floor(diff / day)}天前`;
        } else {
            const date = new Date(timestamp * 1000);
            return `${date.getMonth() + 1}月${date.getDate()}日`;
        }
    };

    /**
     * 格式化数字
     */
    window.formatNumber = function(num) {
        if (num >= 10000) {
            return (num / 10000).toFixed(1) + '万';
        } else if (num >= 1000) {
            return (num / 1000).toFixed(1) + '千';
        }
        return num.toString();
    };

    /**
     * 防抖函数
     */
    window.debounce = function(func, wait) {
        let timeout;
        return function executedFunction(...args) {
            const later = () => {
                clearTimeout(timeout);
                func(...args);
            };
            clearTimeout(timeout);
            timeout = setTimeout(later, wait);
        };
    };

    /**
     * 节流函数
     */
    window.throttle = function(func, limit) {
        let inThrottle;
        return function executedFunction(...args) {
            if (!inThrottle) {
                func(...args);
                inThrottle = true;
                setTimeout(() => inThrottle = false, limit);
            }
        };
    };

    /**
     * 生成随机ID
     */
    window.generateId = function() {
        return Date.now().toString(36) + Math.random().toString(36).substr(2);
    };

    /**
     * 获取URL参数
     */
    window.getUrlParam = function(name) {
        const urlParams = new URLSearchParams(window.location.search);
        return urlParams.get(name);
    };

    /**
     * 设置URL参数
     */
    window.setUrlParam = function(name, value) {
        const urlParams = new URLSearchParams(window.location.search);
        urlParams.set(name, value);
        window.history.replaceState({}, '', `${window.location.pathname}?${urlParams.toString()}`);
    };

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

    // 添加全局动画样式
    const styleSheet = document.createElement('style');
    styleSheet.textContent = `
        @keyframes fadeIn {
            from { opacity: 0; }
            to { opacity: 1; }
        }
        
        @keyframes fadeInUp {
            from {
                opacity: 0;
                transform: translateX(-50%) translateY(20px);
            }
            to {
                opacity: 1;
                transform: translateX(-50%) translateY(0);
            }
        }
        
        @keyframes fadeOutDown {
            from {
                opacity: 1;
                transform: translateX(-50%) translateY(0);
            }
            to {
                opacity: 0;
                transform: translateX(-50%) translateY(20px);
            }
        }
        
        .toast-message {
            animation: fadeInUp 0.2s ease;
        }
    `;
    document.head.appendChild(styleSheet);

    /**
     * 处理发布按钮点击
     */
    window.handlePublishClick = function() {
        // 打开发布弹窗
        openModal('publishModal');
    };

    /**
     * 处理消息按钮点击
     */
    window.handleNotificationClick = function() {
        // 未登录时弹出登录弹窗
        if (!checkLogin()) {
            openModal('loginModal');
            return;
        }
        window.location.href = '/?r=mobile/notification';
    };

    /**
     * 处理我的按钮点击
     */
    window.handleProfileClick = function() {
        // 未登录时弹出登录弹窗
        if (!checkLogin()) {
            openModal('loginModal');
            return;
        }
        window.location.href = '/?r=mobile/profile';
    };
    
    // 页面加载完成后初始化
    document.addEventListener('DOMContentLoaded', initApp);
})();
