package eu.friedcutlet.yokan.ui.screens.home import androidx.compose.foundation.background import androidx.compose.foundation.layout.* import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.LazyRow import androidx.compose.foundation.lazy.items import androidx.compose.foundation.pager.HorizontalPager import androidx.compose.foundation.pager.rememberPagerState import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.icons.Icons import androidx.compose.material.icons.automirrored.filled.ArrowBack import androidx.compose.material.icons.automirrored.filled.ArrowForward import androidx.compose.material.icons.filled.Refresh import androidx.compose.material.icons.filled.Explore import androidx.compose.material.icons.filled.Search import androidx.compose.material.icons.filled.Star import androidx.compose.material.icons.filled.Tune import androidx.compose.material3.* import androidx.compose.runtime.* import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.MotionDurationScale import androidx.compose.ui.draw.clip import androidx.compose.ui.graphics.Brush import androidx.compose.ui.graphics.Color import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.dp import eu.friedcutlet.yokan.database.* import eu.friedcutlet.yokan.services.discovery.DiscoveryIssue import eu.friedcutlet.yokan.ui.components.CoverImage import eu.friedcutlet.yokan.ui.components.EmptyState import eu.friedcutlet.yokan.ui.theme.LocalEinkMode import kotlinx.coroutines.delay import kotlinx.coroutines.launch import kotlin.math.roundToInt import org.jetbrains.compose.resources.stringResource import yokan.composeapp.generated.resources.* import eu.friedcutlet.yokan.ui.theme.YokanScaffold as Scaffold @OptIn(ExperimentalMaterial3Api::class) @Composable internal fun HomeScreen( state: HomeState, onOpen: (HomeCard) -> Unit, onRefresh: () -> Unit, onCustomize: (Boolean) -> Unit, onSearch: (Boolean) -> Unit, onQuery: (String) -> Unit, onSearchSubmit: () -> Unit, onPreferences: ((DbHomePreferences) -> DbHomePreferences) -> Unit, onToken: (String) -> Unit, onAddFeed: (DbHomeSourceFeed) -> Unit, onRemoveFeed: (String) -> Unit, onMoveFeed: (String, Int) -> Unit, onBrowse: () -> Unit, onDismissIssue: () -> Unit = {}, ) { state.openIssue?.let { issue -> AlertDialog(onDismissRequest = onDismissIssue, text = { Text(homeIssueLabel(issue)) }, confirmButton = { TextButton(onClick = onDismissIssue) { Text(stringResource(Res.string.action_cancel)) } }) } if (state.customizeOpen) HomeCustomizeSheet(state, onPreferences, onToken, onAddFeed, onRemoveFeed, onMoveFeed) { onCustomize(false) } if (state.searchOpen) AlertDialog( onDismissRequest = { onSearch(false) }, title = { Text(stringResource(Res.string.home_search)) }, text = { OutlinedTextField(value = state.searchQuery, onValueChange = onQuery, singleLine = true, label = { Text(stringResource(Res.string.home_search_query)) }, modifier = Modifier.fillMaxWidth()) }, confirmButton = { TextButton(onClick = onSearchSubmit, enabled = state.searchQuery.isNotBlank()) { Text(stringResource(Res.string.home_find_sources)) } }, dismissButton = { TextButton(onClick = { onSearch(false) }) { Text(stringResource(Res.string.action_cancel)) } }, ) Scaffold(topBar = { TopAppBar(title = { Text(stringResource(Res.string.nav_home)) }, actions = { IconButton(onClick = { onSearch(true) }) { Icon(Icons.Filled.Search, stringResource(Res.string.home_search)) } IconButton(onClick = onRefresh, enabled = !state.refreshing) { Icon(Icons.Filled.Refresh, stringResource(Res.string.home_refresh)) } IconButton(onClick = { onCustomize(true) }) { Icon(Icons.Filled.Tune, stringResource(Res.string.home_customize)) } }) }) { padding -> BoxWithConstraints(Modifier.fillMaxSize().padding(padding)) { val wide = maxWidth >= 840.dp val cardWidth = if (wide) 172.dp else 136.dp LazyColumn(Modifier.fillMaxSize(), contentPadding = PaddingValues(bottom = 32.dp), verticalArrangement = Arrangement.spacedBy(24.dp)) { item(key = "filters", contentType = "filters") { LazyRow(contentPadding = PaddingValues(horizontal = 20.dp), horizontalArrangement = Arrangement.spacedBy(8.dp)) { items(HomeMediaFilter.entries, key = { it.name }) { filter -> FilterChip(selected = state.preferences.filter == filter, onClick = { onPreferences { it.copy(filter = filter) } }, label = { Text(homeFilterLabel(filter)) }) } } } if (state.featured.isNotEmpty()) item(key = "featured", contentType = "featured") { HomeFeatured(state.featured, state.preferences.autoAdvanceFeatured, wide, onOpen) } items(state.shelves, key = { it.id }, contentType = { "shelf" }) { shelf -> if (shelf.cards.isNotEmpty() || shelf.loading || shelf.issue != null || shelf.section == HomeSection.Continue) { HomeShelfContent(shelf, state.seedTitle, cardWidth, onOpen, onRefresh) { onCustomize(true) } } } if (state.feeds.isEmpty() && HomeSection.Sources !in state.preferences.hiddenSections) item(key = "sources-empty", contentType = "empty") { Column(Modifier.fillMaxWidth().padding(horizontal = 20.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) { Text(stringResource(Res.string.home_source_feeds), style = MaterialTheme.typography.titleLarge) Text(stringResource(Res.string.home_sources_hint), color = MaterialTheme.colorScheme.onSurfaceVariant) Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) { OutlinedButton(onClick = { onCustomize(true) }) { Text(stringResource(Res.string.home_add_feed)) } TextButton(onClick = onBrowse) { Text(stringResource(Res.string.home_browse)) } } } } if (state.shelves.none { it.loading || it.cards.isNotEmpty() || it.issue != null } && state.featured.isEmpty()) item(key = "empty", contentType = "empty") { EmptyState(icon = Icons.Filled.Explore, title = stringResource(Res.string.home_empty), subtitle = stringResource(Res.string.home_empty_hint), modifier = Modifier.fillMaxWidth().padding(24.dp)) } if (state.preferences.enableTmdb) item(key = "tmdb-credit", contentType = "credit") { Text(stringResource(Res.string.home_tmdb_credit), style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant, modifier = Modifier.padding(horizontal = 20.dp)) } } } } } @Composable private fun HomeShelfContent(shelf: HomeShelf, seed: String?, cardWidth: androidx.compose.ui.unit.Dp, onOpen: (HomeCard) -> Unit, onRefresh: () -> Unit, onCustomize: () -> Unit) { Column(verticalArrangement = Arrangement.spacedBy(12.dp)) { Row(Modifier.fillMaxWidth().padding(horizontal = 20.dp), verticalAlignment = Alignment.CenterVertically) { Text(if (shelf.section == HomeSection.BecauseYouRead && seed != null) stringResource(Res.string.home_because_title, seed) else shelf.sourceName?.takeIf { it.isNotBlank() } ?: homeSectionLabel(shelf.section), style = MaterialTheme.typography.titleLarge, modifier = Modifier.weight(1f)) if (shelf.loading) CircularProgressIndicator(Modifier.size(20.dp), strokeWidth = 2.dp) } if (shelf.issue != null) Row(Modifier.fillMaxWidth().padding(horizontal = 20.dp), verticalAlignment = Alignment.CenterVertically) { Text(homeIssueLabel(shelf.issue), style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.onSurfaceVariant, modifier = Modifier.weight(1f)) TextButton(onClick = if (shelf.issue == DiscoveryIssue.Credentials || shelf.issue == DiscoveryIssue.PresetChanged) onCustomize else onRefresh) { Text(stringResource(if (shelf.issue == DiscoveryIssue.Credentials || shelf.issue == DiscoveryIssue.PresetChanged) Res.string.home_customize else Res.string.home_retry)) } } if (shelf.cards.isNotEmpty()) LazyRow(contentPadding = PaddingValues(horizontal = 20.dp), horizontalArrangement = Arrangement.spacedBy(16.dp)) { items(shelf.cards, key = { it.media.key }, contentType = { "media" }) { card -> HomePoster(card, cardWidth) { onOpen(card) } } } else if (shelf.section == HomeSection.Continue) Text(stringResource(Res.string.home_continue_empty), modifier = Modifier.padding(horizontal = 20.dp), color = MaterialTheme.colorScheme.onSurfaceVariant) else if (shelf.loading) LazyRow(contentPadding = PaddingValues(horizontal = 20.dp), horizontalArrangement = Arrangement.spacedBy(16.dp)) { items(4, key = { "placeholder:$it" }) { Box(Modifier.width(cardWidth).aspectRatio(0.68f).clip(MaterialTheme.shapes.medium).background(MaterialTheme.colorScheme.surfaceContainerHighest)) } } } } @Composable private fun HomePoster(card: HomeCard, width: androidx.compose.ui.unit.Dp, onOpen: () -> Unit) { Surface(onClick = onOpen, color = Color.Transparent, shape = MaterialTheme.shapes.medium, modifier = Modifier.width(width)) { Column(verticalArrangement = Arrangement.spacedBy(6.dp)) { Box { CoverImage(card.coverBytes ?: card.media.coverUrl, card.media.title, Modifier.fillMaxWidth().aspectRatio(0.68f), fallbackInitials = card.media.title.take(2)) card.media.rating?.let { rating -> Surface(color = MaterialTheme.colorScheme.inverseSurface, shape = RoundedCornerShape(6.dp), modifier = Modifier.align(Alignment.BottomEnd).padding(6.dp)) { Row(Modifier.padding(horizontal = 6.dp, vertical = 4.dp), verticalAlignment = Alignment.CenterVertically) { Icon(Icons.Filled.Star, null, Modifier.size(14.dp)) Text(formatHomeRating(rating), style = MaterialTheme.typography.labelMedium) } } } } Text(card.media.title, style = MaterialTheme.typography.titleSmall, maxLines = 2, overflow = TextOverflow.Ellipsis) Text(homeFilterLabel(card.media.kind), style = MaterialTheme.typography.labelMedium, color = MaterialTheme.colorScheme.onSurfaceVariant) if (card.chapterId != null) { Text(card.chapterName.orEmpty(), style = MaterialTheme.typography.bodySmall, maxLines = 1, overflow = TextOverflow.Ellipsis) Text(homeProgressLabel(card), style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant) card.progress?.let { LinearProgressIndicator(progress = { it }, modifier = Modifier.fillMaxWidth()) } } } } } @Composable private fun HomeFeatured(cards: List, autoAdvance: Boolean, wide: Boolean, onOpen: (HomeCard) -> Unit) { val pager = rememberPagerState(pageCount = { cards.size }) val scope = rememberCoroutineScope() val eink = LocalEinkMode.current LaunchedEffect(cards.map { it.media.key }, autoAdvance, eink) { if (autoAdvance && !eink && cards.size > 1) while (true) { delay(7_000) if (!pager.isScrollInProgress && (coroutineContext[MotionDurationScale]?.scaleFactor ?: 1f) > 0f) pager.animateScrollToPage((pager.currentPage + 1) % cards.size) } } Column(Modifier.padding(horizontal = 20.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) { HorizontalPager(state = pager, key = { cards[it].media.key }) { page -> val card = cards[page] Box(Modifier.fillMaxWidth().height(if (wide) 340.dp else 320.dp).clip(MaterialTheme.shapes.large) .background(MaterialTheme.colorScheme.surfaceContainerHighest)) { CoverImage(card.media.backdropUrl ?: card.coverBytes ?: card.media.coverUrl, null, Modifier.matchParentSize(), fallbackInitials = card.media.title.take(2)) Box(Modifier.matchParentSize().background(Brush.verticalGradient(listOf(Color.Black.copy(alpha = 0.12f), Color.Black.copy(alpha = 0.94f))))) Column(Modifier.align(Alignment.BottomStart).padding(24.dp).widthIn(max = 680.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) { Text(card.media.title, style = MaterialTheme.typography.headlineSmall, fontWeight = FontWeight.SemiBold, color = Color.White, maxLines = 2, overflow = TextOverflow.Ellipsis) Text(homeFilterLabel(card.media.kind), style = MaterialTheme.typography.labelLarge, color = Color.White) if (card.media.description.isNotBlank()) Text(card.media.description, style = MaterialTheme.typography.bodyMedium, color = Color.White, maxLines = 2, overflow = TextOverflow.Ellipsis) Button(onClick = { onOpen(card) }) { Text(homeActionLabel(card)) } } } } if (cards.size > 1) Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.Center) { IconButton(onClick = { scope.launch { pager.animateScrollToPage((pager.currentPage - 1 + cards.size) % cards.size) } }) { Icon(Icons.AutoMirrored.Filled.ArrowBack, stringResource(Res.string.home_previous)) } Text(stringResource(Res.string.home_featured_page, pager.currentPage + 1, cards.size), style = MaterialTheme.typography.labelLarge) IconButton(onClick = { scope.launch { pager.animateScrollToPage((pager.currentPage + 1) % cards.size) } }) { Icon(Icons.AutoMirrored.Filled.ArrowForward, stringResource(Res.string.home_next)) } } } } internal fun formatHomeRating(rating: Double): String { val tenths = (rating.coerceIn(0.0, 10.0) * 10).roundToInt() return "${tenths / 10}.${tenths % 10}" } @Composable private fun homeActionLabel(card: HomeCard): String = stringResource(when { card.chapterId != null -> Res.string.home_resume card.mangaId != null || card.media.sourceId != null -> Res.string.home_open_title else -> Res.string.home_find_sources }) @Composable private fun homeProgressLabel(card: HomeCard): String = if (card.media.kind == HomeMediaFilter.Anime) { val seconds = card.position / 1_000 stringResource(Res.string.home_video_position, "${seconds / 60}:${(seconds % 60).toString().padStart(2, '0')}") } else if (card.media.kind == HomeMediaFilter.Novel) stringResource(Res.string.home_novel_position, "${((card.novelProgress ?: 0f) * 100).toInt()}%") else stringResource(Res.string.home_page_position, card.position + 1) @Composable internal fun homeFilterLabel(filter: HomeMediaFilter): String = stringResource(when (filter) { HomeMediaFilter.All -> Res.string.home_all HomeMediaFilter.Anime -> Res.string.home_anime HomeMediaFilter.Manga -> Res.string.home_manga HomeMediaFilter.Novel -> Res.string.home_novels HomeMediaFilter.Movie -> Res.string.home_movies HomeMediaFilter.Series -> Res.string.home_series }) @Composable internal fun homeSectionLabel(section: HomeSection): String = stringResource(when (section) { HomeSection.Continue -> Res.string.home_continue HomeSection.Recommended -> Res.string.home_recommended HomeSection.BecauseYouRead -> Res.string.home_because HomeSection.PopularAnime -> Res.string.home_popular_anime HomeSection.PopularManga -> Res.string.home_popular_manga HomeSection.PopularNovels -> Res.string.home_popular_novels HomeSection.PopularMovies -> Res.string.home_popular_movies HomeSection.PopularSeries -> Res.string.home_popular_series HomeSection.Sources -> Res.string.home_source_feeds HomeSection.TmdbRecommended -> Res.string.home_tmdb_recommended }) @Composable private fun homeIssueLabel(issue: DiscoveryIssue): String = stringResource(when (issue) { DiscoveryIssue.Credentials -> Res.string.home_credentials_error DiscoveryIssue.RateLimited -> Res.string.home_rate_error DiscoveryIssue.PresetChanged -> Res.string.home_preset_error DiscoveryIssue.SourceUnavailable -> Res.string.home_source_error DiscoveryIssue.Network -> Res.string.home_network_error })