import { useEffect, useMemo, useState } from 'react'; import { Alert, Linking, Platform, Pressable, StyleSheet, Text, View } from 'react-native'; import PrimaryButton from '../components/PrimaryButton'; import SecondaryButton from '../components/SecondaryButton'; import AppHeader from '../components/layout/AppHeader'; import ScreenContainer from '../components/layout/ScreenContainer'; import SectionTitle from '../components/layout/SectionTitle'; import ProductImage from '../components/product/ProductImage'; import ProductScoreBadge from '../components/product/ProductScoreBadge'; import RatingCategoryRow from '../components/product/RatingCategoryRow'; import { calculateProductRating } from '../services/ratingService'; import { alternativeSearchIssue, findAlternatives } from '../services/alternativesService'; import { colors } from '../utils/constants'; export default function ProductDetailScreen({ product, preferences, onBack, onAddToList, onOpenList, onEditProduct, onShowRatingCriteria, onShowAlternatives, onOpenProduct, productCache, shoppingList, dailyLog, onRecordConsumption }) { const [savedMessage, setSavedMessage] = useState(''); const [suggestions, setSuggestions] = useState([]); const [suggestionsLoading, setSuggestionsLoading] = useState(true); const [suggestionsError, setSuggestionsError] = useState(false); const rating = useMemo(() => calculateProductRating(product, preferences, { shoppingList, dailyLog }), [product, preferences, shoppingList, dailyLog]); const footprint = product.sustainability?.footprint; const missingFields = missingProductFields(product, preferences); const recommendation = rating.overallStatus === 'good' ? 'Passt gut zu dir' : rating.overallStatus === 'critical' ? 'Lieber meiden' : rating.overallStatus === 'unknown' ? 'Zu wenig Daten' : 'Genauer prüfen'; useEffect(() => { let active = true; setSuggestionsLoading(true); setSuggestionsError(false); findAlternatives(product, preferences, productCache, { dailyLog }, { preview: true }) .then((results) => { if (active) setSuggestions(results); }) .catch(() => { if (active) { setSuggestions([]); setSuggestionsError(true); } }) .finally(() => { if (active) setSuggestionsLoading(false); }); return () => { active = false; }; }, [product, preferences, productCache, dailyLog]); function addToList() { if (rating.hasBlockedAllergen) { setSavedMessage('Dieses Produkt enthält ein Allergen aus deinem Profil und wurde nicht hinzugefügt.'); return; } if (rating.allergenReviewRequired) { const message = 'Die App kann Allergenfreiheit nicht bestätigen. Prüfe Zutaten und Spurenhinweise auf der Verpackung, bevor du das Produkt hinzufügst.'; if (Platform.OS === 'web') { if (window.confirm(`${message}\n\nVerpackung geprüft und trotzdem hinzufügen?`)) saveToList(); return; } Alert.alert('Allergene prüfen', message, [ { text: 'Abbrechen', style: 'cancel' }, { text: 'Verpackung geprüft', onPress: saveToList } ]); return; } saveToList(); } function saveToList() { onAddToList(product); setSavedMessage('Zur Einkaufsliste hinzugefügt.'); } return ( {product.brand || 'Ohne Marke'} {product.name} {product.category || 'Produkt'} {sourceLabel(product.dataSource)}{product.cacheStale ? ' · Veraltete Daten' : ''} {product.manualOverrides ? Angaben von dir ergänzt · lokal gespeichert : null} {product.manualOverrides ? Etikettangaben: {manualFieldNames(product.manualOverrides).join(', ') || 'Produkttyp'} : null} {['cache', 'open-food-facts'].includes(product.dataSource) ? Produktdaten geprüft: {formatCheckedDate(product.fetchedAt)} : null} {recommendation} {recommendationMessage(rating)} Bewertbare Daten: {rating.dataCoverage}% der für dein Profil anwendbaren Kriterien (gewichtet). {rating.mainFactors.length > 0 || rating.scoreLimitReasons.length > 0 ? ( Das beeinflusst die Bewertung {rating.mainFactors.map((factor) => ( {factor.label} {factor.score}/100 {factor.message} ))} {rating.scoreLimitReasons.length > 0 ? Bitte beachten {rating.scoreLimitReasons.map((reason) => • {reason})} : null} ) : null} Produktangaben ergänzen {missingFields.length ? `Für eine genauere Bewertung fehlen: ${missingFields.join(', ')}.` : 'Die wichtigsten Angaben für die Bewertung sind vorhanden.'} Übertrage Werte von der Verpackung. Fehlende Werte werden nicht geschätzt. onEditProduct(product)} /> {/^\d{8,14}$/.test(product.barcode || '') ? ( Linking.openURL(`https://ch.openfoodfacts.org/product/${product.barcode}`)}> Produkt auf Open Food Facts öffnen › ) : null} {savedMessage ? ( {savedMessage} Einkaufsliste ansehen › ) : null} { onRecordConsumption(product); setSavedMessage('Portion im Tagesprotokoll erfasst.'); }} /> Es wird die angegebene Portionsgrösse verwendet, sonst die Packungsmenge oder 100 g. Nur tatsächlich Gegessenes erfassen. Ähnliche, bessere Alternativen {suggestionsLoading ? Passende Produkte werden gesucht ... : null} {!suggestionsLoading && suggestions.length === 0 ? {suggestionsError ? 'Alternativen konnten gerade nicht geladen werden.' : alternativeSearchIssue(product, rating) || 'Unter den geprüften Treffern war keine belegbar bessere Alternative derselben Produktart.'} : null} {suggestions.map((item) => onOpenProduct(item.product)} style={styles.suggestionCard}> {item.product.name} {item.reason} Produkt ansehen › )} onShowAlternatives(product)} /> Bewertungskriterien {Object.entries(rating.categoryScores).map(([category, categoryRating]) => ( onShowRatingCriteria(product, category)} rating={categoryRating} /> ))} Umweltwirkung {footprint?.status === 'product-specific' || footprint?.status === 'estimated' ? ( <> CO₂-Fussabdruck: {formatImpact(footprint.valueKgCo2ePerKg)} kg CO₂e/kg {footprint.status === 'product-specific' ? 'Produktspezifische Angabe aus Open Food Facts.' : `Schätzung anhand vergleichbarer Lebensmittel: ${footprint.referenceCategory}. AGRIBALYSE-Durchschnitt, keine Messung dieses Markenprodukts.`} {typeof footprint.packageKgCo2e === 'number' ? ( Für {formatImpact(footprint.packageQuantityGrams, 0)} g Packungsinhalt: ca. {formatImpact(footprint.packageKgCo2e)} kg CO₂e ) : null} Quelle: {footprint.source === 'AGRIBALYSE' ? 'ADEME / ' : ''}{footprint.source}{footprint.datasetVersion ? ` ${footprint.datasetVersion}` : ''} {footprint.datasetUpdatedAt ? ` · Datenstand ${footprint.datasetUpdatedAt.slice(0, 10)}` : ''} {footprint.sourceUpdatedAt ? ` · OFF-Stand ${footprint.sourceUpdatedAt.slice(0, 10)}` : ''} {footprint.sourceId ? ` · Kennung ${footprint.sourceId}` : ''} {footprint.matchMethod ? ` · Zuordnung: ${matchLabel(footprint.matchMethod)}` : ''} {footprint.status === 'estimated' ? ( <> Landnutzung: {formatIndicator(footprint.indicators?.landUse)} Wasserknappheit: {formatIndicator(footprint.indicators?.waterScarcity)} Gesamtwirkung (EF): {formatIndicator(footprint.indicators?.singleScore)} Lebenszyklus bis zum verzehrbaren Lebensmittel; Transport und Verpackung sind im Datensatz enthalten. Diese Indikatoren sind keine CO₂-Werte. ) : null} ) : CO₂-Fussabdruck: Nicht verfügbar.} Green-Score (Open Food Facts): {product.sustainability?.ecoScore || 'Nicht verfügbar'} Zutatenherkunft: {ingredientOriginLabel(product)} {(product.sustainability?.sellingCountries || []).length > 0 ? ( Verkaufsländer: {product.sustainability.sellingCountries.map(formatCountryTag).join(', ')} ) : null} Produktdaten Barcode: {product.barcode} Zutaten: {(product.ingredients || []).join(', ') || 'Keine Angaben'} Angegebene Allergene: {(product.allergens || []).join(', ') || 'Keine Angaben'} Mögliche Allergenspuren: {(product.allergenTraces || []).join(', ') || 'Keine Angaben'} Nutri-Score: {rating.categoryScores.nutrition.nutriScore || 'Keine Angabe'} {rating.categoryScores.nutrition.nutriScoreSource === 'calculated' ? ' (von der App berechnet)' : rating.categoryScores.nutrition.nutriScore ? ' (Open Food Facts)' : ''} ); } function recommendationMessage(rating) { if (rating.hasBlockedAllergen) return rating.categoryScores.allergies.message; if (rating.allergenReviewRequired) return rating.allergenReviewMessage; if (rating.goalConflict) return rating.categoryScores.ingredients.message; if (rating.goalReviewRequired) return 'Für dein Ernährungsziel fehlen Angaben. Prüfe die Zutaten oder Nährwerte auf der Verpackung.'; if (rating.staleDataReviewRequired) return 'Gespeicherte Produktdaten sind veraltet. Prüfe vor dem Kauf die Verpackung.'; if (rating.overallStatus === 'unknown') return 'Für eine Empfehlung fehlen belastbare Produktangaben.'; if (rating.limitedByMissingData) return 'Nur ein Teil der Kriterien ist belegt. Die Empfehlung ist deshalb auf „Prüfen“ begrenzt.'; return 'Tippe unten auf ein Kriterium, um die Bewertung nachzuvollziehen.'; } function missingProductFields(product, preferences) { const nutrition = product.nutrition || {}; const fields = []; const beverage = product.categoryTags?.includes('en:beverages') || product.dataSource === 'local'; if (product.dataCompleteness?.name === false) fields.push('Produktname'); if (!product.categoryTags?.length) fields.push('Produkttyp'); if (!product.dataCompleteness?.ingredients) fields.push('Zutatenliste'); if (preferences.avoidAllergens?.length && !product.dataCompleteness?.allergens) fields.push('Allergenangaben'); if (!Number.isFinite(nutrition.sugarPer100g)) fields.push(`Zucker pro ${beverage ? '100 ml' : '100 g'}`); if (!Number.isFinite(nutrition.proteinPer100g)) fields.push('Protein'); if (!Number.isFinite(nutrition.saltPer100g)) fields.push('Salz'); if (!Number.isFinite(nutrition.fiberPer100g)) fields.push('Ballaststoffe'); if (preferences.exerciseGoal === 'endurance' && !Number.isFinite(nutrition.carbohydratesPer100g)) { fields.push(product.cacheStale ? 'Kohlenhydrate im lokalen Cache (online erneut scannen)' : 'Kohlenhydrate'); } if (preferences.preferredDiet === 'vegan' && !Number.isFinite(nutrition.vitaminB12MicrogramsPer100g)) fields.push('Vitamin B12'); if (beverage && !nutrition.nutriScore) { if (!Number.isFinite(nutrition.energyKjPer100g) && !Number.isFinite(nutrition.caloriesPer100g)) fields.push('Energie'); if (!Number.isFinite(nutrition.saturatedFatPer100g)) fields.push('gesättigte Fettsäuren'); if (!Number.isFinite(nutrition.saltPer100g)) fields.push('Salz'); if (typeof nutrition.hasNonNutritiveSweeteners !== 'boolean') fields.push('Süssstoffe'); } return fields.slice(0, 8); } function manualFieldNames(overrides) { const names = { name: 'Name', brand: 'Marke', ingredients: 'Zutaten', allergens: 'Allergene', allergenTraces: 'Spuren', drinkType: 'Produkttyp' }; return [ ...Object.keys(overrides).filter((key) => key !== 'nutrition').map((key) => names[key]).filter(Boolean), ...Object.keys(overrides.nutrition || {}).map((key) => ({ energyKjPer100g: 'Energie', sugarPer100g: 'Zucker', carbohydratesPer100g: 'Kohlenhydrate', vitaminB12MicrogramsPer100g: 'Vitamin B12', saturatedFatPer100g: 'gesättigte Fettsäuren', saltPer100g: 'Salz', proteinPer100g: 'Protein', fiberPer100g: 'Ballaststoffe', fruitVegetableLegumePercent: 'Frucht- und Gemüseanteil', hasNonNutritiveSweeteners: 'Süssstoffe' })[key] ).filter(Boolean) ]; } function sourceLabel(source) { const labels = { cache: 'Quelle: lokaler Cache', local: 'Quelle: lokal erfasst', 'open-food-facts': 'Quelle: Open Food Facts' }; return labels[source] || 'Quelle: unbekannt'; } function formatCheckedDate(value) { const date = new Date(value); return Number.isNaN(date.getTime()) ? 'unbekannt' : date.toLocaleDateString('de-CH'); } function ingredientOriginLabel(product) { const sustainability = product.sustainability || {}; if (['cache', 'open-food-facts'].includes(product.dataSource) && sustainability.originSource !== 'ingredient-origin') return 'Nicht verfügbar'; return sustainability.originCountry || 'Nicht verfügbar'; } function formatCountryTag(tag) { return tag.replace(/^[a-z]{2}:/, '').replace(/-/g, ' '); } function formatImpact(value, maximumFractionDigits = 2) { return new Intl.NumberFormat('de-CH', { maximumFractionDigits, minimumFractionDigits: value < 0.01 ? 3 : 0 }).format(value); } function formatIndicator(indicator) { if (typeof indicator?.value !== 'number') return 'Nicht verfügbar'; return `${new Intl.NumberFormat('de-CH', { maximumSignificantDigits: 3 }).format(indicator.value)} ${indicator.unit}`; } function matchLabel(method) { return { 'off-category-code': 'OFF-Kategoriecode', 'off-category-proxy': 'OFF-Kategorieproxy', 'reviewed-category-map': 'geprüfte Kategoriezuordnung', 'normalized-name-in-category': 'normalisierter Name innerhalb der Kategorie' }[method] || method; } const styles = StyleSheet.create({ suggestionCard: { backgroundColor: colors.surface, borderColor: colors.border, borderRadius: 16, borderWidth: 1, gap: 8, padding: 16 }, suggestionRow: { alignItems: 'flex-start', flexDirection: 'row', gap: 12 }, suggestionBody: { flex: 1, gap: 8 }, suggestionName: { color: colors.text, flex: 1, fontSize: 16, fontWeight: '800' }, suggestionLink: { color: colors.primary, fontSize: 13, fontWeight: '800' }, factorTitle: { color: colors.text, fontSize: 16, fontWeight: '800' }, factorRow: { borderTopColor: colors.border, borderTopWidth: 1, gap: 4, paddingTop: 10 }, factorHeader: { alignItems: 'center', flexDirection: 'row', justifyContent: 'space-between' }, factorLabel: { color: colors.text, fontSize: 14, fontWeight: '800' }, factorScore: { color: colors.primaryDark, fontSize: 13, fontWeight: '800' }, limitPanel: { backgroundColor: '#fff7e8', borderRadius: 12, gap: 5, padding: 12 }, limitTitle: { color: colors.warning, fontSize: 13, fontWeight: '800' }, productPanel: { backgroundColor: colors.surface, borderColor: colors.border, borderRadius: 20, borderWidth: 1, gap: 14, padding: 18 }, topRow: { alignItems: 'flex-start', flexDirection: 'row', gap: 12 }, copy: { flex: 1 }, brand: { color: colors.primary, fontSize: 13, fontWeight: '800', textTransform: 'uppercase' }, name: { color: colors.text, fontSize: 25, fontWeight: '800', lineHeight: 31, marginTop: 4 }, meta: { color: colors.muted, fontSize: 15, marginTop: 6 }, source: { alignSelf: 'flex-start', backgroundColor: '#eef3ef', borderRadius: 8, color: colors.primaryDark, fontSize: 12, fontWeight: '800', marginTop: 10, paddingHorizontal: 8, paddingVertical: 4 }, recommendation: { borderRadius: 14, gap: 4, padding: 14 }, goodRecommendation: { backgroundColor: '#e4f4e9' }, mediumRecommendation: { backgroundColor: '#fff3d7' }, criticalRecommendation: { backgroundColor: '#fee9e7' }, unknownRecommendation: { backgroundColor: '#edf1ee' }, recommendationTitle: { fontSize: 17, fontWeight: '800' }, goodText: { color: colors.success }, mediumText: { color: '#8a5914' }, criticalText: { color: colors.danger }, unknownText: { color: colors.muted }, recommendationCopy: { color: colors.text, fontSize: 13, lineHeight: 19 }, dataPanel: { backgroundColor: colors.surface, borderColor: colors.border, borderRadius: 18, borderWidth: 1, gap: 8, padding: 14 }, dataText: { color: colors.muted, fontSize: 14, lineHeight: 20 }, saved: { color: colors.success, fontSize: 14, fontWeight: '800' }, savedPanel: { backgroundColor: colors.surfaceTint, borderRadius: 14, gap: 6, padding: 14 }, savedLink: { color: colors.primary, fontSize: 14, fontWeight: '800' } });