package com.dong.demo013.navigation

enum class ComposeGroup {
    Ui, Foundation, Material, Benchmark, Platform
}

data class ComponentDemo(
    val id: String,
    val title: String,
    val group: ComposeGroup
)

val componentDemos: List<ComponentDemo> = listOf(
    // Log
    ComponentDemo("log_test_demo", "日志测试演示", ComposeGroup.Foundation),
    ComponentDemo("log_fault_demo", "fault日志测试", ComposeGroup.Foundation),

)

val groupTitles: Map<ComposeGroup, String> = mapOf(
    ComposeGroup.Ui to "compose.ui",
    ComposeGroup.Foundation to "compose.foundation",
    ComposeGroup.Material to "compose.material",
    ComposeGroup.Platform to "Platform",
)

fun demosByGroup(): Map<ComposeGroup, List<ComponentDemo>> {
    val standardDemos = ComposeGroup.entries.filter { it != ComposeGroup.Platform }
        .associateWith { g -> componentDemos.filter { it.group == g } }
        .toMutableMap()

    val platformDemos = com.dong.demo013.getPlatformDemoList().map {
        ComponentDemo(
            id = it.id,
            title = it.title,
            group = ComposeGroup.Platform
        )
    }

    if (platformDemos.isNotEmpty()) {
        standardDemos[ComposeGroup.Platform] = platformDemos
    }
    
    return standardDemos
}

fun demosJson(): String = buildString {
    append('[')
    componentDemos.forEachIndexed { index, demo ->
        if (index > 0) append(',')
        append("{\"id\":\"")
        append(jsonEscape(demo.id))
        append("\",\"title\":\"")
        append(jsonEscape(demo.title))
        append("\",\"group\":\"")
        append(demo.group.name)
        append("\"}")
    }
    append(']')
}

fun groupTitlesJson(): String = buildString {
    append('{')
    ComposeGroup.entries.forEachIndexed { index, group ->
        if (index > 0) append(',')
        append('"')
        append(group.name)
        append("\":\"")
        append(jsonEscape(groupTitles[group] ?: group.name))
        append('"')
    }
    append('}')
}

private fun jsonEscape(input: String): String = buildString(input.length) {
    input.forEach { ch ->
        when (ch) {
            '\\' -> append("\\\\")
            '"' -> append("\\\"")
            '\n' -> append("\\n")
            '\r' -> append("\\r")
            '\t' -> append("\\t")
            else -> append(ch)
        }
    }
}

sealed interface Page {
    data object Home : Page
    data class Detail(val demo: ComponentDemo) : Page
}
