"use client"; import { withBase } from "@/lib/base-path"; import { useState } from "react"; import { useRouter } from "next/navigation"; import { Icon } from "./Icon"; import { formatDateTime, Notice } from "./ui"; import { useToast } from "./Toast"; import { PROFILE_FIELDS, type ShopProfile } from "@/lib/ai/shared"; const EMPTY: ShopProfile = { business: "", audience: "", tone: "", visualStyle: "", avoid: "", cta: "" }; export function ProfileForm({ pageId, canEdit, canDraft, initial, updatedAt, }: { pageId: string; canEdit: boolean; canDraft: boolean; initial: ShopProfile | null; updatedAt: string | null; }) { const router = useRouter(); const toast = useToast(); const [values, setValues] = useState(initial ?? EMPTY); const [busy, setBusy] = useState<"save" | "draft" | null>(null); const [error, setError] = useState(null); async function request(path: string, method: string, body?: ShopProfile) { const res = await fetch(withBase(path), { method, headers: { "Content-Type": "application/json" }, body: body ? JSON.stringify(body) : undefined }).catch(() => null); const json = res ? await res.json().catch(() => ({})) : {}; return { ok: Boolean(res?.ok), json }; } async function save(e: React.FormEvent) { e.preventDefault(); setBusy("save"); setError(null); const { ok, json } = await request(`/api/pages/${pageId}/profile`, "PUT", values); setBusy(null); if (!ok) return setError(json.error ?? "บันทึกไม่สำเร็จ"); toast.show("บันทึกโปรไฟล์ร้านแล้ว"); router.refresh(); } async function draft() { setBusy("draft"); setError(null); const { ok, json } = await request(`/api/pages/${pageId}/profile/draft`, "POST"); setBusy(null); if (!ok) return setError(json.error ?? "AI ร่างโปรไฟล์ไม่สำเร็จ"); const drafted = json.profile as ShopProfile; // Keep what the owner already typed where the AI found nothing. setValues((cur) => { const next = { ...cur }; for (const f of PROFILE_FIELDS) if (drafted[f.key]) next[f.key] = drafted[f.key]; return next; }); toast.show(`AI ร่างจาก ${json.postCount} โพสต์แล้ว — ตรวจแล้วกดบันทึก`, "warn"); } return (

ข้อมูลร้าน

{updatedAt && บันทึกล่าสุด {formatDateTime(updatedAt)}}
{!canEdit && ผู้อนุมัติขึ้นไปเท่านั้นที่แก้โปรไฟล์ร้านได้} {canEdit && canDraft && (

ยังไม่รู้จะเขียนอะไร? ให้ AI อ่านโพสต์ 90 วันล่าสุดของเพจแล้วร่างให้ก่อน

)} {PROFILE_FIELDS.map((f) => (