import { useEffect, useRef, useState } from 'react';
import { View, Text, StyleSheet, Pressable, TextInput, Modal, ScrollView, Animated, Easing, Platform } from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
import Ionicons from '@expo/vector-icons/Ionicons';
import MaterialCommunityIcons from '@expo/vector-icons/MaterialCommunityIcons';
import { spacing } from '../../../theme';
import { trackingColors, trackingRadii } from '../theme';
import { AddEntryInput, FoodSearchResult, FoodSuggestion, HydrationQuickAdd, QuickFood, RecipeSuggestion, searchFood } from '../../../api/tracking';
import { suggestCategory } from '../utils/category';
import { CategoryPickerField } from './CategoryPickerField';

type SheetView = 'menu' | 'aliment' | 'texte' | 'boisson' | 'sport' | 'poids';

type Props = {
  visible: boolean;
  onClose: () => void;
  onScanBarcode: () => void;
  onTakePhoto: () => void;
  onDescribe: (text: string) => void;
  onAddFood: (input: AddEntryInput) => void;
  disabled: boolean;
  hydrationQuickAdds: HydrationQuickAdd[];
  onQuickAddWater: (item: HydrationQuickAdd) => void;
  quickAddWaterDisabled: boolean;
  onSaveActivity: (description: string, durationMinutes: number | null) => void;
  savingActivity: boolean;
  onSaveWeight: (weightKg: number) => void;
  savingWeight: boolean;
  lastWeightKg: number | null;
  // "EN UN GESTE" — ex-carte "Ajout rapide" (`QuickAddPanel.tsx`, supprimée) : puces
  // d'aliments fréquents pour un ré-ajout en un tap, déplacées dans le "+" pour que
  // toute saisie passe bien par là (demande explicite utilisateur).
  quickFoods: QuickFood[];
};

type SelectedFood =
  | ({ kind: 'recipe' } & RecipeSuggestion)
  | ({ kind: 'food' } & FoodSuggestion);

// Ordre d'affichage demande explicite utilisateur : mes recettes/toute la base
// d'abord (inchangé), puis pour les aliments bruts — Mes aliments (catalogue
// Ingredient), Off, Ciqual, dans cet ordre précis, avec un libellé propre à
// chaque source (`off`/`ciqual` ne sont jamais peuplés en même temps côté
// serveur — cascade Ciqual → OFF, voir `FoodSearchService` — mais on les
// distingue quand même à l'affichage plutôt que de les fusionner sous "Aliments").
const GROUPS: { key: keyof FoodSearchResult; label: string; kind: 'recipe' | 'food' }[] = [
  { key: 'mine', label: 'Mes recettes', kind: 'recipe' },
  { key: 'all', label: 'Toute la base', kind: 'recipe' },
  { key: 'ingredients', label: 'Mes aliments', kind: 'food' },
  { key: 'off', label: 'Off', kind: 'food' },
  { key: 'ciqual', label: 'Ciqual', kind: 'food' },
];

// Arrondi d'affichage pour les champs "portions"/"grammes" synchronisés — 1 décimale
// suffit (0,5 portion, 12,5 g...), au-delà ça ne fait qu'ajouter du bruit visuel.
function formatDecimal(value: number): string {
  return String(Math.round(value * 10) / 10).replace('.', ',');
}

const TITLES: Record<SheetView, string> = {
  menu: 'Ajouter',
  aliment: 'Chercher un aliment',
  texte: 'Décrire à l\'IA',
  boisson: 'Boisson',
  sport: 'Séance de sport',
  poids: 'Poids du jour',
};

// Point d'entrée unique du "+" (mockup "Clem AI proto"/"Mon suivi mobile" 2b) —
// machine à états menu → aliment | texte | boisson | sport | poids, exposée comme
// une PILE de cartes plein écran (demande explicite utilisateur : remplace l'ancien
// popup centré avec voile) — `stack` porte l'historique de navigation ; le bouton
// retour dépile, le bouton fermer (X) ferme tout le flux d'un coup, quelle que soit
// la profondeur. Code-barres et Photo IA ne sont PAS des vues empilées : ils ferment
// directement tout le flux et ouvrent `PhotoCaptureModal` (déjà autonome, cf.
// `TrackingScreen.tsx`), comme avant. Sport garde un champ de description libre (ex.
// "10 km rythme cool") au lieu des pastilles d'activités fixes de la maquette —
// demande explicite utilisateur.
export function AddSheet({
  visible,
  onClose,
  onScanBarcode,
  onTakePhoto,
  onDescribe,
  onAddFood,
  disabled,
  hydrationQuickAdds,
  onQuickAddWater,
  quickAddWaterDisabled,
  onSaveActivity,
  savingActivity,
  onSaveWeight,
  savingWeight,
  lastWeightKg,
  quickFoods,
}: Props) {
  const [stack, setStack] = useState<SheetView[]>(['menu']);
  const current = stack[stack.length - 1];
  const [description, setDescription] = useState('');
  const [category, setCategory] = useState(suggestCategory());
  const [query, setQuery] = useState('');
  const [results, setResults] = useState<FoodSearchResult | null>(null);
  const [selectedFood, setSelectedFood] = useState<SelectedFood | null>(null);
  const [qty, setQty] = useState('');
  // Grammes réels de la portion — champ synchronisé avec `qty` (nombre de
  // portions/unités) dans les deux sens, l'utilisateur pouvant ajuster l'un ou l'autre
  // (demande explicite utilisateur : "je peux modifier les portions ou les grammes").
  const [grams, setGrams] = useState('');
  const [sportDescription, setSportDescription] = useState('');
  const [sportDuration, setSportDuration] = useState('');
  const [weightKg, setWeightKg] = useState(70);
  const debounceRef = useRef<ReturnType<typeof setTimeout> | null>(null);
  // Requête pour laquelle une recherche a réellement été lancée en dernier — sert à
  // ignorer une réponse arrivée en retard (ex. "po" qui répond après "pomme" tapé
  // dans la foulée, la requête "po" étant plus lente car sans match Ciqual elle
  // bascule sur l'appel externe Open Food Facts) : `clearTimeout` n'annule que les
  // timers pas encore déclenchés, jamais une requête déjà partie.
  const latestQueryRef = useRef('');

  // Petit glissement horizontal à chaque changement de carte — direction déduite de
  // la variation de profondeur de pile (entrée depuis la droite en avançant, depuis
  // la gauche en revenant), pour suggérer visuellement l'empilement/dépilement plutôt
  // qu'un simple changement de contenu instantané.
  const slideAnim = useRef(new Animated.Value(0)).current;
  const prevStackLenRef = useRef(stack.length);

  useEffect(() => {
    const grew = stack.length > prevStackLenRef.current;
    prevStackLenRef.current = stack.length;
    slideAnim.setValue(grew ? 28 : -28);
    Animated.timing(slideAnim, {
      toValue: 0,
      duration: 200,
      easing: Easing.out(Easing.cubic),
      useNativeDriver: Platform.OS !== 'web',
    }).start();
  }, [current]);

  useEffect(() => {
    if (visible) setWeightKg(lastWeightKg ?? 70);
  }, [visible, lastWeightKg]);

  useEffect(() => {
    if (debounceRef.current) clearTimeout(debounceRef.current);
    // Ne pas relancer la recherche juste après avoir choisi une suggestion : `pick()` renseigne
    // `query` avec le nom retenu, ce qui redéclenchait ce effect et rouvrait aussitôt la liste.
    // Seuil à 3 caractères (pas 2) : une requête à 2 caractères a très peu de mots
    // significatifs côté Ciqual, tombe souvent en échec et bascule sur l'appel externe
    // OFF (lent, résultats quasi aléatoires) — retarder d'une frappe limite le nombre
    // de ces requêtes courtes qui peuvent ensuite répondre en retard (voir `latestQueryRef`).
    if (selectedFood || query.trim().length < 3) {
      latestQueryRef.current = '';
      setResults(null);
      return;
    }
    const trimmed = query.trim();
    debounceRef.current = setTimeout(() => {
      latestQueryRef.current = trimmed;
      searchFood(trimmed)
        .then((data) => {
          // N'applique que la réponse à la DERNIÈRE recherche lancée — une réponse à une
          // requête précédente arrivée en retard est ignorée plutôt que d'écraser un
          // résultat plus récent déjà affiché.
          if (latestQueryRef.current === trimmed) setResults(data);
        })
        .catch(() => {
          if (latestQueryRef.current === trimmed) setResults(null);
        });
    }, 250);
    return () => {
      if (debounceRef.current) clearTimeout(debounceRef.current);
    };
  }, [query, selectedFood]);

  const qtyNumber = parseFloat(qty.replace(',', '.')) || 0;
  const gramsNumber = parseFloat(grams.replace(',', '.')) || 0;
  // Les grammes sont la valeur de référence pour le calcul (règle de trois sur
  // `caloriesPer100`) — `qty` (nombre de portions) n'est qu'une commodité de saisie
  // synchronisée avec les grammes, jamais utilisée directement pour les kcal.
  const computedKcal = selectedFood?.kind === 'food' ? Math.round((selectedFood.caloriesPer100 * gramsNumber) / 100) : 0;
  const unit = selectedFood?.kind === 'food' ? (qtyNumber > 1 ? selectedFood.unitNamePlural : selectedFood.unitName) : '';

  function resetAll() {
    setStack(['menu']);
    setDescription('');
    setCategory(suggestCategory());
    setQuery('');
    setResults(null);
    setSelectedFood(null);
    setQty('');
    setGrams('');
    setSportDescription('');
    setSportDuration('');
  }

  // Empile une nouvelle carte par-dessus la courante (ex. menu → aliment).
  function push(view: SheetView) {
    setStack((prev) => [...prev, view]);
  }

  // Retour à la carte précédente — jamais en dessous de la racine ('menu').
  function pop() {
    setStack((prev) => (prev.length > 1 ? prev.slice(0, -1) : prev));
  }

  // Ferme tout le flux d'un coup, quelle que soit la profondeur de la pile — le
  // bouton "X" du header a toujours ce comportement (jamais un simple retour d'une
  // carte, contrairement au chevron).
  function closeAll() {
    onClose();
    resetAll();
  }

  function handleScanBarcode() {
    closeAll();
    onScanBarcode();
  }

  function handleTakePhoto() {
    closeAll();
    onTakePhoto();
  }

  function submitDescription() {
    const text = description.trim();
    if (!text) return;
    closeAll();
    onDescribe(text);
  }

  function pick(kind: 'recipe' | 'food', item: RecipeSuggestion | FoodSuggestion) {
    setQuery(item.nom);
    setResults(null);
    if (kind === 'recipe') {
      setSelectedFood({ kind: 'recipe', ...(item as RecipeSuggestion) });
      setQty('');
    } else {
      const food = item as FoodSuggestion;
      setSelectedFood({ kind: 'food', ...food });
      setQty(String(food.defaultQty));
      setGrams(formatDecimal(food.defaultQty * food.gramsPerUnit));
    }
  }

  // Saisie du nombre de portions/unités — recalcule les grammes correspondants.
  function handleQtyChange(text: string) {
    setQty(text);
    if (selectedFood?.kind !== 'food') return;
    const n = parseFloat(text.replace(',', '.'));
    if (Number.isFinite(n)) setGrams(formatDecimal(n * selectedFood.gramsPerUnit));
  }

  // Saisie directe des grammes — recalcule le nombre de portions/unités correspondant.
  function handleGramsChange(text: string) {
    setGrams(text);
    if (selectedFood?.kind !== 'food' || selectedFood.gramsPerUnit <= 0) return;
    const n = parseFloat(text.replace(',', '.'));
    if (Number.isFinite(n)) setQty(formatDecimal(n / selectedFood.gramsPerUnit));
  }

  function submitFood() {
    if (!selectedFood) return;

    if (selectedFood.kind === 'recipe') {
      onAddFood({
        nom: selectedFood.nom,
        kcal: selectedFood.kcal,
        protein: selectedFood.protein,
        carbs: selectedFood.carbs,
        fat: selectedFood.fat,
        quantite: selectedFood.quantite,
        category,
        source: 'rapide',
      });
    } else {
      const g = gramsNumber || selectedFood.defaultQty * selectedFood.gramsPerUnit;
      const q = selectedFood.gramsPerUnit > 0 ? g / selectedFood.gramsPerUnit : qtyNumber || selectedFood.defaultQty;
      const u = q > 1 ? selectedFood.unitNamePlural : selectedFood.unitName;
      onAddFood({
        nom: selectedFood.nom,
        kcal: Math.round((selectedFood.caloriesPer100 * g) / 100),
        protein: Math.round((selectedFood.proteinPer100 * g) / 10) / 10,
        carbs: Math.round((selectedFood.carbsPer100 * g) / 10) / 10,
        fat: Math.round((selectedFood.fatPer100 * g) / 10) / 10,
        quantite: `${Number.isInteger(q) ? q : q.toFixed(1)} ${u}`,
        category,
        source: 'rapide',
        volumeMl: selectedFood.isWater ? g : undefined,
      });
    }

    closeAll();
  }

  function submitSport() {
    const text = sportDescription.trim();
    if (!text) return;
    const minutes = sportDuration.trim() === '' ? null : parseInt(sportDuration, 10);
    onSaveActivity(text, Number.isFinite(minutes as number) ? minutes : null);
    closeAll();
  }

  function submitWeight() {
    onSaveWeight(Math.round(weightKg * 10) / 10);
    closeAll();
  }

  function handleQuickAddWater(item: HydrationQuickAdd) {
    onQuickAddWater(item);
    closeAll();
  }

  function handleQuickAddFood(food: QuickFood) {
    onAddFood({
      nom: food.nom,
      kcal: food.kcal,
      protein: food.protein,
      carbs: food.carbs,
      fat: food.fat,
      quantite: food.quantite,
      category: suggestCategory(),
      source: 'rapide',
    });
    closeAll();
  }

  return (
    <Modal
      visible={visible}
      animationType="slide"
      presentationStyle={Platform.OS === 'ios' ? 'fullScreen' : undefined}
      onRequestClose={stack.length > 1 ? pop : closeAll}
    >
      <SafeAreaView style={styles.screen} edges={['top', 'bottom']}>
        <View style={styles.header}>
          <View style={styles.headerLeft}>
            {stack.length > 1 && (
              <Pressable style={styles.backButton} onPress={pop} hitSlop={10}>
                <Ionicons name="chevron-back" size={20} color={trackingColors.text} />
              </Pressable>
            )}
            <Text style={styles.title}>{TITLES[current]}</Text>
          </View>
          <Pressable style={styles.closeButton} onPress={closeAll} hitSlop={10}>
            <Ionicons name="close" size={20} color={trackingColors.text} />
          </Pressable>
        </View>

        <Animated.View style={[styles.body, { transform: [{ translateX: slideAnim }] }]}>
          <ScrollView keyboardShouldPersistTaps="handled" contentContainerStyle={styles.scrollContent}>
            {current === 'menu' && (
              <View style={styles.menu}>
                <Text style={styles.sectionLabel}>Ajouter un repas</Text>
                <View style={styles.mealGrid}>
                  <Pressable style={[styles.mealTile, styles.mealTilePrimary]} onPress={() => push('aliment')}>
                    <Ionicons name="search" size={22} color="#fff" />
                    <Text style={styles.mealTileTitlePrimary}>Aliment</Text>
                    <Text style={styles.mealTileSubtitlePrimary}>Rechercher un aliment</Text>
                  </Pressable>
                  <Pressable style={styles.mealTile} onPress={handleScanBarcode}>
                    <Ionicons name="barcode-outline" size={22} color={trackingColors.text} />
                    <Text style={styles.mealTileTitle}>Code-barres</Text>
                    <Text style={styles.mealTileSubtitle}>Scanner un produit</Text>
                  </Pressable>
                  <Pressable style={styles.mealTile} onPress={handleTakePhoto}>
                    <Ionicons name="camera-outline" size={22} color={trackingColors.text} />
                    <Text style={styles.mealTileTitle}>Photo IA</Text>
                    <Text style={styles.mealTileSubtitle}>Photographier l'assiette</Text>
                  </Pressable>
                  <Pressable style={styles.mealTile} onPress={() => push('texte')}>
                    <Ionicons name="create-outline" size={22} color={trackingColors.text} />
                    <Text style={styles.mealTileTitle}>Texte IA</Text>
                    <Text style={styles.mealTileSubtitle}>Décrire en une phrase</Text>
                  </Pressable>
                </View>

                <Text style={styles.sectionLabel}>Autre saisie</Text>
                <View style={styles.otherRow}>
                  <Pressable style={styles.otherTile} onPress={() => push('boisson')}>
                    <Ionicons name="water-outline" size={22} color={trackingColors.hydration} />
                    <Text style={styles.otherTileTitle}>Boisson</Text>
                  </Pressable>
                  <Pressable style={styles.otherTile} onPress={() => push('sport')}>
                    <MaterialCommunityIcons name="run" size={22} color={trackingColors.success} />
                    <Text style={styles.otherTileTitle}>Sport</Text>
                  </Pressable>
                  <Pressable style={styles.otherTile} onPress={() => push('poids')}>
                    <MaterialCommunityIcons name="scale-bathroom" size={22} color={trackingColors.primary} />
                    <Text style={styles.otherTileTitle}>Poids</Text>
                  </Pressable>
                </View>

                {quickFoods.length > 0 && (
                  <View>
                    <Text style={styles.sectionLabel}>En un geste</Text>
                    <View style={styles.gestureRow}>
                      {quickFoods.map((food, idx) => (
                        <Pressable
                          key={`${food.nom}-${idx}`}
                          style={styles.gestureChip}
                          onPress={() => handleQuickAddFood(food)}
                          disabled={disabled}
                        >
                          <Text style={styles.gestureChipText} numberOfLines={1}>
                            {food.nom}
                          </Text>
                        </Pressable>
                      ))}
                    </View>
                  </View>
                )}
              </View>
            )}

            {current === 'aliment' && (
              <View>
                <CategoryPickerField category={category} onChange={setCategory} />

                <View style={styles.searchRow}>
                  <TextInput
                    style={styles.searchInput}
                    value={query}
                    onChangeText={(text) => {
                      setQuery(text);
                      setSelectedFood(null);
                    }}
                    placeholder="Aliment ou recette (ex. pomme, riz, poulet...)"
                    placeholderTextColor={trackingColors.textMuted}
                    autoFocus
                  />
                  <Pressable
                    style={[styles.submitButton, (!selectedFood || disabled) && styles.submitButtonDisabled]}
                    onPress={submitFood}
                    disabled={!selectedFood || disabled}
                  >
                    <Ionicons name="add" size={20} color="#fff" />
                  </Pressable>
                </View>

                {selectedFood?.kind === 'food' && (
                  <View style={styles.qtyCard}>
                    <View style={styles.qtyCardRow}>
                      <TextInput
                        style={styles.qtyCardInput}
                        value={qty}
                        onChangeText={handleQtyChange}
                        keyboardType="numeric"
                        textAlign="center"
                      />
                      <Text style={styles.qtyCardUnit}>{unit} de</Text>
                      <TextInput
                        style={styles.qtyCardInput}
                        value={grams}
                        onChangeText={handleGramsChange}
                        keyboardType="numeric"
                        textAlign="center"
                      />
                      <Text style={styles.qtyCardUnit}>g</Text>
                    </View>
                    <Text style={styles.qtySummary}>soit {computedKcal} kcal</Text>
                  </View>
                )}

                {results && (
                  <View style={styles.results}>
                    {GROUPS.every((g) => (results[g.key] as unknown[]).length === 0) && (
                      <Text style={styles.resultsEmpty}>Aucun résultat</Text>
                    )}
                    {GROUPS.map((group, groupIdx) => {
                      const items = results[group.key] as (RecipeSuggestion | FoodSuggestion)[];
                      if (items.length === 0) return null;
                      // Séparation visuelle entre catégories (demande explicite utilisateur) —
                      // jamais avant la toute première catégorie affichée, qu'elle qu'elle soit
                      // (les catégories vides ne comptent pas, `groupIdx` seul suffirait à tort
                      // pour une recherche où "Mes recettes" n'a aucun résultat).
                      const isFirstVisible = GROUPS.slice(0, groupIdx).every((g) => (results[g.key] as unknown[]).length === 0);
                      return (
                        <View key={group.key} style={[styles.resultsGroup, !isFirstVisible && styles.resultsGroupSeparated]}>
                          <Text style={styles.resultsGroupLabel}>{group.label}</Text>
                          {items.map((item, idx) => (
                            <Pressable key={`${group.key}-${idx}`} style={styles.resultRow} onPress={() => pick(group.kind, item)}>
                              <Text style={styles.resultName} numberOfLines={1}>
                                {item.nom}
                              </Text>
                              <Text style={styles.resultSub}>
                                {group.kind === 'recipe'
                                  ? `${(item as RecipeSuggestion).quantite} · ${(item as RecipeSuggestion).kcal} kcal`
                                  : `${(item as FoodSuggestion).portionLabel} · ${(item as FoodSuggestion).caloriesPer100} kcal/100g`}
                              </Text>
                            </Pressable>
                          ))}
                        </View>
                      );
                    })}
                  </View>
                )}
              </View>
            )}

            {current === 'texte' && (
              <View style={styles.descRow}>
                <Ionicons name="pencil-outline" size={18} color={trackingColors.textMuted} />
                <TextInput
                  style={styles.descInput}
                  value={description}
                  onChangeText={setDescription}
                  onSubmitEditing={submitDescription}
                  returnKeyType="send"
                  placeholder="Ex. « salade de pâtes, concombre, feta »"
                  placeholderTextColor={trackingColors.textMuted}
                  autoFocus
                />
                {description.trim().length > 0 && (
                  <Pressable onPress={submitDescription} hitSlop={8}>
                    <Ionicons name="arrow-up-circle" size={26} color={trackingColors.primary} />
                  </Pressable>
                )}
              </View>
            )}

            {current === 'boisson' && (
              <View style={styles.drinkGrid}>
                {hydrationQuickAdds.map((item) => (
                  <Pressable
                    key={item.label}
                    style={styles.drinkTile}
                    onPress={() => handleQuickAddWater(item)}
                    disabled={quickAddWaterDisabled}
                  >
                    <Text style={styles.drinkTileTitle}>{item.label}</Text>
                  </Pressable>
                ))}
              </View>
            )}

            {current === 'sport' && (
              <View style={styles.sportForm}>
                <TextInput
                  style={styles.searchInput}
                  value={sportDescription}
                  onChangeText={setSportDescription}
                  placeholder="Ex. 10 km rythme cool"
                  placeholderTextColor={trackingColors.textMuted}
                  autoFocus
                />
                <View style={styles.qtyRow}>
                  <TextInput
                    style={styles.qtyInput}
                    value={sportDuration}
                    onChangeText={setSportDuration}
                    keyboardType="number-pad"
                    placeholder="Durée"
                    placeholderTextColor={trackingColors.textMuted}
                  />
                  <Text style={styles.qtyUnit}>min</Text>
                </View>
                <Pressable
                  style={[styles.saveButton, (sportDescription.trim() === '' || savingActivity) && styles.submitButtonDisabled]}
                  onPress={submitSport}
                  disabled={sportDescription.trim() === '' || savingActivity}
                >
                  <Text style={styles.saveButtonText}>Enregistrer la séance</Text>
                </Pressable>
              </View>
            )}

            {current === 'poids' && (
              <View style={styles.sportForm}>
                <View style={styles.stepperRow}>
                  <Pressable style={styles.stepperButton} onPress={() => setWeightKg((w) => Math.max(0, Math.round((w - 0.1) * 10) / 10))}>
                    <Text style={styles.stepperSymbol}>−</Text>
                  </Pressable>
                  <View style={styles.stepperValue}>
                    <Text style={styles.stepperValueText}>{weightKg.toFixed(1).replace('.', ',')}</Text>
                    <Text style={styles.stepperUnit}>KILOS</Text>
                  </View>
                  <Pressable style={styles.stepperButton} onPress={() => setWeightKg((w) => Math.round((w + 0.1) * 10) / 10)}>
                    <Text style={styles.stepperSymbol}>+</Text>
                  </Pressable>
                </View>
                <Pressable style={[styles.saveButton, savingWeight && styles.submitButtonDisabled]} onPress={submitWeight} disabled={savingWeight}>
                  <Text style={styles.saveButtonText}>Enregistrer le poids</Text>
                </Pressable>
              </View>
            )}
          </ScrollView>
        </Animated.View>
      </SafeAreaView>
    </Modal>
  );
}

const styles = StyleSheet.create({
  screen: { flex: 1, backgroundColor: trackingColors.cardWhite },
  header: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
    paddingHorizontal: spacing.lg,
    paddingVertical: spacing.md,
    borderBottomWidth: 1,
    borderBottomColor: trackingColors.border,
  },
  headerLeft: { flexDirection: 'row', alignItems: 'center', gap: spacing.xs },
  backButton: { width: 30, height: 30, alignItems: 'center', justifyContent: 'center' },
  title: { fontWeight: '800', fontSize: 18, color: trackingColors.text },
  closeButton: {
    width: 32,
    height: 32,
    borderRadius: 10,
    backgroundColor: trackingColors.card,
    alignItems: 'center',
    justifyContent: 'center',
  },
  body: { flex: 1 },
  scrollContent: { padding: spacing.lg, paddingBottom: spacing.xl },
  menu: { gap: spacing.md },
  sectionLabel: {
    fontSize: 11,
    fontWeight: '700',
    letterSpacing: 0.4,
    textTransform: 'uppercase',
    color: trackingColors.textMuted,
  },
  mealGrid: { flexDirection: 'row', flexWrap: 'wrap', gap: spacing.sm },
  mealTile: {
    width: '47%',
    gap: 6,
    padding: spacing.sm + 2,
    borderRadius: trackingRadii.chip,
    borderWidth: 1,
    borderColor: trackingColors.border,
  },
  mealTilePrimary: { backgroundColor: trackingColors.primary, borderColor: trackingColors.primary },
  mealTileTitle: { fontWeight: '800', fontSize: 14, color: trackingColors.text },
  mealTileSubtitle: { fontSize: 11, color: trackingColors.textMuted },
  mealTileTitlePrimary: { fontWeight: '800', fontSize: 14, color: '#fff' },
  mealTileSubtitlePrimary: { fontSize: 11, color: 'rgba(255,255,255,0.82)' },
  otherRow: { flexDirection: 'row', gap: spacing.sm },
  otherTile: {
    flex: 1,
    gap: 6,
    padding: spacing.sm + 2,
    borderRadius: trackingRadii.chip,
    borderWidth: 1,
    borderColor: trackingColors.border,
    alignItems: 'center',
  },
  otherTileTitle: { fontWeight: '800', fontSize: 12, color: trackingColors.text },
  gestureRow: { flexDirection: 'row', flexWrap: 'wrap', gap: 6, marginTop: spacing.sm },
  gestureChip: {
    backgroundColor: trackingColors.cardWhite,
    borderWidth: 1,
    borderColor: trackingColors.border,
    borderRadius: 12,
    paddingHorizontal: 13,
    paddingVertical: 9,
    maxWidth: 260,
  },
  gestureChipText: { fontSize: 13, fontWeight: '700', color: trackingColors.text },
  searchRow: { flexDirection: 'row', alignItems: 'center', gap: spacing.sm, marginTop: spacing.sm },
  searchInput: {
    flex: 1,
    backgroundColor: trackingColors.card,
    borderWidth: 1,
    borderColor: trackingColors.border,
    borderRadius: trackingRadii.chip,
    paddingHorizontal: spacing.md,
    paddingVertical: spacing.sm,
    fontSize: 15,
    color: trackingColors.text,
  },
  submitButton: {
    width: 44,
    height: 44,
    borderRadius: trackingRadii.chip,
    backgroundColor: trackingColors.primary,
    alignItems: 'center',
    justifyContent: 'center',
  },
  submitButtonDisabled: { backgroundColor: trackingColors.border },
  // Carte "quantité" de l'aliment sélectionné (recherche "aliment") — dimensions
  // volontairement plus généreuses que `qtyRow`/`qtyInput`/`qtyUnit` ci-dessous (réutilisés
  // tels quels par le formulaire Sport pour la durée), styles dédiés pour ne pas les affecter.
  qtyCard: {
    marginTop: spacing.md,
    alignSelf: 'center',
    width: '100%',
    maxWidth: 420,
    alignItems: 'center',
    gap: spacing.sm,
    padding: spacing.lg,
    backgroundColor: trackingColors.card,
    borderWidth: 1,
    borderColor: trackingColors.border,
    borderRadius: trackingRadii.chip,
  },
  qtyCardRow: { flexDirection: 'row', alignItems: 'center', justifyContent: 'center', gap: spacing.sm },
  qtyCardInput: {
    width: 76,
    backgroundColor: trackingColors.cardWhite,
    borderWidth: 1,
    borderColor: trackingColors.border,
    borderRadius: trackingRadii.chip,
    paddingHorizontal: spacing.sm,
    paddingVertical: spacing.sm,
    fontSize: 20,
    fontWeight: '700',
    color: trackingColors.text,
  },
  qtyCardUnit: { fontSize: 16, fontWeight: '600', color: trackingColors.textMuted },
  qtySummary: { fontSize: 26, fontWeight: '800', color: trackingColors.primary },
  qtyRow: { flexDirection: 'row', alignItems: 'center', gap: spacing.sm },
  qtyInput: {
    width: 70,
    backgroundColor: trackingColors.card,
    borderWidth: 1,
    borderColor: trackingColors.border,
    borderRadius: trackingRadii.chip,
    paddingHorizontal: spacing.sm,
    paddingVertical: spacing.xs,
    fontSize: 14,
    color: trackingColors.text,
  },
  qtyUnit: { fontSize: 13, color: trackingColors.textMuted },
  results: {
    backgroundColor: trackingColors.card,
    borderWidth: 1,
    borderColor: trackingColors.border,
    borderRadius: trackingRadii.chip,
    overflow: 'hidden',
    marginTop: spacing.sm,
  },
  resultsEmpty: { fontSize: 13, color: trackingColors.textMuted, padding: spacing.sm, textAlign: 'center' },
  resultsGroup: { paddingVertical: spacing.xs },
  resultsGroupSeparated: { borderTopWidth: 1, borderTopColor: trackingColors.border },
  resultsGroupLabel: {
    fontSize: 11,
    color: trackingColors.textMuted,
    fontWeight: '700',
    textTransform: 'uppercase',
    letterSpacing: 0.3,
    paddingHorizontal: spacing.md,
    paddingVertical: 4,
  },
  resultRow: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
    gap: spacing.sm,
    paddingHorizontal: spacing.md,
    paddingVertical: spacing.sm,
  },
  resultName: { fontSize: 14, color: trackingColors.text, flex: 1 },
  resultSub: { fontSize: 13, color: trackingColors.textMuted },
  descRow: {
    flexDirection: 'row',
    alignItems: 'center',
    gap: spacing.sm,
    backgroundColor: trackingColors.card,
    borderRadius: trackingRadii.chip,
    borderWidth: 1,
    borderColor: trackingColors.border,
    paddingHorizontal: spacing.md,
    paddingVertical: spacing.sm + 2,
  },
  descInput: { flex: 1, fontSize: 14, color: trackingColors.text },
  drinkGrid: { flexDirection: 'row', flexWrap: 'wrap', gap: spacing.sm },
  drinkTile: {
    width: '47%',
    padding: spacing.sm + 4,
    borderRadius: trackingRadii.chip,
    borderWidth: 1,
    borderColor: trackingColors.border,
  },
  drinkTileTitle: { fontWeight: '800', fontSize: 14, color: trackingColors.text },
  sportForm: { gap: spacing.sm },
  saveButton: {
    alignItems: 'center',
    justifyContent: 'center',
    backgroundColor: trackingColors.primary,
    borderRadius: trackingRadii.chip,
    paddingVertical: 14,
  },
  saveButtonText: { fontSize: 15, fontWeight: '700', color: '#fff' },
  stepperRow: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
    backgroundColor: trackingColors.card,
    borderWidth: 1,
    borderColor: trackingColors.border,
    borderRadius: trackingRadii.chip,
    padding: spacing.md,
  },
  stepperButton: {
    width: 44,
    height: 44,
    borderRadius: trackingRadii.pill,
    backgroundColor: trackingColors.cardWhite,
    alignItems: 'center',
    justifyContent: 'center',
  },
  stepperSymbol: { fontSize: 22, fontWeight: '700', color: trackingColors.text },
  stepperValue: { alignItems: 'center' },
  stepperValueText: { fontSize: 30, fontWeight: '800', color: trackingColors.text },
  stepperUnit: { fontSize: 11, fontWeight: '700', color: trackingColors.textMuted, letterSpacing: 1 },
});
