@file:kotlin.OptIn(ExperimentalMaterial3Api::class)

package com.aiosman.ravenow.ui.index.tabs.shorts

import android.net.Uri
import android.view.Gravity
import android.view.ViewGroup
import android.widget.FrameLayout
import androidx.annotation.DrawableRes
import androidx.annotation.OptIn
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.gestures.Orientation
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.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.ui.graphics.RectangleShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.PlayArrow
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.ModalBottomSheet
import androidx.compose.material3.Text
import androidx.compose.material3.rememberModalBottomSheetState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.MutableState
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.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.ColorFilter
import androidx.compose.ui.graphics.toArgb
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalLifecycleOwner
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.ui.viewinterop.AndroidView
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleEventObserver
import androidx.media3.common.C
import androidx.media3.common.MediaItem
import androidx.media3.common.Player
import androidx.media3.common.util.UnstableApi
import androidx.media3.common.util.Util
import androidx.media3.datasource.DataSource
import androidx.media3.datasource.DefaultDataSourceFactory
import androidx.media3.datasource.DefaultHttpDataSource
import androidx.media3.exoplayer.ExoPlayer
import androidx.media3.exoplayer.source.ProgressiveMediaSource
import androidx.media3.ui.AspectRatioFrameLayout
import androidx.media3.ui.PlayerView
import com.aiosman.ravenow.LocalAppTheme
import com.aiosman.ravenow.R
import com.aiosman.ravenow.entity.MomentEntity
import com.aiosman.ravenow.ui.comment.CommentModalContent
import com.aiosman.ravenow.ui.composables.CustomAsyncImage
import com.aiosman.ravenow.ui.modifiers.noRippleClickable
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch

// 激活状态的颜色（点赞/收藏时的红色）
private val ActiveIconColor = Color(0xFFD80264)

/**
 * 创建视频播放器视图
 */
private fun createVideoPlayerView(
    context: android.content.Context,
    exoPlayer: ExoPlayer,
    onViewCreated: (PlayerView) -> Unit
): FrameLayout {
    return FrameLayout(context).apply {
        setBackgroundColor(Color.Black.toArgb())
        layoutParams = FrameLayout.LayoutParams(
            ViewGroup.LayoutParams.MATCH_PARENT,
            ViewGroup.LayoutParams.MATCH_PARENT
        )

        val playerView = PlayerView(context).apply {
            hideController()
            useController = false
            player = exoPlayer
            resizeMode = AspectRatioFrameLayout.RESIZE_MODE_ZOOM
            setShutterBackgroundColor(Color.Black.toArgb())
            setKeepContentOnPlayerReset(false)
            
            layoutParams = FrameLayout.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.MATCH_PARENT,
                Gravity.CENTER
            )
            
            // 布局完成后固定内容帧尺寸 - 使用更可靠的方法
            var layoutListener: android.view.ViewTreeObserver.OnGlobalLayoutListener? = null
            layoutListener = object : android.view.ViewTreeObserver.OnGlobalLayoutListener {
                override fun onGlobalLayout() {
                    try {
                        val frame = findViewById<AspectRatioFrameLayout>(androidx.media3.ui.R.id.exo_content_frame)
                        if (frame != null && width > 0 && height > 0) {
                            // 确保内容帧的尺寸和缩放模式正确设置
                            val layoutParams = FrameLayout.LayoutParams(
                                width,
                                height,
                                Gravity.CENTER
                            )
                            frame.layoutParams = layoutParams
                            frame.setResizeMode(AspectRatioFrameLayout.RESIZE_MODE_ZOOM)
                            // 强制重新布局
                            frame.requestLayout()
                        }
                    } catch (e: Exception) {
                        // 忽略异常
                    }
                }
            }
            
            // 使用 post 确保在布局完成后执行
            post {
                viewTreeObserver.addOnGlobalLayoutListener(layoutListener)
                // 延迟移除监听器，确保多次布局变化都能处理
                postDelayed({
                    try {
                        layoutListener?.let { viewTreeObserver.removeOnGlobalLayoutListener(it) }
                    } catch (e: Exception) {
                        // 忽略异常
                    }
                }, 500)
            }
        }
        
        // 添加视频准备监听，确保视频准备就绪时也设置正确的缩放
        exoPlayer.addListener(object : Player.Listener {
            override fun onVideoSizeChanged(videoSize: androidx.media3.common.VideoSize) {
                playerView.post {
                    try {
                        val frame = playerView.findViewById<AspectRatioFrameLayout>(androidx.media3.ui.R.id.exo_content_frame)
                        if (frame != null && playerView.width > 0 && playerView.height > 0) {
                            frame.layoutParams = FrameLayout.LayoutParams(
                                playerView.width,
                                playerView.height,
                                Gravity.CENTER
                            )
                            frame.setResizeMode(AspectRatioFrameLayout.RESIZE_MODE_ZOOM)
                            frame.requestLayout()
                        }
                    } catch (e: Exception) {
                        // 忽略异常
                    }
                }
            }
        })
        
        onViewCreated(playerView)
        addView(playerView)
    }
}

/**
 * 处理视频点击事件（播放/暂停）
 */
private fun handleVideoClick(
    pauseIconVisibleState: MutableState<Boolean>,
    exoPlayer: ExoPlayer,
    scope: CoroutineScope
) {
    scope.launch {
        if (exoPlayer.isPlaying) {
            // 正在播放：暂停
            exoPlayer.pause()
            pauseIconVisibleState.value = true
        } else {
            // 已暂停：恢复播放
            exoPlayer.playWhenReady = true
            exoPlayer.play()
            pauseIconVisibleState.value = false
        }
    }
}

@Composable
fun ShortViewCompose(
    videoItemsUrl: List<String> = emptyList(),
    videoMoments: List<MomentEntity> = emptyList(),
    clickItemPosition: Int = 0,
    videoHeader: @Composable () -> Unit = {},
    videoBottom: @Composable ((MomentEntity) -> Unit)? = null,
    onLikeClick: ((MomentEntity) -> Unit)? = null,
    onCommentClick: ((MomentEntity) -> Unit)? = null,
    onCommentAdded: ((MomentEntity) -> Unit)? = null,
    onFavoriteClick: ((MomentEntity) -> Unit)? = null,
    onShareClick: ((MomentEntity) -> Unit)? = null,
    onAvatarClick: ((MomentEntity) -> Unit)? = null,
    onPageChanged: ((Int) -> Unit)? = null,
    isPageVisible: Boolean = true
) {
    // 优先使用 videoMoments，如果没有则使用 videoItemsUrl
    val items = if (videoMoments.isNotEmpty()) {
        videoMoments.mapNotNull { moment ->
            // MomentVideoEntity 的 url 已经在 toMomentItem() 中添加了 BASE_SERVER 前缀
            moment.videos?.firstOrNull()?.url
        }
    } else {
        videoItemsUrl
    }
    
    // 如果视频列表为空，显示空状态
    if (items.isEmpty()) {
        Box(
            modifier = Modifier.fillMaxSize(),
            contentAlignment = Alignment.Center
        ) {
            Text(
                text = "暂无视频",
                color = Color.White,
                fontSize = 16.sp
            )
        }
        return
    }
    
    // 确保 items 不为空后再创建 PagerState
    val pagerState: PagerState = remember(items.size) {
        val maxPage = maxOf(0, items.size - 1)
        PagerState(
            currentPage = clickItemPosition.coerceIn(0, maxPage),
            minPage = 0,
            maxPage = maxPage
        )
    }
    val initialLayout = remember {
        mutableStateOf(true)
    }
    
    Pager(
        modifier = Modifier
            .fillMaxSize()
            .clip(RectangleShape),
        state = pagerState,
        orientation = Orientation.Vertical,
        offscreenLimit = 1 // 只预加载相邻页面，减少内存占用
    ) {
        // 使用 key 确保每个页面独立，避免状态混乱
        androidx.compose.runtime.key(page) {
            val currentMoment = if (videoMoments.isNotEmpty() && page < videoMoments.size) {
                videoMoments[page]
            } else {
                null
            }
            
            // 同步页码到外部（用于返回时恢复进度）
            LaunchedEffect(pagerState.currentPage) {
                onPageChanged?.invoke(pagerState.currentPage)
            }
            
            SingleVideoItemContent(
                videoUrl = items[page],
                moment = currentMoment,
                pagerState = pagerState,
                pager = page,
                initialLayout = initialLayout,
                VideoHeader = videoHeader,
                VideoBottom = videoBottom,
                onLikeClick = onLikeClick,
                onCommentClick = onCommentClick,
                onCommentAdded = onCommentAdded,
                onFavoriteClick = onFavoriteClick,
                onShareClick = onShareClick,
                onAvatarClick = onAvatarClick,
                isPageVisible = isPageVisible
            )
        }
    }

    LaunchedEffect(clickItemPosition) {
        delay(300)
        initialLayout.value = false
    }

}

@Composable
private fun SingleVideoItemContent(
    videoUrl: String,
    moment: MomentEntity?,
    pagerState: PagerState,
    pager: Int,
    initialLayout: MutableState<Boolean>,
    VideoHeader: @Composable() () -> Unit = {},
    VideoBottom: @Composable ((MomentEntity) -> Unit)? = null,
    onLikeClick: ((MomentEntity) -> Unit)? = null,
    onCommentClick: ((MomentEntity) -> Unit)? = null,
    onCommentAdded: ((MomentEntity) -> Unit)? = null,
    onFavoriteClick: ((MomentEntity) -> Unit)? = null,
    onShareClick: ((MomentEntity) -> Unit)? = null,
    onAvatarClick: ((MomentEntity) -> Unit)? = null,
    isPageVisible: Boolean = true
) {
    // 将暂停状态移到每个视频项内部，使用 remember 保存，避免在点赞/关注时被重置
    val pauseIconVisibleState = remember(pager) {
        mutableStateOf(false)
    }
    
    // 当页面切换时，重置暂停状态
    LaunchedEffect(pager, pagerState.currentPage) {
        if (pager != pagerState.currentPage) {
            pauseIconVisibleState.value = false
        }
    }
    
    Box(
        modifier = Modifier
            .fillMaxSize()
            .clip(RectangleShape) // 确保内容不会溢出到box外
    ) {
        VideoPlayer(
            videoUrl = videoUrl,
            moment = moment,
            pagerState = pagerState,
            pager = pager,
            pauseIconVisibleState = pauseIconVisibleState,
            onLikeClick = onLikeClick,
            onCommentClick = onCommentClick,
            onCommentAdded = onCommentAdded,
            onFavoriteClick = onFavoriteClick,
            onShareClick = onShareClick,
            onAvatarClick = onAvatarClick,
            isPageVisible = isPageVisible
        )
        VideoHeader.invoke()
        if (moment != null && VideoBottom != null) {
            Box(modifier = Modifier.align(Alignment.BottomStart)) {
                VideoBottom.invoke(moment)
            }
        }
        if (initialLayout.value) {
            Box(
                modifier = Modifier
                    .fillMaxSize()
                    .background(color = Color.Black)
            )
        }
    }
}

@OptIn(UnstableApi::class)
@Composable
fun VideoPlayer(
    videoUrl: String,
    moment: MomentEntity?,
    pagerState: PagerState,
    pager: Int,
    pauseIconVisibleState: MutableState<Boolean>,
    onLikeClick: ((MomentEntity) -> Unit)? = null,
    onCommentClick: ((MomentEntity) -> Unit)? = null,
    onCommentAdded: ((MomentEntity) -> Unit)? = null,
    onFavoriteClick: ((MomentEntity) -> Unit)? = null,
    onShareClick: ((MomentEntity) -> Unit)? = null,
    onAvatarClick: ((MomentEntity) -> Unit)? = null,
    isPageVisible: Boolean = true
) {
    val context = LocalContext.current
    val scope = rememberCoroutineScope()
    val lifecycleOwner = LocalLifecycleOwner.current
    val configuration = androidx.compose.ui.platform.LocalConfiguration.current
    val screenHeight = configuration.screenHeightDp.dp
    // 根据屏幕高度计算最大高度，用于限制弹窗最大高度
    // 小屏幕（< 600dp）：75%，中等屏幕（600-800dp）：70%，大屏幕（> 800dp）：65%
    val maxSheetHeight = when {
        screenHeight.value < 600 -> screenHeight * 0.75f
        screenHeight.value <= 800 -> screenHeight * 0.7f
        else -> screenHeight * 0.65f
    }
    var showCommentModal by remember { mutableStateOf(false) }
    var sheetState = rememberModalBottomSheetState(
        skipPartiallyExpanded = true
    )
    
    // 确保弹窗从下往上展开
    LaunchedEffect(showCommentModal) {
        if (showCommentModal) {
            sheetState.expand()
        } else {
            sheetState.hide()
        }
    }
    // 使用 key 确保每个视频的 ExoPlayer 完全独立，避免状态残留
    val exoPlayer = remember(videoUrl) {
        ExoPlayer.Builder(context).build().apply {
            // 创建带有认证头的数据源
            val httpDataSourceFactory = DefaultHttpDataSource.Factory()
                .setUserAgent(Util.getUserAgent(context, context.packageName))
                .setDefaultRequestProperties(
                    mapOf(
                        "Authorization" to "Bearer ${com.aiosman.ravenow.AppStore.token ?: ""}",
                        "DEVICE-OS" to "Android"
                    )
                )
            
            val dataSourceFactory = DefaultDataSourceFactory(context, httpDataSourceFactory)
            val source = ProgressiveMediaSource.Factory(dataSourceFactory)
                .createMediaSource(MediaItem.fromUri(Uri.parse(videoUrl)))
            
            prepare(source)
            videoScalingMode = C.VIDEO_SCALING_MODE_SCALE_TO_FIT_WITH_CROPPING
            repeatMode = Player.REPEAT_MODE_ONE
        }
    }
    
    // 根据页面状态控制播放
    // 使用 remember 保存上一次的当前页面，只在页面真正切换时才重置暂停状态
    val previousCurrentPage = remember(pager) { mutableStateOf(pagerState.currentPage) }
    LaunchedEffect(pager, pagerState.currentPage, isPageVisible) {
        val isCurrentPage = pager == pagerState.currentPage && isPageVisible
        val pageChanged = previousCurrentPage.value != pagerState.currentPage
        
        if (isCurrentPage) {
            // 当前页面且页面可见
            if (pageChanged) {
                // 页面切换了（从其他页面切换到当前页面），恢复播放并重置暂停状态
                exoPlayer.playWhenReady = true
                exoPlayer.play()
                pauseIconVisibleState.value = false
                previousCurrentPage.value = pagerState.currentPage
            } else {
                // 页面未切换，保持当前的播放/暂停状态
                // 如果用户手动暂停了，不要自动恢复播放；如果正在播放，保持播放
                if (!pauseIconVisibleState.value && !exoPlayer.isPlaying) {
                    exoPlayer.playWhenReady = true
                    exoPlayer.play()
                }
            }
        } else {
            // 非当前页面或页面不可见：立即暂停并停止准备播放
            exoPlayer.playWhenReady = false
            exoPlayer.pause()
            pauseIconVisibleState.value = false
            previousCurrentPage.value = pagerState.currentPage
        }
    }
    // 视频播放器容器 - 确保每个视频页面都被正确裁剪
    Box(
        modifier = Modifier
            .fillMaxSize()
            .clip(RectangleShape)
    ) {
        var playerView by remember { mutableStateOf<PlayerView?>(null) }

        // 使用 key 强制每个视频的 PlayerView 完全独立，避免布局状态残留
        androidx.compose.runtime.key(videoUrl) {
            AndroidView(
                factory = { ctx ->
                    createVideoPlayerView(ctx, exoPlayer) { view ->
                        playerView = view
                    }
                },
                modifier = Modifier
                    .fillMaxSize()
                    .clip(RectangleShape)
                    .noRippleClickable {
                        handleVideoClick(pauseIconVisibleState, exoPlayer, scope)
                    }
            )
        }

        if (pauseIconVisibleState.value) {
            Icon(
                imageVector = Icons.Default.PlayArrow,
                contentDescription = null,
                modifier = Modifier
                    .align(Alignment.Center)
                    .size(80.dp)
            )
        }

        // Release ExoPlayer when the videoUrl changes or the composable leaves composition
        // 使用 key 后，DisposableEffect 会在 videoUrl 变化时自动触发
        DisposableEffect(videoUrl) {
            onDispose {
                try {
                    exoPlayer.release()
                    playerView?.player = null
                    playerView = null // Release the reference to the PlayerView
                } catch (e: Exception) {
                    // 忽略释放时的异常
                }
            }
        }

        DisposableEffect(lifecycleOwner) {
            val observer = LifecycleEventObserver { _, event ->
                when (event) {
                    Lifecycle.Event.ON_PAUSE -> {
                        // 应用进入后台时暂停
                        exoPlayer.playWhenReady = false
                        exoPlayer.pause()
                    }

                    Lifecycle.Event.ON_RESUME -> {
                        // 返回前台且为当前页面时恢复播放
                        if (pager == pagerState.currentPage) {
                            exoPlayer.playWhenReady = true
                            exoPlayer.play()
                        }
                    }

                    else -> {}
                }
            }
            lifecycleOwner.lifecycle.addObserver(observer)

            onDispose {
                lifecycleOwner.lifecycle.removeObserver(observer)
            }
        }


    }
    // action buttons
    Box(
        modifier = Modifier.fillMaxSize(),
        contentAlignment = Alignment.BottomEnd
    ) {
        Column(
            modifier = Modifier.padding(bottom = 72.dp, end = 12.dp),
            horizontalAlignment = Alignment.CenterHorizontally
        ) {
            if (moment != null) {
                // 使用 key 确保状态变化时重新组合，包含所有可能变化的状态以避免不必要的重组
                // 移除 key，让 Compose 自动处理重组，避免头像闪烁
                UserAvatar(
                    avatarUrl = moment.avatar,
                    onClick = { onAvatarClick?.invoke(moment) }
                )
                VideoBtn(
                    icon = if (moment.liked) R.drawable.rider_pro_moment_liked else R.drawable.rider_pro_moment_like,
                    text = formatCount(moment.likeCount),
                    isActive = moment.liked,
                    onClick = { onLikeClick?.invoke(moment) }
                )
                VideoBtn(
                    icon = R.mipmap.icon_comment,
                    text = formatCount(moment.commentCount),
                    onClick = {
                        showCommentModal = true
                        onCommentClick?.invoke(moment)
                    }
                )
                VideoBtn(
                    icon = if (moment.isFavorite) R.mipmap.icon_variant_2 else R.mipmap.icon_collect,
                    text = formatCount(moment.favoriteCount),
                    isActive = false, // 收藏后不使用红色滤镜，保持图标原本颜色
                    keepOriginalColor = moment.isFavorite, // 收藏后保持原始颜色
                    onClick = { onFavoriteClick?.invoke(moment) }
                )
                VideoBtn(
                    icon = R.mipmap.icon_share,
                    text = formatCount(moment.shareCount),
                    onClick = { onShareClick?.invoke(moment) }
                )
            } else {
                UserAvatar()
                VideoBtn(icon = R.drawable.rider_pro_moment_like, text = "0")
                VideoBtn(
                    icon = R.mipmap.icon_comment,
                    text = "0",
                    onClick = {
                        showCommentModal = true
                    }
                )
                VideoBtn(icon = R.mipmap.icon_collect, text = "0")
                VideoBtn(icon = R.mipmap.icon_share, text = "0")
            }
        }
    }
    // info
    if (moment != null) {
        Box(
            modifier = Modifier.fillMaxSize(),
            contentAlignment = Alignment.BottomStart
        ) {
            Column(modifier = Modifier.padding(start = 16.dp, bottom = 16.dp)) {
                if (moment.location.isNotEmpty() && moment.location != "Worldwide") {
                    Row(
                        modifier = Modifier
                            .padding(bottom = 8.dp)
                            .background(color = Color.Gray),
                        verticalAlignment = Alignment.CenterVertically,
                        horizontalArrangement = Arrangement.Start,
                    ) {
                        Image(
                            modifier = Modifier
                                .size(20.dp)
                                .padding(start = 4.dp, end = 6.dp),
                            painter = painterResource(id = R.drawable.rider_pro_video_location),
                            contentDescription = ""
                        )
                        Text(
                            modifier = Modifier.padding(end = 4.dp),
                            text = moment.location,
                            fontSize = 12.sp,
                            color = Color.White,
                            style = TextStyle(fontWeight = FontWeight.Bold)
                        )
                    }
                }
                Text(
                    text = "@${moment.nickname}",
                    fontSize = 16.sp,
                    color = Color.White,
                    style = TextStyle(fontWeight = FontWeight.Bold)
                )
                if (!moment.momentTextContent.isNullOrEmpty()) {
                    Text(
                        modifier = Modifier
                            .fillMaxWidth()
                            .padding(top = 4.dp),
                        text = com.aiosman.ravenow.utils.Utils.unescapeHtml(moment.momentTextContent),
                        fontSize = 16.sp,
                        color = Color.White,
                        style = TextStyle(fontWeight = FontWeight.Bold),
                        overflow = TextOverflow.Ellipsis,
                        maxLines = 2
                    )
                }
            }
        }
    }

    if (showCommentModal && moment != null) {
        val AppColors = LocalAppTheme.current
        ModalBottomSheet(
            onDismissRequest = { 
                scope.launch {
                    sheetState.hide()
                }
                showCommentModal = false
            },
            containerColor = AppColors.background,
            sheetState = sheetState,
            shape = RoundedCornerShape(topStart = 16.dp, topEnd = 16.dp)
        ) {
            Box(
                modifier = Modifier
                    .fillMaxWidth()
                    .heightIn(max = maxSheetHeight)
            ) {
                CommentModalContent(
                    postId = moment.id,
                    commentCount = moment.commentCount,
                    onCommentAdded = {
                        onCommentAdded?.invoke(moment)
                    }
                )
            }
        }
    }
}

@Composable
fun UserAvatar(
    avatarUrl: String? = null,
    onClick: (() -> Unit)? = null
) {
    // 使用 key 确保当 avatarUrl 不变时不会重新创建组件，避免闪烁
    androidx.compose.runtime.key(avatarUrl) {
        Box(
            modifier = Modifier
                .padding(bottom = 16.dp)
                .size(40.dp)
                .border(width = 3.dp, color = Color.White, shape = RoundedCornerShape(40.dp))
                .clip(RoundedCornerShape(40.dp))
                .then(
                    if (onClick != null) {
                        Modifier.noRippleClickable { onClick() }
                    } else {
                        Modifier
                    }
                )
        ) {
            if (avatarUrl != null && avatarUrl.isNotEmpty()) {
                CustomAsyncImage(
                    imageUrl = avatarUrl,
                    contentDescription = "用户头像",
                    modifier = Modifier.fillMaxSize(),
                    defaultRes = R.drawable.default_avatar,
                    showShimmer = false // 禁用 shimmer 效果，避免闪烁
                )
            } else {
                Image(
                    painter = painterResource(id = R.drawable.default_avatar),
                    contentDescription = "用户头像"
                )
            }
        }
    }
}

// 格式化数字显示
private fun formatCount(count: Int): String {
    return when {
        count >= 1_000_000 -> String.format("%.1fM", count / 1_000_000.0)
        count >= 1_000 -> String.format("%.1fK", count / 1_000.0)
        else -> count.toString()
    }
}

@Composable
fun VideoBtn(
    @DrawableRes icon: Int, 
    text: String, 
    onClick: (() -> Unit)? = null,
    isActive: Boolean = false,
    keepOriginalColor: Boolean = false // 是否保持原始颜色（不应用白色滤镜）
) {
    Column(
        modifier = Modifier
            .padding(bottom = 16.dp)
            .noRippleClickable {
                onClick?.invoke()
            },
        horizontalAlignment = Alignment.CenterHorizontally,
    ) {
        Image(
            modifier = Modifier.size(30.dp),
            painter = painterResource(id = icon),
            contentDescription = "",
            contentScale = ContentScale.FillBounds, // 填满容器，让图标看起来更大
            colorFilter = when {
                isActive -> ColorFilter.tint(ActiveIconColor)
                keepOriginalColor -> null // 保持原始颜色
                else -> ColorFilter.tint(Color.White) // 未激活状态时图标为白色
            }
        )
        Text(
            text = text,
            fontSize = 11.sp,
            color = Color.White,
            style = TextStyle(fontWeight = FontWeight.Bold)
        )
    }
}









