package com.example.ui.recipes import androidx.compose.foundation.BorderStroke import androidx.compose.foundation.background import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.ExperimentalLayoutApi import androidx.compose.foundation.layout.FlowRow import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer 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.LazyRow import androidx.compose.foundation.lazy.items import androidx.compose.foundation.shape.CircleShape import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.icons.Icons import androidx.compose.material.icons.automirrored.filled.MenuBook import androidx.compose.material.icons.filled.Add import androidx.compose.material.icons.filled.AutoAwesome import androidx.compose.material.icons.filled.Close import androidx.compose.material.icons.filled.Download import androidx.compose.material.icons.filled.Kitchen import androidx.compose.material.icons.filled.People import androidx.compose.material.icons.filled.Schedule import androidx.compose.material.icons.filled.Search import androidx.compose.material3.Card import androidx.compose.material3.CardDefaults import androidx.compose.material3.FilledTonalButton import androidx.compose.material3.FilterChip import androidx.compose.material3.FilterChipDefaults import androidx.compose.material3.FloatingActionButton import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.material3.MaterialTheme import androidx.compose.material3.OutlinedTextField import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.material3.TextButton import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.platform.testTag import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.dp import coil.compose.AsyncImage import com.example.data.model.CustomFoodEntry import com.example.data.model.FoodCategory import com.example.data.model.FoodPreferenceEntry import com.example.data.model.FoodPreferenceStatus import com.example.data.model.InventoryItem import com.example.data.model.MealType import com.example.data.model.RecipeCategoryTag import com.example.data.model.RecipeEntry import com.example.data.model.RecipeSuggestion import com.example.data.model.SuggestionUiState import com.example.domain.DailyBenchmarkGap import com.example.domain.RecipeStockMatch import com.example.domain.RecipeStockMatcher import com.example.ui.common.FoodCategoryColorDot import com.example.ui.common.badgeBorderColor import com.example.ui.common.badgeContainerColor import com.example.ui.common.badgeTextColor import com.example.ui.common.isSatieaDarkTheme import java.util.Locale private enum class RecipesSubTab(val label: String) { BOOK("Mes recettes"), IDEAS("Idées & Goûts") } @Composable fun RecipesScreen( recipes: List, inventoryItems: List = emptyList(), customFoods: List, foodPreferences: List, selectedIdeaMealType: MealType, dailyBenchmarkGap: DailyBenchmarkGap, suggestionUiState: SuggestionUiState, savedSuggestionIds: Set, onAddRecipeClick: () -> Unit, onImportRecipeClick: () -> Unit = {}, onRecipeClick: (RecipeEntry) -> Unit, onSavePreference: (name: String, status: FoodPreferenceStatus, category: FoodCategory?) -> Unit, onRemovePreference: (slugId: String) -> Unit, onSelectIdeaMealType: (MealType) -> Unit, onGenerateIdeas: (cravingNote: String) -> Unit, onSaveSuggestedRecipe: (RecipeSuggestion) -> Unit, onLogSuggestedRecipe: (RecipeSuggestion, MealType) -> Unit, onLikeSuggestedRecipeIngredients: (RecipeSuggestion) -> Unit ) { var activeSubTab by rememberSaveable { mutableStateOf(RecipesSubTab.BOOK) } var searchQuery by rememberSaveable { mutableStateOf("") } var selectedTag by rememberSaveable { mutableStateOf(null) } var filterByStockOnly by rememberSaveable { mutableStateOf(false) } var cravingNote by rememberSaveable { mutableStateOf("") } val customCategoriesLookup = remember(customFoods) { CustomFoodEntry.buildCategoriesLookup(customFoods) } val stockMatchesByRecipeId = remember(recipes, inventoryItems) { if (inventoryItems.isEmpty()) { emptyMap() } else { recipes.associate { recipe -> recipe.id to RecipeStockMatcher.evaluate(recipe, inventoryItems) } } } val stockReadyCount = remember(stockMatchesByRecipeId) { stockMatchesByRecipeId.values.count { it.isAlmostAvailable } } val filteredRecipes = remember(recipes, searchQuery, selectedTag, filterByStockOnly, stockMatchesByRecipeId) { val query = searchQuery.trim().lowercase(Locale.FRENCH) val filtered = recipes.filter { recipe -> val matchesTag = selectedTag == null || recipe.categoryTag.equals(selectedTag, ignoreCase = true) val matchesQuery = query.isBlank() || recipe.title.lowercase(Locale.FRENCH).contains(query) || recipe.parsedIngredients().any { it.name.lowercase(Locale.FRENCH).contains(query) } val matchesStock = !filterByStockOnly || (stockMatchesByRecipeId[recipe.id]?.isAlmostAvailable == true) matchesTag && matchesQuery && matchesStock } if (filterByStockOnly) { filtered.sortedWith( compareBy { stockMatchesByRecipeId[it.id]?.missingCount ?: Int.MAX_VALUE } .thenByDescending { stockMatchesByRecipeId[it.id]?.availableCount ?: 0 } ) } else { filtered } } Box( modifier = Modifier .fillMaxSize() .background(MaterialTheme.colorScheme.background) .testTag("recipes_screen") ) { LazyColumn( modifier = Modifier .fillMaxSize() .testTag("recipes_list"), contentPadding = PaddingValues( start = 20.dp, end = 20.dp, top = 16.dp, bottom = 96.dp ), verticalArrangement = Arrangement.spacedBy(14.dp) ) { // Header item { Column(verticalArrangement = Arrangement.spacedBy(12.dp)) { Column { Text( text = if (activeSubTab == RecipesSubTab.BOOK) { "Mon Recueil de Recettes" } else { "Idées & Mes Goûts" }, style = MaterialTheme.typography.headlineMedium, color = MaterialTheme.colorScheme.onBackground, fontWeight = FontWeight.Bold ) Text( text = if (activeSubTab == RecipesSubTab.BOOK) { if (recipes.isEmpty()) { "Conservez vos recettes préférées et notez-les en 1 clic" } else { "${recipes.size} recette${if (recipes.size > 1) "s" else ""} • ingrédients colorés & portions ajustables" } } else { "Vos envies & vos repères alimentaires du jour réunis" }, style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.onBackground.copy(alpha = 0.7f) ) } // Segmented sub-tab switcher Surface( shape = RoundedCornerShape(16.dp), color = MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.55f), modifier = Modifier .fillMaxWidth() .testTag("recipes_subtab_switcher") ) { Row( modifier = Modifier .fillMaxWidth() .padding(4.dp), horizontalArrangement = Arrangement.spacedBy(4.dp) ) { RecipesSubTab.entries.forEach { tab -> val isSelected = activeSubTab == tab Surface( onClick = { activeSubTab = tab }, modifier = Modifier .weight(1f) .height(48.dp) .testTag("recipes_subtab_${tab.name.lowercase()}"), shape = RoundedCornerShape(12.dp), color = if (isSelected) { MaterialTheme.colorScheme.surface } else { MaterialTheme.colorScheme.surface.copy(alpha = 0f) }, tonalElevation = if (isSelected) 3.dp else 0.dp ) { Row( verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.Center ) { Icon( imageVector = if (tab == RecipesSubTab.BOOK) { Icons.AutoMirrored.Filled.MenuBook } else { Icons.Default.AutoAwesome }, contentDescription = null, tint = if (isSelected) { MaterialTheme.colorScheme.primary } else { MaterialTheme.colorScheme.onSurfaceVariant }, modifier = Modifier.size(17.dp) ) Spacer(modifier = Modifier.width(6.dp)) Text( text = tab.label, style = MaterialTheme.typography.labelLarge, color = if (isSelected) { MaterialTheme.colorScheme.onSurface } else { MaterialTheme.colorScheme.onSurfaceVariant }, fontWeight = if (isSelected) FontWeight.Bold else FontWeight.Medium ) } } } } } } } if (activeSubTab == RecipesSubTab.IDEAS) { ideasAndTastesItems( preferences = foodPreferences, customFoods = customFoods, selectedMealType = selectedIdeaMealType, benchmarkGap = dailyBenchmarkGap, suggestionUiState = suggestionUiState, savedSuggestionIds = savedSuggestionIds, cravingNote = cravingNote, onCravingNoteChange = { cravingNote = it }, onSelectMealType = onSelectIdeaMealType, onSavePreference = onSavePreference, onRemovePreference = onRemovePreference, onGenerateIdeas = { onGenerateIdeas(cravingNote) }, onSaveSuggestedRecipe = onSaveSuggestedRecipe, onLogSuggestedRecipe = onLogSuggestedRecipe, onLikeRecipeIngredients = onLikeSuggestedRecipeIngredients ) } else { // Quick Import Recipe banner (URL / Photo / Text) item { FilledTonalButton( onClick = onImportRecipeClick, shape = RoundedCornerShape(14.dp), modifier = Modifier .fillMaxWidth() .testTag("import_recipe_button") ) { Icon( imageVector = Icons.Default.Download, contentDescription = null, modifier = Modifier.size(18.dp) ) Spacer(modifier = Modifier.width(8.dp)) Text( text = "Importer une recette (Lien, Photo ou Texte)", fontWeight = FontWeight.SemiBold, maxLines = 1, overflow = TextOverflow.Ellipsis ) } } // Search bar & Category filter chips if (recipes.isNotEmpty()) { item { OutlinedTextField( value = searchQuery, onValueChange = { if (it.length <= 60) searchQuery = it }, modifier = Modifier .fillMaxWidth() .testTag("recipe_search_input"), placeholder = { Text("Rechercher une recette ou un ingrédient...") }, leadingIcon = { Icon( imageVector = Icons.Default.Search, contentDescription = null, tint = MaterialTheme.colorScheme.primary ) }, trailingIcon = { if (searchQuery.isNotEmpty()) { IconButton(onClick = { searchQuery = "" }) { Icon( imageVector = Icons.Default.Close, contentDescription = "Effacer la recherche" ) } } }, singleLine = true, shape = RoundedCornerShape(14.dp) ) } item { LazyRow( horizontalArrangement = Arrangement.spacedBy(8.dp), modifier = Modifier.fillMaxWidth() ) { if (inventoryItems.isNotEmpty()) { item { FilterChip( selected = filterByStockOnly, onClick = { filterByStockOnly = !filterByStockOnly }, leadingIcon = { Icon( imageVector = Icons.Default.Kitchen, contentDescription = null, modifier = Modifier.size(16.dp) ) }, label = { Text("Avec mon stock ($stockReadyCount)") }, colors = FilterChipDefaults.filterChipColors( selectedContainerColor = MaterialTheme.colorScheme.secondaryContainer, selectedLabelColor = MaterialTheme.colorScheme.onSecondaryContainer ), modifier = Modifier.testTag("recipe_filter_stock") ) } } item { FilterChip( selected = selectedTag == null && !filterByStockOnly, onClick = { selectedTag = null filterByStockOnly = false }, label = { Text("Toutes") }, colors = FilterChipDefaults.filterChipColors( selectedContainerColor = MaterialTheme.colorScheme.primaryContainer, selectedLabelColor = MaterialTheme.colorScheme.onPrimaryContainer ) ) } items(RecipeCategoryTag.entries, key = { it.name }) { tag -> FilterChip( selected = selectedTag == tag.name, onClick = { selectedTag = if (selectedTag == tag.name) null else tag.name }, label = { Text(tag.displayName) }, colors = FilterChipDefaults.filterChipColors( selectedContainerColor = MaterialTheme.colorScheme.primaryContainer, selectedLabelColor = MaterialTheme.colorScheme.onPrimaryContainer ) ) } } } } // Content if (recipes.isEmpty()) { item { EmptyRecipesView(onAddRecipeClick = onAddRecipeClick) } } else if (filteredRecipes.isEmpty()) { item { Surface( shape = RoundedCornerShape(18.dp), color = MaterialTheme.colorScheme.surface, modifier = Modifier.fillMaxWidth() ) { Column( modifier = Modifier .fillMaxWidth() .padding(24.dp), horizontalAlignment = Alignment.CenterHorizontally ) { Text( text = "Aucune recette ne correspond à ce filtre", style = MaterialTheme.typography.titleSmall, color = MaterialTheme.colorScheme.onSurface, fontWeight = FontWeight.SemiBold ) Spacer(modifier = Modifier.height(8.dp)) TextButton( onClick = { searchQuery = "" selectedTag = null filterByStockOnly = false } ) { Text("Réinitialiser les filtres") } } } } } else { items(filteredRecipes, key = { it.id }) { recipe -> RecipeCardItem( recipe = recipe, stockMatch = stockMatchesByRecipeId[recipe.id], customCategoriesLookup = customCategoriesLookup, onClick = { onRecipeClick(recipe) } ) } } } } if (activeSubTab == RecipesSubTab.BOOK) { FloatingActionButton( onClick = onAddRecipeClick, modifier = Modifier .align(Alignment.BottomEnd) .padding(24.dp) .testTag("add_recipe_fab"), containerColor = MaterialTheme.colorScheme.primary, contentColor = MaterialTheme.colorScheme.onPrimary, shape = CircleShape ) { Icon( imageVector = Icons.Default.Add, contentDescription = "Créer une recette", modifier = Modifier.size(28.dp) ) } } } } @OptIn(ExperimentalLayoutApi::class) @Composable private fun RecipeCardItem( recipe: RecipeEntry, stockMatch: RecipeStockMatch? = null, customCategoriesLookup: Map>, onClick: () -> Unit ) { val isDark = isSatieaDarkTheme() val ingredients = remember(recipe.ingredientsSerialized) { recipe.parsedIngredients() } val dominantCategories = remember(recipe.ingredientsSerialized, customCategoriesLookup) { recipe.dominantCategories(customCategoriesLookup).take(4) } Card( modifier = Modifier .fillMaxWidth() .clickable(onClick = onClick) .testTag("recipe_card_${recipe.id}"), shape = RoundedCornerShape(20.dp), colors = CardDefaults.cardColors( containerColor = MaterialTheme.colorScheme.surface ), border = BorderStroke(1.dp, MaterialTheme.colorScheme.outlineVariant.copy(alpha = 0.3f)) ) { Column(modifier = Modifier.fillMaxWidth()) { if (!recipe.photoUri.isNullOrBlank()) { Box( modifier = Modifier .fillMaxWidth() .height(145.dp) ) { AsyncImage( model = recipe.photoUri, contentDescription = "Photo de ${recipe.title}", modifier = Modifier.fillMaxSize(), contentScale = ContentScale.Crop ) Surface( shape = RoundedCornerShape(10.dp), color = MaterialTheme.colorScheme.surface.copy(alpha = 0.9f), modifier = Modifier .align(Alignment.TopStart) .padding(12.dp) ) { Text( text = recipe.categoryEnum().displayName, style = MaterialTheme.typography.labelSmall, color = MaterialTheme.colorScheme.primary, fontWeight = FontWeight.Bold, modifier = Modifier.padding(horizontal = 10.dp, vertical = 4.dp) ) } } } Column( modifier = Modifier .fillMaxWidth() .padding(18.dp) ) { if (recipe.photoUri.isNullOrBlank()) { Surface( shape = RoundedCornerShape(10.dp), color = MaterialTheme.colorScheme.primaryContainer ) { Text( text = recipe.categoryEnum().displayName, style = MaterialTheme.typography.labelSmall, color = MaterialTheme.colorScheme.onPrimaryContainer, fontWeight = FontWeight.SemiBold, modifier = Modifier.padding(horizontal = 10.dp, vertical = 4.dp) ) } Spacer(modifier = Modifier.height(8.dp)) } Text( text = recipe.title, style = MaterialTheme.typography.titleMedium, color = MaterialTheme.colorScheme.onSurface, fontWeight = FontWeight.Bold, maxLines = 2, overflow = TextOverflow.Ellipsis ) val stockBadge = stockMatch?.badgeLabel() if (stockBadge != null) { Spacer(modifier = Modifier.height(6.dp)) val (bg, fg) = when { stockMatch.isFullyAvailable -> MaterialTheme.colorScheme.secondaryContainer to MaterialTheme.colorScheme.onSecondaryContainer stockMatch.isAlmostAvailable -> MaterialTheme.colorScheme.primaryContainer.copy(alpha = 0.7f) to MaterialTheme.colorScheme.onPrimaryContainer else -> MaterialTheme.colorScheme.surfaceVariant to MaterialTheme.colorScheme.onSurfaceVariant } Surface( shape = RoundedCornerShape(8.dp), color = bg ) { Row( verticalAlignment = Alignment.CenterVertically, modifier = Modifier.padding(horizontal = 8.dp, vertical = 3.dp) ) { Icon( imageVector = Icons.Default.Kitchen, contentDescription = null, tint = fg, modifier = Modifier.size(13.dp) ) Spacer(modifier = Modifier.width(5.dp)) Text( text = stockBadge, style = MaterialTheme.typography.labelSmall, fontWeight = FontWeight.SemiBold, color = fg ) } } } Spacer(modifier = Modifier.height(8.dp)) // Metadata chips (prep time, servings, ingredient count) Row( horizontalArrangement = Arrangement.spacedBy(14.dp), verticalAlignment = Alignment.CenterVertically ) { Row(verticalAlignment = Alignment.CenterVertically) { Icon( imageVector = Icons.Default.Schedule, contentDescription = null, tint = MaterialTheme.colorScheme.onSurfaceVariant, modifier = Modifier.size(15.dp) ) Spacer(modifier = Modifier.width(4.dp)) Text( text = recipe.formatPrepTimeLabel(), style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant ) } Row(verticalAlignment = Alignment.CenterVertically) { Icon( imageVector = Icons.Default.People, contentDescription = null, tint = MaterialTheme.colorScheme.onSurfaceVariant, modifier = Modifier.size(15.dp) ) Spacer(modifier = Modifier.width(4.dp)) Text( text = "${recipe.servings} portion${if (recipe.servings > 1) "s" else ""}", style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant ) } Text( text = "${ingredients.size} ingrédient${if (ingredients.size > 1) "s" else ""}", style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant ) } if (dominantCategories.isNotEmpty()) { Spacer(modifier = Modifier.height(12.dp)) FlowRow( horizontalArrangement = Arrangement.spacedBy(6.dp), verticalArrangement = Arrangement.spacedBy(6.dp) ) { dominantCategories.forEach { cat -> Surface( shape = RoundedCornerShape(9.dp), color = cat.badgeContainerColor(isDark), border = BorderStroke(1.dp, cat.badgeBorderColor(isDark)) ) { Row( modifier = Modifier.padding(horizontal = 8.dp, vertical = 4.dp), verticalAlignment = Alignment.CenterVertically ) { FoodCategoryColorDot(category = cat, size = 7.dp) Spacer(modifier = Modifier.width(5.dp)) Text( text = cat.shortLabel, style = MaterialTheme.typography.labelSmall, color = cat.badgeTextColor(isDark), fontWeight = FontWeight.Medium ) } } } } } } } } } @Composable private fun EmptyRecipesView(onAddRecipeClick: () -> Unit) { Column( modifier = Modifier .fillMaxWidth() .padding(vertical = 44.dp, horizontal = 20.dp), horizontalAlignment = Alignment.CenterHorizontally ) { Surface( modifier = Modifier.size(82.dp), shape = CircleShape, color = MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.5f) ) { Box(contentAlignment = Alignment.Center) { Icon( imageVector = Icons.AutoMirrored.Filled.MenuBook, contentDescription = null, tint = MaterialTheme.colorScheme.primary, modifier = Modifier.size(38.dp) ) } } Spacer(modifier = Modifier.height(20.dp)) Text( text = "Votre recueil est prêt", style = MaterialTheme.typography.titleMedium, color = MaterialTheme.colorScheme.onBackground, fontWeight = FontWeight.Bold ) Spacer(modifier = Modifier.height(8.dp)) Text( text = "Ajoutez vos plats maison avec photo, ingrédients colorés et étapes, puis notez une portion dans votre journal en un clic.", style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.onBackground.copy(alpha = 0.7f), textAlign = TextAlign.Center ) Spacer(modifier = Modifier.height(20.dp)) TextButton( onClick = onAddRecipeClick, modifier = Modifier.testTag("empty_recipes_add_button") ) { Text( text = "+ Créer ma première recette", style = MaterialTheme.typography.titleSmall, color = MaterialTheme.colorScheme.primary ) } } }