"use client"; import * as React from "react"; import { useRouter } from "next/navigation"; import { toast } from "sonner"; import { Badge } from "@/components/ui/badge"; import { Button } from "@/components/ui/button"; import { Alert, AlertDescription } from "@/components/ui/alert"; import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"; import { resetMissionCommandChain, saveMissionCommandChain } from "@/app/(frontend)/intelligence/missions/actions"; import type { ChainMode, ChainParticipant } from "@/lib/command-chain"; import { CONNECT_REJECTION_MESSAGES, autoOrientPair, checkConnect, invalidLinkKeys, type ChainDraft, } from "./chainDraftRules"; import { MissionCommandChainChart } from "./MissionCommandChainChart"; import { MissionCommandChainList } from "./MissionCommandChainList"; interface MissionCommandChainSectionProps { missionId: number; mode: ChainMode; links: Array<{ supervisorId: number; subordinateId: number; source: "default" | "override" }>; participants: ChainParticipant[]; editable: boolean; lockReason: string | null; } const MODE_LABELS: Record = { stored: "Override", default: "Live defaults", legacy: "Legacy rule", }; function draftFromLinks( links: MissionCommandChainSectionProps["links"], ): ChainDraft { const draft: ChainDraft = {}; for (const link of links) { const row = draft[link.subordinateId] ?? []; if (!row.includes(link.supervisorId)) draft[link.subordinateId] = [...row, link.supervisorId]; } return draft; } /** * Operation COMMAND section: the chain of command as an editable org chart * (primary) plus the per-person supervisor list (fallback). Both tabs share * one draft; edits stay local until Save, and the server re-validates * everything (`saveMissionCommandChain`). */ export function MissionCommandChainSection({ missionId, mode, links, participants, editable, lockReason, }: MissionCommandChainSectionProps) { const router = useRouter(); const [pending, setPending] = React.useState(false); const [draft, setDraft] = React.useState(() => draftFromLinks(links)); // Refreeze the draft when a save/reset refreshes server state. const signature = React.useMemo( () => links .map((l) => `${l.supervisorId}>${l.subordinateId}`) .sort() .join(","), [links], ); React.useEffect(() => { setDraft(draftFromLinks(links)); // eslint-disable-next-line react-hooks/exhaustive-deps }, [signature]); const tryAdd = (supervisorId: number, subordinateId: number) => { const error = checkConnect(draft, participants, supervisorId, subordinateId); if (error) { toast.error(CONNECT_REJECTION_MESSAGES[error]); return; } setDraft((prev) => { const row = prev[subordinateId] ?? []; if (row.includes(supervisorId)) return prev; return { ...prev, [subordinateId]: [...row, supervisorId] }; }); }; const remove = (supervisorId: number, subordinateId: number) => { setDraft((prev) => ({ ...prev, [subordinateId]: (prev[subordinateId] ?? []).filter((s) => s !== supervisorId), })); }; /** Canvas connect: the drag direction is only a hint; rank decides. */ const handleChartAdd = (dragFrom: number, dragTo: number) => { const { supervisorId, subordinateId } = autoOrientPair(participants, dragFrom, dragTo); tryAdd(supervisorId, subordinateId); }; const invalidKeys = React.useMemo(() => invalidLinkKeys(draft, participants), [draft, participants]); const save = async () => { setPending(true); const payload = Object.entries(draft).flatMap(([subordinateId, supervisorIds]) => supervisorIds.map((supervisorId) => ({ supervisorId, subordinateId: Number(subordinateId) })), ); const result = await saveMissionCommandChain({ missionId, links: payload }); setPending(false); if (!result.success) { toast.error(result.error ?? "Could not save the chain."); return; } toast.success("Chain of command saved."); router.refresh(); }; const reset = async () => { setPending(true); const result = await resetMissionCommandChain({ missionId }); setPending(false); if (!result.success) { toast.error(result.error ?? "Could not reset the chain."); return; } toast.success("Chain reset to live defaults."); router.refresh(); }; const nothingToDraw = participants.length === 0; const [tab, setTab] = React.useState<"chart" | "list">(mode === "legacy" ? "list" : "chart"); return (

Who commands whom for this operation. Supervisors may rate their subordinates as a command review. Drag between cards to add a link; the higher-ranked card becomes the supervisor.

{MODE_LABELS[mode]}
{mode === "legacy" && ( This mission was rated before the chain existed, so its command reviews follow the original assignment rule and cannot be edited here. )} {editable === false && lockReason && mode !== "legacy" && ( {lockReason} )} {mode === "legacy" ? ( {}} onRemoveSupervisor={() => {}} /> ) : nothingToDraw ? (

No one has RSVP'd yes yet, so there is no chain to draw.

) : ( setTab(v === "list" ? "list" : "chart")}> Org chart List ({ id: p.id, name: p.name, rankIndex: p.rankIndex, rankLabel: p.rankLabel, }))} draft={draft} invalidKeys={invalidKeys} editable={editable} onAddLink={handleChartAdd} onRemoveLink={remove} /> tryAdd(supervisorId, subordinateId)} onRemoveSupervisor={(subordinateId, supervisorId) => remove(supervisorId, subordinateId)} /> )} {editable && mode !== "legacy" && !nothingToDraw && (
Changes apply to this mission only
)}
); }