import { useEffect, useState } from 'react';
import { View, Text, StyleSheet, Pressable, TextInput, Modal, ActivityIndicator, ScrollView, Image } from 'react-native';
import Ionicons from '@expo/vector-icons/Ionicons';
import {
  AnalyzedIngredient,
  BarcodeProduct,
  PhotoAnalysisResult,
  PortionOption,
  TrackingSummary,
  addEntryWithPhoto,
  analyzeDescription,
  analyzePhoto,
  correctPhotoAnalysis,
  lookupBarcode,
  savePortionPreference,
} from '../../../api/tracking';
import { ProductCard } from '../../../components/ProductCard';
import { ScanCameraView } from '../../../components/ScanCameraView';
import { colors, spacing, radii, typography } from '../../../theme';
import { suggestCategory } from '../utils/category';
import { scaleIngredientQuantity, sumIngredientMacros } from '../utils/ingredients';
import { AnalyzingOverlay } from './AnalyzingOverlay';
import { CategoryPickerField } from './CategoryPickerField';
import { IngredientRow } from './IngredientRow';

// Toute la logique métier (lookup Open Food Facts, analyse IA, calcul du volume d'eau,
// stockage de la photo) reste côté Symfony — voir `mobile/src/api/tracking.ts` et
// `Api\V1\TrackingController`. Ce composant ne fait que capturer/afficher.
//
// Deux modes explicites et étanches (demande utilisateur — pas de détection auto
// mêlant les deux, contrairement au web historique `initPhotoModal()`) :
// - `barcode` : scan code-barres, lookup Open Food Facts uniquement, jamais d'appel IA.
// - `photo` : prise de photo (ou import galerie), analyse IA uniquement.
// L'écran de capture lui-même (caméra, permission, import galerie) est factorisé
// dans `ScanCameraView`, partagé avec `ProductScanModal` (produits) — même
// interface de scan dans les deux flux.

type Mode = 'barcode' | 'photo';

type Props = {
  visible: boolean;
  onClose: () => void;
  onAdded: (summary: TrackingSummary) => void;
  // Mode choisi par les tuiles "Code-barres"/"Photo IA" de `AddSheet` avant l'ouverture
  // de la modale (cf. TrackingScreen).
  initialMode: Mode;
  // Texte saisi dans la vue "texte" de `AddSheet`, avant même l'ouverture de la
  // modale (cf. TrackingScreen) — si présent, on saute l'écran caméra et on lance
  // directement l'analyse IA du texte, quel que soit `initialMode`.
  initialDescription?: string;
};

type Screen =
  | { kind: 'scan' }
  | { kind: 'looking-up' }
  | { kind: 'product'; product: BarcodeProduct }
  // `message` distingue une première analyse d'une correction à l'écran d'attente
  // (`AnalyzingOverlay`), cf. `analyzePhotoUri()`/`requestCorrection()`/`handleDescribe()`.
  | { kind: 'analyzing'; message: string }
  | { kind: 'ai-result'; photoUri?: string; result: PhotoAnalysisResult }
  | { kind: 'error'; message: string; retry: () => void };

export function PhotoCaptureModal({ visible, onClose, onAdded, initialMode, initialDescription }: Props) {
  const [screen, setScreen] = useState<Screen>({ kind: 'scan' });
  const [mode, setMode] = useState<Mode>(initialMode);
  const [category, setCategory] = useState(suggestCategory());
  const [submitting, setSubmitting] = useState(false);

  useEffect(() => {
    if (visible) {
      setCategory(suggestCategory());
      setMode(initialMode);
      if (initialDescription) {
        handleDescribe(initialDescription);
      } else {
        setScreen({ kind: 'scan' });
      }
    }
  }, [visible, initialMode, initialDescription]);

  async function handleBarcodeFound(data: string) {
    setScreen({ kind: 'looking-up' });

    try {
      const result = await lookupBarcode(data);
      if (result.found) {
        setScreen({ kind: 'product', product: result });
      } else {
        // Pas de fiche Open Food Facts pour ce code — message explicite plutôt qu'un retour
        // silencieux au scan. Jamais de bascule automatique sur l'IA en mode barcode : pour
        // ça, l'utilisateur doit fermer et rouvrir en mode "Prendre une photo".
        setScreen({
          kind: 'error',
          message: 'Produit introuvable sur Open Food Facts.',
          retry: () => setScreen({ kind: 'scan' }),
        });
      }
    } catch (e) {
      setScreen({
        kind: 'error',
        message: e instanceof Error ? e.message : 'Recherche impossible.',
        retry: () => setScreen({ kind: 'scan' }),
      });
    }
  }

  async function analyzePhotoUri(uri: string) {
    setScreen({ kind: 'analyzing', message: "L'IA analyse votre plat…" });
    try {
      const result = await analyzePhoto(uri);
      setScreen({ kind: 'ai-result', photoUri: uri, result });
    } catch (e) {
      setScreen({
        kind: 'error',
        message: e instanceof Error ? e.message : 'Analyse impossible.',
        retry: () => setScreen({ kind: 'scan' }),
      });
    }
  }

  // Ne rejoue l'analyse que sur une photo (`photoUri` requis) — pas de correction pour
  // "Décrire mon plat", qui n'a pas de support visuel sur lequel l'IA pourrait revenir.
  async function requestCorrection(photoUri: string, previousResult: PhotoAnalysisResult, correction: string) {
    setScreen({ kind: 'analyzing', message: "L'IA applique votre correction…" });
    try {
      const result = await correctPhotoAnalysis(photoUri, previousResult, correction);
      setScreen({ kind: 'ai-result', photoUri, result });
    } catch (e) {
      setScreen({
        kind: 'error',
        message: e instanceof Error ? e.message : 'Correction impossible.',
        retry: () => setScreen({ kind: 'ai-result', photoUri, result: previousResult }),
      });
    }
  }

  async function handleDescribe(description: string) {
    setScreen({ kind: 'analyzing', message: "L'IA estime votre plat…" });
    try {
      const result = await analyzeDescription(description);
      setScreen({ kind: 'ai-result', result });
    } catch (e) {
      setScreen({
        kind: 'error',
        message: e instanceof Error ? e.message : 'Estimation impossible.',
        retry: () => handleDescribe(description),
      });
    }
  }

  async function confirmProduct(product: BarcodeProduct, qty: number, portion: PortionOption, remember: boolean) {
    setSubmitting(true);
    try {
      const grams = qty * portion.gramsPerUnit;
      const kcal = Math.round((product.caloriesPer100 * grams) / 100);
      const protein = Math.round((product.proteinPer100 * grams) / 10) / 10;
      const carbs = Math.round((product.carbsPer100 * grams) / 10) / 10;
      const fat = Math.round((product.fatPer100 * grams) / 10) / 10;
      const unit = qty > 1 ? portion.unitNamePlural : portion.unitName;

      if (product.code && remember) {
        await savePortionPreference({
          barcode: product.code,
          unitName: portion.unitName,
          unitNamePlural: portion.unitNamePlural,
          gramsPerUnit: portion.gramsPerUnit,
        }).catch(() => {});
      }

      const summary = await addEntryWithPhoto({
        nom: product.nom,
        kcal,
        protein,
        carbs,
        fat,
        quantite: `${Number.isInteger(qty) ? qty : qty.toFixed(1)} ${unit}`,
        category,
        source: 'photo',
        volumeMl: product.isWater ? grams : undefined,
        barcode: product.code,
      });
      onAdded(summary);
      onClose();
    } catch (e) {
      setScreen({
        kind: 'error',
        message: e instanceof Error ? e.message : 'Ajout impossible.',
        retry: () => setScreen({ kind: 'product', product }),
      });
    } finally {
      setSubmitting(false);
    }
  }

  async function confirmAiResult(
    photoUri: string | undefined,
    result: PhotoAnalysisResult,
    kcal: number,
    protein: number,
    carbs: number,
    fat: number,
    ingredients: AnalyzedIngredient[],
  ) {
    setSubmitting(true);
    try {
      const summary = await addEntryWithPhoto({
        nom: result.nom,
        kcal,
        protein,
        carbs,
        fat,
        category,
        source: 'photo',
        volumeMl: result.volumeMl ?? undefined,
        ingredients,
        photoUri,
      });
      onAdded(summary);
      onClose();
    } catch (e) {
      setScreen({
        kind: 'error',
        message: e instanceof Error ? e.message : 'Ajout impossible.',
        retry: () => setScreen({ kind: 'ai-result', photoUri, result }),
      });
    } finally {
      setSubmitting(false);
    }
  }

  const headerTitle =
    screen.kind === 'scan'
      ? mode === 'barcode' ? 'Scanner un code-barre' : 'Prendre une photo'
      : screen.kind === 'looking-up'
        ? 'Recherche du produit…'
        : screen.kind === 'product'
          ? 'Produit reconnu'
          : screen.kind === 'analyzing'
            ? screen.message
            : screen.kind === 'ai-result'
              ? 'Plat détecté'
              : 'Photo';

  return (
    <Modal visible={visible} animationType="slide" onRequestClose={onClose} presentationStyle="fullScreen">
      <View style={styles.root}>
        <View style={styles.header}>
          <Text style={styles.headerTitle}>{headerTitle}</Text>
          <Pressable onPress={onClose} hitSlop={12}>
            <Ionicons name="close" size={24} color={colors.text} />
          </Pressable>
        </View>

        {screen.kind === 'scan' && (
          <ScanCameraView
            mode={mode}
            onBarcodeFound={handleBarcodeFound}
            onPhotoCaptured={analyzePhotoUri}
            photoHint="Photographiez votre plat, ou importez une photo"
            permissionDeniedText={
              mode === 'barcode'
                ? "L'accès à la caméra est nécessaire pour scanner un code-barre."
                : "L'accès à la caméra est nécessaire pour photographier votre plat."
            }
          />
        )}

        {screen.kind === 'looking-up' && (
          <View style={styles.center}>
            <ActivityIndicator color={colors.primary} size="large" />
            <Text style={styles.loadingText}>Recherche du produit…</Text>
          </View>
        )}

        {screen.kind === 'analyzing' && <AnalyzingOverlay message={screen.message} />}

        {screen.kind === 'error' && (
          <View style={styles.center}>
            <Ionicons name="alert-circle-outline" size={40} color={colors.danger} />
            <Text style={styles.errorText}>{screen.message}</Text>
            <Pressable style={styles.actionButton} onPress={screen.retry}>
              <Text style={styles.actionButtonText}>Réessayer</Text>
            </Pressable>
          </View>
        )}

        {screen.kind === 'product' && (
          <ProductResultView
            product={screen.product}
            category={category}
            onCategoryChange={setCategory}
            submitting={submitting}
            onConfirm={(qty, portion, remember) => confirmProduct(screen.product, qty, portion, remember)}
          />
        )}

        {screen.kind === 'ai-result' && (
          <AiResultView
            photoUri={screen.photoUri}
            result={screen.result}
            category={category}
            onCategoryChange={setCategory}
            submitting={submitting}
            onConfirm={(kcal, protein, carbs, fat, ingredients) =>
              confirmAiResult(screen.photoUri, screen.result, kcal, protein, carbs, fat, ingredients)
            }
            onRequestCorrection={
              screen.photoUri
                ? (correction, ingredients, kcal, protein, carbs, fat) =>
                    requestCorrection(screen.photoUri!, { ...screen.result, ingredients, kcal, protein, carbs, fat }, correction)
                : undefined
            }
          />
        )}
      </View>
    </Modal>
  );
}

function Macro({ label, value, color }: { label: string; value: string; color: string }) {
  return (
    <View style={styles.macro}>
      <Text style={[styles.macroValue, { color }]}>{value}</Text>
      <Text style={styles.caption}>{label}</Text>
    </View>
  );
}

// Produit Open Food Facts trouvé via son code-barres — les macros sont pour 100 g/mL,
// recalculées localement à chaque changement de quantité/portion, à l'identique de
// `renderProductResult()` dans `tracking.js` (aucune règle de calcul dupliquée pour
// autant : ce sont les mêmes multiplications simples que le calcul serveur ferait sur
// les mêmes valeurs `caloriesPer100`/`gramsPerUnit` renvoyées par Symfony).
function ProductResultView({
  product,
  category,
  onCategoryChange,
  submitting,
  onConfirm,
}: {
  product: BarcodeProduct;
  category: string;
  onCategoryChange: (value: string) => void;
  submitting: boolean;
  onConfirm: (qty: number, portion: PortionOption, remember: boolean) => void;
}) {
  const [qty, setQty] = useState(String(product.defaultQty));
  const [portion, setPortion] = useState<PortionOption>({
    label: product.portionLabel,
    unitName: product.unitName,
    unitNamePlural: product.unitNamePlural,
    gramsPerUnit: product.gramsPerUnit,
    defaultQty: product.defaultQty,
  });
  const [activeOptionIdx, setActiveOptionIdx] = useState(0);
  const [portionPanelOpen, setPortionPanelOpen] = useState(false);
  const [unitNameDraft, setUnitNameDraft] = useState(product.unitName);
  const [gramsDraft, setGramsDraft] = useState(String(product.gramsPerUnit));
  const [remember, setRemember] = useState(true);

  const qtyNumber = parseFloat(qty.replace(',', '.')) || 0;
  const grams = qtyNumber * portion.gramsPerUnit;
  const kcal = Math.round((product.caloriesPer100 * grams) / 100);
  const protein = Math.round((product.proteinPer100 * grams) / 10) / 10;
  const carbs = Math.round((product.carbsPer100 * grams) / 10) / 10;
  const fat = Math.round((product.fatPer100 * grams) / 10) / 10;
  const unit = qtyNumber > 1 ? portion.unitNamePlural : portion.unitName;

  function applyPortionEdit(nextUnitName: string, nextGrams: string) {
    const parsedGrams = parseFloat(nextGrams.replace(',', '.'));
    setPortion((p) => ({
      ...p,
      unitName: nextUnitName.trim() || p.unitName,
      unitNamePlural: nextUnitName.trim() || p.unitNamePlural,
      gramsPerUnit: Number.isFinite(parsedGrams) && parsedGrams > 0 ? parsedGrams : p.gramsPerUnit,
    }));
  }

  return (
    <ScrollView contentContainerStyle={styles.resultBody}>
      <ProductCard product={product} />

      <CategoryPickerField category={category} onChange={onCategoryChange} />

      {product.portionOptions && product.portionOptions.length > 0 && (
        <View style={styles.chipRow}>
          {product.portionOptions.map((opt, idx) => (
            <Pressable
              key={opt.label}
              style={[styles.portionChip, idx === activeOptionIdx && styles.portionChipActive]}
              onPress={() => {
                setActiveOptionIdx(idx);
                setPortion(opt);
                setQty(String(opt.defaultQty));
                setUnitNameDraft(opt.unitName);
                setGramsDraft(String(opt.gramsPerUnit));
              }}
            >
              <Text style={[styles.portionChipText, idx === activeOptionIdx && styles.portionChipTextActive]}>{opt.label}</Text>
            </Pressable>
          ))}
        </View>
      )}

      <View style={styles.qtyRow}>
        <Text style={styles.label}>Quantité</Text>
        <TextInput style={styles.qtyInput} value={qty} onChangeText={setQty} keyboardType="numeric" />
        <Text style={styles.qtyUnit}>{unit}</Text>
      </View>

      <Pressable onPress={() => setPortionPanelOpen((v) => !v)}>
        <Text style={styles.linkText}>Corriger la portion</Text>
      </Pressable>

      {portionPanelOpen && (
        <View style={styles.portionPanel}>
          <View style={styles.portionPanelRow}>
            <Text style={styles.body}>1</Text>
            <TextInput
              style={styles.portionUnitInput}
              value={unitNameDraft}
              onChangeText={(v) => {
                setUnitNameDraft(v);
                applyPortionEdit(v, gramsDraft);
              }}
            />
            <Text style={styles.body}>=</Text>
            <TextInput
              style={styles.portionGramsInput}
              value={gramsDraft}
              keyboardType="numeric"
              onChangeText={(v) => {
                setGramsDraft(v);
                applyPortionEdit(unitNameDraft, v);
              }}
            />
            <Text style={styles.body}>g</Text>
          </View>
          <Pressable style={styles.rememberRow} onPress={() => setRemember((v) => !v)}>
            <Ionicons name={remember ? 'checkbox' : 'square-outline'} size={18} color={colors.primary} />
            <Text style={styles.body}>Se souvenir de cette portion pour ce produit</Text>
          </Pressable>
        </View>
      )}

      <Text style={styles.label}>Pour cette quantité</Text>
      <View style={styles.macrosRow}>
        <Macro label="Calories" value={`${kcal} kcal`} color={colors.success} />
        <Macro label="Protéines" value={`${protein} g`} color="#6366f1" />
        <Macro label="Glucides" value={`${carbs} g`} color="#f59e0b" />
        <Macro label="Lipides" value={`${fat} g`} color="#f43f5e" />
      </View>

      <Pressable
        style={[styles.addButton, (submitting || qtyNumber <= 0) && styles.addButtonDisabled]}
        disabled={submitting || qtyNumber <= 0}
        onPress={() => onConfirm(qtyNumber, portion, remember)}
      >
        <Text style={styles.addButtonText}>Ajouter au suivi</Text>
      </Pressable>
    </ScrollView>
  );
}

// Résultat d'analyse IA (photo) — ingrédients retirables, calories corrigibles avant
// ajout, à l'identique de `renderResult()` dans `tracking.js`.
function AiResultView({
  photoUri,
  result,
  category,
  onCategoryChange,
  submitting,
  onConfirm,
  onRequestCorrection,
}: {
  photoUri?: string;
  result: PhotoAnalysisResult;
  category: string;
  onCategoryChange: (value: string) => void;
  submitting: boolean;
  onConfirm: (kcal: number, protein: number, carbs: number, fat: number, ingredients: AnalyzedIngredient[]) => void;
  // Absent quand il n'y a pas de photo (résultat venant de "Décrire mon plat") — dans ce
  // cas la section de correction n'est pas affichée, cf. `requestCorrection()`.
  onRequestCorrection?: (
    correction: string,
    ingredients: AnalyzedIngredient[],
    kcal: number,
    protein: number,
    carbs: number,
    fat: number,
  ) => void;
}) {
  const [ingredients, setIngredients] = useState(result.ingredients);
  const [kcal, setKcal] = useState(String(result.kcal));
  const [protein, setProtein] = useState(result.protein);
  const [carbs, setCarbs] = useState(result.carbs);
  const [fat, setFat] = useState(result.fat);
  const [correctionOpen, setCorrectionOpen] = useState(false);
  const [correction, setCorrection] = useState('');

  // Resynchronise le total affiché (kcal + macros) avec la nouvelle liste
  // d'ingrédients à chaque modification (quantité changée, ingrédient retiré) — voir
  // `sumIngredientMacros()`. Ne recalcule que si la liste n'est pas vide : un plat
  // sans ingrédient détaillé (ex. après avoir tout retiré) garde son dernier total
  // connu plutôt que de retomber à 0, l'utilisateur pouvant toujours le retaper à la main.
  function applyIngredients(next: AnalyzedIngredient[]) {
    setIngredients(next);
    if (next.length === 0) return;
    const totals = sumIngredientMacros(next);
    setKcal(String(Math.round(totals.kcal)));
    setProtein(Math.round(totals.protein * 10) / 10);
    setCarbs(Math.round(totals.carbs * 10) / 10);
    setFat(Math.round(totals.fat * 10) / 10);
  }

  function removeIngredient(idx: number) {
    applyIngredients(ingredients.filter((_, i) => i !== idx));
  }

  function submitCorrection() {
    if (correction.trim() === '') return;
    onRequestCorrection?.(correction.trim(), ingredients, parseInt(kcal, 10) || result.kcal, protein, carbs, fat);
    setCorrection('');
    setCorrectionOpen(false);
  }

  return (
    <ScrollView contentContainerStyle={styles.resultBody}>
      {photoUri && <Image source={{ uri: photoUri }} style={styles.resultPhoto} />}
      <Text style={styles.resultTitle}>{result.nom}</Text>
      <Text style={styles.resultSub}>Confiance {result.confidence}%</Text>

      <CategoryPickerField category={category} onChange={onCategoryChange} />

      <Text style={styles.label}>Ingrédients identifiés</Text>
      {ingredients.length === 0 && <Text style={styles.body}>Aucun ingrédient</Text>}
      {ingredients.map((ing, idx) => (
        <IngredientRow
          key={`${ing.name}-${idx}`}
          ingredient={ing}
          onChangeQuantity={(quantity) =>
            applyIngredients(ingredients.map((item, i) => (i === idx ? scaleIngredientQuantity(item, quantity) : item)))
          }
          onRemove={() => removeIngredient(idx)}
        />
      ))}

      {onRequestCorrection && (
        <>
          <Pressable style={styles.correctToggle} onPress={() => setCorrectionOpen((v) => !v)}>
            <Ionicons name="sparkles" size={15} color={colors.primary} />
            <Text style={styles.correctToggleText}>Corriger l'analyse de l'IA</Text>
          </Pressable>

          {correctionOpen && (
            <View style={styles.portionPanel}>
              <TextInput
                style={styles.correctionInput}
                value={correction}
                onChangeText={setCorrection}
                placeholder="Ex : ce ne sont pas des champignons mais du maïs"
                placeholderTextColor={colors.textMuted}
                multiline
                autoFocus
              />
              <Pressable
                style={[styles.actionButton, correction.trim() === '' && styles.addButtonDisabled]}
                disabled={correction.trim() === ''}
                onPress={submitCorrection}
              >
                <Text style={styles.actionButtonText}>Redemander à l'IA</Text>
              </Pressable>
            </View>
          )}
        </>
      )}

      <View style={styles.qtyRow}>
        <Text style={styles.label}>Calories estimées</Text>
        <TextInput style={styles.qtyInput} value={kcal} onChangeText={setKcal} keyboardType="numeric" />
        <Text style={styles.qtyUnit}>kcal</Text>
      </View>

      <View style={styles.macrosRow}>
        <Macro label="Protéines" value={`${protein} g`} color="#6366f1" />
        <Macro label="Glucides" value={`${carbs} g`} color="#f59e0b" />
        <Macro label="Lipides" value={`${fat} g`} color="#f43f5e" />
      </View>

      <Pressable
        style={[styles.addButton, submitting && styles.addButtonDisabled]}
        disabled={submitting}
        onPress={() => onConfirm(parseInt(kcal, 10) || result.kcal, protein, carbs, fat, ingredients)}
      >
        <Text style={styles.addButtonText}>Ajouter au suivi</Text>
      </Pressable>
    </ScrollView>
  );
}

const styles = StyleSheet.create({
  root: { flex: 1, backgroundColor: colors.background },
  header: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
    paddingHorizontal: spacing.lg,
    paddingTop: spacing.lg,
    paddingBottom: spacing.sm,
  },
  headerTitle: { ...typography.body, fontWeight: '700', fontSize: 17, color: colors.text },
  center: { flex: 1, alignItems: 'center', justifyContent: 'center', gap: spacing.md, padding: spacing.xl },
  actionButton: { backgroundColor: colors.primary, borderRadius: radii.md, paddingHorizontal: spacing.lg, paddingVertical: spacing.sm },
  actionButtonText: { ...typography.body, color: '#fff', fontWeight: '700' },
  loadingText: { ...typography.body, color: colors.textMuted },
  errorText: { ...typography.body, color: colors.text, textAlign: 'center' },
  resultBody: { padding: spacing.lg, gap: spacing.sm },
  resultPhoto: { width: '100%', aspectRatio: 1.4, borderRadius: radii.lg, marginBottom: spacing.xs },
  resultTitle: { ...typography.title, fontSize: 20, color: colors.text },
  resultSub: { ...typography.caption, color: colors.textMuted, marginBottom: spacing.xs },
  chipRow: { flexDirection: 'row', flexWrap: 'wrap', gap: spacing.xs },
  portionChip: {
    borderWidth: 1,
    borderColor: colors.border,
    borderRadius: radii.pill,
    paddingHorizontal: spacing.md,
    paddingVertical: spacing.xs,
  },
  portionChipActive: { backgroundColor: colors.primary, borderColor: colors.primary },
  portionChipText: { ...typography.caption, color: colors.text, fontWeight: '600' },
  portionChipTextActive: { color: '#fff' },
  qtyRow: { flexDirection: 'row', alignItems: 'center', gap: spacing.sm, marginTop: spacing.xs },
  qtyInput: {
    width: 90,
    borderWidth: 1,
    borderColor: colors.border,
    borderRadius: radii.md,
    paddingHorizontal: spacing.sm,
    paddingVertical: spacing.xs,
    ...typography.body,
    fontSize: 14,
    color: colors.text,
  },
  qtyUnit: { ...typography.caption, color: colors.textMuted, marginLeft: 'auto' },
  linkText: { ...typography.caption, color: colors.primary, fontWeight: '700' },
  correctToggle: {
    flexDirection: 'row',
    alignItems: 'center',
    alignSelf: 'flex-start',
    gap: 6,
    marginTop: spacing.xs,
    paddingHorizontal: spacing.md,
    paddingVertical: spacing.xs + 2,
    borderRadius: radii.pill,
    backgroundColor: colors.primary + '1a',
    borderWidth: 1,
    borderColor: colors.primary,
  },
  correctToggleText: { ...typography.caption, color: colors.primary, fontWeight: '700', fontSize: 13 },
  portionPanel: { gap: spacing.sm, backgroundColor: colors.card, borderRadius: radii.md, padding: spacing.sm, borderWidth: 1, borderColor: colors.border },
  portionPanelRow: { flexDirection: 'row', alignItems: 'center', gap: spacing.xs },
  portionUnitInput: {
    flex: 1,
    borderWidth: 1,
    borderColor: colors.border,
    borderRadius: radii.sm,
    paddingHorizontal: spacing.sm,
    paddingVertical: 4,
    ...typography.body,
    fontSize: 14,
    color: colors.text,
  },
  portionGramsInput: {
    width: 70,
    borderWidth: 1,
    borderColor: colors.border,
    borderRadius: radii.sm,
    paddingHorizontal: spacing.sm,
    paddingVertical: 4,
    ...typography.body,
    fontSize: 14,
    color: colors.text,
  },
  rememberRow: { flexDirection: 'row', alignItems: 'center', gap: spacing.xs },
  correctionInput: {
    borderWidth: 1,
    borderColor: colors.border,
    borderRadius: radii.sm,
    paddingHorizontal: spacing.sm,
    paddingVertical: spacing.sm,
    ...typography.body,
    fontSize: 14,
    color: colors.text,
    minHeight: 60,
    textAlignVertical: 'top',
  },
  label: { ...typography.caption, color: colors.textMuted, fontWeight: '700', letterSpacing: 0.3 },
  macrosRow: { flexDirection: 'row', justifyContent: 'space-between', marginTop: spacing.sm },
  macro: { alignItems: 'center', gap: 2 },
  macroValue: { ...typography.body, fontWeight: '700', fontSize: 15 },
  caption: { ...typography.caption, color: colors.textMuted },
  body: { ...typography.body, fontSize: 14, color: colors.text },
  addButton: { backgroundColor: colors.primary, borderRadius: radii.md, paddingVertical: spacing.sm + 2, alignItems: 'center', marginTop: spacing.md },
  addButtonDisabled: { backgroundColor: colors.border },
  addButtonText: { ...typography.body, color: '#fff', fontWeight: '700' },
});
