package com.aiosman.ravenow.ui.index.tabs.moment.tabs.expolre

import android.annotation.SuppressLint
import android.widget.Toast
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.fillMaxSize
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.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.wrapContentWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.LazyRow
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.pager.HorizontalPager
import androidx.compose.foundation.pager.rememberPagerState
import androidx.compose.material3.Card
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.wrapContentSize
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.ui.platform.LocalContext
import androidx.compose.material.ExperimentalMaterialApi
import androidx.compose.material.Icon
import androidx.compose.material.pullrefresh.PullRefreshIndicator
import androidx.compose.material.pullrefresh.pullRefresh
import androidx.compose.material.pullrefresh.rememberPullRefreshState
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
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.runtime.LaunchedEffect
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.ColorFilter
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.ui.draw.clip
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.draw.blur
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.res.stringResource
import com.aiosman.ravenow.ui.composables.CustomAsyncImage
import androidx.lifecycle.viewmodel.compose.viewModel
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.R
import kotlinx.coroutines.launch
import com.aiosman.ravenow.data.Room
import com.aiosman.ravenow.data.Agent
import com.aiosman.ravenow.data.api.ApiClient
import com.aiosman.ravenow.ui.NavigationRoute
import com.aiosman.ravenow.ui.composables.AgentCard
import com.aiosman.ravenow.ui.modifiers.noRippleClickable
import com.aiosman.ravenow.ui.post.NewPostViewModel

// Banner数据类
data class BannerItem(
    val id: Int,
    val title: String,
    val subtitle: String,
    val imageUrl: String,
    val backgroundImageUrl: String,
    val userCount: Int,
    val agentName: String,
    val trtcId: String,
    val avatar: String
) {
    companion object {
        fun fromRoom(room: Room): BannerItem {
            return BannerItem(
                id = room.id,
                title = room.name ,
                subtitle = room.description ,
                imageUrl = "${ApiClient.RETROFIT_URL}${room.creator.profile.avatar}"+"?token="+"${AppStore.token}" ?: "",
                backgroundImageUrl = "${ApiClient.BASE_API_URL+"/outside"}${room.recommendBanner}"+"?token="+"${AppStore.token}" ?: "",
                userCount = room.userCount,
                agentName = room.creator.profile.nickname,
                trtcId = room.trtcRoomId,
                avatar = if (room.avatar.isNullOrEmpty()) {
                    // 将 groupId 转换为 Base64
                    val groupIdBase64 = android.util.Base64.encodeToString(
                        room.trtcType.toByteArray(),
                        android.util.Base64.NO_WRAP
                    )
                    "${ApiClient.RETROFIT_URL+"group/avatar?groupIdBase64="}${groupIdBase64}"+"&token="+"${AppStore.token}"
                } else {
                    "${ApiClient.BASE_API_URL+"/outside/"}${room.avatar}"+"?token="+"${AppStore.token}"
                }
            )
        }
    }
}

// Agent数据类
data class AgentItem(
    val id: Int,
    val title: String,
    val desc: String,
    val avatar: String,
    val useCount: Int,
    val openId: String
) {
    companion object {
        fun fromAgent(agent: Agent): AgentItem {
            return AgentItem(
                id = agent.id,
                title = agent.title,
                desc = agent.desc,
                avatar = "${ApiClient.BASE_API_URL+"/outside"}${agent.avatar}"+"?token="+"${AppStore.token}",
                useCount = agent.useCount,
                openId = agent.openId,
            )
        }
    }
}

/**
 * 探索页面
 */
@OptIn(ExperimentalMaterialApi::class)
@Composable
fun Explore() {
    val navController = LocalNavController.current
    val AppColors = LocalAppTheme.current
    val scope = rememberCoroutineScope()
    val viewModel: ExploreViewModel = viewModel()

    // 模拟刷新状态
    var isRefreshing by remember { mutableStateOf(false) }

    val enterSuccessText = stringResource(R.string.group_room_enter_success)
    val enterFailText = stringResource(R.string.group_room_enter_fail) // 假设有这个资源

    // 监听ViewModel的刷新状态
    LaunchedEffect(viewModel.isRefreshing) {
        isRefreshing = viewModel.isRefreshing
    }

    val pullRefreshState = rememberPullRefreshState(
        refreshing = isRefreshing,
        onRefresh = {
            scope.launch {
                // 重新请求数据
                viewModel.refreshBannerData()
                viewModel.refreshAgentData()
            }
        }
    )

    @SuppressLint("SuspiciousIndentation")
    @Composable
    fun AgentCard2(agentItem: AgentItem) {
        val AppColors = LocalAppTheme.current

        Row(
            modifier = Modifier
                .fillMaxWidth()
                .padding(vertical = 12.dp),
            verticalAlignment = Alignment.CenterVertically
        ) {
            // 左侧头像
            Box(
                modifier = Modifier
                    .size(48.dp)
                    .background(Color(0xFFF5F5F5), RoundedCornerShape(24.dp)),
                contentAlignment = Alignment.Center
            ) {
                if (agentItem.avatar.isNotEmpty()) {
                    CustomAsyncImage(
                        imageUrl = agentItem.avatar,
                        contentDescription = "Agent头像",
                        modifier = Modifier
                            .size(48.dp)
                            .clip(RoundedCornerShape(24.dp)),
                        contentScale = androidx.compose.ui.layout.ContentScale.Crop
                    )
                } else {
                    Image(
                        painter = painterResource(R.mipmap.rider_pro_agent),
                        contentDescription = "默认头像",
                        modifier = Modifier.size(24.dp),
                        colorFilter = ColorFilter.tint(AppColors.secondaryText)
                    )
                }
            }

            Spacer(modifier = Modifier.width(12.dp))

            // 中间文字内容
            Column(
                modifier = Modifier
                    .weight(1f)
                    .padding(end = 8.dp)
            ) {
                // 标题
                Text(
                    text = agentItem.title,
                    fontSize = 14.sp,
                    fontWeight = androidx.compose.ui.text.font.FontWeight.W600,
                    color = AppColors.text,
                    maxLines = 1,
                    overflow = androidx.compose.ui.text.style.TextOverflow.Ellipsis
                )

                Spacer(modifier = Modifier.height(8.dp))

                // 描述
                Text(
                    text = agentItem.desc,
                    fontSize = 12.sp,
                    color = AppColors.secondaryText,
                    maxLines = 1,
                    overflow = androidx.compose.ui.text.style.TextOverflow.Ellipsis
                )
            }

            // 右侧聊天按钮
            Box(
                modifier = Modifier
                    .size(width = 60.dp, height = 32.dp)
                    .background(
                        color = Color(0X147c7480),
                        shape = RoundedCornerShape(8.dp)
                    )
                    .clickable {
                        // 检查游客模式，如果是游客则跳转登录
                        if (GuestLoginCheckOut.needLogin(GuestLoginCheckOutScene.CHAT_WITH_AGENT)) {
                            navController.navigate(NavigationRoute.Login.route)
                        } else {
                            viewModel.createSingleChat(agentItem.openId)
                            viewModel.goToChatAi(agentItem.openId, navController = navController)
                        }
                    },
                contentAlignment = Alignment.Center
            ) {
                Text(
                    text = stringResource(R.string.chat),
                    fontSize = 12.sp,
                    color = AppColors.text,
                    fontWeight = androidx.compose.ui.text.font.FontWeight.W500
                )
            }
        }
    }

    @Composable
    fun AgentPage(agentItems: List<AgentItem>, page: Int, modifier: Modifier = Modifier) {
        Column(
            modifier = modifier
                .fillMaxSize()
                .padding(horizontal = 0.dp)
        ) {
            // 显示3个agent
            agentItems.forEachIndexed { index, agentItem ->
                AgentCard2(agentItem = agentItem)
                if (index < agentItems.size - 1) {
                    Spacer(modifier = Modifier.height(8.dp))
                }
            }
        }
    }

    @OptIn(ExperimentalFoundationApi::class)
    @Composable
    fun AgentViewPagerSection(agentItems: List<AgentItem>) {
        val AppColors = LocalAppTheme.current

        // 每页显示3个agent
        val itemsPerPage = 3
        val totalPages = (agentItems.size + itemsPerPage - 1) / itemsPerPage

        if (totalPages > 0) {
            val pagerState = rememberPagerState(pageCount = { totalPages })

            Column {
                // Agent内容
                Box(
                    modifier = Modifier
                        .fillMaxWidth()
                ) {
                    HorizontalPager(
                        state = pagerState,
                        modifier = Modifier.fillMaxSize(),
                        contentPadding = androidx.compose.foundation.layout.PaddingValues(horizontal = 4.dp),
                        pageSpacing = 0.dp
                    ) { page ->
                        // 计算当前页面的偏移量
                        val pageOffset = (
                                (pagerState.currentPage - page) + pagerState
                                    .currentPageOffsetFraction
                                ).coerceIn(-1f, 1f)

                        // 根据偏移量计算缩放比例
                        val scale = 1f - (0.1f * kotlin.math.abs(pageOffset))

                        AgentPage(
                            agentItems = agentItems.drop(page * itemsPerPage).take(itemsPerPage),
                            page = page,
                            modifier = Modifier
                                .graphicsLayer {
                                    scaleX = scale
                                    scaleY = scale
                                }
                        )
                    }
                }

                // 指示器
                Row(
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(top = 12.dp),
                    horizontalArrangement = androidx.compose.foundation.layout.Arrangement.Center
                ) {
                    repeat(totalPages) { index ->
                        Box(
                            modifier = Modifier
                                .padding(horizontal = 4.dp)
                                .size(3.dp)
                                .background(
                                    color = if (pagerState.currentPage == index) AppColors.text else AppColors.secondaryText.copy(alpha = 0.3f),
                                    shape = androidx.compose.foundation.shape.CircleShape
                                )
                        )
                    }
                }
            }
        }
    }

    @Composable
    fun HotChatRoomGridItem(roomItem: BannerItem) {
        val AppColors = LocalAppTheme.current
        val context = LocalContext.current
        Row(
            modifier = Modifier
                .padding(horizontal = 2.dp, vertical = 4.dp)
                .background( when (roomItem.id % 6) {
                    0 -> Color(0x285856d6)
                    1 -> Color(0x2832ade6)
                    2 -> Color(0x28ff9500)
                    3 -> Color(0x28ff3b30)
                    4 -> Color(0x28af52de)
                    else -> Color(0x28ffcc00)
                },
                    shape = RoundedCornerShape(12.dp))
                .clickable {
                    // 检查游客模式，如果是游客则跳转登录
                    if (GuestLoginCheckOut.needLogin(GuestLoginCheckOutScene.JOIN_GROUP_CHAT)) {
                        navController.navigate(NavigationRoute.Login.route)
                    } else {
                        // 调用加入房间接口
                        viewModel.joinRoom(
                            trtcId = roomItem.trtcId.toString(),
                            name = roomItem.title,
                            avatar = roomItem.avatar,
                            navController = navController,
                            onSuccess = {
                                Toast.makeText(context, enterSuccessText, Toast.LENGTH_SHORT).show()
                            },
                            onError = { errorMessage ->
                                Toast.makeText(context, enterFailText, Toast.LENGTH_SHORT).show()
                            }
                        )
                    }
                },

            verticalAlignment = Alignment.CenterVertically
        ) {
            // 左侧图标
            Spacer(modifier = Modifier.width(16.dp))
            Box(
                modifier = Modifier
                    .size(24.dp),
                contentAlignment = Alignment.Center
            ) {

                Icon(
                    painter = painterResource(id = R.drawable.rider_pro_group_chat),
                    contentDescription = null,
                    modifier = Modifier
                        .size(24.dp),
                    tint = AppColors.text
                )
            }

            Spacer(modifier = Modifier.width(6.dp))

            // 右侧文字
            Text(
                text = roomItem.title,
                fontSize = 14.sp,
                fontWeight = androidx.compose.ui.text.font.FontWeight.W500,
                color = AppColors.text,
                maxLines = 1,
                overflow = androidx.compose.ui.text.style.TextOverflow.Ellipsis,
                modifier = Modifier.padding(end = 16.dp, top = 8.dp, bottom = 8.dp)
            )
        }
    }

    @Composable
    fun HotChatRoomGrid(roomItems: List<BannerItem>) {
        val AppColors = LocalAppTheme.current

        Column(
            modifier = Modifier
                .wrapContentWidth()
                .padding(vertical = 2.dp)
        ) {
            repeat(3) { rowIndex ->
                Row(
                    modifier = Modifier
                        .wrapContentWidth()
                        .padding(vertical = 2.dp),
                    horizontalArrangement = androidx.compose.foundation.layout.Arrangement.spacedBy(8.dp)
                ) {
                    repeat(3) { columnIndex ->
                        val itemIndex = rowIndex * 2 + columnIndex
                        if (itemIndex < roomItems.size) {
                            val roomItem = roomItems[itemIndex]
                            HotChatRoomGridItem(roomItem = roomItem)
                        } else {
                            // 填充空白占位
                            //Spacer(modifier = Modifier.width(80.dp))
                        }
                    }
                }
            }
        }
    }

    @Composable
    fun HotChatRoomGridSection(roomItems: List<BannerItem>) {
        val AppColors = LocalAppTheme.current

        // 每行显示3个数据，总共3行
        val itemsPerRow = 3
        val totalRows = 3
        val totalItems = itemsPerRow * totalRows

        // 计算需要多少个完整的3x3网格
        val gridCount = (roomItems.size + totalItems - 1) / totalItems

        LazyRow(
            modifier = Modifier.fillMaxWidth(),
            contentPadding = androidx.compose.foundation.layout.PaddingValues(horizontal = 0.dp),
            horizontalArrangement = androidx.compose.foundation.layout.Arrangement.spacedBy(6.dp)
        ) {
            repeat(1) { gridIndex ->
                item {
                    HotChatRoomGrid(roomItems = viewModel.bannerItems.take(8))
                }
            }
        }
    }



    @Composable
    fun BannerCard(bannerItem: BannerItem, viewModel: ExploreViewModel, modifier: Modifier = Modifier) {
        val AppColors = LocalAppTheme.current
        val context = LocalContext.current
        val navController = LocalNavController.current

        Card(
            modifier = modifier
                .fillMaxSize()
                .padding(horizontal = 0.dp),
            shape = RoundedCornerShape(20.dp),
            elevation = androidx.compose.material3.CardDefaults.cardElevation(defaultElevation = 0.dp)
        ) {
            Box(
                modifier = Modifier.fillMaxSize()
            ) {
                // 背景图片
                if (bannerItem.backgroundImageUrl.isNotEmpty()) {
                    CustomAsyncImage(
                        context = context,
                        imageUrl = bannerItem.backgroundImageUrl,
                        contentDescription = "背景图片",
                        modifier = Modifier.fillMaxSize(),
                        contentScale = androidx.compose.ui.layout.ContentScale.Crop
                    )
                } else {
                    // 如果没有背景图片，使用默认渐变背景
                    Box(
                        modifier = Modifier
                            .fillMaxSize()
                            .background(
                                brush = androidx.compose.ui.graphics.Brush.linearGradient(
                                    colors = listOf(
                                        Color(0xFF4CAF50),
                                        Color(0xFF4CAF50).copy(alpha = 0.8f)
                                    )
                                )
                            )
                    )
                }

                // 内容
                Column(
                    modifier = Modifier
                        .fillMaxSize(),
                    verticalArrangement = androidx.compose.foundation.layout.Arrangement.SpaceBetween
                ) {
                    // 顶部：用户数量
                    Row(
                        verticalAlignment = Alignment.CenterVertically
                    ) {
                        /* Image(
                             painter = painterResource(R.drawable.rider_pro_nav_profile),
                             contentDescription = "chat",
                             modifier = Modifier.size(16.dp),
                             colorFilter = ColorFilter.tint(Color.White)
                         )
                         Spacer(modifier = Modifier.width(4.dp))
                         Text(
                             text = "${bannerItem.userCount}人在聊",
                             fontSize = 12.sp,
                             color = Color.White,
                             fontWeight = androidx.compose.ui.text.font.FontWeight.W500
                         )*/
                    }

                    // 底部：标题和描述
                    Column {
                        Text(
                            text = bannerItem.title,
                            fontSize = 24.sp,
                            maxLines = 1,
                            overflow = androidx.compose.ui.text.style.TextOverflow.Ellipsis,
                            fontWeight = androidx.compose.ui.text.font.FontWeight.Bold,
                            color = Color.White,
                            modifier = Modifier.padding(start = 16.dp)
                        )
                        Spacer(modifier = Modifier.height(8.dp))
                        Text(
                            text = bannerItem.subtitle,
                            fontSize = 14.sp,
                            color = Color.White.copy(alpha = 0.9f),
                            maxLines = 2,
                            overflow = androidx.compose.ui.text.style.TextOverflow.Ellipsis,
                            modifier = Modifier.padding(start = 16.dp, end = 16.dp)
                        )
                        Spacer(modifier = Modifier.height(16.dp))

                        Row(
                            modifier = Modifier.fillMaxWidth()
                                .background(brush = androidx.compose.ui.graphics.Brush.verticalGradient(
                                    colors = listOf(
                                        Color(0x00000000),  // 底部颜色（透明）
                                        Color(0x33000000), // 顶部颜色

                                    )
                                )),
                            horizontalArrangement = androidx.compose.foundation.layout.Arrangement.SpaceBetween,
                            verticalAlignment = Alignment.CenterVertically
                        ) {
                            Row( modifier = Modifier
                                .fillMaxWidth()
                                .padding(16.dp),
                                verticalAlignment = Alignment.CenterVertically){
                                // 左侧头像
                                Box(
                                    modifier = Modifier
                                        .size(24.dp)
                                        .background(
                                            Color.White.copy(alpha = 0.2f),
                                            RoundedCornerShape(16.dp)
                                        )

                                ) {
                                    CustomAsyncImage(
                                        context = context,
                                        imageUrl = bannerItem.imageUrl,
                                        contentDescription = "agent Image",
                                        contentScale = ContentScale.Crop,
                                        modifier = Modifier.fillMaxSize()
                                            .clip(RoundedCornerShape(24.dp)))
                                }

                                // 中间信息区域（占比1）
                                Column(
                                    modifier = Modifier
                                        .weight(1f)
                                        .padding(horizontal = 8.dp)
                                ) {
                                    Text(
                                        text = bannerItem.agentName,
                                        fontSize = 10.sp,
                                        color = Color(0xfff5f5f5).copy(alpha = 0.6f),
                                        fontWeight = androidx.compose.ui.text.font.FontWeight.W500
                                    )
                                    Text(
                                        text = bannerItem.subtitle,
                                        fontSize = 12.sp,
                                        color = Color.White,
                                        maxLines = 1,
                                        fontWeight = androidx.compose.ui.text.font.FontWeight.W400,
                                        modifier = Modifier.padding(top = 2.dp)
                                    )
                                }

                                // 右侧进入按钮
                                Box(
                                    modifier = Modifier
                                        .width(69.dp)
                                        .height(29.dp)
                                        .background(
                                            color = Color(0x7dffffff),
                                            shape = RoundedCornerShape(8.dp)
                                        )
                                        .clickable {
                                            // 检查游客模式，如果是游客则跳转登录
                                            if (GuestLoginCheckOut.needLogin(GuestLoginCheckOutScene.JOIN_GROUP_CHAT)) {
                                                navController.navigate(NavigationRoute.Login.route)
                                            } else {
                                                // 调用加入房间接口
                                                viewModel.joinRoom(
                                                    trtcId = bannerItem.trtcId.toString(),
                                                    name = bannerItem.title,
                                                    avatar = bannerItem.avatar,
                                                    navController = navController,
                                                    onSuccess = {
                                                        Toast.makeText(context, enterSuccessText, Toast.LENGTH_SHORT).show()
                                                    },
                                                    onError = { errorMessage ->
                                                        Toast.makeText(context, enterFailText, Toast.LENGTH_SHORT).show()
                                                    }
                                                )
                                            }
                                        },
                                    contentAlignment = Alignment.Center
                                ) {
                                    Text(
                                        text = stringResource(R.string.group_room_enter),
                                        fontSize = 14.sp,
                                        color = Color.White,
                                        fontWeight = androidx.compose.ui.text.font.FontWeight.W600
                                    )
                                }

                            }

                        }
                    }
                }
            }
        }

    }
    Box(
        modifier = Modifier
            .fillMaxSize()
            .pullRefresh(pullRefreshState)
    ) {
        LazyColumn(
            modifier = Modifier.fillMaxSize(),
            contentPadding = androidx.compose.foundation.layout.PaddingValues(16.dp)
        ) {


            // 第一块区域
            item {
                Row(
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(vertical = 6.dp),
                    horizontalArrangement = androidx.compose.foundation.layout.Arrangement.SpaceBetween
                ) {
                    // 第一个 - 靠左显示
                    Column(
                        modifier = Modifier
                            .clickable {
                                // 检查游客模式，如果是游客则跳转登录
                                if (GuestLoginCheckOut.needLogin(GuestLoginCheckOutScene.JOIN_GROUP_CHAT)) {
                                    navController.navigate(NavigationRoute.Login.route)
                                } else {
                                    navController.navigate(NavigationRoute.CreateGroupChat.route)
                                }
                            },
                        horizontalAlignment = Alignment.CenterHorizontally
                    ) {
                        Box(
                            modifier = Modifier
                                .size(64.dp)
                                .background(Color(0XFFC686FF), RoundedCornerShape(24.dp)),
                            contentAlignment = Alignment.Center
                        ) {
                            Image(
                                painter = painterResource(R.mipmap.rider_pro_group),
                                contentDescription = "创建群聊",
                                modifier = Modifier.size(24.dp),

                                )
                        }
                        Spacer(modifier = Modifier.size(8.dp))
                        Text(
                            text = "创建群聊",
                            fontSize = 12.sp,
                            color = AppColors.text,
                            fontWeight = androidx.compose.ui.text.font.FontWeight.W500
                        )
                    }

                    // 中间两个 - 平均分布
                    Row(
                        modifier = Modifier.weight(1f),
                        horizontalArrangement = androidx.compose.foundation.layout.Arrangement.SpaceEvenly
                    ) {
                        // 第二个
                        Column(
                            modifier = Modifier
                                .clickable {
                                    // 检查游客模式，如果是游客则跳转登录
                                    if (GuestLoginCheckOut.needLogin(GuestLoginCheckOutScene.CREATE_AGENT)) {
                                        navController.navigate(NavigationRoute.Login.route)
                                    } else {
                                        navController.navigate(NavigationRoute.AddAgent.route)
                                    }
                                },
                            horizontalAlignment = Alignment.CenterHorizontally
                        ) {
                            Box(
                                modifier = Modifier
                                    .size(64.dp)
                                    .background(Color(0xFF94f9f2), RoundedCornerShape(24.dp)),
                                contentAlignment = Alignment.Center
                            ) {
                                Image(
                                    painter = painterResource(R.mipmap.rider_pro_agent),
                                    contentDescription = "创建智能体",
                                    modifier = Modifier.size(24.dp),

                                    )
                            }
                            Spacer(modifier = Modifier.size(8.dp))
                            Text(
                                text = "创建Agent",
                                fontSize = 12.sp,
                                color = AppColors.text,
                                fontWeight = androidx.compose.ui.text.font.FontWeight.W500
                            )
                        }

                        // 第三个
                        Column(
                            modifier = Modifier
                                .clickable {
                                    // 检查游客模式，如果是游客则跳转登录
                                    if (GuestLoginCheckOut.needLogin(GuestLoginCheckOutScene.CREATE_POST)) {
                                        navController.navigate(NavigationRoute.Login.route)
                                    } else {
                                        NewPostViewModel.asNewPost()
                                        navController.navigate("NewPost")
                                    }
                                },
                            horizontalAlignment = Alignment.CenterHorizontally
                        ) {
                            Box(
                                modifier = Modifier
                                    .size(64.dp)
                                    .background(Color(0xFFfafd5d), RoundedCornerShape(24.dp)),
                                contentAlignment = Alignment.Center
                            ) {
                                Image(
                                    painter = painterResource(R.mipmap.rider_pro_release),
                                    contentDescription = "发布动态",
                                    modifier = Modifier.size(24.dp),

                                    )
                            }
                            Spacer(modifier = Modifier.size(8.dp))
                            Text(
                                text = "发布动态",
                                fontSize = 12.sp,
                                color = AppColors.text,
                                fontWeight = androidx.compose.ui.text.font.FontWeight.W500
                            )
                        }
                    }

                    // 第四个 - 靠右显示
                    Column(
                        horizontalAlignment = Alignment.CenterHorizontally
                    ) {
                        Box(
                            modifier = Modifier
                                .size(64.dp)
                                .background(Color(0xFFfc724b), RoundedCornerShape(24.dp)),
                            contentAlignment = Alignment.Center
                        ) {
                            Image(
                                painter = painterResource(R.mipmap.rider_pro_fire),
                                contentDescription = "热门智能体",
                                modifier = Modifier.size(24.dp),

                                )
                        }
                        Spacer(modifier = Modifier.size(8.dp))
                        Text(
                            text = "热门Agents",
                            fontSize = 12.sp,
                            color = AppColors.text,
                            fontWeight = androidx.compose.ui.text.font.FontWeight.W500
                        )
                    }
                }
            }

            @OptIn(ExperimentalFoundationApi::class)
            @Composable
            fun BannerSection(bannerItems: List<BannerItem>) {
                val AppColors = LocalAppTheme.current
                val context = LocalContext.current
                val scope = rememberCoroutineScope()

                val pagerState = rememberPagerState(pageCount = { bannerItems.size })

                // 预加载banner图片
                LaunchedEffect(bannerItems) {
                    bannerItems.forEach { bannerItem ->
                        if (bannerItem.backgroundImageUrl.isNotEmpty()) {
                            // 预加载背景图片
                            com.aiosman.ravenow.utils.Utils.getImageLoader(context).enqueue(
                                coil.request.ImageRequest.Builder(context)
                                    .data(bannerItem.backgroundImageUrl)
                                    .memoryCachePolicy(coil.request.CachePolicy.ENABLED)
                                    .diskCachePolicy(coil.request.CachePolicy.ENABLED)
                                    .build()
                            )
                        }
                        if (bannerItem.imageUrl.isNotEmpty()) {
                            // 预加载头像图片
                            com.aiosman.ravenow.utils.Utils.getImageLoader(context).enqueue(
                                coil.request.ImageRequest.Builder(context)
                                    .data(bannerItem.imageUrl)
                                    .memoryCachePolicy(coil.request.CachePolicy.ENABLED)
                                    .diskCachePolicy(coil.request.CachePolicy.ENABLED)
                                    .build()
                            )
                        }
                    }
                }

                Column {
                    // Banner内容
                    Box(
                        modifier = Modifier
                            .fillMaxWidth()
                            .height(362.dp)
                    ) {
                        HorizontalPager(
                            state = pagerState,
                            modifier = Modifier.fillMaxSize(),
                            contentPadding = androidx.compose.foundation.layout.PaddingValues(horizontal = 4.dp),
                        ) { page ->
                            val bannerItem = bannerItems[page]

                            // 计算当前页面的偏移量
                            val pageOffset = (
                                    (pagerState.currentPage - page) + pagerState
                                        .currentPageOffsetFraction
                                    ).coerceIn(-1f, 1f)

                            // 根据偏移量计算缩放比例
                            val scale = 1f - (0.1f * kotlin.math.abs(pageOffset))

                            BannerCard(
                                bannerItem = bannerItem,
                                viewModel = viewModel,
                                modifier = Modifier
                                    .graphicsLayer {
                                        scaleX = scale
                                        scaleY = scale
                                    }
                            )
                        }
                    }

                    // 指示器
                    Row(
                        modifier = Modifier
                            .fillMaxWidth()
                            .padding(top = 12.dp),
                        horizontalArrangement = androidx.compose.foundation.layout.Arrangement.Center
                    ) {
                        bannerItems.forEachIndexed { index, _ ->
                            Box(
                                modifier = Modifier
                                    .padding(horizontal = 4.dp)
                                    .size(3.dp)
                                    .background(
                                        color = if (pagerState.currentPage == index) AppColors.text else AppColors.secondaryText.copy(alpha = 0.3f),
                                        shape = androidx.compose.foundation.shape.CircleShape
                                    )
                            )
                        }
                    }
                }
            }


            // 第二块区域：Banner
            item {
                Column(
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(vertical = 16.dp)
                ) {
                    // 标题
                    Row(
                        verticalAlignment = Alignment.CenterVertically,
                        modifier = Modifier.padding(bottom = 12.dp)
                    ) {
                        Image(
                            painter = painterResource(R.mipmap.rider_pro_fire2),
                            contentDescription = "fire",
                            modifier = Modifier.size(28.dp),
                        )
                        Spacer(modifier = Modifier.width(4.dp))
                        Text(
                            text = "正在高能对话中",
                            fontSize = 16.sp,
                            fontWeight = androidx.compose.ui.text.font.FontWeight.W600,
                            color = AppColors.text
                        )
                    }

                    // Banner
                    BannerSection(bannerItems = viewModel.bannerItems)
                }
            }

            // 第三块区域：推荐Agent
            item {
                Column(
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(vertical = 16.dp)
                ) {
                    // 标题
                    Row(
                        verticalAlignment = Alignment.CenterVertically,
                        modifier = Modifier.padding(bottom = 12.dp)
                    ) {
                        Image(
                            painter = painterResource(R.mipmap.rider_pro_agent2),
                            contentDescription = "agent",
                            modifier = Modifier.size(28.dp),

                            )
                        Spacer(modifier = Modifier.width(4.dp))
                        Text(
                            text = "推荐给你的智能体",
                            fontSize = 16.sp,
                            fontWeight = androidx.compose.ui.text.font.FontWeight.W600,
                            color = AppColors.text
                        )
                    }

                    // Agent ViewPager
                    AgentViewPagerSection(agentItems = viewModel.agentItems.take(9))
                }
            }

            // 第四块区域：热门聊天室
            item {
                Column(
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(vertical = 16.dp)
                ) {
                    // 标题
                    Row(
                        verticalAlignment = Alignment.CenterVertically,
                        modifier = Modifier.padding(bottom = 12.dp)
                    ) {
                        Image(
                            painter = painterResource(R.mipmap.rider_pro_hot_room),
                            contentDescription = "chat room",
                            modifier = Modifier.size(24.dp),
                        )
                        Spacer(modifier = Modifier.width(4.dp))
                        Text(
                            text = "热门聊天室",
                            fontSize = 16.sp,
                            fontWeight = androidx.compose.ui.text.font.FontWeight.W600,
                            color = AppColors.text
                        )
                    }

                    // 热门聊天室列表
                    HotChatRoomGridSection(roomItems = viewModel.bannerItems)
                }
            }
        }

        PullRefreshIndicator(
            refreshing = isRefreshing,
            state = pullRefreshState,
            modifier = Modifier.align(Alignment.TopCenter)
        )
    }
}
