"use client"; import { useState } from "react"; import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"; import { Button } from "@/components/ui/button"; type NutritionData = { perServing: { calories: number; proteinG: number; carbsG: number; fatG: number; fiberG: number; sodiumMg: number; }; }; interface NutritionPanelProps { recipeId: string; initialData?: NutritionData | null; } export function NutritionPanel({ recipeId, initialData }: NutritionPanelProps) { const [nutrition, setNutrition] = useState(initialData ?? null); const [loading, setLoading] = useState(false); const [error, setError] = useState(null); async function handleEstimate() { setLoading(true); setError(null); try { const res = await fetch(`/api/v1/recipes/${recipeId}/nutrition`, { method: "POST", }); if (!res.ok) { const body = await res.json() as { error?: string }; throw new Error(body.error ?? "Failed to estimate nutrition"); } const data = await res.json() as { nutrition: NutritionData }; setNutrition(data.nutrition); } catch (err) { setError(err instanceof Error ? err.message : "Something went wrong"); } finally { setLoading(false); } } if (!nutrition && !loading) { return (
{error &&

{error}

}
); } return (
Nutrition per serving
{error &&

{error}

}
{nutrition && (
{Math.round(nutrition.perServing.calories)} kcal
)} {loading && !nutrition && (

Estimating nutrition…

)}
); } function MacroCell({ label, value, unit, }: { label: string; value: number; unit: string; }) { return (
{label} {Math.round(value)} {unit}
); }