"use client"; import { useCallback, useEffect, useState } from "react"; import { Loader2, Sparkles } from "lucide-react"; import { Button } from "@/components/ui/button"; import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle, } from "@/components/ui/dialog"; import { Input } from "@/components/ui/input"; import { Label } from "@/components/ui/label"; import { Textarea } from "@/components/ui/textarea"; import { BRIEF_OUTCOMES, BRIEF_PURPOSES, BRIEF_TONES, DRAFT_SIZES, OUTCOME_LABELS, PURPOSE_LABELS, TONE_LABELS, } from "@/lib/npc-dialogue/generationPrompt"; import type { BriefOutcome, BriefPurpose, BriefTone, DialogueBrief, DraftSize, } from "@/lib/npc-dialogue/generationPrompt"; import { generateNpcDialogueDraft, listDialogueFlagKeys, } from "@/app/(frontend)/personnel/contacts/[id]/actions"; import type { GeneratedDialogueDraft } from "@/app/(frontend)/personnel/contacts/[id]/actions"; /** The canvas node a branch can be attached under, when one is selected. */ export interface AttachTarget { readonly id: string; /** Short human description, e.g. `choice: "What's our radio situation?"`. */ readonly label: string; /** The output a new branch would use, e.g. `a new choice button`. */ readonly output: string; /** False when the node cannot take another connection (an end node). */ readonly canAttach: boolean; /** * Where a returned branch continues: back to this node when it is a menu of * choices, on to the step this node already led to otherwise, or null when * returning is impossible (a condition, or nothing after it). */ readonly returnsTo: "caller" | "successor" | null; } /** How the generated draft lands on the canvas. */ export type DraftPlacement = "attach" | "beside" | "replace"; /** What the caller needs to do with the returned draft. */ export interface DraftPlacementChoice { readonly placement: DraftPlacement; /** Point the branch's open end back at the node it attached from. */ readonly returnToCaller: boolean; } interface GenerateDraftDialogProps { readonly open: boolean; readonly onOpenChange: (open: boolean) => void; /** The contact this conversation belongs to. Null until the doc is saved. */ readonly npcId: number | null; /** The dialogue document, so its voice override applies. Null until saved. */ readonly dialogueId: number | null; /** Nodes already on the canvas, so the author is warned about replacement. */ readonly nodeCount: number; /** The selected node, when exactly one is selected. Null disables attaching. */ readonly attachTarget: AttachTarget | null; /** Receives the draft, the brief that produced it, and where it should go. */ readonly onGenerated: ( result: GeneratedDialogueDraft, brief: DialogueBrief, choice: DraftPlacementChoice, ) => void; } interface FlagOption { key: string; flagType: string; } const INITIAL_BRIEF: DialogueBrief = { purpose: "greet", goal: "", outcome: "none", flagKey: "", tone: "clipped", size: 4, mustInclude: "", }; /** * Admin-panel surface: the Payload admin bundle does not load the frontend's * shadcn theme variables, so every surface here is styled explicitly in zinc, * the same way `NodeEditDialog` does it. Native selects are deliberate too: a * portaled Radix Select inherits nothing inside the admin panel's theme scope, * which leaves it transparent and unable to take pointer events. */ const FIELD_LABEL = "text-[10px] uppercase tracking-wider text-white/50"; const SELECT_CLASS = "w-full rounded border border-white/20 bg-zinc-800 px-2 py-1.5 text-sm text-white outline-none focus:border-white/40"; const TEXT_INPUT_CLASS = "bg-zinc-800 border-white/20 text-white placeholder:text-white/30 focus-visible:ring-0 focus-visible:border-white/40"; /** * The brief that seeds a generated conversation. * * The fields are deliberately narrow: a model asked for "a conversation" with no * shape produces something generic, while a brief that names the purpose, the * takeaway and the outcome produces something an author can edit rather than * rewrite. Nothing here reaches the database. Cancelling leaves the canvas as it * was, and generating only touches unsaved field state. */ export function GenerateDraftDialog({ open, onOpenChange, npcId, dialogueId, nodeCount, attachTarget, onGenerated, }: GenerateDraftDialogProps) { const [brief, setBrief] = useState(INITIAL_BRIEF); // A branch is the default whenever there is a conversation to branch off: the // whole-graph replace is the destructive option, so it should not be the one // that happens because nobody looked at the dropdown. const [placement, setPlacement] = useState("attach"); const [returnToCaller, setReturnToCaller] = useState(true); const effectivePlacement: DraftPlacement = nodeCount === 0 ? "replace" : attachTarget?.canAttach ? placement : placement === "attach" ? "beside" : placement; const [flags, setFlags] = useState([]); const [flagsError, setFlagsError] = useState(null); const [busy, setBusy] = useState(false); const [error, setError] = useState(null); const set = useCallback((key: K, value: DialogueBrief[K]) => { setBrief((current) => ({ ...current, [key]: value })); }, []); // The flag list is only needed to populate the outcome dropdown, so it is // fetched when the dialog opens rather than on every editor render. useEffect(() => { if (!open) return; let cancelled = false; void (async () => { const res = await listDialogueFlagKeys(); if (cancelled) return; if (res.success && res.data) { setFlags(res.data); setFlagsError(null); } else { setFlags([]); setFlagsError(res.error ?? "Could not load player flags."); } })(); return () => { cancelled = true; }; }, [open]); useEffect(() => { if (!open) return; setError(null); // Attach when something is selected, otherwise insert beside the graph. A // remembered "replace" from a previous open would be destructive by default. setPlacement(attachTarget ? "attach" : "beside"); }, [open, attachTarget]); async function handleGenerate() { if (npcId === null) { setError("Save this conversation against a contact first."); return; } const goal = brief.goal.trim(); if (goal.length < 8) { setError("Describe what the player should learn or do."); return; } if (brief.outcome === "set-flag" && !brief.flagKey) { setError("Choose which flag the conversation should set."); return; } setBusy(true); setError(null); try { const scope = effectivePlacement === "replace" ? "full" : "fragment"; const res = await generateNpcDialogueDraft(npcId, { ...brief, goal }, dialogueId, { scope, insertionHint: scope === "fragment" && effectivePlacement === "attach" && attachTarget ? `${attachTarget.label}, through ${attachTarget.output}` : null, }); if (!res.success || !res.data) { setError(res.error ?? "The model could not produce a usable conversation."); return; } onGenerated(res.data, { ...brief, goal }, { placement: effectivePlacement, // The toggle is hidden when there is nothing to return to, so an // untouched default must not be sent as a request and then reported back // as a refusal the author never asked for. returnToCaller: attachTarget?.returnsTo != null && returnToCaller, }); onOpenChange(false); } finally { setBusy(false); } } return ( (busy ? undefined : onOpenChange(next))}> Draft a conversation Describe the beat you want. The model writes a flowchart into the canvas as an unsaved draft, so nothing reaches players until you review it and save. {/* Scrolls instead of growing past the viewport on a short screen. */}