package tv.tivilux.nativeplayer.ui.screens import androidx.compose.foundation.background import androidx.compose.foundation.clickable import androidx.compose.foundation.focusable import androidx.compose.foundation.verticalScroll import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.border import androidx.compose.foundation.layout.* import androidx.compose.foundation.lazy.LazyRow import androidx.compose.foundation.lazy.items import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.runtime.DisposableEffect import androidx.compose.material3.Text import androidx.compose.material3.CircularProgressIndicator import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.draw.clip import androidx.compose.ui.draw.scale import androidx.compose.ui.focus.FocusRequester import androidx.compose.ui.focus.focusRequester import androidx.compose.ui.focus.onFocusChanged import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Brush 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.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 androidx.compose.ui.window.Dialog import coil.compose.AsyncImage import tv.tivilux.nativeplayer.AppScreen import tv.tivilux.nativeplayer.model.HouseholdProfile import tv.tivilux.nativeplayer.model.MediaEntry import tv.tivilux.nativeplayer.model.PlaybackProgress import tv.tivilux.nativeplayer.model.SessionInfo import tv.tivilux.nativeplayer.ui.components.LuxButton import tv.tivilux.nativeplayer.ui.components.LuxCard import tv.tivilux.nativeplayer.ui.theme.LuxGold import tv.tivilux.nativeplayer.ui.theme.LuxGreen import tv.tivilux.nativeplayer.ui.theme.LuxLine import tv.tivilux.nativeplayer.ui.theme.LuxMuted import tv.tivilux.nativeplayer.ui.theme.LuxPanel2 import tv.tivilux.nativeplayer.ui.theme.LuxText import kotlinx.coroutines.Job import kotlinx.coroutines.delay import kotlinx.coroutines.launch @Composable fun HomeScreen( session: SessionInfo?, activeProfile: HouseholdProfile, profilesCount: Int, lastPlayed: MediaEntry?, continueWatching: List, sportsLiveCount: Int, sportsChannelCount: Int, sportsScanning: Boolean, sportsBackgroundLoading: Boolean, sportsBackgroundCategory: String, sportsBackgroundReady: Boolean, onNavigate: (AppScreen) -> Unit, onResume: (MediaEntry) -> Unit, onContinue: (PlaybackProgress) -> Unit, onRemoveContinue: (PlaybackProgress) -> Unit, onProfiles: () -> Unit, ) { var removeCandidate by remember { mutableStateOf(null) } var continueRemoveMode by remember { mutableStateOf(false) } LaunchedEffect(continueWatching.size) { if (continueWatching.isEmpty()) continueRemoveMode = false } val phoneTouch = isPhoneTouchDevice() val phoneScrollState = rememberScrollState() BoxWithConstraints(Modifier.fillMaxSize()) { val compact = maxHeight < 650.dp val outer = if (compact) 18.dp else 26.dp val heroHeight = if (compact) 190.dp else 232.dp val tileHeight = if (compact) 82.dp else 94.dp Column( Modifier.fillMaxSize() .then(if (phoneTouch) Modifier.verticalScroll(phoneScrollState) else Modifier) .padding(outer), verticalArrangement = Arrangement.spacedBy(if (compact) 11.dp else 14.dp), ) { Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.SpaceBetween) { Column { Text("TIVILUX", color = LuxGold, fontSize = 12.sp, fontWeight = FontWeight.Black, letterSpacing = 2.2.sp) Text("Premium Television OS", color = LuxMuted, fontSize = 10.sp) } Row(horizontalArrangement = Arrangement.spacedBy(8.dp), verticalAlignment = Alignment.CenterVertically) { LuxButton("${activeProfile.name.uppercase()} • ${if (profilesCount > 1) "SWITCH" else "PROFILE"}", onProfiles) LuxButton("⚙ SETTINGS", { onNavigate(AppScreen.SETTINGS) }) } } Box( Modifier.fillMaxWidth().height(heroHeight) .background( Brush.horizontalGradient(listOf(Color(0xFF25333E), Color(0xFF121820), Color(0xFF090C11))), RoundedCornerShape(24.dp), ) .border(1.dp, LuxGold.copy(alpha = .24f), RoundedCornerShape(24.dp)) .padding(horizontal = if (compact) 24.dp else 32.dp, vertical = if (compact) 18.dp else 24.dp) ) { Column(Modifier.align(Alignment.CenterStart).fillMaxWidth(.67f)) { Row(verticalAlignment = Alignment.CenterVertically) { Box(Modifier.size(7.dp).background(LuxGreen, RoundedCornerShape(50))) Spacer(Modifier.width(7.dp)) Text("READY FOR ${activeProfile.name.uppercase()}", color = LuxGold, fontSize = 9.sp, fontWeight = FontWeight.Bold, letterSpacing = 1.2.sp) } Spacer(Modifier.height(7.dp)) Text("Your TV. Your lineup. Your progress.", color = LuxText, fontSize = if (compact) 30.sp else 38.sp, fontWeight = FontWeight.Light, lineHeight = if (compact) 34.sp else 42.sp) Spacer(Modifier.height(6.dp)) Text( "Live TV, sports, movies and series with household profiles and instant resume.", color = LuxMuted, fontSize = if (compact) 11.sp else 13.sp, ) Spacer(Modifier.height(if (compact) 10.dp else 14.dp)) Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) { LuxButton("WATCH LIVE", { onNavigate(AppScreen.LIVE) }, primary = true) if (continueWatching.isNotEmpty()) { LuxButton("CONTINUE WATCHING", { onContinue(continueWatching.first()) }) } else if (lastPlayed != null) { LuxButton("RESUME ${lastPlayed.name.take(18)}", { onResume(lastPlayed) }) } } } Column( Modifier.align(Alignment.CenterEnd).width(if (compact) 235.dp else 282.dp) .background(Color(0xA1121820), RoundedCornerShape(18.dp)) .border(1.dp, LuxLine, RoundedCornerShape(18.dp)).padding(16.dp), verticalArrangement = Arrangement.spacedBy(7.dp), ) { Text("ACCOUNT", color = LuxMuted, fontSize = 8.sp, fontWeight = FontWeight.Bold, letterSpacing = 1.1.sp) Text(session?.username.orEmpty(), color = LuxText, fontSize = 14.sp, fontWeight = FontWeight.SemiBold, maxLines = 1, overflow = TextOverflow.Ellipsis) Text("${session?.status ?: "Connected"} • Profile: ${activeProfile.name}", color = LuxGold, fontSize = 9.sp) if ((session?.maxConnections ?: 0) > 0) { Text("Connections ${session?.activeConnections}/${session?.maxConnections}", color = LuxMuted, fontSize = 9.sp) } session?.expiration?.takeIf { it.isNotBlank() && it != "0" && !it.equals("null", true) }?.let { Text("Expires ${formatExpiration(it)}", color = LuxMuted, fontSize = 9.sp) } } } if (continueWatching.isNotEmpty()) { Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.SpaceBetween) { Text("Continue Watching", color = LuxText, fontSize = if (compact) 16.sp else 19.sp, fontWeight = FontWeight.SemiBold) Text( if (continueRemoveMode) "REMOVE MODE • OK TO REMOVE • BACK WHEN DONE" else "${activeProfile.name}'s history", color = if (continueRemoveMode) LuxGold else LuxMuted, fontSize = 9.sp, fontWeight = if (continueRemoveMode) FontWeight.Bold else FontWeight.Normal, ) } LazyRow(Modifier.fillMaxWidth().height(if (compact) 112.dp else 132.dp), horizontalArrangement = Arrangement.spacedBy(9.dp)) { items(continueWatching, key = { "cw:${it.item.type}:${it.item.id}" }) { progress -> ContinueCard( progress = progress, removeMode = continueRemoveMode, onClick = { onContinue(progress) }, onLongPress = { if (continueWatching.size <= 1) { removeCandidate = progress } else { continueRemoveMode = true } }, onRemove = { onRemoveContinue(progress) }, onExitRemoveMode = { continueRemoveMode = false }, ) } } } Text("Browse", color = LuxText, fontSize = if (compact) 16.sp else 19.sp, fontWeight = FontWeight.SemiBold) Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(9.dp)) { HomeTile("LIVE TV", "Full guide + preview", Modifier.weight(1f).height(tileHeight)) { onNavigate(AppScreen.LIVE) } SportsHomeTile( subtitle = when { sportsLiveCount > 0 -> "$sportsLiveCount live • $sportsChannelCount feeds" sportsScanning -> "Scanning today's EPG" sportsChannelCount > 0 -> "$sportsChannelCount feeds ready" else -> "Games + team feeds" }, loading = sportsBackgroundLoading, loadingCategory = sportsBackgroundCategory, ready = sportsBackgroundReady, modifier = Modifier.weight(1.08f).height(tileHeight), ) { onNavigate(AppScreen.SPORTS) } HomeTile("MOVIES", "Complete VOD library", Modifier.weight(1f).height(tileHeight)) { onNavigate(AppScreen.MOVIES) } HomeTile("SERIES", "Resume + next episode", Modifier.weight(1f).height(tileHeight)) { onNavigate(AppScreen.SERIES) } HomeTile("FAVORITES", "${activeProfile.name}'s TV guide", Modifier.weight(1f).height(tileHeight)) { onNavigate(AppScreen.FAVORITES) } HomeTile("SETTINGS", "Player + guide + profiles", Modifier.weight(1f).height(tileHeight)) { onNavigate(AppScreen.SETTINGS) } } } } removeCandidate?.let { progress -> RemoveContinueWatchingDialog( progress = progress, onRemove = { onRemoveContinue(progress) removeCandidate = null }, onDismiss = { removeCandidate = null }, ) } } @Composable private fun ContinueCard( progress: PlaybackProgress, removeMode: Boolean, onClick: () -> Unit, onLongPress: () -> Unit, onRemove: () -> Unit, onExitRemoveMode: () -> Unit, ) { val item = progress.item val nextEpisode = progress.positionMs <= 0L && item.type.name == "EPISODE" var focused by remember { mutableStateOf(false) } var selectHeld by remember { mutableStateOf(false) } var longPressTriggered by remember { mutableStateOf(false) } var holdJob by remember { mutableStateOf(null) } val scope = rememberCoroutineScope() DisposableEffect(Unit) { onDispose { holdJob?.cancel() } } Box( modifier = Modifier .width(235.dp) .fillMaxHeight() .scale(if (focused) 1.008f else 1f) .clip(RoundedCornerShape(18.dp)) .background(if (focused) Color(0xFF202631) else tv.tivilux.nativeplayer.ui.theme.LuxPanel) .border(1.dp, if (focused) LuxGold else LuxLine, RoundedCornerShape(18.dp)) .onFocusChanged { focused = it.isFocused } .focusable() .onPreviewKeyEvent { event -> if (removeMode && event.key == Key.Back) { if (event.type == KeyEventType.KeyDown) onExitRemoveMode() return@onPreviewKeyEvent true } if (event.key !in setOf(Key.Enter, Key.DirectionCenter)) { return@onPreviewKeyEvent false } if (removeMode) { when (event.type) { KeyEventType.KeyDown -> true KeyEventType.KeyUp -> { val enteredRemoveModeFromThisHold = longPressTriggered selectHeld = false holdJob?.cancel() holdJob = null longPressTriggered = false if (!enteredRemoveModeFromThisHold) onRemove() true } else -> false } } else { when (event.type) { KeyEventType.KeyDown -> { if (!selectHeld) { selectHeld = true longPressTriggered = false holdJob?.cancel() holdJob = scope.launch { delay(550) if (selectHeld && !longPressTriggered) { longPressTriggered = true onLongPress() } } } true } KeyEventType.KeyUp -> { val wasLongPress = longPressTriggered selectHeld = false holdJob?.cancel() holdJob = null longPressTriggered = false if (!wasLongPress) onClick() true } else -> false } } } .clickable(onClick = { if (removeMode) onRemove() else onClick() }), ) { Row(Modifier.fillMaxSize()) { Box(Modifier.width(86.dp).fillMaxHeight().background(LuxPanel2)) { AsyncImage(item.image.takeIf { it.isNotBlank() }, item.name, Modifier.fillMaxSize(), contentScale = ContentScale.Crop) } Column(Modifier.weight(1f).padding(11.dp), verticalArrangement = Arrangement.spacedBy(4.dp)) { Text(if (nextEpisode) "NEXT EPISODE" else "CONTINUE", color = LuxGold, fontSize = 8.sp, fontWeight = FontWeight.Bold) Text(item.seriesName.ifBlank { item.name }, color = LuxText, fontSize = 12.sp, fontWeight = FontWeight.SemiBold, maxLines = 2, overflow = TextOverflow.Ellipsis) if (item.season > 0 && item.episodeNumber > 0) { Text("S${item.season} E${item.episodeNumber} • ${item.name}", color = LuxMuted, fontSize = 9.sp, maxLines = 1, overflow = TextOverflow.Ellipsis) } if (progress.durationMs > 0L && progress.positionMs > 0L) { val percent = ((progress.positionMs.toDouble() / progress.durationMs.toDouble()) * 100).toInt().coerceIn(0, 100) Text("$percent% watched", color = LuxMuted, fontSize = 8.sp) } if (focused) { Text(if (removeMode) "OK • REMOVE BACK • DONE" else "HOLD OK • OPTIONS", color = if (removeMode) LuxGold else LuxMuted, fontSize = 7.sp, maxLines = 1) } } } if (removeMode) { Box( Modifier .align(Alignment.TopEnd) .padding(7.dp) .size(25.dp) .background(Color(0xFFD84B4B), RoundedCornerShape(50)), contentAlignment = Alignment.Center, ) { Text("×", color = Color.White, fontSize = 20.sp, fontWeight = FontWeight.Bold) } } } } @Composable private fun RemoveContinueWatchingDialog( progress: PlaybackProgress, onRemove: () -> Unit, onDismiss: () -> Unit, ) { val removeFocus = remember { FocusRequester() } var selectReady by remember { mutableStateOf(false) } LaunchedEffect(Unit) { delay(80) runCatching { removeFocus.requestFocus() } } Dialog(onDismissRequest = onDismiss) { Column( Modifier .onPreviewKeyEvent { event -> if (!selectReady && event.key in setOf(Key.Enter, Key.DirectionCenter)) { if (event.type == KeyEventType.KeyUp) selectReady = true true } else { false } } .widthIn(min = 520.dp, max = 700.dp) .background(Color(0xFF111820), RoundedCornerShape(18.dp)) .border(1.dp, LuxGold.copy(alpha = .7f), RoundedCornerShape(18.dp)) .padding(22.dp), verticalArrangement = Arrangement.spacedBy(14.dp), ) { Text( "CONTINUE WATCHING", color = LuxGold, fontSize = 10.sp, fontWeight = FontWeight.Bold, letterSpacing = 1.2.sp, ) Text( "Remove from Continue Watching?", color = LuxText, fontSize = 22.sp, fontWeight = FontWeight.SemiBold, ) Text( progress.item.seriesName.ifBlank { progress.item.name }, color = LuxText, fontSize = 14.sp, fontWeight = FontWeight.Medium, maxLines = 2, overflow = TextOverflow.Ellipsis, ) Text( "This only removes it from this profile's Continue Watching row. It does not delete the movie, episode or series.", color = LuxMuted, fontSize = 11.sp, ) Row(horizontalArrangement = Arrangement.spacedBy(10.dp)) { LuxButton( "REMOVE", onRemove, modifier = Modifier.focusRequester(removeFocus), primary = true, ) LuxButton("CANCEL", onDismiss) } } } } @Composable private fun SportsHomeTile( subtitle: String, loading: Boolean, loadingCategory: String, ready: Boolean, modifier: Modifier, onClick: () -> Unit, ) { LuxCard(modifier = modifier, onClick = onClick) { Column(Modifier.padding(13.dp), verticalArrangement = Arrangement.spacedBy(4.dp)) { Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(7.dp)) { Text("SPORTS", color = LuxGold, fontSize = 9.sp, fontWeight = FontWeight.Bold, letterSpacing = 1.05.sp) when { loading -> CircularProgressIndicator( modifier = Modifier.size(12.dp), strokeWidth = 1.7.dp, color = LuxGold, ) ready -> Text("✓", color = LuxGreen, fontSize = 11.sp, fontWeight = FontWeight.Black) } } Text(subtitle, color = LuxText, fontSize = 11.sp, fontWeight = FontWeight.SemiBold, maxLines = 1, overflow = TextOverflow.Ellipsis) Text( when { loading && loadingCategory.isNotBlank() -> "Loading $loadingCategory…" loading -> "Building Game Center…" ready -> "GAME CENTER READY" else -> "OPEN →" }, color = if (ready && !loading) LuxGreen else LuxMuted, fontSize = 8.sp, maxLines = 1, overflow = TextOverflow.Ellipsis, ) } } } @Composable private fun HomeTile(title: String, subtitle: String, modifier: Modifier, onClick: () -> Unit) { LuxCard(modifier = modifier, onClick = onClick) { Column(Modifier.padding(13.dp), verticalArrangement = Arrangement.spacedBy(4.dp)) { Text(title, color = LuxGold, fontSize = 9.sp, fontWeight = FontWeight.Bold, letterSpacing = 1.05.sp) Text(subtitle, color = LuxText, fontSize = 11.sp, fontWeight = FontWeight.SemiBold, maxLines = 1, overflow = TextOverflow.Ellipsis) Text("OPEN →", color = LuxMuted, fontSize = 8.sp) } } } private fun formatExpiration(raw: String): String { val epoch = raw.toLongOrNull() ?: return raw return runCatching { java.text.SimpleDateFormat("MMM d, yyyy", java.util.Locale.getDefault()).format(java.util.Date(epoch * 1000L)) }.getOrDefault(raw) }