"use client"; import { useState } from "react"; import { useTranslations } from "next-intl"; import { useRouter } from "next/navigation"; import { Sparkles, Loader2 } from "lucide-react"; import { toast } from "sonner"; import { Button } from "@/components/ui/button"; import { FakeProgressBar } from "@/components/ui/fake-progress-bar"; type GeneratedRecipe = { ingredients: Array<{ rawName: string; quantity?: number; unit?: string; note?: string }>; steps: Array<{ instruction: string; timerSeconds?: number }>; }; export function GenerateContentButton({ recipeId, title, description, }: { recipeId: string; title: string; description?: string | null; }) { const t = useTranslations("ai.generate"); const router = useRouter(); const [busy, setBusy] = useState(false); async function generate() { setBusy(true); try { const prompt = description?.trim() ? `${title}: ${description.trim()}` : title; const genRes = await fetch("/api/v1/ai/generate", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ prompt }), }); if (!genRes.ok) { toast.error(t("contentGenerateFailed")); return; } const generated = await genRes.json() as GeneratedRecipe; const saveRes = await fetch(`/api/v1/recipes/${recipeId}`, { method: "PUT", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ ingredients: generated.ingredients.map((ing, i) => ({ rawName: ing.rawName, quantity: ing.quantity, unit: ing.unit, note: ing.note, order: i, })), steps: generated.steps.map((s, i) => ({ instruction: s.instruction, timerSeconds: s.timerSeconds, order: i, })), }), }); if (!saveRes.ok) { toast.error(t("contentSaveFailed")); return; } toast.success(t("contentGenerated")); router.refresh(); } finally { setBusy(false); } } return (
); }