"use client"; /* eslint-disable @next/next/no-img-element -- generated image URLs, not optimisable */ import { withBase } from "@/lib/base-path"; import { useState, useEffect } 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) type OverlayPos = "top" | "center" | "bottom"; let sarabunFontPromise: Promise | null = null; function loadSarabunFont() { if (!sarabunFontPromise) { const font = new FontFace("Sarabun", `url(${withBase("/fonts/sarabun/Sarabun-Bold.ttf")})`, { weight: "700" }); sarabunFontPromise = font.load().then((loaded) => { document.fonts.add(loaded); return loaded; }); } return sarabunFontPromise; } function wrapText(ctx: CanvasRenderingContext2D, text: string, maxWidth: number): string[] { const lines: string[] = []; const paragraphs = text.split("\n"); for (const para of paragraphs) { const words = para.split(" "); let current = ""; for (const w of words) { const test = current ? `${current} ${w}` : w; if (ctx.measureText(test).width > maxWidth && current) { lines.push(current); current = w; } else { current = test; } } if (current) lines.push(current); } return lines; } function buildComposite(imgUrl: string, text: string, pos: OverlayPos): Promise { return new Promise((resolve, reject) => { const img = new Image(); img.onload = async () => { try { await loadSarabunFont(); } catch { /* Canvas will use the Thai fallback font. */ } const canvas = document.createElement("canvas"); canvas.width = img.naturalWidth; canvas.height = img.naturalHeight; const ctx = canvas.getContext("2d"); if (!ctx) { reject(new Error("no canvas context")); return; } ctx.drawImage(img, 0, 0); const fontSize = Math.max(28, Math.round(img.naturalHeight * 0.065)); ctx.font = `bold ${fontSize}px 'Sarabun', 'Noto Sans Thai', 'Prompt', sans-serif`; const maxW = img.naturalWidth * 0.84; const lines = wrapText(ctx, text.trim(), maxW); const lineH = fontSize * 1.55; const pad = fontSize * 1.1; const zoneH = lines.length * lineH + pad * 2; let zoneY: number; if (pos === "top") zoneY = 0; else if (pos === "bottom") zoneY = img.naturalHeight - zoneH; else zoneY = (img.naturalHeight - zoneH) / 2; const grad = ctx.createLinearGradient(0, zoneY, 0, zoneY + zoneH); if (pos === "top") { grad.addColorStop(0, "rgba(0,0,0,0.48)"); grad.addColorStop(1, "rgba(0,0,0,0)"); } else if (pos === "bottom") { grad.addColorStop(0, "rgba(0,0,0,0)"); grad.addColorStop(1, "rgba(0,0,0,0.48)"); } else { grad.addColorStop(0, "rgba(0,0,0,0)"); grad.addColorStop(0.15, "rgba(0,0,0,0.42)"); grad.addColorStop(0.85, "rgba(0,0,0,0.42)"); grad.addColorStop(1, "rgba(0,0,0,0)"); } ctx.fillStyle = grad; ctx.fillRect(0, zoneY, img.naturalWidth, zoneH); ctx.fillStyle = "#ffffff"; ctx.textAlign = "center"; ctx.shadowColor = "rgba(0,0,0,0.35)"; ctx.shadowBlur = fontSize * 0.28; ctx.shadowOffsetY = 2; const textStartY = pos === "top" ? pad + fontSize : zoneY + pad + fontSize; lines.forEach((line, i) => { ctx.fillText(line, img.naturalWidth / 2, textStartY + i * lineH); }); canvas.toBlob( (blob) => { if (!blob) { reject(new Error("toBlob failed")); return; } resolve(URL.createObjectURL(blob)); }, "image/jpeg", 0.93, ); }; img.onerror = reject; img.src = imgUrl; }); } 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" | "overlay" | null>(null); const [error, setError] = useState(null); const [profileMissing, setProfileMissing] = useState(false); const [overlayText, setOverlayText] = useState(""); const [overlayPos, setOverlayPos] = useState("bottom"); const [overlayPreview, setOverlayPreview] = useState(null); 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); setOverlayText(""); setOverlayPreview(null); setResult(String(r.data.url ?? "")); } useEffect(() => { if (!result || !overlayText.trim()) return; let cancelled = false; buildComposite(result, overlayText, overlayPos) .then((url) => { if (!cancelled) setOverlayPreview((prev) => { if (prev) URL.revokeObjectURL(prev); return url; }); }) .catch(() => {}); return () => { cancelled = true; }; }, [result, overlayText, overlayPos]); async function handleUse() { if (!result) return; if (hasImage && !window.confirm("แทนที่รูปเดิมของโพสต์ด้วยรูปนี้?")) return; if (!overlayText.trim()) { onUse(result); setResult(null); setOpen(false); return; } setBusy("overlay"); setError(null); try { const compositeUrl = overlayPreview ?? await buildComposite(result, overlayText, overlayPos); const resp = await fetch(compositeUrl); const blob = await resp.blob(); const file = new File([blob], "ai-image-overlay.jpg", { type: "image/jpeg" }); const form = new FormData(); form.append("pageId", pageId); form.append("file", file); const uploadRes = await fetch(withBase("/api/upload"), { method: "POST", body: form }); const data: Record = await uploadRes.json().catch(() => ({})); if (!uploadRes.ok) throw new Error(typeof data.error === "string" ? data.error : "อัปโหลดไม่สำเร็จ"); onUse(String(data.url)); setResult(null); setOpen(false); } catch (e) { setError(e instanceof Error ? e.message : "เพิ่มข้อความบนรูปไม่สำเร็จ ลองใหม่"); } finally { setBusy(null); } } if (!open) { return ( ); } return (
ให้ AI สร้างรูป