"use client"; /* eslint-disable @next/next/no-img-element -- generated image URLs, not optimisable */ import { withBase } from "@/lib/base-path"; import { useState } from "react"; import Link from "next/link"; import { Icon } from "./Icon"; import { Notice } from "./ui"; import { IMAGE_PROMPT_MAX, IMAGE_SIZES, type ImageSizeKey } from "@/lib/ai/image-shared"; // (server-only helpers live in lib/ai/image.ts — never import that file here) async function post(body: Record): Promise<{ ok: true; data: Record } | { ok: false; error: string }> { const res = await fetch(withBase("/api/ai/image"), { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body), }).catch(() => null); const data = res ? await res.json().catch(() => ({})) : {}; if (!res?.ok) return { ok: false, error: (data.error as string) ?? "AI ทำงานไม่สำเร็จ ลองใหม่อีกครั้ง" }; return { ok: true, data }; } /** * Two explicit steps: AI drafts an image prompt the user can edit, then a * second press makes the image. The chosen image only fills the editor — * saving and approval stay exactly as for an uploaded picture. */ export function ImageAssistant({ pageId, initialIdea, hasImage, onUse, }: { pageId: string; initialIdea: string; hasImage: boolean; onUse: (url: string) => void; }) { const [hasPrompt, setHasPrompt] = useState(false); const [open, setOpen] = useState(false); const [idea, setIdea] = useState(""); const [prompt, setPrompt] = useState(""); const [size, setSize] = useState("square"); const [result, setResult] = useState(null); const [busy, setBusy] = useState<"prompt" | "generate" | null>(null); const [error, setError] = useState(null); const [profileMissing, setProfileMissing] = useState(false); async function draftPrompt() { setBusy("prompt"); setError(null); const r = await post({ action: "prompt", pageId, description: idea }); setBusy(null); if (!r.ok) return setError(r.error); setPrompt(String(r.data.prompt ?? "")); setHasPrompt(true); setProfileMissing(Boolean(r.data.profileMissing)); } async function makeImage() { setBusy("generate"); setError(null); const r = await post({ action: "generate", pageId, prompt, size }); setBusy(null); if (!r.ok) return setError(r.error); setResult(String(r.data.url ?? "")); } if (!open) { return ( ); } return (
ให้ AI สร้างรูป