import type { QueueItem, QueueStatus } from './encounterLifecycle'; // Preference tiers for what to preview after a close (design ยง3.5). const TIERS: QueueStatus[][] = [ ['in-progress', 'onleave'], // resume what you're juggling ['triaged', 'arrived'], // ready to see ['scheduled'], // later today ]; /** Smartest next item to PREVIEW (not enter) after closing `closedKey`. Undefined nothing left to pick. */ export const nextCandidateKey = (items: QueueItem[], closedKey: string): string | undefined => { const pool = items.filter((i) => i.key !== closedKey); for (const tier of TIERS) { const hit = pool.find((i) => tier.includes(i.status)); if (hit) return hit.key; } return undefined; }; /** What the overview's selection should become when the queue or the active encounter changes. */ export type SelectionOutcome = | { kind: 'keep' } | { kind: 'clear' } | { kind: 'select'; key: string }; /** * THE ACTIVE ENCOUNTER IS NEVER "STALE SELECTION", EVEN WHEN IT IS NOT ON TODAY'S QUEUE. * * The overview renders the workspace only while `selectedKey === active.item.key`. So re-selecting the * queue's first item whenever the selection is not a queue row **unmounts the open visit** - and an active * encounter that is not a queue row is a real state, not an edge case: stagnant-draft nag opens * a visit whose note has been waiting for days, which is precisely the visit that is NOT on today's board. * * Extracted rather than left inline because it is load-bearing and invisible: with the guard missing, * the nag's wiring lands, the active slot fills, and the workspace never appears - the button reads as dead * for a second reason, which is the failure exists to remove. * * @param activeKey the key of the ACTIVE encounter, if there is one. */ export const selectionAfterQueueChange = ( items: QueueItem[], selectedKey: string | undefined, activeKey: string | undefined, ): SelectionOutcome => { if (activeKey !== undefined && selectedKey === activeKey) return { kind: 'keep' }; if (items.length === 0) return { kind: 'clear' }; if (items.some((i) => i.key === selectedKey)) return { kind: 'keep' }; // Prefer a visit already under way - resuming beats starting. const first = items.find((i) => i.status === 'in-progress') ?? items[0]; return { kind: 'select', key: first.key }; };