package mg.dot.feufaro.data

import feufaro.composeapp.generated.resources.Res
import org.jetbrains.compose.resources.ExperimentalResourceApi

data class DrawerItem(
    val id: Int,
    val title: String,
    val contentTitle: String,
    val path: String
)

@OptIn(ExperimentalResourceApi::class)
suspend fun getDynamicDrawerItems(): List<DrawerItem> {
    return try {
        val bytes = Res.readBytes("files/feuList.txt")
        val content = bytes.decodeToString()

        val lines = content.lines().filter { it.isNotBlank() }

        lines.mapIndexed { index, line ->
            val parts = line.split("|")

            val fileName = parts[0]
            val fileTitle = if (parts.size > 1) parts[1] else "Sans titre"

            DrawerItem(
                id = index + 1,
                title = fileName.removeSuffix(".txt"),
                contentTitle = fileTitle,
                path = "assets://$fileName"
            )
        }
    } catch (e: Exception) {
        println("Erreur lors du chargement : ${e.message}")
        emptyList()
    }
}

private fun extractTitle(content: String): String? {
    val regex = Regex("""\|t:([^|]+)""")
    return regex.find(content)?.groupValues?.get(1)?.trim()
}