package com.aiosman.ravenow.ui.index

import androidx.compose.animation.animateColorAsState
import androidx.compose.animation.core.animateFloatAsState
import androidx.compose.animation.core.FastOutLinearInEasing
import androidx.compose.animation.core.LinearOutSlowInEasing
import androidx.compose.animation.core.updateTransition
import androidx.compose.animation.core.animateFloat
import androidx.compose.animation.core.FastOutSlowInEasing
import androidx.compose.animation.core.tween
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.WindowInsets
import androidx.compose.foundation.layout.asPaddingValues
import androidx.compose.foundation.layout.systemBars
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.navigationBars
import androidx.compose.foundation.layout.requiredHeight
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.offset
import androidx.compose.foundation.layout.requiredWidth
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.pager.HorizontalPager
import androidx.compose.foundation.pager.rememberPagerState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.DrawerValue
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.ModalNavigationDrawer
import androidx.compose.material3.NavigationBar
import androidx.compose.material3.NavigationBarItem
import androidx.compose.material3.NavigationBarItemColors
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Switch
import androidx.compose.material3.SwitchDefaults
import androidx.compose.material3.Text
import androidx.compose.material3.rememberModalBottomSheetState
import androidx.compose.material3.rememberDrawerState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.alpha
import androidx.compose.ui.draw.scale
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.ColorFilter
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.platform.LocalLayoutDirection
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.LayoutDirection
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.ui.zIndex
import com.aiosman.ravenow.AppState
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale
import com.aiosman.ravenow.AppStore
import com.aiosman.ravenow.GuestLoginCheckOut
import com.aiosman.ravenow.GuestLoginCheckOutScene
import com.aiosman.ravenow.LocalAppTheme
import com.aiosman.ravenow.LocalNavController
import com.aiosman.ravenow.Messaging
import com.aiosman.ravenow.R
import com.aiosman.ravenow.ui.NavigationRoute
import com.aiosman.ravenow.ui.index.tabs.add.AddPage
import com.aiosman.ravenow.ui.index.tabs.ai.Agent
import com.aiosman.ravenow.ui.index.tabs.message.NotificationsScreen
import com.aiosman.ravenow.ui.index.tabs.moment.MomentsList
import com.aiosman.ravenow.ui.index.tabs.profile.ProfileWrap
import com.aiosman.ravenow.ui.index.tabs.search.DiscoverScreen
import com.aiosman.ravenow.ui.index.tabs.shorts.ShortVideo
import com.aiosman.ravenow.ui.index.tabs.street.StreetPage
import com.aiosman.ravenow.ui.modifiers.noRippleClickable
import com.aiosman.ravenow.ui.post.NewPostViewModel
import com.aiosman.ravenow.utils.ResourceCleanupManager
import com.google.accompanist.systemuicontroller.rememberSystemUiController
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch

@OptIn(ExperimentalFoundationApi::class, ExperimentalMaterial3Api::class)
@Composable
fun IndexScreen() {
    val AppColors = LocalAppTheme.current
    val model = IndexViewModel
    val navigationBarHeight = with(LocalDensity.current) {
        WindowInsets.navigationBars.getBottom(this).toDp()
    }
    val navController = LocalNavController.current
    val item = listOf(
        NavigationItem.Home,
        //NavigationItem.Dynamic,
        NavigationItem.Ai,
        NavigationItem.Add,
        NavigationItem.Notification,
        NavigationItem.Profile
    )
    val systemUiController = rememberSystemUiController()
    val pagerState = rememberPagerState(pageCount = { item.size })
    val coroutineScope = rememberCoroutineScope()
    val drawerState = rememberDrawerState(DrawerValue.Closed)
    val bottomSheetState = rememberModalBottomSheetState()
    val context = LocalContext.current

    // 注意：不要在离开 Index 路由时全量清理资源，以免返回后列表被重置
    LaunchedEffect(Unit) {
        systemUiController.setNavigationBarColor(Color.Transparent)
    }
    LaunchedEffect(model.openDrawer) {
        if (model.openDrawer) {
            drawerState.open()
            model.openDrawer = false
        }
    }
    CompositionLocalProvider(LocalLayoutDirection provides LayoutDirection.Rtl) {
        ModalNavigationDrawer(
            drawerState = drawerState,
            gesturesEnabled = drawerState.isOpen,
            drawerContent = {
                CompositionLocalProvider(LocalLayoutDirection provides LayoutDirection.Ltr) {
                    SideMenuContent(
                        onClose = {
                            coroutineScope.launch {
                                drawerState.close()
                            }
                        },
                        navController = navController,
                        context = context,
                        isDrawerOpen = drawerState.isOpen
                    )
                }
            }
        ) {
            CompositionLocalProvider(LocalLayoutDirection provides LayoutDirection.Ltr) {
                Scaffold(
                    bottomBar = {
                        NavigationBar(
                            modifier = Modifier.height(58.dp + navigationBarHeight),
                            containerColor = AppColors.tabUnselectedBackground
                        ) {
                            item.forEachIndexed { idx, it ->
                                val isSelected = model.tabIndex == idx
                                // 定义新的选中颜色
                                val selectedColor = Color(0xFF7C45ED)

                                val iconTint by animateColorAsState(
                                    targetValue = if (isSelected) selectedColor else AppColors.text,
                                    animationSpec = tween(durationMillis = 250), label = ""
                                )

                                Box(
                                    modifier = Modifier
                                        .weight(1f)
                                        .padding(top = 2.dp)
                                        .noRippleClickable {
                                            if (it.route === NavigationItem.Add.route) {
                                                // 检查游客模式，如果是游客则跳转登录
                                                if (GuestLoginCheckOut.needLogin(GuestLoginCheckOutScene.CREATE_POST)) {
                                                    navController.navigate(NavigationRoute.Login.route)
                                                    return@noRippleClickable
                                                }
                                                // 显示创建底部弹窗
                                                model.showCreateBottomSheet = true
                                                return@noRippleClickable
                                            }

                                            // 检查消息tab的游客模式
                                            if (it.route === NavigationItem.Notification.route) {
                                                if (GuestLoginCheckOut.needLogin(GuestLoginCheckOutScene.VIEW_MESSAGES)) {
                                                    navController.navigate(NavigationRoute.Login.route)
                                                    return@noRippleClickable
                                                }
                                            }

                                            // 检查我的tab的游客模式
                                            if (it.route === NavigationItem.Profile.route) {
                                                if (GuestLoginCheckOut.needLogin(GuestLoginCheckOutScene.VIEW_PROFILE)) {
                                                    navController.navigate(NavigationRoute.Login.route)
                                                    return@noRippleClickable
                                                }
                                            }

                                            coroutineScope.launch {
                                                pagerState.scrollToPage(idx)
                                            }
                                            model.tabIndex = idx
                                        },
                                    contentAlignment = Alignment.Center
                                ) {
                                    Column(
                                        horizontalAlignment = Alignment.CenterHorizontally,
                                        verticalArrangement = Arrangement.Center
                                    ) {
                                        if (it.route == NavigationItem.Add.route) {
                                            // Add按钮：只显示大图标
                                            Image(
                                                painter = painterResource(if (isSelected) it.selectedIcon() else it.icon()),
                                                contentDescription = it.label(),
                                                modifier = Modifier.size(32.dp),
                                                colorFilter = if (!isSelected) ColorFilter.tint(AppColors.text) else null
                                            )
                                        } else {
                                            // 其他按钮：图标+文字
                                            Box(
                                                modifier = Modifier
                                                    .width(48.dp)
                                                    .height(32.dp)
                                                    .background(
                                                        color = if (isSelected) selectedColor.copy(alpha = 0.15f) else Color.Transparent,
                                                        shape = RoundedCornerShape(12.dp)
                                                    ),
                                                contentAlignment = Alignment.Center
                                            ) {
                                                Image(
                                                    painter = painterResource(if (isSelected) it.selectedIcon() else it.icon()),
                                                    contentDescription = it.label(),
                                                    modifier = Modifier.size(24.dp),
                                                    colorFilter = if (!isSelected) ColorFilter.tint(AppColors.text) else null
                                                )
                                            }

                                            // 文字标签，可控制间距
                                            Spacer(modifier = Modifier.height(1.dp))

                                            Text(
                                                text = it.label(),
                                                fontSize = 10.sp,
                                                color = if (isSelected) selectedColor else AppColors.text,
                                                fontWeight = if (isSelected) FontWeight.W600 else FontWeight.Normal
                                            )
                                        }
                                    }
                                }

                            }
                        }
                    }
                ) { innerPadding ->
                    innerPadding
                    HorizontalPager(
                        state = pagerState,
                        modifier = Modifier
                            .background(AppColors.background)
                            .padding(0.dp),
                        userScrollEnabled = false
                    ) { page ->
                        when (page) {
                            0 -> Agent()
                            1 -> Home(isPageVisible = pagerState.currentPage == 1)
                            2 -> Add()
                            3 -> Notifications()
                            4 -> Profile()
                        }
                    }
                }
            }
        }
        
        // 创建底部弹窗
        if (model.showCreateBottomSheet) {
            CreateBottomSheet(
                sheetState = bottomSheetState,
                onDismiss = {
                    // 使用协程来优雅地关闭弹窗
                    coroutineScope.launch {
                        bottomSheetState.hide()
                        model.showCreateBottomSheet = false
                    }
                },
                onAiClick = {
                    // 使用协程来优雅地关闭弹窗并导航
                    coroutineScope.launch {
                        bottomSheetState.hide() // 触发关闭动画
                        model.showCreateBottomSheet = false
                        // 检查游客模式，如果是游客则跳转登录
                        if (GuestLoginCheckOut.needLogin(GuestLoginCheckOutScene.CREATE_AGENT)) {
                            navController.navigate(NavigationRoute.Login.route)
                        } else {
                            navController.navigate(NavigationRoute.AddAgent.route)
                        }
                    }
                },
                onGroupChatClick = {
                    // 使用协程来优雅地关闭弹窗并导航
                    coroutineScope.launch {
                        bottomSheetState.hide() // 触发关闭动画
                        model.showCreateBottomSheet = false
                        // 检查游客模式，如果是游客则跳转登录
                        if (GuestLoginCheckOut.needLogin(GuestLoginCheckOutScene.JOIN_GROUP_CHAT)) {
                            navController.navigate(NavigationRoute.Login.route)
                        } else {
                            navController.navigate(NavigationRoute.CreateGroupChat.route)
                        }
                    }
                },
                onMomentClick = {
                    // 使用协程来优雅地关闭弹窗并导航
                    coroutineScope.launch {
                        bottomSheetState.hide() // 触发关闭动画
                        model.showCreateBottomSheet = false
                        // 导航到动态创建页面
                        NewPostViewModel.asNewPost()
                        navController.navigate(NavigationRoute.NewPost.route)
                    }
                }
            )
        }
    }
}

@Composable
fun Home(
    isPageVisible: Boolean = true
) {
    val systemUiController = rememberSystemUiController()
    val context = LocalContext.current

    LaunchedEffect(AppState.darkMode) {
        systemUiController.setStatusBarColor(Color.Transparent, darkIcons = !AppState.darkMode)
    }

    // 注意：避免在离开 Home 时清理动态资源，防止返回详情后触发重新加载

    Column(
        modifier = Modifier
            .fillMaxSize(),
        verticalArrangement = Arrangement.Center,
        horizontalAlignment = Alignment.CenterHorizontally
    ) {
        MomentsList(isPageVisible = isPageVisible)
    }
}


@Composable
fun Street() {
    val systemUiController = rememberSystemUiController()
    val context = LocalContext.current

    LaunchedEffect(AppState.darkMode) {
        systemUiController.setStatusBarColor(Color.Transparent, darkIcons = !AppState.darkMode)
    }

    // 页面退出时清理搜索相关资源
    DisposableEffect(Unit) {
        onDispose {
            ResourceCleanupManager.cleanupPageResources("search")
        }
    }

    Column(
        modifier = Modifier
            .fillMaxSize(),
        verticalArrangement = Arrangement.Center,
        horizontalAlignment = Alignment.CenterHorizontally
    ) {
        StreetPage()
    }
}

@Composable
fun Add() {
    val systemUiController = rememberSystemUiController()
    LaunchedEffect(AppState.darkMode) {
        systemUiController.setStatusBarColor(Color.Black, darkIcons = !AppState.darkMode)
    }
    Column(
        modifier = Modifier
            .fillMaxSize()
            .background(Color.Black),
        verticalArrangement = Arrangement.Center,
        horizontalAlignment = Alignment.CenterHorizontally
    ) {
        AddPage()
    }
}

@Composable
fun Video() {
    val systemUiController = rememberSystemUiController()
    LaunchedEffect(AppState.darkMode) {
        systemUiController.setStatusBarColor(Color.Black, darkIcons = false)
    }
    Column(
        modifier = Modifier
            .fillMaxSize(),
        verticalArrangement = Arrangement.Top,
        horizontalAlignment = Alignment.CenterHorizontally,
    ) {
        ShortVideo()
    }
}


@Composable
fun Profile() {
    val systemUiController = rememberSystemUiController()
    val context = LocalContext.current

    LaunchedEffect(AppState.darkMode) {
        systemUiController.setStatusBarColor(Color.Transparent, !AppState.darkMode)
    }

    Column(
        modifier = Modifier
            .fillMaxSize(),
        verticalArrangement = Arrangement.Center,
        horizontalAlignment = Alignment.CenterHorizontally
    ) {
        ProfileWrap()
    }
}

@Composable
fun Notifications() {
    val systemUiController = rememberSystemUiController()
    val context = LocalContext.current

    LaunchedEffect(AppState.darkMode) {
        systemUiController.setStatusBarColor(Color.Transparent, !AppState.darkMode)
    }

    // 页面退出时清理消息相关资源
    DisposableEffect(Unit) {
        onDispose {
            ResourceCleanupManager.cleanupPageResources("message")
        }
    }

    Column(
        modifier = Modifier
            .fillMaxSize(),
        verticalArrangement = Arrangement.Center,
        horizontalAlignment = Alignment.CenterHorizontally
    ) {
        NotificationsScreen()
    }
}

@Composable
fun NavItem(
    iconRes: Int,
    label: String,
    modifier: Modifier = Modifier,
    rightContent: @Composable (() -> Unit)? = null
) {
    val appColors = LocalAppTheme.current
    Row(
        modifier = modifier
            .fillMaxWidth()
            .padding(top = 8.dp, start = 16.dp, end = 16.dp, bottom = 8.dp),
        verticalAlignment = Alignment.CenterVertically
    ) {
        Image(
            painter = painterResource(id = iconRes),
            contentDescription = null,
            modifier = Modifier.size(24.dp),
            colorFilter = ColorFilter.tint(appColors.text)
        )
        Text(
            text = label,
            modifier = Modifier
                .padding(start = 8.dp)
                .weight(1f),
            color = appColors.text,
        )
        if (rightContent != null) {
            rightContent()
        } else {
            Image(
                painter = painterResource(id = R.drawable.rave_now_nav_right),
                contentDescription = null,
                modifier = Modifier.size(24.dp),
                colorFilter = ColorFilter.tint(appColors.secondaryText)
            )
        }

    }
}

@Composable
fun SideMenuContent(
    onClose: () -> Unit,
    navController: androidx.navigation.NavController,
    context: android.content.Context,
    isDrawerOpen: Boolean
) {
    val appColors = LocalAppTheme.current
    val coroutineScope = rememberCoroutineScope()
    var messageNotificationEnabled by remember { mutableStateOf(true) }
    var darkModeEnabled by remember { mutableStateOf(AppState.darkMode) }
    
    // 同步暗色模式状态
    LaunchedEffect(AppState.darkMode) {
        darkModeEnabled = AppState.darkMode
    }
    
    // 菜单背景色 - 根据暗色模式适配
    val menuBackgroundColor = if (darkModeEnabled) {
        appColors.secondaryBackground // 暗色模式：深灰色
    } else {
        Color(0xFFFAF9FB) // 亮色模式：浅灰色
    }
    // 遮罩颜色 黑色透明度0.6
    val overlayColor = Color.Black.copy(alpha = 0.6f)
    // 卡片背景色 - 根据暗色模式适配
    val cardBackgroundColor = if (darkModeEnabled) {
        appColors.background // 暗色模式：深色背景
    } else {
        Color.White // 亮色模式：白色
    }
    // 文字颜色 - 根据暗色模式适配
    val textColor = appColors.text
    // 图标颜色 - 根据暗色模式适配
    val iconColor = appColors.text
    // 跟随系统文字颜色 - 根据暗色模式适配
    val followSystemTextColor = appColors.secondaryText
    // 开关开启颜色 #7C45ED
    val switchActiveColor = Color(0xFF7C45ED)
    
    Box(
        modifier = Modifier
            .fillMaxSize()
    ) {
        // 左侧半透明遮罩（平滑淡入淡出）
        val overlayTransition = updateTransition(targetState = isDrawerOpen, label = "overlay")
        val overlayAlpha by overlayTransition.animateFloat(
            transitionSpec = {
                if (targetState) {
                    tween(durationMillis = 400, easing = LinearOutSlowInEasing)
                } else {
                    tween(durationMillis = 300, easing = FastOutLinearInEasing)
                }
            },
            label = "overlayAlpha"
        ) { open -> if (open) 0.6f else 0f }
        Box(
            modifier = Modifier
                .fillMaxSize()
                .background(Color.Black.copy(alpha = overlayAlpha))
        )
        
        // 右侧菜单面板
        Box(
            modifier = Modifier
                .requiredWidth(302.dp)
                .requiredHeight(874.dp)
                .align(Alignment.CenterEnd)
                .background(menuBackgroundColor)
        ) {
            // 顶部状态栏间距
            val statusBarHeight = WindowInsets.systemBars.asPaddingValues().calculateTopPadding()
            
        // 扫一扫功能入口
        Row(
            modifier = Modifier
                .align(Alignment.TopEnd)
                .offset(x = (-60).dp, y = 88.dp)
                .noRippleClickable {
                    coroutineScope.launch {
                        onClose()
                        navController.navigate(NavigationRoute.ScanQr.route)
                    }
                },
            horizontalArrangement = Arrangement.spacedBy(8.dp),
            verticalAlignment = Alignment.CenterVertically
        ) {
            Image(
                painter = painterResource(id = R.mipmap.sao),
                contentDescription = null,
                modifier = Modifier.size(24.dp),
                colorFilter = ColorFilter.tint(iconColor)
            )
            Text(
                text = stringResource(R.string.scan_qr),
                fontSize = 14.sp,
                color = textColor,
                textAlign = TextAlign.Center
            )
        }
// QR码图标 - 右边距离右边112dp，上边距离上边68pt
            Image(
                painter = painterResource(id = R.mipmap.qr_code_icon),
                contentDescription = null,
                modifier = Modifier
                    .size(24.dp)
                    .align(Alignment.TopEnd)
                    .offset(x = (-26).dp, y = 88.dp)
                    .noRippleClickable {
                        // TODO: 实现QR码功能
                    },
                colorFilter = ColorFilter.tint(iconColor)
            )
            
            // 菜单选项卡片组 - 第一组卡片上方距离上方108pt（绝对定位）
            Column(
                modifier = Modifier
                    .fillMaxWidth()
                    .offset(y = 128.dp) // 直接距离顶部128dp（整体下移20dp）
                    .padding(horizontal = 16.dp),
                verticalArrangement = Arrangement.spacedBy(8.dp)
            ) {
                // 第一组卡片：编辑资料、账号安全、收藏
                MenuCard(
                    backgroundColor = cardBackgroundColor,
                    textColor = textColor,
                    iconColor = iconColor,
                    width = 270.dp,
                    height = 164.dp,
                    items = listOf(
                        MenuItem(
                            icon = R.mipmap.icons_edited_data,
                            label = stringResource(R.string.edit_profile_info),
                            onClick = {
                                coroutineScope.launch {
                                    onClose()
                                    navController.navigate(NavigationRoute.AccountEdit.route)
                                }
                            }
                        ),
                        MenuItem(
                            icon = R.mipmap.icons_account_and_security,
                            label = stringResource(R.string.account_and_security),
                            onClick = {
                                coroutineScope.launch {
                                    onClose()
                                    navController.navigate(NavigationRoute.AccountSetting.route)
                                }
                            }
                        ),
                        MenuItem(
                            icon = R.mipmap.collect,
                            label = stringResource(R.string.favourites),
                            onClick = {
                                coroutineScope.launch {
                                    onClose()
                                    navController.navigate(NavigationRoute.FavouriteList.route)
                                }
                            }
                        )
                    )
                )
                
                // 第二组卡片：暗色模式、消息通知
                MenuCard(
                    backgroundColor = cardBackgroundColor,
                    textColor = textColor,
                    iconColor = iconColor,
                    width = 270.dp,
                    height = 112.dp, // 根据设计图，第二组卡片高度为112dp
                    items = listOf(
                        MenuItem(
                            icon = R.mipmap.icons_dark_mode,
                            label = stringResource(R.string.dark_mode),
                            rightContent = {
                                Switch(
                                    checked = darkModeEnabled,
                                    onCheckedChange = { 
                                        darkModeEnabled = it
                                        AppState.darkMode = it
                                        AppState.appTheme = if (it) {
                                            com.aiosman.ravenow.DarkThemeColors()
                                        } else {
                                            com.aiosman.ravenow.LightThemeColors()
                                        }
                                        AppStore.saveDarkMode(it)
                                    },
                                    colors = SwitchDefaults.colors(
                                        checkedThumbColor = Color.White,
                                        checkedTrackColor = switchActiveColor,
                                        uncheckedThumbColor = Color.White,
                                        uncheckedTrackColor = switchActiveColor.copy(alpha = 0.5f),
                                        uncheckedBorderColor = Color.Transparent
                                    ),
                                    modifier = Modifier.size(width = 64.dp, height = 28.dp)
                                )
                            }
                        ),
                        MenuItem(
                            icon = R.mipmap.icons_bell,
                            label = stringResource(R.string.message_notification),
                            rightContent = {
                                Switch(
                                    checked = messageNotificationEnabled,
                                    onCheckedChange = { messageNotificationEnabled = it },
                                    colors = SwitchDefaults.colors(
                                        checkedThumbColor = Color.White,
                                        checkedTrackColor = switchActiveColor,
                                        uncheckedThumbColor = Color.White,
                                        uncheckedTrackColor = switchActiveColor.copy(alpha = 0.5f),
                                        uncheckedBorderColor = Color.Transparent
                                    ),
                                    modifier = Modifier.size(width = 64.dp, height = 28.dp)
                                )
                            }
                        )
                    )
                )
                
                // 第三组卡片：关于派派、反馈、退出登录
                MenuCard(
                    backgroundColor = cardBackgroundColor,
                    textColor = textColor,
                    iconColor = iconColor,
                    width = 270.dp,
                    height = 164.dp,
                    items = listOf(
                        MenuItem(
                            icon = R.mipmap.icons_about,
                            label = stringResource(R.string.about_paipai),
                            onClick = {
                                coroutineScope.launch {
                                    onClose()
                                    navController.navigate(NavigationRoute.AboutScreen.route)
                                }
                            }
                        ),
                        MenuItem(
                            icon = R.mipmap.feedback_icon,
                            label = stringResource(R.string.feedback),
                            onClick = {
                                coroutineScope.launch {
                                    onClose()
                                    navController.navigate(NavigationRoute.AboutScreen.route)
                                }
                            }
                        ),
                        MenuItem(
                            icon = R.mipmap.log_out_icon,
                            label = stringResource(R.string.logout_confirm),
                            onClick = {
                                coroutineScope.launch {
                                    onClose()
                                    // 只有非游客用户才需要取消注册推送设备
                                    if (!AppStore.isGuest) {
                                        Messaging.unregisterDevice(context)
                                    }
                                    AppStore.apply {
                                        token = null
                                        rememberMe = false
                                        isGuest = false
                                        saveData()
                                    }
                                    navController.navigate(NavigationRoute.Login.route) {
                                        popUpTo(NavigationRoute.Login.route) {
                                            inclusive = true
                                        }
                                    }
                                    AppState.ReloadAppState(context)
                                }
                            },
                            showRightArrow = false
                        )
                    )
                )
            }
        }
    }
}

data class MenuItem(
    val icon: Int,
    val label: String,
    val onClick: (() -> Unit)? = null,
    val rightContent: @Composable (() -> Unit)? = null,
    val showRightArrow: Boolean = true
)

@Composable
fun MenuCard(
    backgroundColor: Color,
    textColor: Color,
    iconColor: Color,
    items: List<MenuItem>,
    width: androidx.compose.ui.unit.Dp? = null,
    height: androidx.compose.ui.unit.Dp? = null
) {
    Column(
        modifier = Modifier
            .then(if (width != null) Modifier.requiredWidth(width) else Modifier.fillMaxWidth())
            .then(if (height != null) Modifier.requiredHeight(height) else Modifier)
            .background(backgroundColor, RoundedCornerShape(16.dp))
            .padding(horizontal = 16.dp),
        verticalArrangement = if (height != null) Arrangement.SpaceEvenly else Arrangement.spacedBy(8.dp) // 固定高度时均匀分布
    ) {
        items.forEachIndexed { index, item ->
            Box(
                modifier = Modifier
                    .then(if (height != null) Modifier.weight(1f) else Modifier),
                contentAlignment = Alignment.Center
            ) {
                MenuItemRow(item = item, compact = height != null, textColor = textColor, iconColor = iconColor) // 传递颜色参数
            }
        }
    }
}

@Composable
fun MenuItemRow(item: MenuItem, compact: Boolean = false, textColor: Color, iconColor: Color) {
    val appColors = LocalAppTheme.current
    Row(
        modifier = Modifier
            .fillMaxWidth()
            .then(
                if (item.onClick != null) {
                    Modifier.noRippleClickable { item.onClick?.invoke() }
                } else {
                    Modifier
                }
            )
            .padding(vertical = if (compact) 4.dp else 8.dp), // 紧凑模式下减少垂直padding
        horizontalArrangement = Arrangement.SpaceBetween,
        verticalAlignment = Alignment.CenterVertically
    ) {
        Row(
            horizontalArrangement = Arrangement.spacedBy(12.dp),
            verticalAlignment = Alignment.CenterVertically,
            modifier = Modifier.weight(1f)
        ) {
            Image(
                painter = painterResource(id = item.icon),
                contentDescription = null,
                modifier = Modifier.size(24.dp),
                colorFilter = ColorFilter.tint(iconColor)
            )
            Text(
                text = item.label,
                fontSize = 14.sp,
                color = textColor
            )
        }
        
        if (item.rightContent != null) {
            item.rightContent?.invoke()
        } else if (item.showRightArrow) {
            Image(
                painter = painterResource(id = R.drawable.rave_now_nav_right),
                contentDescription = null,
                modifier = Modifier.size(24.dp),
                colorFilter = ColorFilter.tint(appColors.text)
            )
        }
    }
}