"use client"; import { useEffect, useMemo, useRef, useState, Fragment } from "react"; import { LockIcon, MessageCircleIcon, XIcon } from "lucide-react"; import type { GameNpc } from "@/payload-types"; import type { ChoiceGate, DialogueNext, DialogueNode, FlowData } from "@/lib/npc-dialogue/dialogue"; import { collectNodeTokens } from "@/lib/npc-dialogue/interpolate"; import type { ResolvedNodeTexts } from "@/lib/npc-dialogue/interpolate"; import { DialogueText } from "@/lib/npc-dialogue/DialogueText"; import { findStartNode } from "@/lib/npc-dialogue/dialogue"; import { flowHash, loadSeenMap, mergeSeenNodes, saveSeenMap, unseenNodeIds } from "@/lib/npc-dialogue/seen"; import type { SeenMap } from "@/lib/npc-dialogue/seen"; import { DOSSIER } from "@/components/frontend/operations"; import { Button } from "@/components/ui/button"; import { Dialog, DialogContent, DialogTitle, } from "@/components/ui/dialog"; import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger, } from "@/components/ui/tooltip"; import { evaluateNpcDialogueChoices, evaluateNpcDialogueCondition, resolveNpcDialogueTexts, triggerNpcDialogueEvent, } from "@/app/(frontend)/personnel/contacts/[id]/actions"; interface NpcConversationProps { readonly npc: GameNpc; readonly dialogue: { id: number; flowData?: FlowData } | null | undefined; } interface ResolvedFlow { nodes: DialogueNode[]; startId: string | null; } type LogEntry = | { kind: "node"; id: string; node: DialogueNode; /** Server-resolved display strings (flag tokens interpolated), when the * node had tokens. Undefined = render the raw authored strings. */ resolved?: ResolvedNodeTexts; } | { kind: "player"; id: string; text: string }; /** Resolves the authored flowchart into a shape the runtime can walk. */ function resolveFlow(dialogue: NpcConversationProps["dialogue"]): ResolvedFlow | null { if (!dialogue?.flowData || !Array.isArray(dialogue.flowData.nodes)) return null; const nodes = dialogue.flowData.nodes as DialogueNode[]; return { nodes, startId: findStartNode(nodes)?.id ?? null }; } const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms)); /** Text length drives how long the NPC "types"; jitter keeps it human. */ function typingDelayMs(text: string): number { return Math.min(2600, 450 + text.length * 24) * (0.85 + Math.random() * 0.3); } function nodeText(node: DialogueNode): string { return node.data.body || node.data.effect?.message || node.data.closing || node.data.leadIn || ""; } export function NpcConversation({ npc, dialogue }: NpcConversationProps) { const flow = useMemo(() => resolveFlow(dialogue), [dialogue]); const [open, setOpen] = useState(false); const [log, setLog] = useState([]); /** Speaker label while the NPC types; "" for speaker-less narration. */ const [typing, setTyping] = useState(null); /** True while the player's chosen line is "typing" into the log. */ const [playerTyping, setPlayerTyping] = useState(false); /** `${nodeId}:${index}` keys of one-time choices picked in THIS conversation. * Purely local: it resets on every `begin()`, so a choice hidden here * reappears the next time the conversation is opened. Persist across * conversations with a condition + player flag instead. */ const [takenChoices, setTakenChoices] = useState>(new Set()); /** Per-node visibility gates for condition-gated choices, fetched from * the server when the conversation lands on a choice node. Cleared on * every `begin()` so flags gained mid-conversation are re-checked. */ const [choiceGates, setChoiceGates] = useState>({}); /** Per-browser read progress powering the NEW badges. Loaded after mount so * server and client markup agree (localStorage is invisible to SSR). */ const [seenMap, setSeenMap] = useState({}); useEffect(() => { setSeenMap(loadSeenMap()); }, []); const seq = useRef(0); const sessionRef = useRef(0); const scrollRef = useRef(null); const nextId = () => `entry-${seq.current++}`; // Invalidate pending typing timers when the component unmounts. useEffect( () => () => { sessionRef.current += 1; }, [], ); // Keep the newest line in view. useEffect(() => { const el = scrollRef.current; if (el) el.scrollTop = el.scrollHeight; }, [log, typing, playerTyping, open]); // The choice node the log currently rests on (if any). const activeChoiceNodeId = useMemo(() => { const last = [...log].reverse().find((entry) => entry.kind === "node"); return last && last.kind === "node" && last.node.type === "choice" ? last.node.id : null; }, [log]); // Fetch the server-side visibility gates when landing on a choice node // that has gated choices. Gated choices stay hidden until confirmed, so a // forbidden option never flashes on screen. useEffect(() => { if (!open || !flow || !activeChoiceNodeId) return; if (choiceGates[activeChoiceNodeId]) return; const node = flow.nodes.find((n) => n.id === activeChoiceNodeId); const hasGated = (node?.data.choices ?? []).some((c) => c.condition?.key?.trim()); if (!hasGated) return; let cancelled = false; void evaluateNpcDialogueChoices(Number(npc.id), activeChoiceNodeId).then((res) => { if (!cancelled && res.success && Array.isArray(res.data)) { const gate = res.data; setChoiceGates((prev) => ({ ...prev, [activeChoiceNodeId]: gate })); } }); return () => { cancelled = true; }; }, [open, flow, activeChoiceNodeId, choiceGates, npc.id]); // NEW badge inputs: current flowchart signature + the nodes this browser // has not read yet (a GM edit changes the hash and re-flags everything). const seenKey = dialogue ? String(dialogue.id) : ""; const flowSignature = useMemo(() => flowHash(dialogue?.flowData), [dialogue]); const allNodeIds = useMemo(() => (flow ? flow.nodes.map((n) => n.id) : []), [flow]); const unseenTargets = useMemo( () => new Set(unseenNodeIds(seenMap[seenKey], flowSignature, allNodeIds)), [seenMap, seenKey, flowSignature, allNodeIds], ); if (npc.canMessage !== true || !flow || flow.nodes.length === 0) return null; /** Records that this browser has read a node (persisted, idempotent). */ const markSeen = (nodeId: string) => { setSeenMap((prev) => { const entry = prev[seenKey]; if (entry && entry.hash === flowSignature && entry.nodes.includes(nodeId)) return prev; const next: SeenMap = { ...prev, [seenKey]: { hash: flowSignature, nodes: mergeSeenNodes(entry, flowSignature, nodeId) }, }; saveSeenMap(next); return next; }); }; /** Resolves the node's display strings server-side (flag tokens), then * appends it to the log after a length-based "typing" delay. Nodes without * tokens skip the round trip and render their raw authored text. */ const typeIn = async (node: DialogueNode, token: number) => { let resolved: ResolvedNodeTexts | undefined; if (collectNodeTokens(node).length > 0) { const res = await resolveNpcDialogueTexts(Number(npc.id), node.id); if (sessionRef.current !== token) return; if (res.success && res.data) resolved = res.data; } setTyping(node.type === "event" ? "" : node.data.speaker?.trim() || npc.name); await sleep(typingDelayMs(nodeText(node))); if (sessionRef.current !== token) return; setTyping(null); setLog((prev) => [...prev, { kind: "node", id: nextId(), node, resolved }]); markSeen(node.id); }; // Opening the conversation walks the start node and auto-advances through // linear dialogue/event nodes, so the player lands on the first interactive // node (a choice, an end, or a dead end) without clicking Continue. Each // line arrives after its own typing delay. const begin = () => { const token = ++sessionRef.current; setLog([]); setTyping(null); setPlayerTyping(false); setTakenChoices(new Set()); setChoiceGates({}); setOpen(true); if (!flow.startId) return; void (async () => { const start = flow.nodes.find((n) => n.id === flow.startId) ?? null; if (start) await cascadeFrom(start, token); })(); }; /** Types `start`, then auto-advances through linear dialogue/event/delay/ * condition nodes so the player always lands on the next interactive node * (a choice or an end). Delay nodes pause the conversation; condition nodes * branch on the player's flags, evaluated server-side. Neither is logged. */ const cascadeFrom = async (start: DialogueNode, token: number) => { let current: DialogueNode | null = start; const seen = new Set(); while (current && !seen.has(current.id) && sessionRef.current === token) { seen.add(current.id); if (current.type === "delay") { const seconds = Math.min(30, Math.max(0.5, current.data.delaySeconds ?? 2)); setTyping(""); await sleep(seconds * 1000); if (sessionRef.current !== token) return; setTyping(null); const target: string | undefined = current.data.next?.target; current = target ? (flow.nodes.find((n) => n.id === target) ?? null) : null; continue; } if (current.type === "condition") { const result = await evaluateNpcDialogueCondition(Number(npc.id), current.id); if (sessionRef.current !== token) return; const branch = result.success && result.data ? current.data.trueTarget : current.data.falseTarget; current = branch ? (flow.nodes.find((n) => n.id === branch) ?? null) : null; continue; } await typeIn(current, token); if (sessionRef.current !== token) return; if (current.type === "dialogue" || current.type === "event") { if (current.type === "event" && current.data.effect) { // Await the effect so flags it writes are visible to the lines // that follow (interpolated text and later condition nodes). await triggerNpcDialogueEvent(Number(npc.id), current.id).catch(() => undefined); if (sessionRef.current !== token) return; } const target: string | undefined = current.data.next?.target; current = target ? (flow.nodes.find((n) => n.id === target) ?? null) : null; } else { current = null; } } }; const close = () => { sessionRef.current += 1; setTyping(null); setPlayerTyping(false); setOpen(false); }; const lastNode = [...log].reverse().find((entry) => entry.kind === "node"); // The player's line types out (shorter than NPC pacing), lands, and then // the NPC starts typing its reply. `displayText` is the label as shown on // the button (flag tokens already interpolated server-side). const pick = (hop: DialogueNext, choiceIndex: number, displayText?: string) => { const token = sessionRef.current; const text = displayText || hop.label || "…"; if (hop.once && lastNode && lastNode.kind === "node") { const key = `${lastNode.node.id}:${choiceIndex}`; setTakenChoices((prev) => (prev.has(key) ? prev : new Set(prev).add(key))); } void (async () => { setPlayerTyping(true); await sleep(Math.min(1100, 300 + text.length * 16) * (0.85 + Math.random() * 0.3)); if (sessionRef.current !== token) return; setPlayerTyping(false); setLog((prev) => [...prev, { kind: "player", id: nextId(), text }]); const target = flow.nodes.find((n) => n.id === hop.target); if (target) await cascadeFrom(target, token); })(); }; // The choices offered by the node the log currently rests on. One-time // choices the player already took are hidden; if that empties the list the // footer falls back to the End conversation button so nobody gets stuck. const choiceNode = lastNode && lastNode.kind === "node" && lastNode.node.type === "choice" ? lastNode.node : null; const visibleChoices = choiceNode ? (choiceNode.data.choices ?? []).reduce< { hop: DialogueNext; index: number; locked: boolean }[] >((acc, hop, index) => { if (hop.once && takenChoices.has(`${choiceNode.id}:${index}`)) return acc; if (!hop.condition?.key?.trim()) { acc.push({ hop, index, locked: false }); return acc; } // Gated choices stay hidden until the server confirms them; a failing // gate with an authored hint renders the choice locked instead. const gate = choiceGates[choiceNode.id]?.[index]; if (!gate) return acc; if (gate.pass) acc.push({ hop, index, locked: false }); else if (gate.showLocked) acc.push({ hop, index, locked: true }); return acc; }, []) : []; const anySelectableChoice = visibleChoices.some((choice) => !choice.locked); /** Button text for a choice: the server-resolved label when the choice * node's strings contained flag tokens, the raw label otherwise. */ const choiceLabel = (hop: DialogueNext, index: number): string => ((lastNode?.kind === "node" ? lastNode.resolved?.labels?.[index] : undefined) ?? hop.label) || "…"; /** Rich hover tooltip for a choice (resolved like labels); undefined when * the author left it empty. */ const choiceTooltip = (hop: DialogueNext, index: number): string | undefined => { const raw = (lastNode?.kind === "node" ? lastNode.resolved?.tooltips?.[index] : undefined) ?? hop.tooltip; return raw?.trim() ? raw : undefined; }; /** Tooltip for a locked choice (resolved like labels); generic fallback * when the author left the hint blank. */ const choiceHint = (hop: DialogueNext, index: number): string => { const raw = (lastNode?.kind === "node" ? lastNode.resolved?.hints?.[index] : undefined) ?? hop.lockedHint; return raw?.trim() ? raw : "Locked."; }; return ( <> {unseenTargets.size > 0 && ( New )} !next && close()}>
Conversation // {npc.name}
{flow.startId === null ? (
This conversation has no start node. Ask staff to configure it.
) : ( <>
{log.map((entry) => ( ))} {typing !== null && } {playerTyping && }
{!typing && !playerTyping && lastNode && lastNode.kind === "node" && (lastNode.node.type === "choice" || lastNode.node.type === "end") && (
{lastNode.node.type === "choice" && visibleChoices.length > 0 && ( {visibleChoices.map(({ hop, index, locked }) => { const isNew = unseenTargets.has(hop.target); const button = ( ); const tip = locked ? choiceHint(hop, index) : choiceTooltip(hop, index); if (!tip) return {button}; return ( {button} ); })} )} {(lastNode.node.type === "end" || !anySelectableChoice) && ( )}
)} )}
); } function TimelineEntry({ entry, speakerDefault, }: { entry: LogEntry; speakerDefault: string; }) { if (entry.kind === "player") { return (
You

); } const { node, resolved } = entry; if (node.type === "event") { // Narration: no speaker, styled like a mission briefing line. const body = resolved?.body ?? node.data.body; const message = resolved?.message ?? node.data.effect?.message; const text = body || message || "An event unfolds…"; return (

); } if (node.type === "end") { const text = (resolved?.closing ?? node.data.closing) || "The conversation ends."; return (

); } if (node.type === "choice") { // The choice buttons live in the footer; only the lead-in joins the log. const leadIn = resolved?.leadIn ?? node.data.leadIn; if (!leadIn) return null; return (

); } const speaker = node.data.speaker?.trim() || speakerDefault; const body = resolved?.body ?? node.data.body; return (
{speaker}

{body ? ( ) : ( … )}

); } /** Three bouncing dots while a line is "typing". `player` renders the * right-aligned cyan variant for the player's incoming response. */ function TypingIndicator({ speaker, player }: { speaker?: string; player?: boolean }) { return (
{player ? ( You ) : speaker ? ( {speaker} ) : null} {[0, 150, 300].map((delay) => ( ))}
); }