import { useState, useEffect, useRef } from 'react' import { api } from '../api' const MEALS = ['breakfast', 'lunch', 'dinner', 'snack'] export default function LogFood() { const [tab, setTab] = useState('log') // log, scan, search const [mealType, setMealType] = useState('lunch') const [foodName, setFoodName] = useState('') const [brand, setBrand] = useState('') const [calories, setCalories] = useState('') const [protein, setProtein] = useState('') const [carbs, setCarbs] = useState('') const [fat, setFat] = useState('') const [servings, setServings] = useState('1') const [barcode, setBarcode] = useState('') const [searchQuery, setSearchQuery] = useState('') const [searchResults, setSearchResults] = useState([]) const [todayFood, setTodayFood] = useState(null) const [loading, setLoading] = useState(false) const [success, setSuccess] = useState('') useEffect(() => { loadToday() }, []) async function loadToday() { try { const today = new Date().toISOString().split('T')[0] const data = await api.listFood(today) setTodayFood(data) } catch (err) { console.error(err) } } function fillFromProduct(product) { setFoodName(product.product_name || '') setBrand(product.brand || '') setCalories(product.calories_100g ? String(Math.round(product.calories_100g)) : '') setProtein(product.protein_100g ? String(Math.round(product.protein_100g)) : '') setCarbs(product.carbs_100g ? String(Math.round(product.carbs_100g)) : '') setFat(product.fat_100g ? String(Math.round(product.fat_100g)) : '') setTab('log') } async function handleScan() { if (!barcode.trim()) return setLoading(true) try { const product = await api.scanBarcode(barcode.trim()) fillFromProduct(product) } catch (err) { alert('Product not found. Try manual entry.') } finally { setLoading(false) } } async function handleSearch() { if (!searchQuery.trim()) return setLoading(true) try { const data = await api.searchFood(searchQuery) setSearchResults(data.results || []) } catch (err) { alert(err.message) } finally { setLoading(false) } } async function handleLog(e) { e.preventDefault() if (!foodName.trim()) return setLoading(true) try { const today = new Date().toISOString().split('T')[0] await api.logFood({ meal_type: mealType, food_name: foodName, brand: brand || null, calories: calories ? parseFloat(calories) * parseFloat(servings || 1) : null, protein_g: protein ? parseFloat(protein) * parseFloat(servings || 1) : null, carbs_g: carbs ? parseFloat(carbs) * parseFloat(servings || 1) : null, fat_g: fat ? parseFloat(fat) * parseFloat(servings || 1) : null, servings: parseFloat(servings || 1), food_date: today, }) setSuccess('Food logged!') setFoodName(''); setBrand(''); setCalories(''); setProtein(''); setCarbs(''); setFat(''); setServings('1') await loadToday() setTimeout(() => setSuccess(''), 2000) } catch (err) { alert(err.message) } finally { setLoading(false) } } return (

Food Log

{success &&
{success}
} {/* Tab bar */}
{/* Barcode scan */} {tab === 'scan' && (
setBarcode(e.target.value)} placeholder="Enter or scan barcode" inputMode="numeric" />

Powered by Open Food Facts (4M+ products)

)} {/* Food search */} {tab === 'search' && (
setSearchQuery(e.target.value)} placeholder="Search foods..." onKeyDown={e => e.key === 'Enter' && handleSearch()} />
{searchResults.map((r, i) => (
fillFromProduct(r)}>
{r.product_name || 'Unknown'}
{r.brand && `${r.brand} ยท `}{r.calories_100g ? `${Math.round(r.calories_100g)} cal/100g` : ''}
))}
)} {/* Manual log form */} {tab === 'log' && (
{MEALS.map(m => ( ))}
setFoodName(e.target.value)} placeholder="e.g. Grilled chicken breast" required />
setBrand(e.target.value)} placeholder="" />
setCalories(e.target.value)} placeholder="per serving" />
setServings(e.target.value)} />
setProtein(e.target.value)} />
setCarbs(e.target.value)} />
setFat(e.target.value)} />
)} {/* Today's summary */} {todayFood && (
Today: {Math.round(todayFood.total_calories)} cal
{MEALS.map(m => { const items = todayFood.meals[m] || [] if (items.length === 0) return null return (
{m}
{items.map(item => (
{item.food_name} {item.calories ? `${Math.round(item.calories)} cal` : ''}
))}
) })}
)}
) }