package com.example.kmptpc_compose_sample

import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.safeContentPadding
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.material.Button
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateMapOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.ExperimentalComposeUiApi
import androidx.compose.ui.backhandler.BackHandler
import com.example.kmptpc_compose_sample.navigation.ComponentDemo
import com.example.kmptpc_compose_sample.navigation.ComposeGroup
import com.example.kmptpc_compose_sample.navigation.componentDemos
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.composable
import androidx.navigation.compose.rememberNavController
import androidx.navigation.toRoute
import kotlinx.serialization.Serializable

@Serializable
private data class HomeRoute(val unused: String = "home")

@Serializable
private data class DetailRoute(val demoId: String)

@Composable
internal fun App() {
    MaterialTheme {
        val navController = rememberNavController()

        // 首页状态提升：保留在 App 层，以便从详情返回时恢复列表/搜索/展开状态
        val listState = rememberLazyListState()
        var searchQuery by remember { mutableStateOf("") }
        val expandedGroups = remember {
            mutableStateMapOf<ComposeGroup, Boolean>().apply {
                ComposeGroup.entries.forEach { put(it, true) }
            }
        }
//        Button(
//            onClick = {
//                test1()
//            },
//            content = { Text("11") }
//        )
        Column(
            modifier = Modifier
                .safeContentPadding()
                .fillMaxSize(),
            horizontalAlignment = Alignment.CenterHorizontally,
        ) {
            NavHost(
                navController = navController,
                startDestination = HomeRoute(),
                modifier = Modifier.fillMaxSize(),
            ) {
                composable<HomeRoute> {
                    HomeScreen(
                        onSelect = { demo ->
                            navController.navigate(DetailRoute(demoId = demo.id))
                        },
                        listState = listState,
                        searchQuery = searchQuery,
                        onSearchChange = { searchQuery = it },
                        expandedGroups = expandedGroups,
                    )
                }
                composable<DetailRoute> { backStackEntry ->
                    val route = backStackEntry.toRoute<DetailRoute>()
                    val demo: ComponentDemo? = componentDemos.find { it.id == route.demoId }
                    if (demo == null) {
                        navController.popBackStack()
                        return@composable
                    }
                    DetailScreenWithBack(
                        demo = demo,
                        onBack = { navController.popBackStack() },
                    )
                }
            }
        }
    }
}

/**
 * 详情页：包装 [DemoScreen]，并注册 [BackHandler]。
 * 与 NavHost 配合后，可得到：
 * - 预测性返回（NavHost 内部 PredictiveBackHandler）
 * - 边缘返回手势（OHOS 等 actual 的 limitBackGestureSwipeEdge）
 * - 系统返回键/Back：由此 BackHandler 处理
 */
@OptIn(ExperimentalComposeUiApi::class)
@Composable
private fun DetailScreenWithBack(
    demo: ComponentDemo,
    onBack: () -> Unit,
) {
    BackHandler(enabled = true, onBack = onBack)
    DemoScreen(demo = demo, onBack = onBack)
}
