"use client"; import { withBase } from "@/lib/base-path"; import { useState } from "react"; import Link from "next/link"; import { Icon } from "./Icon"; import { Notice } from "./ui"; import { CAPTION_REFINEMENTS, type CaptionRefinement } from "@/lib/ai/shared"; interface Variant { angle: string; caption: string; } /** * Drafts or rewrites the caption with Codex CLI. The chosen text only fills the * editor — saving and approval stay exactly as for hand-written posts. */ export function CaptionAssistant({ pageId, targets, caption, initialTopic, onChange, }: { pageId: string; targets: string[]; caption: string; initialTopic?: string; onChange: (text: string, fromAi: boolean) => void; }) { const [open, setOpen] = useState(Boolean(initialTopic)); const [topic, setTopic] = useState(initialTopic ?? ""); const [variants, setVariants] = useState([]); const [busy, setBusy] = useState(null); const [error, setError] = useState(null); const [profileMissing, setProfileMissing] = useState(false); const [previous, setPrevious] = useState(null); async function run(input: { topic: string } | { refine: CaptionRefinement }) { const label = "refine" in input ? input.refine : "draft"; setBusy(label); setError(null); const res = await fetch(withBase("/api/ai/caption"), { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ pageId, targets, caption, ...input }), }).catch(() => null); const body = res ? await res.json().catch(() => ({})) : {}; setBusy(null); if (!res?.ok) return setError(body.error ?? "AI ทำงานไม่สำเร็จ ลองใหม่อีกครั้ง"); setVariants(body.variants ?? []); setProfileMissing(Boolean(body.profileMissing)); } function use(v: Variant) { setPrevious(caption); onChange(v.caption, true); setVariants([]); } if (!open) { return ( ); } return (
ให้ AI ช่วยเขียน