package tv.tivilux.nativeplayer.ui.screens import android.content.Context import androidx.activity.compose.BackHandler import androidx.compose.foundation.background import androidx.compose.foundation.gestures.* import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.verticalScroll import androidx.compose.foundation.focusGroup import androidx.compose.foundation.lazy.rememberLazyListState import androidx.compose.foundation.lazy.itemsIndexed import androidx.compose.ui.graphics.Brush import androidx.compose.ui.focus.focusRequester import androidx.compose.ui.focus.FocusRequester import androidx.compose.runtime.LaunchedEffect 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.items import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.ui.window.Dialog import androidx.compose.material3.Text import androidx.compose.runtime.Composable 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.Modifier 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.platform.LocalContext 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.annotation.ExperimentalCoilApi import coil.imageLoader import java.io.File import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import tv.tivilux.nativeplayer.BuildConfig import tv.tivilux.nativeplayer.model.AppSettings import tv.tivilux.nativeplayer.model.Category import tv.tivilux.nativeplayer.model.ContentType import tv.tivilux.nativeplayer.model.MediaEntry import tv.tivilux.nativeplayer.model.SessionInfo import tv.tivilux.nativeplayer.data.SupportReportContext import tv.tivilux.nativeplayer.ui.components.LuxButton import tv.tivilux.nativeplayer.ui.components.SupportIssue import tv.tivilux.nativeplayer.ui.components.SupportReportDialog import tv.tivilux.nativeplayer.ui.components.StreamDiagnosticsDialog 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.LuxPanel import tv.tivilux.nativeplayer.ui.theme.LuxText enum class SettingsSection(val label: String, val subtitle: String) { TV_GUIDE("TV Guide", "Guide layout, channel rows, focus and preview behavior"), ORGANIZE("Channels & Categories", "Hide categories and restore hidden channels"), PLAYBACK("Playback", "Buffering and live-stream playback preferences"), EPG("EPG", "Program guide timing, descriptions and loading"), REMOTE("Remote Control", "TiviMate-style quick press and long-press shortcuts"), APPEARANCE("Theme Studio", "Color themes, custom accents and focus highlights"), GENERAL("General", "Startup and series playback behavior"), SYSTEM("System", "App behavior, storage maintenance and cache controls"), SUPPORT("Support", "Report channel, playback, guide, sports or account problems"), ACCOUNT("Account & About", "Provider status, device information and sign out"), } @Composable fun SettingsScreen( session: SessionInfo?, settings: AppSettings, onSettings: (AppSettings) -> Unit, onLogout: () -> Unit, onCheckUpdates: () -> Unit, onUpdatePlaylist: () -> Unit, playlistRefreshStatus: String, onManageProfiles: () -> Unit, reportContext: SupportReportContext = SupportReportContext(), categoryLists: Map> = emptyMap(), hiddenCategoryIds: Map> = emptyMap(), hiddenLiveChannels: List = emptyList(), onMoveCategory: (ContentType, String, Int) -> Unit = { _, _, _ -> }, onToggleCategoryHidden: (ContentType, String) -> Unit = { _, _ -> }, onUnhideLiveChannel: (MediaEntry) -> Unit = {}, updateStatus: String? = null, ) { var section by remember { mutableStateOf(if (tv.tivilux.nativeplayer.ui.theme.ThemeStudioNavigation.openOnNextSettings) SettingsSection.APPEARANCE else SettingsSection.TV_GUIDE) } androidx.compose.runtime.LaunchedEffect(Unit) { tv.tivilux.nativeplayer.ui.theme.ThemeStudioNavigation.openOnNextSettings = false } var cacheStatus by remember { mutableStateOf(null) } var showSupportReport by remember { mutableStateOf(false) } var showStreamDiagnostics by remember { mutableStateOf(false) } val context = LocalContext.current.applicationContext val cacheScope = rememberCoroutineScope() Box(Modifier.fillMaxSize()) { Column( Modifier.fillMaxSize().padding(horizontal = 28.dp, vertical = 20.dp), verticalArrangement = Arrangement.spacedBy(12.dp), ) { Row(verticalAlignment = Alignment.Bottom) { Column(Modifier.weight(1f)) { Text("SETTINGS", color = LuxGold, fontSize = 10.sp, fontWeight = FontWeight.Bold, letterSpacing = 1.7.sp) Text("TiviLux Settings", color = LuxText, fontSize = 31.sp, fontWeight = FontWeight.SemiBold) Text("TV-first controls • choose a category on the left, then adjust it on the right", color = LuxMuted, fontSize = 11.sp) } Text("TiviLux Native ${BuildConfig.VERSION_NAME}", color = LuxMuted.copy(alpha = .72f), fontSize = 9.sp) } Row( Modifier.fillMaxWidth().weight(1f), horizontalArrangement = Arrangement.spacedBy(14.dp), ) { SettingsRail( selected = section, onOpen = { section = it }, modifier = Modifier.width(300.dp).fillMaxHeight(), ) Column( Modifier.weight(1f).fillMaxHeight() .background(Color(0xAA0B1017), RoundedCornerShape(18.dp)) .border(1.dp, LuxLine, RoundedCornerShape(18.dp)) .padding(16.dp), verticalArrangement = Arrangement.spacedBy(8.dp), ) { Text(section.label, color = LuxText, fontSize = 25.sp, fontWeight = FontWeight.SemiBold) Text(section.subtitle, color = LuxMuted, fontSize = 10.sp) Spacer(Modifier.height(2.dp)) SettingsDetail( section = section, session = session, settings = settings, onSettings = onSettings, onLogout = onLogout, onCheckUpdates = onCheckUpdates, onUpdatePlaylist = onUpdatePlaylist, playlistRefreshStatus = playlistRefreshStatus, onManageProfiles = onManageProfiles, onReportProblem = { showSupportReport = true }, onStreamDiagnostics = { showStreamDiagnostics = true }, categoryLists = categoryLists, hiddenCategoryIds = hiddenCategoryIds, hiddenLiveChannels = hiddenLiveChannels, onMoveCategory = onMoveCategory, onToggleCategoryHidden = onToggleCategoryHidden, onUnhideLiveChannel = onUnhideLiveChannel, updateStatus = updateStatus, cacheStatus = cacheStatus, onClearCache = { cacheStatus = "Clearing temporary cache…" cacheScope.launch { cacheStatus = withContext(Dispatchers.IO) { clearTemporaryAppCache(context) } } }, onBack = {}, ) } } } if (showStreamDiagnostics) { StreamDiagnosticsDialog(onDismiss = { showStreamDiagnostics = false }) } if (showSupportReport) { SupportReportDialog( details = reportContext, initialIssue = SupportIssue.OTHER, onDismiss = { showSupportReport = false }, ) } } } @Composable private fun SettingsRail( selected: SettingsSection, onOpen: (SettingsSection) -> Unit, modifier: Modifier = Modifier, ) { LazyColumn( modifier .background(Color(0xAA090D13), RoundedCornerShape(18.dp)) .border(1.dp, LuxLine, RoundedCornerShape(18.dp)) .padding(10.dp), verticalArrangement = Arrangement.spacedBy(6.dp), ) { items(SettingsSection.values().toList(), key = { it.name }) { item -> SettingsCategoryRow(item.label, item.subtitle, selected = item == selected) { onOpen(item) } } } } @Composable private fun ColumnScope.SettingsDetail( section: SettingsSection, session: SessionInfo?, settings: AppSettings, onSettings: (AppSettings) -> Unit, onLogout: () -> Unit, onCheckUpdates: () -> Unit, onUpdatePlaylist: () -> Unit, playlistRefreshStatus: String, onManageProfiles: () -> Unit, onReportProblem: () -> Unit, onStreamDiagnostics: () -> Unit, categoryLists: Map>, hiddenCategoryIds: Map>, hiddenLiveChannels: List, onMoveCategory: (ContentType, String, Int) -> Unit, onToggleCategoryHidden: (ContentType, String) -> Unit, onUnhideLiveChannel: (MediaEntry) -> Unit, updateStatus: String?, cacheStatus: String?, onClearCache: () -> Unit, onBack: () -> Unit, ) { LazyColumn( Modifier.fillMaxWidth().weight(1f), verticalArrangement = Arrangement.spacedBy(8.dp), ) { when (section) { SettingsSection.TV_GUIDE -> { item { InfoSetting("Preview window", "Always on in the TV Guide for fast Guide ↔ Fullscreen handoff") } item { InfoSetting("Guide browsing", "Focus does not retune live TV") } item { InfoSetting("Tune behavior", "Press OK to tune • press OK again for full screen • hold BACK also opens full screen") } item { ToggleSetting("Show channel numbers", "Display provider channel numbers in the channel column.", settings.showChannelNumbers) { onSettings(settings.copy(showChannelNumbers = it)) } } item { ToggleSetting("Show channel logos", "Display channel artwork in the guide.", settings.showChannelLogos) { onSettings(settings.copy(showChannelLogos = it)) } } item { ChoiceSetting("TV Guide order", "Provider, A-Z, channel number, or your own Manual order. Manual ordering is edited from HOLD OK inside the Guide.", if (settings.channelSort == "Name") "A-Z" else settings.channelSort, listOf("Provider", "A-Z", "Channel #", "Manual")) { onSettings(settings.copy(channelSort = it)) } } item { ChoiceSetting("Favorites Guide order", "Favorites can keep a completely separate Provider, A-Z, channel number, or Manual order.", if (settings.favoriteChannelSort == "Name") "A-Z" else settings.favoriteChannelSort, listOf("Provider", "A-Z", "Channel #", "Manual")) { onSettings(settings.copy(favoriteChannelSort = it)) } } item { ToggleSetting("Favorites first", "Keep favorite channels at the top unless Manual ordering is active.", settings.favoritesFirst) { onSettings(settings.copy(favoritesFirst = it)) } } item { InfoSetting("Manual reorder", "In TV Guide or Favorites Guide: HOLD OK → Reorder channels → OK to pick/drop → arrows to move → BACK saves") } item { ToggleSetting("Highlight tuned channel", "Give the currently tuned channel a stronger row treatment.", settings.highlightCurrentChannel) { onSettings(settings.copy(highlightCurrentChannel = it)) } } item { ToggleSetting("Program progress", "Show progress through the program currently airing.", settings.showProgramProgress) { onSettings(settings.copy(showProgramProgress = it)) } } item { ToggleSetting("Two-line program titles", "Allow a second line for program time/details.", settings.twoLineProgramTitles) { onSettings(settings.copy(twoLineProgramTitles = it)) } } item { ToggleSetting("Highlight current program", "Make the program airing now easier to spot.", settings.highlightCurrentProgram) { onSettings(settings.copy(highlightCurrentProgram = it)) } } item { ToggleSetting("Current-time marker", "Show the vertical NOW line through the guide.", settings.fullHeightTimeIndicator) { onSettings(settings.copy(fullHeightTimeIndicator = it)) } } item { ChoiceSetting("Guide density", "Press OK to cycle row height.", settings.guideDensity, listOf("Compact", "Comfortable", "Spacious")) { onSettings(settings.copy(guideDensity = it)) } } item { ChoiceSetting("Guide font size", "Press OK to cycle text size.", settings.guideFontSize, listOf("Small", "Normal", "Large")) { onSettings(settings.copy(guideFontSize = it)) } } } SettingsSection.ORGANIZE -> { item { InfoSetting("Remote controls", "UP/DOWN select • LEFT/RIGHT move category • OK hide/show") } item { SectionCaption("LIVE TV CATEGORIES") } items(categoryLists[ContentType.LIVE].orEmpty(), key = { "live-${it.id}" }) { category -> CategoryManageRow( category = category, hidden = category.id in hiddenCategoryIds[ContentType.LIVE].orEmpty(), onMove = { delta -> onMoveCategory(ContentType.LIVE, category.id, delta) }, onToggle = { onToggleCategoryHidden(ContentType.LIVE, category.id) }, ) } item { SectionCaption("MOVIE CATEGORIES") } items(categoryLists[ContentType.MOVIE].orEmpty(), key = { "movie-${it.id}" }) { category -> CategoryManageRow( category = category, hidden = category.id in hiddenCategoryIds[ContentType.MOVIE].orEmpty(), onMove = { delta -> onMoveCategory(ContentType.MOVIE, category.id, delta) }, onToggle = { onToggleCategoryHidden(ContentType.MOVIE, category.id) }, ) } item { SectionCaption("SERIES CATEGORIES") } items(categoryLists[ContentType.SERIES].orEmpty(), key = { "series-${it.id}" }) { category -> CategoryManageRow( category = category, hidden = category.id in hiddenCategoryIds[ContentType.SERIES].orEmpty(), onMove = { delta -> onMoveCategory(ContentType.SERIES, category.id, delta) }, onToggle = { onToggleCategoryHidden(ContentType.SERIES, category.id) }, ) } item { SectionCaption("HIDDEN LIVE CHANNELS") } if (hiddenLiveChannels.isEmpty()) { item { InfoSetting("Hidden channels", "None • Hide a channel from HOLD OK in the TV Guide") } } else { items(hiddenLiveChannels, key = { "hidden-channel-${it.id}" }) { channel -> HiddenChannelRow(channel = channel) { onUnhideLiveChannel(channel) } } } } SettingsSection.PLAYBACK -> { item { ChoiceSetting("Fullscreen clock", "No Clock hides the time. Other sizes show the time during fullscreen Live TV.", if (settings.showFullscreenClock) settings.fullscreenClockSize else "No Clock", listOf("No Clock", "Small", "Medium", "Large")) { choice -> onSettings(settings.copy(showFullscreenClock = choice != "No Clock", fullscreenClockSize = if (choice == "No Clock") settings.fullscreenClockSize else choice)) } } item { ChoiceSetting("Clock position", "Choose where the clock appears during fullscreen Live TV.", settings.fullscreenClockPosition, listOf("Top Left", "Top Right", "Bottom Left", "Bottom Right")) { choice -> onSettings(settings.copy(fullscreenClockPosition = choice)) } } item { ChoiceSetting("Performance profile", "Turbo prioritizes instant channel starts; Resilient keeps a larger safety buffer.", settings.bufferPreset, listOf("Turbo", "Balanced", "Resilient")) { onSettings(settings.copy(bufferPreset = it)) } } item { ToggleSetting("Prefer HLS for live TV", "Request .m3u8 live streams when supported by the provider.", settings.preferHlsLive) { onSettings(settings.copy(preferHlsLive = it)) } } item { InfoSetting("Playback engine", "Media3 / ExoPlayer • separate Live/VOD buffer tuning") } item { InfoSetting("Video surface", "Native Android TV PlayerView") } item { InfoSetting("Live player handoff", "Shared decoder between guide and full screen") } item { InfoSetting("Guide fetch control", "Viewport-aware EPG prefetch • bounded background work") } } SettingsSection.EPG -> { item { ChoiceSetting("EPG time offset", "Press OK to shift guide time when provider EPG is out of sync.", formatOffset(settings.epgTimeOffsetHours), (-4..4).map(::formatOffset)) { value -> onSettings(settings.copy(epgTimeOffsetHours = parseOffset(value))) } } item { ToggleSetting("Program descriptions", "Show synopsis text in the guide preview panel.", settings.showProgramDescriptions) { onSettings(settings.copy(showProgramDescriptions = it)) } } item { InfoSetting("Guide loading", "Progressive visible-row loading") } item { InfoSetting("Timeline", "2-hour rolling guide / 30-minute headers") } } SettingsSection.REMOTE -> { item { ToggleSetting("TV remote shortcuts", "Enable TiviLux quick-press / long-press navigation on Live TV.", settings.remoteShortcutsEnabled) { onSettings(settings.copy(remoteShortcutsEnabled = it)) } } item { ShortcutSetting("GUIDE • OK", "Quick press", "Tune selected channel") } item { ShortcutSetting("GUIDE • OK", "Long press", "Open Settings") } item { ShortcutSetting("GUIDE • BACK", "Quick press", "Return toward groups/menu") } item { ShortcutSetting("GUIDE • BACK", "Long press", "Return current channel to full screen") } item { ShortcutSetting("GUIDE • LEFT", "Long press", "Jump two hours into past programs") } item { ShortcutSetting("PROGRAM • OK", "Quick press", "Show player controls") } item { ShortcutSetting("PROGRAM • OK", "Long press", "Quick controls panel") } item { ShortcutSetting("PROGRAM • LEFT", "Quick press", "Channel list / mini guide") } item { ShortcutSetting("PROGRAM • RIGHT", "Quick press", "Previous channel") } item { ShortcutSetting("PROGRAM • UP", "Press", "Channel up • never opens the HUD") } item { ShortcutSetting("PROGRAM • DOWN", "Press", "Channel down • never opens the HUD") } item { InfoSetting("Hardware channel keys", "CHANNEL + / - maps to the same channel surfing actions") } item { ShortcutSetting("PROGRAM • BACK", "Quick press", "Return to TV guide") } item { InfoSetting("Future-program actions", "Record/remind is reserved until a real DVR/reminder engine is connected") } } SettingsSection.APPEARANCE -> { item { ThemePresetMenu(settings.colorTheme) { onSettings(settings.copy(colorTheme = it)) } } item { InfoSetting("Custom colors", "Select a color row to open a visual palette. D-pad to a swatch and press OK.") } if (settings.colorTheme == "Custom") { item { ThemeColorPicker("Background", "Base app background", settings.customBackground) { onSettings(settings.copy(customBackground = it)) } } item { ThemeColorPicker("Accent", "Buttons, labels and active states", settings.customAccent) { onSettings(settings.copy(customAccent = it)) } } item { ThemeColorPicker("Focus", "Remote-control selection highlight", settings.customFocus) { onSettings(settings.copy(customFocus = it)) } } item { ThemeLivePreview(settings) } } item { ThemeResetButton { onSettings(settings.copy(colorTheme = "Original Gold", customBackground = "#090B10", customAccent = "#E8C38B", customFocus = "#F3D6AB")) } } item { InfoSetting("Performance", "Visual colors only. No playlist refresh, playback restart, or decoder changes.") } } SettingsSection.GENERAL -> { item { ToggleSetting("Start on Live TV", "Open the TV guide immediately after sign-in.", settings.startOnLiveTv) { onSettings(settings.copy(startOnLiveTv = it)) } } item { ToggleSetting("Autoplay next episode", "Continue to the next episode automatically when supported.", settings.autoplayNextEpisode) { onSettings(settings.copy(autoplayNextEpisode = it)) } } item { InfoSetting("Navigation", "D-pad optimized") } item { InfoSetting("Movie / series details", "Full details before playback") } item { InfoSetting("VOD remote", "LEFT/RIGHT quick seek 10 sec • OK play/pause • compact transport HUD") } item { LuxButton("MANAGE HOUSEHOLD MEMBERS", onManageProfiles) } } SettingsSection.SYSTEM -> { item { Column(verticalArrangement = Arrangement.spacedBy(7.dp)) { LuxButton("UPDATE PLAYLIST", onUpdatePlaylist) Text("Refresh Live TV, Movies and Series from your provider. Saved catalogs stay available during the update.", color = LuxMuted, fontSize = 10.sp) Text(playlistRefreshStatus, color = LuxMuted, fontSize = 10.sp) } } item { InfoSetting("HOME button behavior", "HOME / app switch stops playback and closes TiviLux so audio cannot keep playing in the background") } item { InfoSetting("BACK exit", "Existing two-step BACK exit remains enabled") } item { Column(verticalArrangement = Arrangement.spacedBy(7.dp)) { LuxButton("CLEAR CACHE", onClearCache) Text( "Clears temporary artwork/download cache only. Login, profiles, Favorites, Continue Watching, Guide order and settings are preserved.", color = LuxMuted, fontSize = 10.sp, ) if (!cacheStatus.isNullOrBlank()) { Text(cacheStatus, color = if (cacheStatus.startsWith("Cache cleared")) LuxGreen else LuxMuted, fontSize = 10.sp) } } } } SettingsSection.SUPPORT -> { item { LuxButton("REPORT A PROBLEM", onReportProblem) } item { LuxButton("STREAM DIAGNOSTICS", onStreamDiagnostics) } item { InfoSetting("What gets attached", "App/build, device + Android version, and available channel/player context") } item { InfoSetting("Privacy", "Passwords and provider credentials are never included in support reports") } item { InfoSetting("Delivery", "Reports are sent to the private TiviLux admin support channel") } } SettingsSection.ACCOUNT -> { item { LuxButton("MANAGE HOUSEHOLD MEMBERS", onManageProfiles) } item { InfoSetting("Account", session?.username.orEmpty()) } item { InfoSetting("Provider status", session?.status ?: "Connected") } item { InfoSetting("Connections", if ((session?.maxConnections ?: 0) > 0) "${session?.activeConnections}/${session?.maxConnections}" else "Not reported") } item { InfoSetting("Expires", friendlyExpiration(session?.expiration)) } item { InfoSetting("App version", "TiviLux Native ${BuildConfig.VERSION_NAME} • build ${BuildConfig.VERSION_CODE}") } item { InfoSetting("Device support", "Android TV / Fire TV / onn. / Shield / ChromeOS") } item { Column(verticalArrangement = Arrangement.spacedBy(7.dp)) { LuxButton("CHECK FOR UPDATES", onCheckUpdates) if (!updateStatus.isNullOrBlank()) Text(updateStatus, color = LuxMuted, fontSize = 10.sp) } } item { Spacer(Modifier.height(8.dp)); LuxButton("SIGN OUT / CHANGE PROVIDER", onLogout) } } } } } @Composable private fun SectionCaption(text: String) { Text( text, color = LuxGold, fontSize = 9.sp, fontWeight = FontWeight.Bold, letterSpacing = 1.4.sp, modifier = Modifier.padding(top = 8.dp, bottom = 2.dp), ) } @Composable private fun CategoryManageRow( category: Category, hidden: Boolean, onMove: (Int) -> Unit, onToggle: () -> Unit, ) { var focused by remember { mutableStateOf(false) } Row( Modifier.fillMaxWidth() .background(if (focused) Color(0xFF2A251A) else LuxPanel, RoundedCornerShape(13.dp)) .border(if (focused) 2.dp else 1.dp, if (focused) LuxGold else LuxLine, RoundedCornerShape(13.dp)) .onFocusChanged { focused = it.isFocused } .focusable() .onPreviewKeyEvent { event -> if (event.type != KeyEventType.KeyDown) return@onPreviewKeyEvent false when (event.key) { Key.DirectionLeft -> { onMove(-1); true } Key.DirectionRight -> { onMove(1); true } Key.Enter, Key.DirectionCenter -> { onToggle(); true } else -> false } } .clickable(onClick = onToggle) .padding(horizontal = 18.dp, vertical = 13.dp), verticalAlignment = Alignment.CenterVertically, ) { Column(Modifier.weight(1f)) { Text(category.name, color = if (hidden) LuxMuted else LuxText, fontSize = 13.sp, fontWeight = FontWeight.SemiBold, maxLines = 1, overflow = TextOverflow.Ellipsis) Text("LEFT / RIGHT • move", color = LuxMuted, fontSize = 9.sp) } Text(if (hidden) "HIDDEN • OK SHOW" else "VISIBLE • OK HIDE", color = if (hidden) LuxMuted else LuxGold, fontSize = 9.sp, fontWeight = FontWeight.Bold) } } @Composable private fun HiddenChannelRow(channel: MediaEntry, onRestore: () -> Unit) { var focused by remember { mutableStateOf(false) } Row( Modifier.fillMaxWidth() .background(if (focused) Color(0xFF202A34) else LuxPanel, RoundedCornerShape(13.dp)) .border(1.dp, if (focused) LuxGold else LuxLine, RoundedCornerShape(13.dp)) .onFocusChanged { focused = it.isFocused } .focusable() .clickable(onClick = onRestore) .padding(horizontal = 18.dp, vertical = 13.dp), verticalAlignment = Alignment.CenterVertically, ) { Text(channel.name, color = LuxText, fontSize = 12.sp, fontWeight = FontWeight.SemiBold, modifier = Modifier.weight(1f), maxLines = 1, overflow = TextOverflow.Ellipsis) Text("OK • RESTORE", color = LuxGold, fontSize = 9.sp, fontWeight = FontWeight.Bold) } } @Composable private fun ShortcutSetting(context: String, press: String, action: String) { Row( Modifier.fillMaxWidth() .background(LuxPanel, RoundedCornerShape(13.dp)) .border(1.dp, LuxLine, RoundedCornerShape(13.dp)) .padding(horizontal = 18.dp, vertical = 13.dp), verticalAlignment = Alignment.CenterVertically, ) { Column(Modifier.width(180.dp)) { Text(context, color = LuxText, fontSize = 12.sp, fontWeight = FontWeight.SemiBold) Text(press, color = LuxGold, fontSize = 9.sp, fontWeight = FontWeight.Bold) } Text(action, color = LuxMuted, fontSize = 11.sp, modifier = Modifier.weight(1f)) } } @Composable private fun SettingsCategoryRow(title: String, subtitle: String, selected: Boolean = false, onClick: () -> Unit) { var focused by remember { mutableStateOf(false) } Row( Modifier.fillMaxWidth() .background(if (focused) Color(0xFF202A34) else LuxPanel, RoundedCornerShape(13.dp)) .border(1.dp, if (focused) LuxGold else LuxLine, RoundedCornerShape(13.dp)) .onFocusChanged { focused = it.isFocused } .focusable() .clickable(onClick = onClick) .padding(horizontal = 18.dp, vertical = 15.dp), verticalAlignment = Alignment.CenterVertically, ) { Column(Modifier.weight(1f)) { Text(title, color = LuxText, fontSize = 15.sp, fontWeight = FontWeight.SemiBold) Text(subtitle, color = LuxMuted, fontSize = 10.sp, maxLines = 1, overflow = TextOverflow.Ellipsis) } Text(if (selected) "•" else ">", color = if (focused || selected) LuxGold else LuxMuted, fontSize = 20.sp, fontWeight = FontWeight.Bold) } } @Composable private fun BackRow(onBack: () -> Unit) { var focused by remember { mutableStateOf(false) } Row( Modifier.fillMaxWidth() .background(if (focused) Color(0xFF202A34) else Color.Transparent, RoundedCornerShape(11.dp)) .border(1.dp, if (focused) LuxGold else Color.Transparent, RoundedCornerShape(11.dp)) .onFocusChanged { focused = it.isFocused } .focusable() .clickable(onClick = onBack) .padding(horizontal = 14.dp, vertical = 10.dp), verticalAlignment = Alignment.CenterVertically, ) { Text("< SETTINGS", color = if (focused) LuxGold else LuxMuted, fontSize = 11.sp, fontWeight = FontWeight.Bold) } } @Composable private fun ToggleSetting(title: String, subtitle: String, value: Boolean, onChange: (Boolean) -> Unit) { var focused by remember { mutableStateOf(false) } Row( Modifier.fillMaxWidth() .background(if (focused) Color(0xFF202A34) else LuxPanel, RoundedCornerShape(13.dp)) .border(1.dp, if (focused) LuxGold else LuxLine, RoundedCornerShape(13.dp)) .onFocusChanged { focused = it.isFocused } .focusable() .clickable { onChange(!value) } .padding(horizontal = 18.dp, vertical = 14.dp), verticalAlignment = Alignment.CenterVertically, ) { Column(Modifier.weight(1f)) { Text(title, color = LuxText, fontSize = 13.sp, fontWeight = FontWeight.SemiBold) Text(subtitle, color = LuxMuted, fontSize = 10.sp) } Row( Modifier.width(74.dp).height(30.dp) .background(if (value) LuxGold else Color(0xFF303741), RoundedCornerShape(50)) .padding(horizontal = 8.dp), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.Center, ) { Text(if (value) "ON" else "OFF", color = if (value) Color(0xFF16130F) else LuxText, fontSize = 10.sp, fontWeight = FontWeight.Bold) } } } @Composable private fun ChoiceSetting(title: String, subtitle: String, value: String, choices: List, onChange: (String) -> Unit) { var focused by remember { mutableStateOf(false) } val nextValue = remember(value, choices) { val i = choices.indexOf(value) choices[(if (i < 0) 0 else (i + 1) % choices.size)] } Row( Modifier.fillMaxWidth() .background(if (focused) Color(0xFF202A34) else LuxPanel, RoundedCornerShape(13.dp)) .border(1.dp, if (focused) LuxGold else LuxLine, RoundedCornerShape(13.dp)) .onFocusChanged { focused = it.isFocused } .focusable() .clickable { onChange(nextValue) } .padding(horizontal = 18.dp, vertical = 14.dp), verticalAlignment = Alignment.CenterVertically, ) { Column(Modifier.weight(1f)) { Text(title, color = LuxText, fontSize = 13.sp, fontWeight = FontWeight.SemiBold) Text(subtitle, color = LuxMuted, fontSize = 10.sp) } Text(value, color = if (focused) LuxGold else LuxText, fontSize = 12.sp, fontWeight = FontWeight.SemiBold) Spacer(Modifier.width(12.dp)) Text(">", color = LuxMuted, fontSize = 16.sp, fontWeight = FontWeight.Bold) } } @Composable private fun InfoSetting(title: String, value: String) { Row( Modifier.fillMaxWidth().background(LuxPanel, RoundedCornerShape(13.dp)).border(1.dp, LuxLine, RoundedCornerShape(13.dp)).padding(horizontal = 18.dp, vertical = 14.dp), horizontalArrangement = Arrangement.SpaceBetween, verticalAlignment = Alignment.CenterVertically, ) { Text(title, color = LuxMuted, fontSize = 11.sp) Text(value, color = LuxText, fontSize = 11.sp, fontWeight = FontWeight.SemiBold, modifier = Modifier.fillMaxWidth(.62f), maxLines = 2, overflow = TextOverflow.Ellipsis) } } @OptIn(ExperimentalCoilApi::class) private fun clearTemporaryAppCache(context: Context): String { val cacheDirs = listOfNotNull(context.cacheDir, context.externalCacheDir).distinctBy { it.absolutePath } val before = cacheDirs.sumOf(::folderSizeBytes) var failures = 0 // Clear Coil through its public cache APIs so we never delete an active disk-cache // journal out from under the image loader while Settings is still on screen. val imageLoader = context.imageLoader if (!runCatching { imageLoader.memoryCache?.clear() }.isSuccess) failures++ if (!runCatching { imageLoader.diskCache?.clear() }.isSuccess) failures++ // Clear the rest of Android's temporary cache (including old updater downloads), // but leave the live Coil cache directory itself in place after DiskCache.clear(). cacheDirs.forEach { dir -> dir.listFiles()?.forEach { child -> if (dir == context.cacheDir && child.name == "tivilux-image-cache") return@forEach if (!runCatching { child.deleteRecursively() }.getOrDefault(false)) failures++ } } val after = cacheDirs.sumOf(::folderSizeBytes) val freed = (before - after).coerceAtLeast(0L) return if (failures == 0) { "Cache cleared • ${formatCacheBytes(freed)} removed" } else { "Cache cleared • ${formatCacheBytes(freed)} removed • $failures temporary item(s) could not be cleared" } } private fun folderSizeBytes(file: File): Long { if (!file.exists()) return 0L if (file.isFile) return file.length() return file.listFiles()?.sumOf(::folderSizeBytes) ?: 0L } private fun formatCacheBytes(bytes: Long): String = when { bytes >= 1024L * 1024L * 1024L -> String.format(java.util.Locale.US, "%.2f GB", bytes / (1024.0 * 1024.0 * 1024.0)) bytes >= 1024L * 1024L -> String.format(java.util.Locale.US, "%.1f MB", bytes / (1024.0 * 1024.0)) bytes >= 1024L -> String.format(java.util.Locale.US, "%.1f KB", bytes / 1024.0) else -> "$bytes B" } private fun formatOffset(hours: Int): String = when { hours > 0 -> "+${hours}h" hours < 0 -> "${hours}h" else -> "0h" } private fun parseOffset(value: String): Int = value.removeSuffix("h").removePrefix("+").toIntOrNull() ?: 0 private fun friendlyExpiration(raw: String?): String { if (raw.isNullOrBlank() || raw == "0" || raw.equals("null", true)) return "Not reported" 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) } // Theme Studio: presentation-only controls. No playback, repository, or guide state is accessed. private val themePickerColors = listOf( "#090B10", "#101114", "#1B2029", "#23252A", "#303750", "#475569", "#FFFFFF", "#F5F2EC", "#D1D5DB", "#94A3B8", "#E8C38B", "#F3D6AB", "#E50914", "#FF454F", "#E65B62", "#FF8B25", "#FFB347", "#FFD78A", "#F5A3D1", "#FFB4DF", "#FF9BCD", "#A78BFA", "#7C3AED", "#6366F1", "#7DD3FC", "#79E6F2", "#9EE8F4", "#77D99A", "#16A34A", "#15261E" ) private val themePreviewPalettes = listOf( Triple("Original Gold", "Signature black · champagne gold", listOf("#090B10", "#13161D", "#E8C38B", "#F3D6AB")), Triple("Netflix Style", "Cinema black · rich crimson", listOf("#080A0E", "#171C24", "#D52235", "#FF6370")), Triple("Monochrome", "Graphite · frost white", listOf("#101318", "#232B35", "#E3E9F1", "#FFFFFF")), Triple("Pink Luxe", "Onyx · rose gold", listOf("#110F17", "#28202C", "#DDA8B8", "#FFD7DF")), Triple("Cotton Candy", "Midnight · soft aurora", listOf("#111829", "#222D43", "#82D9D2", "#F6A9D0")), Triple("Halloween", "Obsidian · ember copper", listOf("#0E1014", "#26202A", "#E8873A", "#FFC67D")), Triple("Christmas", "Pine black · warm brass", listOf("#0D1717", "#1B302D", "#CBA96D", "#F0D5A0")) ) private fun safeThemeColor(hex: String) = Color(android.graphics.Color.parseColor(hex)) @Composable private fun ThemePresetMenu(selected: String, onChoose: (String) -> Unit) { var open by remember { mutableStateOf(false) } var focused by remember { mutableStateOf(false) } Row(Modifier.fillMaxWidth().background(LuxPanel, RoundedCornerShape(13.dp)) .border(1.dp, if (focused) LuxGold else LuxLine, RoundedCornerShape(13.dp)) .onFocusChanged { focused = it.isFocused }.clickable { open = true }.focusable() .padding(16.dp), verticalAlignment = Alignment.CenterVertically) { Column(Modifier.weight(1f)) { Text("COLOR THEME", color = LuxText, fontWeight = FontWeight.Bold, fontSize = 14.sp) Text("Press OK to browse theme previews", color = LuxMuted, fontSize = 11.sp) } Text(selected + " ▾", color = LuxGold, fontSize = 13.sp) } if (open) Dialog(onDismissRequest = { open = false }) { val listState = rememberLazyListState() val selectedIndex = themePreviewPalettes.indexOfFirst { it.first == selected }.coerceAtLeast(0) LaunchedEffect(open) { listState.scrollToItem(selectedIndex) } Column(Modifier.fillMaxWidth().heightIn(max = 490.dp) .background(Brush.verticalGradient(listOf(Color(0xFF222C3A), Color(0xFF0B1019))), RoundedCornerShape(18.dp)) .border(1.dp, Color(0xFF61738A).copy(alpha = .55f), RoundedCornerShape(18.dp)) .padding(16.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) { Text("CHOOSE YOUR LOOK", color = Color.White, fontSize = 20.sp, fontWeight = FontWeight.Bold) Text("D-pad ↑ ↓ to browse · OK to apply · Back to close", color = Color(0xFFBAC4D3), fontSize = 12.sp) LazyColumn(state = listState, modifier = Modifier.fillMaxWidth().weight(1f), verticalArrangement = Arrangement.spacedBy(8.dp)) { itemsIndexed(themePreviewPalettes) { index, item -> val (name, subtitle, colors) = item var rowFocused by remember { mutableStateOf(false) } val focusRequester = remember { FocusRequester() } LaunchedEffect(rowFocused) { if (rowFocused) listState.animateScrollToItem(index) } Row(Modifier.fillMaxWidth() .background(Brush.horizontalGradient(listOf(safeThemeColor(colors[1]), safeThemeColor(colors[0]))), RoundedCornerShape(12.dp)) .border(if (rowFocused) 3.dp else 1.dp, if (rowFocused) Color.White else if (selected == name) safeThemeColor(colors[2]) else Color(0xFF425064), RoundedCornerShape(12.dp)) .onFocusChanged { rowFocused = it.isFocused } .clickable { onChoose(name); open = false }.focusRequester(focusRequester).focusable() .padding(12.dp), verticalAlignment = Alignment.CenterVertically) { Row(horizontalArrangement = Arrangement.spacedBy(4.dp)) { colors.forEach { hex -> Box(Modifier.size(width = 20.dp, height = 40.dp) .background(Brush.verticalGradient(listOf(Color.White.copy(alpha = .24f), Color.Transparent)), RoundedCornerShape(5.dp)) .background(safeThemeColor(hex).copy(alpha = .88f), RoundedCornerShape(5.dp)) .border(1.dp, Color.White.copy(alpha = .35f), RoundedCornerShape(5.dp))) } } Spacer(Modifier.width(12.dp)) Column(Modifier.weight(1f)) { Text(name, color = Color.White, fontSize = 15.sp, fontWeight = FontWeight.Bold) Text(subtitle, color = Color(0xFFD0D7E1), fontSize = 11.sp) } if (selected == name) Text("✓", color = safeThemeColor(colors[2]), fontSize = 20.sp) } } item { var customFocused by remember { mutableStateOf(false) } Text("CUSTOM COLORS →", modifier = Modifier.fillMaxWidth() .background(Color(0xFF263245), RoundedCornerShape(10.dp)) .border(if (customFocused) 3.dp else 1.dp, if (customFocused) Color.White else Color(0xFF526174), RoundedCornerShape(10.dp)) .onFocusChanged { customFocused = it.isFocused } .clickable { onChoose("Custom"); open = false }.focusable().padding(15.dp), color = Color.White, fontSize = 14.sp, fontWeight = FontWeight.Bold) } } Text("Scroll for all 7 themes + Custom", color = Color(0xFFB6C2D2), fontSize = 11.sp) } } } @Composable private fun ThemeColorPicker(title: String, description: String, selected: String, onChoose: (String) -> Unit) { var open by remember { mutableStateOf(false) } var focused by remember { mutableStateOf(false) } Row(Modifier.fillMaxWidth().background(LuxPanel, RoundedCornerShape(12.dp)) .border(1.dp, if (focused) LuxGold else LuxLine, RoundedCornerShape(12.dp)) .onFocusChanged { focused = it.isFocused }.clickable { open = true }.focusable() .padding(14.dp), verticalAlignment = Alignment.CenterVertically) { Box(Modifier.size(35.dp).background(safeThemeColor(selected), RoundedCornerShape(8.dp)) .border(1.dp, Color.White.copy(alpha = .45f), RoundedCornerShape(8.dp))) Spacer(Modifier.width(12.dp)) Column(Modifier.weight(1f)) { Text(title, color = LuxText, fontSize = 14.sp, fontWeight = FontWeight.Bold) Text(description, color = LuxMuted, fontSize = 11.sp) } Text("CHOOSE ▾", color = LuxGold, fontSize = 12.sp, fontWeight = FontWeight.Bold) } if (open) Dialog(onDismissRequest = { open = false }) { Column(Modifier.fillMaxWidth().background(Color(0xFF141A24), RoundedCornerShape(18.dp)) .padding(18.dp), verticalArrangement = Arrangement.spacedBy(14.dp)) { Text("CHOOSE $title COLOR", color = Color.White, fontSize = 19.sp, fontWeight = FontWeight.Bold) Text("Navigate with D-pad · Press OK to apply", color = Color(0xFFBAC4D3), fontSize = 12.sp) themePickerColors.chunked(10).forEach { rowColors -> Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) { rowColors.forEach { hex -> var swatchFocused by remember { mutableStateOf(false) } Box(Modifier.size(39.dp) .border(if (swatchFocused) 3.dp else if (selected.equals(hex, true)) 2.dp else 1.dp, if (swatchFocused) Color.White else if (selected.equals(hex, true)) Color(0xFFE8C38B) else Color(0xFF4B5563), RoundedCornerShape(9.dp)) .padding(4.dp).background(safeThemeColor(hex), RoundedCornerShape(5.dp)) .onFocusChanged { swatchFocused = it.isFocused } .clickable { onChoose(hex); open = false }.focusable()) } } } Text("Selected color", color = Color(0xFFBAC4D3), fontSize = 11.sp) Box(Modifier.fillMaxWidth().height(24.dp).background(safeThemeColor(selected), RoundedCornerShape(6.dp))) } } } @Composable private fun ThemeLivePreview(settings: AppSettings) { val bg = Color(android.graphics.Color.parseColor(settings.customBackground)) val accent = Color(android.graphics.Color.parseColor(settings.customAccent)) val focus = Color(android.graphics.Color.parseColor(settings.customFocus)) val textColor = if (bg.red * .2126f + bg.green * .7152f + bg.blue * .0722f > .48f) Color.Black else Color.White Column(modifier = Modifier.fillMaxWidth().background(bg, RoundedCornerShape(12.dp)) .border(2.dp, focus, RoundedCornerShape(12.dp)).padding(16.dp), verticalArrangement = Arrangement.spacedBy(9.dp)) { Text("LIVE THEME PREVIEW", color = accent, fontSize = 12.sp, fontWeight = FontWeight.Bold) Text("Live TV • Movies • Series • Sports", color = textColor, fontSize = 13.sp) Text("Focused selection", modifier = Modifier.background(focus, RoundedCornerShape(6.dp)).padding(8.dp), color = if (focus.red * .2126f + focus.green * .7152f + focus.blue * .0722f > .48f) Color.Black else Color.White, fontSize = 12.sp) } } @Composable private fun ThemeResetButton(onReset: () -> Unit) { var focused by remember { mutableStateOf(false) } Box(modifier = Modifier.fillMaxWidth().padding(vertical = 7.dp) .border(if (focused) 2.dp else 1.dp, if (focused) LuxGold else LuxLine, RoundedCornerShape(12.dp)) .onFocusChanged { focused = it.isFocused } .clickable { onReset() }.focusable().padding(15.dp)) { Text("RESET TO ORIGINAL GOLD", color = LuxGold, fontSize = 13.sp, fontWeight = FontWeight.Bold) } }