package tv.tivilux.nativeplayer.ui.screens import androidx.activity.compose.BackHandler 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.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxHeight import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.width import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.itemsIndexed import androidx.compose.foundation.lazy.rememberLazyListState import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.DisposableEffect 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 androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.focus.FocusRequester import androidx.compose.ui.focus.focusRequester import androidx.compose.ui.focus.onFocusChanged import androidx.compose.ui.graphics.Color import androidx.compose.ui.input.key.Key import androidx.compose.ui.input.key.KeyEventType import androidx.compose.ui.input.key.key import androidx.compose.ui.input.key.onPreviewKeyEvent import androidx.compose.ui.input.key.type 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.window.Dialog import androidx.lifecycle.Lifecycle import androidx.lifecycle.LifecycleEventObserver import androidx.lifecycle.compose.LocalLifecycleOwner import tv.tivilux.nativeplayer.model.Category import tv.tivilux.nativeplayer.model.MediaEntry import tv.tivilux.nativeplayer.ui.components.VideoSurface import tv.tivilux.nativeplayer.ui.components.rememberTiviLuxPlayer 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.LuxPanel2 import tv.tivilux.nativeplayer.ui.theme.LuxText /** * Four-up Live TV MultiView for Android TV remotes. * * The selected tile owns audio; the other tiles remain muted. This avoids four audio tracks * playing at once while still keeping all active video feeds live. Short-OK opens the channel * picker for the selected tile; long-OK expands that tile to the normal fullscreen player. */ @Composable fun MultiViewScreen( channels: List, categories: List, selectedCategoryId: String?, channelsForCategory: (String?) -> List, slots: List, bufferPreset: String, maxConnections: Int, streamUrlFor: (MediaEntry?) -> String?, onSetSlot: (Int, MediaEntry?) -> Unit, onPlayFullScreen: (MediaEntry) -> Unit, onBack: () -> Unit, ) { val slotLimit = if (maxConnections > 0) maxConnections.coerceIn(1, 4) else 4 var selectedSlot by remember { mutableStateOf(0) } var pickerSlot by remember { mutableStateOf(null) } var okHeld by remember { mutableStateOf(false) } var longOkTriggered by remember { mutableStateOf(false) } val focusRequester = remember { FocusRequester() } val player0 = rememberTiviLuxPlayer(bufferPreset, vodOptimized = false) val player1 = rememberTiviLuxPlayer(bufferPreset, vodOptimized = false) val player2 = rememberTiviLuxPlayer(bufferPreset, vodOptimized = false) val player3 = rememberTiviLuxPlayer(bufferPreset, vodOptimized = false) val players = remember(player0, player1, player2, player3) { listOf(player0, player1, player2, player3) } val lifecycleOwner = LocalLifecycleOwner.current DisposableEffect(lifecycleOwner, players) { val observer = LifecycleEventObserver { _, event -> if (event == Lifecycle.Event.ON_STOP) { players.forEach { it.pause() } } } lifecycleOwner.lifecycle.addObserver(observer) onDispose { lifecycleOwner.lifecycle.removeObserver(observer) } } LaunchedEffect(pickerSlot) { if (pickerSlot == null) { kotlinx.coroutines.delay(60) runCatching { focusRequester.requestFocus() } } } LaunchedEffect(selectedSlot, slots) { players.forEachIndexed { index, player -> val active = index < slotLimit && slots.getOrNull(index) != null player.volume = if (active && index == selectedSlot) 1f else 0f if (!active) { player.stop() player.clearMediaItems() } } } LaunchedEffect(okHeld, selectedSlot, slots) { if (okHeld) { kotlinx.coroutines.delay(650) if (okHeld && !longOkTriggered) { val selected = slots.getOrNull(selectedSlot) if (selected != null) { longOkTriggered = true onPlayFullScreen(selected) } } } } BackHandler(enabled = pickerSlot == null, onBack = onBack) Box( Modifier.fillMaxSize() .background(Color.Black) .focusRequester(focusRequester) .focusable() .onPreviewKeyEvent { event -> if (pickerSlot != null) return@onPreviewKeyEvent false when (event.key) { Key.DirectionLeft -> { if (event.type == KeyEventType.KeyDown && selectedSlot % 2 == 1) selectedSlot -= 1 true } Key.DirectionRight -> { if (event.type == KeyEventType.KeyDown && selectedSlot % 2 == 0 && selectedSlot + 1 < slotLimit) selectedSlot += 1 true } Key.DirectionUp -> { if (event.type == KeyEventType.KeyDown && selectedSlot >= 2) selectedSlot -= 2 true } Key.DirectionDown -> { if (event.type == KeyEventType.KeyDown && selectedSlot + 2 < slotLimit) selectedSlot += 2 true } Key.Enter, Key.DirectionCenter -> { when (event.type) { KeyEventType.KeyDown -> { if (!okHeld) { okHeld = true longOkTriggered = false } } KeyEventType.KeyUp -> { val wasLong = longOkTriggered okHeld = false longOkTriggered = false if (!wasLong) pickerSlot = selectedSlot } else -> Unit } true } Key.Back -> { if (event.type == KeyEventType.KeyDown) onBack() true } else -> false } } ) { // Presentation-only refresh: the 2x2 wall now uses the full TV canvas. // The tiny 2dp seam preserves visual separation without shrinking the video tiles. Column(Modifier.fillMaxSize(), verticalArrangement = Arrangement.spacedBy(2.dp)) { Row(Modifier.weight(1f).fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(2.dp)) { MultiViewTile( slot = 0, channel = slots[0], enabled = 0 < slotLimit, selected = selectedSlot == 0, player = player0, streamUrl = streamUrlFor(slots[0]), modifier = Modifier.weight(1f).fillMaxHeight(), ) MultiViewTile( slot = 1, channel = slots[1], enabled = 1 < slotLimit, selected = selectedSlot == 1, player = player1, streamUrl = streamUrlFor(slots[1]), modifier = Modifier.weight(1f).fillMaxHeight(), ) } Row(Modifier.weight(1f).fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(2.dp)) { MultiViewTile( slot = 2, channel = slots[2], enabled = 2 < slotLimit, selected = selectedSlot == 2, player = player2, streamUrl = streamUrlFor(slots[2]), modifier = Modifier.weight(1f).fillMaxHeight(), ) MultiViewTile( slot = 3, channel = slots[3], enabled = 3 < slotLimit, selected = selectedSlot == 3, player = player3, streamUrl = streamUrlFor(slots[3]), modifier = Modifier.weight(1f).fillMaxHeight(), ) } } Box( Modifier.align(Alignment.TopStart) .padding(8.dp) .background(Color.Black.copy(alpha = .62f), RoundedCornerShape(8.dp)) .padding(horizontal = 9.dp, vertical = 5.dp) ) { Text( "MULTIVIEW • ${slots.take(slotLimit).count { it != null }} / $slotLimit ACTIVE", color = LuxGold, fontSize = 8.sp, fontWeight = FontWeight.Bold, letterSpacing = .7.sp, ) } } pickerSlot?.let { slot -> ChannelPickerDialog( slotNumber = slot + 1, channels = channels, categories = categories, selectedCategoryId = selectedCategoryId, channelsForCategory = channelsForCategory, selected = slots.getOrNull(slot), onClear = { onSetSlot(slot, null) pickerSlot = null }, onSelect = { channel -> onSetSlot(slot, channel) selectedSlot = slot pickerSlot = null }, onDismiss = { pickerSlot = null }, ) } } @Composable private fun MultiViewTile( slot: Int, channel: MediaEntry?, enabled: Boolean, selected: Boolean, player: androidx.media3.exoplayer.ExoPlayer, streamUrl: String?, modifier: Modifier = Modifier, ) { val borderColor = when { selected -> LuxGold enabled -> LuxLine else -> LuxLine.copy(alpha = .35f) } Box( modifier.background(Color.Black) .border(if (selected) 3.dp else 1.dp, borderColor), ) { if (enabled && channel != null) { VideoSurface( url = streamUrl, modifier = Modifier.fillMaxSize(), autoPlay = true, controller = false, externalPlayer = player, ) Box( Modifier.align(Alignment.BottomStart).fillMaxWidth() .background(Color.Black.copy(alpha = .68f)) .padding(horizontal = 10.dp, vertical = 6.dp) ) { Column { Text("VIEW ${slot + 1}", color = if (selected) LuxGold else LuxMuted, fontSize = 8.sp, fontWeight = FontWeight.Bold) Text(channel.name, color = LuxText, fontSize = 12.sp, fontWeight = FontWeight.SemiBold, maxLines = 1, overflow = TextOverflow.Ellipsis) if (selected) Text("AUDIO", color = LuxGold, fontSize = 8.sp, fontWeight = FontWeight.Bold) } } } else { Column( Modifier.align(Alignment.Center), horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.spacedBy(7.dp), ) { Text("VIEW ${slot + 1}", color = if (selected) LuxGold else LuxMuted, fontSize = 9.sp, fontWeight = FontWeight.Bold) Text( if (enabled) "Press OK to add a channel" else "Unavailable on this provider plan", color = if (enabled) LuxText else LuxMuted, fontSize = 12.sp, ) } } } } @Composable private fun ChannelPickerDialog( slotNumber: Int, channels: List, categories: List, selectedCategoryId: String?, channelsForCategory: (String?) -> List, selected: MediaEntry?, onClear: () -> Unit, onSelect: (MediaEntry) -> Unit, onDismiss: () -> Unit, ) { var activeCategoryId by remember(slotNumber) { mutableStateOf(null) } val categoryFocus = remember { FocusRequester() } val channelFocus = remember { FocusRequester() } val categoryListState = rememberLazyListState() val channelListState = rememberLazyListState() val categoryCounts = remember(channels) { channels.groupingBy { it.categoryId }.eachCount() } val preferredCategoryId = selected?.categoryId?.takeIf { id -> categories.any { it.id == id } } ?: selectedCategoryId?.takeIf { id -> categories.any { it.id == id } } val preferredCategoryIndex = categories.indexOfFirst { it.id == preferredCategoryId } .takeIf { it >= 0 } ?: 0 val activeCategory = activeCategoryId?.let { id -> categories.firstOrNull { it.id == id } } val categoryChannels = if (activeCategoryId == null) emptyList() else channelsForCategory(activeCategoryId) val selectedChannelIndex = categoryChannels.indexOfFirst { it.id == selected?.id } .takeIf { it >= 0 } ?: 0 LaunchedEffect(activeCategoryId, categories.size, categoryChannels.size, selected?.id) { if (activeCategoryId == null && categories.isNotEmpty()) { runCatching { categoryListState.scrollToItem(preferredCategoryIndex) } kotlinx.coroutines.delay(40) runCatching { categoryFocus.requestFocus() } } else if (activeCategoryId != null && categoryChannels.isNotEmpty()) { runCatching { channelListState.scrollToItem(selectedChannelIndex) } kotlinx.coroutines.delay(40) runCatching { channelFocus.requestFocus() } } } BackHandler(enabled = activeCategoryId != null) { activeCategoryId = null } Dialog(onDismissRequest = onDismiss) { Column( Modifier.width(720.dp).height(520.dp) .background(Color(0xFF10161D), RoundedCornerShape(18.dp)) .border(1.dp, LuxGold.copy(alpha = .45f), RoundedCornerShape(18.dp)) .padding(16.dp), verticalArrangement = Arrangement.spacedBy(10.dp), ) { Text("MULTIVIEW • VIEW $slotNumber", color = LuxGold, fontSize = 9.sp, fontWeight = FontWeight.Bold, letterSpacing = 1.2.sp) if (activeCategoryId == null) { Text("Choose a Live TV category", color = LuxText, fontSize = 23.sp, fontWeight = FontWeight.SemiBold) Text("${categories.size} groups • ${channels.size} available channels", color = LuxMuted, fontSize = 10.sp) if (selected != null) { MultiViewPickerRow( label = "Clear this tile", sublabel = selected.name, selected = false, onClick = onClear, ) } if (categories.isEmpty()) { Text( "No Live TV groups are available for this provider.", color = LuxMuted, fontSize = 12.sp, modifier = Modifier.padding(vertical = 16.dp), ) } else { LazyColumn( Modifier.fillMaxWidth().weight(1f), state = categoryListState, verticalArrangement = Arrangement.spacedBy(6.dp), contentPadding = PaddingValues(bottom = 8.dp), ) { itemsIndexed(categories, key = { _, category -> category.id }) { index, category -> val count = categoryCounts[category.id] ?: channelsForCategory(category.id).size MultiViewPickerRow( label = category.name, sublabel = "$count channels", selected = category.id == preferredCategoryId, modifier = if (index == preferredCategoryIndex) Modifier.focusRequester(categoryFocus) else Modifier, onClick = { activeCategoryId = category.id }, ) } } } } else { Text(activeCategory?.name ?: "Live TV", color = LuxText, fontSize = 23.sp, fontWeight = FontWeight.SemiBold) Text("${categoryChannels.size} channels • BACK returns to categories", color = LuxMuted, fontSize = 10.sp) MultiViewPickerRow( label = "← Back to categories", sublabel = "Choose another Live TV group", selected = false, onClick = { activeCategoryId = null }, ) if (selected != null) { MultiViewPickerRow( label = "Clear this tile", sublabel = selected.name, selected = false, onClick = onClear, ) } LazyColumn( Modifier.fillMaxWidth().weight(1f), state = channelListState, verticalArrangement = Arrangement.spacedBy(6.dp), contentPadding = PaddingValues(bottom = 8.dp), ) { itemsIndexed(categoryChannels, key = { index, channel -> "${channel.id}:$index" }) { index, channel -> MultiViewPickerRow( label = channel.name, sublabel = if (channel.number > 0) "CH ${channel.number}" else (activeCategory?.name ?: "Live TV"), selected = channel.id == selected?.id, modifier = if (index == selectedChannelIndex) Modifier.focusRequester(channelFocus) else Modifier, onClick = { onSelect(channel) }, ) } } } } } } @Composable private fun MultiViewPickerRow( label: String, sublabel: String, selected: Boolean, modifier: Modifier = Modifier, onClick: () -> Unit, ) { var focused by remember { mutableStateOf(false) } Row( modifier.fillMaxWidth() .background(if (focused || selected) LuxPanel2 else LuxPanel, RoundedCornerShape(10.dp)) .border(1.dp, if (focused) LuxGold else LuxLine, RoundedCornerShape(10.dp)) .onFocusChanged { focused = it.isFocused } .focusable() .clickable(onClick = onClick) .padding(horizontal = 12.dp, vertical = 10.dp), verticalAlignment = Alignment.CenterVertically, ) { Box( Modifier.size(8.dp).background(if (selected) LuxGold else Color.Transparent, RoundedCornerShape(50)) .border(1.dp, LuxGold.copy(alpha = .6f), RoundedCornerShape(50)) ) Spacer(Modifier.width(10.dp)) Column(Modifier.weight(1f)) { Text(label, color = LuxText, fontSize = 12.sp, fontWeight = FontWeight.SemiBold, maxLines = 1, overflow = TextOverflow.Ellipsis) if (sublabel.isNotBlank()) Text(sublabel, color = LuxMuted, fontSize = 9.sp, maxLines = 1, overflow = TextOverflow.Ellipsis) } } }