"use client"; import { useCallback, useEffect, useMemo, useRef, useState } from "react"; import { ChevronDownIcon, ChevronUpIcon, XIcon } from "lucide-react"; import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle, } from "@/components/ui/dialog"; import { Button } from "@/components/ui/button"; import { Input } from "@/components/ui/input"; import { Label } from "@/components/ui/label"; import { Checkbox } from "@/components/ui/checkbox"; import type { DialogueAttachment, DialogueCondition, DialogueConditionGroup, DialogueFlagCondition, DialogueFlagOp, DialogueNext, DialogueNode, DialogueNodeData, NpcDialogueEffect, NpcDialogueNodeType, } from "@/lib/npc-dialogue/dialogue"; import { conditionSummary, EFFECT_TYPES, outgoingHops } from "@/lib/npc-dialogue/dialogue"; import { reorderChoice } from "@/lib/npc-dialogue/reorder"; import { MarkupEditor } from "./MarkupEditor"; import { LineAssist } from "./LineAssist"; import { uploadNpcDialogueAttachment } from "@/app/(frontend)/personnel/contacts/[id]/actions"; interface NodeEditDialogProps { readonly node: DialogueNode | null; /** Every node in the flow, used to build the "goes to" target lists. */ readonly allNodes: DialogueNode[]; readonly open: boolean; readonly onOpenChange: (open: boolean) => void; readonly onSave: (nodeId: string, data: DialogueNodeData) => void; /** The contact this flow belongs to, for the per-line AI controls. */ readonly npcId: number | null; } const EFFECT_LABELS: Record = { notify: "Notify user (in-app)", emit: "Log game event", reward: "Reward (unconfigured)", flag: "Set player flag", }; const FLAG_OP_LABELS: Record = { set_true: "Set to true", set_false: "Set to false", set_number: "Set number to", set_text: "Set text to", add: "Add to number", }; const CONDITION_OP_LABELS: Record = { is_true: "is true", is_false: "is false", gte: "is at least", lte: "is at most", gt: "is greater than", lt: "is less than", eq: "equals", }; /** Group combinators, in UI order. Groups are single-level over leaves. */ const GROUP_OP_LABELS: Record = { and: "All conditions match (AND)", or: "Any condition matches (OR)", nor: "No condition matches (NOR)", }; /** Ops that compare against a number (everything except is_true/is_false). */ const NUMERIC_OPS: DialogueFlagCondition["op"][] = ["gte", "lte", "gt", "lt", "eq"]; /** A blank leaf used when switching into single mode or adding a group row. */ const EMPTY_LEAF: DialogueFlagCondition = { kind: "flag", key: "", op: "is_true" }; /** Max height (px) the dialogue Line box auto-grows to. Longer content scrolls * inside the box from here; the user can still drag-resize it taller. */ const MAX_LINE_HEIGHT_PX = 200; /** Short readable label for a node in the target pickers, with a text snippet. */ function nodeLabel(node: DialogueNode): string { const d = node.data; let preview: string; switch (node.type) { case "dialogue": { const speaker = d.speaker?.trim(); const body = d.body?.trim(); preview = speaker && body ? `${speaker}: ${body}` : speaker || body || "Empty line"; break; } case "choice": { const lead = d.leadIn?.trim(); const count = d.choices?.length ?? 0; const tail = `${count} choice${count === 1 ? "" : "s"}`; preview = lead ? `${lead} (${tail})` : tail; break; } case "event": preview = d.body?.trim() || d.effect?.message?.trim() || (d.effect ? EFFECT_LABELS[d.effect.type] : "Narration"); break; case "delay": preview = d.delaySeconds ? `${d.delaySeconds}s pause` : "Pause"; break; case "condition": { const c = d.condition; preview = c ? conditionSummary(c) : "Condition"; break; } default: preview = d.closing?.trim() || "Conversation ends"; } const trimmed = preview.length > 48 ? `${preview.slice(0, 48)}…` : preview; return `${node.type} · ${trimmed}`; } /** Inline editor for a single dialogue node's data. */ export function NodeEditDialog({ node, allNodes, open, onOpenChange, onSave, npcId, }: NodeEditDialogProps) { const [draft, setDraft] = useState(null); // The line immediately before this node, so a rewrite does not restate it. // Reads the incoming hop's source rather than a separate "previous" prop, // because the graph already knows and nothing else does. const previousLine = useMemo(() => { if (!node) return null; const source = allNodes.find((candidate) => outgoingHops(candidate).some((hop) => hop?.target === node.id), ); return source?.data.body?.trim() || source?.data.leadIn?.trim() || null; }, [node, allNodes]); // Users for the "Specific user" flag target. Fetched once per open; the // admin context is already authenticated, so cookie auth is enough. const [users, setUsers] = useState<{ id: number; username: string }[]>([]); useEffect(() => { let active = true; if (!open) return; fetch("/api/users?limit=1000&depth=0") .then((res) => (res.ok ? res.json() : null)) .then((data) => { if (!active) return; const list = Array.isArray(data?.docs) ? data.docs : []; setUsers( list .filter((u: { username?: unknown }) => Boolean(u?.username)) .map((u: { id: number; username: string }) => ({ id: u.id, username: `${u.username} (id ${u.id})`, })), ); }) .catch(() => { if (active) setUsers([]); }); return () => { active = false; }; }, [open]); useEffect(() => { setDraft(node?.data ?? null); }, [node?.id, open]); const patch = (partial: Partial) => setDraft((prev) => (prev ? { ...prev, ...partial } : prev)); const lineRef = useRef(null); /** Auto-grow the line box to its content up to MAX_LINE_HEIGHT_PX so long * lines do not scroll in a fixed-height box. The user can still drag-resize * it taller; typing re-sizes it to fit. */ const autoSizeLine = useCallback(() => { const el = lineRef.current; if (!el) return; el.style.height = "auto"; el.style.height = `${Math.min(el.scrollHeight, MAX_LINE_HEIGHT_PX)}px`; }, []); useEffect(() => { autoSizeLine(); }, [draft?.body, autoSizeLine]); // Guard lives below every hook so their call order never changes: on the // first render draft is still null, and returning early here would skip the // hooks defined above it on later renders (a Rules of Hooks violation). if (!node || !draft) return null; const patchEffect = (partial: Partial) => patch({ effect: { type: "notify", ...draft.effect, ...partial } }); const setChoice = (index: number, next: DialogueNext) => patch({ choices: (draft.choices ?? []).map((choice, i) => (i === index ? next : choice)) }); const addChoice = () => patch({ choices: [...(draft.choices ?? []), { label: "", target: "" }] }); const removeChoice = (index: number) => patch({ choices: (draft.choices ?? []).filter((_, i) => i !== index) }); /** Swap a choice with its neighbour so choices can be reordered. No-op at * the ends, so the buttons can be disabled there. */ const moveChoice = (index: number, direction: -1 | 1) => { const ordered = reorderChoice(draft.choices ?? [], index, direction); if (ordered) patch({ choices: ordered }); }; /** Toggle/replace a choice's visibility gate; null removes the gate. */ const setChoiceCondition = (index: number, next: DialogueCondition | null) => patch({ choices: (draft.choices ?? []).map((c, i) => i === index ? { ...c, condition: next ?? undefined } : c, ), }); const targetOptions = allNodes.filter((n) => n.id !== node.id); return ( e.stopPropagation()} > Edit {node.type} onOpenChange(false)} className="p-2 -m-2 hover:bg-zinc-100 dark:hover:bg-zinc-800 transition-colors focus:outline-none focus-visible:ring-2 focus-visible:ring-zinc-400 rounded-full" aria-label="Close" >
{node.type === "dialogue" && (
patch({ speaker: e.target.value || undefined })} placeholder="Defaults to the NPC's name" className="bg-zinc-800 border-white/20 text-white placeholder:text-white/30" />
)} {node.type === "dialogue" && (
{ patch({ body: next || undefined }); autoSizeLine(); }} placeholder="The NPC says…" rows={4} textareaRef={lineRef} className="rounded bg-zinc-800 border border-white/20 px-2 py-1.5 text-sm text-white placeholder:text-white/30 resize-y" /> { patch({ body: next || undefined }); autoSizeLine(); }} />

Line breaks are kept. **bold**, *italic*, {`{red}color{/}`} and {'`code`'} render in the conversation. Colors take a friendly name (red, amber, cyan, emerald, violet, pink, slate, ...) or a hex code like {`{#ff00ff}`}. Insert flag values with {'{{flag_key}}'}; text flags may carry their own color markup. Pick a branch with a ternary: {'{{ trust ? friend : hostile }}'}, also {'{{ !key }}'} and {'{{ rep >= 5 ? elite : rookie }}'}. Branches may nest tokens. Inline images use {'![alt](url)'} (e.g. {`![coin](/api/media/file/coin.png)`}) and render at text height. Lines starting with "- " or "1. " become lists. Right-click the box for a markup menu.

)} {node.type === "choice" && (
patch({ leadIn: next || undefined })} placeholder="Optional line before the choices." rows={2} className="rounded bg-zinc-800 border border-white/20 px-2 py-1.5 text-sm text-white placeholder:text-white/30 resize-y" /> patch({ leadIn: next || undefined })} />
{(draft.choices ?? []).map((choice, index) => (
setChoice(index, { ...choice, label: e.target.value })} placeholder="How do you respond?" className="bg-zinc-800 border-white/20 text-white placeholder:text-white/30" /> setChoice(index, { ...choice, label: next || undefined }) } />
setChoice(index, { ...choice, tooltip: next || undefined }) } placeholder="Hover card. Supports markup, {{flags}} and ![alt](url) images." rows={2} preview={false} className="rounded bg-zinc-800 border border-white/20 px-2 py-1.5 text-sm text-white placeholder:text-white/30 resize-y" />
{choice.condition && (
setChoiceCondition(index, next)} /> setChoice(index, { ...choice, lockedHint: next || undefined }) } placeholder='Shown on the disabled choice, e.g. "Needs {amber}trusted{/} standing."' rows={2} preview={false} className="rounded bg-zinc-800 border border-white/20 px-2 py-1.5 text-sm text-white placeholder:text-white/30 resize-y" />

Player-specific flag takes priority; falls back to global (no user). Missing = false / 0. With a lock message the choice stays visible but disabled (tooltip explains why) while the condition fails; without one it is hidden entirely.

)}
))} {(draft.choices?.length ?? 0) === 0 && (

No choices yet. Add one above.

)}
)} {node.type === "event" && (
patch({ body: next || undefined })} placeholder="Describe what happens. Shown as a speaker-less narrative line." rows={3} className="rounded bg-zinc-800 border border-white/20 px-2 py-1.5 text-sm text-white placeholder:text-white/30 resize-y" />

Flag values insert as {'{{flag_key}}'}; markup renders like dialogue lines.

{draft.effect?.type === "notify" && (
patchEffect({ title: e.target.value || undefined })} className="bg-zinc-800 border-white/20 text-white" />
)} {draft.effect?.type === "flag" && (
patchEffect({ flagKey: e.target.value || undefined })} placeholder="met_informant" className="bg-zinc-800 border-white/20 text-white placeholder:text-white/30" />
{draft.effect.flagTarget === "user" && ( )}

A flag's identity is (owner, key): the same key holds independent values for each target. Defaults to this player.

{(draft.effect.flagOp === "set_number" || draft.effect.flagOp === "add") && (
patchEffect({ flagAmount: Number(e.target.value) || 0 }) } className="bg-zinc-800 border-white/20 text-white" />
)} {draft.effect.flagOp === "set_text" && (
patchEffect({ flagText: e.target.value || undefined })} placeholder="{green}NOMINAL{/}" className="bg-zinc-800 border-white/20 text-white placeholder:text-white/30" />

Conversations insert this value wherever {'{{key}}'} appears. Colors like {` {green}...{/}`} render in dialogue lines.

)} {(draft.effect.flagOp === "set_true" || draft.effect.flagOp === "set_false" || draft.effect.flagOp === "set_number" || draft.effect.flagOp === "set_text") && (
patchEffect({ flagDelayMinutes: Number(e.target.value) > 0 ? Number(e.target.value) : undefined, }) } placeholder="0 = immediate" className="bg-zinc-800 border-white/20 text-white placeholder:text-white/30" />

For slow-burn narrative: the flag reads as false / 0 until this many minutes have passed, so conditions fail and {"{{countdown:key}}"} tokens tick down to it. Leave empty for an immediate write.

)}

Creates the flag when the player does not have it yet. "Add" keeps numeric flags running totals; "Set text to" converts the flag to a text flag.

)} {draft.effect && (
patchEffect({ message: next || undefined })} placeholder="What happens when the player reaches this node?" rows={3} preview={false} className="rounded bg-zinc-800 border border-white/20 px-2 py-1.5 text-sm text-white placeholder:text-white/30 resize-y" />
)} {draft.effect && draft.effect.type !== "notify" && ( )} {draft.effect && draft.effect.type !== "notify" && ( )}
)} {node.type === "delay" && (
patch({ delaySeconds: Math.max(0, Number(e.target.value) || 0) }) } className="bg-zinc-800 border-white/20 text-white" />

The conversation shows typing dots for this long, then continues.

)} {node.type === "condition" && (
patch({ condition })} />

Player-specific flag takes priority; falls back to global (no user). Missing = false / 0.

)} {node.type === "end" && (
patch({ closing: next || undefined })} placeholder="The conversation ends." rows={3} className="rounded bg-zinc-800 border border-white/20 px-2 py-1.5 text-sm text-white placeholder:text-white/30 resize-y" /> patch({ closing: next || undefined })} />

Flag values insert as {'{{flag_key}}'}; markup renders like dialogue lines.

)} {(node.type === "dialogue" || node.type === "event") && ( patch({ attachments: attachments.length > 0 ? attachments : undefined }) } /> )} {(node.type === "dialogue" || node.type === "event" || node.type === "delay") && (
)}
); } /** * Attachment list for a dialogue/event node. Uploads go to the `media` * collection through the conversation upload action (which gates on * npc-dialogues:update); flowData only keeps the returned pointer plus an * editable chip label. Removing here only drops the pointer, never the file. */ function AttachmentEditor({ attachments, onChange, }: { attachments: DialogueAttachment[]; onChange: (next: DialogueAttachment[]) => void; }) { const inputRef = useRef(null); const [busy, setBusy] = useState(false); const [error, setError] = useState(null); const upload = async (file: File) => { setBusy(true); setError(null); try { const formData = new FormData(); formData.append("file", file); const result = await uploadNpcDialogueAttachment(formData); if (result.success && result.data) { onChange([ ...attachments, { mediaId: result.data.mediaId, label: result.data.filename }, ]); } else { setError(result.error ?? "Upload failed."); } } finally { setBusy(false); } }; return (
{ const file = e.target.files?.[0]; if (file) void upload(file); e.target.value = ""; }} /> {attachments.map((attachment, index) => (
onChange( attachments.map((a, i) => i === index ? { ...a, label: e.target.value || undefined } : a, ), ) } className="h-7 bg-zinc-800 border-white/20 text-xs text-white placeholder:text-white/30" /> #{attachment.mediaId}
))} {attachments.length === 0 && (

No attachments on this line.

)} {error &&

{error}

}

Players see these as chips under the line that open a file viewer. Text, PDF or image, up to 8 MB. Files live in the media library; removing a chip never deletes the file.

); } /** * Single-level condition builder: a combinator dropdown (one flag, or an * AND / OR / NOR group) plus one editable row per leaf. Groups never nest, * which keeps authored JSON shallow and the runtime evaluator single-pass. */ function ConditionFields({ value, onChange, }: { value: DialogueCondition; onChange: (next: DialogueCondition) => void; }) { const mode = value.kind === "group" ? `group:${value.op}` : "leaf"; const setMode = (next: string) => { if (next === mode) return; if (next === "leaf") { onChange(value.kind === "group" ? (value.children[0] ?? EMPTY_LEAF) : value); return; } const op = next.slice("group:".length) as DialogueConditionGroup["op"]; if (value.kind === "group") onChange({ ...value, op }); else onChange({ kind: "group", op, children: [value] }); }; const patchLeaf = (index: number, partial: Partial) => { if (value.kind === "flag" && index === 0) onChange({ ...value, ...partial }); else if (value.kind === "group") onChange({ ...value, children: value.children.map((c, i) => (i === index ? { ...c, ...partial } : c)), }); }; const leaves = value.kind === "group" ? value.children : [value]; return (
{leaves.map((leaf, index) => (
{value.kind === "group" && leaves.length > 1 && ( )}
patchLeaf(index, { key: e.target.value })} placeholder="met_informant" className="bg-zinc-800 border-white/20 text-white placeholder:text-white/30" /> {NUMERIC_OPS.includes(leaf.op) && (
patchLeaf(index, { amount: Number(e.target.value) || 0 })} className="bg-zinc-800 border-white/20 text-white" />
)}
))} {value.kind === "group" && ( )}
); }