"use client"; import { useEffect, useMemo, useRef, useState } from "react"; import { useRouter } from "next/navigation"; import { KindPill } from "@/components/Pills"; import { api } from "@/lib/client"; import { KIND_ORDER, KINDS, type KindId } from "@/lib/kinds"; import type { EntryDTO } from "@/lib/serialize"; type Mode = "rich" | "fields" | "stats"; const DEFAULT_FIELDS_BY_KIND: Partial> = { npc: [ ["Race", ""], ["Pronouns", ""], ["Alignment", ""], ["Status", ""], ["Location", ""], ["Affiliation", ""], ], pc: [ ["Class & Level", ""], ["Player", ""], ["Race", ""], ["Background", ""], ], location: [ ["Region", ""], ["Population", ""], ["Government", ""], ["Climate", ""], ], faction: [ ["Headquarters", ""], ["Leader", ""], ["Allies", ""], ["Enemies", ""], ], item: [ ["Type", ""], ["Rarity", ""], ["Attunement", ""], ["Owner", ""], ], deity: [ ["Domain", ""], ["Symbol", ""], ["Alignment", ""], ], beast: [ ["Type", ""], ["Size", ""], ["Habitat", ""], ], }; const STAT_KEYS = ["AC", "HP", "Speed", "STR", "DEX", "CON", "INT", "WIS", "CHA", "Saving Throws", "Damage Resist.", "Condition Imm.", "Senses", "Languages", "Challenge"]; export function EditorScreen({ existing }: { existing?: EntryDTO }) { const router = useRouter(); const isEdit = !!existing; const [kind, setKind] = useState((existing?.kind as KindId) ?? "npc"); const [title, setTitle] = useState(existing?.title ?? ""); const [subtitle, setSubtitle] = useState(existing?.subtitle ?? ""); const [summary, setSummary] = useState(existing?.summary ?? ""); const [body, setBody] = useState(existing?.body ?? ""); const [isPublic, setIsPublic] = useState(existing?.isPublic ?? false); const [tags, setTags] = useState(existing?.tags ?? []); const [tagDraft, setTagDraft] = useState(""); const [fields, setFields] = useState<[string, string][]>(() => { if (existing?.fields && Object.keys(existing.fields).length) return Object.entries(existing.fields).map(([k, v]) => [k, String(v)]); return DEFAULT_FIELDS_BY_KIND[(existing?.kind as KindId) ?? "npc"]?.slice() ?? []; }); const [newFieldKey, setNewFieldKey] = useState(""); const [stats, setStats] = useState<[string, string][]>(() => Object.entries(existing?.stats ?? {}).map(([k, v]) => [k, String(v)]) ); const [abilities, setAbilities] = useState<{ name: string; text: string }[]>( existing?.abilities ?? [] ); const [mode, setMode] = useState("rich"); const [busy, setBusy] = useState(false); const [error, setError] = useState(null); const [suggestions, setSuggestions] = useState([]); const [showSuggest, setShowSuggest] = useState(false); const textareaRef = useRef(null); // load suggestion candidates once useEffect(() => { api("/api/entries").then(setSuggestions).catch(() => {}); }, []); // Caret-aware [[ suggestion popover useEffect(() => { const ta = textareaRef.current; if (!ta) return; const txt = body.slice(0, ta.selectionStart ?? body.length); setShowSuggest(/\[\[$/.test(txt)); }, [body]); const wordCount = useMemo( () => (body.trim() ? body.trim().split(/\s+/).length : 0), [body] ); const linkCount = useMemo(() => { const re = /\[\[([^\]]+)\]\]/g; let n = 0; while (re.exec(body) !== null) n++; return n; }, [body]); const insertSuggestion = (title: string) => { const ta = textareaRef.current; if (!ta) return; const start = ta.selectionStart ?? body.length; const next = body.slice(0, start) + title + "]]" + body.slice(start); setBody(next); setShowSuggest(false); requestAnimationFrame(() => { ta.focus(); ta.selectionStart = ta.selectionEnd = start + title.length + 2; }); }; const addField = () => { if (!newFieldKey.trim()) return; setFields((f) => [...f, [newFieldKey.trim(), ""]]); setNewFieldKey(""); }; const updateField = (i: number, k: string, v: string) => setFields((f) => f.map((x, idx) => (idx === i ? [k, v] : x))); const removeField = (i: number) => setFields((f) => f.filter((_, idx) => idx !== i)); const addTag = () => { const t = tagDraft.trim().replace(/^#/, "").toLowerCase(); if (!t) return; if (!tags.includes(t)) setTags((s) => [...s, t]); setTagDraft(""); }; const setStat = (i: number, k: string, v: string) => setStats((s) => s.map((x, idx) => (idx === i ? [k, v] : x))); const addStat = (k?: string) => setStats((s) => [...s, [k ?? "", ""]]); const removeStat = (i: number) => setStats((s) => s.filter((_, idx) => idx !== i)); const addAbility = () => setAbilities((a) => [...a, { name: "", text: "" }]); const removeAbility = (i: number) => setAbilities((a) => a.filter((_, idx) => idx !== i)); const submit = async () => { if (!title.trim()) { setError("Title required"); return; } setBusy(true); setError(null); const fieldsObj: Record = {}; for (const [k, v] of fields) { if (k.trim()) fieldsObj[k.trim()] = v; } const statsObj: Record = {}; for (const [k, v] of stats) { if (k.trim()) statsObj[k.trim()] = v; } const payload = { kind, title: title.trim(), subtitle: subtitle.trim(), summary: summary.trim(), body, isPublic, tags, fields: fieldsObj, stats: statsObj, abilities, }; try { if (isEdit && existing) { await api(`/api/entries/${existing.slug}`, { method: "PATCH", body: JSON.stringify(payload), }); router.push(`/article/${existing.slug}`); } else { const created = await api("/api/entries", { method: "POST", body: JSON.stringify(payload), }); router.push(`/article/${created.slug}`); } } catch (e) { setError((e as Error).message); } finally { setBusy(false); } }; const onDelete = async () => { if (!existing) return; if (!confirm(`Delete "${existing.title}"?`)) return; await api(`/api/entries/${existing.slug}`, { method: "DELETE" }); router.push("/search"); }; return (
{isEdit && ( editing · {existing!.slug} )}
{isEdit && ( )}
{error &&
{error}
}
setTitle(e.target.value)} placeholder="Inscribe a title…" /> setSubtitle(e.target.value)} placeholder="Subtitle, epithet, or kenning…" />
{kind === "beast" && ( )}
{mode === "rich" && ( <> setSummary(e.target.value)} placeholder="One-line summary (shown in the codex stack)" />