package tv.tivilux.nativeplayer.ui.screens import androidx.compose.foundation.background import androidx.compose.foundation.border import androidx.compose.foundation.clickable import androidx.compose.foundation.focusable import androidx.compose.foundation.layout.* import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.grid.GridCells import androidx.compose.foundation.lazy.grid.LazyVerticalGrid import androidx.compose.foundation.lazy.grid.items import androidx.compose.foundation.lazy.items import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material3.DropdownMenu import androidx.compose.material3.DropdownMenuItem import androidx.compose.material3.OutlinedTextField import androidx.compose.material3.Button import androidx.compose.material3.TextButton import androidx.compose.material3.OutlinedButton import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import kotlinx.coroutines.delay import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.focus.onFocusChanged import androidx.compose.ui.graphics.Brush import androidx.compose.ui.graphics.Color import androidx.compose.ui.layout.ContentScale 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 coil.compose.AsyncImage import tv.tivilux.nativeplayer.model.Category import tv.tivilux.nativeplayer.model.MediaEntry import tv.tivilux.nativeplayer.ui.components.PosterCard import tv.tivilux.nativeplayer.ui.theme.LuxGold import tv.tivilux.nativeplayer.ui.theme.LuxLine import tv.tivilux.nativeplayer.ui.theme.LuxMuted import tv.tivilux.nativeplayer.ui.theme.LuxPanel import tv.tivilux.nativeplayer.ui.theme.LuxText @Composable fun CatalogScreen( title: String, eyebrow: String, categories: List, selectedCategory: String?, entries: List, searchEntries: List, refreshStatus: String, onRefresh: () -> Unit, onCategory: (String?) -> Unit, onEntry: (MediaEntry) -> Unit, ) { val context = LocalContext.current val sortPrefs = remember(context) { context.getSharedPreferences("tivilux_catalog_sort", android.content.Context.MODE_PRIVATE) } val preferenceKey = remember(title) { "sort_${title.lowercase(java.util.Locale.ROOT)}" } var sortMode by remember(preferenceKey) { mutableStateOf(sortPrefs.getString(preferenceKey, "recent") ?: "recent") } var sortOpen by remember { mutableStateOf(false) } var searchOpen by rememberSaveable(title) { mutableStateOf(false) } var searchText by rememberSaveable(title) { mutableStateOf("") } val searching = searchText.isNotBlank() var matchedEntries by remember { mutableStateOf>(emptyList()) } LaunchedEffect(searchEntries, searchText) { matchedEntries = if (!searching) emptyList() else withContext(Dispatchers.Default) { val query = searchText.trim() searchEntries.filter { it.name.contains(query, ignoreCase = true) } } } val displayEntries = if (searching) matchedEntries else entries // Sort the currently visible catalog in a single cancellable background pass. // This prevents an old category/search sort from overwriting the new selection. var sortedEntries by remember { mutableStateOf>(emptyList()) } LaunchedEffect(displayEntries, sortMode) { sortedEntries = withContext(Dispatchers.Default) { val rows = displayEntries.map { entry -> CatalogSortRow(entry, entry.name.lowercase(java.util.Locale.ROOT), extractCatalogYear(entry.year, entry.name), parseCatalogRating(entry.rating)) } val sorted = when (sortMode) { "az" -> rows.sortedBy { it.name } "za" -> rows.sortedByDescending { it.name } "yearnew" -> rows.sortedWith(compareByDescending { it.year }.thenBy { it.name }) "yearold" -> rows.sortedWith(compareBy { if (it.year > 0) it.year else Int.MAX_VALUE }.thenBy { it.name }) "rating" -> rows.sortedWith(compareByDescending { it.rating }.thenBy { it.name }) else -> rows.sortedWith(compareByDescending { it.entry.addedEpoch }.thenBy { it.name }) } sorted.map { it.entry } } } var highlighted by remember(sortedEntries) { mutableStateOf(sortedEntries.firstOrNull()) } var heroEntry by remember(sortedEntries) { mutableStateOf(sortedEntries.firstOrNull()) } // Rapid D-pad movement used to make the large hero artwork churn on every focus hop. // A tiny debounce keeps navigation immediate while only loading artwork for the title // the viewer actually pauses on. LaunchedEffect(highlighted?.id) { delay(90) heroEntry = highlighted } Row(Modifier.fillMaxSize().padding(16.dp), horizontalArrangement = Arrangement.spacedBy(14.dp)) { Column( Modifier.width(176.dp).fillMaxHeight() .background(LuxPanel, RoundedCornerShape(16.dp)) .border(1.dp, LuxLine, RoundedCornerShape(16.dp)) .padding(9.dp) ) { Text("$eyebrow GROUPS", color = LuxGold, fontSize = 9.sp, fontWeight = FontWeight.Bold, letterSpacing = 1.3.sp, modifier = Modifier.padding(7.dp)) CatalogCategoryRow("All", selectedCategory == null) { onCategory(null) } LazyColumn { items(categories, key = { it.id }) { c -> CatalogCategoryRow(c.name, selectedCategory == c.id) { onCategory(c.id) } } } } Column(Modifier.weight(1f).fillMaxHeight()) { CatalogHero(title, eyebrow, heroEntry, displayEntries.size) Spacer(Modifier.height(5.dp)) Row(Modifier.fillMaxWidth().height(40.dp), horizontalArrangement = Arrangement.spacedBy(7.dp), verticalAlignment = Alignment.CenterVertically) { if (searchOpen || searchText.isNotBlank()) { OutlinedTextField( value = searchText, onValueChange = { searchText = it }, placeholder = { Text("Search all $title", fontSize = 12.sp) }, singleLine = true, modifier = Modifier.weight(1f).height(52.dp), ) TextButton(onClick = { searchText = ""; searchOpen = false }) { Text("Close", fontSize = 11.sp) } } else { OutlinedButton(onClick = { searchOpen = true }, modifier = Modifier.weight(1f)) { Text("⌕ Search $title", fontSize = 11.sp) } } OutlinedButton(onClick = onRefresh, enabled = !refreshStatus.startsWith("Updating")) { Text(if (refreshStatus.startsWith("Updating")) "Refreshing…" else "↻ Refresh", fontSize = 11.sp) } Box { var sortFocused by remember { mutableStateOf(false) } Box(Modifier .background(if (sortFocused || sortOpen) Color(0x22E8C38B) else LuxPanel, RoundedCornerShape(8.dp)) .border(1.dp, if (sortFocused || sortOpen) LuxGold else LuxLine, RoundedCornerShape(8.dp)) .onFocusChanged { sortFocused = it.isFocused } .clickable { sortOpen = true } .padding(horizontal = 10.dp, vertical = 9.dp) ) { Text("${catalogSortOptions.firstOrNull { it.first == sortMode }?.second ?: "Recently Added"} ▾", color = LuxText, fontSize = 10.sp) } DropdownMenu(expanded = sortOpen, onDismissRequest = { sortOpen = false }, modifier = Modifier.background(LuxPanel)) { catalogSortOptions.forEach { (value, label) -> DropdownMenuItem( text = { Text((if (sortMode == value) "✓ " else " ") + label, color = LuxText, fontSize = 12.sp) }, onClick = { sortOpen = false sortMode = value sortPrefs.edit().putString(preferenceKey, value).apply() } ) } } } } if (refreshStatus != "Ready") Text(refreshStatus, color = LuxMuted, fontSize = 10.sp, maxLines = 1) Spacer(Modifier.height(5.dp)) if (displayEntries.isEmpty()) { Text( if (searching) "No matches found in the cached $title library. Try Refresh Library." else if (selectedCategory == null) "Loading the complete provider $title library…" else "Nothing returned for this category.", color = LuxMuted, modifier = Modifier.padding(20.dp), ) } else { LazyVerticalGrid( columns = GridCells.Adaptive(116.dp), horizontalArrangement = Arrangement.spacedBy(8.dp), verticalArrangement = Arrangement.spacedBy(7.dp), ) { items(sortedEntries, key = { "${it.type}:${it.id}" }) { entry -> CompactCatalogPoster(entry, { onEntry(entry) }, { highlighted = entry }) } } } } } } @Composable private fun CatalogHero(title: String, eyebrow: String, entry: MediaEntry?, count: Int) { Box( Modifier.fillMaxWidth().height(82.dp) .background( Brush.horizontalGradient(listOf(Color(0xFF18222B), Color(0xFF10161D))), RoundedCornerShape(16.dp), ) .border(1.dp, LuxLine, RoundedCornerShape(16.dp)) ) { if (entry?.image?.isNotBlank() == true) { AsyncImage( model = entry.image, contentDescription = entry.name, modifier = Modifier.align(Alignment.CenterEnd).width(170.dp).fillMaxHeight(), contentScale = ContentScale.Crop, alpha = .38f, ) Box( Modifier.align(Alignment.CenterEnd).width(200.dp).fillMaxHeight().background( Brush.horizontalGradient(listOf(Color(0xFF121920), Color.Transparent)) ) ) } Column(Modifier.fillMaxHeight().padding(horizontal = 12.dp, vertical = 5.dp), verticalArrangement = Arrangement.Center) { Row(Modifier.fillMaxWidth(.75f), horizontalArrangement = Arrangement.SpaceBetween) { Text(eyebrow, color = LuxGold, fontSize = 9.sp, fontWeight = FontWeight.Bold, letterSpacing = 1.4.sp) Text("$count titles", color = LuxMuted, fontSize = 9.sp) } Text(entry?.name ?: title, color = LuxText, fontSize = 19.sp, fontWeight = FontWeight.SemiBold, maxLines = 1, overflow = TextOverflow.Ellipsis) val meta = entry?.let { listOf(it.year, it.rating.takeIf { r -> r.isNotBlank() }?.let { r -> "★ $r" }.orEmpty()).filter { value -> value.isNotBlank() }.joinToString(" • ") }.orEmpty() if (meta.isNotBlank()) Text(meta, color = LuxGold, fontSize = 10.sp) if (!entry?.plot.isNullOrBlank()) { Text(entry?.plot.orEmpty(), color = LuxMuted, fontSize = 10.sp, maxLines = 1, overflow = TextOverflow.Ellipsis, modifier = Modifier.fillMaxWidth(.68f)) } else { Text("Browse $title. Press OK on a title for details.", color = LuxMuted, fontSize = 10.sp, modifier = Modifier.padding(top = 5.dp)) } } } } @Composable private fun CatalogCategoryRow(name: String, selected: Boolean, onClick: () -> Unit) { var focused by remember { mutableStateOf(false) } Box( Modifier.fillMaxWidth() .background(if (selected || focused) Color(0x22E8C38B) else Color.Transparent, RoundedCornerShape(9.dp)) .border(1.dp, if (focused) LuxGold else Color.Transparent, RoundedCornerShape(9.dp)) .onFocusChanged { focused = it.isFocused } .focusable() .clickable(onClick = onClick) .padding(horizontal = 10.dp, vertical = 9.dp) ) { Text(name, color = if (selected || focused) LuxText else LuxMuted, fontSize = 11.sp, maxLines = 1, overflow = TextOverflow.Ellipsis) } } private val catalogSortOptions = listOf( "recent" to "Recently Added", "az" to "Title: A–Z", "za" to "Title: Z–A", "yearnew" to "Year: Newest First", "yearold" to "Year: Oldest First", "rating" to "Highest Rated", ) private val catalogYearPattern = Regex("(?:19|20)\\d{2}") private val catalogTitleYearPattern = Regex("\\((?:19|20)\\d{2}\\)") private fun extractCatalogYear(year: String, name: String): Int { val fromMetadata = catalogYearPattern.find(year)?.value?.toIntOrNull() val fromTitle = catalogTitleYearPattern.find(name)?.value?.trim('(', ')')?.toIntOrNull() return fromMetadata ?: fromTitle ?: 0 } private data class CatalogSortRow(val entry: MediaEntry, val name: String, val year: Int, val rating: Double) private fun parseCatalogRating(raw: String): Double = Regex("[0-9]+(?:\\.[0-9]+)?").find(raw)?.value?.toDoubleOrNull() ?: -1.0 @Composable private fun CompactCatalogPoster(entry: MediaEntry, onClick: () -> Unit, onFocus: () -> Unit) { var focused by remember { mutableStateOf(false) } Column( Modifier.fillMaxWidth() .background(if (focused) Color(0xFF26323D) else LuxPanel, RoundedCornerShape(9.dp)) .border(if (focused) 2.dp else 1.dp, if (focused) LuxGold else LuxLine, RoundedCornerShape(9.dp)) .onFocusChanged { focused = it.isFocused; if (it.isFocused) onFocus() } .focusable().clickable(onClick = onClick) ) { AsyncImage( model = entry.image.takeIf { it.isNotBlank() }, contentDescription = entry.name, modifier = Modifier.fillMaxWidth().height(110.dp), contentScale = ContentScale.Crop, ) Text(entry.name, color = LuxText, fontSize = 10.sp, maxLines = 1, overflow = TextOverflow.Ellipsis, modifier = Modifier.padding(horizontal = 5.dp, vertical = 4.dp)) } }