"use client"; import { useRef, useState, useTransition } from "react"; import { useRouter } from "next/navigation"; import { Button } from "@/components/ui/button"; import Editor, { EditorData } from "@/components/editor"; import { savePageAction } from "@/lib/pages/actions"; import { validatePage } from "@/lib/pages/validation"; import { Loader2 } from "lucide-react"; import { toast } from "sonner"; export default function CreatePageClient() { const router = useRouter(); const [isPending, startTransition] = useTransition(); const [fieldErrors, setFieldErrors] = useState<{ title?: string[]; slug?: string[] }>({}); const dataRef = useRef({ title: "", type: "NEWS", slug: "", location: "", tags: [], blocks: [], }); function handleSave(status: "DRAFT" | "PUBLISHED") { startTransition(async () => { const data = dataRef.current; const payload = { id: null, slug: data.slug || data.title.toLowerCase().replace(/\s+/g, "-"), title: data.title, type: data.type, status, blocks: data.blocks, meta: { location: data.location, tags: data.tags }, }; const parsed = validatePage(payload); if (!parsed.success) { const errors: { title?: string[]; slug?: string[] } = {}; for (const msg of parsed.errors) { if (msg.toLowerCase().includes("title")) { (errors.title ??= []).push(msg); } else if (msg.toLowerCase().includes("slug")) { (errors.slug ??= []).push(msg); } } setFieldErrors(errors); toast.error(parsed.errors.join(", ")); return; } setFieldErrors({}); try { await savePageAction(payload); toast.success("Page saved"); router.push("/news"); } catch (e) { toast.error(e instanceof Error ? e.message : "Failed to save page"); } }); } return (

Create page

{ dataRef.current = data; setFieldErrors({}); }} errors={fieldErrors} />
); }