feat: integrate Firebase AI and food preferences

- Enable Firebase AI and App Check dependencies
- Configure App Check in MainActivity
- Add FoodPreference entity and DAO methods
- Bump Room database version to 5 for new table migration
This commit is contained in:
bleackstorm committed 2026-11-21 23:30:54 +01:00
1 parent d4d5d77d71
commit 1331fae119
23 files changed
+3077 -161

No files matched your search

@@ -9,15 +9,22 @@ import androidx.lifecycle.viewModelScope
import com.example.data.model.CustomFoodEntry
import com.example.data.model.DefaultFoodCatalog
import com.example.data.model.FoodCategory
import com.example.data.model.FoodPreferenceEntry
import com.example.data.model.FoodPreferenceStatus
import com.example.data.model.FoodUnit
import com.example.data.model.MealEntry
import com.example.data.model.MealFoodItem
import com.example.data.model.MealType
import com.example.data.model.RecipeEntry
import com.example.data.model.RecipeSuggestion
import com.example.data.model.SuggestionUiState
import com.example.data.preferences.GoogleSheetsPreferencesManager
import com.example.data.preferences.ThemePreferencesManager
import com.example.data.repository.MealRepository
import com.example.domain.CsvExportUseCase
import com.example.domain.CulinaryIdeasGenerator
import com.example.domain.DailyBenchmarkAnalyzer
import com.example.domain.DailyBenchmarkGap
import com.example.domain.GoogleSheetsSyncUseCase
import com.example.domain.SheetsRestoreResult
import com.example.domain.SheetsSyncResult
@@ -26,6 +33,7 @@ import com.example.notification.MealNotificationManager
import com.example.ui.common.UiEvent
import com.example.ui.theme.AppThemeMode
import com.example.util.GoogleSheetsAuthHelper
import com.example.widget.SatieaAppWidgetProvider
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.channels.Channel
@@ -40,6 +48,7 @@ import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.receiveAsFlow
import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.launch
import java.time.LocalTime
import java.time.ZoneId
import java.util.Locale
@@ -97,6 +106,7 @@ class MealViewModel(application: Application) : AndroidViewModel(application) {
// Domain Use Cases
private val sheetsSyncUseCase = GoogleSheetsSyncUseCase(context, repository, sheetsPrefs)
private val csvExportUseCase = CsvExportUseCase(context)
private val culinaryIdeasGenerator by lazy { CulinaryIdeasGenerator() }
// UDF Event Channel
private val _uiEventChannel = Channel<UiEvent>(Channel.BUFFERED)
@@ -142,6 +152,50 @@ class MealViewModel(application: Application) : AndroidViewModel(application) {
initialValue = emptyList()
)
val foodPreferences: StateFlow<List<FoodPreferenceEntry>> = repository.observeFoodPreferences()
.catch { error ->
if (error is CancellationException) throw error
emit(emptyList())
}
.stateIn(
scope = viewModelScope,
started = SharingStarted.WhileSubscribed(5000L),
initialValue = emptyList()
)
private val _selectedIdeaMealType = MutableStateFlow(
SatieaAppWidgetProvider.suggestMealTypeForHour(LocalTime.now().hour)
)
val selectedIdeaMealType: StateFlow<MealType> = _selectedIdeaMealType.asStateFlow()
val dailyBenchmarkGap: StateFlow<DailyBenchmarkGap> = combine(
repository.observeMeals(),
repository.observeCustomFoods(),
_selectedIdeaMealType
) { meals, foods, mealType ->
val lookup = foods.associate { it.name.lowercase(Locale.FRENCH).trim() to it.resolvedCategory() }
DailyBenchmarkAnalyzer.analyzeToday(
meals = meals,
targetMealType = mealType,
customCategoryLookup = lookup
)
}
.flowOn(Dispatchers.Default)
.stateIn(
scope = viewModelScope,
started = SharingStarted.WhileSubscribed(5000L),
initialValue = DailyBenchmarkAnalyzer.analyzeToday(
meals = emptyList(),
targetMealType = _selectedIdeaMealType.value
)
)
private val _suggestionUiState = MutableStateFlow<SuggestionUiState>(SuggestionUiState.Idle)
val suggestionUiState: StateFlow<SuggestionUiState> = _suggestionUiState.asStateFlow()
private val _savedSuggestionIds = MutableStateFlow<Set<String>>(emptySet())
val savedSuggestionIds: StateFlow<Set<String>> = _savedSuggestionIds.asStateFlow()
// Asynchronous background computation of WeeklyStats including food category diversity
val weeklyStats: StateFlow<WeeklyStats> = combine(
repository.observeMeals(),
@@ -354,6 +408,146 @@ class MealViewModel(application: Application) : AndroidViewModel(application) {
}
}
// ------------------------------------------------------------------------
// Food Preferences & AI Culinary Ideas
// ------------------------------------------------------------------------
fun setFoodPreference(
name: String,
status: FoodPreferenceStatus,
category: FoodCategory? = null,
note: String = "",
showFeedback: Boolean = true
) {
val cleanName = name.trim()
if (cleanName.isBlank()) return
viewModelScope.launch {
val result = repository.saveFoodPreference(
name = cleanName,
status = status,
category = category,
note = note
)
if (result.isSuccess) {
if (showFeedback) {
val label = when (status) {
FoodPreferenceStatus.LIKED -> "ajouté à vos aliments aimés"
FoodPreferenceStatus.DISLIKED -> "ajouté à vos aliments évités"
FoodPreferenceStatus.TO_TRY -> "ajouté à vos découvertes à tester"
}
emitEvent(UiEvent.ShowSnackbar("« $cleanName » $label ✨"))
}
triggerAutoSheetsSyncIfNeeded()
} else {
emitEvent(UiEvent.ShowSnackbar(result.exceptionOrNull()?.localizedMessage ?: "Erreur d'enregistrement"))
}
}
}
fun removeFoodPreference(slugId: String) {
viewModelScope.launch {
repository.deleteFoodPreference(slugId)
triggerAutoSheetsSyncIfNeeded()
}
}
fun setIdeaMealType(mealType: MealType) {
_selectedIdeaMealType.value = mealType
}
fun generateCulinaryIdeas(cravingNote: String = "") {
viewModelScope.launch {
_suggestionUiState.value = SuggestionUiState.Loading
val targetType = _selectedIdeaMealType.value
val currentMeals = repository.getAllMealsSnapshot()
val lookup = customFoods.value.associate {
it.name.lowercase(Locale.FRENCH).trim() to it.resolvedCategory()
}
val gap = DailyBenchmarkAnalyzer.analyzeToday(
meals = currentMeals,
targetMealType = targetType,
customCategoryLookup = lookup
)
val currentPrefs = foodPreferences.value
val existingTitles = recipes.value.map { it.title }
val result = culinaryIdeasGenerator.generateIdeas(
preferences = currentPrefs,
benchmarkGap = gap,
cravingNote = cravingNote.trim(),
existingRecipeTitles = existingTitles
)
result.fold(
onSuccess = { bundle ->
_savedSuggestionIds.value = emptySet()
_suggestionUiState.value = SuggestionUiState.Success(
recipes = bundle.recipes,
discoveries = bundle.discoveries,
targetMealType = targetType,
contextSummary = bundle.contextSummary.ifBlank { gap.gentleSummary }
)
},
onFailure = { error ->
_suggestionUiState.value = SuggestionUiState.Error(
error.localizedMessage ?: "Impossible de générer des idées pour le moment."
)
}
)
}
}
fun saveSuggestedRecipe(suggestion: RecipeSuggestion) {
viewModelScope.launch {
val recipeEntry = suggestion.toRecipeEntry()
enrichCatalogWithFoodItems(suggestion.ingredients)
val result = repository.saveRecipe(recipeEntry)
if (result.isSuccess) {
_savedSuggestionIds.value = _savedSuggestionIds.value + suggestion.id
emitEvent(UiEvent.ShowSnackbar("« ${suggestion.title} » enregistrée dans Mes recettes ✨"))
triggerAutoSheetsSyncIfNeeded()
} else {
emitEvent(UiEvent.ShowSnackbar("Erreur lors de l'enregistrement de la recette"))
}
}
}
fun likeSuggestedRecipeIngredients(suggestion: RecipeSuggestion) {
val dislikedSlugs = foodPreferences.value
.filter { it.status == FoodPreferenceStatus.DISLIKED }
.map { it.slugId }
.toSet()
val candidates = suggestion.ingredients
.filter { it.resolvedCategory() != FoodCategory.FAT_SEASONING && it.resolvedCategory() != FoodCategory.OTHER }
.take(4)
if (candidates.isEmpty()) return
viewModelScope.launch {
var addedCount = 0
candidates.forEach { item ->
val slug = FoodPreferenceEntry.buildSlugId(item.name)
if (slug !in dislikedSlugs) {
repository.saveFoodPreference(
name = item.name,
status = FoodPreferenceStatus.LIKED,
category = item.resolvedCategory()
)
addedCount++
}
}
if (addedCount > 0) {
emitEvent(
UiEvent.ShowSnackbar(
"$addedCount ingrédient${if (addedCount > 1) "s" else ""} ajouté${if (addedCount > 1) "s" else ""} à vos aliments aimés ♥"
)
)
triggerAutoSheetsSyncIfNeeded()
}
}
}
// ------------------------------------------------------------------------
// Google Drive Account & Sheets Sync
// ------------------------------------------------------------------------
@@ -395,6 +589,7 @@ class MealViewModel(application: Application) : AndroidViewModel(application) {
add("${result.count} repas")
if (result.foodsCount > 0) add("${result.foodsCount} aliments")
if (result.recipesCount > 0) add("${result.recipesCount} recettes")
if (result.preferencesCount > 0) add("${result.preferencesCount} goûts")
}.joinToString(", ")
emitEvent(UiEvent.ShowSnackbar("Sauvegardé sur Google Drive ($summaryParts) 📊"))
}
@@ -428,6 +623,7 @@ class MealViewModel(application: Application) : AndroidViewModel(application) {
add("${result.mealsCount} repas")
if (result.foodsCount > 0) add("${result.foodsCount} aliments")
if (result.recipesCount > 0) add("${result.recipesCount} recettes")
if (result.preferencesCount > 0) add("${result.preferencesCount} goûts")
}.joinToString(", ")
emitEvent(UiEvent.ShowSnackbar("Restauration réussie ✨ : $summaryParts"))
}
@@ -0,0 +1,822 @@
package com.example.ui.recipes
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
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.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.LazyListScope
import androidx.compose.foundation.lazy.LazyRow
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.AutoAwesome
import androidx.compose.material.icons.filled.Block
import androidx.compose.material.icons.filled.BookmarkAdded
import androidx.compose.material.icons.filled.BookmarkBorder
import androidx.compose.material.icons.filled.Check
import androidx.compose.material.icons.filled.ErrorOutline
import androidx.compose.material.icons.filled.ExpandLess
import androidx.compose.material.icons.filled.ExpandMore
import androidx.compose.material.icons.filled.Favorite
import androidx.compose.material.icons.filled.FavoriteBorder
import androidx.compose.material.icons.filled.People
import androidx.compose.material.icons.filled.Refresh
import androidx.compose.material.icons.filled.Restaurant
import androidx.compose.material.icons.filled.Schedule
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.FilledTonalButton
import androidx.compose.material3.FilterChip
import androidx.compose.material3.FilterChipDefaults
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedButton
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.platform.testTag
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import com.example.data.model.CustomFoodEntry
import com.example.data.model.DiscoverySuggestion
import com.example.data.model.FoodCategory
import com.example.data.model.FoodPreferenceEntry
import com.example.data.model.FoodPreferenceStatus
import com.example.data.model.MealType
import com.example.data.model.RecipeSuggestion
import com.example.data.model.SuggestionUiState
import com.example.domain.DailyBenchmarkGap
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
fun LazyListScope.ideasAndTastesItems(
preferences: List<FoodPreferenceEntry>,
customFoods: List<CustomFoodEntry>,
selectedMealType: MealType,
benchmarkGap: DailyBenchmarkGap,
suggestionUiState: SuggestionUiState,
savedSuggestionIds: Set<String>,
cravingNote: String,
onCravingNoteChange: (String) -> Unit,
onSelectMealType: (MealType) -> Unit,
onSavePreference: (name: String, status: FoodPreferenceStatus, category: FoodCategory?) -> Unit,
onRemovePreference: (slugId: String) -> Unit,
onGenerateIdeas: () -> Unit,
onSaveSuggestedRecipe: (RecipeSuggestion) -> Unit,
onLogSuggestedRecipe: (RecipeSuggestion, MealType) -> Unit,
onLikeRecipeIngredients: (RecipeSuggestion) -> Unit
) {
// 1. Taste Profile Editor Card
item(key = "taste_profile_card") {
TasteProfileCard(
preferences = preferences,
customFoods = customFoods,
onSavePreference = onSavePreference,
onRemovePreference = onRemovePreference
)
}
// 2. Daily Benchmarks Context & Generator Card
item(key = "benchmark_generator_card") {
BenchmarkGeneratorCard(
selectedMealType = selectedMealType,
benchmarkGap = benchmarkGap,
cravingNote = cravingNote,
isLoading = suggestionUiState is SuggestionUiState.Loading,
onCravingNoteChange = onCravingNoteChange,
onSelectMealType = onSelectMealType,
onGenerateIdeas = onGenerateIdeas
)
}
// 3. Results Section
when (suggestionUiState) {
is SuggestionUiState.Idle -> {
item(key = "ideas_idle_hint") {
Surface(
shape = RoundedCornerShape(18.dp),
color = MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.35f),
modifier = Modifier.fillMaxWidth()
) {
Column(
modifier = Modifier.padding(18.dp),
verticalArrangement = Arrangement.spacedBy(6.dp)
) {
Text(
text = "Votre inspiration sur mesure",
style = MaterialTheme.typography.titleSmall,
color = MaterialTheme.colorScheme.onSurface,
fontWeight = FontWeight.Bold
)
Text(
text = "Satiéa croise vos aliments aimés, vos exclusions et vos repères manquants du jour pour imaginer des recettes simples et de nouvelles idées à goûter — sans calcul de calories.",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
}
}
}
}
is SuggestionUiState.Loading -> {
item(key = "ideas_loading_card") {
Card(
modifier = Modifier
.fillMaxWidth()
.testTag("ideas_loading_card"),
shape = RoundedCornerShape(20.dp),
colors = CardDefaults.cardColors(
containerColor = MaterialTheme.colorScheme.primaryContainer.copy(alpha = 0.4f)
)
) {
Row(
modifier = Modifier
.fillMaxWidth()
.padding(20.dp),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(16.dp)
) {
CircularProgressIndicator(
modifier = Modifier.size(28.dp),
strokeWidth = 3.dp,
color = MaterialTheme.colorScheme.primary
)
Column(verticalArrangement = Arrangement.spacedBy(2.dp)) {
Text(
text = "Préparation de vos idées…",
style = MaterialTheme.typography.titleSmall,
color = MaterialTheme.colorScheme.onSurface,
fontWeight = FontWeight.Bold
)
Text(
text = "Analyse de vos goûts et de vos repères pour ce ${selectedMealType.displayName.lowercase()}.",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
}
}
}
}
}
is SuggestionUiState.Error -> {
item(key = "ideas_error_card") {
Card(
modifier = Modifier
.fillMaxWidth()
.testTag("ideas_error_card"),
shape = RoundedCornerShape(20.dp),
colors = CardDefaults.cardColors(
containerColor = MaterialTheme.colorScheme.errorContainer.copy(alpha = 0.65f)
)
) {
Column(
modifier = Modifier
.fillMaxWidth()
.padding(18.dp),
verticalArrangement = Arrangement.spacedBy(10.dp)
) {
Row(
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(8.dp)
) {
Icon(
imageVector = Icons.Default.ErrorOutline,
contentDescription = null,
tint = MaterialTheme.colorScheme.onErrorContainer
)
Text(
text = "Génération interrompue",
style = MaterialTheme.typography.titleSmall,
color = MaterialTheme.colorScheme.onErrorContainer,
fontWeight = FontWeight.Bold
)
}
Text(
text = suggestionUiState.message,
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onErrorContainer
)
FilledTonalButton(
onClick = onGenerateIdeas,
modifier = Modifier.testTag("ideas_retry_button")
) {
Icon(
imageVector = Icons.Default.Refresh,
contentDescription = null,
modifier = Modifier.size(16.dp)
)
Spacer(modifier = Modifier.width(6.dp))
Text("Réessayer")
}
}
}
}
}
is SuggestionUiState.Success -> {
if (suggestionUiState.contextSummary.isNotBlank()) {
item(key = "ideas_context_summary") {
Surface(
shape = RoundedCornerShape(16.dp),
color = MaterialTheme.colorScheme.secondaryContainer.copy(alpha = 0.5f),
modifier = Modifier.fillMaxWidth()
) {
Text(
text = suggestionUiState.contextSummary,
style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.onSecondaryContainer,
modifier = Modifier.padding(14.dp)
)
}
}
}
if (suggestionUiState.recipes.isNotEmpty()) {
item(key = "ideas_recipes_header") {
Text(
text = "Idées de recettes sur mesure",
style = MaterialTheme.typography.titleLarge,
color = MaterialTheme.colorScheme.onBackground,
fontWeight = FontWeight.Bold,
modifier = Modifier.padding(top = 4.dp)
)
}
items(suggestionUiState.recipes, key = { it.id }) { suggestion ->
SuggestedRecipeCard(
suggestion = suggestion,
isSaved = suggestion.id in savedSuggestionIds,
onSaveToBook = { onSaveSuggestedRecipe(suggestion) },
onLogToJournal = { onLogSuggestedRecipe(suggestion, suggestionUiState.targetMealType) },
onLikeIngredients = { onLikeRecipeIngredients(suggestion) }
)
}
}
if (suggestionUiState.discoveries.isNotEmpty()) {
item(key = "ideas_discoveries_header") {
Column(modifier = Modifier.padding(top = 6.dp)) {
Text(
text = "Nouvelles découvertes à tester",
style = MaterialTheme.typography.titleLarge,
color = MaterialTheme.colorScheme.onBackground,
fontWeight = FontWeight.Bold
)
Text(
text = "Pour varier vos assiettes et enrichir vos repères en douceur",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onBackground.copy(alpha = 0.7f)
)
}
}
items(suggestionUiState.discoveries, key = { it.id }) { discovery ->
val slug = FoodPreferenceEntry.buildSlugId(discovery.foodName)
val existingStatus = preferences.firstOrNull { it.slugId == slug }?.status
DiscoverySuggestionCard(
discovery = discovery,
currentStatus = existingStatus,
onSetStatus = { newStatus ->
onSavePreference(discovery.foodName, newStatus, discovery.category)
}
)
}
}
}
}
}
@OptIn(ExperimentalLayoutApi::class)
@Composable
private fun BenchmarkGeneratorCard(
selectedMealType: MealType,
benchmarkGap: DailyBenchmarkGap,
cravingNote: String,
isLoading: Boolean,
onCravingNoteChange: (String) -> Unit,
onSelectMealType: (MealType) -> Unit,
onGenerateIdeas: () -> Unit
) {
val isDark = isSatieaDarkTheme()
Card(
modifier = Modifier
.fillMaxWidth()
.testTag("benchmark_generator_card"),
shape = RoundedCornerShape(22.dp),
colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surface),
border = BorderStroke(1.dp, MaterialTheme.colorScheme.primary.copy(alpha = 0.3f))
) {
Column(
modifier = Modifier
.fillMaxWidth()
.padding(18.dp),
verticalArrangement = Arrangement.spacedBy(12.dp)
) {
Column(verticalArrangement = Arrangement.spacedBy(2.dp)) {
Text(
text = "Repères du jour à compléter",
style = MaterialTheme.typography.titleLarge,
color = MaterialTheme.colorScheme.onSurface,
fontWeight = FontWeight.Bold
)
Text(
text = benchmarkGap.gentleSummary,
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
}
// Meal type selector row
LazyRow(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
items(MealType.entries, key = { it.name }) { type ->
FilterChip(
selected = selectedMealType == type,
onClick = { onSelectMealType(type) },
label = { Text(type.displayName) },
colors = FilterChipDefaults.filterChipColors(
selectedContainerColor = MaterialTheme.colorScheme.primaryContainer,
selectedLabelColor = MaterialTheme.colorScheme.onPrimaryContainer
),
modifier = Modifier.testTag("idea_meal_type_${type.name.lowercase()}")
)
}
}
// Visual badges of priority categories to complete
if (benchmarkGap.priorityMissingCategories.isNotEmpty()) {
Column(verticalArrangement = Arrangement.spacedBy(6.dp)) {
Text(
text = "Pistes ciblées pour ce repas :",
style = MaterialTheme.typography.labelMedium,
color = MaterialTheme.colorScheme.onSurfaceVariant,
fontWeight = FontWeight.SemiBold
)
FlowRow(
horizontalArrangement = Arrangement.spacedBy(6.dp),
verticalArrangement = Arrangement.spacedBy(6.dp)
) {
benchmarkGap.priorityMissingCategories.forEach { cat ->
Surface(
shape = RoundedCornerShape(10.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
)
}
}
}
}
}
}
// Optional craving / mood input
OutlinedTextField(
value = cravingNote,
onValueChange = { if (it.length <= 100) onCravingNoteChange(it) },
modifier = Modifier
.fillMaxWidth()
.testTag("idea_craving_input"),
placeholder = { Text("Envie du moment (optionnel : rapide 15 min, chaud, sucré-salé…)") },
singleLine = true,
shape = RoundedCornerShape(14.dp)
)
// Primary Generate CTA
Button(
onClick = onGenerateIdeas,
enabled = !isLoading,
modifier = Modifier
.fillMaxWidth()
.height(52.dp)
.testTag("generate_ideas_button"),
shape = RoundedCornerShape(16.dp),
colors = ButtonDefaults.buttonColors(
containerColor = MaterialTheme.colorScheme.primary,
contentColor = MaterialTheme.colorScheme.onPrimary
)
) {
if (isLoading) {
CircularProgressIndicator(
modifier = Modifier.size(18.dp),
strokeWidth = 2.dp,
color = MaterialTheme.colorScheme.onPrimary
)
Spacer(modifier = Modifier.width(10.dp))
Text("Recherche d'idées en cours…")
} else {
Icon(
imageVector = Icons.Default.AutoAwesome,
contentDescription = null,
modifier = Modifier.size(18.dp)
)
Spacer(modifier = Modifier.width(8.dp))
Text(
text = "Proposer des idées & découvertes",
style = MaterialTheme.typography.labelLarge
)
}
}
}
}
}
@OptIn(ExperimentalLayoutApi::class)
@Composable
private fun SuggestedRecipeCard(
suggestion: RecipeSuggestion,
isSaved: Boolean,
onSaveToBook: () -> Unit,
onLogToJournal: () -> Unit,
onLikeIngredients: () -> Unit
) {
val isDark = isSatieaDarkTheme()
var stepsExpanded by rememberSaveable(suggestion.id) { mutableStateOf(false) }
Card(
modifier = Modifier
.fillMaxWidth()
.testTag("suggested_recipe_card_${suggestion.id}"),
shape = RoundedCornerShape(22.dp),
colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surface),
border = BorderStroke(1.dp, MaterialTheme.colorScheme.outlineVariant.copy(alpha = 0.35f))
) {
Column(
modifier = Modifier
.fillMaxWidth()
.padding(18.dp),
verticalArrangement = Arrangement.spacedBy(10.dp)
) {
// Tag + Time + Servings row
Row(
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(10.dp)
) {
Surface(
shape = RoundedCornerShape(9.dp),
color = MaterialTheme.colorScheme.primaryContainer
) {
Text(
text = suggestion.categoryTag.displayName,
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.onPrimaryContainer,
fontWeight = FontWeight.Bold,
modifier = Modifier.padding(horizontal = 8.dp, vertical = 4.dp)
)
}
Row(verticalAlignment = Alignment.CenterVertically) {
Icon(
imageVector = Icons.Default.Schedule,
contentDescription = null,
tint = MaterialTheme.colorScheme.onSurfaceVariant,
modifier = Modifier.size(14.dp)
)
Spacer(modifier = Modifier.width(4.dp))
Text(
text = "${suggestion.prepTimeMinutes} min",
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(14.dp)
)
Spacer(modifier = Modifier.width(4.dp))
Text(
text = "${suggestion.servings} portion${if (suggestion.servings > 1) "s" else ""}",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
}
}
Text(
text = suggestion.title,
style = MaterialTheme.typography.titleLarge,
color = MaterialTheme.colorScheme.onSurface,
fontWeight = FontWeight.Bold
)
if (suggestion.whyItFits.isNotBlank()) {
Text(
text = suggestion.whyItFits,
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
}
// Completed dietary benchmark badges
if (suggestion.completedCategories.isNotEmpty()) {
FlowRow(
horizontalArrangement = Arrangement.spacedBy(6.dp),
verticalArrangement = Arrangement.spacedBy(6.dp)
) {
suggestion.completedCategories.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
)
}
}
}
}
}
// Color-coded ingredients list
if (suggestion.ingredients.isNotEmpty()) {
Column(verticalArrangement = Arrangement.spacedBy(4.dp)) {
Text(
text = "Ingrédients (${suggestion.servings} portion${if (suggestion.servings > 1) "s" else ""})",
style = MaterialTheme.typography.labelMedium,
color = MaterialTheme.colorScheme.onSurface,
fontWeight = FontWeight.SemiBold
)
suggestion.ingredients.forEach { item ->
Row(
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(8.dp)
) {
FoodCategoryColorDot(category = item.resolvedCategory(), size = 8.dp)
Text(
text = item.displayBadge(),
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurface
)
}
}
}
}
// Expandable steps
if (suggestion.steps.isNotEmpty()) {
Row(
modifier = Modifier
.fillMaxWidth()
.clickable { stepsExpanded = !stepsExpanded }
.padding(vertical = 4.dp),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.SpaceBetween
) {
Text(
text = if (stepsExpanded) "Masquer les étapes" else "Voir les ${suggestion.steps.size} étapes de préparation",
style = MaterialTheme.typography.labelMedium,
color = MaterialTheme.colorScheme.primary,
fontWeight = FontWeight.SemiBold
)
Icon(
imageVector = if (stepsExpanded) Icons.Default.ExpandLess else Icons.Default.ExpandMore,
contentDescription = null,
tint = MaterialTheme.colorScheme.primary
)
}
AnimatedVisibility(visible = stepsExpanded) {
Column(verticalArrangement = Arrangement.spacedBy(6.dp)) {
suggestion.steps.forEachIndexed { idx, step ->
Text(
text = "${idx + 1}. $step",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurface.copy(alpha = 0.9f)
)
}
}
}
}
// Action buttons row
FlowRow(
horizontalArrangement = Arrangement.spacedBy(8.dp),
verticalArrangement = Arrangement.spacedBy(8.dp),
modifier = Modifier.fillMaxWidth()
) {
FilledTonalButton(
onClick = onSaveToBook,
enabled = !isSaved,
contentPadding = PaddingValues(horizontal = 12.dp, vertical = 8.dp),
modifier = Modifier.testTag("save_suggested_recipe_${suggestion.id}")
) {
Icon(
imageVector = if (isSaved) Icons.Default.BookmarkAdded else Icons.Default.BookmarkBorder,
contentDescription = null,
modifier = Modifier.size(16.dp)
)
Spacer(modifier = Modifier.width(6.dp))
Text(if (isSaved) "Enregistrée ✓" else "Enregistrer")
}
Button(
onClick = onLogToJournal,
contentPadding = PaddingValues(horizontal = 12.dp, vertical = 8.dp),
modifier = Modifier.testTag("log_suggested_recipe_${suggestion.id}")
) {
Icon(
imageVector = Icons.Default.Restaurant,
contentDescription = null,
modifier = Modifier.size(16.dp)
)
Spacer(modifier = Modifier.width(6.dp))
Text("Noter au journal")
}
OutlinedButton(
onClick = onLikeIngredients,
contentPadding = PaddingValues(horizontal = 12.dp, vertical = 8.dp),
modifier = Modifier.testTag("like_suggested_recipe_${suggestion.id}")
) {
Icon(
imageVector = Icons.Default.FavoriteBorder,
contentDescription = null,
modifier = Modifier.size(16.dp)
)
Spacer(modifier = Modifier.width(6.dp))
Text("Aimer")
}
}
}
}
}
@OptIn(ExperimentalLayoutApi::class)
@Composable
private fun DiscoverySuggestionCard(
discovery: DiscoverySuggestion,
currentStatus: FoodPreferenceStatus?,
onSetStatus: (FoodPreferenceStatus) -> Unit
) {
val isDark = isSatieaDarkTheme()
Card(
modifier = Modifier
.fillMaxWidth()
.testTag("discovery_card_${discovery.id}"),
shape = RoundedCornerShape(18.dp),
colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surface),
border = BorderStroke(1.dp, discovery.category.badgeBorderColor(isDark).copy(alpha = 0.7f))
) {
Column(
modifier = Modifier
.fillMaxWidth()
.padding(16.dp),
verticalArrangement = Arrangement.spacedBy(8.dp)
) {
Row(
modifier = Modifier.fillMaxWidth(),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.SpaceBetween
) {
Row(
verticalAlignment = Alignment.CenterVertically,
modifier = Modifier.weight(1f)
) {
FoodCategoryColorDot(category = discovery.category, size = 11.dp)
Spacer(modifier = Modifier.width(8.dp))
Text(
text = discovery.foodName,
style = MaterialTheme.typography.titleMedium,
color = MaterialTheme.colorScheme.onSurface,
fontWeight = FontWeight.Bold
)
}
Surface(
shape = RoundedCornerShape(8.dp),
color = discovery.category.badgeContainerColor(isDark)
) {
Text(
text = discovery.category.shortLabel,
style = MaterialTheme.typography.labelSmall,
color = discovery.category.badgeTextColor(isDark),
fontWeight = FontWeight.Medium,
modifier = Modifier.padding(horizontal = 8.dp, vertical = 3.dp)
)
}
}
if (discovery.benchmarkReason.isNotBlank()) {
Text(
text = discovery.benchmarkReason,
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
}
if (discovery.pairingIdea.isNotBlank()) {
Surface(
shape = RoundedCornerShape(10.dp),
color = MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.45f),
modifier = Modifier.fillMaxWidth()
) {
Text(
text = "Idée simple : ${discovery.pairingIdea}",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurface,
modifier = Modifier.padding(horizontal = 10.dp, vertical = 7.dp)
)
}
}
FlowRow(
horizontalArrangement = Arrangement.spacedBy(6.dp),
verticalArrangement = Arrangement.spacedBy(6.dp)
) {
val isToTry = currentStatus == FoodPreferenceStatus.TO_TRY
val isLiked = currentStatus == FoodPreferenceStatus.LIKED
val isDisliked = currentStatus == FoodPreferenceStatus.DISLIKED
FilledTonalButton(
onClick = { onSetStatus(FoodPreferenceStatus.TO_TRY) },
contentPadding = PaddingValues(horizontal = 10.dp, vertical = 6.dp)
) {
Icon(
imageVector = if (isToTry) Icons.Default.Check else Icons.Default.AutoAwesome,
contentDescription = null,
modifier = Modifier.size(15.dp)
)
Spacer(modifier = Modifier.width(5.dp))
Text(if (isToTry) "À tester ✓" else "+ À tester")
}
OutlinedButton(
onClick = { onSetStatus(FoodPreferenceStatus.LIKED) },
contentPadding = PaddingValues(horizontal = 10.dp, vertical = 6.dp)
) {
Icon(
imageVector = if (isLiked) Icons.Default.Favorite else Icons.Default.FavoriteBorder,
contentDescription = null,
modifier = Modifier.size(15.dp)
)
Spacer(modifier = Modifier.width(5.dp))
Text(if (isLiked) "Aimé ✓" else "J'aime")
}
TextButton(
onClick = { onSetStatus(FoodPreferenceStatus.DISLIKED) },
contentPadding = PaddingValues(horizontal = 10.dp, vertical = 6.dp)
) {
Icon(
imageVector = Icons.Default.Block,
contentDescription = null,
modifier = Modifier.size(15.dp)
)
Spacer(modifier = Modifier.width(4.dp))
Text(if (isDisliked) "Évité ✓" else "J'évite")
}
}
}
}
}
@@ -25,6 +25,7 @@ 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.People
import androidx.compose.material.icons.filled.Schedule
@@ -59,8 +60,14 @@ 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.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.ui.common.FoodCategoryColorDot
import com.example.ui.common.badgeBorderColor
import com.example.ui.common.badgeContainerColor
@@ -68,15 +75,34 @@ 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<RecipeEntry>,
customFoods: List<CustomFoodEntry>,
foodPreferences: List<FoodPreferenceEntry>,
selectedIdeaMealType: MealType,
dailyBenchmarkGap: DailyBenchmarkGap,
suggestionUiState: SuggestionUiState,
savedSuggestionIds: Set<String>,
onAddRecipeClick: () -> Unit,
onRecipeClick: (RecipeEntry) -> 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<String?>(null) }
var cravingNote by rememberSaveable { mutableStateOf("") }
val customCategoryLookup = remember(customFoods) {
customFoods.associate { it.name.lowercase(Locale.FRENCH).trim() to it.resolvedCategory() }
@@ -113,152 +139,249 @@ fun RecipesScreen(
) {
// Header
item {
Column {
Text(
text = "Mon Recueil de Recettes",
style = MaterialTheme.typography.headlineMedium,
color = MaterialTheme.colorScheme.onBackground,
fontWeight = FontWeight.Bold
)
Text(
text = 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"
},
style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.onBackground.copy(alpha = 0.7f)
)
}
}
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)
)
}
// Search bar & Category filter chips
if (recipes.isNotEmpty()) {
item {
OutlinedTextField(
value = searchQuery,
onValueChange = { if (it.length <= 60) searchQuery = it },
// Segmented sub-tab switcher
Surface(
shape = RoundedCornerShape(16.dp),
color = MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.55f),
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"
)
.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
)
}
}
}
},
singleLine = true,
shape = RoundedCornerShape(14.dp)
)
}
item {
LazyRow(
horizontalArrangement = Arrangement.spacedBy(8.dp),
modifier = Modifier.fillMaxWidth()
) {
item {
FilterChip(
selected = selectedTag == null,
onClick = { selectedTag = null },
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(
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 {
// Search bar & Category filter chips
if (recipes.isNotEmpty()) {
item {
OutlinedTextField(
value = searchQuery,
onValueChange = { if (it.length <= 60) searchQuery = it },
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
.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"
)
}
}
) {
Text("Réinitialiser les filtres")
},
singleLine = true,
shape = RoundedCornerShape(14.dp)
)
}
item {
LazyRow(
horizontalArrangement = Arrangement.spacedBy(8.dp),
modifier = Modifier.fillMaxWidth()
) {
item {
FilterChip(
selected = selectedTag == null,
onClick = { selectedTag = null },
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
)
)
}
}
}
}
} else {
items(filteredRecipes, key = { it.id }) { recipe ->
RecipeCardItem(
recipe = recipe,
customCategoryLookup = customCategoryLookup,
onClick = { onRecipeClick(recipe) }
)
// 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
}
) {
Text("Réinitialiser les filtres")
}
}
}
}
} else {
items(filteredRecipes, key = { it.id }) { recipe ->
RecipeCardItem(
recipe = recipe,
customCategoryLookup = customCategoryLookup,
onClick = { onRecipeClick(recipe) }
)
}
}
}
}
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)
)
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)
)
}
}
}
}
@@ -0,0 +1,523 @@
package com.example.ui.recipes
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.foundation.BorderStroke
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.Row
import androidx.compose.foundation.layout.Spacer
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.LazyRow
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.KeyboardActions
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Add
import androidx.compose.material.icons.filled.AutoAwesome
import androidx.compose.material.icons.filled.Block
import androidx.compose.material.icons.filled.Close
import androidx.compose.material.icons.filled.Favorite
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.DropdownMenu
import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.FilledIconButton
import androidx.compose.material3.FilterChip
import androidx.compose.material3.FilterChipDefaults
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButtonDefaults
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.minimumInteractiveComponentSize
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.platform.testTag
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.unit.dp
import com.example.data.model.CustomFoodEntry
import com.example.data.model.DefaultFoodCatalog
import com.example.data.model.FoodCategory
import com.example.data.model.FoodPreferenceEntry
import com.example.data.model.FoodPreferenceStatus
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
@OptIn(ExperimentalLayoutApi::class)
@Composable
fun TasteProfileCard(
preferences: List<FoodPreferenceEntry>,
customFoods: List<CustomFoodEntry>,
onSavePreference: (name: String, status: FoodPreferenceStatus, category: FoodCategory?) -> Unit,
onRemovePreference: (slugId: String) -> Unit
) {
val isDark = isSatieaDarkTheme()
var activeStatus by rememberSaveable { mutableStateOf(FoodPreferenceStatus.LIKED) }
var inputText by rememberSaveable { mutableStateOf("") }
var manualCategoryOverride by remember { mutableStateOf<FoodCategory?>(null) }
var showCategoryPicker by remember { mutableStateOf(false) }
val customLookup = remember(customFoods) {
customFoods.associate { it.name.lowercase(Locale.FRENCH).trim() to it.resolvedCategory() }
}
val inferredCategory = remember(inputText, customLookup) {
if (inputText.isBlank()) FoodCategory.OTHER
else FoodCategory.inferFromName(inputText, customLookup)
}
val effectiveCategory = manualCategoryOverride ?: inferredCategory
val likedList = remember(preferences) { preferences.filter { it.status == FoodPreferenceStatus.LIKED } }
val dislikedList = remember(preferences) { preferences.filter { it.status == FoodPreferenceStatus.DISLIKED } }
val toTryList = remember(preferences) { preferences.filter { it.status == FoodPreferenceStatus.TO_TRY } }
val activeList = when (activeStatus) {
FoodPreferenceStatus.LIKED -> likedList
FoodPreferenceStatus.DISLIKED -> dislikedList
FoodPreferenceStatus.TO_TRY -> toTryList
}
val allSavedSlugs = remember(preferences) { preferences.map { it.slugId }.toSet() }
val autocompleteSuggestions = remember(inputText, customFoods, allSavedSlugs) {
val query = inputText.trim().lowercase(Locale.FRENCH)
if (query.length < 2) emptyList()
else {
val pool = buildList {
customFoods.forEach { add(it.name to it.resolvedCategory()) }
DefaultFoodCatalog.builtInFoods.forEach { add(it.name to it.category) }
}.distinctBy { it.first.lowercase(Locale.FRENCH) }
pool.filter { (name, _) ->
name.lowercase(Locale.FRENCH).contains(query) &&
FoodPreferenceEntry.buildSlugId(name) !in allSavedSlugs
}.take(5)
}
}
fun submitInput() {
val cleaned = inputText.trim()
if (cleaned.isNotBlank()) {
onSavePreference(cleaned, activeStatus, effectiveCategory)
inputText = ""
manualCategoryOverride = null
showCategoryPicker = false
}
}
Card(
modifier = Modifier
.fillMaxWidth()
.testTag("taste_profile_card"),
shape = RoundedCornerShape(22.dp),
colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surface),
border = BorderStroke(1.dp, MaterialTheme.colorScheme.outlineVariant.copy(alpha = 0.35f))
) {
Column(
modifier = Modifier
.fillMaxWidth()
.padding(18.dp),
verticalArrangement = Arrangement.spacedBy(12.dp)
) {
Column(verticalArrangement = Arrangement.spacedBy(2.dp)) {
Text(
text = "Mes goûts alimentaires",
style = MaterialTheme.typography.titleLarge,
color = MaterialTheme.colorScheme.onSurface,
fontWeight = FontWeight.Bold
)
Text(
text = "Indiquez ce que vous aimez, évitez ou souhaitez découvrir",
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
}
// Status switcher pills with live counters
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.spacedBy(8.dp)
) {
StatusTabPill(
label = "J'aime",
count = likedList.size,
icon = Icons.Default.Favorite,
selected = activeStatus == FoodPreferenceStatus.LIKED,
onClick = { activeStatus = FoodPreferenceStatus.LIKED },
modifier = Modifier
.weight(1f)
.testTag("taste_tab_liked")
)
StatusTabPill(
label = "J'évite",
count = dislikedList.size,
icon = Icons.Default.Block,
selected = activeStatus == FoodPreferenceStatus.DISLIKED,
onClick = { activeStatus = FoodPreferenceStatus.DISLIKED },
modifier = Modifier
.weight(1f)
.testTag("taste_tab_disliked")
)
StatusTabPill(
label = "À tester",
count = toTryList.size,
icon = Icons.Default.AutoAwesome,
selected = activeStatus == FoodPreferenceStatus.TO_TRY,
onClick = { activeStatus = FoodPreferenceStatus.TO_TRY },
modifier = Modifier
.weight(1f)
.testTag("taste_tab_to_try")
)
}
// Quick-add input row with live category color dot
Row(
modifier = Modifier.fillMaxWidth(),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(8.dp)
) {
OutlinedTextField(
value = inputText,
onValueChange = {
if (it.length <= 60) {
inputText = it
manualCategoryOverride = null
}
},
modifier = Modifier
.weight(1f)
.testTag("taste_food_input"),
placeholder = {
Text(
text = when (activeStatus) {
FoodPreferenceStatus.LIKED -> "Ajouter un aliment aimé (ex. saumon, comté…)"
FoodPreferenceStatus.DISLIKED -> "Aliment évité ou allergie…"
FoodPreferenceStatus.TO_TRY -> "Aliment à découvrir…"
},
maxLines = 1
)
},
leadingIcon = {
Box(
modifier = Modifier
.minimumInteractiveComponentSize()
.clickable { showCategoryPicker = !showCategoryPicker },
contentAlignment = Alignment.Center
) {
FoodCategoryColorDot(category = effectiveCategory, size = 12.dp)
}
},
singleLine = true,
shape = RoundedCornerShape(14.dp),
keyboardOptions = KeyboardOptions(imeAction = ImeAction.Done),
keyboardActions = KeyboardActions(onDone = { submitInput() })
)
FilledIconButton(
onClick = { submitInput() },
enabled = inputText.isNotBlank(),
modifier = Modifier
.size(48.dp)
.testTag("taste_add_button"),
colors = IconButtonDefaults.filledIconButtonColors(
containerColor = MaterialTheme.colorScheme.primary,
contentColor = MaterialTheme.colorScheme.onPrimary
)
) {
Icon(
imageVector = Icons.Default.Add,
contentDescription = "Ajouter cet aliment"
)
}
}
// Optional category override strip
AnimatedVisibility(visible = showCategoryPicker || inputText.isNotBlank()) {
Column(verticalArrangement = Arrangement.spacedBy(6.dp)) {
Text(
text = "Catégorie : ${effectiveCategory.displayName} (appuyez pour modifier)",
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
if (showCategoryPicker) {
LazyRow(horizontalArrangement = Arrangement.spacedBy(6.dp)) {
items(FoodCategory.entries, key = { it.code }) { cat ->
FilterChip(
selected = effectiveCategory == cat,
onClick = {
manualCategoryOverride = cat
showCategoryPicker = false
},
leadingIcon = { FoodCategoryColorDot(category = cat, size = 8.dp) },
label = { Text(cat.shortLabel, style = MaterialTheme.typography.labelSmall) }
)
}
}
}
}
}
// Autocomplete suggestions row
if (autocompleteSuggestions.isNotEmpty()) {
LazyRow(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
items(autocompleteSuggestions, key = { it.first }) { (name, cat) ->
Surface(
shape = RoundedCornerShape(12.dp),
color = cat.badgeContainerColor(isDark),
border = BorderStroke(1.dp, cat.badgeBorderColor(isDark)),
modifier = Modifier.clickable {
onSavePreference(name, activeStatus, cat)
inputText = ""
manualCategoryOverride = null
showCategoryPicker = false
}
) {
Row(
modifier = Modifier.padding(horizontal = 10.dp, vertical = 6.dp),
verticalAlignment = Alignment.CenterVertically
) {
FoodCategoryColorDot(category = cat, size = 8.dp)
Spacer(modifier = Modifier.width(6.dp))
Text(
text = "+ $name",
style = MaterialTheme.typography.labelMedium,
color = cat.badgeTextColor(isDark),
fontWeight = FontWeight.Medium
)
}
}
}
}
}
// Current preferences list for active tab
if (activeList.isNotEmpty()) {
FlowRow(
horizontalArrangement = Arrangement.spacedBy(8.dp),
verticalArrangement = Arrangement.spacedBy(8.dp),
modifier = Modifier.fillMaxWidth()
) {
activeList.forEach { pref ->
PreferenceFoodChip(
entry = pref,
isDark = isDark,
onChangeStatus = { newStatus ->
onSavePreference(pref.name, newStatus, pref.category)
},
onRemove = { onRemovePreference(pref.slugId) }
)
}
}
} else {
// Friendly empty state + quick starter picks for LIKED
Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
Text(
text = when (activeStatus) {
FoodPreferenceStatus.LIKED -> "Ajoutez quelques aliments que vous aimez (ou choisissez ci-dessous) :"
FoodPreferenceStatus.DISLIKED -> "Aucun aliment évité renseigné. Vos allergies ou aversions seront strictement exclues."
FoodPreferenceStatus.TO_TRY -> "Aucune découverte en attente. Générez des idées ci-dessous pour en ajouter en 1 clic !"
},
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant
)
if (activeStatus == FoodPreferenceStatus.LIKED) {
val starterPicks = remember(allSavedSlugs) {
FoodPreferenceEntry.quickStartLikedPicks
.filter { FoodPreferenceEntry.buildSlugId(it.first) !in allSavedSlugs }
.take(10)
}
if (starterPicks.isNotEmpty()) {
FlowRow(
horizontalArrangement = Arrangement.spacedBy(6.dp),
verticalArrangement = Arrangement.spacedBy(6.dp)
) {
starterPicks.forEach { (foodName, cat) ->
Surface(
shape = RoundedCornerShape(12.dp),
color = MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.55f),
border = BorderStroke(1.dp, cat.badgeBorderColor(isDark).copy(alpha = 0.6f)),
modifier = Modifier.clickable {
onSavePreference(foodName, FoodPreferenceStatus.LIKED, cat)
}
) {
Row(
modifier = Modifier.padding(horizontal = 10.dp, vertical = 6.dp),
verticalAlignment = Alignment.CenterVertically
) {
FoodCategoryColorDot(category = cat, size = 7.dp)
Spacer(modifier = Modifier.width(6.dp))
Text(
text = "+ $foodName",
style = MaterialTheme.typography.labelMedium,
color = MaterialTheme.colorScheme.onSurface
)
}
}
}
}
}
}
}
}
}
}
}
@Composable
private fun StatusTabPill(
label: String,
count: Int,
icon: androidx.compose.ui.graphics.vector.ImageVector,
selected: Boolean,
onClick: () -> Unit,
modifier: Modifier = Modifier
) {
val containerColor = if (selected) {
MaterialTheme.colorScheme.primaryContainer
} else {
MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.45f)
}
val contentColor = if (selected) {
MaterialTheme.colorScheme.onPrimaryContainer
} else {
MaterialTheme.colorScheme.onSurfaceVariant
}
Surface(
onClick = onClick,
modifier = modifier.height(48.dp),
shape = RoundedCornerShape(14.dp),
color = containerColor,
border = if (selected) BorderStroke(1.dp, MaterialTheme.colorScheme.primary.copy(alpha = 0.5f)) else null
) {
Row(
modifier = Modifier.padding(horizontal = 8.dp),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.Center
) {
Icon(
imageVector = icon,
contentDescription = null,
tint = contentColor,
modifier = Modifier.size(15.dp)
)
Spacer(modifier = Modifier.width(5.dp))
Text(
text = "$label ($count)",
style = MaterialTheme.typography.labelMedium,
color = contentColor,
fontWeight = if (selected) FontWeight.Bold else FontWeight.Medium,
maxLines = 1
)
}
}
}
@Composable
private fun PreferenceFoodChip(
entry: FoodPreferenceEntry,
isDark: Boolean,
onChangeStatus: (FoodPreferenceStatus) -> Unit,
onRemove: () -> Unit
) {
var menuExpanded by remember { mutableStateOf(false) }
Box {
Surface(
shape = RoundedCornerShape(12.dp),
color = entry.category.badgeContainerColor(isDark),
border = BorderStroke(1.dp, entry.category.badgeBorderColor(isDark)),
modifier = Modifier.clickable { menuExpanded = true }
) {
Row(
modifier = Modifier.padding(start = 10.dp, end = 4.dp, top = 6.dp, bottom = 6.dp),
verticalAlignment = Alignment.CenterVertically
) {
FoodCategoryColorDot(category = entry.category, size = 8.dp)
Spacer(modifier = Modifier.width(6.dp))
Text(
text = entry.name,
style = MaterialTheme.typography.labelMedium,
color = entry.category.badgeTextColor(isDark),
fontWeight = FontWeight.SemiBold
)
Spacer(modifier = Modifier.width(4.dp))
Icon(
imageVector = Icons.Default.Close,
contentDescription = "Retirer ${entry.name}",
tint = entry.category.badgeTextColor(isDark).copy(alpha = 0.75f),
modifier = Modifier
.size(20.dp)
.clickable { onRemove() }
.padding(2.dp)
)
}
}
DropdownMenu(
expanded = menuExpanded,
onDismissRequest = { menuExpanded = false }
) {
if (entry.status != FoodPreferenceStatus.LIKED) {
DropdownMenuItem(
text = { Text("Déplacer dans « J'aime »") },
leadingIcon = { Icon(Icons.Default.Favorite, contentDescription = null) },
onClick = {
menuExpanded = false
onChangeStatus(FoodPreferenceStatus.LIKED)
}
)
}
if (entry.status != FoodPreferenceStatus.TO_TRY) {
DropdownMenuItem(
text = { Text("Déplacer dans « À tester »") },
leadingIcon = { Icon(Icons.Default.AutoAwesome, contentDescription = null) },
onClick = {
menuExpanded = false
onChangeStatus(FoodPreferenceStatus.TO_TRY)
}
)
}
if (entry.status != FoodPreferenceStatus.DISLIKED) {
DropdownMenuItem(
text = { Text("Déplacer dans « J'évite »") },
leadingIcon = { Icon(Icons.Default.Block, contentDescription = null) },
onClick = {
menuExpanded = false
onChangeStatus(FoodPreferenceStatus.DISLIKED)
}
)
}
DropdownMenuItem(
text = { Text("Supprimer") },
leadingIcon = { Icon(Icons.Default.Close, contentDescription = null) },
onClick = {
menuExpanded = false
onRemove()
}
)
}
}
}