<?php
session_start();

// 数据存储配置
define('MOMENTS_FILE', __DIR__ . '/moments_data/moments.json');
define('PROFILE_FILE', __DIR__ . '/moments_data/profile.json');
define('CHAT_FILE', __DIR__ . '/moments_data/chat.json');
define('USERS_FILE', __DIR__ . '/moments_data/users.json');
define('PRIVATE_MESSAGES_FILE', __DIR__ . '/moments_data/private_messages.json'); // 新增私信数据文件
define('LIKES_FILE', __DIR__ . '/moments_data/likes.json'); // 新增点赞数据文件
define('ANNOUNCEMENT_FILE', __DIR__ . '/moments_data/announcement.json'); // 新增公告文件
define('AVATAR_DIR', __DIR__ . '/moments_data/avatars/');
define('MOMENT_IMG_DIR', __DIR__ . '/moments_data/images/');
define('MOMENT_VIDEO_DIR', __DIR__ . '/moments_data/videos/');
define('AUDIO_DIR', __DIR__ . '/moments_data/audios/'); // 新增音频目录
define('MAX_IMG_SIZE', 5 * 1024 * 1024);
define('MAX_VIDEO_SIZE', 50 * 1024 * 1024);
define('MAX_AUDIO_SIZE', 10 * 1024 * 1024); // 新增音频大小限制
define('MAX_IMG_COUNT', 9);

// 初始化目录
$requiredDirs = [dirname(MOMENTS_FILE), AVATAR_DIR, MOMENT_IMG_DIR, MOMENT_VIDEO_DIR, AUDIO_DIR];
foreach ($requiredDirs as $dir) {
    if (!file_exists($dir)) mkdir($dir, 0755, true);
}

// 初始化数据文件
if (!file_exists(MOMENTS_FILE)) file_put_contents(MOMENTS_FILE, json_encode([]));
if (!file_exists(PROFILE_FILE)) file_put_contents(PROFILE_FILE, json_encode([
    'nickname' => '游客',
    'avatar' => 'https://picsum.photos/60/60?default'
]));
if (!file_exists(CHAT_FILE)) file_put_contents(CHAT_FILE, json_encode([]));
if (!file_exists(USERS_FILE)) file_put_contents(USERS_FILE, json_encode([]));
if (!file_exists(PRIVATE_MESSAGES_FILE)) file_put_contents(PRIVATE_MESSAGES_FILE, json_encode([]));
if (!file_exists(LIKES_FILE)) file_put_contents(LIKES_FILE, json_encode([]));
if (!file_exists(ANNOUNCEMENT_FILE)) {
    file_put_contents(ANNOUNCEMENT_FILE, json_encode([
        'title' => '系统公告',
        'content' => '欢迎使用表白墙系统！',
        'enabled' => true,
        'update_time' => date('Y-m-d H:i:s'),
        'update_by' => '系统'
    ], JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE));
}

// 退出登录
if (isset($_GET['action']) && $_GET['action'] === 'logout') {
    session_destroy();
    header("Location: " . $_SERVER['PHP_SELF']);
    exit;
}

// 辅助函数
function readUsersData() {
    return json_decode(file_get_contents(USERS_FILE), true) ?: [];
}

function writeUsersData($data) {
    file_put_contents(USERS_FILE, json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE));
}

function validateVideo($tmpPath, $origName, $fileSize) {
    if ($fileSize > MAX_VIDEO_SIZE) return false;
    $allowedExts = ['mp4', 'avi', 'mov', 'wmv', 'flv', 'webm'];
    $ext = strtolower(pathinfo($origName, PATHINFO_EXTENSION));
    return in_array($ext, $allowedExts);
}

function validateImage($tmpPath, $origName, $fileSize) {
    if ($fileSize > MAX_IMG_SIZE) return false;
    $allowedExts = ['jpg', 'jpeg', 'png', 'gif', 'webp'];
    $ext = strtolower(pathinfo($origName, PATHINFO_EXTENSION));
    if (!in_array($ext, $allowedExts)) return false;
    $header = bin2hex(file_get_contents($tmpPath, false, null, 0, 8));
    $imgHeaders = ['ffd8ffe0', '89504e47', '47494638', '52494646'];
    foreach ($imgHeaders as $h) {
        if (strpos($header, $h) === 0) return true;
    }
    return false;
}

function validateAudio($tmpPath, $origName, $fileSize) {
    if ($fileSize > MAX_AUDIO_SIZE) return false;
    $allowedExts = ['mp3', 'wav', 'ogg', 'm4a'];
    $ext = strtolower(pathinfo($origName, PATHINFO_EXTENSION));
    return in_array($ext, $allowedExts);
}

function readMomentsData() {
    return json_decode(file_get_contents(MOMENTS_FILE), true) ?: [];
}

function writeMomentsData($data) {
    file_put_contents(MOMENTS_FILE, json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE));
}

function readProfileData() {
    return json_decode(file_get_contents(PROFILE_FILE), true) ?: ['nickname' => '游客', 'avatar' => 'https://picsum.photos/60/60?default'];
}

function writeProfileData($data) {
    file_put_contents(PROFILE_FILE, json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE));
}

function readChatData() {
    $data = json_decode(file_get_contents(CHAT_FILE), true) ?: [];
    // 按时间倒序排序（最新的在数组末尾）
    usort($data, function($a, $b) {
        return strtotime($a['time']) - strtotime($b['time']); // 正序：最早的在前
    });
    return $data;
}

function writeChatData($data) {
    file_put_contents(CHAT_FILE, json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE));
}

// 新增：私信相关函数
function readPrivateMessages() {
    return json_decode(file_get_contents(PRIVATE_MESSAGES_FILE), true) ?: [];
}

function writePrivateMessages($data) {
    file_put_contents(PRIVATE_MESSAGES_FILE, json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE));
}

// 新增：公告相关函数
function readAnnouncement() {
    if (!file_exists(ANNOUNCEMENT_FILE)) {
        return [
            'title' => '系统公告',
            'content' => '欢迎使用表白墙系统！',
            'enabled' => true,
            'update_time' => date('Y-m-d H:i:s'),
            'update_by' => '系统'
        ];
    }
    return json_decode(file_get_contents(ANNOUNCEMENT_FILE), true) ?: [];
}

function getUserList($excludeId = null) {
    $users = readUsersData();
    if ($excludeId) {
        $users = array_filter($users, function($user) use ($excludeId) {
            return $user['id'] !== $excludeId;
        });
    }
    return array_values($users);
}

function getPrivateMessagesBetween($userId1, $userId2) {
    $messages = readPrivateMessages();
    $filtered = [];
    
    foreach ($messages as $message) {
        if (($message['sender_id'] === $userId1 && $message['receiver_id'] === $userId2) ||
            ($message['sender_id'] === $userId2 && $message['receiver_id'] === $userId1)) {
            $filtered[] = $message;
        }
    }
    
    // 按时间排序
    usort($filtered, function($a, $b) {
        return strtotime($a['time']) - strtotime($b['time']);
    });
    
    return $filtered;
}

function getUnreadCount($userId) {
    $messages = readPrivateMessages();
    $count = 0;
    
    foreach ($messages as $message) {
        if ($message['receiver_id'] === $userId && !($message['read'] ?? false)) {
            $count++;
        }
    }
    
    return $count;
}

function markMessagesAsRead($userId1, $userId2) {
    $messages = readPrivateMessages();
    $updated = false;
    
    foreach ($messages as &$message) {
        if ($message['sender_id'] === $userId2 && $message['receiver_id'] === $userId1 && !($message['read'] ?? false)) {
            $message['read'] = true;
            $message['read_time'] = date('Y-m-d H:i:s');
            $updated = true;
        }
    }
    
    if ($updated) {
        writePrivateMessages($messages);
    }
}

// 新增：点赞相关函数
function readLikesData() {
    return json_decode(file_get_contents(LIKES_FILE), true) ?: [];
}

function writeLikesData($data) {
    file_put_contents(LIKES_FILE, json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE));
}

function getLikesForMoment($momentIndex) {
    $likes = readLikesData();
    $momentLikes = [];
    
    foreach ($likes as $like) {
        if ($like['moment_index'] == $momentIndex) {
            $momentLikes[] = $like;
        }
    }
    
    return $momentLikes;
}

function getUserLikedMoment($momentIndex, $userId) {
    $likes = readLikesData();
    
    foreach ($likes as $like) {
        if ($like['moment_index'] == $momentIndex && $like['user_id'] === $userId) {
            return true;
        }
    }
    
    return false;
}

function getLikeCount($momentIndex) {
    $likes = readLikesData();
    $count = 0;
    
    foreach ($likes as $like) {
        if ($like['moment_index'] == $momentIndex) {
            $count++;
        }
    }
    
    return $count;
}

// ========== 搜索用户 API ==========
if (isset($_GET['action']) && $_GET['action'] === 'search_users' && isset($_SESSION['is_login']) && $_SESSION['is_login']) {
    $keyword = isset($_GET['keyword']) ? trim($_GET['keyword']) : '';
    
    // 读取所有用户
    $users = readUsersData();
    $currentUserId = $_SESSION['user_id'];
    $searchResults = [];
    
    foreach ($users as $user) {
        // 排除当前用户
        if ($user['id'] === $currentUserId) {
            continue;
        }
        
        // 确保用户有必要的字段
        if (!isset($user['bio'])) {
            $user['bio'] = '这个人很懒，还没有写个人介绍...';
        }
        if (!isset($user['avatar'])) {
            $user['avatar'] = 'https://picsum.photos/60/60?default';
        }
        
        // 如果没有关键词，显示所有用户
        if (empty($keyword)) {
            $searchResults[] = $user;
            continue;
        }
        
        // 搜索匹配
        $found = false;
        $keywordLower = strtolower($keyword);
        
        if (isset($user['nickname']) && stripos($user['nickname'], $keyword) !== false) {
            $found = true;
        }
        if (!$found && isset($user['username']) && stripos($user['username'], $keyword) !== false) {
            $found = true;
        }
        if (!$found && isset($user['bio']) && stripos($user['bio'], $keyword) !== false) {
            $found = true;
        }
        
        if ($found) {
            $searchResults[] = $user;
        }
    }
    
    // 返回结果
    header('Content-Type: application/json');
    echo json_encode([
        'success' => true,
        'results' => $searchResults,
        'count' => count($searchResults),
        'keyword' => $keyword
    ]);
    exit;
}

// 登录逻辑
$loginError = '';
$registerError = '';
$registerSuccess = '';

// 用户注册逻辑
if (isset($_POST['register_submit'])) {
    $username = trim($_POST['reg_username']);
    $password = $_POST['reg_password'];
    $confirmPassword = $_POST['reg_confirm_password'];
    $nickname = trim($_POST['reg_nickname']);
    
    // 验证输入
    if (empty($username) || empty($password) || empty($confirmPassword) || empty($nickname)) {
        $registerError = '所有字段都必须填写';
    } elseif (strlen($username) < 3 || strlen($username) > 20) {
        $registerError = '用户名长度必须在3-20个字符之间';
    } elseif (strlen($password) < 6) {
        $registerError = '密码长度至少6个字符';
    } elseif ($password !== $confirmPassword) {
        $registerError = '两次输入的密码不一致';
    } elseif (strlen($nickname) < 2 || strlen($nickname) > 20) {
        $registerError = '昵称长度必须在2-20个字符之间';
    } else {
        // 检查用户名是否已存在
        $users = readUsersData();
        foreach ($users as $user) {
            if ($user['username'] === $username) {
                $registerError = '用户名已存在';
                break;
            }
        }
        
        if (!$registerError) {
            // 创建新用户
            $newUser = [
                'id' => uniqid() . '_' . time(),
                'username' => $username,
                'password' => password_hash($password, PASSWORD_DEFAULT),
                'nickname' => $nickname,
                'bio' => '这个人很懒，还没有写个人介绍...',
                'avatar' => 'https://picsum.photos/60/60?random=' . rand(1, 1000),
                'register_time' => date('Y-m-d H:i:s'),
                'last_login' => null,
                'is_active' => true,
                'last_active' => date('Y-m-d H:i:s')
            ];
            
            $users[] = $newUser;
            writeUsersData($users);
            
            $registerSuccess = '注册成功！请登录';
            header("Location: " . $_SERVER['PHP_SELF'] . "?showLogin=1&registerSuccess=1");
            exit;
        }
    }
    
    if ($registerError) {
        header("Location: " . $_SERVER['PHP_SELF'] . "?showRegister=1&error=" . urlencode($registerError));
        exit;
    }
}

// 用户登录逻辑
if (isset($_POST['login_submit'])) {
    $username = trim($_POST['username']);
    $password = $_POST['password'];
    
    if (empty($username) || empty($password)) {
        $loginError = '请输入用户名和密码';
    } else {
        // 检查用户是否存在
        $users = readUsersData();
        $userFound = false;
        
        foreach ($users as $user) {
            if ($user['username'] === $username && password_verify($password, $user['password'])) {
                // 确保用户有bio字段（向后兼容）
                if (!isset($user['bio'])) {
                    $user['bio'] = '这个人很懒，还没有写个人介绍...';
                }
                
                // 登录成功
                $_SESSION['is_login'] = true;
                $_SESSION['user_id'] = $user['id'];
                $_SESSION['username'] = $user['username'];
                $_SESSION['nickname'] = $user['nickname'];
                $_SESSION['bio'] = $user['bio'];
                $_SESSION['avatar'] = $user['avatar'];
                $_SESSION['register_time'] = $user['register_time'] ?? date('Y-m-d H:i:s');
                
                // 更新用户最后登录时间
                $user['last_login'] = date('Y-m-d H:i:s');
                $user['last_active'] = date('Y-m-d H:i:s');
                $users = array_map(function($u) use ($user) {
                    return $u['id'] === $user['id'] ? $user : $u;
                }, $users);
                writeUsersData($users);
                
                // 更新当前个人资料
                $profile = readProfileData();
                $profile['nickname'] = $user['nickname'];
                $profile['avatar'] = $user['avatar'];
                writeProfileData($profile);
                
                $userFound = true;
                break;
            }
        }
        
        if (!$userFound) {
            // 检查是否为管理员账户（向后兼容）
            if ($username === 'admin' && $password === '123456') {
                $_SESSION['is_login'] = true;
                $_SESSION['user_id'] = 'admin';
                $_SESSION['username'] = 'admin';
                $_SESSION['nickname'] = '管理员';
                $_SESSION['avatar'] = 'https://picsum.photos/60/60?admin';
                $_SESSION['bio'] = '系统管理员';
                $_SESSION['register_time'] = date('Y-m-d H:i:s');
                
                // 更新当前个人资料
                $profile = readProfileData();
                $profile['nickname'] = '管理员';
                writeProfileData($profile);
            } else {
                $loginError = '用户名或密码错误';
            }
        }
    }
    
    if ($loginError) {
        header("Location: " . $_SERVER['PHP_SELF'] . "?showLogin=1&error=" . urlencode($loginError));
        exit;
    } else {
        header("Location: " . $_SERVER['PHP_SELF']);
        exit;
    }
}

// 点赞/取消点赞 - 修复无法取消的问题
if (isset($_GET['action']) && $_GET['action'] === 'toggle_like' && isset($_GET['moment_index']) && $_SESSION['is_login']) {
    $momentIndex = (int)$_GET['moment_index'];
    $userId = $_SESSION['user_id'];
    $userNickname = $_SESSION['nickname'];
    
    $likes = readLikesData();
    $liked = false;
    $foundIndex = -1;
    
    // 修复：正确检查是否已经点赞
    foreach ($likes as $index => $like) {
        if ($like['moment_index'] == $momentIndex && $like['user_id'] === $userId) {
            $foundIndex = $index;
            $liked = true;
            break;
        }
    }
    
    if ($liked && $foundIndex !== -1) {
        // 取消点赞 - 确保正确删除
        array_splice($likes, $foundIndex, 1);
    } else {
        // 点赞
        $likes[] = [
            'moment_index' => $momentIndex,
            'user_id' => $userId,
            'user_nickname' => $userNickname,
            'user_avatar' => $_SESSION['avatar'],
            'time' => date('Y-m-d H:i:s')
        ];
    }
    
    writeLikesData(array_values($likes));
    
    // 返回JSON响应
    header('Content-Type: application/json');
    echo json_encode([
        'success' => true,
        'liked' => !$liked, // 修复：返回新的状态
        'like_count' => getLikeCount($momentIndex),
        'likes' => getLikesForMoment($momentIndex)
    ]);
    exit;
}

// 获取点赞列表
if (isset($_GET['action']) && $_GET['action'] === 'get_likes' && isset($_GET['moment_index'])) {
    $momentIndex = (int)$_GET['moment_index'];
    
    header('Content-Type: application/json');
    echo json_encode([
        'success' => true,
        'like_count' => getLikeCount($momentIndex),
        'likes' => getLikesForMoment($momentIndex),
        'user_liked' => $_SESSION['is_login'] ? getUserLikedMoment($momentIndex, $_SESSION['user_id']) : false
    ]);
    exit;
}

// 发送私信
if (isset($_POST['send_private_message']) && $_SESSION['is_login']) {
    $receiverId = $_POST['receiver_id'];
    $message = trim($_POST['message_content']);
    $messageType = $_POST['message_type'] ?? 'text';
    $uploadedFiles = [];
    $duration = 0;
    
    if (empty($message) && $messageType === 'text') {
        echo "<script>alert('消息内容不能为空！');history.back();</script>";
        exit;
    }
    
    // 处理文件上传
    if (isset($_FILES['private_message_file']) && $_FILES['private_message_file']['error'] === UPLOAD_ERR_OK) {
        $file = $_FILES['private_message_file'];
        if ($messageType === 'image' && validateImage($file['tmp_name'], $file['name'], $file['size'])) {
            $ext = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
            $newName = uniqid() . "_" . time() . "." . $ext;
            $targetPath = MOMENT_IMG_DIR . $newName;
            if (move_uploaded_file($file['tmp_name'], $targetPath)) {
                $uploadedFiles[] = 'moments_data/images/' . $newName;
            }
        } elseif ($messageType === 'video' && validateVideo($file['tmp_name'], $file['name'], $file['size'])) {
            $ext = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
            $newName = uniqid() . "_" . time() . "." . $ext;
            $targetPath = MOMENT_VIDEO_DIR . $newName;
            if (move_uploaded_file($file['tmp_name'], $targetPath)) {
                $uploadedFiles[] = 'moments_data/videos/' . $newName;
            }
        } elseif ($messageType === 'audio' && validateAudio($file['tmp_name'], $file['name'], $file['size'])) {
            $ext = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
            $newName = uniqid() . "_" . time() . "." . $ext;
            $targetPath = AUDIO_DIR . $newName;
            if (move_uploaded_file($file['tmp_name'], $targetPath)) {
                $uploadedFiles[] = 'moments_data/audios/' . $newName;
                // 获取音频时长（这里简化处理，实际可能需要音频处理库）
                $duration = isset($_POST['audio_duration']) ? (int)$_POST['audio_duration'] : 0;
                $duration = min($duration, 60); // 限制最多60秒
            }
        } else {
            echo "<script>alert('文件无效或超出大小！');history.back();</script>";
            exit;
        }
    }
    
    $messages = readPrivateMessages();
    $newMessage = [
        'id' => uniqid() . '_' . time(),
        'sender_id' => $_SESSION['user_id'],
        'sender_nickname' => $_SESSION['nickname'],
        'sender_avatar' => $_SESSION['avatar'],
        'receiver_id' => $receiverId,
        'content' => $message,
        'type' => $messageType,
        'file' => !empty($uploadedFiles) ? $uploadedFiles[0] : '',
        'music_url' => trim($_POST['music_url'] ?? ''),
        'time' => date('Y-m-d H:i:s'),
        'read' => false,
        'read_time' => null
    ];
    
    // 如果是音频消息，添加时长信息
    if ($messageType === 'audio') {
        $newMessage['duration'] = $duration;
    }
    
    $messages[] = $newMessage;
    writePrivateMessages($messages);
    
    // 更新用户最后活跃时间
    $users = readUsersData();
    $users = array_map(function($user) {
        if ($user['id'] === $_SESSION['user_id']) {
            $user['last_active'] = date('Y-m-d H:i:s');
        }
        return $user;
    }, $users);
    writeUsersData($users);
    
    header("Location: " . $_SERVER['PHP_SELF'] . "?page=messages&chat_with=" . urlencode($receiverId));
    exit;
}

// 获取私信列表
if (isset($_GET['action']) && $_GET['action'] === 'get_conversations' && $_SESSION['is_login']) {
    $userId = $_SESSION['user_id'];
    $messages = readPrivateMessages();
    $conversations = [];
    $userCache = [];
    
    // 获取所有与我相关的消息
    foreach ($messages as $message) {
        if ($message['sender_id'] === $userId || $message['receiver_id'] === $userId) {
            $otherUserId = $message['sender_id'] === $userId ? $message['receiver_id'] : $message['sender_id'];
            
            if (!isset($userCache[$otherUserId])) {
                $userCache[$otherUserId] = getUserById($otherUserId);
            }
            
            if (!isset($conversations[$otherUserId])) {
                $conversations[$otherUserId] = [
                    'user' => $userCache[$otherUserId],
                    'last_message' => $message,
                    'unread_count' => 0,
                    'message_count' => 0
                ];
            }
            
            $conversations[$otherUserId]['message_count']++;
            
            if ($message['receiver_id'] === $userId && !($message['read'] ?? false)) {
                $conversations[$otherUserId]['unread_count']++;
            }
            
            // 更新最后一条消息
            if (strtotime($message['time']) > strtotime($conversations[$otherUserId]['last_message']['time'])) {
                $conversations[$otherUserId]['last_message'] = $message;
            }
        }
    }
    
    // 转换为数组并排序
    $conversations = array_values($conversations);
    usort($conversations, function($a, $b) {
        return strtotime($b['last_message']['time']) - strtotime($a['last_message']['time']);
    });
    
    header('Content-Type: application/json');
    echo json_encode([
        'success' => true,
        'conversations' => $conversations,
        'total_unread' => getUnreadCount($userId)
    ]);
    exit;
}

// 获取用户列表（API接口）- 修复：移到正确位置，在 get_conversations 外面
if (isset($_GET['action']) && $_GET['action'] === 'get_users' && $_SESSION['is_login']) {
    $users = readUsersData();
    
    // 排除当前用户
    $filteredUsers = array_filter($users, function($user) {
        return $user['id'] !== $_SESSION['user_id'];
    });
    
    header('Content-Type: application/json');
    echo json_encode([
        'success' => true,
        'users' => array_values($filteredUsers)
    ]);
    exit;
}

// 获取与特定用户的私信
if (isset($_GET['action']) && $_GET['action'] === 'get_messages' && isset($_GET['user_id']) && $_SESSION['is_login']) {
    $userId = $_SESSION['user_id'];
    $otherUserId = $_GET['user_id'];
    
    // 标记为已读
    markMessagesAsRead($userId, $otherUserId);
    
    $messages = getPrivateMessagesBetween($userId, $otherUserId);
    
    header('Content-Type: application/json');
    echo json_encode([
        'success' => true,
        'messages' => $messages,
        'other_user' => getUserById($otherUserId)
    ]);
    exit;
}

// 获取用户信息
function getUserById($userId) {
    $users = readUsersData();
    foreach ($users as $user) {
        if ($user['id'] === $userId) {
            return $user;
        }
    }
    return null;
}

// 发布朋友圈（已登录用户）
if (isset($_POST['moment_submit']) && $_SESSION['is_login']) {
    $content = trim($_POST['content']);
    $uploadedImgs = [];
    $uploadedVideos = [];
    $musicUrl = trim($_POST['music_url'] ?? '');

    // 处理图片上传
    if (isset($_FILES['moment_imgs']) && $_FILES['moment_imgs']['error'][0] !== UPLOAD_ERR_NO_FILE) {
        $files = $_FILES['moment_imgs'];
        $imgCount = count($files['name']);
        if ($imgCount > MAX_IMG_COUNT) {
            echo "<script>alert('最多上传9张图！');history.back();</script>";
            exit;
        }

        for ($i = 0; $i < $imgCount; $i++) {
            if ($files['error'][$i] !== UPLOAD_ERR_OK || !is_uploaded_file($files['tmp_name'][$i])) continue;
            if (!validateImage($files['tmp_name'][$i], $files['name'][$i], $files['size'][$i])) {
                echo "<script>alert('{$files['name'][$i]} 无效或超出大小！');history.back();</script>";
                exit;
            }
            $ext = strtolower(pathinfo($files['name'][$i], PATHINFO_EXTENSION));
            $newName = uniqid() . "_" . time() . "." . $ext;
            $targetPath = MOMENT_IMG_DIR . $newName;
            if (move_uploaded_file($files['tmp_name'][$i], $targetPath)) {
                $uploadedImgs[] = 'moments_data/images/' . $newName;
            }
        }
    }

    // 处理视频上传
    if (isset($_FILES['moment_video']) && $_FILES['moment_video']['error'] === UPLOAD_ERR_OK) {
        $videoFile = $_FILES['moment_video'];
        if (validateVideo($videoFile['tmp_name'], $videoFile['name'], $videoFile['size'])) {
            $ext = strtolower(pathinfo($videoFile['name'], PATHINFO_EXTENSION));
            $newName = uniqid() . "_" . time() . "." . $ext;
            $targetPath = MOMENT_VIDEO_DIR . $newName;
            if (move_uploaded_file($videoFile['tmp_name'], $targetPath)) {
                $uploadedVideos[] = 'moments_data/videos/' . $newName;
            }
        } else {
            echo "<script>alert('视频文件无效或超出大小！');history.back();</script>";
            exit;
        }
    }

    // 保存动态
    if (!empty($content) || !empty($uploadedImgs) || !empty($uploadedVideos) || !empty($musicUrl)) {
        $moments = readMomentsData();
        $profile = readProfileData();
        array_unshift($moments, [
            'id' => uniqid() . '_' . time(),
            'avatar' => $profile['avatar'],
            'nickname' => $profile['nickname'],
            'content' => $content,
            'time' => date('Y-m-d H:i:s'),
            'images' => $uploadedImgs,
            'videos' => $uploadedVideos,
            'music_url' => $musicUrl,
            'comments' => [],
            'likes' => 0,
            'user_id' => $_SESSION['user_id'] ?? 'unknown'
        ]);
        writeMomentsData($moments);
    }

    header("Location: " . $_SERVER['PHP_SELF']);
    exit;
}

// 发布聊天消息
if (isset($_POST['chat_submit'])) {
    $chatContent = trim($_POST['chat_content']);
    $messageType = $_POST['message_type'] ?? 'text';
    $uploadedFiles = [];
    $duration = 0;
    
    // 修复：音乐类型不需要文本内容
    if (empty($chatContent) && $messageType === 'text') {
        echo "<script>alert('消息内容不能为空！');history.back();</script>";
        exit;
    }

    // 处理文件上传
    if (isset($_FILES['chat_file']) && $_FILES['chat_file']['error'] === UPLOAD_ERR_OK) {
        $file = $_FILES['chat_file'];
        if ($messageType === 'image' && validateImage($file['tmp_name'], $file['name'], $file['size'])) {
            $ext = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
            $newName = uniqid() . "_" . time() . "." . $ext;
            $targetPath = MOMENT_IMG_DIR . $newName;
            if (move_uploaded_file($file['tmp_name'], $targetPath)) {
                $uploadedFiles[] = 'moments_data/images/' . $newName;
            }
        } elseif ($messageType === 'video' && validateVideo($file['tmp_name'], $file['name'], $file['size'])) {
            $ext = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
            $newName = uniqid() . "_" . time() . "." . $ext;
            $targetPath = MOMENT_VIDEO_DIR . $newName;
            if (move_uploaded_file($file['tmp_name'], $targetPath)) {
                $uploadedFiles[] = 'moments_data/videos/' . $newName;
            }
        } elseif ($messageType === 'audio' && validateAudio($file['tmp_name'], $file['name'], $file['size'])) {
            $ext = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
            $newName = uniqid() . "_" . time() . "." . $ext;
            $targetPath = AUDIO_DIR . $newName;
            if (move_uploaded_file($file['tmp_name'], $targetPath)) {
                $uploadedFiles[] = 'moments_data/audios/' . $newName;
                // 获取音频时长
                $duration = isset($_POST['audio_duration']) ? (int)$_POST['audio_duration'] : 0;
                $duration = min($duration, 60); // 限制最多60秒
            }
        } else {
            echo "<script>alert('文件无效或超出大小！');history.back();</script>";
            exit;
        }
    }

    $musicUrl = trim($_POST['music_url'] ?? '');
    $sender = $_SESSION['is_login'] ? $_SESSION['nickname'] : '游客';
    $senderAvatar = $_SESSION['is_login'] ? $_SESSION['avatar'] : 'https://picsum.photos/40/40?default';

    $chatData = readChatData();
    $newChat = [
        'sender' => $sender,
        'sender_avatar' => $senderAvatar,
        'content' => $chatContent,
        'type' => $messageType,
        'file' => !empty($uploadedFiles) ? $uploadedFiles[0] : '',
        'music_url' => $musicUrl,
        'time' => date('Y-m-d H:i:s'),
        'user_id' => $_SESSION['user_id'] ?? 'guest'
    ];
    
    // 如果是音频消息，添加时长信息
    if ($messageType === 'audio') {
        $newChat['duration'] = $duration;
    }
    
        // 当前：新消息在开头（显示在上面）
    // array_unshift($chatData, $newChat);
    
    // 改为：新消息在末尾（显示在下面）
    $chatData[] = $newChat;
    writeChatData($chatData);

    header("Location: " . $_SERVER['PHP_SELF'] . "?page=chat");
    exit;
}

// 提交评论
if (isset($_POST['comment_submit'])) {
    $index = $_POST['moment_index'];
    $commentContent = trim($_POST['comment_content']);
    if (empty($commentContent)) {
        echo "<script>alert('评论不能为空！');history.back();</script>";
        exit;
    }

    $moments = readMomentsData();
    if (isset($moments[$index])) {
        $commenter = $_SESSION['is_login'] ? $_SESSION['nickname'] : '游客';
        $commenterAvatar = $_SESSION['is_login'] ? $_SESSION['avatar'] : 'https://picsum.photos/30/30?default';
        $moments[$index]['comments'][] = [
            'commenter' => $commenter,
            'commenter_avatar' => $commenterAvatar,
            'content' => $commentContent,
            'time' => date('Y-m-d H:i:s'),
            'user_id' => $_SESSION['user_id'] ?? 'guest'
        ];
        writeMomentsData($moments);
    }

    header("Location: " . $_SERVER['PHP_SELF']);
    exit;
}

// 编辑个人资料
if (isset($_POST['profile_submit']) && $_SESSION['is_login']) {
    $nickname = trim($_POST['nickname']);
    $bio = trim($_POST['bio'] ?? '');
    
    if (empty($nickname)) {
        echo "<script>alert('昵称不能为空！');history.back();</script>";
        exit;
    }
    
    // 验证个人介绍长度（最多75个字）
    if (mb_strlen($bio, 'UTF-8') > 75) {
        echo "<script>alert('个人介绍最多75个字！当前字数：' + mb_strlen(\$bio, 'UTF-8') + '字');history.back();</script>";
        exit;
    }
    
    // 更新会话中的昵称和个人介绍
    $_SESSION['nickname'] = $nickname;
    $_SESSION['bio'] = $bio;
    
    // 更新用户数据
    $users = readUsersData();
    $users = array_map(function($user) use ($nickname, $bio) {
        if ($user['id'] === $_SESSION['user_id']) {
            $user['nickname'] = $nickname;
            $user['bio'] = $bio;
            $user['last_active'] = date('Y-m-d H:i:s');
            
            // 处理头像上传
            if ($_FILES['avatar']['error'] === UPLOAD_ERR_OK && is_uploaded_file($_FILES['avatar']['tmp_name'])) {
                if (validateImage($_FILES['avatar']['tmp_name'], $_FILES['avatar']['name'], $_FILES['avatar']['size'])) {
                    $ext = strtolower(pathinfo($_FILES['avatar']['name'], PATHINFO_EXTENSION));
                    $newName = uniqid() . "_avatar." . $ext;
                    $targetPath = AVATAR_DIR . $newName;
                    move_uploaded_file($_FILES['avatar']['tmp_name'], $targetPath);
                    $user['avatar'] = 'moments_data/avatars/' . $newName;
                    $_SESSION['avatar'] = $user['avatar'];
                } else {
                    echo "<script>alert('头像无效或超出大小！');history.back();</script>";
                    exit;
                }
            }
        }
        return $user;
    }, $users);
    writeUsersData($users);
    
    // 更新个人资料文件
    $profile = readProfileData();
    $profile['nickname'] = $nickname;
    if (isset($_SESSION['avatar'])) {
        $profile['avatar'] = $_SESSION['avatar'];
    }
    writeProfileData($profile);
    
    header("Location: " . $_SERVER['PHP_SELF']);
    exit;
}

// 读取数据
$allMoments = readMomentsData();
$chatMessages = readChatData();
$userProfile = readProfileData();
$announcement = readAnnouncement();
$isLogin = isset($_SESSION['is_login']) && $_SESSION['is_login'];
$currentPage = $_GET['page'] ?? 'moments';
$chatWithUserId = $_GET['chat_with'] ?? null;

// 获取错误和成功消息
if (isset($_GET['error'])) {
    $loginError = urldecode($_GET['error']);
}
if (isset($_GET['registerSuccess'])) {
    $registerSuccess = '注册成功！请登录';
}
// 处理base64语音数据
if (isset($_POST['voice_data']) && $_SESSION['is_login']) {
    $voiceData = $_POST['voice_data'];
    $duration = intval($_POST['duration'] ?? 0);
    $context = $_POST['context'] ?? 'chat';
    $receiverId = $_POST['receiver_id'] ?? '';
    
    // 验证数据
    if (empty($voiceData) || $duration < 1) {
        echo json_encode(['success' => false, 'error' => '无效的语音数据']);
        exit;
    }
    
    // 解码base64数据
    if (strpos($voiceData, 'data:audio/') === 0) {
        // 格式：data:audio/webm;base64,xxxxxxxx
        $voiceData = substr($voiceData, strpos($voiceData, 'base64,') + 7);
    }
    
    $audioBinary = base64_decode($voiceData);
    
    if ($audioBinary) {
        // 确定文件扩展名
        $extension = 'mp3'; // 默认
        if (strpos($_SERVER['CONTENT_TYPE'] ?? '', 'webm') !== false || 
            strpos($voiceData, 'webm') !== false) {
            $extension = 'webm';
        } elseif (strpos($_SERVER['CONTENT_TYPE'] ?? '', 'mp4') !== false) {
            $extension = 'm4a';
        } elseif (strpos($_SERVER['CONTENT_TYPE'] ?? '', 'ogg') !== false) {
            $extension = 'ogg';
        }
        
        // 保存文件
        $filename = uniqid() . '_voice.' . $extension;
        $filepath = AUDIO_DIR . $filename;
        
        if (file_put_contents($filepath, $audioBinary)) {
            $audioUrl = 'moments_data/audios/' . $filename;
            
            // 保存到聊天
            if ($context === 'chat') {
                $chatData = readChatData();
                $newChat = [
                    'sender' => $_SESSION['nickname'],
                    'sender_avatar' => $_SESSION['avatar'],
                    'content' => '语音消息',
                    'type' => 'audio',
                    'file' => $audioUrl,
                    'music_url' => '',
                    'time' => date('Y-m-d H:i:s'),
                    'user_id' => $_SESSION['user_id'],
                    'duration' => $duration
                ];
                array_unshift($chatData, $newChat);
                writeChatData($chatData);
                
                echo json_encode(['success' => true, 'audio_url' => $audioUrl]);
                
            // 保存到私信
            } elseif ($context === 'private' && $receiverId) {
                $messages = readPrivateMessages();
                $newMessage = [
                    'id' => uniqid() . '_' . time(),
                    'sender_id' => $_SESSION['user_id'],
                    'sender_nickname' => $_SESSION['nickname'],
                    'sender_avatar' => $_SESSION['avatar'],
                    'receiver_id' => $receiverId,
                    'content' => '语音消息',
                    'type' => 'audio',
                    'file' => $audioUrl,
                    'music_url' => '',
                    'time' => date('Y-m-d H:i:s'),
                    'read' => false,
                    'read_time' => null,
                    'duration' => $duration
                ];
                $messages[] = $newMessage;
                writePrivateMessages($messages);
                
                echo json_encode(['success' => true, 'audio_url' => $audioUrl]);
            }
            exit;
        }
    }
    
    echo json_encode(['success' => false, 'error' => '保存失败']);
    exit;
}
?>

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>申集初中表白墙</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <style>
:root {
    /* ========== 薰衣草紫梦幻配色 ========== */
    --primary-color: #7B2CBF;        /* 深紫 - 主要按钮颜色 */
    --primary-dark: #6A1B9A;         /* 更深紫 - 悬停状态 */
    --primary-light: #E6E6FA;        /* 淡薰衣草紫 - 主背景 */
    --secondary-color: #B3E0FF;      /* 淡天蓝 - 公告栏 */
    --danger-color: #FF6B6B;         /* 柔和红 - 危险操作 */
    --warning-color: #FFB347;        /* 柔和橙 */
    --bg-color: #E6E6FA;             /* 淡薰衣草紫背景 */
    --card-bg: #F2F2F2;              /* 浅米灰卡片 */
    --text-color: #3A006F;           /* 深紫/近黑文字 */
    --text-secondary: #999999;       /* 浅灰文字 */
    --border-color: #D8C8E6;         /* 浅灰紫边框 */
    --shadow-light: 0 2px 12px rgba(123, 44, 191, 0.1);
    --shadow-medium: 0 4px 20px rgba(123, 44, 191, 0.15);
    --radius-sm: 8px;
    --radius-md: 12px;
    --radius-lg: 16px;
    --radius-full: 9999px;
    --transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}

* {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
    -webkit-tap-highlight-color: transparent;
}

body {
    font-family: -apple-system, BlinkMacSystemFont, "PingFang SC", "Helvetica Neue", "Hiragino Sans GB", "Microsoft YaHei", sans-serif;
    background: var(--bg-color);
    color: var(--text-color);
    line-height: 1.6;
    -webkit-font-smoothing: antialiased;
    -moz-osx-font-smoothing: grayscale;
    overflow-x: hidden;
}

.container {
    max-width: 600px;
    margin: 0 auto;
    min-height: 100vh;
    background: var(--bg-color);
    position: relative;
    box-shadow: 0 0 30px rgba(123, 44, 191, 0.08);
}

/* 系统公告 - 精致小横幅 */
.announcement-banner {
    background: linear-gradient(135deg, #B3E0FF 0%, #99CCFF 100%);
    color: #0047AB;
    padding: 6px 12px;
    margin: 15px 16px 15px 16px; /* 修改这里：将 -10px 改为 15px */
    cursor: pointer;
    transition: var(--transition);
    position: relative;
    border-radius: 12px;
    overflow: hidden;
    animation: slideDown 0.5s ease;
    display: <?php echo $announcement['enabled'] ? 'block' : 'none'; ?>;
    box-shadow: 0 3px 10px rgba(179, 224, 255, 0.3);
    z-index: 10;
}

.announcement-banner:hover {
    background: linear-gradient(135deg, #99CCFF 0%, #B3E0FF 100%);
    transform: translateY(-2px);
    box-shadow: 0 5px 15px rgba(179, 224, 255, 0.4);
}

.announcement-content {
    display: flex;
    align-items: center;
    gap: 8px;
}

.announcement-icon {
    font-size: 16px;
    width: 24px;
    height: 24px;
    background: rgba(0, 71, 171, 0.2);
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    flex-shrink: 0;
}

.announcement-text {
    flex: 1;
    min-width: 0;
}

.announcement-title {
    font-weight: 600;
    font-size: 13px;
    margin-bottom: 2px;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}

.announcement-desc {
    font-size: 11px;
    opacity: 0.9;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}

.announcement-time {
    font-size: 9px;
    opacity: 0.7;
    text-align: right;
    margin-top: 2px;
    font-family: monospace;
}

/* 公告详情弹窗 - 毛玻璃精致版 */
.announcement-detail-modal {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(0, 0, 0, 0.4);
    display: none;
    justify-content: center;
    align-items: center;
    z-index: 2000;
    backdrop-filter: blur(20px) saturate(180%);
    -webkit-backdrop-filter: blur(20px) saturate(180%);
    animation: fadeIn 0.4s cubic-bezier(0.4, 0, 0.2, 1);
}

.announcement-detail-modal-content {
    width: 90%;
    max-width: 400px;
    background: rgba(255, 255, 255, 0.15);
    backdrop-filter: blur(30px) saturate(200%);
    -webkit-backdrop-filter: blur(30px) saturate(200%);
    border-radius: 24px;
    overflow: hidden;
    box-shadow: 
        0 20px 60px rgba(0, 0, 0, 0.25),
        0 8px 30px rgba(0, 0, 0, 0.1),
        inset 0 1px 0 rgba(255, 255, 255, 0.2),
        inset 0 0 0 1px rgba(255, 255, 255, 0.1);
    animation: modalSlideIn 0.5s cubic-bezier(0.16, 1, 0.3, 1);
    border: 1px solid rgba(255, 255, 255, 0.2);
}

@keyframes modalSlideIn {
    from {
        opacity: 0;
        transform: translateY(40px) scale(0.95);
    }
    to {
        opacity: 1;
        transform: translateY(0) scale(1);
    }
}

.announcement-detail-modal-header {
    padding: 28px 30px;
    text-align: center;
    font-size: 22px;
    font-weight: 700;
    color: white;
    background: linear-gradient(
        135deg,
        rgba(179, 224, 255, 0.4),
        rgba(153, 204, 255, 0.3)
    );
    backdrop-filter: blur(10px);
    -webkit-backdrop-filter: blur(10px);
    position: relative;
    border-bottom: 1px solid rgba(255, 255, 255, 0.1);
    text-shadow: 0 1px 2px rgba(0, 0, 0, 0.2);
    letter-spacing: 0.5px;
}

.announcement-detail-modal-header::after {
    content: '';
    position: absolute;
    bottom: 0;
    left: 50%;
    transform: translateX(-50%);
    width: 60px;
    height: 3px;
    background: linear-gradient(90deg, 
        transparent, 
        rgba(255, 255, 255, 0.6), 
        transparent);
    border-radius: 2px;
}

.announcement-detail-modal-body {
    padding: 30px;
    max-height: 60vh;
    overflow-y: auto;
    background: rgba(255, 255, 255, 0.08);
    backdrop-filter: blur(20px);
    -webkit-backdrop-filter: blur(20px);
}

.announcement-full-content {
    font-size: 17px;
    line-height: 1.7;
    color: rgba(255, 255, 255, 0.95);
    padding: 24px;
    background: rgba(255, 255, 255, 0.1);
    backdrop-filter: blur(15px);
    -webkit-backdrop-filter: blur(15px);
    border-radius: 16px;
    margin-bottom: 30px;
    box-shadow: 
        inset 0 0 0 1px rgba(255, 255, 255, 0.1),
        0 4px 20px rgba(0, 0, 0, 0.15);
    font-weight: 450;
    position: relative;
}

.announcement-full-content::before {
    content: '';
    position: absolute;
    top: -1px;
    left: -1px;
    right: -1px;
    bottom: -1px;
    background: linear-gradient(
        135deg,
        rgba(179, 224, 255, 0.2),
        rgba(255, 255, 255, 0.05)
    );
    border-radius: 17px;
    z-index: -1;
    pointer-events: none;
}

.announcement-meta {
    background: rgba(255, 255, 255, 0.08);
    backdrop-filter: blur(15px);
    -webkit-backdrop-filter: blur(15px);
    border-radius: 16px;
    padding: 24px;
    box-shadow: 
        inset 0 0 0 1px rgba(255, 255, 255, 0.1),
        0 4px 20px rgba(0, 0, 0, 0.15);
    position: relative;
    border: 1px solid rgba(255, 255, 255, 0.05);
}

.announcement-meta::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    height: 1px;
    background: linear-gradient(
        90deg,
        transparent,
        rgba(255, 255, 255, 0.3),
        transparent
    );
}

.announcement-meta-item {
    display: flex;
    align-items: center;
    margin-bottom: 16px;
    font-size: 15px;
    color: rgba(255, 255, 255, 0.85);
    padding: 12px 16px;
    background: rgba(255, 255, 255, 0.05);
    backdrop-filter: blur(10px);
    -webkit-backdrop-filter: blur(10px);
    border-radius: 12px;
    border: 1px solid rgba(255, 255, 255, 0.08);
    transition: all 0.3s ease;
    animation: itemFadeIn 0.5s ease-out;
    animation-fill-mode: backwards;
}

.announcement-meta-item:hover {
    background: rgba(255, 255, 255, 0.1);
    transform: translateX(4px);
    border-color: rgba(255, 255, 255, 0.15);
}

@keyframes itemFadeIn {
    from {
        opacity: 0;
        transform: translateY(8px);
    }
    to {
        opacity: 1;
        transform: translateY(0);
    }
}

.announcement-meta-item:last-child {
    margin-bottom: 0;
}

.announcement-meta-item:nth-child(1) { animation-delay: 0.1s; }
.announcement-meta-item:nth-child(2) { animation-delay: 0.2s; }
.announcement-meta-item:nth-child(3) { animation-delay: 0.3s; }

.announcement-meta-item::before {
    content: '';
    font-size: 18px;
    margin-right: 14px;
    opacity: 0.7;
}

.announcement-meta-item:nth-child(1)::before { content: '🕐'; }
.announcement-meta-item:nth-child(2)::before { content: '👤'; }
.announcement-meta-item:nth-child(3)::before { content: '📊'; }

.announcement-meta-item strong {
    color: rgba(255, 255, 255, 0.95);
    font-weight: 600;
    margin-right: 10px;
    min-width: 90px;
    text-shadow: 0 1px 1px rgba(0, 0, 0, 0.2);
}

/* 关闭按钮区域 */
.announcement-detail-modal .modal-actions {
    padding: 24px 30px 30px;
    background: linear-gradient(
        to top,
        rgba(0, 0, 0, 0.2),
        transparent
    );
    border-top: 1px solid rgba(255, 255, 255, 0.1);
    display: flex;
    justify-content: center;
    position: relative;
}

.announcement-detail-modal .modal-actions::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    height: 1px;
    background: linear-gradient(
        90deg,
        transparent,
        rgba(255, 255, 255, 0.2),
        transparent
    );
}

.announcement-detail-modal .modal-btn {
    flex: 1;
    padding: 16px 24px;
    border: none;
    background: linear-gradient(
        135deg,
        rgba(179, 224, 255, 0.3),
        rgba(153, 204, 255, 0.2)
    );
    color: rgba(255, 255, 255, 0.95);
    font-size: 16px;
    font-weight: 600;
    cursor: pointer;
    transition: all 0.3s ease;
    border-radius: 14px;
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 10px;
    box-shadow: 
        0 4px 15px rgba(0, 0, 0, 0.2),
        inset 0 1px 0 rgba(255, 255, 255, 0.2),
        inset 0 0 0 1px rgba(255, 255, 255, 0.1);
    backdrop-filter: blur(10px);
    -webkit-backdrop-filter: blur(10px);
    text-shadow: 0 1px 1px rgba(0, 0, 0, 0.2);
    position: relative;
    overflow: hidden;
}

.announcement-detail-modal .modal-btn::before {
    content: '';
    position: absolute;
    top: 0;
    left: -100%;
    width: 100%;
    height: 100%;
    background: linear-gradient(
        90deg,
        transparent,
        rgba(255, 255, 255, 0.1),
        transparent
    );
    transition: left 0.5s ease;
}

.announcement-detail-modal .modal-btn:hover {
    transform: translateY(-2px);
    box-shadow: 
        0 8px 25px rgba(0, 0, 0, 0.3),
        inset 0 1px 0 rgba(255, 255, 255, 0.3),
        inset 0 0 0 1px rgba(255, 255, 255, 0.2);
    background: linear-gradient(
        135deg,
        rgba(179, 224, 255, 0.4),
        rgba(153, 204, 255, 0.3)
    );
}

.announcement-detail-modal .modal-btn:hover::before {
    left: 100%;
}

.announcement-detail-modal .modal-btn:active {
    transform: translateY(0);
    box-shadow: 
        0 2px 10px rgba(0, 0, 0, 0.2),
        inset 0 1px 0 rgba(255, 255, 255, 0.1),
        inset 0 0 0 1px rgba(255, 255, 255, 0.1);
}

/* 滚动条样式 */
.announcement-detail-modal-body::-webkit-scrollbar {
    width: 6px;
}

.announcement-detail-modal-body::-webkit-scrollbar-track {
    background: rgba(255, 255, 255, 0.05);
    border-radius: 3px;
    backdrop-filter: blur(10px);
}

.announcement-detail-modal-body::-webkit-scrollbar-thumb {
    background: rgba(255, 255, 255, 0.15);
    border-radius: 3px;
    border: 1px solid rgba(255, 255, 255, 0.1);
    box-shadow: inset 0 0 6px rgba(0, 0, 0, 0.1);
}

.announcement-detail-modal-body::-webkit-scrollbar-thumb:hover {
    background: rgba(255, 255, 255, 0.2);
}

/* 响应式调整 */
@media (max-width: 480px) {
    .announcement-detail-modal-content {
        width: 92%;
        max-width: 92%;
        border-radius: 20px;
    }
    
    .announcement-detail-modal-header {
        padding: 24px;
        font-size: 20px;
    }
    
    .announcement-detail-modal-body {
        padding: 24px;
    }
    
    .announcement-full-content {
        font-size: 16px;
        padding: 20px;
        border-radius: 14px;
    }
    
    .announcement-meta {
        padding: 20px;
        border-radius: 14px;
    }
    
    .announcement-meta-item {
        font-size: 14px;
        padding: 10px 14px;
    }
    
    .announcement-detail-modal .modal-actions {
        padding: 20px 24px 24px;
    }
}
/* 微信风格顶部栏 */
.wechat-header {
    height: 88px;
    background: linear-gradient(135deg, #E6E6FA 0%, #D8C8E6 100%);
    color: var(--text-color);
    display: flex;
    align-items: center;
    justify-content: center;
    position: relative;
    font-size: 17px;
    font-weight: 500;
    padding-top: 44px;
    box-shadow: 0 2px 10px rgba(123, 44, 191, 0.2);
    z-index: 100;
}

.header-back {
    position: absolute;
    left: 15px;
    top: 50%;
    transform: translateY(-50%);
    font-size: 24px;
    cursor: pointer;
    opacity: 0.9;
    transition: var(--transition);
}

.header-back:hover {
    opacity: 1;
    transform: translateY(-50%) scale(1.1);
}

.header-title {
    font-weight: 600;
    letter-spacing: 0.5px;
}

.header-more {
    position: absolute;
    right: 15px;
    top: 50%;
    transform: translateY(-50%);
    font-size: 24px;
    cursor: pointer;
    opacity: 0.9;
    transition: var(--transition);
    width: 36px;
    height: 36px;
    display: flex;
    align-items: center;
    justify-content: center;
    border-radius: var(--radius-full);
    background: rgba(123, 44, 191, 0.1);
}

.header-more:hover {
    opacity: 1;
    background: rgba(123, 44, 191, 0.2);
    transform: translateY(-50%) rotate(90deg);
}

.dropdown-menu {
    position: absolute;
    top: 100%;
    right: 10px;
    background: white;
    border-radius: var(--radius-md);
    box-shadow: var(--shadow-medium);
    display: none;
    z-index: 1001;
    min-width: 140px;
    overflow: hidden;
    animation: fadeInDown 0.2s ease;
    border: 1px solid var(--border-color);
}

@keyframes fadeInDown {
    from {
        opacity: 0;
        transform: translateY(-10px);
    }
    to {
        opacity: 1;
        transform: translateY(0);
    }
}

.dropdown-menu.show {
    display: block;
}

.dropdown-item {
    padding: 14px 20px;
    font-size: 15px;
    color: var(--text-color);
    cursor: pointer;
    border-bottom: 1px solid var(--border-color);
    transition: var(--transition);
    display: flex;
    align-items: center;
    gap: 10px;
}

.dropdown-item:last-child {
    border-bottom: none;
}

.dropdown-item:hover {
    background: var(--primary-light);
}

.dropdown-item.logout {
    color: var(--danger-color);
}

.dropdown-item.logout:hover {
    background: rgba(255, 107, 107, 0.1);
}

/* 音频消息样式 */
.audio-message {
    display: flex;
    align-items: center;
    gap: 10px;
    padding: 10px 15px;
    background: var(--primary-light);
    border-radius: var(--radius-lg);
    cursor: pointer;
    transition: var(--transition);
    border: 1px solid rgba(123, 44, 191, 0.2);
}

.audio-message:hover {
    background: #E0D6F0;
    transform: scale(1.02);
}

.audio-icon {
    width: 40px;
    height: 40px;
    background: var(--primary-color);
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    color: white;
    font-size: 16px;
    animation: pulseAudio 2s infinite;
}

@keyframes pulseAudio {
    0%, 100% { 
        box-shadow: 0 0 0 0 rgba(123, 44, 191, 0.4);
    }
    50% { 
        box-shadow: 0 0 0 10px rgba(123, 44, 191, 0);
    }
}

.audio-info {
    flex: 1;
    min-width: 0;
}

.audio-duration {
    font-size: 13px;
    color: var(--text-secondary);
    margin-top: 2px;
}

.audio-play-btn {
    width: 36px;
    height: 36px;
    background: white;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    border: none;
    color: var(--primary-color);
    cursor: pointer;
    transition: var(--transition);
    box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
}

.audio-play-btn:hover {
    transform: scale(1.1);
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.audio-play-btn.playing {
    background: var(--primary-color);
    color: white;
}

.audio-wave {
    display: flex;
    align-items: center;
    gap: 3px;
    height: 20px;
    margin-top: 4px;
}

.audio-wave-bar {
    width: 3px;
    background: var(--primary-color);
    border-radius: 2px;
    animation: wave 1.5s ease-in-out infinite;
}

@keyframes wave {
    0%, 100% { height: 4px; }
    50% { height: 12px; }
}

.audio-wave-bar:nth-child(2) { animation-delay: 0.1s; }
.audio-wave-bar:nth-child(3) { animation-delay: 0.2s; }
.audio-wave-bar:nth-child(4) { animation-delay: 0.3s; }
.audio-wave-bar:nth-child(5) { animation-delay: 0.4s; }

/* 音频录制界面 */
.audio-recorder {
    position: fixed;
    bottom: 180px;
    left: 50%;
    transform: translateX(-50%);
    background: white;
    border-radius: var(--radius-lg);
    padding: 20px;
    box-shadow: var(--shadow-medium);
    z-index: 1002;
    display: none;
    flex-direction: column;
    align-items: center;
    gap: 15px;
    min-width: 280px;
    animation: slideUp 0.3s ease;
}

.audio-recorder.show {
    display: flex;
}

.recording-time {
    font-size: 32px;
    font-weight: bold;
    color: var(--danger-color);
    font-family: monospace;
}

.recording-wave {
    display: flex;
    align-items: center;
    gap: 4px;
    height: 40px;
    margin: 10px 0;
}

.recording-wave-bar {
    width: 4px;
    background: var(--danger-color);
    border-radius: 2px;
    animation: recordingWave 0.8s ease-in-out infinite;
}

@keyframes recordingWave {
    0%, 100% { height: 10px; }
    50% { height: 25px; }
}

.recording-controls {
    display: flex;
    gap: 20px;
    align-items: center;
}

.recording-btn {
    width: 50px;
    height: 50px;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    border: none;
    cursor: pointer;
    transition: var(--transition);
    font-size: 20px;
    color: white;
}

.recording-btn.record {
    background: var(--danger-color);
    box-shadow: 0 4px 15px rgba(255, 107, 107, 0.4);
}

.recording-btn.record:hover {
    background: #FF8A8A;
    transform: scale(1.1);
}

.recording-btn.stop {
    background: var(--primary-color);
    box-shadow: 0 4px 15px rgba(123, 44, 191, 0.4);
}

.recording-btn.stop:hover {
    background: var(--primary-dark);
    transform: scale(1.1);
}

.recording-btn.cancel {
    background: var(--text-secondary);
    box-shadow: 0 4px 15px rgba(153, 153, 153, 0.4);
}

.recording-btn.cancel:hover {
    background: #666;
    transform: scale(1.1);
}

.recording-hint {
    font-size: 12px;
    color: var(--text-secondary);
    text-align: center;
    margin-top: 10px;
}

/* 底部导航栏 */
.wechat-tabbar {
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    max-width: 600px;
    margin: 0 auto;
    background: rgba(255, 255, 255, 0.95);
    backdrop-filter: blur(10px);
    border-top: 1px solid var(--border-color);
    display: flex;
    height: 68px;
    z-index: 1000;
    padding: 0 10px;
}

.tab-item {
    flex: 1;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    font-size: 11px;
    color: #4B0082; /* 底部导航文字颜色 */
    cursor: pointer;
    transition: var(--transition);
    position: relative;
    border-radius: var(--radius-sm);
    margin: 5px;
}

.tab-item:hover {
    background: rgba(123, 44, 191, 0.05);
}

.tab-item.active {
    color: var(--primary-color);
}

.tab-item.active .tab-icon {
    transform: translateY(-3px);
    animation: bounce 0.5s;
}

@keyframes bounce {
    0%, 100% { transform: translateY(-3px); }
    50% { transform: translateY(-8px); }
}

.tab-icon {
    font-size: 22px;
    margin-bottom: 4px;
    transition: var(--transition);
    color: #4B0082; /* 底部导航图标颜色 */
}

.tab-badge {
    position: absolute;
    top: -2px;
    right: 10px;
    background: var(--danger-color);
    color: white;
    border-radius: var(--radius-full);
    min-width: 18px;
    height: 18px;
    font-size: 10px;
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 0 4px;
    animation: pulse 2s infinite;
}

@keyframes pulse {
    0%, 100% { transform: scale(1); }
    50% { transform: scale(1.1); }
}

/* 朋友圈页面 */
.moments-page {
    display: <?php echo $currentPage === 'moments' ? 'block' : 'none'; ?>;
    padding-bottom: 80px;
    background: var(--bg-color);
}

/* 朋友圈封面 */
.moments-cover {
    height: 320px;
    background: linear-gradient(135deg, #E6E6FA 0%, #D8C8E6 100%);
    position: relative;
    overflow: hidden;
}

.moments-cover::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: linear-gradient(to bottom, rgba(0,0,0,0.1), rgba(0,0,0,0.2));
}

.user-card {
    position: absolute;
    top: 30px;
    left: 25px;
    bottom: auto;
    display: flex;
    align-items: flex-start;
    gap: 15px;
}

.user-avatar {
    width: 80px;
    height: 80px;
    border-radius: var(--radius-md);
    border: 4px solid white;
    background-size: cover;
    background-color: #f0f0f0;
    cursor: pointer;
    transition: var(--transition);
    box-shadow: var(--shadow-medium);
}

.user-avatar:hover {
    transform: scale(1.05);
    box-shadow: 0 8px 25px rgba(0, 0, 0, 0.15);
}

.user-info {
    margin-bottom: 15px;
    padding: 12px 16px;
    background: #FFF8E1; /* 个人信息框奶白色 */
    border-radius: var(--radius-md);
    box-shadow: var(--shadow-light);
    backdrop-filter: blur(10px);
}

.user-nickname {
    color: #551A8B; /* 深紫色昵称 */
    font-size: 18px;
    font-weight: 600;
    margin-bottom: 5px;
}

.user-id {
    color: var(--text-secondary);
    font-size: 13px;
    font-family: 'Courier New', monospace;
}

.user-bio {
    color: var(--text-secondary);
    font-size: 13px;
    margin-top: 6px;
    line-height: 1.4;
    max-width: 200px;
    word-break: break-word;
    max-height: 60px;
    overflow: hidden;
    text-overflow: ellipsis;
    display: -webkit-box;
    -webkit-line-clamp: 3;
    -webkit-box-orient: vertical;
}

.user-status {
    display: inline-block;
    padding: 2px 8px;
    background: #D8C8E6; /* 浅灰紫标签 */
    color: #666;
    border-radius: 10px;
    font-size: 11px;
    margin-left: 8px;
}

/* 朋友圈列表 */
.moments-list {
    margin-top: 50px;
    padding: 0 16px;
}

.moment-item {
    background: var(--card-bg);
    border-radius: var(--radius-lg);
    padding: 20px;
    margin-bottom: 16px;
    box-shadow: var(--shadow-light);
    border: 1px solid var(--border-color);
    transition: var(--transition);
    position: relative;
    overflow: hidden;
}

.moment-item:hover {
    box-shadow: var(--shadow-medium);
    transform: translateY(-2px);
}

.moment-item::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    width: 4px;
    height: 100%;
    background: linear-gradient(to bottom, var(--primary-color), var(--primary-dark));
    border-radius: var(--radius-lg) 0 0 var(--radius-lg);
}

.moment-header {
    display: flex;
    margin-bottom: 16px;
    align-items: center;
}

.moment-avatar {
    width: 44px;
    height: 44px;
    border-radius: var(--radius-md);
    background-size: cover;
    margin-right: 14px;
    border: 2px solid var(--primary-light);
    box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
}

.moment-info {
    flex: 1;
}

.moment-nickname {
    font-size: 16px;
    color: #551A8B; /* 深紫色昵称 */
    font-weight: 600;
    margin-bottom: 4px;
}

.moment-time {
    font-size: 12px;
    color: var(--text-secondary);
    display: flex;
    align-items: center;
    gap: 6px;
}

.moment-time::before {
    content: '发布时间：';
    font-size: 11px;
}

.moment-content {
    font-size: 15px;
    line-height: 1.7;
    color: #000000; /* 正文黑色 */
    margin-bottom: 16px;
    word-break: break-word;
    white-space: pre-wrap;
}

.moment-images {
    display: flex;
    flex-wrap: wrap;
    gap: 6px;
    margin-bottom: 16px;
}

.moment-image {
    border-radius: var(--radius-sm);
    background-color: #f8f8f8;
    object-fit: cover;
    transition: var(--transition);
    cursor: pointer;
}

.moment-image:hover {
    transform: scale(1.02);
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.image-1 {
    width: 100%;
    max-height: 320px;
    border-radius: var(--radius-md);
}

.image-2, .image-3 {
    width: calc(50% - 3px);
    height: 160px;
}

.image-4 {
    width: calc(33.333% - 4px);
    height: 120px;
}

.moment-video {
    width: 100%;
    max-height: 320px;
    border-radius: var(--radius-md);
    background: #000;
    margin-bottom: 16px;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.music-share {
    background: linear-gradient(135deg, var(--primary-light) 0%, #F0F5FF 100%);
    padding: 16px;
    border-radius: var(--radius-md);
    margin: 16px 0;
    border-left: 4px solid var(--primary-color);
    display: flex;
    align-items: center;
    cursor: pointer;
    transition: var(--transition);
    position: relative;
    overflow: hidden;
}

.music-share:hover {
    transform: translateX(5px);
    box-shadow: var(--shadow-light);
}

.music-share::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: linear-gradient(45deg, transparent 30%, rgba(255,255,255,0.3) 50%, transparent 70%);
    animation: shimmer 2s infinite;
}

@keyframes shimmer {
    0% { transform: translateX(-100%); }
    100% { transform: translateX(100%); }
}

.music-icon {
    font-size: 24px;
    margin-right: 14px;
    color: var(--primary-color);
}

.music-info {
    flex: 1;
    min-width: 0;
}

.music-title {
    font-size: 15px;
    color: var(--text-color);
    margin-bottom: 4px;
    font-weight: 500;
}

.music-desc {
    font-size: 13px;
    color: var(--text-secondary);
    word-break: break-all;
}

.moment-actions {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-top: 16px;
    padding-top: 16px;
    border-top: 1px solid var(--border-color);
}

.action-btn {
    display: flex;
    align-items: center;
    gap: 8px;
    font-size: 14px;
    color: var(--text-secondary);
    cursor: pointer;
    transition: var(--transition);
    padding: 8px 14px;
    border-radius: var(--radius-sm);
}

.action-btn:hover {
    background: var(--primary-light);
    color: var(--primary-dark);
    transform: translateY(-1px);
}

.action-btn.active {
    color: var(--danger-color);
    background: rgba(255, 107, 107, 0.1);
}

.action-btn.active .fas {
    color: var(--danger-color);
}

.like-comment {
    display: flex;
    gap: 16px;
}

/* 点赞区域 */
.likes-section {
    background: var(--primary-light);
    border-radius: var(--radius-md);
    padding: 12px 16px;
    margin-top: 12px;
    font-size: 14px;
}

.likes-list {
    display: flex;
    flex-wrap: wrap;
    gap: 8px;
    margin-top: 8px;
}

.like-item {
    display: flex;
    align-items: center;
    gap: 6px;
    background: white;
    padding: 4px 8px;
    border-radius: var(--radius-sm);
    border: 1px solid var(--border-color);
}

.like-avatar {
    width: 20px;
    height: 20px;
    border-radius: 50%;
    background-size: cover;
}

.like-name {
    font-size: 12px;
    color: var(--primary-color);
}

/* 评论区域 */
.comments-section {
    background: var(--primary-light);
    border-radius: var(--radius-md);
    padding: 16px;
    margin-top: 16px;
}

.comment-item {
    padding: 10px 0;
    font-size: 14px;
    line-height: 1.5;
    border-bottom: 1px solid rgba(0,0,0,0.05);
}

.comment-item:last-child {
    border-bottom: none;
}

.commenter {
    color: var(--primary-color);
    font-weight: 500;
    margin-right: 8px;
}

/* 私信页面 */
.messages-page {
    display: <?php echo $currentPage === 'messages' ? 'block' : 'none'; ?>;
    padding-bottom: 80px;
    background: var(--bg-color);
}

.conversations-list {
    padding: 16px;
}

.conversation-item {
    display: flex;
    align-items: center;
    padding: 12px 16px;
    background: white;
    border-radius: var(--radius-md);
    margin-bottom: 10px;
    cursor: pointer;
    transition: var(--transition);
    border: 1px solid var(--border-color);
}

.conversation-item:hover {
    transform: translateX(5px);
    box-shadow: var(--shadow-light);
    border-color: var(--primary-color);
}

.conversation-item.unread {
    background: var(--primary-light);
    border-left: 4px solid var(--primary-color);
}

.conversation-avatar {
    width: 50px;
    height: 50px;
    border-radius: var(--radius-md);
    background-size: cover;
    margin-right: 12px;
    border: 2px solid var(--primary-light);
}

.conversation-info {
    flex: 1;
    min-width: 0;
}

.conversation-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 4px;
}

.conversation-name {
    font-size: 16px;
    font-weight: 600;
    color: var(--text-color);
}

.conversation-time {
    font-size: 11px;
    color: var(--text-secondary);
}

.conversation-preview {
    font-size: 13px;
    color: var(--text-secondary);
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}

.conversation-unread {
    background: var(--danger-color);
    color: white;
    border-radius: var(--radius-full);
    min-width: 20px;
    height: 20px;
    font-size: 11px;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-left: 8px;
}

/* 私信聊天页面 */
.private-chat-page {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: white;
    z-index: 2000;
    display: <?php echo $chatWithUserId ? 'block' : 'none'; ?>;
    animation: slideIn 0.3s ease;
}

@keyframes slideIn {
    from {
        transform: translateX(100%);
    }
    to {
        transform: translateX(0);
    }
}

/* 私信聊天页面头部 */
.private-chat-header {
    height: 88px;
    background: linear-gradient(135deg, #E6E6FA 0%, #D8C8E6 100%);
    color: var(--text-color);
    display: flex;
    align-items: center;
    padding: 44px 16px 0 16px;
    position: relative;
}

.private-chat-back {
    font-size: 24px;
    cursor: pointer;
    margin-right: 16px;
    padding: 8px;
}

.private-chat-user {
    display: flex;
    align-items: center;
    gap: 12px;
}

.private-chat-avatar {
    width: 40px;
    height: 40px;
    border-radius: var(--radius-md);
    background-size: cover;
    border: 2px solid white;
}

.private-chat-name {
    font-size: 17px;
    font-weight: 500;
}

.private-chat-status {
    font-size: 12px;
    opacity: 0.8;
}

.private-chat-messages {
    position: absolute;
    top: 88px;
    left: 0;
    right: 0;
    bottom: 180px;
    padding: 16px;
    overflow-y: auto;
    overflow-x: hidden;
    scroll-behavior: smooth;
}

.private-message {
    margin-bottom: 20px;
    display: flex;
    align-items: flex-start;
    animation: fadeIn 0.3s ease;
}

.private-message-left .private-message-avatar {
    margin-right: 12px;
}

.private-message-right .private-message-avatar {
    margin-left: 12px;
}

.private-message-avatar {
    width: 38px;
    height: 38px;
    border-radius: var(--radius-md);
    background-size: cover;
    background-color: #f0f0f0;
    flex-shrink: 0;
}

.private-message-content {
    max-width: 75%;
    min-width: 60px;
}

.private-message-bubble {
    padding: 10px 14px;
    border-radius: var(--radius-lg);
    font-size: 14px;
    line-height: 1.5;
    word-wrap: break-word;
    position: relative;
    box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
}

.private-message-left .private-message-bubble {
    background: white;
    border-top-left-radius: 4px;
    border: 1px solid var(--border-color);
}

.private-message-right .private-message-bubble {
    background: linear-gradient(135deg, var(--primary-color) 0%, var(--primary-dark) 100%);
    color: white;
    border-top-right-radius: 4px;
    box-shadow: 0 2px 8px rgba(123, 44, 191, 0.3);
}

.private-message-time {
    font-size: 11px;
    color: var(--text-secondary);
    margin-top: 4px;
    text-align: right;
}

.private-message-right {
    flex-direction: row-reverse;
}

.private-message-right .private-message-time {
    text-align: left;
}

.private-chat-input-area {
    position: absolute;
    bottom: 0;
    left: 0;
    right: 0;
    background: rgba(255, 255, 255, 0.95);
    backdrop-filter: blur(10px);
    border-top: 1px solid var(--border-color);
    padding: 12px 16px;
    z-index: 2;
    box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.05);
    height: 180px;
}

/* 聊天页面 - 根据是否有公告调整位置 */
.chat-page {
    display: <?php echo $currentPage === 'chat' ? 'block' : 'none'; ?>;
    position: fixed;
    top: <?php echo ($announcement['enabled'] && $currentPage === 'moments') ? '88px' : '44px'; ?>;
    left: 0;
    right: 0;
    bottom: 68px;
    max-width: 600px;
    margin: 0 auto;
    background: var(--bg-color);
    overflow: hidden;
    z-index: 1;
}

.chat-messages {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 180px; /* 输入区域高度 */
    padding: 16px;
    
    /* 关键修复：确保可以滑动 */
    overflow-y: auto;  /* 确保是auto或scroll */
    overflow-x: hidden;
    
    /* 移动端流畅滑动 */
    -webkit-overflow-scrolling: touch;
    
    /* 确保高度正确 */
    height: calc(100% - 180px);
    
    /* 允许触摸滚动 */
    touch-action: pan-y;
}

.chat-messages::-webkit-scrollbar {
    width: 4px;
}

.chat-messages::-webkit-scrollbar-track {
    background: transparent;
}

.chat-messages::-webkit-scrollbar-thumb {
    background: var(--primary-color);
    border-radius: 2px;
}

.chat-messages::-webkit-scrollbar-thumb:hover {
    background: var(--primary-dark);
}

.chat-messages {
    scrollbar-width: thin;
    scrollbar-color: var(--primary-color) transparent;
}

.chat-message {
    margin-bottom: 20px;
    display: flex;
    align-items: flex-start;
    animation: fadeIn 0.3s ease;
}

@keyframes fadeIn {
    from {
        opacity: 0;
        transform: translateY(10px);
    }
    to {
        opacity: 1;
        transform: translateY(0);
    }
}

.message-avatar {
    width: 42px;
    height: 42px;
    border-radius: var(--radius-md);
    background-size: cover;
    background-color: #f0f0f0;
    flex-shrink: 0;
    box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
}

.message-left .message-avatar {
    margin-right: 12px;
}

.message-right .message-avatar {
    margin-left: 12px;
}

.message-content {
    max-width: 70%;
    min-width: 60px;
}

.message-bubble {
    padding: 12px 16px;
    border-radius: var(--radius-lg);
    font-size: 15px;
    line-height: 1.5;
    word-wrap: break-word;
    position: relative;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.message-left .message-bubble {
    background: white;
    border-top-left-radius: 4px;
    border: 1px solid var(--border-color);
}

.message-right .message-bubble {
    background: linear-gradient(135deg, var(--primary-color) 0%, var(--primary-dark) 100%);
    color: white;
    border-top-right-radius: 4px;
    box-shadow: 0 2px 8px rgba(123, 44, 191, 0.3);
}

.message-time {
    font-size: 11px;
    color: var(--text-secondary);
    margin-top: 6px;
    text-align: center;
}

.message-right {
    flex-direction: row-reverse;
}

/* 聊天输入框 */
.chat-input-area {
    position: absolute;
    bottom: 0;
    left: 0;
    right: 0;
    background: rgba(255, 255, 255, 0.95);
    backdrop-filter: blur(10px);
    border-top: 1px solid var(--border-color);
    padding: 12px 16px;
    z-index: 2;
    box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.05);
    height: 180px;
}

.input-toolbar {
    display: flex;
    align-items: center;
    gap: 8px;
    margin-bottom: 12px;
}

.tool-btn {
    width: 40px;
    height: 40px;
    border-radius: var(--radius-full);
    background: var(--bg-color);
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 18px;
    cursor: pointer;
    color: var(--text-color);
    transition: var(--transition);
    border: none;
}

.tool-btn:hover {
    background: var(--primary-light);
    color: var(--primary-dark);
    transform: translateY(-2px);
}

.tool-btn.active {
    background: var(--primary-color);
    color: white;
    box-shadow: 0 4px 12px rgba(123, 44, 191, 0.3);
}

.tool-btn.audio-recording {
    background: var(--danger-color);
    color: white;
    animation: pulseRecording 1s infinite;
}

@keyframes pulseRecording {
    0%, 100% { 
        box-shadow: 0 0 0 0 rgba(255, 107, 107, 0.4);
    }
    50% { 
        box-shadow: 0 0 0 8px rgba(255, 107, 107, 0);
    }
}

.input-box {
    display: flex;
    align-items: flex-end;
    gap: 12px;
}

.input-box textarea {
    flex: 1;
    padding: 12px 16px;
    border: 2px solid var(--border-color);
    border-radius: var(--radius-lg);
    resize: none;
    font-size: 15px;
    line-height: 1.5;
    max-height: 120px;
    background: white;
    transition: var(--transition);
    font-family: inherit;
}

.input-box textarea:focus {
    outline: none;
    border-color: var(--primary-color);
    box-shadow: 0 0 0 3px rgba(123, 44, 191, 0.1);
}

.music-input {
    flex: 1;
    padding: 12px 16px;
    border: 2px solid var(--border-color);
    border-radius: var(--radius-lg);
    font-size: 15px;
    background: white;
    display: none;
    transition: var(--transition);
}

.music-input:focus {
    outline: none;
    border-color: var(--primary-color);
    box-shadow: 0 0 0 3px rgba(123, 44, 191, 0.1);
}

.send-btn {
    padding: 12px 20px;
    background: linear-gradient(135deg, var(--primary-color) 0%, var(--primary-dark) 100%);
    color: white;
    border: none;
    border-radius: var(--radius-lg);
    font-size: 15px;
    font-weight: 500;
    cursor: pointer;
    transition: var(--transition);
    box-shadow: 0 4px 12px rgba(123, 44, 191, 0.3);
    display: flex;
    align-items: center;
    gap: 8px;
}

.send-btn:hover {
    transform: translateY(-2px);
    box-shadow: 0 6px 20px rgba(123, 44, 191, 0.4);
}

.send-btn:disabled {
    background: #cccccc;
    cursor: not-allowed;
    transform: none;
    box-shadow: none;
    opacity: 0.6;
}

/* 音乐播放器 */
.music-player {
    position: fixed;
    bottom: 136px;
    left: 16px;
    right: 16px;
    max-width: 568px;
    margin: 0 auto;
    background: linear-gradient(135deg, var(--primary-color) 0%, var(--primary-dark) 100%);
    border-radius: var(--radius-lg);
    padding: 14px 18px;
    display: none;
    align-items: center;
    gap: 15px;
    z-index: 1002;
    box-shadow: 0 8px 32px rgba(123, 44, 191, 0.4);
    color: white;
    backdrop-filter: blur(10px);
    border: 1px solid rgba(255, 255, 255, 0.1);
    animation: slideUp 0.3s ease;
}

@keyframes slideUp {
    from {
        opacity: 0;
        transform: translateY(30px);
    }
    to {
        opacity: 1;
        transform: translateY(0);
    }
}

.music-player.show {
    display: flex;
}

.music-player-info {
    flex: 1;
    min-width: 0;
}

.music-player-title {
    font-size: 15px;
    font-weight: 600;
    margin-bottom: 4px;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}

.music-player-controls {
    display: flex;
    align-items: center;
    gap: 12px;
}

.music-control-btn {
    background: rgba(255, 255, 255, 0.2);
    width: 36px;
    height: 36px;
    border-radius: var(--radius-full);
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    transition: var(--transition);
    border: none;
    color: white;
    font-size: 16px;
}

.music-control-btn:hover {
    background: rgba(255, 255, 255, 0.3);
    transform: scale(1.1);
}

/* 弹窗样式 */
.modal-overlay {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(0, 0, 0, 0.5);
    display: none;
    justify-content: center;
    align-items: center;
    z-index: 2000;
    backdrop-filter: blur(4px);
    animation: fadeIn 0.3s ease;
}

.modal-content {
    width: 85%;
    max-width: 320px;
    background: white;
    border-radius: var(--radius-lg);
    overflow: hidden;
    box-shadow: var(--shadow-medium);
    animation: slideUp 0.3s ease;
}

.modal-header {
    padding: 20px;
    text-align: center;
    font-size: 18px;
    font-weight: 600;
    color: var(--text-color);
    background: linear-gradient(to right, var(--primary-light), #F8F9FA);
    border-bottom: 1px solid var(--border-color);
}

.modal-body {
    padding: 20px;
    max-height: 70vh;
    overflow-y: auto;
}

.form-group {
    margin-bottom: 16px;
}

.form-label {
    display: block;
    margin-bottom: 6px;
    font-size: 14px;
    color: var(--text-color);
    font-weight: 500;
}

.form-input {
    width: 100%;
    padding: 12px 16px;
    border: 2px solid var(--border-color);
    border-radius: var(--radius-md);
    font-size: 15px;
    transition: var(--transition);
    background: white;
}

.form-input:focus {
    outline: none;
    border-color: var(--primary-color);
    box-shadow: 0 0 0 3px rgba(123, 44, 191, 0.1);
}

.form-input.error {
    border-color: var(--danger-color);
}

.form-textarea {
    width: 100%;
    padding: 12px 16px;
    border: 2px solid var(--border-color);
    border-radius: var(--radius-md);
    font-size: 15px;
    resize: none;
    height: 100px;
    transition: var(--transition);
    font-family: inherit;
    background: white;
}

.form-textarea:focus {
    outline: none;
    border-color: var(--primary-color);
    box-shadow: 0 0 0 3px rgba(123, 44, 191, 0.1);
}

.form-hint {
    font-size: 12px;
    color: var(--text-secondary);
    margin-top: 4px;
}

.form-error {
    color: var(--danger-color);
    font-size: 12px;
    margin-top: 4px;
}

.form-success {
    color: var(--primary-color);
    font-size: 13px;
    text-align: center;
    padding: 10px;
    background: var(--primary-light);
    border-radius: var(--radius-sm);
    margin-bottom: 15px;
}

.modal-actions {
    display: flex;
    border-top: 1px solid var(--border-color);
}

.modal-btn {
    flex: 1;
    padding: 16px;
    border: none;
    background: none;
    font-size: 16px;
    font-weight: 500;
    cursor: pointer;
    transition: var(--transition);
}

.modal-btn.cancel {
    color: var(--text-secondary);
    border-right: 1px solid var(--border-color);
}

.modal-btn.cancel:hover {
    background: var(--bg-color);
}

.modal-btn.confirm {
    color: var(--primary-dark);
    font-weight: 600;
}

.modal-btn.confirm:hover {
    background: var(--primary-light);
}

.modal-btn.secondary {
    color: var(--secondary-color);
}

.modal-btn.secondary:hover {
    background: rgba(179, 224, 255, 0.1);
}

/* 发布按钮 */
.publish-btn {
    position: fixed;
    bottom: 90px;
    right: 20px;
    width: 56px;
    height: 56px;
    background: linear-gradient(135deg, var(--primary-color) 0%, var(--primary-dark) 100%);
    color: white;
    border-radius: var(--radius-full);
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 28px;
    cursor: pointer;
    box-shadow: 0 6px 20px rgba(123, 44, 191, 0.4);
    transition: var(--transition);
    z-index: 999;
    border: 4px solid white;
}

.publish-btn:hover {
    transform: scale(1.1) rotate(90deg);
    box-shadow: 0 8px 30px rgba(123, 44, 191, 0.6);
}

/* 空状态 */
.empty-state {
    text-align: center;
    padding: 80px 20px;
    color: var(--text-secondary);
}

.empty-icon {
    font-size: 60px;
    margin-bottom: 20px;
    opacity: 0.3;
    animation: pulse 2s infinite;
}

@keyframes pulse {
    0%, 100% { opacity: 0.3; }
    50% { opacity: 0.5; }
}

/* 切换按钮 */
.switch-buttons {
    display: flex;
    margin-bottom: 20px;
    border-bottom: 1px solid var(--border-color);
}

.switch-btn {
    flex: 1;
    padding: 14px;
    text-align: center;
    background: none;
    border: none;
    font-size: 16px;
    color: var(--text-secondary);
    cursor: pointer;
    position: relative;
    transition: var(--transition);
}

.switch-btn:hover {
    color: var(--primary-color);
}

.switch-btn.active {
    color: var(--primary-color);
    font-weight: 500;
}

.switch-btn.active::after {
    content: '';
    position: absolute;
    bottom: -1px;
    left: 0;
    right: 0;
    height: 2px;
    background: var(--primary-color);
}

/* 响应式设计 */
@media (max-width: 480px) {
    .container {
        max-width: 100%;
    }
    
    .moments-cover {
        height: 200px;
    }
    
    .user-avatar {
        width: 70px;
        height: 70px;
    }
    
    .user-info {
        padding: 10px 14px;
    }
    
    .user-nickname {
        font-size: 16px;
    }
    
    .moment-item {
        padding: 16px;
        margin-bottom: 12px;
    }
    
    .chat-messages {
        padding: 12px;
        bottom: 170px;
    }
    
    .chat-input-area {
        height: 170px;
        padding: 10px 14px;
    }
    
    .message-bubble {
        max-width: 85%;
        padding: 10px 14px;
    }
    
    .modal-content {
        width: 90%;
    }
}

/* 加载动画 */
.loading {
    display: inline-block;
    width: 20px;
    height: 20px;
    border: 3px solid rgba(123, 44, 191, 0.3);
    border-radius: 50%;
    border-top-color: var(--primary-color);
    animation: spin 1s ease-in-out infinite;
}

@keyframes spin {
    to { transform: rotate(360deg); }
}

/* 工具类 */
.hidden {
    display: none !important;
}

.text-truncate {
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}
/* 私信搜索框 */
.messages-search-bar {
    padding: 12px 16px;
    background: white;
    border-bottom: 1px solid var(--border-color);
    position: sticky;
    top: 88px;
    z-index: 10;
}

.search-input-wrapper {
    position: relative;
    display: flex;
    align-items: center;
}

.search-input-wrapper i {
    position: absolute;
    left: 14px;
    color: var(--text-secondary);
    font-size: 16px;
}

#messageSearch {
    width: 100%;
    padding: 12px 16px 12px 44px;
    border: 2px solid var(--border-color);
    border-radius: var(--radius-lg);
    font-size: 15px;
    background: var(--bg-color);
    transition: var(--transition);
}

#messageSearch:focus {
    outline: none;
    border-color: var(--primary-color);
    box-shadow: 0 0 0 3px rgba(123, 44, 191, 0.1);
}

.search-clear {
    position: absolute;
    right: 14px;
    background: none;
    border: none;
    color: var(--text-secondary);
    cursor: pointer;
    font-size: 16px;
    padding: 4px;
    border-radius: 50%;
    transition: var(--transition);
}

.search-clear:hover {
    background: var(--border-color);
    color: var(--text-color);
}

/* 搜索结果 */
.search-results {
    padding: 8px;
}

.search-result-item {
    display: flex;
    align-items: center;
    padding: 12px 16px;
    background: white;
    border-radius: var(--radius-md);
    margin-bottom: 8px;
    cursor: pointer;
    transition: var(--transition);
    border: 1px solid var(--border-color);
}

.search-result-item:hover {
    transform: translateX(5px);
    box-shadow: var(--shadow-light);
    border-color: var(--primary-color);
    background: var(--primary-light);
}

.search-result-avatar {
    width: 48px;
    height: 48px;
    border-radius: var(--radius-md);
    background-size: cover;
    margin-right: 12px;
    border: 2px solid var(--primary-light);
}

.search-result-info {
    flex: 1;
}

.search-result-name {
    font-size: 16px;
    font-weight: 600;
    color: var(--text-color);
    margin-bottom: 4px;
}

.search-result-id {
    font-size: 12px;
    color: var(--text-secondary);
    font-family: monospace;
}

.search-result-bio {
    font-size: 13px;
    color: var(--text-secondary);
    margin-top: 4px;
    line-height: 1.4;
    max-width: 200px;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}

.search-result-action {
    background: var(--primary-color);
    color: white;
    border: none;
    padding: 8px 16px;
    border-radius: var(--radius-md);
    font-size: 13px;
    cursor: pointer;
    transition: var(--transition);
}

.search-result-action:hover {
    background: var(--primary-dark);
    transform: translateY(-2px);
}

.search-no-results {
    text-align: center;
    padding: 40px 20px;
    color: var(--text-secondary);
}

.search-no-results i {
    font-size: 40px;
    margin-bottom: 16px;
    opacity: 0.3;
}
/* 搜索按钮 */
.search-button {
    background: linear-gradient(135deg, var(--primary-color) 0%, var(--primary-dark) 100%);
    color: white;
    border: none;
    padding: 10px 16px;
    border-radius: var(--radius-md);
    font-size: 14px;
    cursor: pointer;
    transition: var(--transition);
    margin-left: 8px;
    display: flex;
    align-items: center;
    gap: 6px;
    white-space: nowrap;
    box-shadow: 0 2px 8px rgba(123, 44, 191, 0.3);
}

.search-button:hover {
    background: linear-gradient(135deg, var(--primary-dark) 0%, #5a1a8a 100%);
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(123, 44, 191, 0.4);
}

.search-button:active {
    transform: translateY(0);
    box-shadow: 0 2px 4px rgba(123, 44, 191, 0.3);
}

.search-button:disabled {
    background: #cccccc;
    cursor: not-allowed;
    transform: none;
    box-shadow: none;
}

/* 移动端适配 */
@media (max-width: 480px) {
    .search-button span {
        display: none;
    }
    
    .search-button {
        padding: 10px;
        min-width: 40px;
        justify-content: center;
    }
}
</style>
</head>
<body>
    <div class="container">
        

        <!-- 微信风格顶部栏 -->
        <div class="wechat-header">
            <div class="header-back" onclick="goBack()">‹</div>
            <div class="header-title" id="headerTitle">
                <?php 
                if ($currentPage === 'moments') echo '表白墙';
                elseif ($currentPage === 'chat') echo '聊天室';
                elseif ($currentPage === 'messages') echo '私信';
                else echo '表白墙';
                ?>
            </div>
            <div class="header-more" id="headerMore">
                <i class="fas fa-ellipsis-v"></i>
            </div>
            <!-- 下拉菜单 -->
            <div class="dropdown-menu" id="dropdownMenu">
                <?php if ($isLogin): ?>
                    <div class="dropdown-item" onclick="showProfileModal()">
                        <i class="fas fa-user"></i>
                        <span>个人资料</span>
                    </div>
                    <?php if ($currentPage !== 'messages'): ?>
                        <div class="dropdown-item" onclick="switchPage('messages')">
                            <i class="fas fa-envelope"></i>
                            <span>私信</span>
                            <?php if (getUnreadCount($_SESSION['user_id']) > 0): ?>
                                <span class="conversation-unread"><?php echo getUnreadCount($_SESSION['user_id']); ?></span>
                            <?php endif; ?>
                        </div>
                    <?php endif; ?>
                    <div class="dropdown-item logout" onclick="showLogoutModal()">
                        <i class="fas fa-sign-out-alt"></i>
                        <span>退出登录</span>
                    </div>
                <?php else: ?>
                    <div class="dropdown-item" onclick="showLoginModal()">
                        <i class="fas fa-sign-in-alt"></i>
                        <span>登录</span>
                    </div>
                    <div class="dropdown-item" onclick="showRegisterModal()">
                        <i class="fas fa-user-plus"></i>
                        <span>注册</span>
                    </div>
                <?php endif; ?>
            </div>
        </div>

        <!-- 公告详情弹窗 -->
<div class="announcement-detail-modal" id="announcementModal">
    <div class="announcement-detail-modal-content">
                <div class="announcement-modal-header"><?php echo htmlspecialchars($announcement['title']); ?></div>
                <div class="announcement-modal-body">
                    <div class="announcement-full-content">
                        <?php echo nl2br(htmlspecialchars($announcement['content'])); ?>
                    </div>
                    <div class="announcement-meta">
                        <div class="announcement-meta-item">更新时间: <?php echo $announcement['update_time']; ?></div>
                        <div class="announcement-meta-item">更新者: <?php echo htmlspecialchars($announcement['update_by']); ?></div>
                        <div class="announcement-meta-item">状态: <?php echo $announcement['enabled'] ? '已启用' : '已禁用'; ?></div>
                    </div>
                </div>
                <div class="modal-actions">
                    <button type="button" class="modal-btn cancel" onclick="closeAnnouncementDetail()">关闭</button>
                </div>
            </div>
        </div>

        <!-- 音频录制界面 -->
        <div class="audio-recorder" id="audioRecorder">
            <div class="recording-time" id="recordingTime">00:00</div>
            <div class="recording-wave" id="recordingWave">
                <div class="recording-wave-bar"></div>
                <div class="recording-wave-bar"></div>
                <div class="recording-wave-bar"></div>
                <div class="recording-wave-bar"></div>
                <div class="recording-wave-bar"></div>
                <div class="recording-wave-bar"></div>
                <div class="recording-wave-bar"></div>
                <div class="recording-wave-bar"></div>
            </div>
            <div class="recording-controls">
                <button class="recording-btn cancel" onclick="cancelRecording()" title="取消">
                    <i class="fas fa-times"></i>
                </button>
                <button class="recording-btn record" id="recordBtn" onclick="toggleRecording()" title="开始/停止录音">
                    <i class="fas fa-microphone"></i>
                </button>
                <button class="recording-btn stop" id="stopBtn" onclick="stopRecording()" title="完成录音" style="display: none;">
                    <i class="fas fa-check"></i>
                </button>
            </div>
            <div class="recording-hint" id="recordingHint">点击麦克风按钮开始录音，最多60秒</div>
        </div>

        <!-- 私信聊天页面 -->
        <div class="private-chat-page" id="privateChatPage">
            <div class="private-chat-header">
                <div class="private-chat-back" onclick="closePrivateChat()">
                    <i class="fas fa-arrow-left"></i>
                </div>
                <div class="private-chat-user" id="privateChatUser">
                    <!-- 用户信息将通过JavaScript动态加载 -->
                </div>
            </div>
            <div class="private-chat-messages" id="privateChatMessages">
                <!-- 私信消息将通过JavaScript动态加载 -->
            </div>
            <div class="private-chat-input-area">
                <div class="input-toolbar">
                    <button type="button" class="tool-btn active" data-type="text" onclick="setPrivateMessageType('text')">
                        <i class="fas fa-comment-dots"></i>
                    </button>
                    <button type="button" class="tool-btn" data-type="image" onclick="setPrivateMessageType('image')">
                        <i class="fas fa-image"></i>
                    </button>
                    <button type="button" class="tool-btn" data-type="video" onclick="setPrivateMessageType('video')">
                        <i class="fas fa-video"></i>
                    </button>
                    <button type="button" class="tool-btn" data-type="audio" onclick="startPrivateAudioRecording()">
                        <i class="fas fa-microphone"></i>
                    </button>
                    <button type="button" class="tool-btn" data-type="music" onclick="setPrivateMessageType('music')">
                        <i class="fas fa-music"></i>
                    </button>
                </div>
                <form method="post" action="" enctype="multipart/form-data" id="privateChatForm">
                    <input type="hidden" name="receiver_id" id="receiverId" value="<?php echo htmlspecialchars($chatWithUserId); ?>">
                    <input type="hidden" name="message_type" id="privateMessageType" value="text">
                    <input type="hidden" name="audio_duration" id="privateAudioDuration" value="0">
                    <div class="input-box">
                        <textarea name="message_content" id="privateMessageContent" placeholder="输入私信内容..."></textarea>
                        <input type="file" name="private_message_file" id="privateMessageFile" class="hidden" accept="image/*,video/*,audio/*">
                        <input type="text" name="music_url" id="privateMusicUrl" class="music-input" placeholder="请输入音乐链接...">
                        <button type="submit" name="send_private_message" class="send-btn" id="privateSendBtn">
                            <i class="fas fa-paper-plane"></i>
                            <span>发送</span>
                        </button>
                    </div>
                </form>
            </div>
        </div>

        <!-- 音乐播放器 -->
        <div class="music-player" id="musicPlayer">
            <div class="music-player-info">
                <div class="music-player-title" id="musicPlayerTitle">正在播放</div>
                <audio id="audioPlayer" style="display: none;"></audio>
            </div>
            <div class="music-player-controls">
                <button class="music-control-btn" onclick="playPauseMusic()">
                    <i class="fas fa-play" id="playPauseIcon"></i>
                </button>
                <button class="music-control-btn" onclick="stopMusic()">
                    <i class="fas fa-stop"></i>
                </button>
                <button class="music-control-btn" onclick="closeMusicPlayer()">
                    <i class="fas fa-times"></i>
                </button>
            </div>
        </div>

        <!-- 朋友圈页面 -->
<div class="moments-page">
    <!-- 朋友圈封面 -->
    <div class="moments-cover">
        <div class="user-card">
            <div class="user-avatar" id="userAvatar" style="background-image: url('<?php echo htmlspecialchars($userProfile['avatar']); ?>');"></div>
            <div class="user-info">
                <div class="user-nickname">
                    <?php echo htmlspecialchars($userProfile['nickname']); ?>
                    <?php if ($isLogin): ?>
                        <span class="user-status">已登录</span>
                    <?php endif; ?>
                </div>
                <div class="user-id">
                    <?php if ($isLogin): ?>
                        ID: <?php echo $_SESSION['user_id'] ?? 'unknown'; ?>
                    <?php else: ?>
                        游客访问
                    <?php endif; ?>
                </div>
                <div class="user-bio">
                    <?php if ($isLogin): ?>
                        <?php echo htmlspecialchars($_SESSION['bio'] ?? '这个人很懒，还没有写个人介绍...'); ?>
                    <?php else: ?>
                        登录后可以编辑个人介绍
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>
    
    <!-- 系统公告 - 现在在封面下方 -->
    <?php if ($announcement['enabled'] && $currentPage === 'moments'): ?>
    <div class="announcement-banner" onclick="showAnnouncementDetail()">
        <div class="announcement-content">
            <div class="announcement-icon">
                <i class="fas fa-bullhorn"></i>
            </div>
            <div class="announcement-text">
                <div class="announcement-title"><?php echo htmlspecialchars($announcement['title']); ?></div>
                <div class="announcement-desc">
                    <?php 
                    $shortContent = mb_strlen($announcement['content'], 'UTF-8') > 30 
                        ? mb_substr($announcement['content'], 0, 30, 'UTF-8') . '...' 
                        : $announcement['content'];
                    echo htmlspecialchars($shortContent); 
                    ?>
                </div>
            </div>
            <div style="font-size: 14px; opacity: 0.7; margin-left: auto;">
                <i class="fas fa-chevron-right"></i>
            </div>
        </div>
        <div class="announcement-time">
            更新: <?php echo date('m-d H:i', strtotime($announcement['update_time'])); ?> 
        </div>
    </div>
    <?php endif; ?>
    
    <!-- 朋友圈列表 -->
    <div class="moments-list">
                <?php if (empty($allMoments)): ?>
                    <div class="empty-state">
                        <div class="empty-icon"><i class="far fa-comment-dots"></i></div>
                        <div>还没有朋友圈内容</div>
                        <div style="font-size: 14px; margin-top: 10px; color: #aaa;"><?php echo $isLogin ? '点击下方按钮发布第一条动态' : '登录后可以发布朋友圈'; ?></div>
                        <?php if (!$isLogin): ?>
                            <div style="margin-top: 20px;">
                                <button onclick="showLoginModal()" style="padding: 8px 20px; background: var(--primary-color); color: white; border: none; border-radius: 20px; font-size: 14px; cursor: pointer; margin-right: 10px;">立即登录</button>
                                <button onclick="showRegisterModal()" style="padding: 8px 20px; background: var(--secondary-color); color: white; border: none; border-radius: 20px; font-size: 14px; cursor: pointer;">注册账号</button>
                            </div>
                        <?php endif; ?>
                    </div>
                <?php else: ?>
                    <?php foreach ($allMoments as $index => $moment): ?>
                        <?php
                        $likes = getLikesForMoment($index);
                        $likeCount = count($likes);
                        $userLiked = $isLogin ? getUserLikedMoment($index, $_SESSION['user_id']) : false;
                        ?>
                        <div class="moment-item" data-index="<?php echo $index; ?>" id="moment-<?php echo $index; ?>">
                            <div class="moment-header">
                                <div class="moment-avatar" style="background-image: url('<?php echo htmlspecialchars($moment['avatar']); ?>');"></div>
                                <div class="moment-info">
                                    <div class="moment-nickname"><?php echo htmlspecialchars($moment['nickname']); ?></div>
                                    <div class="moment-time"><?php echo $moment['time']; ?></div>
                                </div>
                            </div>
                            
                            <div class="moment-content"><?php echo htmlspecialchars($moment['content']); ?></div>
                            
                            <?php if (!empty($moment['music_url'])): ?>
                                <div class="music-share" onclick="playMusic('<?php echo htmlspecialchars($moment['music_url']); ?>', '音乐分享 - <?php echo htmlspecialchars($moment['nickname']); ?>')">
                                    <div class="music-icon"><i class="fas fa-music"></i></div>
                                    <div class="music-info">
                                        <div class="music-title">音乐分享</div>
                                        <div class="music-desc text-truncate"><?php echo htmlspecialchars($moment['music_url']); ?></div>
                                    </div>
                                </div>
                            <?php endif; ?>
                            
                            <?php if (!empty($moment['images'])): ?>
                                <div class="moment-images">
                                    <?php foreach ($moment['images'] as $imgIndex => $imgPath): ?>
                                        <img src="<?php echo htmlspecialchars($imgPath); ?>" 
                                             class="moment-image image-<?php echo min(count($moment['images']), 4); ?>" 
                                             alt="朋友圈图片"
                                             onclick="previewImage(this)">
                                    <?php endforeach; ?>
                                </div>
                            <?php endif; ?>
                            
                            <?php if (!empty($moment['videos'])): ?>
                                <div class="moment-videos">
                                    <?php foreach ($moment['videos'] as $videoPath): ?>
                                        <video controls class="moment-video">
                                            <source src="<?php echo htmlspecialchars($videoPath); ?>" type="video/mp4">
                                        </video>
                                    <?php endforeach; ?>
                                </div>
                            <?php endif; ?>
                            
                            <div class="moment-actions">
                                <div class="moment-time"><?php echo date('H:i', strtotime($moment['time'])); ?></div>
                                <div class="like-comment">
                                    <div class="action-btn <?php echo $userLiked ? 'active' : ''; ?>" onclick="toggleLike(<?php echo $index; ?>)" id="like-btn-<?php echo $index; ?>">
                                        <i class="<?php echo $userLiked ? 'fas' : 'far'; ?> fa-heart"></i>
                                        <span>赞 <span id="like-count-<?php echo $index; ?>"><?php echo $likeCount; ?></span></span>
                                    </div>
                                    <div class="action-btn" onclick="showCommentModal(<?php echo $index; ?>)">
                                        <i class="far fa-comment"></i>
                                        <span>评论</span>
                                    </div>
                                    <?php if ($isLogin && $moment['user_id'] !== $_SESSION['user_id']): ?>
                                        <div class="action-btn" onclick="startPrivateChat('<?php echo $moment['user_id']; ?>', '<?php echo htmlspecialchars($moment['nickname']); ?>')">
                                            <i class="fas fa-envelope"></i>
                                            <span>私信</span>
                                        </div>
                                    <?php endif; ?>
                                </div>
                            </div>
                            
                            <?php if ($likeCount > 0): ?>
                                <div class="likes-section">
                                    <div style="color: var(--primary-color); font-weight: 500;">
                                        <i class="fas fa-heart" style="color: var(--danger-color);"></i> 
                                        <span id="likes-preview-<?php echo $index; ?>">
                                            <?php
                                            $likeNames = array_slice(array_column($likes, 'user_nickname'), 0, 3);
                                            echo implode(', ', $likeNames);
                                            if ($likeCount > 3) echo '等' . $likeCount . '人';
                                            ?>
                                        </span>
                                    </div>
                                    <div class="likes-list" id="likes-list-<?php echo $index; ?>" style="display: none;">
                                        <?php foreach ($likes as $like): ?>
                                            <div class="like-item">
                                                <div class="like-avatar" style="background-image: url('<?php echo htmlspecialchars($like['user_avatar']); ?>');"></div>
                                                <div class="like-name"><?php echo htmlspecialchars($like['user_nickname']); ?></div>
                                            </div>
                                        <?php endforeach; ?>
                                    </div>
                                    <?php if ($likeCount > 3): ?>
                                        <div style="text-align: center; margin-top: 8px;">
                                            <button onclick="toggleLikesList(<?php echo $index; ?>)" class="modal-btn secondary" style="padding: 4px 12px; font-size: 12px;">
                                                查看全部
                                            </button>
                                        </div>
                                    <?php endif; ?>
                                </div>
                            <?php endif; ?>
                            
                            <?php if (!empty($moment['comments'])): ?>
                                <div class="comments-section">
                                    <?php foreach ($moment['comments'] as $comment): ?>
                                        <div class="comment-item">
                                            <span class="commenter"><?php echo htmlspecialchars($comment['commenter']); ?>：</span>
                                            <span><?php echo htmlspecialchars($comment['content']); ?></span>
                                            <div style="font-size: 11px; color: #aaa; margin-top: 2px;"><?php echo date('H:i', strtotime($comment['time'])); ?></div>
                                        </div>
                                    <?php endforeach; ?>
                                </div>
                            <?php endif; ?>
                        </div>
                    <?php endforeach; ?>
                <?php endif; ?>
            </div>
            
            <!-- 发布按钮 -->
            <?php if ($isLogin): ?>
                <div class="publish-btn" onclick="showPublishModal()">
                    <i class="fas fa-plus"></i>
                </div>
            <?php endif; ?>
        </div>

        <!-- 私信页面 -->
<div class="messages-page">
       <!-- 搜索框 -->
    <div class="messages-search-bar">
    <div class="search-input-wrapper">
        <i class="fas fa-search"></i>
        <input type="text" id="messageSearch" 
               placeholder="搜索用户昵称、用户名..." 
               oninput="handleSearchInput(this)">
        <!-- 删除这行 -->
        <!-- <button class="search-clear" onclick="clearSearch()" style="display: none;" title="清除搜索">
            <i class="fas fa-times"></i>
        </button> -->
        <button class="search-button" onclick="performSearch()" id="searchButton" disabled title="搜索用户">
            <i class="fas fa-search"></i>
            <span>搜索</span>
        </button>
    </div>
</div>
    
    <!-- 搜索结果 -->
    <div id="searchResults" class="search-results" style="display: none;"></div>
    
    <!-- 对话列表 -->
    <div class="conversations-list" id="conversationsList">
        <!-- 对话将通过JavaScript加载 -->
        <div class="empty-state" style="padding-top: 100px;" id="conversationsEmpty">
            <div class="empty-icon"><i class="fas fa-envelope"></i></div>
            <div>还没有私信</div>
            <div style="font-size: 14px; margin-top: 10px; color: #aaa;">搜索用户开始私聊吧</div>
            <?php if (!$isLogin): ?>
                <div style="margin-top: 20px;">
                    <button onclick="showLoginModal()" style="padding: 8px 20px; background: var(--primary-color); color: white; border: none; border-radius: 20px; font-size: 14px; cursor: pointer; margin-right: 10px;">登录后使用</button>
                </div>
            <?php endif; ?>
        </div>
    </div>
</div>
    
    <div class="conversations-list" id="conversationsList">
        <!-- 搜索结果 -->
        <div id="searchResults" class="search-results" style="display: none;"></div>
        
        <!-- 对话列表将通过JavaScript动态加载 -->
        <div class="empty-state" style="padding-top: 100px;" id="conversationsEmpty">
            <div class="empty-icon"><i class="fas fa-envelope"></i></div>
            <div>还没有私信</div>
            <div style="font-size: 14px; margin-top: 10px; color: #aaa;">搜索用户开始私聊吧</div>
            <?php if (!$isLogin): ?>
                <div style="margin-top: 20px;">
                    <button onclick="showLoginModal()" style="padding: 8px 20px; background: var(--primary-color); color: white; border: none; border-radius: 20px; font-size: 14px; cursor: pointer; margin-right: 10px;">登录后使用</button>
                </div>
            <?php endif; ?>
        </div>
    </div>
</div>

        <!-- 聊天页面 -->
        <div class="chat-page">
            <div class="chat-messages" id="chatMessages">
                <?php if (empty($chatMessages)): ?>
                    <div class="empty-state" style="padding-top: 100px;">
                        <div class="empty-icon"><i class="far fa-comments"></i></div>
                        <div>还没有聊天记录</div>
                        <div style="font-size: 14px; margin-top: 10px; color: #aaa;">开始和朋友们聊天吧</div>
                        <?php if (!$isLogin): ?>
                            <div style="margin-top: 20px;">
                                <button onclick="showLoginModal()" style="padding: 8px 20px; background: var(--primary-color); color: white; border: none; border-radius: 20px; font-size: 14px; cursor: pointer; margin-right: 10px;">登录后聊天</button>
                            </div>
                        <?php endif; ?>
                    </div>
                <?php else: ?>
                    <?php foreach ($chatMessages as $index => $message): ?>
                        <?php
                        $isCurrentUser = false;
                        if ($isLogin) {
                            $isCurrentUser = $message['user_id'] === $_SESSION['user_id'];
                        } else {
                            $isCurrentUser = $message['sender'] === '游客';
                        }
                        ?>
                        <div class="chat-message <?php echo $isCurrentUser ? 'message-right' : 'message-left'; ?>">
                            <div class="message-avatar" style="background-image: url('<?php echo htmlspecialchars($message['sender_avatar'] ?? $userProfile['avatar']); ?>');"></div>
                            <div class="message-content">
                                <div class="message-bubble">
                                    <?php if ($message['type'] === 'text'): ?>
                                        <?php echo htmlspecialchars($message['content']); ?>
                                    <?php elseif ($message['type'] === 'image' && !empty($message['file'])): ?>
                                        <img src="<?php echo htmlspecialchars($message['file']); ?>" 
                                             style="max-width: 200px; border-radius: 8px; cursor: pointer;"
                                             onclick="previewImage(this)"
                                             alt="聊天图片">
                                    <?php elseif ($message['type'] === 'video' && !empty($message['file'])): ?>
                                        <video controls style="max-width: 200px; border-radius: 8px;">
                                            <source src="<?php echo htmlspecialchars($message['file']); ?>" type="video/mp4">
                                        </video>
                                    <?php elseif ($message['type'] === 'audio' && !empty($message['file'])): ?>
                                        <div class="audio-message" onclick="playAudio('<?php echo htmlspecialchars($message['file']); ?>', this, <?php echo $message['duration'] ?? 0; ?>)">
                                            <div class="audio-icon">
                                                <i class="fas fa-microphone"></i>
                                            </div>
                                            <div class="audio-info">
                                                <div style="font-size: 12px; color: #666;">语音消息</div>
                                                <div class="audio-wave">
                                                    <div class="audio-wave-bar"></div>
                                                    <div class="audio-wave-bar"></div>
                                                    <div class="audio-wave-bar"></div>
                                                    <div class="audio-wave-bar"></div>
                                                    <div class="audio-wave-bar"></div>
                                                </div>
                                                <div class="audio-duration"><?php echo $message['duration'] ?? 0; ?>秒</div>
                                            </div>
                                            <button class="audio-play-btn">
                                                <i class="fas fa-play"></i>
                                            </button>
                                        </div>
                                    <?php elseif ($message['type'] === 'music' && !empty($message['music_url'])): ?>
                                        <div style="display: flex; align-items: center; gap: 10px; cursor: pointer;" 
                                             onclick="playMusic('<?php echo htmlspecialchars($message['music_url']); ?>', '音乐分享 - <?php echo htmlspecialchars($message['sender']); ?>')">
                                            <div style="font-size: 24px;"><i class="fas fa-music"></i></div>
                                            <div>
                                                <div style="font-size: 14px; font-weight: 500;">音乐分享</div>
                                                <div style="font-size: 12px; opacity: 0.8;">点击播放</div>
                                            </div>
                                        </div>
                                    <?php endif; ?>
                                </div>
                                <div class="message-time">
                                    <?php echo date('H:i', strtotime($message['time'])); ?>
                                    <?php if ($message['sender']): ?>
                                        <div style="font-size: 10px;"><?php echo htmlspecialchars($message['sender']); ?></div>
                                    <?php endif; ?>
                                </div>
                            </div>
                        </div>
                    <?php endforeach; ?>
                <?php endif; ?>
            </div>

            <!-- 聊天输入框 -->
            <div class="chat-input-area">
                <div class="input-toolbar">
                    <button type="button" class="tool-btn active" data-type="text" onclick="setMessageType('text')">
                        <i class="fas fa-comment-dots"></i>
                    </button>
                    <button type="button" class="tool-btn" data-type="image" onclick="setMessageType('image')">
                        <i class="fas fa-image"></i>
                    </button>
                    <button type="button" class="tool-btn" data-type="video" onclick="setMessageType('video')">
                        <i class="fas fa-video"></i>
                    </button>
                    <button type="button" class="tool-btn" data-type="audio" onclick="startAudioRecording()" id="audioRecordBtn">
                        <i class="fas fa-microphone"></i>
                    </button>
                    <button type="button" class="tool-btn" data-type="music" onclick="setMessageType('music')">
                        <i class="fas fa-music"></i>
                    </button>
                </div>
                <form method="post" action="" enctype="multipart/form-data" id="chatForm">
                    <input type="hidden" name="message_type" id="messageType" value="text">
                    <input type="hidden" name="audio_duration" id="audioDuration" value="0">
                    <div class="input-box">
                        <textarea name="chat_content" id="chatContent" placeholder="<?php echo $isLogin ? '输入消息...' : '请先登录后发送消息'; ?>" <?php echo !$isLogin ? 'disabled' : ''; ?>></textarea>
                        <input type="file" name="chat_file" id="chatFile" class="hidden" accept="image/*,video/*,audio/*">
                        <input type="text" name="music_url" id="musicUrl" class="music-input" placeholder="请输入音乐链接..." <?php echo !$isLogin ? 'disabled' : ''; ?>>
                        <button type="submit" name="chat_submit" class="send-btn" id="sendBtn" <?php echo !$isLogin ? 'disabled' : ''; ?>>
                            <i class="fas fa-paper-plane"></i>
                            <span>发送</span>
                        </button>
                    </div>
                </form>
            </div>
        </div>

        <!-- 底部导航 -->
        <div class="wechat-tabbar">
            <div class="tab-item <?php echo $currentPage === 'moments' ? 'active' : ''; ?>" onclick="switchPage('moments')">
                <div class="tab-icon"><i class="fas fa-stream"></i></div>
                <div>表白墙</div>
            </div>
            <div class="tab-item <?php echo $currentPage === 'chat' ? 'active' : ''; ?>" onclick="switchPage('chat')">
                <div class="tab-icon"><i class="fas fa-comments"></i></div>
                <div>聊天</div>
            </div>
            <div class="tab-item <?php echo $currentPage === 'messages' ? 'active' : ''; ?>" onclick="switchPage('messages')">
                <div class="tab-icon"><i class="fas fa-envelope"></i></div>
                <div>私信</div>
                <?php if ($isLogin && getUnreadCount($_SESSION['user_id']) > 0): ?>
                    <div class="tab-badge" id="unreadBadge"><?php echo getUnreadCount($_SESSION['user_id']); ?></div>
                <?php endif; ?>
            </div>
            <div class="tab-item" onclick="showProfileModal()">
                <div class="tab-icon"><i class="fas fa-user"></i></div>
                <div>我的</div>
            </div>
        </div>
    </div>

    <!-- 登录/注册弹窗 -->
    <div class="modal-overlay" id="authModal">
        <div class="modal-content">
            <div class="modal-header" id="authModalTitle">登录</div>
            <div class="modal-body">
                <!-- 切换按钮 -->
                <div class="switch-buttons">
                    <button class="switch-btn active" id="loginTab" onclick="switchAuthTab('login')">登录</button>
                    <button class="switch-btn" id="registerTab" onclick="switchAuthTab('register')">注册</button>
                </div>
                
                <!-- 成功消息 -->
                <?php if ($registerSuccess): ?>
                    <div class="form-success">
                        <i class="fas fa-check-circle"></i> <?php echo $registerSuccess; ?>
                    </div>
                <?php endif; ?>
                
                <!-- 登录表单 -->
                <div id="loginFormContainer">
                    <?php if ($loginError): ?>
                        <div class="form-error" style="text-align: center; margin-bottom: 15px; padding: 10px; background: #fff0f0; border-radius: 6px;">
                            <i class="fas fa-exclamation-circle"></i> <?php echo $loginError; ?>
                        </div>
                    <?php endif; ?>
                    <form method="post" action="" id="loginForm">
                        <div class="form-group">
                            <label class="form-label" for="username">用户名</label>
                            <input type="text" id="username" name="username" class="form-input" placeholder="请输入用户名" value="<?php echo isset($_POST['username']) ? htmlspecialchars($_POST['username']) : ''; ?>" required>
                        </div>
                        <div class="form-group">
                            <label class="form-label" for="password">密码</label>
                            <input type="password" id="password" name="password" class="form-input" placeholder="请输入密码" required>
                            <div class="form-hint">先注册再登录</div>
                        </div>
                        <div class="modal-actions">
                            <button type="button" class="modal-btn cancel" onclick="closeAuthModal()">取消</button>
                            <button type="submit" name="login_submit" class="modal-btn confirm">登录</button>
                        </div>
                    </form>
                </div>
                
                <!-- 注册表单 -->
                <div id="registerFormContainer" class="hidden">
                    <?php if ($registerError && isset($_GET['showRegister'])): ?>
                        <div class="form-error" style="text-align: center; margin-bottom: 15px; padding: 10px; background: #fff0f0; border-radius: 6px;">
                            <i class="fas fa-exclamation-circle"></i> <?php echo $registerError; ?>
                        </div>
                    <?php endif; ?>
                    <form method="post" action="" id="registerForm">
                        <div class="form-group">
                            <label class="form-label" for="reg_username">用户名</label>
                            <input type="text" id="reg_username" name="reg_username" class="form-input" placeholder="3-20个字符" value="<?php echo isset($_POST['reg_username']) ? htmlspecialchars($_POST['reg_username']) : ''; ?>" required>
                            <div class="form-hint">用户名用于登录，不能包含特殊字符</div>
                        </div>
                        <div class="form-group">
                            <label class="form-label" for="reg_nickname">昵称</label>
                            <input type="text" id="reg_nickname" name="reg_nickname" class="form-input" placeholder="2-20个字符" value="<?php echo isset($_POST['reg_nickname']) ? htmlspecialchars($_POST['reg_nickname']) : ''; ?>" required>
                            <div class="form-hint">昵称将显示在朋友圈和聊天中</div>
                        </div>
                        <div class="form-group">
                            <label class="form-label" for="reg_password">密码</label>
                            <input type="password" id="reg_password" name="reg_password" class="form-input" placeholder="至少6个字符" required>
                        </div>
                        <div class="form-group">
                            <label class="form-label" for="reg_confirm_password">确认密码</label>
                            <input type="password" id="reg_confirm_password" name="reg_confirm_password" class="form-input" placeholder="再次输入密码" required>
                        </div>
                        <div class="modal-actions">
                            <button type="button" class="modal-btn cancel" onclick="closeAuthModal()">取消</button>
                            <button type="submit" name="register_submit" class="modal-btn secondary">注册</button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>

    <!-- 发布弹窗 -->
    <div class="modal-overlay" id="publishModal">
        <div class="modal-content">
            <div class="modal-header">发布朋友圈</div>
            <div class="modal-body">
                <form method="post" action="" enctype="multipart/form-data" id="publishForm">
                    <div class="form-group">
                        <textarea name="content" class="form-textarea" placeholder="分享新鲜事..." id="momentContent"></textarea>
                    </div>
                    <div class="form-group">
                        <input type="file" name="moment_imgs[]" id="momentImgsInput" multiple accept="image/*" class="hidden">
                        <button type="button" class="form-input" style="text-align: left; background: #f8f8f8; cursor: pointer;" onclick="document.getElementById('momentImgsInput').click()">
                            <i class="fas fa-images"></i> 添加图片 (最多9张)
                        </button>
                    </div>
                    <div class="form-group">
                        <input type="file" name="moment_video" id="momentVideoInput" accept="video/*" class="hidden">
                        <button type="button" class="form-input" style="text-align: left; background: #f8f8f8; cursor: pointer;" onclick="document.getElementById('momentVideoInput').click()">
                            <i class="fas fa-video"></i> 添加视频
                        </button>
                    </div>
                    <div class="form-group">
                        <input type="text" name="music_url" class="form-input" placeholder="🎵 分享音乐链接">
                    </div>
                    <div class="modal-actions">
                        <button type="button" class="modal-btn cancel" onclick="closePublishModal()">取消</button>
                        <button type="submit" name="moment_submit" class="modal-btn confirm">发布</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- 评论弹窗 -->
    <div class="modal-overlay" id="commentModal">
        <div class="modal-content">
            <div class="modal-header">发表评论</div>
            <div class="modal-body">
                <form method="post" action="" id="commentForm">
                    <input type="hidden" name="moment_index" id="commentMomentIndex">
                    <div class="form-group">
                        <textarea name="comment_content" class="form-textarea" placeholder="输入评论内容..." required></textarea>
                    </div>
                    <div class="modal-actions">
                        <button type="button" class="modal-btn cancel" onclick="closeCommentModal()">取消</button>
                        <button type="submit" name="comment_submit" class="modal-btn confirm">发送</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- 个人资料弹窗 -->
    <div class="modal-overlay" id="profileModal">
        <div class="modal-content">
            <div class="modal-header">个人资料</div>
            <div class="modal-body">
                <?php if ($isLogin): ?>
                    <form method="post" action="" enctype="multipart/form-data" id="profileForm">
                        <div class="form-group" style="text-align: center;">
                            <div style="width: 80px; height: 80px; border-radius: 50%; margin: 0 auto 16px; background-size: cover; border: 4px solid var(--primary-light); background-image: url('<?php echo htmlspecialchars($_SESSION['avatar'] ?? $userProfile['avatar']); ?>');"
                                 id="avatarPreview">
                            </div>
                            <input type="file" name="avatar" id="avatarInput" accept="image/*" class="hidden">
                            <button type="button" class="modal-btn confirm" style="margin: 10px auto; display: block; width: auto; padding: 8px 20px;" onclick="document.getElementById('avatarInput').click()">
                                更换头像
                            </button>
                        </div>
                        <div class="form-group">
                            <label class="form-label">用户名</label>
                            <input type="text" class="form-input" value="<?php echo htmlspecialchars($_SESSION['username'] ?? ''); ?>" readonly style="background: #f5f5f5;">
                        </div>
                        <div class="form-group">
                            <label class="form-label">昵称</label>
                            <input type="text" name="nickname" class="form-input" value="<?php echo htmlspecialchars($_SESSION['nickname'] ?? $userProfile['nickname']); ?>" placeholder="昵称" required>
                        </div>
                        <div class="form-group">
                            <label class="form-label">个人介绍 <span style="font-size: 12px; color: #999;">(最多75字)</span></label>
                            <textarea name="bio" class="form-input" placeholder="介绍一下你自己，最多75字..." 
                                      style="height: 80px; resize: vertical; padding: 10px 12px; font-family: inherit; font-size: 14px;"
                                      maxlength="75" 
                                      oninput="updateBioCounter(this)"><?php echo htmlspecialchars($_SESSION['bio'] ?? ''); ?></textarea>
                            <div class="form-hint" id="bioCounter">0/75</div>
                        </div>
                        <?php if (isset($_SESSION['register_time'])): ?>
                            <div class="form-group">
                                <label class="form-label">注册时间</label>
                                <input type="text" class="form-input" value="<?php echo htmlspecialchars($_SESSION['register_time']); ?>" readonly style="background: #f5f5f5;">
                            </div>
                        <?php endif; ?>
                        <div class="modal-actions">
                            <button type="button" class="modal-btn cancel" onclick="closeProfileModal()">取消</button>
                            <button type="submit" name="profile_submit" class="modal-btn confirm">保存</button>
                        </div>
                    </form>
                <?php else: ?>
                    <div style="text-align: center; padding: 40px 20px;">
                        <i class="fas fa-user-circle" style="font-size: 60px; color: #ccc; margin-bottom: 20px;"></i>
                        <p style="color: var(--text-secondary); margin-bottom: 20px;">请先登录查看个人资料</p>
                        <button onclick="showLoginModal()" style="padding: 10px 24px; background: var(--primary-color); color: white; border: none; border-radius: 20px; font-size: 14px; cursor: pointer; margin-right: 10px;">登录</button>
                        <button onclick="showRegisterModal()" style="padding: 10px 24px; background: var(--secondary-color); color: white; border: none; border-radius: 20px; font-size: 14px; cursor: pointer;">注册</button>
                    </div>
                <?php endif; ?>
            </div>
        </div>
    </div>

    <!-- 退出登录确认弹窗 -->
    <div class="modal-overlay" id="logoutModal">
        <div class="modal-content">
            <div class="modal-header">退出登录</div>
            <div class="modal-body">
                <div style="text-align: center; padding: 24px 0;">
                    <i class="fas fa-sign-out-alt" style="font-size: 40px; color: var(--primary-color); margin-bottom: 16px;"></i>
                    <p style="font-size: 16px; color: var(--text-color); margin-bottom: 8px;">确定要退出登录吗？</p>
                    <p style="font-size: 14px; color: var(--text-secondary);">退出后需要重新登录才能使用全部功能</p>
                </div>
                <div class="modal-actions">
                    <button type="button" class="modal-btn cancel" onclick="closeLogoutModal()">取消</button>
                    <button type="button" class="modal-btn confirm" onclick="confirmLogout()">确定退出</button>
                </div>
            </div>
        </div>
    </div>

    <script>
        // DOM元素
        const authModal = document.getElementById('authModal');
        const publishModal = document.getElementById('publishModal');
        const commentModal = document.getElementById('commentModal');
        const profileModal = document.getElementById('profileModal');
        const logoutModal = document.getElementById('logoutModal');
        const announcementModal = document.getElementById('announcementModal');
        const audioRecorder = document.getElementById('audioRecorder');
        const headerMore = document.getElementById('headerMore');
        const dropdownMenu = document.getElementById('dropdownMenu');
        const userAvatar = document.getElementById('userAvatar');
        const chatContent = document.getElementById('chatContent');
        const chatFile = document.getElementById('chatFile');
        const musicUrl = document.getElementById('musicUrl');
        const messageType = document.getElementById('messageType');
        const sendBtn = document.getElementById('sendBtn');
        const audioRecordBtn = document.getElementById('audioRecordBtn');
        const musicPlayer = document.getElementById('musicPlayer');
        const audioPlayer = document.getElementById('audioPlayer');
        const musicPlayerTitle = document.getElementById('musicPlayerTitle');
        const playPauseIcon = document.getElementById('playPauseIcon');
        const loginTab = document.getElementById('loginTab');
        const registerTab = document.getElementById('registerTab');
        const loginFormContainer = document.getElementById('loginFormContainer');
        const registerFormContainer = document.getElementById('registerFormContainer');
        const authModalTitle = document.getElementById('authModalTitle');
        const privateChatPage = document.getElementById('privateChatPage');
        const privateChatMessages = document.getElementById('privateChatMessages');
        const privateChatUser = document.getElementById('privateChatUser');
        const conversationsList = document.getElementById('conversationsList');
        const conversationsEmpty = document.getElementById('conversationsEmpty');
        const unreadBadge = document.getElementById('unreadBadge');
        
        // 状态变量
        const isLogin = <?php echo $isLogin ? 'true' : 'false'; ?>;
        const currentPage = '<?php echo $currentPage; ?>';
        const chatWithUserId = '<?php echo $chatWithUserId; ?>';
        let currentAudio = null;
        let imagePreviewModal = null;
        let currentAuthTab = 'login';
        let currentConversationUserId = null;
        let privateChatInterval = null;
        let conversationsInterval = null;
        
// ========== 搜索功能变量 ==========
let searchTimer = null;
let lastSearchKeyword = '';

// ========== 搜索功能函数 ==========

// 处理搜索输入
function handleSearchInput(input) {
    const keyword = input.value.trim();
    const clearBtn = input.parentNode.querySelector('.search-clear');
    const searchButton = document.getElementById('searchButton');
    
    // 更新清除按钮显示
    if (clearBtn) {
        clearBtn.style.display = keyword === '' ? 'none' : 'flex';
    }
    
    // 更新搜索按钮状态
    if (searchButton) {
        searchButton.disabled = keyword === '';
    }
    
    // 清除之前的定时器
    if (searchTimer) {
        clearTimeout(searchTimer);
    }
    
    // 如果输入为空，清除搜索结果
    if (keyword === '') {
        clearSearchResults();
        return;
    }
    
    // 设置新的定时器（300ms后执行搜索）
    searchTimer = setTimeout(() => {
        if (keyword !== lastSearchKeyword) {
            performSearch(keyword);
        }
    }, 300);
}

// 执行搜索
async function performSearch(keyword = null) {
    if (!keyword) {
        const searchInput = document.getElementById('messageSearch');
        keyword = searchInput ? searchInput.value.trim() : '';
    }
    
    if (!keyword) {
        clearSearchResults();
        return;
    }
    
    // 保存当前搜索关键词
    lastSearchKeyword = keyword;
    
    const searchResults = document.getElementById('searchResults');
    const conversationsEmpty = document.getElementById('conversationsEmpty');
    
    // 显示加载状态
    searchResults.style.display = 'block';
    searchResults.innerHTML = `
        <div style="text-align: center; padding: 60px 20px;">
            <div class="loading" style="width: 40px; height: 40px; border-width: 4px; margin: 0 auto;"></div>
            <div style="margin-top: 20px; color: var(--text-secondary);">正在搜索 "${keyword}"...</div>
        </div>
    `;
    
    // 隐藏对话列表
    if (conversationsEmpty) {
        conversationsEmpty.style.display = 'none';
    }
    
    try {
        // 调用搜索API
        const response = await fetch(`?action=search_users&keyword=${encodeURIComponent(keyword)}`);
        
        if (!response.ok) {
            throw new Error(`搜索失败 (${response.status})`);
        }
        
        const data = await response.json();
        
        if (!data.success) {
            throw new Error(data.error || '搜索失败');
        }
        
        // 渲染搜索结果
        renderSearchResults(data.results, keyword);
        
    } catch (error) {
        console.error('搜索出错:', error);
        
        searchResults.innerHTML = `
            <div class="search-no-results">
                <i class="fas fa-exclamation-triangle" style="font-size: 40px; color: var(--danger-color);"></i>
                <div style="margin-top: 16px; font-size: 16px; color: var(--text-color);">搜索失败</div>
                <div style="margin-top: 8px; font-size: 14px; color: var(--text-secondary);">${error.message}</div>
                <button onclick="performSearch('${keyword}')" 
                        style="margin-top: 20px; padding: 10px 20px; background: var(--primary-color); color: white; border: none; border-radius: 8px; cursor: pointer; font-size: 14px;">
                    <i class="fas fa-redo"></i> 重试搜索
                </button>
            </div>
        `;
    }
}

// 渲染搜索结果
function renderSearchResults(users, keyword) {
    const searchResults = document.getElementById('searchResults');
    
    if (!users || users.length === 0) {
        searchResults.innerHTML = `
            <div class="search-no-results">
                <i class="fas fa-user-slash" style="font-size: 40px; color: var(--text-secondary);"></i>
                <div style="margin-top: 16px; font-size: 16px; color: var(--text-color);">未找到用户</div>
                <div style="margin-top: 8px; font-size: 14px; color: var(--text-secondary);">尝试搜索其他关键词</div>
            </div>
        `;
        return;
    }
    
    // 创建搜索结果HTML
    let resultsHTML = `
        <div style="padding: 12px 16px; font-size: 14px; color: var(--text-secondary); border-bottom: 1px solid var(--border-color); background: var(--bg-color);">
            <i class="fas fa-search" style="margin-right: 8px;"></i>
            找到 ${users.length} 个用户
        </div>
    `;
    
    users.forEach(user => {
        // 确保用户信息完整
        const nickname = user.nickname || '未知用户';
        const username = user.username || '未知用户名';
        const bio = user.bio || '这个人很懒，还没有写个人介绍...';
        const avatar = user.avatar || 'https://picsum.photos/60/60?default';
        
        resultsHTML += `
            <div class="search-result-item">
                <div class="search-result-avatar" style="background-image: url('${avatar}');"></div>
                <div class="search-result-info">
                    <div class="search-result-name">${escapeHtml(nickname)}</div>
                    <div class="search-result-id">用户名: ${escapeHtml(username)}</div>
                    <div class="search-result-bio">${escapeHtml(bio)}</div>
                </div>
                <button class="search-result-action" onclick="startPrivateChat('${user.id}', '${escapeHtml(nickname)}')">
                    私信
                </button>
            </div>
        `;
    });
    
    searchResults.innerHTML = resultsHTML;
}

// 清除搜索
function clearSearch() {
    const searchInput = document.getElementById('messageSearch');
    const clearBtn = document.querySelector('.search-clear');
    const searchButton = document.getElementById('searchButton');
    const conversationsEmpty = document.getElementById('conversationsEmpty');
    
    if (searchInput) {
        searchInput.value = '';
        searchInput.focus();
    }
    
    if (clearBtn) {
        clearBtn.style.display = 'none';
    }
    
    if (searchButton) {
        searchButton.disabled = true;
    }
    
    clearSearchResults();
    
    // 显示对话列表空状态
    if (conversationsEmpty) {
        conversationsEmpty.style.display = 'block';
    }
}

// 清除搜索结果
function clearSearchResults() {
    const searchResults = document.getElementById('searchResults');
    if (searchResults) {
        searchResults.style.display = 'none';
        searchResults.innerHTML = '';
    }
    
    lastSearchKeyword = '';
}

// HTML转义函数
function escapeHtml(text) {
    const div = document.createElement('div');
    div.textContent = text;
    return div.innerHTML;
}

// 初始化搜索功能
function initSearch() {
    const searchInput = document.getElementById('messageSearch');
    const searchButton = document.getElementById('searchButton');
    
    if (searchInput) {
        // 绑定键盘事件
        searchInput.addEventListener('keydown', function(e) {
            // 回车键搜索
            if (e.key === 'Enter') {
                e.preventDefault();
                performSearch();
                return false;
            }
            
            // ESC键清除
            if (e.key === 'Escape') {
                clearSearch();
                return false;
            }
        });
        
        // 绑定焦点事件
        searchInput.addEventListener('focus', function() {
            this.select();
        });
    }
    
    if (searchButton) {
        // 绑定点击事件
        searchButton.addEventListener('click', function(e) {
            e.preventDefault();
            performSearch();
        });
    }
}
        
        // 音频录制相关
        let mediaRecorder = null;
        let audioChunks = [];
        let recordingTimer = null;
        let recordingSeconds = 0;
        let isRecording = false;
        let currentRecordingContext = 'chat'; // 'chat' 或 'private'

        // 页面初始化
        document.addEventListener('DOMContentLoaded', function() {
    
    // 初始化搜索按钮状态
    const searchInput = document.getElementById('messageSearch');
    const searchButton = document.getElementById('searchButton');
    
    if (searchInput && searchButton) {
        // 初始状态
        searchButton.disabled = searchInput.value.trim() === '';
        
        // 实时更新按钮状态
        searchInput.addEventListener('input', function() {
            searchButton.disabled = this.value.trim() === '';
        });
    }
    
            // 头像点击事件
            userAvatar.addEventListener('click', function() {
                showProfileModal();
            });

            // 聊天输入框自适应
            if (chatContent) {
                chatContent.addEventListener('input', function() {
                    this.style.height = 'auto';
                    this.style.height = Math.min(this.scrollHeight, 120) + 'px';
                    updateSendButton();
                });
            }

            // 音乐链接输入框监听
            if (musicUrl) {
                musicUrl.addEventListener('input', updateSendButton);
            }

            // 顶部更多按钮点击事件
            headerMore.addEventListener('click', function(e) {
                e.stopPropagation();
                dropdownMenu.classList.toggle('show');
            });

            // 点击其他地方关闭下拉菜单
            document.addEventListener('click', function(e) {
                if (!e.target.closest('.header-more') && !e.target.closest('.dropdown-menu')) {
                    dropdownMenu.classList.remove('show');
                }
            });

            // 自动显示登录弹窗
            <?php if (isset($_GET['showLogin']) && $_GET['showLogin'] === '1'): ?>
                setTimeout(() => showLoginModal(), 300);
            <?php endif; ?>
            
            // 自动显示注册弹窗
            <?php if (isset($_GET['showRegister']) && $_GET['showRegister'] === '1'): ?>
                setTimeout(() => showRegisterModal(), 300);
            <?php endif; ?>

            // 滚动到聊天底部
            if (currentPage === 'chat') {
                setTimeout(() => {
                    scrollToChatBottom();
                }, 100);
            }

            // 音频播放状态监听
            if (audioPlayer) {
                audioPlayer.addEventListener('play', function() {
                    playPauseIcon.className = 'fas fa-pause';
                });
                
                audioPlayer.addEventListener('pause', function() {
                    playPauseIcon.className = 'fas fa-play';
                });
                
                audioPlayer.addEventListener('ended', function() {
                    closeMusicPlayer();
                });
            }

            // 头像预览更新
            const avatarInput = document.getElementById('avatarInput');
            if (avatarInput) {
                avatarInput.addEventListener('change', function(e) {
                    if (e.target.files && e.target.files[0]) {
                        const reader = new FileReader();
                        reader.onload = function(event) {
                            document.getElementById('avatarPreview').style.backgroundImage = `url(${event.target.result})`;
                        };
                        reader.readAsDataURL(e.target.files[0]);
                    }
                });
            }

            // 注册表单验证
            const registerForm = document.getElementById('registerForm');
            if (registerForm) {
                registerForm.addEventListener('submit', function(e) {
                    const username = document.getElementById('reg_username').value;
                    const password = document.getElementById('reg_password').value;
                    const confirmPassword = document.getElementById('reg_confirm_password').value;
                    const nickname = document.getElementById('reg_nickname').value;
                    
                    let isValid = true;
                    
                    // 清除之前的错误样式
                    document.querySelectorAll('.form-input').forEach(input => {
                        input.classList.remove('error');
                    });
                    
                    // 验证用户名
                    if (username.length < 3 || username.length > 20) {
                        document.getElementById('reg_username').classList.add('error');
                        isValid = false;
                    }
                    
                    // 验证昵称
                    if (nickname.length < 2 || nickname.length > 20) {
                        document.getElementById('reg_nickname').classList.add('error');
                        isValid = false;
                    }
                    
                    // 验证密码
                    if (password.length < 6) {
                        document.getElementById('reg_password').classList.add('error');
                        isValid = false;
                    }
                    
                    // 验证确认密码
                    if (password !== confirmPassword) {
                        document.getElementById('reg_confirm_password').classList.add('error');
                        isValid = false;
                    }
                    
                    if (!isValid) {
                        e.preventDefault();
                        showToast('请检查表单中的错误', 'error');
                    }
                });
            }
            
            // 防止聊天输入框滚动事件冒泡
            const chatMessages = document.getElementById('chatMessages');
            const chatInputArea = document.querySelector('.chat-input-area');
            
            if (chatMessages) {
                chatMessages.addEventListener('touchmove', function(e) {
                  //  e.stopPropagation();
                }, { passive: false });
                
                chatMessages.addEventListener('wheel', function(e) {
                    e.stopPropagation();
                }, { passive: false });
            }
            
            if (chatInputArea) {
                chatInputArea.addEventListener('touchstart', function(e) {
                    e.stopPropagation();
                }, { passive: false });
            }
            
            // 私信功能初始化
            if (isLogin) {
                // 加载私信列表
                if (currentPage === 'messages') {
                    loadConversations();
                    // 每10秒刷新一次私信列表
                    conversationsInterval = setInterval(loadConversations, 10000);
                }
                
                // 如果有打开的私信聊天，加载消息
                if (chatWithUserId) {
                    openPrivateChat(chatWithUserId);
                }
            }
            
            // 个人介绍字符计数器
            updateBioCounter(document.querySelector('textarea[name="bio"]'));
            
            // 初始化音频录制
            initAudioRecording();
            
                if (currentPage === 'chat') {
        setTimeout(() => {
            const chatMessages = document.getElementById('chatMessages');
            if (chatMessages && chatMessages.scrollHeight > chatMessages.clientHeight) {
                chatMessages.scrollTop = chatMessages.scrollHeight;
            }
        }, 300);
    }
});

        
        // 页面卸载时清理定时器
        window.addEventListener('beforeunload', function() {
            if (privateChatInterval) {
                clearInterval(privateChatInterval);
            }
            if (conversationsInterval) {
                clearInterval(conversationsInterval);
            }
            if (recordingTimer) {
                clearInterval(recordingTimer);
            }
            if (mediaRecorder && isRecording) {
                mediaRecorder.stop();
            }
        });

        // 个人介绍字符计数器
        function updateBioCounter(textarea) {
            const counter = document.getElementById('bioCounter');
            if (counter && textarea) {
                const length = textarea.value.length;
                counter.textContent = `${length}/75`;
                
                // 如果超过限制，显示警告色
                if (length >= 70) {
                    counter.style.color = 'var(--warning-color)';
                } else if (length >= 75) {
                    counter.style.color = 'var(--danger-color)';
                } else {
                    counter.style.color = 'var(--text-secondary)';
                }
            }
        }

        // 切换认证标签页
        function switchAuthTab(tab) {
            currentAuthTab = tab;
            
            // 更新标签按钮
            loginTab.classList.remove('active');
            registerTab.classList.remove('active');
            
            if (tab === 'login') {
                loginTab.classList.add('active');
                loginFormContainer.classList.remove('hidden');
                registerFormContainer.classList.add('hidden');
                authModalTitle.textContent = '登录';
            } else {
                registerTab.classList.add('active');
                loginFormContainer.classList.add('hidden');
                registerFormContainer.classList.remove('hidden');
                authModalTitle.textContent = '注册';
            }
        }

        // 切换页面
        function switchPage(page) {
            window.location.href = `?page=${page}`;
        }

        // 返回上一页
        function goBack() {
            if (privateChatPage.style.display === 'block') {
                closePrivateChat();
            } else {
                window.history.back();
            }
        }

        // 点赞功能 - 已修复
        async function toggleLike(momentIndex) {
            if (!isLogin) {
                showLoginModal();
                return;
            }
            
            try {
                const response = await fetch(`?action=toggle_like&moment_index=${momentIndex}`);
                const data = await response.json();
                
                if (data.success) {
                    const likeBtn = document.getElementById(`like-btn-${momentIndex}`);
                    const likeCount = document.getElementById(`like-count-${momentIndex}`);
                    const likesPreview = document.getElementById(`likes-preview-${momentIndex}`);
                    const likesList = document.getElementById(`likes-list-${momentIndex}`);
                    
                    // 更新按钮状态
                    if (data.liked) {
                        likeBtn.classList.add('active');
                        likeBtn.querySelector('i').className = 'fas fa-heart';
                        showToast('点赞成功！', 'success');
                    } else {
                        likeBtn.classList.remove('active');
                        likeBtn.querySelector('i').className = 'far fa-heart';
                        showToast('取消点赞', 'info');
                    }
                    
                    // 更新点赞数
                    likeCount.textContent = data.like_count;
                    
                    // 更新点赞预览
                    if (data.like_count > 0) {
                        const likes = data.likes.slice(0, 3);
                        let previewText = likes.map(like => like.user_nickname).join(', ');
                        if (data.like_count > 3) {
                            previewText += '等' + data.like_count + '人';
                        }
                        likesPreview.textContent = previewText;
                        
                        // 更新点赞列表
                        if (likesList) {
                            likesList.innerHTML = data.likes.map(like => `
                                <div class="like-item">
                                    <div class="like-avatar" style="background-image: url('${like.user_avatar}');"></div>
                                    <div class="like-name">${like.user_nickname}</div>
                                </div>
                            `).join('');
                        }
                    }
                }
            } catch (error) {
                console.error('点赞失败:', error);
                showToast('操作失败，请重试', 'error');
            }
        }

        // 显示/隐藏点赞列表
        function toggleLikesList(momentIndex) {
            const likesList = document.getElementById(`likes-list-${momentIndex}`);
            if (likesList) {
                likesList.style.display = likesList.style.display === 'none' ? 'flex' : 'none';
            }
        }

        // 设置消息类型
        function setMessageType(type) {
            if (!isLogin) {
                showLoginModal();
                return;
            }
            
            if (messageType) messageType.value = type;
            
            // 更新按钮激活状态
            document.querySelectorAll('.tool-btn').forEach(btn => {
                btn.classList.remove('active');
                if (btn.getAttribute('data-type') === type) {
                    btn.classList.add('active');
                }
            });
            
            // 隐藏所有输入框
            if (chatContent) chatContent.style.display = 'none';
            if (chatFile) chatFile.style.display = 'none';
            if (musicUrl) musicUrl.style.display = 'none';
            
            // 显示对应的输入框
            if (type === 'text' && chatContent) {
                chatContent.style.display = 'block';
                chatContent.required = true;
                chatContent.focus();
            } else if ((type === 'image' || type === 'video') && chatFile) {
                chatFile.accept = type === 'image' ? 'image/*' : 'video/*';
                chatFile.click();
            } else if (type === 'music' && musicUrl) {
                musicUrl.style.display = 'block';
                musicUrl.required = true;
                musicUrl.focus();
            }
            
            updateSendButton();
        }

        // 设置私信消息类型
        function setPrivateMessageType(type) {
            const privateMessageType = document.getElementById('privateMessageType');
            const privateMessageContent = document.getElementById('privateMessageContent');
            const privateMessageFile = document.getElementById('privateMessageFile');
            const privateMusicUrl = document.getElementById('privateMusicUrl');
            const privateSendBtn = document.getElementById('privateSendBtn');
            
            if (privateMessageType) privateMessageType.value = type;
            
            // 更新按钮激活状态
            document.querySelectorAll('#privateChatPage .tool-btn').forEach(btn => {
                btn.classList.remove('active');
                if (btn.getAttribute('data-type') === type) {
                    btn.classList.add('active');
                }
            });
            
            // 隐藏所有输入框
            if (privateMessageContent) privateMessageContent.style.display = 'none';
            if (privateMusicUrl) privateMusicUrl.style.display = 'none';
            
            // 显示对应的输入框
            if (type === 'text' && privateMessageContent) {
                privateMessageContent.style.display = 'block';
                privateMessageContent.required = true;
                privateMessageContent.focus();
            } else if ((type === 'image' || type === 'video') && privateMessageFile) {
                privateMessageFile.accept = type === 'image' ? 'image/*' : type === 'video' ? 'video/*' : '*/*';
                privateMessageFile.click();
            } else if (type === 'music' && privateMusicUrl) {
                privateMusicUrl.style.display = 'block';
                privateMusicUrl.required = true;
                privateMusicUrl.focus();
            }
            
            updatePrivateSendButton();
        }

        // 更新发送按钮状态
        function updateSendButton() {
            if (!sendBtn) return;
            
            const type = messageType ? messageType.value : 'text';
            let canSend = false;
            
            if (type === 'text' && chatContent) {
                canSend = chatContent.value.trim() !== '';
            } else if (type === 'music' && musicUrl) {
                canSend = musicUrl.value.trim() !== '';
            } else if ((type === 'image' || type === 'video') && chatFile) {
                canSend = chatFile.files.length > 0;
            }
            
            sendBtn.disabled = !canSend;
        }

        // 更新私信发送按钮状态
        function updatePrivateSendButton() {
            const privateSendBtn = document.getElementById('privateSendBtn');
            const privateMessageType = document.getElementById('privateMessageType');
            const privateMessageContent = document.getElementById('privateMessageContent');
            const privateMusicUrl = document.getElementById('privateMusicUrl');
            
            if (!privateSendBtn) return;
            
            const type = privateMessageType ? privateMessageType.value : 'text';
            let canSend = false;
            
            if (type === 'text' && privateMessageContent) {
                canSend = privateMessageContent.value.trim() !== '';
            } else if (type === 'music' && privateMusicUrl) {
                canSend = privateMusicUrl.value.trim() !== '';
            } else if ((type === 'image' || type === 'video')) {
                // 文件上传不需要实时验证
                canSend = true;
            }
            
            privateSendBtn.disabled = !canSend;
        }

        // 文件选择后自动发送
        if (chatFile) {
            chatFile.addEventListener('change', function() {
                if (this.files.length > 0) {
                    updateSendButton();
                    // 自动提交表单
                    setTimeout(() => {
                        if (!sendBtn.disabled) {
                            document.getElementById('chatForm').submit();
                        }
                    }, 300);
                }
            });
        }

        // 私信文件选择
        const privateMessageFile = document.getElementById('privateMessageFile');
        if (privateMessageFile) {
            privateMessageFile.addEventListener('change', function() {
                if (this.files.length > 0) {
                    updatePrivateSendButton();
                    // 自动提交表单
                    setTimeout(() => {
                        const privateSendBtn = document.getElementById('privateSendBtn');
                        if (privateSendBtn && !privateSendBtn.disabled) {
                            document.getElementById('privateChatForm').submit();
                        }
                    }, 300);
                }
            });
        }

        // 滚动到聊天底部
        function scrollToChatBottom() {
            const chatMessages = document.getElementById('chatMessages');
            if (chatMessages) {
                chatMessages.scrollTop = chatMessages.scrollHeight;
            }
        }

        // 滚动到私信底部
        function scrollToPrivateChatBottom() {
            if (privateChatMessages) {
                privateChatMessages.scrollTop = privateChatMessages.scrollHeight;
            }
        }

        // 加载私信列表
        async function loadConversations() {
            if (!isLogin) return;
            
            try {
                const response = await fetch('?action=get_conversations');
                const data = await response.json();
                
                if (data.success) {
                    // 更新未读徽章
                    if (unreadBadge) {
                        if (data.total_unread > 0) {
                            unreadBadge.textContent = data.total_unread;
                            unreadBadge.style.display = 'flex';
                        } else {
                            unreadBadge.style.display = 'none';
                        }
                    }
                    
                    // 更新下拉菜单的未读数
                    const dropdownUnread = document.querySelector('.dropdown-item .conversation-unread');
                    if (dropdownUnread) {
                        if (data.total_unread > 0) {
                            dropdownUnread.textContent = data.total_unread;
                            dropdownUnread.style.display = 'inline-flex';
                        } else {
                            dropdownUnread.style.display = 'none';
                        }
                    }
                    
                    // 更新私信列表
                    if (conversationsList && currentPage === 'messages') {
                        if (data.conversations.length > 0) {
                            conversationsEmpty.style.display = 'none';
                            conversationsList.innerHTML = data.conversations.map(conv => {
                                const lastMessage = conv.last_message;
                                const timeAgo = getTimeAgo(lastMessage.time);
                                let preview = '';
                                
                                if (lastMessage.type === 'text') {
                                    preview = lastMessage.content.length > 20 ? 
                                        lastMessage.content.substring(0, 20) + '...' : lastMessage.content;
                                } else if (lastMessage.type === 'image') {
                                    preview = '[图片]';
                                } else if (lastMessage.type === 'video') {
                                    preview = '[视频]';
                                } else if (lastMessage.type === 'audio') {
                                    preview = '[语音]';
                                } else if (lastMessage.type === 'music') {
                                    preview = '[音乐]';
                                }
                                
                                return `
                                    <div class="conversation-item ${conv.unread_count > 0 ? 'unread' : ''}" 
                                         onclick="openPrivateChat('${conv.user.id}', '${escapeHtml(conv.user.nickname)}')">
                                        <div class="conversation-avatar" style="background-image: url('${conv.user.avatar}');"></div>
                                        <div class="conversation-info">
                                            <div class="conversation-header">
                                                <div class="conversation-name">${escapeHtml(conv.user.nickname)}</div>
                                                <div class="conversation-time">${timeAgo}</div>
                                            </div>
                                            <div class="conversation-preview">
                                                ${escapeHtml(preview)}
                                            </div>
                                        </div>
                                        ${conv.unread_count > 0 ? 
                                            `<div class="conversation-unread">${conv.unread_count}</div>` : ''}
                                    </div>
                                `;
                            }).join('');
                        } else {
                            conversationsEmpty.style.display = 'block';
                            conversationsList.innerHTML = '';
                        }
                    }
                }
            } catch (error) {
                console.error('加载私信列表失败:', error);
            }
        }

        // 打开私信聊天
        async function openPrivateChat(userId, nickname = null) {
            if (!isLogin) {
                showLoginModal();
                return;
            }
            
            currentConversationUserId = userId;
            
            // 显示私信聊天页面
            privateChatPage.style.display = 'block';
            document.querySelector('.container').style.overflow = 'hidden';
            
            // 更新标题
            document.getElementById('headerTitle').textContent = '私信';
            
            // 加载用户信息
            try {
                const response = await fetch(`?action=get_messages&user_id=${userId}`);
                const data = await response.json();
                
                if (data.success) {
                    // 更新用户信息
                    if (data.other_user) {
                        privateChatUser.innerHTML = `
                            <div class="private-chat-avatar" style="background-image: url('${data.other_user.avatar}');"></div>
                            <div>
                                <div class="private-chat-name">${escapeHtml(data.other_user.nickname)}</div>
                                <div class="private-chat-status">${data.other_user.last_active ? '最近活跃: ' + getTimeAgo(data.other_user.last_active) : '离线'}</div>
                            </div>
                        `;
                    } else if (nickname) {
                        privateChatUser.innerHTML = `
                            <div class="private-chat-avatar"></div>
                            <div class="private-chat-name">${escapeHtml(nickname)}</div>
                        `;
                    }
                    
                    // 加载消息
                    loadPrivateMessages(data.messages);
                    
                    // 设置接收者ID
                    document.getElementById('receiverId').value = userId;
                    
                    // 开始轮询新消息
                    if (privateChatInterval) {
                        clearInterval(privateChatInterval);
                    }
                    privateChatInterval = setInterval(() => loadPrivateMessages(), 3000);
                }
            } catch (error) {
                console.error('打开私信失败:', error);
                showToast('加载私信失败', 'error');
            }
        }

        // 开始私信（从朋友圈点击）
        function startPrivateChat(userId, nickname) {
            openPrivateChat(userId, nickname);
        }

        // 加载私信消息
        async function loadPrivateMessages(messages = null) {
            if (!currentConversationUserId) return;
            
            try {
                if (!messages) {
                    const response = await fetch(`?action=get_messages&user_id=${currentConversationUserId}`);
                    const data = await response.json();
                    if (data.success) {
                        messages = data.messages;
                    } else {
                        return;
                    }
                }
                
                // 渲染消息
                privateChatMessages.innerHTML = messages.map(msg => {
                    const isCurrentUser = msg.sender_id === '<?php echo $_SESSION['user_id'] ?? ''; ?>';
                    const time = new Date(msg.time).toLocaleTimeString('zh-CN', { 
                        hour: '2-digit', 
                        minute: '2-digit' 
                    });
                    
                    let contentHtml = '';
                    if (msg.type === 'text') {
                        contentHtml = escapeHtml(msg.content);
                    } else if (msg.type === 'image' && msg.file) {
                        contentHtml = `<img src="${msg.file}" style="max-width: 200px; border-radius: 8px; cursor: pointer;" onclick="previewImage(this)" alt="私信图片">`;
                    } else if (msg.type === 'video' && msg.file) {
                        contentHtml = `<video controls style="max-width: 200px; border-radius: 8px;"><source src="${msg.file}" type="video/mp4"></video>`;
                    } else if (msg.type === 'audio' && msg.file) {
                        contentHtml = `
                            <div class="audio-message" onclick="playAudio('${msg.file}', this, ${msg.duration || 0})">
                                <div class="audio-icon">
                                    <i class="fas fa-microphone"></i>
                                </div>
                                <div class="audio-info">
                                    <div style="font-size: 12px; color: #666;">语音消息</div>
                                    <div class="audio-wave">
                                        <div class="audio-wave-bar"></div>
                                        <div class="audio-wave-bar"></div>
                                        <div class="audio-wave-bar"></div>
                                        <div class="audio-wave-bar"></div>
                                        <div class="audio-wave-bar"></div>
                                    </div>
                                    <div class="audio-duration">${msg.duration || 0}秒</div>
                                </div>
                                <button class="audio-play-btn">
                                    <i class="fas fa-play"></i>
                                </button>
                            </div>
                        `;
                    } else if (msg.type === 'music' && msg.music_url) {
                        contentHtml = `
                            <div style="display: flex; align-items: center; gap: 10px; cursor: pointer;" 
                                 onclick="playMusic('${msg.music_url}', '音乐分享 - ${escapeHtml(msg.sender_nickname)}')">
                                <div style="font-size: 24px;"><i class="fas fa-music"></i></div>
                                <div>
                                    <div style="font-size: 14px; font-weight: 500;">音乐分享</div>
                                    <div style="font-size: 12px; opacity: 0.8;">点击播放</div>
                                </div>
                            </div>
                        `;
                    }
                    
                    return `
                        <div class="private-message ${isCurrentUser ? 'private-message-right' : 'private-message-left'}">
                            <div class="private-message-avatar" style="background-image: url('${msg.sender_avatar}');"></div>
                            <div class="private-message-content">
                                <div class="private-message-bubble">
                                    ${contentHtml}
                                </div>
                                <div class="private-message-time">
                                    ${time}
                                </div>
                            </div>
                        </div>
                    `;
                }).join('');
                
                // 滚动到底部
                scrollToPrivateChatBottom();
                
                // 刷新私信列表
                loadConversations();
                
            } catch (error) {
                console.error('加载私信消息失败:', error);
            }
        }

        // 关闭私信聊天
        function closePrivateChat() {
            privateChatPage.style.display = 'none';
            document.querySelector('.container').style.overflow = '';
            currentConversationUserId = null;
            
            // 更新标题
            document.getElementById('headerTitle').textContent = '私信';
            
            // 清除定时器
            if (privateChatInterval) {
                clearInterval(privateChatInterval);
                privateChatInterval = null;
            }
            
            // 刷新私信列表
            loadConversations();
        }
        
        // 搜索用户
async function searchUsers(keyword) {
    const searchResults = document.getElementById('searchResults');
    const clearBtn = document.querySelector('.search-clear');
    const conversationsEmpty = document.getElementById('conversationsEmpty');
    const searchButton = document.getElementById('searchButton');
    
    // 显示/隐藏清除按钮和更新搜索按钮状态
    if (keyword.trim() === '') {
        searchResults.style.display = 'none';
        clearBtn.style.display = 'none';
        conversationsEmpty.style.display = 'block';
        if (searchButton) {
            searchButton.disabled = true;
        }
        return;
    } else {
        clearBtn.style.display = 'flex';
        conversationsEmpty.style.display = 'none';
        if (searchButton) {
            searchButton.disabled = false;
        }
    }
    
    // 显示加载状态
    searchResults.style.display = 'block';
    searchResults.innerHTML = `
        <div style="text-align: center; padding: 40px;">
            <div class="loading" style="margin: 0 auto;"></div>
            <div style="margin-top: 16px; color: var(--text-secondary);">搜索中...</div>
        </div>
    `;
    
    // 防抖处理
    await new Promise(resolve => setTimeout(resolve, 300));
    
    try {
        // 获取所有用户
        const response = await fetch('?action=get_users');
        const data = await response.json();
        
        if (data.success) {
            // 过滤用户
            const filteredUsers = data.users.filter(user => 
                user.nickname.toLowerCase().includes(keyword.toLowerCase()) ||
                user.username.toLowerCase().includes(keyword.toLowerCase()) ||
                (user.bio && user.bio.toLowerCase().includes(keyword.toLowerCase()))
            );
            
            if (filteredUsers.length > 0) {
                searchResults.innerHTML = filteredUsers.map(user => `
                    <div class="search-result-item">
                        <div class="search-result-avatar" style="background-image: url('${user.avatar}');"></div>
                        <div class="search-result-info">
                            <div class="search-result-name">${escapeHtml(user.nickname)}</div>
                            <div class="search-result-id">ID: ${user.username}</div>
                            <div class="search-result-bio">${escapeHtml(user.bio || '这个人很懒，还没有写个人介绍...')}</div>
                        </div>
                        <button class="search-result-action" onclick="startPrivateChat('${user.id}', '${escapeHtml(user.nickname)}')">
                            发消息
                        </button>
                    </div>
                `).join('');
            } else {
                searchResults.innerHTML = `
                    <div class="search-no-results">
                        <i class="fas fa-user-slash"></i>
                        <div>没有找到用户</div>
                        <div style="font-size: 14px; margin-top: 8px;">尝试搜索其他关键词</div>
                    </div>
                `;
            }
        }
    } catch (error) {
        console.error('搜索用户失败:', error);
        showToast('搜索失败，请重试', 'error');
    }
}

// 触发搜索（搜索按钮点击）
function triggerSearch() {
    const searchInput = document.getElementById('messageSearch');
    if (searchInput && searchInput.value.trim() !== '') {
        searchUsers(searchInput.value);
    }
}

// 搜索框键盘事件
function handleSearchKeydown(event) {
    // 回车键触发搜索
    if (event.key === 'Enter') {
        event.preventDefault();
        event.stopPropagation();
        triggerSearch();
        return false;
    }
    
    // ESC键清除搜索
    if (event.key === 'Escape') {
        clearSearch();
        event.target.blur();
        event.preventDefault();
        return false;
    }
}

// 清除搜索
function clearSearch() {
    const searchInput = document.getElementById('messageSearch');
    const searchResults = document.getElementById('searchResults');
    const clearBtn = document.querySelector('.search-clear');
    const conversationsEmpty = document.getElementById('conversationsEmpty');
    const searchButton = document.getElementById('searchButton');
    
    searchInput.value = '';
    searchResults.style.display = 'none';
    clearBtn.style.display = 'none';
    conversationsEmpty.style.display = 'block';
    if (searchButton) {
        searchButton.disabled = true;
    }
    
    // 聚焦到搜索框
    searchInput.focus();
}

// 清除搜索
function clearSearch() {
    const searchInput = document.getElementById('messageSearch');
    const searchResults = document.getElementById('searchResults');
    const clearBtn = document.querySelector('.search-clear');
    const conversationsEmpty = document.getElementById('conversationsEmpty');
    
    searchInput.value = '';
    searchResults.style.display = 'none';
    clearBtn.style.display = 'none';
    conversationsEmpty.style.display = 'block';
}

        // 播放音频消息
        function playAudio(audioUrl, element, duration) {
            if (!audioUrl) {
                showToast('无效的音频文件', 'error');
                return;
            }
            
            const playBtn = element.querySelector('.audio-play-btn');
            const audio = new Audio(audioUrl);
            
            // 停止当前播放的音频
            if (currentAudio && currentAudio !== audio) {
                currentAudio.pause();
                document.querySelectorAll('.audio-play-btn').forEach(btn => {
                    btn.innerHTML = '<i class="fas fa-play"></i>';
                    btn.classList.remove('playing');
                });
            }
            
            currentAudio = audio;
            
            if (audio.paused) {
                audio.play();
                playBtn.innerHTML = '<i class="fas fa-pause"></i>';
                playBtn.classList.add('playing');
                
                audio.onended = function() {
                    playBtn.innerHTML = '<i class="fas fa-play"></i>';
                    playBtn.classList.remove('playing');
                };
                
                audio.onpause = function() {
                    playBtn.innerHTML = '<i class="fas fa-play"></i>';
                    playBtn.classList.remove('playing');
                };
                
                showToast('播放语音消息 (' + duration + '秒)', 'success');
            } else {
                audio.pause();
                playBtn.innerHTML = '<i class="fas fa-play"></i>';
                playBtn.classList.remove('playing');
            }
        }

        // 播放音乐
        function playMusic(url, title) {
            if (!url) {
                showToast('无效的音乐链接', 'error');
                return;
            }
            
            if (currentAudio) {
                currentAudio.pause();
            }
            
            audioPlayer.src = url;
            musicPlayerTitle.textContent = title;
            musicPlayer.classList.add('show');
            
            audioPlayer.play().then(() => {
                currentAudio = audioPlayer;
                showToast('开始播放: ' + title, 'success');
            }).catch(e => {
                console.error('播放失败:', e);
                showToast('无法播放该音乐，请检查链接是否正确', 'error');
            });
        }

        // 播放/暂停音乐
        function playPauseMusic() {
            if (!currentAudio) return;
            
            if (currentAudio.paused) {
                currentAudio.play();
            } else {
                currentAudio.pause();
            }
        }

        // 停止音乐
        function stopMusic() {
            if (currentAudio) {
                currentAudio.pause();
                currentAudio.currentTime = 0;
            }
        }

        // 关闭音乐播放器
        function closeMusicPlayer() {
            if (currentAudio) {
                currentAudio.pause();
                currentAudio = null;
            }
            musicPlayer.classList.remove('show');
        }

        // 图片预览
        function previewImage(imgElement) {
            if (!imagePreviewModal) {
                imagePreviewModal = document.createElement('div');
                imagePreviewModal.className = 'modal-overlay';
                imagePreviewModal.style.display = 'none';
                imagePreviewModal.innerHTML = `
                    <div style="position: relative; width: 90vw; max-width: 500px; max-height: 90vh;">
                        <button onclick="closeImagePreview()" style="position: absolute; top: 20px; right: 20px; z-index: 1; background: rgba(0,0,0,0.5); color: white; border: none; width: 40px; height: 40px; border-radius: 50%; font-size: 20px; cursor: pointer; display: flex; align-items: center; justify-content: center;">
                            <i class="fas fa-times"></i>
                        </button>
                        <img src="" style="width: 100%; height: 100%; object-fit: contain; border-radius: 12px;">
                    </div>
                `;
                document.body.appendChild(imagePreviewModal);
                
                imagePreviewModal.addEventListener('click', function(e) {
                    if (e.target === this) {
                        closeImagePreview();
                    }
                });
            }
            
            imagePreviewModal.querySelector('img').src = imgElement.src;
            imagePreviewModal.style.display = 'flex';
        }

        // 关闭图片预览
        function closeImagePreview() {
            if (imagePreviewModal) {
                imagePreviewModal.style.display = 'none';
            }
        }

        // 修改后
function showAnnouncementDetail() {
    const modal = document.getElementById('announcementModal');
    if (modal) modal.style.display = 'flex';
}

function closeAnnouncementDetail() {
    const modal = document.getElementById('announcementModal');
    if (modal) modal.style.display = 'none';
}

        // 增强兼容性的音频录制初始化
async function initAudioRecording() {
    try {
        // 1. 检查浏览器支持
     /*   if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) {
            showToast('您的浏览器不支持录音功能', 'error');
            return false;
        }*/
        
        console.log('开始初始化录音...');
        
        // 2. 尝试获取麦克风权限
        const stream = await navigator.mediaDevices.getUserMedia({ 
            audio: {
                echoCancellation: true,
                noiseSuppression: true,
                autoGainControl: true,
                // 移动端优化参数
                sampleRate: 44100,
                channelCount: 1
            }
        });
        
        console.log('麦克风权限获取成功');
        
        // 3. 确定最适合的音频格式（关键！）
        let mimeType = 'audio/webm';
        let fileExtension = 'webm';
        
        // 检测设备和浏览器
        const userAgent = navigator.userAgent.toLowerCase();
        const isIOS = /iphone|ipad|ipod/.test(userAgent);
        const isAndroid = /android/.test(userAgent);
        const isChrome = /chrome/.test(userAgent) && !/edge/.test(userAgent);
        const isSafari = /safari/.test(userAgent) && !/chrome/.test(userAgent);
        const isFirefox = /firefox/.test(userAgent);
        const isWeChat = /micromessenger/.test(userAgent);
        
        // 根据不同设备和浏览器选择格式
        if (isIOS) {
            // iOS Safari 只支持特定格式
            if (isSafari) {
                mimeType = 'audio/mp4'; // iOS Safari 支持 mp4
                fileExtension = 'm4a';
            } else if (isChrome) {
                mimeType = 'audio/webm'; // iOS Chrome 支持 webm
                fileExtension = 'webm';
            }
        } else if (isAndroid) {
            // Android 一般支持 webm
            mimeType = 'audio/webm';
            fileExtension = 'webm';
        }
        
        // 微信浏览器特殊处理
        if (isWeChat) {
            mimeType = 'audio/mp4'; // 微信内置浏览器更兼容 mp4
            fileExtension = 'm4a';
        }
        
        // 4. 检查浏览器是否支持该格式
        let supportedType = mimeType;
        if (!MediaRecorder.isTypeSupported(mimeType)) {
            console.log(`${mimeType} 不被支持，尝试其他格式...`);
            
            // 尝试常用格式
            const possibleTypes = [
                'audio/webm',
                'audio/webm;codecs=opus',
                'audio/mp4',
                'audio/mp4;codecs=mp4a',
                'audio/ogg',
                'audio/wav',
                'audio/aac',
                ''
            ];
            
            for (const type of possibleTypes) {
                if (type === '' || MediaRecorder.isTypeSupported(type)) {
                    supportedType = type || 'audio/webm';
                    console.log(`使用格式: ${supportedType}`);
                    break;
                }
            }
        }
        
        // 5. 创建MediaRecorder
        const options = supportedType ? { mimeType: supportedType } : {};
        mediaRecorder = new MediaRecorder(stream, options);
        
        console.log('MediaRecorder 创建成功，状态:', mediaRecorder.state);
        
        // 6. 设置录音数据回调
        audioChunks = []; // 重置chunks
        
        mediaRecorder.ondataavailable = function(event) {
            console.log('收到音频数据:', event.data.size, 'bytes');
            if (event.data && event.data.size > 0) {
                audioChunks.push(event.data);
            }
        };
        
        // 7. 录音结束处理（关键修改！）
        mediaRecorder.onstop = async function() {
            console.log('录音停止，处理数据...');
            
            try {
                if (audioChunks.length === 0) {
                    showToast('录音数据为空', 'error');
                    return;
                }
                
                // 创建Blob
                const audioBlob = new Blob(audioChunks, { 
                    type: supportedType || 'audio/webm' 
                });
                
                console.log('音频Blob大小:', audioBlob.size, 'bytes');
                
                // 转换为base64格式（兼容性更好）
                const reader = new FileReader();
                
                reader.onloadend = function() {
                    const base64data = reader.result;
                    
                    // 创建隐藏的表单并提交
                    const form = document.createElement('form');
                    form.method = 'POST';
                    form.style.display = 'none';
                    
                    // 添加数据
                    const voiceData = document.createElement('input');
                    voiceData.type = 'hidden';
                    voiceData.name = 'voice_data';
                    voiceData.value = base64data;
                    form.appendChild(voiceData);
                    
                    const durationInput = document.createElement('input');
                    durationInput.type = 'hidden';
                    durationInput.name = 'duration';
                    durationInput.value = recordingSeconds;
                    form.appendChild(durationInput);
                    
                    const contextInput = document.createElement('input');
                    contextInput.type = 'hidden';
                    contextInput.name = 'context';
                    contextInput.value = currentRecordingContext;
                    form.appendChild(contextInput);
                    
                    if (currentRecordingContext === 'private') {
                        const receiverInput = document.createElement('input');
                        receiverInput.type = 'hidden';
                        receiverInput.name = 'receiver_id';
                        receiverInput.value = document.getElementById('receiverId')?.value || '';
                        form.appendChild(receiverInput);
                    }
                    
                    // 添加CSRF令牌（如果需要）
                    const tokenInput = document.createElement('input');
                    tokenInput.type = 'hidden';
                    tokenInput.name = 'voice_token';
                    tokenInput.value = Date.now();
                    form.appendChild(tokenInput);
                    
                    document.body.appendChild(form);
                    
                    console.log('提交语音数据...');
                    showToast('正在上传语音...', 'info');
                    
                    form.submit();
                };
                
                reader.onerror = function() {
                    console.error('文件读取错误');
                    showToast('处理录音数据失败', 'error');
                };
                
                reader.readAsDataURL(audioBlob);
                
            } catch (error) {
                console.error('处理录音数据时出错:', error);
                showToast('处理录音失败: ' + error.message, 'error');
            } finally {
                // 清理资源
                audioChunks = [];
                recordingSeconds = 0;
                isRecording = false;
                
                // 停止所有音频轨道
                if (stream) {
                    stream.getTracks().forEach(track => {
                        track.stop();
                        console.log('停止音频轨道:', track.label);
                    });
                }
                
                // 隐藏录音界面
                audioRecorder.classList.remove('show');
                if (audioRecordBtn) {
                    audioRecordBtn.classList.remove('audio-recording');
                }
                
                // 重置录音按钮
                if (document.getElementById('recordBtn')) {
                    document.getElementById('recordBtn').innerHTML = '<i class="fas fa-microphone"></i>';
                    document.getElementById('recordBtn').style.display = 'block';
                    if (document.getElementById('stopBtn')) {
                        document.getElementById('stopBtn').style.display = 'none';
                    }
                }
            }
        };
        
        // 8. 错误处理
        mediaRecorder.onerror = function(event) {
            console.error('MediaRecorder错误:', event);
            showToast('录音出错: ' + (event.error?.message || '未知错误'), 'error');
            
            // 清理
            audioChunks = [];
            isRecording = false;
            audioRecorder.classList.remove('show');
            
            if (stream) {
                stream.getTracks().forEach(track => track.stop());
            }
        };
        
        // 9. 状态变化监听（调试用）
        mediaRecorder.onstart = function() {
            console.log('录音开始');
        };
        
        mediaRecorder.onpause = function() {
            console.log('录音暂停');
        };
        
        mediaRecorder.onresume = function() {
            console.log('录音恢复');
        };
        
        return true;
        
    } catch (error) {
        console.error('初始化录音失败:', error);
        
        // 详细的错误提示
  /*      let errorMsg = '无法访问麦克风';
        if (error.name === 'NotAllowedError' || error.name === 'PermissionDeniedError') {
            errorMsg = '麦克风权限被拒绝，请检查浏览器设置';
        } else if (error.name === 'NotFoundError' || error.name === 'DevicesNotFoundError') {
            errorMsg = '未找到麦克风设备';
        } else if (error.name === 'NotReadableError' || error.name === 'TrackStartError') {
            errorMsg = '麦克风被其他程序占用';
        } else if (error.name === 'OverconstrainedError') {
            errorMsg = '麦克风配置要求无法满足';
        } else if (error.name === 'TypeError') {
            errorMsg = '浏览器不支持录音功能';
        }
        */
        showToast(errorMsg, 'error');
        
        // 清理UI
        audioRecorder.classList.remove('show');
        if (audioRecordBtn) {
            audioRecordBtn.classList.remove('audio-recording');
        }
        
        return false;
    }
}

        // 开始聊天音频录制
        function startAudioRecording() {
            if (!isLogin) {
                showLoginModal();
                return;
            }
            
            currentRecordingContext = 'chat';
            audioRecorder.classList.add('show');
            document.getElementById('recordingTime').textContent = '00:00';
            document.getElementById('recordingHint').textContent = '点击麦克风按钮开始录音，最多60秒';
            document.getElementById('recordBtn').style.display = 'block';
            document.getElementById('stopBtn').style.display = 'none';
            
            if (audioRecordBtn) {
                audioRecordBtn.classList.add('audio-recording');
            }
        }

        // 开始私信音频录制
        function startPrivateAudioRecording() {
            if (!isLogin) {
                showLoginModal();
                return;
            }
            
            currentRecordingContext = 'private';
            audioRecorder.classList.add('show');
            document.getElementById('recordingTime').textContent = '00:00';
            document.getElementById('recordingHint').textContent = '点击麦克风按钮开始录音，最多60秒';
            document.getElementById('recordBtn').style.display = 'block';
            document.getElementById('stopBtn').style.display = 'none';
        }

        // 切换录音状态
        function toggleRecording() {
            if (!mediaRecorder) {
                showToast('麦克风初始化失败', 'error');
                return;
            }
            
            if (!isRecording) {
                // 开始录音
                audioChunks = [];
                mediaRecorder.start();
                isRecording = true;
                
                // 更新界面
                document.getElementById('recordBtn').innerHTML = '<i class="fas fa-stop"></i>';
                document.getElementById('recordBtn').style.display = 'none';
                document.getElementById('stopBtn').style.display = 'block';
                document.getElementById('recordingHint').textContent = '正在录音...点击完成按钮结束录音';
                
                // 开始计时
                recordingSeconds = 0;
                recordingTimer = setInterval(() => {
                    recordingSeconds++;
                    const minutes = Math.floor(recordingSeconds / 60);
                    const seconds = recordingSeconds % 60;
                    document.getElementById('recordingTime').textContent = 
                        `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
                    
                    // 超过60秒自动停止
                    if (recordingSeconds >= 60) {
                        stopRecording();
                        showToast('录音已满60秒，自动停止', 'warning');
                    }
                }, 1000);
            }
        }

        // 停止录音
        function stopRecording() {
            if (isRecording && mediaRecorder) {
                mediaRecorder.stop();
                isRecording = false;
                
                // 停止计时器
                if (recordingTimer) {
                    clearInterval(recordingTimer);
                    recordingTimer = null;
                }
            }
        }

        // 取消录音
        function cancelRecording() {
            if (isRecording && mediaRecorder) {
                mediaRecorder.stop();
                isRecording = false;
                
                // 停止计时器
                if (recordingTimer) {
                    clearInterval(recordingTimer);
                    recordingTimer = null;
                }
                
                // 重置
                audioChunks = [];
                recordingSeconds = 0;
                
                // 隐藏录音界面
                audioRecorder.classList.remove('show');
                if (audioRecordBtn) {
                    audioRecordBtn.classList.remove('audio-recording');
                }
                
                showToast('录音已取消', 'info');
            } else {
                // 如果没有在录音，直接隐藏
                audioRecorder.classList.remove('show');
                if (audioRecordBtn) {
                    audioRecordBtn.classList.remove('audio-recording');
                }
            }
        }

        // 显示提示消息
        function showToast(message, type = 'info') {
            const toast = document.createElement('div');
            toast.style.cssText = `
                position: fixed;
                top: 100px;
                left: 50%;
                transform: translateX(-50%) translateY(-20px);
                background: ${type === 'success' ? '#07c160' : type === 'error' ? '#ff4d4f' : '#1890ff'};
                color: white;
                padding: 12px 24px;
                border-radius: 8px;
                box-shadow: 0 4px 12px rgba(0,0,0,0.15);
                z-index: 3000;
                animation: toastIn 0.3s ease, toastOut 0.3s ease 2.7s;
                font-size: 14px;
                font-weight: 500;
                opacity: 0;
            `;
            
            const icon = type === 'success' ? '✓' : type === 'error' ? '✗' : 'ℹ️';
            toast.textContent = `${icon} ${message}`;
            document.body.appendChild(toast);
            
            // 触发动画
            setTimeout(() => {
                toast.style.animation = 'toastIn 0.3s ease forwards';
            }, 10);
            
            // 3秒后移除
            setTimeout(() => {
                toast.style.animation = 'toastOut 0.3s ease forwards';
                setTimeout(() => {
                    document.body.removeChild(toast);
                }, 300);
            }, 3000);
        }

        // 辅助函数：HTML转义
        function escapeHtml(text) {
            const div = document.createElement('div');
            div.textContent = text;
            return div.innerHTML;
        }

        // 辅助函数：时间格式化
        function getTimeAgo(timestamp) {
            const now = new Date();
            const time = new Date(timestamp);
            const diff = Math.floor((now - time) / 1000); // 秒数差
            
            if (diff < 60) {
                return '刚刚';
            } else if (diff < 3600) {
                return Math.floor(diff / 60) + '分钟前';
            } else if (diff < 86400) {
                return Math.floor(diff / 3600) + '小时前';
            } else if (diff < 2592000) {
                return Math.floor(diff / 86400) + '天前';
            } else {
                return time.toLocaleDateString('zh-CN');
            }
        }

        // 添加CSS动画
        const style = document.createElement('style');
        style.textContent = `
            @keyframes toastIn {
                from {
                    opacity: 0;
                    transform: translateX(-50%) translateY(-20px);
                }
                to {
                    opacity: 1;
                    transform: translateX(-50%) translateY(0);
                }
            }
            
            @keyframes toastOut {
                from {
                    opacity: 1;
                    transform: translateX(-50%) translateY(0);
                }
                to {
                    opacity: 0;
                    transform: translateX(-50%) translateY(-20px);
                }
            }
        `;
        document.head.appendChild(style);

        // 弹窗控制
        function showLoginModal() { 
            switchAuthTab('login');
            authModal.style.display = 'flex'; 
            dropdownMenu.classList.remove('show');
        }
        
        function showRegisterModal() { 
            switchAuthTab('register');
            authModal.style.display = 'flex'; 
            dropdownMenu.classList.remove('show');
        }
        
        function closeAuthModal() { 
            authModal.style.display = 'none'; 
        }
        
        function showPublishModal() { 
            if (!isLogin) {
                showLoginModal();
                return;
            }
            publishModal.style.display = 'flex'; 
        }
        function closePublishModal() { publishModal.style.display = 'none'; }
        
        function showCommentModal(index) { 
            if (!isLogin) {
                showLoginModal();
                return;
            }
            document.getElementById('commentMomentIndex').value = index;
            commentModal.style.display = 'flex'; 
        }
        function closeCommentModal() { commentModal.style.display = 'none'; }
        
        function showProfileModal() { 
            profileModal.style.display = 'flex'; 
        }
        function closeProfileModal() { profileModal.style.display = 'none'; }
        
        function showLogoutModal() { 
            logoutModal.style.display = 'flex'; 
            dropdownMenu.classList.remove('show');
        }
        function closeLogoutModal() { logoutModal.style.display = 'none'; }
        
        function confirmLogout() {
            window.location.href = '?action=logout';
        }

        // 点击外部关闭弹窗
        window.onclick = function(e) {
            if (e.target === authModal) closeAuthModal();
            if (e.target === publishModal) closePublishModal();
            if (e.target === commentModal) closeCommentModal();
            if (e.target === profileModal) closeProfileModal();
            if (e.target === logoutModal) closeLogoutModal();
            if (e.target.id === 'announcementModal' || e.target.classList.contains('announcement-detail-modal')) {
    closeAnnouncementDetail();
}
            if (e.target === audioRecorder) cancelRecording();
        }

        // 键盘快捷键
document.addEventListener('keydown', function(e) {
    const searchInput = document.getElementById('messageSearch');
    
    // 如果焦点在搜索框，让handleSearchKeydown处理
    if (searchInput && document.activeElement === searchInput) {
        return; // 让搜索框自己的事件处理器处理
    }
    
    // 按 / 键聚焦到搜索框
    if (e.key === '/' && currentPage === 'messages' && document.activeElement.tagName !== 'INPUT') {
        e.preventDefault();
        if (searchInput) {
            searchInput.focus();
        }
    }
    
    // ESC键关闭弹窗
    if (e.key === 'Escape') {
        closeAuthModal();
        closePublishModal();
        closeCommentModal();
        closeProfileModal();
        closeLogoutModal();
        closeImagePreview();
        closeAnnouncementDetail();
        cancelRecording();
    }
    
    // Enter发送消息
    if (e.key === 'Enter' && !e.shiftKey) {
        const activeElement = document.activeElement;
        
        if (activeElement.id === 'chatContent' && !sendBtn.disabled) {
            e.preventDefault();
            document.getElementById('chatForm').submit();
        } else if (activeElement.id === 'privateMessageContent') {
            const privateSendBtn = document.getElementById('privateSendBtn');
            if (privateSendBtn && !privateSendBtn.disabled) {
                e.preventDefault();
                document.getElementById('privateChatForm').submit();
            }
        }
    }
});
    </script>
</body>
</html>