@gemina/elements 0.13.2 → 0.13.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +211 -8
- package/dist/chat.cjs +1 -1
- package/dist/chat.cjs.map +1 -1
- package/dist/chat.js +2 -2
- package/dist/{chunk-R7LDCMGS.js → chunk-GWTTD7QH.js} +2 -2
- package/dist/{chunk-R7LDCMGS.js.map → chunk-GWTTD7QH.js.map} +1 -1
- package/dist/{chunk-HRWPF27V.js → chunk-MPBZCA44.js} +2 -2
- package/dist/{chunk-JGZOUFGG.js → chunk-XEWKY2DW.js} +2 -2
- package/dist/index.cjs +1 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.js +3 -3
- package/dist/verification.cjs +1 -1
- package/dist/verification.cjs.map +1 -1
- package/dist/verification.js +2 -2
- package/package.json +1 -1
- /package/dist/{chunk-HRWPF27V.js.map → chunk-MPBZCA44.js.map} +0 -0
- /package/dist/{chunk-JGZOUFGG.js.map → chunk-XEWKY2DW.js.map} +0 -0
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts","../src/token-manager.ts","../src/chat.tsx","../src/internal/response-like.ts","../src/version.ts","../src/verification/index.tsx","../src/verification/field-types.ts","../src/verification/classify.ts","../src/verification/pointer.ts","../src/verification/bindings.ts","../src/verification/row-plan.ts","../src/verification/row-cells.ts","../src/verification/form.tsx","../src/verification/review-filter.ts","../src/verification/tip.tsx","../src/verification/viewer.tsx","../src/verification/viewer-math.ts","../src/verification/styles.ts"],"sourcesContent":["// Token management (no React required — also available as\n// `@gemina/elements/token-manager`).\nexport { GeminaTokenManager } from './token-manager';\nexport type { FetchTokenResult, GeminaTokenManagerOptions } from './token-manager';\n\n// Chat UI (React — also available as `@gemina/elements/chat`).\nexport { GeminaChat } from './chat';\nexport type { GeminaChatProps, GeminaChatTheme, GeminaChatDirection } from './chat';\n\n// Verification UI (React — also available as `@gemina/elements/verification`).\nexport { GeminaVerification } from './verification/index';\nexport type {\n GeminaVerificationProps,\n GeminaVerificationTheme,\n GeminaVerificationDirection,\n VerificationErrorReason,\n VerificationErrorDetail,\n VerificationCompletion,\n} from './verification/index';\n\nexport { VERSION } from './version';\n","/**\n * GeminaTokenManager — in-memory holder for short-lived Gemina session\n * tokens, per the Document Intelligence token spec (PRD §6.11.1).\n *\n * Security model (the five footguns this file designs out):\n *\n * 1. **The API key never enters the browser.** The constructor throws if it\n * is handed a raw string instead of a `fetchToken` callback, and\n * `getToken()` rejects if the callback ever resolves with an\n * API-key-shaped string (32 alphanumerics, no dots).\n * 2. **The token is never persisted.** No `localStorage`, `sessionStorage`,\n * cookies, or IndexedDB anywhere in this package — the token lives only\n * in memory, inside state that is not an own property of the instance.\n * 3. **The browser never asserts its own scope.** This manager carries no\n * scope parameters at all; scope is signed into the token server-side.\n * 4. **No refresh token is held in the browser.** Renewal always goes back\n * through the tenant's own authenticated backend via `fetchToken`.\n * 5. **The SDK cannot mint or widen TTL/scope.** This class only *stores*\n * what the tenant backend minted; it has no code path to\n * `POST /v1/sessions/token`.\n *\n * Storage choice: internal state (including the token) lives in a\n * module-scoped `WeakMap` keyed by the instance rather than in an ordinary\n * class field. An ordinary field — even a `#private` one via devtools — is\n * trivially discoverable by enumerating the instance; the WeakMap keeps the\n * token out of `Object.keys`, `JSON.stringify`, spread copies, and casual\n * inspection, and it is unreachable without a reference to both the WeakMap\n * (module-private) and the instance. This is hardening against accidental\n * exposure/serialization, not encryption: code running in the same realm\n * with a debugger can still read process memory. The upgrade path for\n * stronger isolation is a Web Worker (see PRD §6.11.1).\n *\n * SSR-safe: this module touches no `window`/`document` at import time and\n * starts no timers — refresh happens lazily inside `getToken()`, so an idle\n * manager consumes nothing and never keeps a Node process alive.\n */\n\n/** What `fetchToken` must resolve with (mirror of the mint response). */\nexport interface FetchTokenResult {\n /** The raw session token (a JWT). Pass it WITHOUT a \"Bearer \" prefix. */\n token: string;\n /** Token lifetime in seconds, as returned by the mint endpoint. */\n expiresIn: number;\n}\n\n/** Constructor options for {@link GeminaTokenManager}. */\nexport interface GeminaTokenManagerOptions {\n /**\n * Callback that obtains a fresh session token from the TENANT'S OWN\n * backend (which in turn calls Gemina's `POST /v1/sessions/token` with\n * the API key, server-side). It must resolve with\n * `{ token, expiresIn }`. It must NEVER return a Gemina API key.\n */\n fetchToken: () => Promise<FetchTokenResult>;\n /**\n * How many seconds before the token's expiry `getToken()` starts\n * refreshing. Default 60 (the PRD's `exp − 60s` refresh point).\n */\n refreshSkewSeconds?: number;\n}\n\n/** Gemina API keys are exactly 32 alphanumerics with no prefix. */\nconst API_KEY_SHAPE = /^[A-Za-z0-9]{32}$/;\n\nconst API_KEY_ERROR =\n 'GeminaTokenManager received an API-key-shaped credential (32 alphanumeric ' +\n 'characters). Gemina API keys are master keys and must NEVER enter the ' +\n 'browser: mint a short-lived session token on YOUR backend via ' +\n 'POST /v1/sessions/token (sessions.mintRetrievalToken in @gemina/sdk) and ' +\n 'return { token, expiresIn } from fetchToken instead.';\n\ninterface TokenState {\n fetchToken: () => Promise<FetchTokenResult>;\n refreshSkewMs: number;\n /** The cached raw token, or null when absent/invalidated. */\n token: string | null;\n /** Epoch ms after which the cached token is considered expired. */\n expiresAtMs: number;\n /** Shared in-flight refresh, so concurrent callers never stampede. */\n inFlight: Promise<string> | null;\n /** Bumped by invalidate(); stale refreshes must not repopulate the cache. */\n epoch: number;\n}\n\n// Module-private state store — see the header comment for why the token is\n// deliberately NOT an own property of the instance.\nconst STATES = new WeakMap<GeminaTokenManager, TokenState>();\n\nfunction getState(manager: GeminaTokenManager): TokenState {\n const state = STATES.get(manager);\n if (state === undefined) {\n throw new Error(\n 'GeminaTokenManager state missing — was the instance constructed normally? ' +\n '(Object.create/deserialization is not supported.)',\n );\n }\n return state;\n}\n\n/**\n * Validate what `fetchToken` resolved with and return the raw token.\n * Rejects API-key-shaped strings and anything that is not JWT-shaped.\n */\nfunction validateFetchedToken(result: FetchTokenResult): string {\n if (result === null || typeof result !== 'object') {\n throw new Error(\n 'GeminaTokenManager: fetchToken must resolve with { token, expiresIn } ' +\n `(got ${result === null ? 'null' : typeof result}).`,\n );\n }\n const { token, expiresIn } = result;\n if (typeof token !== 'string' || token.length === 0) {\n throw new Error(\n 'GeminaTokenManager: fetchToken resolved without a token string. ' +\n 'Return { token, expiresIn } from the mint response.',\n );\n }\n if (API_KEY_SHAPE.test(token)) {\n throw new Error(API_KEY_ERROR);\n }\n // Session tokens are JWTs: exactly three non-empty dot-separated segments.\n const segments = token.split('.');\n if (segments.length !== 3 || segments.some((segment) => segment.length === 0)) {\n throw new Error(\n 'GeminaTokenManager: fetchToken resolved with a value that is not a ' +\n 'session token. Gemina session tokens are JWTs (three dot-separated ' +\n 'segments); return the `token` field from POST /v1/sessions/token.',\n );\n }\n if (typeof expiresIn !== 'number' || !Number.isFinite(expiresIn) || expiresIn <= 0) {\n throw new Error(\n 'GeminaTokenManager: fetchToken resolved with an invalid expiresIn ' +\n `(${String(expiresIn)}). Return the mint response's expiresIn (seconds > 0).`,\n );\n }\n return token;\n}\n\n/**\n * Holds a short-lived Gemina session token in memory and keeps it fresh.\n *\n * ```ts\n * const tokenManager = new GeminaTokenManager({\n * // YOUR backend endpoint — it holds the API key and mints the token.\n * fetchToken: async () => {\n * const res = await fetch(\"/api/gemina-session\", { method: \"POST\" });\n * if (!res.ok) throw new Error(\"Failed to mint Gemina session token\");\n * return res.json(); // { token, expiresIn }\n * },\n * });\n * ```\n *\n * - `getToken()` fetches lazily on first use, then auto-refreshes when the\n * cached token is within `refreshSkewSeconds` of expiry. Concurrent\n * callers share a single in-flight fetch.\n * - `invalidate()` drops the cache so the next `getToken()` refetches\n * (use after a 401).\n * - No timers run while idle; nothing is ever written to storage.\n */\nexport class GeminaTokenManager {\n constructor(options: GeminaTokenManagerOptions) {\n if (typeof options === 'string') {\n // Someone did `new GeminaTokenManager(\"<api key or token>\")`.\n throw new Error(\n API_KEY_SHAPE.test(options)\n ? API_KEY_ERROR\n : 'GeminaTokenManager takes { fetchToken } — a callback that asks ' +\n 'YOUR backend for a fresh session token — not a raw string. ' +\n 'Never pass a Gemina API key to browser code.',\n );\n }\n if (options === null || typeof options !== 'object') {\n throw new Error(\n 'GeminaTokenManager requires an options object: new GeminaTokenManager({ fetchToken }).',\n );\n }\n const { fetchToken, refreshSkewSeconds = 60 } = options;\n if (typeof fetchToken === 'string') {\n throw new Error(\n (API_KEY_SHAPE.test(fetchToken) ? `${API_KEY_ERROR} ` : '') +\n 'GeminaTokenManager: fetchToken must be a function returning ' +\n 'Promise<{ token, expiresIn }>, not a string.',\n );\n }\n if (typeof fetchToken !== 'function') {\n throw new Error(\n 'GeminaTokenManager: fetchToken is required and must be a function ' +\n 'returning Promise<{ token, expiresIn }>.',\n );\n }\n if (\n typeof refreshSkewSeconds !== 'number' ||\n !Number.isFinite(refreshSkewSeconds) ||\n refreshSkewSeconds < 0\n ) {\n throw new Error(\n `GeminaTokenManager: refreshSkewSeconds must be a non-negative number (got ${String(\n refreshSkewSeconds,\n )}).`,\n );\n }\n\n STATES.set(this, {\n fetchToken,\n refreshSkewMs: refreshSkewSeconds * 1000,\n token: null,\n expiresAtMs: 0,\n inFlight: null,\n epoch: 0,\n });\n }\n\n /**\n * Return a valid session token, fetching or refreshing as needed.\n *\n * A cached token is reused until `now >= expiry - refreshSkewSeconds`\n * (expiry computed as `Date.now() + expiresIn * 1000` at fetch time).\n * All concurrent callers during a refresh share ONE in-flight fetch.\n * A failed fetch is not cached — the next call retries.\n */\n getToken(): Promise<string> {\n const state = getState(this);\n\n if (state.token !== null && Date.now() < state.expiresAtMs - state.refreshSkewMs) {\n return Promise.resolve(state.token);\n }\n\n if (state.inFlight !== null) {\n return state.inFlight;\n }\n\n const epoch = state.epoch;\n const fetchStartedAtMs = Date.now();\n // Start the user callback immediately (getToken() should fire the mint\n // request right away), but convert a synchronous throw into a rejection\n // so the in-flight bookkeeping below stays consistent.\n let fetched: Promise<FetchTokenResult>;\n try {\n fetched = Promise.resolve(state.fetchToken());\n } catch (error) {\n fetched = Promise.reject(error);\n }\n const inFlight: Promise<string> = fetched\n .then((result) => {\n const token = validateFetchedToken(result);\n if (state.epoch === epoch) {\n state.token = token;\n state.expiresAtMs = fetchStartedAtMs + result.expiresIn * 1000;\n }\n // If invalidate() ran mid-flight, still hand this (already-minted)\n // token to the callers who asked before the invalidation — but do\n // not cache it; the next getToken() fetches fresh.\n return token;\n })\n .finally(() => {\n if (state.inFlight === inFlight) {\n state.inFlight = null;\n }\n });\n\n state.inFlight = inFlight;\n return inFlight;\n }\n\n /**\n * Drop the cached token (and detach any in-flight refresh) so the next\n * `getToken()` fetches a fresh one. Call this when the API answers 401,\n * then retry the request once with a new `getToken()`.\n */\n invalidate(): void {\n const state = getState(this);\n state.token = null;\n state.expiresAtMs = 0;\n state.inFlight = null;\n state.epoch += 1;\n }\n}\n","/**\n * <GeminaChat> — drop-in chat UI over Gemina Document Intelligence.\n *\n * Auth flows exclusively through a {@link GeminaTokenManager}: the component\n * asks it for a short-lived session token per turn and calls\n * `POST /v1/chat/query` through `@gemina/sdk`. It never sees — and cannot\n * accept — a Gemina API key (the token manager throws on API-key-shaped\n * credentials).\n *\n * SSR-safe: no `window`/`document` access at import time; styles are\n * injected on mount.\n */\nimport { useCallback, useEffect, useRef, useState } from 'react';\nimport type * as React from 'react';\nimport { GeminaClient } from '@gemina/sdk';\nimport type { ChatQueryOutDTO } from '@gemina/sdk';\nimport { getResponseLike, httpStatus, readErrorEnvelope } from './internal/response-like';\nimport type { GeminaTokenManager } from './token-manager';\nimport { VERSION } from './version';\n\n/** Visual theme. `\"auto\"` follows `prefers-color-scheme`. */\nexport type GeminaChatTheme = 'light' | 'dark' | 'auto';\n\n/**\n * Text direction. `\"auto\"` flips the widget to RTL when the user's latest\n * message contains Hebrew, and lets each bubble resolve its own direction.\n */\nexport type GeminaChatDirection = 'ltr' | 'rtl' | 'auto';\n\nexport interface GeminaChatProps {\n /** Token source. Required — see {@link GeminaTokenManager}. */\n tokenManager: GeminaTokenManager;\n /** Gemina API base URL (default `https://api.gemina.co`). */\n baseUrl?: string;\n /**\n * Optional end-user id forwarded with each query. On the session-token\n * path the token's SIGNED scope always wins server-side — this is a\n * hint, not a security control.\n */\n endUserId?: string;\n /** Visual theme (default `\"auto\"`). */\n theme?: GeminaChatTheme;\n /** Text direction (default `\"auto\"`). */\n dir?: GeminaChatDirection;\n /** Input placeholder text. */\n placeholder?: string;\n /**\n * Header text — whatever identity the embedding platform wants the chat\n * to carry: a brand (\"Acme Invoices\"), an assistant persona (\"Gemina's\n * AI Rep\"), anything. Text only, rendered verbatim. When set, the header\n * is always visible; without it the header appears only once a\n * conversation has started (to host \"New chat\"). Colors and fonts are\n * themeable separately via the `--gemina-chat-*` CSS variables\n * (including `--gemina-chat-header-bg` for the header bar).\n */\n title?: string;\n /**\n * Plain text shown centered in the empty conversation area until the\n * first message. Use it to set expectations about what the assistant\n * can and can't see (e.g. \"Answers come from your indexed document\n * data\"). Newlines split it into separately spaced paragraphs — no\n * markup, so the string stays safe and portable.\n */\n intro?: string;\n /** Called with the cited `documentId` when a citation chip is clicked. */\n onCitationClick?: (documentId: string) => void;\n /** Extra class name(s) for the root element (e.g. to override CSS vars). */\n className?: string;\n}\n\ninterface UserMessage {\n id: number;\n role: 'user';\n text: string;\n}\n\ninterface AssistantMessage {\n id: number;\n role: 'assistant';\n text: string;\n citations: string[];\n confident: boolean;\n}\n\ninterface ErrorMessage {\n id: number;\n role: 'error';\n text: string;\n /** Present only when a retry is offered; holds the original user text. */\n retryText?: string;\n}\n\ntype ChatMessage = UserMessage | AssistantMessage | ErrorMessage;\n\n/** `Omit` that distributes over each member of a union. */\ntype DistributiveOmit<T, K extends PropertyKey> = T extends unknown ? Omit<T, K> : never;\n\ntype ChatMessageInput = DistributiveOmit<ChatMessage, 'id'>;\n\n/** Hebrew Unicode block (U+0590–U+05FF). */\nconst HEBREW_RE = /[\\u0590-\\u05FF]/;\n\n// Stable backend error codes. These survive production's `detail`-stripping\n// (see the chat-pricing handoff); we switch on HTTP status first and refine\n// with these where the same status can mean two different things.\nconst ERR_CHAT_QUOTA_EXCEEDED = 'CHAT_QUOTA_EXCEEDED';\nconst ERR_DI_NOT_IN_PLAN = 'DOCUMENT_INTELLIGENCE_NOT_IN_PLAN';\nconst ERR_UNPROCESSABLE = 'UNPROCESSABLE_ERROR';\nconst ERR_BAD_GATEWAY = 'BAD_GATEWAY_ERROR';\n// A conversation id that the server no longer knows (24h idle TTL, explicit\n// reset, or end-user scope drift). A turn that CARRIED a session and 404s is\n// this by construction — the chat/query handler raises 404 for nothing else —\n// so the component drops the id and restarts the conversation transparently.\nconst ERR_CHAT_SESSION_NOT_FOUND = 'CHAT_SESSION_NOT_FOUND';\n\ninterface ChatErrorInfo {\n status: number | undefined;\n errorCode: string | undefined;\n /** Human-readable server fallback (`errors[0].description`). */\n description: string | undefined;\n /** Whole seconds until reset, from the `Retry-After` header (429). */\n retryAfterSeconds: number | undefined;\n}\n\n/**\n * Read what the backend actually sent on an error. Only the HTTP status, the\n * stable `errors[0].error_code` / `description`, and the `Retry-After` header\n * are reliable across environments — production strips `errors[0].detail`, so\n * we never touch it. The envelope parsing (with its defensive clone/json\n * dance) lives in `readErrorEnvelope`; only the `Retry-After` header handling\n * is chat-specific.\n */\nasync function readChatError(error: unknown): Promise<ChatErrorInfo> {\n const envelope = await readErrorEnvelope(error);\n const info: ChatErrorInfo = { ...envelope, retryAfterSeconds: undefined };\n\n const rawRetryAfter = getResponseLike(error)?.headers?.get?.('retry-after');\n if (rawRetryAfter !== null && rawRetryAfter !== undefined) {\n const seconds = Number(rawRetryAfter);\n if (Number.isFinite(seconds) && seconds > 0) {\n info.retryAfterSeconds = seconds;\n }\n }\n return info;\n}\n\nconst SESSION_EXPIRED_TEXT = 'Session expired — please reload the page or sign in again.';\nconst CONVERSATION_RESET_TEXT =\n 'This conversation is no longer available — send your message again to start a new one.';\nconst RATE_LIMIT_TEXT = \"You're sending messages too quickly — try again shortly.\";\nconst PLAN_GATE_TEXT = \"Chat isn't included in your plan.\";\nconst UNANSWERABLE_TEXT = \"We couldn't answer that. Try rephrasing your question.\";\nconst SERVICE_UNAVAILABLE_TEXT = 'The chat service is temporarily unavailable. Please try again.';\nconst GENERIC_ERROR_TEXT = \"Something went wrong and your message wasn't answered.\";\n\n/** Friendly \"resets in about N days/hours/minutes\" from Retry-After seconds. */\nfunction formatResetHint(seconds: number | undefined): string {\n if (seconds === undefined || !Number.isFinite(seconds) || seconds <= 0) {\n return 'at the next billing cycle';\n }\n const days = Math.round(seconds / 86400);\n if (days >= 1) {\n return `in about ${days} day${days === 1 ? '' : 's'}`;\n }\n const hours = Math.round(seconds / 3600);\n if (hours >= 1) {\n return `in about ${hours} hour${hours === 1 ? '' : 's'}`;\n }\n const minutes = Math.max(1, Math.round(seconds / 60));\n return `in about ${minutes} minute${minutes === 1 ? '' : 's'}`;\n}\n\n/**\n * Map a chat error to the bubble we render. Switches on HTTP status, refined by\n * the stable backend `error_code`. `retryText` is set only when resending the\n * same text could plausibly succeed — never for quota / plan / validation\n * outcomes, where an identical retry would just fail the same way.\n */\nfunction describeChatError(info: ChatErrorInfo, originalText: string): ChatMessageInput {\n const { status, errorCode } = info;\n\n // Over the included cap AND out of credits — the chat is blocked. Retrying\n // won't help; point at the reset time from the Retry-After header.\n if (status === 429 && errorCode === ERR_CHAT_QUOTA_EXCEEDED) {\n return {\n role: 'error',\n text: `You've used your included chats and are out of credits. Included chats reset ${formatResetHint(\n info.retryAfterSeconds,\n )}.`,\n };\n }\n // Any other 429 is a transient rate limit — a retry after a moment is fine.\n if (status === 429) {\n return { role: 'error', text: RATE_LIMIT_TEXT, retryText: originalText };\n }\n // Document Intelligence not in the plan/contract. NOT an auth failure.\n if (status === 402 || status === 403 || errorCode === ERR_DI_NOT_IN_PLAN) {\n return { role: 'error', text: PLAN_GATE_TEXT };\n }\n // Session expired — only surfaces after the 401-invalidate-retry-once path\n // has already failed a second time.\n if (status === 401) {\n return { role: 'error', text: SESSION_EXPIRED_TEXT };\n }\n // A stale conversation id that slipped past the transparent restart — only\n // the stable error_code reliably means \"the conversation is gone\". A bare 404\n // is a routing/gateway miss (e.g. the endpoint isn't deployed), which reads\n // better as a transient service error than a confusing \"conversation reset\".\n if (errorCode === ERR_CHAT_SESSION_NOT_FOUND) {\n return { role: 'error', text: CONVERSATION_RESET_TEXT, retryText: originalText };\n }\n if (status === 404) {\n return { role: 'error', text: SERVICE_UNAVAILABLE_TEXT, retryText: originalText };\n }\n // The question couldn't be answered (e.g. no searchable text). Expected, not\n // a server error — invite a rephrase rather than a blind retry.\n if (status === 422 || errorCode === ERR_UNPROCESSABLE) {\n return { role: 'error', text: UNANSWERABLE_TEXT };\n }\n // Chat backend timed out / unreachable — transient, offer retry.\n if (status === 502 || errorCode === ERR_BAD_GATEWAY) {\n return { role: 'error', text: SERVICE_UNAVAILABLE_TEXT, retryText: originalText };\n }\n // Anything else (incl. 500): prefer the server's description if it sent one.\n return {\n role: 'error',\n text: info.description ?? GENERIC_ERROR_TEXT,\n retryText: originalText,\n };\n}\n\n/**\n * The API reports citations as an array of `documentId` strings; normalize\n * defensively so `{ documentId }` objects also work if the shape evolves.\n */\nfunction normalizeCitations(citations: unknown): string[] {\n if (!Array.isArray(citations)) {\n return [];\n }\n const ids: string[] = [];\n for (const item of citations) {\n if (typeof item === 'string' && item.length > 0) {\n ids.push(item);\n } else if (\n item !== null &&\n typeof item === 'object' &&\n typeof (item as { documentId?: unknown }).documentId === 'string'\n ) {\n ids.push((item as { documentId: string }).documentId);\n }\n }\n return ids;\n}\n\n// --- Styles -----------------------------------------------------------------\n// Hand-rolled, no UI deps. Everything is scoped under .gemina-chat and driven\n// by CSS custom properties so host apps can re-theme without touching the DOM.\n\nconst DARK_VARS = `\n --gemina-chat-bg: #101418;\n --gemina-chat-fg: #e6e9ee;\n --gemina-chat-border: #2a323c;\n --gemina-chat-accent: #4c8dff;\n --gemina-chat-accent-fg: #ffffff;\n --gemina-chat-assistant-bg: #1c232b;\n --gemina-chat-assistant-fg: #e6e9ee;\n --gemina-chat-muted: #98a2b3;\n --gemina-chat-error: #f97066;\n --gemina-chat-low-confidence: #f7b27a;\n`;\n\nconst CHAT_CSS = `\n.gemina-chat {\n --gemina-chat-bg: #ffffff;\n --gemina-chat-fg: #1a1d21;\n --gemina-chat-border: #d9dce1;\n --gemina-chat-accent: #2f6fed;\n --gemina-chat-accent-fg: #ffffff;\n --gemina-chat-assistant-bg: #f2f4f7;\n --gemina-chat-assistant-fg: #1a1d21;\n --gemina-chat-muted: #667085;\n --gemina-chat-error: #b42318;\n --gemina-chat-low-confidence: #b54708;\n --gemina-chat-header-bg: transparent;\n --gemina-chat-radius: 10px;\n --gemina-chat-font: system-ui, -apple-system, \"Segoe UI\", Roboto, sans-serif;\n\n box-sizing: border-box;\n display: flex;\n flex-direction: column;\n min-height: 320px;\n max-height: 600px;\n background: var(--gemina-chat-bg);\n color: var(--gemina-chat-fg);\n border: 1px solid var(--gemina-chat-border);\n border-radius: var(--gemina-chat-radius);\n font-family: var(--gemina-chat-font);\n font-size: 14px;\n line-height: 1.5;\n}\n.gemina-chat *, .gemina-chat *::before, .gemina-chat *::after { box-sizing: border-box; }\n.gemina-chat--dark { ${DARK_VARS} }\n@media (prefers-color-scheme: dark) {\n .gemina-chat--auto { ${DARK_VARS} }\n}\n.gemina-chat__header {\n display: flex;\n align-items: center;\n /* Guaranteed minimum separation. The pushing itself is the button's\n auto margin below — NOT a margin on the title, whose dir=\"auto\" can\n resolve opposite to the widget (English title in an RTL chat) and\n collapse an inline-aware margin to the wrong side. */\n gap: 12px;\n flex: 0 0 auto;\n padding: 6px 10px;\n border-bottom: 1px solid var(--gemina-chat-border);\n background: var(--gemina-chat-header-bg);\n}\n.gemina-chat__title {\n font-size: 13px;\n font-weight: 600;\n overflow: hidden;\n text-overflow: ellipsis;\n white-space: nowrap;\n}\n.gemina-chat__newchat {\n margin-inline-start: auto;\n flex-shrink: 0;\n font: inherit;\n font-size: 12px;\n padding: 3px 10px;\n border-radius: var(--gemina-chat-radius);\n border: 1px solid var(--gemina-chat-border);\n background: transparent;\n color: var(--gemina-chat-accent);\n cursor: pointer;\n}\n.gemina-chat__newchat:hover:not(:disabled) { border-color: var(--gemina-chat-accent); }\n.gemina-chat__newchat:disabled { opacity: 0.5; cursor: default; }\n.gemina-chat__log {\n flex: 1;\n overflow-y: auto;\n padding: 12px;\n display: flex;\n flex-direction: column;\n gap: 8px;\n}\n.gemina-chat__msg {\n max-width: 85%;\n padding: 8px 12px;\n border-radius: var(--gemina-chat-radius);\n white-space: pre-wrap;\n overflow-wrap: break-word;\n}\n.gemina-chat__msg--user {\n align-self: flex-end;\n background: var(--gemina-chat-accent);\n color: var(--gemina-chat-accent-fg);\n}\n.gemina-chat--rtl .gemina-chat__msg--user, .gemina-chat[dir=\"rtl\"] .gemina-chat__msg--user {\n align-self: flex-start;\n}\n.gemina-chat--rtl .gemina-chat__msg--assistant, .gemina-chat[dir=\"rtl\"] .gemina-chat__msg--assistant {\n align-self: flex-end;\n}\n.gemina-chat__msg--assistant {\n align-self: flex-start;\n background: var(--gemina-chat-assistant-bg);\n color: var(--gemina-chat-assistant-fg);\n}\n.gemina-chat__msg--low-confidence {\n border: 1px dashed var(--gemina-chat-low-confidence);\n}\n.gemina-chat__low-confidence-note {\n margin-top: 6px;\n font-size: 12px;\n color: var(--gemina-chat-low-confidence);\n}\n.gemina-chat__citations {\n display: flex;\n flex-wrap: wrap;\n gap: 4px;\n margin-top: 6px;\n}\n.gemina-chat__citation {\n font: inherit;\n font-size: 12px;\n padding: 2px 8px;\n border-radius: 999px;\n border: 1px solid var(--gemina-chat-border);\n background: transparent;\n color: var(--gemina-chat-accent);\n cursor: pointer;\n}\n.gemina-chat__citation:hover { border-color: var(--gemina-chat-accent); }\n.gemina-chat__msg--error {\n align-self: flex-start;\n background: transparent;\n border: 1px solid var(--gemina-chat-error);\n color: var(--gemina-chat-error);\n}\n.gemina-chat__retry {\n font: inherit;\n font-size: 12px;\n margin-top: 6px;\n display: block;\n padding: 2px 10px;\n border-radius: var(--gemina-chat-radius);\n border: 1px solid var(--gemina-chat-error);\n background: transparent;\n color: var(--gemina-chat-error);\n cursor: pointer;\n}\n.gemina-chat__intro {\n display: flex;\n flex-direction: column;\n gap: 10px;\n margin: auto;\n max-width: 46ch;\n padding: 16px;\n text-align: center;\n font-size: 13px;\n color: var(--gemina-chat-muted);\n}\n.gemina-chat__intro-line { margin: 0; }\n.gemina-chat__typing {\n align-self: flex-start;\n display: flex;\n align-items: center;\n gap: 5px;\n color: var(--gemina-chat-muted);\n font-size: 12px;\n padding: 0 4px;\n}\n.gemina-chat__typing-dots {\n display: inline-flex;\n align-items: center;\n gap: 3px;\n}\n.gemina-chat__typing-dots span {\n width: 4px;\n height: 4px;\n border-radius: 50%;\n background: currentColor;\n opacity: 0.25;\n animation: gemina-chat-thinking 1.2s infinite ease-in-out;\n}\n.gemina-chat__typing-dots span:nth-child(2) { animation-delay: 0.2s; }\n.gemina-chat__typing-dots span:nth-child(3) { animation-delay: 0.4s; }\n@keyframes gemina-chat-thinking {\n 0%, 60%, 100% { opacity: 0.25; transform: translateY(0); }\n 30% { opacity: 1; transform: translateY(-2px); }\n}\n@media (prefers-reduced-motion: reduce) {\n .gemina-chat__typing-dots span { animation: none; opacity: 0.6; }\n}\n.gemina-chat__composer {\n display: flex;\n gap: 8px;\n padding: 10px;\n border-top: 1px solid var(--gemina-chat-border);\n}\n.gemina-chat__input {\n flex: 1;\n resize: none;\n font: inherit;\n color: inherit;\n background: transparent;\n border: 1px solid var(--gemina-chat-border);\n border-radius: var(--gemina-chat-radius);\n padding: 8px 10px;\n min-height: 38px;\n}\n.gemina-chat__input:focus {\n outline: 2px solid var(--gemina-chat-accent);\n outline-offset: -1px;\n}\n.gemina-chat__send {\n font: inherit;\n align-self: flex-end;\n border: none;\n border-radius: var(--gemina-chat-radius);\n background: var(--gemina-chat-accent);\n color: var(--gemina-chat-accent-fg);\n padding: 8px 16px;\n cursor: pointer;\n}\n.gemina-chat__send:disabled { opacity: 0.5; cursor: default; }\n`;\n\nconst STYLE_ATTR = 'data-gemina-chat';\n\n/**\n * Inject the widget stylesheet once per document (idempotent across\n * instances; intentionally not removed on unmount so sibling instances and\n * quick remounts never flash unstyled).\n */\nfunction ensureStylesInjected(): void {\n if (typeof document === 'undefined') {\n return;\n }\n if (document.head.querySelector(`style[${STYLE_ATTR}]`) !== null) {\n return;\n }\n const style = document.createElement('style');\n style.setAttribute(STYLE_ATTR, VERSION);\n style.textContent = CHAT_CSS;\n document.head.appendChild(style);\n}\n\n/**\n * Embeddable Gemina Document Intelligence chat.\n *\n * ```tsx\n * <GeminaChat\n * tokenManager={tokenManager}\n * onCitationClick={(documentId) => openDocument(documentId)}\n * />\n * ```\n */\nexport function GeminaChat(props: GeminaChatProps): React.JSX.Element {\n const {\n tokenManager,\n baseUrl,\n endUserId,\n theme = 'auto',\n dir = 'auto',\n placeholder = 'Ask about your documents…',\n title,\n intro,\n onCitationClick,\n className,\n } = props;\n\n const [messages, setMessages] = useState<ChatMessage[]>([]);\n const [draft, setDraft] = useState('');\n const [busy, setBusy] = useState(false);\n const nextIdRef = useRef(0);\n const mountedRef = useRef(false);\n const logRef = useRef<HTMLDivElement | null>(null);\n // The conversation id (server-issued) that gives the chat memory across\n // turns. Held in a ref, not state: it changes per turn but must never\n // trigger a re-render, and the send flow reads its latest value directly.\n // Distinct from the auth session TOKEN the token manager holds.\n const sessionIdRef = useRef<string | undefined>(undefined);\n\n useEffect(() => {\n mountedRef.current = true;\n ensureStylesInjected();\n return () => {\n mountedRef.current = false;\n };\n }, []);\n\n // Keep the newest message in view.\n useEffect(() => {\n const log = logRef.current;\n if (log !== null) {\n log.scrollTop = log.scrollHeight;\n }\n }, [messages, busy]);\n\n const appendMessage = useCallback((message: ChatMessageInput) => {\n const id = nextIdRef.current++;\n setMessages((prev) => [...prev, { ...message, id }]);\n }, []);\n\n const chatOnce = useCallback(\n (token: string, message: string): Promise<ChatQueryOutDTO> => {\n const client = GeminaClient.withSessionToken(token, baseUrl);\n const sessionId = sessionIdRef.current;\n return client.chat.chatQuery({\n // Thread the conversation id when we have one so follow-ups resolve\n // referents (\"what about the total?\"); omit it to start a new one.\n chatQueryInDTO: { message, endUserId, ...(sessionId ? { sessionId } : {}) },\n });\n },\n [baseUrl, endUserId],\n );\n\n /** One turn, with the mandated 401-invalidate-retry-once behavior. */\n const queryWithRetry = useCallback(\n async (message: string): Promise<ChatQueryOutDTO> => {\n const token = await tokenManager.getToken();\n try {\n return await chatOnce(token, message);\n } catch (error) {\n if (httpStatus(error) !== 401) {\n throw error;\n }\n // Token likely expired mid-session: drop it, re-mint via the\n // tenant backend, retry exactly once. A second 401 propagates.\n tokenManager.invalidate();\n const freshToken = await tokenManager.getToken();\n return await chatOnce(freshToken, message);\n }\n },\n [tokenManager, chatOnce],\n );\n\n const performSend = useCallback(\n async (text: string) => {\n setBusy(true);\n try {\n let result: ChatQueryOutDTO;\n const hadSession = sessionIdRef.current !== undefined;\n try {\n result = await queryWithRetry(text);\n } catch (error) {\n // A turn that CARRIED a session and 404s means the conversation is\n // gone (24h idle TTL, an explicit reset, or end-user scope drift).\n // Drop the stale id and retry once as a fresh conversation, so the\n // expiry is transparent — the user just gets an answer, no memory.\n if (hadSession && httpStatus(error) === 404) {\n sessionIdRef.current = undefined;\n result = await queryWithRetry(text);\n } else {\n throw error;\n }\n }\n if (!mountedRef.current) {\n return;\n }\n // The response always returns the (possibly newly created) conversation\n // id — store it so the next turn continues this thread.\n sessionIdRef.current = result.sessionId ?? sessionIdRef.current;\n appendMessage({\n role: 'assistant',\n text: result.answer,\n citations: normalizeCitations(result.citations),\n confident: result.confident !== false,\n });\n } catch (error) {\n if (!mountedRef.current) {\n return;\n }\n // Reading the error body is async (fetch), so re-check mount after.\n const info = await readChatError(error);\n if (!mountedRef.current) {\n return;\n }\n appendMessage(describeChatError(info, text));\n } finally {\n if (mountedRef.current) {\n setBusy(false);\n }\n }\n },\n [queryWithRetry, appendMessage],\n );\n\n /**\n * Reset to a brand-new conversation: clear the transcript and forget the\n * session id so the next message starts fresh. The old session is deleted\n * server-side best-effort — the local reset is authoritative, and a failed\n * delete just leaves the session to lapse on its idle TTL.\n */\n const startNewChat = useCallback(() => {\n if (busy) {\n return;\n }\n const staleSession = sessionIdRef.current;\n sessionIdRef.current = undefined;\n setMessages([]);\n setDraft('');\n if (staleSession !== undefined) {\n void (async () => {\n try {\n const token = await tokenManager.getToken();\n await GeminaClient.withSessionToken(token, baseUrl).chat.deleteChatSession({\n sessionId: staleSession,\n });\n } catch {\n // Unreachable/expired session: nothing to clean up client-side.\n }\n })();\n }\n }, [busy, tokenManager, baseUrl]);\n\n const submitDraft = useCallback(() => {\n const text = draft.trim();\n if (text.length === 0 || busy) {\n return;\n }\n setDraft('');\n appendMessage({ role: 'user', text });\n void performSend(text);\n }, [draft, busy, appendMessage, performSend]);\n\n const retryMessage = useCallback(\n (failed: ErrorMessage) => {\n if (busy || failed.retryText === undefined) {\n return;\n }\n const text = failed.retryText;\n // Replace the error entry; the original user bubble is still there.\n setMessages((prev) => prev.filter((message) => message.id !== failed.id));\n void performSend(text);\n },\n [busy, performSend],\n );\n\n const handleKeyDown = useCallback(\n (event: React.KeyboardEvent<HTMLTextAreaElement>) => {\n if (event.key === 'Enter' && !event.shiftKey) {\n event.preventDefault();\n submitDraft();\n }\n },\n [submitDraft],\n );\n\n const handleSubmit = useCallback(\n (event: React.FormEvent<HTMLFormElement>) => {\n event.preventDefault();\n submitDraft();\n },\n [submitDraft],\n );\n\n // dir=\"auto\": follow the user's latest message (Hebrew → RTL); individual\n // bubbles additionally resolve their own direction via dir=\"auto\".\n let effectiveDir: 'ltr' | 'rtl';\n if (dir === 'auto') {\n let lastUserText = '';\n for (let i = messages.length - 1; i >= 0; i--) {\n const message = messages[i];\n if (message !== undefined && message.role === 'user') {\n lastUserText = message.text;\n break;\n }\n }\n effectiveDir = HEBREW_RE.test(lastUserText) ? 'rtl' : 'ltr';\n } else {\n effectiveDir = dir;\n }\n const bubbleDir = dir === 'auto' ? 'auto' : undefined;\n\n const rootClassName = [\n 'gemina-chat',\n `gemina-chat--${theme}`,\n effectiveDir === 'rtl' ? 'gemina-chat--rtl' : '',\n className ?? '',\n ]\n .filter((part) => part.length > 0)\n .join(' ');\n\n return (\n <div className={rootClassName} dir={effectiveDir}>\n {(title !== undefined || messages.length > 0) && (\n <div className=\"gemina-chat__header\">\n {title !== undefined && (\n <div className=\"gemina-chat__title\" dir={bubbleDir}>\n {title}\n </div>\n )}\n {messages.length > 0 && (\n <button\n type=\"button\"\n className=\"gemina-chat__newchat\"\n onClick={startNewChat}\n disabled={busy}\n >\n New chat\n </button>\n )}\n </div>\n )}\n <div\n ref={logRef}\n role=\"log\"\n aria-live=\"polite\"\n aria-busy={busy}\n aria-label=\"Chat messages\"\n className=\"gemina-chat__log\"\n >\n {messages.length === 0 && intro !== undefined && (\n <div className=\"gemina-chat__intro\" dir={bubbleDir}>\n {intro\n .split('\\n')\n .filter((line) => line.trim().length > 0)\n .map((line, index) => (\n <p key={index} className=\"gemina-chat__intro-line\">\n {line}\n </p>\n ))}\n </div>\n )}\n {messages.map((message) => {\n if (message.role === 'user') {\n return (\n <div\n key={message.id}\n className=\"gemina-chat__msg gemina-chat__msg--user\"\n dir={bubbleDir}\n >\n {message.text}\n </div>\n );\n }\n if (message.role === 'assistant') {\n const lowConfidence = !message.confident;\n return (\n <div\n key={message.id}\n className={\n 'gemina-chat__msg gemina-chat__msg--assistant' +\n (lowConfidence ? ' gemina-chat__msg--low-confidence' : '')\n }\n dir={bubbleDir}\n >\n {message.text}\n {lowConfidence && (\n <div className=\"gemina-chat__low-confidence-note\">\n Low confidence — please verify against the cited documents.\n </div>\n )}\n {message.citations.length > 0 && (\n <div className=\"gemina-chat__citations\">\n {message.citations.map((documentId, index) => (\n <button\n key={`${documentId}-${index}`}\n type=\"button\"\n className=\"gemina-chat__citation\"\n title={`Open document ${documentId}`}\n onClick={() => onCitationClick?.(documentId)}\n >\n {documentId}\n </button>\n ))}\n </div>\n )}\n </div>\n );\n }\n return (\n <div\n key={message.id}\n role=\"alert\"\n className=\"gemina-chat__msg gemina-chat__msg--error\"\n >\n {message.text}\n {message.retryText !== undefined && (\n <button\n type=\"button\"\n className=\"gemina-chat__retry\"\n onClick={() => retryMessage(message)}\n >\n Retry\n </button>\n )}\n </div>\n );\n })}\n {busy && (\n // The label alone is what the aria-live log announces; the dots are\n // decoration (aria-hidden), and prefers-reduced-motion freezes them.\n <div className=\"gemina-chat__typing\">\n Thinking\n <span className=\"gemina-chat__typing-dots\" aria-hidden=\"true\">\n <span />\n <span />\n <span />\n </span>\n </div>\n )}\n </div>\n <form className=\"gemina-chat__composer\" onSubmit={handleSubmit}>\n <textarea\n className=\"gemina-chat__input\"\n aria-label=\"Chat message\"\n rows={1}\n value={draft}\n placeholder={placeholder}\n dir={bubbleDir}\n onChange={(event) => setDraft(event.target.value)}\n onKeyDown={handleKeyDown}\n />\n <button\n type=\"submit\"\n className=\"gemina-chat__send\"\n aria-label=\"Send message\"\n disabled={busy || draft.trim().length === 0}\n >\n Send\n </button>\n </form>\n </div>\n );\n}\n","/**\n * Shared transport-error helpers for the widgets (chat + verification).\n *\n * Extracted verbatim from chat.tsx so both components read thrown SDK errors\n * the same way. Pure and dependency-free: no React, no DOM.\n */\n\n/**\n * The response-like object carried by a thrown transport error. We pull it off\n * by shape rather than `instanceof ResponseError` — robust against duplicated\n * `@gemina/sdk` copies in a bundle (class identity is not shared across\n * copies). On the fetch transport this is the raw `Response`, so `status`,\n * `headers`, and the JSON body are all reachable from here.\n */\nexport interface ResponseLike {\n status?: number;\n headers?: { get?: (name: string) => string | null };\n json?: () => Promise<unknown>;\n clone?: () => ResponseLike;\n}\n\nexport function getResponseLike(error: unknown): ResponseLike | undefined {\n if (error !== null && typeof error === 'object' && 'response' in error) {\n const response = (error as { response?: unknown }).response;\n if (response !== null && typeof response === 'object') {\n return response as ResponseLike;\n }\n }\n return undefined;\n}\n\n/** Extract an HTTP status from a thrown value, or `undefined`. */\nexport function httpStatus(error: unknown): number | undefined {\n const status = getResponseLike(error)?.status;\n return typeof status === 'number' ? status : undefined;\n}\n\n/** What the standard backend error envelope reliably carries. */\nexport interface ErrorEnvelope {\n status: number | undefined;\n /** Stable backend `errors[0].error_code`. */\n errorCode: string | undefined;\n /** Human-readable server fallback (`errors[0].description`). */\n description: string | undefined;\n}\n\n/**\n * Read what the backend actually sent on an error. Only the HTTP status and\n * the stable `errors[0].error_code` / `description` are reliable across\n * environments — production strips `errors[0].detail`, so we never touch it.\n * The fetch body can be read once, so we clone defensively; if that fails\n * (non-JSON, empty, or already consumed) the status still stands.\n */\nexport async function readErrorEnvelope(error: unknown): Promise<ErrorEnvelope> {\n const response = getResponseLike(error);\n const info: ErrorEnvelope = {\n status: typeof response?.status === 'number' ? response.status : undefined,\n errorCode: undefined,\n description: undefined,\n };\n if (response === undefined) {\n return info;\n }\n\n let body: unknown;\n try {\n const source = typeof response.clone === 'function' ? response.clone() : response;\n body = typeof source.json === 'function' ? await source.json() : undefined;\n } catch {\n body = undefined;\n }\n if (body !== null && typeof body === 'object') {\n const errors = (body as { errors?: unknown }).errors;\n if (\n Array.isArray(errors) &&\n errors.length > 0 &&\n errors[0] !== null &&\n typeof errors[0] === 'object'\n ) {\n const first = errors[0] as { error_code?: unknown; description?: unknown };\n if (typeof first.error_code === 'string') {\n info.errorCode = first.error_code;\n }\n if (typeof first.description === 'string') {\n info.description = first.description;\n }\n }\n }\n return info;\n}\n","/** Package version. Keep in sync with package.json. */\nexport const VERSION = '0.13.2';\n","/**\n * <GeminaVerification> — drop-in human verification UI for one extraction.\n *\n * Auth flows exclusively through a {@link GeminaTokenManager} (chat parity):\n * the component asks it for a short-lived session token and calls\n * `GET /v1/documents/extractions/{id}` through `@gemina/sdk`. It never sees —\n * and cannot accept — a Gemina API key.\n *\n * This module owns the fetch + state machine + edge states (Task 14):\n * loading → unavailable | review — the layout/flash/RTL layer (Task 15):\n * the stacked-below-860px root observer, eye-click → viewer flash wiring,\n * chat-parity Hebrew direction autodetect, and the silent expired-image-URL\n * refresh — the edit state + progress footer (Task 16): the immutable\n * edits map with delete-on-revert dirty tracking, and the\n * \"N confirmed · M corrected\" line fed by composeSubmission — and the submit\n * flow (Task 17): the confirm-final dialog, the PUT with 401\n * invalidate-retry-once, the 409 silent-refetch landing, submit-error with\n * edits preserved, and the exactly-once onComplete.\n *\n * SSR-safe: no `window`/`document` access at import time; styles are\n * injected on mount.\n */\nimport { useCallback, useEffect, useId, useMemo, useRef, useState } from 'react';\nimport type * as React from 'react';\nimport { GeminaClient } from '@gemina/sdk';\nimport type { ExtractionPrimaryViewOutDTO } from '@gemina/sdk';\nimport { httpStatus, readErrorEnvelope } from '../internal/response-like';\nimport { readDescriptors, readRowMutableTables, validateInput } from './field-types';\nimport type { RowMutableTable, ValidationFieldDescriptor } from './field-types';\nimport {\n buildBindings,\n composeSubmission,\n countRowsAt,\n indexBindingsByFieldPointer,\n toInputString,\n} from './bindings';\nimport type { FieldBinding, RowSourcesEntry } from './bindings';\nimport {\n collectCellViews, displayColumns, matchesTablePointer, planTableCells, pruneEmptyAddedRows,\n unitSizePairErrors,\n} from './row-cells';\nimport type { PlannedRow } from './row-cells';\nimport {\n initialRowPlan, insertRowAfter, isIdentityPlan, nextAddedRowId, removeRow, rowSourcesOf,\n} from './row-plan';\nimport type { RowPlanEntry } from './row-plan';\nimport { classifyData, ROW_META_KEY } from './classify';\nimport { VerificationForm } from './form';\nimport { withEmptyMutableTables } from './form';\nimport {\n computeHidden, countUnits, hasAnyConfidence, NOTHING_HIDDEN,\n} from './review-filter';\nimport { ensureVerificationStylesInjected } from './styles';\nimport type {\n GeminaVerificationProps,\n VerificationErrorDetail,\n VerificationErrorReason,\n} from './types';\nimport { VerificationViewer } from './viewer';\nimport type { RelativeRect } from './viewer';\n\nexport type {\n GeminaVerificationProps,\n GeminaVerificationTheme,\n GeminaVerificationDirection,\n VerificationErrorReason,\n VerificationErrorDetail,\n VerificationCompletion,\n} from './types';\n\n/**\n * The component's complete phase model. `review`, `confirming`, `submitting`,\n * and `submit-error` form the REVIEW FAMILY: all four render the same review\n * content (form, edits, aria-live progress — kept mounted so edits stay\n * visible through the whole submit sequence); confirming/submitting add the\n * overlay on top, submit-error the inline error banner. The read-only flag\n * lives in separate `alreadyValidated` state, not in the variants, so the\n * family shares it without every variant re-carrying it.\n */\ntype Phase =\n | { name: 'loading' }\n | { name: 'unavailable'; reason: VerificationErrorReason; message: string; canRetry: boolean }\n | { name: 'review' }\n | { name: 'confirming' } // confirm dialog open over review\n | { name: 'submitting' } // PUT in flight; dialog stays, buttons disabled\n | { name: 'submit-error'; message: string }\n | { name: 'done'; confirmed: number; corrected: number };\n\n/** The four phases that render the review content. */\ntype ReviewFamilyPhase = Extract<\n Phase,\n { name: 'review' | 'confirming' | 'submitting' | 'submit-error' }\n>;\n\n/** Hebrew Unicode block (U+0590–U+05FF) — chat.tsx's exact detector. */\nconst HEBREW_RE = /[\\u0590-\\u05FF]/;\n\n/** Below this root width the two panes stack (one column, sticky viewer). */\nconst STACKED_BREAKPOINT = 860; // px\n\n/** At most one silent image-URL refresh per window — the refetch-loop brake. */\nconst IMAGE_REFRESH_THROTTLE_MS = 60_000;\n\nconst LOADING_TEXT = 'Loading extraction…';\nconst SESSION_EXPIRED_TEXT = 'Session expired — please reload the page or sign in again.';\n// The SUBMIT-side 401 copy must NOT suggest reloading: the reviewer's edits\n// live only in component state, and a reload would destroy them — while a\n// fresh sign-in in another tab plus Retry preserves and submits them.\nconst SUBMIT_SESSION_EXPIRED_TEXT =\n 'Session expired — sign in again in another tab, then press Retry. Your corrections are still here.';\nconst NOT_AVAILABLE_TEXT = 'This extraction is not available.';\nconst LOAD_FAILED_TEXT = \"Couldn't load the extraction.\";\nconst PURGED_TEXT = 'Document no longer available (retention policy).';\nconst NOT_COMPLETED_TEXT = 'This extraction did not complete, so there is nothing to verify.';\nconst VERIFICATION_UNAVAILABLE_TEXT = \"Verification isn't available for this extraction.\";\n// Deliberately does NOT imply the shown data is the corrected data — the\n// primary view returns the ORIGINAL extraction, not the validated values.\nconst ALREADY_VALIDATED_TEXT = 'Already verified — showing the original extraction.';\n// \"Feedback\" is retired from every user-visible string: it framed the\n// reviewer's corrections as an optional opinion collected for someone else,\n// when they are the values that get recorded. The word survives only in code\n// comments and in the API surface (`meta.validationFeedback`, the `onError`\n// reason names), which are contract rather than copy.\nconst CONFIRM_TEXT =\n \"Submit these values? This is final — they can be submitted once and can't be changed.\";\nconst SUBMITTING_TEXT = 'Submitting…';\nconst SUBMIT_FAILED_TEXT = 'Submission failed — your corrections are still here.';\n// Same verb as the action that produced it: Submit -> Submitted.\nconst DONE_TITLE_TEXT = 'Submitted';\n\n/** What a successful load pins for the review phase (values + schema together,\n * so the derived memos see one consistent snapshot). */\ninterface LoadedData {\n values: unknown;\n schema: string[];\n /** Empty whenever the backend or the host's SDK predates the typed contract. */\n fields: ValidationFieldDescriptor[];\n /**\n * Tables the SERVER declares row-mutable. Empty means no row controls\n * anywhere — the correct behaviour against a pre-1.5.0 backend, and the\n * reason a `custom_template` table never grows an Add line button.\n */\n rowMutableTables: RowMutableTable[];\n}\n\n/** The empty edits map — the initial state AND every load's reset value.\n * One shared instance (SectionShared contract: `edits` is compared by\n * reference, so \"no edits\" must always be the same object). */\nconst NO_EDITS: ReadonlyMap<string, string> = new Map();\n\n/** Same reference-stability contract as NO_EDITS, for the row plans. */\nconst NO_ROW_PLANS: ReadonlyMap<string, RowPlanEntry[]> = new Map();\nconst NO_PLANNED_TABLES: ReadonlyMap<string, PlannedRow[]> = new Map();\n\n/**\n * The identity plan for every table the server declared row-mutable.\n *\n * Returns the shared empty map when there are none, so a pre-1.5.0 backend\n * keeps the exact reference-equality behaviour the row memo depends on.\n */\nfunction seedRowPlans(tables: RowMutableTable[], values: unknown): ReadonlyMap<string, RowPlanEntry[]> {\n if (tables.length === 0) {\n return NO_ROW_PLANS;\n }\n const plans = new Map<string, RowPlanEntry[]>();\n for (const table of tables) {\n plans.set(table.pointer, initialRowPlan(countRowsAt(values, table.pointer), table.pointer));\n }\n return plans;\n}\n\n/**\n * Unavailable reasons that are FAILURES (a thrown fetch: 401/404/network/5xx)\n * announce assertively as role=\"alert\". The meta-derived landings (purged,\n * not-completed, verification-unavailable) are calm facts about the extraction\n * — the load succeeded, there is just nothing to verify — and announce\n * politely as role=\"status\".\n */\nconst ALERT_REASONS: ReadonlySet<VerificationErrorReason> = new Set([\n 'session-expired',\n 'not-available',\n 'load-failed',\n]);\n\n/**\n * Embeddable Gemina extraction-verification UI.\n *\n * ```tsx\n * <GeminaVerification\n * extractionId={extractionId}\n * tokenManager={tokenManager}\n * onComplete={(result) => console.log(result.summary)}\n * />\n * ```\n */\nexport function GeminaVerification(props: GeminaVerificationProps): React.JSX.Element {\n const {\n extractionId,\n tokenManager,\n baseUrl,\n theme = 'auto',\n dir = 'auto',\n onComplete,\n onError,\n className,\n } = props;\n\n const [phase, setPhase] = useState<Phase>({ name: 'loading' });\n // Lifted OUT of the review phase variant (Task 17 restructure): the whole\n // review family reads it (read-only form, banner, hidden progress line)\n // while confirming/submitting/submit-error carry no flags of their own.\n // In every load path read-only ⇔ already-validated, so ONE flag serves both.\n const [alreadyValidated, setAlreadyValidated] = useState(false);\n const [loaded, setLoaded] = useState<LoadedData | null>(null);\n // One plan per row-mutable table, keyed by its pointer. Reset with the\n // edits on every load: a plan outliving its extraction would map rows to\n // sources that no longer exist.\n const [rowPlans, setRowPlans] = useState<ReadonlyMap<string, RowPlanEntry[]>>(NO_ROW_PLANS);\n // Dirty fields only: raw schema key → current input string, VERBATIM (no\n // trim/normalize — that is the composer's job at submit). Replaced\n // immutably on every change; delete-on-revert keeps composeSubmission's\n // confirmed/corrected counts honest (see its edits-map contract).\n const [edits, setEdits] = useState<ReadonlyMap<string, string>>(NO_EDITS);\n // Held separately from `loaded`: the expiry refresh swaps an expired URL in\n // place without disturbing the (memo-feeding) values/schema snapshot.\n const [imageUrl, setImageUrl] = useState<string | null>(null);\n // The rects currently flashing on the viewer (null = no flash in flight).\n const [flashRects, setFlashRects] = useState<RelativeRect[] | null>(null);\n // One-column layout, driven by the ROOT's own width (see the observer below).\n const [stacked, setStacked] = useState(false);\n // The review filter hides fields and rows that already scored `high`.\n // OFF by default: this component ships to every embedder, so an unfiltered\n // form is the default everywhere, and the state is never persisted.\n const [filterOn, setFilterOn] = useState(false);\n\n const rootRef = useRef<HTMLDivElement | null>(null);\n const mountedRef = useRef(false);\n // Monotonic load id: a load that lost the race (prop change re-ran the\n // effect, or Retry started a newer attempt) must not write its result.\n const loadSeqRef = useRef(0);\n // Timestamp of the last expiry-triggered refetch (the 60s throttle).\n const lastImageRefreshRef = useRef(0);\n // Latest onError without threading its identity through the load callback.\n const onErrorRef = useRef(onError);\n onErrorRef.current = onError;\n const onCompleteRef = useRef(onComplete);\n onCompleteRef.current = onComplete;\n // onComplete fires EXACTLY once per loaded extraction; load() resets it.\n const completedRef = useRef(false);\n // Re-entry latch for doSubmit (the disabled Confirm button is the UI guard;\n // this is the belt for a re-dispatch racing the disabling re-render).\n const submitInFlightRef = useRef(false);\n // Set by Cancel: focus returns to the Submit button, but only from the\n // effect AFTER the review re-render — while the handler runs the phase is\n // still `confirming`, so the footer button is still disabled and unfocusable.\n const restoreFocusRef = useRef(false);\n const submitButtonRef = useRef<HTMLButtonElement | null>(null);\n const confirmButtonRef = useRef<HTMLButtonElement | null>(null);\n const cancelButtonRef = useRef<HTMLButtonElement | null>(null);\n // Focus landings for the phases that unmount the dialog under the keyboard\n // user: the submit-error Retry button, and the done state (tabIndex -1).\n const retrySubmitButtonRef = useRef<HTMLButtonElement | null>(null);\n const doneStateRef = useRef<HTMLDivElement | null>(null);\n\n /**\n * Enter a terminal unavailable state and notify the host. onError fires\n * once per terminal-state ENTRY (see the prop's JSDoc): each resolved load\n * attempt calls this at most once, and a Retry that fails again re-enters —\n * and therefore re-fires.\n */\n const enterUnavailable = useCallback(\n (\n reason: VerificationErrorReason,\n message: string,\n canRetry: boolean,\n detail?: VerificationErrorDetail,\n ) => {\n setPhase({ name: 'unavailable', reason, message, canRetry });\n onErrorRef.current?.(reason, detail);\n },\n [],\n );\n\n const fetchOnce = useCallback(async () => {\n const token = await tokenManager.getToken();\n return GeminaClient.withSessionToken(token, baseUrl).documents.getDocumentExtraction({\n documentExtractionId: extractionId,\n });\n }, [tokenManager, baseUrl, extractionId]);\n\n /** The chat widget's mandated 401 pattern: invalidate + retry exactly once. */\n const fetchWithRetry = useCallback(async () => {\n try {\n return await fetchOnce();\n } catch (error) {\n if (httpStatus(error) !== 401) {\n throw error;\n }\n tokenManager.invalidate();\n return await fetchOnce();\n }\n }, [fetchOnce, tokenManager]);\n\n const load = useCallback(async () => {\n const seq = ++loadSeqRef.current;\n /** Guard on EVERY async setState: unmount AND stale-load protection. */\n const live = () => mountedRef.current && loadSeqRef.current === seq;\n\n setPhase({ name: 'loading' });\n // Per-extraction onComplete semantics: a new load (extractionId change,\n // Retry, the 409 refetch) re-arms the exactly-once guard.\n completedRef.current = false;\n // A stale flash must not survive into the next review: the viewer\n // unmounts during loading, and a REMOUNTED viewer handed old non-null\n // flashRects would phantom-flash the new document once it sizes up.\n setFlashRects(null);\n // A new load must not inherit the previous extraction's expiry-refresh\n // throttle window (the viewer is unmounted until review re-enters, so\n // nothing can race this reset).\n lastImageRefreshRef.current = 0;\n let view: ExtractionPrimaryViewOutDTO;\n try {\n view = await fetchWithRetry();\n } catch (error) {\n // Reading the error body is async (fetch), so re-check liveness after.\n const detail = await readErrorEnvelope(error);\n if (!live()) {\n return;\n }\n if (detail.status === 401) {\n // Only reachable after the invalidate-retry-once path failed again.\n enterUnavailable('session-expired', SESSION_EXPIRED_TEXT, false, detail);\n } else if (detail.status === 404) {\n enterUnavailable('not-available', NOT_AVAILABLE_TEXT, false, detail);\n } else {\n // Everything else — 5xx, network failures, and a tokenManager whose\n // fetchToken rejected (no HTTP status at all) — is retryable: the\n // server or the tenant's token backend may recover.\n enterUnavailable('load-failed', LOAD_FAILED_TEXT, true, detail);\n }\n return;\n }\n if (!live()) {\n return;\n }\n\n const enterReview = (validated: boolean) => {\n const schema = view.meta.validationFeedback?.validationSchema;\n setLoaded({\n values: view.values,\n schema: Array.isArray(schema) ? schema : [],\n fields: readDescriptors(view.meta.validationFeedback?.validationFields),\n rowMutableTables: readRowMutableTables(view.meta.validationFeedback?.rowMutableTables),\n });\n // Fresh extraction data → clean editing slate, batched with setLoaded so\n // new bindings never pair with old edits for even one commit. Covers the\n // extractionId change, Retry, AND the Task-17 409-refetch (all of which\n // route through load()).\n setEdits(NO_EDITS);\n // The filter is a view mode on THIS extraction, so it resets with the\n // slate. Without this, the same mounted component opens the next\n // extraction already filtered, which reads as missing fields.\n setFilterOn(false);\n setRowPlans(seedRowPlans(readRowMutableTables(view.meta.validationFeedback?.rowMutableTables), view.values));\n const url = view.document.imageUrl;\n setImageUrl(typeof url === 'string' && url.length > 0 ? url : null);\n setAlreadyValidated(validated);\n setPhase({ name: 'review' });\n };\n\n // Result mapping — EXACT order: purge before status, validated before\n // schema (an already-validated extraction with a null schema must land in\n // review-readOnly, not verification-unavailable).\n if (view.meta.purgedAt != null) {\n enterUnavailable('purged', PURGED_TEXT, false);\n } else if (view.meta.processingStatus !== 'success') {\n enterUnavailable('not-completed', NOT_COMPLETED_TEXT, false);\n } else if (view.meta.validated === true) {\n enterReview(true);\n } else if (\n !Array.isArray(view.meta.validationFeedback?.validationSchema) ||\n view.meta.validationFeedback.validationSchema.length === 0\n ) {\n enterUnavailable('verification-unavailable', VERIFICATION_UNAVAILABLE_TEXT, false);\n } else {\n enterReview(false);\n }\n }, [fetchWithRetry, enterUnavailable]);\n\n useEffect(() => {\n mountedRef.current = true;\n ensureVerificationStylesInjected();\n void load();\n return () => {\n mountedRef.current = false;\n };\n }, [load]);\n\n // Stacked layout: the ROOT observes its OWN width — not the window, because\n // the host may embed the widget in a narrow column of a wide page — and\n // flips to one column below the breakpoint. useEffect (not layout effect)\n // keeps server rendering warning-free; the first client frame corrects.\n // SSR/test-safe: no ResizeObserver → a one-shot measure; a width of 0\n // (unmeasured or hidden host) never forces a layout flip.\n useEffect(() => {\n const el = rootRef.current;\n if (el === null) {\n return;\n }\n const apply = (width: number) => setStacked(width > 0 && width < STACKED_BREAKPOINT);\n if (typeof ResizeObserver === 'undefined') {\n apply(el.getBoundingClientRect().width);\n return;\n }\n const observer = new ResizeObserver((entries) => {\n const entry = entries[0];\n if (!entry) {\n return;\n }\n // Border-box width: the element's OUTER width — the same box the\n // no-ResizeObserver fallback's getBoundingClientRect measures, so the\n // 860px breakpoint means one thing on both paths. contentRect is the\n // pre-borderBoxSize fallback (Safari < 15.4), off by padding + border.\n const width = entry.borderBoxSize?.[0]?.inlineSize ?? entry.contentRect.width;\n apply(width);\n });\n observer.observe(el);\n return () => observer.disconnect();\n }, []);\n\n // --- Derived review data — computed ONCE per load (form stability contract:\n // `classified`/`bindingIndex` are compared by reference in the row memo). ---\n // classifyData is total (null/garbage values → empty buckets) — no guard.\n const classified = useMemo(() => classifyData(loaded?.values), [loaded]);\n const bindings = useMemo(\n () => buildBindings(loaded?.schema ?? [], loaded?.values, loaded?.fields),\n [loaded],\n );\n const bindingIndex = useMemo(() => indexBindingsByFieldPointer(bindings), [bindings]);\n // By RAW key — how a planned table cell finds the extracted value behind it.\n const bindingsByRawKey = useMemo(() => {\n const map = new Map<string, FieldBinding>();\n for (const binding of bindings) {\n map.set(binding.key.raw, binding);\n }\n return map;\n }, [bindings]);\n // Bindings whose fieldPointer matches no classified leaf — the \"model\n // missed the whole field\" case, rendered as the form's Not-detected section.\n const unmatched = useMemo(() => {\n const rendered = new Set<string>();\n for (const field of classified.headers) {\n rendered.add(field.pointer);\n }\n for (const list of classified.simpleLists) {\n for (const item of list.items) {\n rendered.add(item.pointer);\n }\n }\n for (const entity of classified.entities) {\n for (const item of entity.items) {\n for (const cell of Object.values(item)) {\n rendered.add(cell.pointer);\n }\n }\n }\n for (const table of classified.tables) {\n for (const row of table.rows) {\n for (const [key, cell] of Object.entries(row)) {\n // _rowMeta is synthetic (its pointer is the ROW pointer) — it never\n // corresponds to a binding, so it must not mask one.\n if (key !== ROW_META_KEY) {\n rendered.add(cell.pointer);\n }\n }\n }\n }\n return bindings.filter((binding) => !rendered.has(binding.fieldPointer));\n }, [classified, bindings]);\n // Every detection region the extraction carries, feeding the viewer's\n // overlay toggle. Memoized on the classified snapshot (stability contract):\n // the viewer sees ONE stable array per load. undefined when there is\n // genuinely nothing to overlay — the viewer's hasRects check treats\n // undefined and empty alike (toggle disabled); undefined states the intent.\n const overlayRects = useMemo(() => {\n const rects: RelativeRect[] = [];\n for (const field of classified.headers) {\n if (field.coordinates) {\n rects.push(field.coordinates);\n }\n }\n for (const list of classified.simpleLists) {\n for (const item of list.items) {\n if (item.coordinates) {\n rects.push(item.coordinates);\n }\n }\n }\n for (const entity of classified.entities) {\n for (const item of entity.items) {\n for (const cell of Object.values(item)) {\n if (cell.coordinates) {\n rects.push(cell.coordinates);\n }\n }\n }\n }\n for (const table of classified.tables) {\n for (const row of table.rows) {\n for (const [key, cell] of Object.entries(row)) {\n // _rowMeta is synthetic (coordinates null by construction) — skip\n // it so a future row-level coordinate never renders a stray box.\n if (key !== ROW_META_KEY && cell.coordinates) {\n rects.push(cell.coordinates);\n }\n }\n }\n }\n return rects.length > 0 ? rects : undefined;\n }, [classified]);\n\n // dir=\"auto\" (chat parity): Hebrew anywhere in the bound DISPLAY values —\n // toInputString over binding.extracted, the same strings the inputs prefill,\n // never the raw JSON payload — flips the whole widget to RTL. Computed once\n // per load: `bindings` is memoized on the loaded snapshot.\n const hasHebrewContent = useMemo(\n () => bindings.some((binding) => HEBREW_RE.test(toInputString(binding.extracted))),\n [bindings],\n );\n const effectiveDir: 'ltr' | 'rtl' = dir === 'auto' ? (hasHebrewContent ? 'rtl' : 'ltr') : dir;\n\n // Revert detection needs the binding behind a raw key. Read through a ref\n // so handleEdit stays permanently stable (SectionShared contract: the\n // table-row memo compares onEdit by reference; a per-load identity would\n // silently re-render every row once per load).\n\n // The edit tracker. The value is stored VERBATIM — never trimmed or\n // normalized (IME safety: the input must echo exactly what the user is\n // composing; composeSubmission trims at submit time). Dirty-tracking\n // contract (Task 4): the entry is DELETED when the value returns to the\n // binding's initial input string, so composeSubmission's counts stay honest.\n // Every change builds a NEW Map (SectionShared: the row-memo comparator\n // short-circuits on reference equality, so in-place mutation renders nothing);\n // no-op updates return `prev` unchanged to keep that same short-circuit.\n const handleEdit = useCallback((editKey: string, value: string, binding: FieldBinding) => {\n // Pristine = the input shows exactly what an untouched input would show:\n // toInputString of the binding's DISPLAY value (FieldInput's prefill) —\n // including '' for a never-extracted fill-in.\n const pristine = value === toInputString(binding.extracted);\n setEdits((prev) => {\n if (pristine) {\n if (!prev.has(editKey)) {\n return prev;\n }\n const next = new Map(prev);\n next.delete(editKey);\n return next;\n }\n if (prev.get(editKey) === value) {\n return prev;\n }\n const next = new Map(prev);\n next.set(editKey, value);\n return next;\n });\n }, []);\n\n // Progress counts — composeSubmission IS the source of truth (the same call\n // Task 17 submits), so the line can never disagree with what would be sent.\n /**\n * Every row-mutable table's rows, resolved to cells. Computed once and shared\n * with the form, the pair rule and the submit gate — deriving it per consumer\n * is how they would come to disagree about which row a cell belongs to.\n */\n const plannedTables = useMemo(() => {\n const tables = loaded?.rowMutableTables ?? [];\n if (tables.length === 0) {\n return NO_PLANNED_TABLES;\n }\n const out = new Map<string, PlannedRow[]>();\n for (const table of tables) {\n const plan = rowPlans.get(table.pointer);\n if (plan === undefined) {\n continue;\n }\n const classifiedTable = classified.tables.find(\n (candidate) => matchesTablePointer(table.pointer, candidate.pointer),\n );\n const columns = displayColumns(table, classifiedTable?.columns ?? []);\n out.set(table.pointer, planTableCells(table, plan, columns, bindingsByRawKey));\n }\n return out;\n }, [loaded, rowPlans, classified, bindingsByRawKey]);\n\n /** Every editable cell, planned or not — the pair rule and the gate share it. */\n const cellViews = useMemo(\n () => collectCellViews(bindings, plannedTables),\n [bindings, plannedTables],\n );\n\n /**\n * The same tables, minus added rows nobody typed into. Used for SUBMISSION\n * only — the empty row stays on screen so the reviewer can still fill it in.\n */\n const submissionTables = useMemo(\n () => pruneEmptyAddedRows(plannedTables, edits),\n [plannedTables, edits],\n );\n const submissionCells = useMemo(\n () => collectCellViews(bindings, submissionTables),\n [bindings, submissionTables],\n );\n\n /**\n * The alignment for every table whose row set the reviewer actually changed.\n *\n * Identity plans are OMITTED, not sent as a no-op: the wire payload for an\n * untouched submission has to stay byte-identical to what it was before row\n * editing existed, and a pre-2b backend silently ignores the key anyway.\n */\n const rowSources = useMemo(() => {\n const entries: RowSourcesEntry[] = [];\n for (const table of loaded?.rowMutableTables ?? []) {\n // From the PRUNED rows, so an abandoned \"Add line\" leaves no trace.\n const rows = submissionTables.get(table.pointer);\n if (rows === undefined) {\n continue;\n }\n const plan = rows.map((row) => row.entry);\n if (isIdentityPlan(plan, countRowsAt(loaded?.values, table.pointer))) {\n continue;\n }\n entries.push({ table: table.pointer, sources: rowSourcesOf(plan) });\n }\n return entries;\n }, [loaded, submissionTables]);\n\n const submission = useMemo(\n () => composeSubmission(bindings, edits, { cells: submissionCells, rowSources }),\n [bindings, edits, submissionCells, rowSources],\n );\n\n // Flash wiring (form → viewer). STABLE callback — the table-row memo\n // compares onFlash by reference, so rows never re-render on unrelated\n // flashes — that stores a FRESH array per eye-click: TableRow memoizes its\n // row rects, so without the copy a second click on the same row would hand\n // the viewer's flash effect an identical reference and never restart.\n const handleFlash = useCallback((rects: Array<{ points: [number, number][] }>) => {\n setFlashRects(rects.map((rect) => ({ points: rect.points })));\n }, []);\n\n // The viewer announces the fade finished: drop our reference so the next\n // click is a fresh transition. NEVER gate anything beyond this cleanup on\n // onFlashComplete — it may never fire (the image may never load).\n const handleFlashComplete = useCallback(() => {\n setFlashRects(null);\n }, []);\n\n /**\n * Silent expired-image-URL refresh. Swaps ONLY `imageUrl` — deliberately\n * NOT `loaded` (values/meta): replacing the loaded snapshot would re-create\n * the memoized classified/bindings objects and shift the dirty-tracking\n * baseline mid-edit, yanking the form out from under the reviewer. (The\n * plan's \"and refreshed values/meta\" parenthetical is superseded by review.)\n * Throttled to one refetch per 60s so a signed URL that keeps dying (e.g. a\n * document purged mid-review) cannot refetch-loop; the viewer's own\n * has-loaded gate already stops the loop for URLs that never load at all.\n *\n * INVARIANT: any future refetch that writes state must bump loadSeqRef or\n * route through load() — a refetch that writes without owning the sequence\n * can be overtaken by a newer load and clobber its state.\n */\n const handleImageExpired = useCallback(() => {\n const now = Date.now();\n if (now - lastImageRefreshRef.current < IMAGE_REFRESH_THROTTLE_MS) {\n return;\n }\n lastImageRefreshRef.current = now;\n const seq = loadSeqRef.current;\n fetchWithRetry()\n .then((view) => {\n // A newer load owns the state now (or we unmounted) — drop it.\n if (!mountedRef.current || loadSeqRef.current !== seq) {\n return;\n }\n const url = view.document.imageUrl;\n if (typeof url === 'string' && url.length > 0) {\n setImageUrl(url);\n }\n })\n // Swallowed by design: the refresh is best-effort background work — the\n // review (and any pending edits) must stay put on failure. The reviewer\n // keeps a broken image until the next throttle window; phase/loaded/\n // edits are never touched from here.\n .catch(() => {});\n }, [fetchWithRetry]);\n\n const handleRetry = useCallback(() => {\n void load();\n }, [load]);\n\n /** Row controls. Both replace the whole map so the row memo sees a new\n * reference exactly when a plan actually changed. */\n const handleAddRow = useCallback((tablePointer: string, afterPosition: number) => {\n // Minted HERE, not inside the updater: an updater must be pure, and React\n // invokes it twice under Strict Mode.\n const id = nextAddedRowId(tablePointer);\n setRowPlans((prev) => {\n const plan = prev.get(tablePointer);\n if (plan === undefined) {\n return prev;\n }\n const next = new Map(prev);\n next.set(tablePointer, insertRowAfter(plan, afterPosition, id));\n return next;\n });\n }, []);\n\n const handleRemoveRow = useCallback((tablePointer: string, position: number) => {\n setRowPlans((prev) => {\n const plan = prev.get(tablePointer);\n if (plan === undefined) {\n return prev;\n }\n const nextPlan = removeRow(plan, position);\n if (nextPlan === plan) {\n return prev;\n }\n const next = new Map(prev);\n next.set(tablePointer, nextPlan);\n return next;\n });\n }, []);\n\n /**\n * How many edited fields the reviewer must fix before this can be submitted.\n *\n * Derived from `edits` x descriptors, NOT from every binding: an extracted\n * value that fails validation is the model's output, not the reviewer's\n * mistake, and blocking a submission on a field they never touched would be\n * indefensible. FieldInput applies the identical rule when deciding whether\n * to show its inline error, so the count and the red borders can never\n * disagree.\n *\n * Validation is one-shot and irreversible, so the gate is a hard disable\n * rather than a warning.\n */\n /**\n * The one cross-field rule the server enforces, surfaced before submission\n * rather than discovered after it. See `unitSizePairErrors`.\n */\n const pairErrors = useMemo(() => unitSizePairErrors(cellViews, edits), [cellViews, edits]);\n\n // --- review filter -------------------------------------------------------\n // The SAME suppression the form applies, computed from the SAME helper, so\n // the two can never disagree about which promoted headers exist. A pointer\n // counted here but skipped there (or vice versa) makes \"Showing X of Y\" lie.\n // The SAME promotion the form applies, from the SAME helper, so the two can\n // never disagree about which tables are rendered or which headers are\n // suppressed. `tables` matters as much as `suppressed`: an empty\n // server-declared row-mutable table is promoted into the rendered list\n // without existing in `classified.tables`, so rows added to one would\n // otherwise render without being counted.\n const rendered = useMemo(\n () => withEmptyMutableTables(classified, loaded?.rowMutableTables ?? []),\n [classified, loaded?.rowMutableTables],\n );\n // Offering the switch on an unscored extraction would be a control that\n // does nothing. Overall confidence does not count — it is not a review unit\n // and cannot be hidden.\n const canFilter = useMemo(\n () => hasAnyConfidence(classified, rendered.tables, plannedTables),\n [classified, rendered, plannedTables],\n );\n const hidden = useMemo(\n () => (filterOn && canFilter\n ? computeHidden({\n classified,\n tables: rendered.tables,\n plannedTables,\n cellViews,\n bindingIndex,\n edits,\n pairErrors,\n suppressed: rendered.suppressed,\n })\n : NOTHING_HIDDEN),\n [filterOn, canFilter, classified, rendered, plannedTables, cellViews, bindingIndex, edits, pairErrors],\n );\n // `unmatched` bindings render as the \"Not detected\" section — editable\n // fields the reviewer can fill in — so they are review units too. They carry\n // no confidence and are therefore never hidden, which is why they add to\n // both totals equally. Leaving them out made the count contradict the screen.\n const totalUnits = useMemo(\n () => countUnits(classified, rendered.tables, plannedTables, rendered.suppressed) + unmatched.length,\n [classified, rendered, plannedTables, unmatched],\n );\n const visibleUnits = totalUnits - hidden.fields.size - hidden.rows.size;\n // Only while filtering, and only when there was something to begin with:\n // a genuinely empty extraction is a different state with its own copy.\n const allClear = filterOn && totalUnits > 0 && visibleUnits === 0;\n\n const invalidCount = useMemo(() => {\n // Row-level errors count even with no edits at all: the extraction itself\n // can arrive with one half of the pair filled.\n const rowLevel = pairErrors.size;\n if (edits.size === 0) {\n return rowLevel;\n }\n const byEditKey = new Map(cellViews.map((view) => [view.editKey, view.binding]));\n let count = 0;\n for (const [editKey, value] of edits) {\n // A cell already flagged by the row rule must not be counted twice.\n if (!pairErrors.has(editKey) && validateInput(value, byEditKey.get(editKey)?.field) !== null) {\n count += 1;\n }\n }\n return count + rowLevel;\n }, [edits, cellViews, pairErrors]);\n\n /**\n * The PUT. Reuses the `submission` memo — the SAME pure composeSubmission\n * result the progress line displays — so what the reviewer was just shown\n * (\"N confirmed · M corrected\") is by construction what goes on the wire.\n * 401 handling mirrors the GET: invalidate + retry exactly once. Outcomes:\n * success → done (+ exactly-once onComplete); 409 → SILENT refetch through\n * load() (the seq-guard invariant), landing in the already-validated\n * read-only review with no onError; 401 after the retry → submit-error with\n * the session-expired copy; anything else → submit-error with the server's\n * description when present. Edits are NEVER cleared on failure — the\n * submit-error review keeps the form (and the corrections) mounted.\n */\n const doSubmit = useCallback(async () => {\n if (submitInFlightRef.current) {\n return;\n }\n submitInFlightRef.current = true;\n const seq = loadSeqRef.current;\n /** Same liveness rule as load(): a newer load owns the state now. */\n const live = () => mountedRef.current && loadSeqRef.current === seq;\n setPhase({ name: 'submitting' });\n const body = submission;\n const submitOnce = async () => {\n const token = await tokenManager.getToken();\n return GeminaClient.withSessionToken(token, baseUrl).documents.validateDocumentExtraction({\n targetDocumentExtractionId: extractionId,\n // Conditional spread, matching the house pattern: without a row edit\n // the request body is byte-identical to what it was before this\n // feature, so nothing changes for the overwhelmingly common path.\n extractionValidationInDTO: {\n data: body.data,\n ...(body.rowSources.length > 0 ? { rowSources: body.rowSources } : {}),\n },\n });\n };\n try {\n let result: Awaited<ReturnType<typeof submitOnce>>;\n try {\n try {\n result = await submitOnce();\n } catch (error) {\n if (httpStatus(error) !== 401) {\n throw error;\n }\n tokenManager.invalidate();\n result = await submitOnce();\n }\n } catch (error) {\n const detail = await readErrorEnvelope(error);\n if (!live()) {\n return;\n }\n if (detail.status === 409) {\n // Someone verified concurrently. Refetch and land in the\n // already-validated read-only banner state — deliberately NO\n // onError (the extraction IS verified; that is a success shape),\n // and the brief loading flash is accepted.\n void load();\n return;\n }\n if (detail.status === 401) {\n // Only after the one mandated retry. Edits are kept: a fresh\n // sign-in elsewhere + Retry can still succeed — hence the\n // submit-specific copy (never \"reload the page\").\n setPhase({ name: 'submit-error', message: SUBMIT_SESSION_EXPIRED_TEXT });\n onErrorRef.current?.('session-expired', detail);\n return;\n }\n setPhase({\n name: 'submit-error',\n message: detail.description ?? SUBMIT_FAILED_TEXT,\n });\n onErrorRef.current?.('submit-failed', detail);\n return;\n }\n if (!live()) {\n return;\n }\n setPhase({ name: 'done', confirmed: body.confirmed, corrected: body.corrected });\n if (!completedRef.current) {\n completedRef.current = true;\n // The generated client resolves ExtractionValidationResultOutDTO;\n // its `.data` is the ComparisonSummaryModel the host is promised.\n onCompleteRef.current?.({ correctedValues: body.byLabel, summary: result.data });\n }\n } finally {\n submitInFlightRef.current = false;\n }\n }, [submission, tokenManager, baseUrl, extractionId, load]);\n\n const handleSubmitClick = useCallback(() => {\n setPhase({ name: 'confirming' });\n }, []);\n\n const handleConfirm = useCallback(() => {\n void doSubmit();\n }, [doSubmit]);\n\n const handleCancelConfirm = useCallback(() => {\n restoreFocusRef.current = true;\n setPhase({ name: 'review' });\n }, []);\n\n /** Retry goes STRAIGHT back to submitting — confirm-final is never re-asked. */\n const handleRetrySubmit = useCallback(() => {\n void doSubmit();\n }, [doSubmit]);\n\n const handleConfirmKeyDown = useCallback(\n (event: React.KeyboardEvent) => {\n // Keys only act while the QUESTION is open. During `submitting` the\n // in-flight PUT cannot be aborted (Escape is ignored) and both dialog\n // buttons are disabled — nothing inside is focusable, so there is\n // nothing to trap either; the phase resolves to done/submit-error in\n // one round-trip and the phase-entry effect re-anchors focus there.\n if (phase.name !== 'confirming') {\n return;\n }\n if (event.key === 'Escape') {\n event.stopPropagation();\n handleCancelConfirm();\n return;\n }\n // Minimal focus trap: the dialog has exactly two tabbables (Cancel and\n // Confirm), so Tab/Shift+Tab wrap between them instead of escaping into\n // the scrimmed background the overlay only covers visually.\n if (event.key === 'Tab') {\n const cancel = cancelButtonRef.current;\n const confirm = confirmButtonRef.current;\n if (cancel === null || confirm === null) {\n return;\n }\n const active = document.activeElement;\n if (event.shiftKey && active === cancel) {\n event.preventDefault();\n confirm.focus();\n } else if (!event.shiftKey && active === confirm) {\n event.preventDefault();\n cancel.focus();\n } else if (active !== cancel && active !== confirm) {\n // Belt only: focus INSIDE the overlay subtree but on neither button\n // (no such element exists today). This is NOT scrim-click recovery —\n // a blur to <body> would put keydowns outside this subtree handler\n // entirely; the scrim's mousedown preventDefault is what keeps that\n // blur from ever happening.\n event.preventDefault();\n confirm.focus();\n }\n }\n },\n [phase.name, handleCancelConfirm],\n );\n\n // Phase-entry focus anchoring. Entering `confirming` moves focus to the\n // final-action button (Enter submits, Escape cancels); a Cancel hands it\n // back to the Submit button — from here, AFTER the review re-render\n // re-enabled it. The two phases that unmount the dialog under the keyboard\n // user get their own landings (without them focus drops to <body>):\n // submit-error → the inline Retry button; done → the state container\n // (tabIndex -1, no ring — a non-interactive announcement landing).\n useEffect(() => {\n if (phase.name === 'confirming') {\n confirmButtonRef.current?.focus();\n } else if (phase.name === 'review' && restoreFocusRef.current) {\n restoreFocusRef.current = false;\n submitButtonRef.current?.focus();\n } else if (phase.name === 'submit-error') {\n retrySubmitButtonRef.current?.focus();\n } else if (phase.name === 'done') {\n doneStateRef.current?.focus();\n }\n }, [phase.name]);\n\n const rootClassName = [\n 'gemina-verification',\n `gemina-verification--${theme}`,\n effectiveDir === 'rtl' ? 'gemina-verification--rtl' : '',\n stacked ? 'gemina-verification--stacked' : '',\n className ?? '',\n ]\n .filter((part) => part.length > 0)\n .join(' ');\n\n // One id per instance for the dialog's label (multiple widgets may coexist).\n const dialogTextId = useId();\n\n /**\n * The review family: review | confirming | submitting | submit-error all\n * render THIS content, so the form (edits included!) and the aria-live\n * progress region stay mounted through the whole submit sequence. Only the\n * decorations differ per member: confirming/submitting put the overlay up\n * (same dialog shell — the copy flips to \"Submitting…\" and both buttons\n * disable, which is the double-click guard), submit-error adds the inline\n * error banner. The form is never readOnly-flipped mid-flight — that would\n * visually discard the reviewer's edits.\n */\n const renderReview = (reviewPhase: ReviewFamilyPhase): React.JSX.Element => {\n const overlayUp = reviewPhase.name === 'confirming' || reviewPhase.name === 'submitting';\n return (\n <>\n {alreadyValidated && (\n <div className=\"gemina-verification__banner\">{ALREADY_VALIDATED_TEXT}</div>\n )}\n <div className=\"gemina-verification__panes\">\n {imageUrl !== null && (\n <VerificationViewer\n src={imageUrl}\n relativeRects={overlayRects}\n flashRects={flashRects}\n onFlashComplete={handleFlashComplete}\n onImageExpired={handleImageExpired}\n />\n )}\n {/* Everything scored high and the reviewer asked to see only what\n needs attention — so the form would be empty. An empty form is\n indistinguishable from a broken one, so say which it is. */}\n {allClear ? (\n <p className=\"gemina-verification__all-scored\" role=\"status\">\n {`Nothing needs review — all ${totalUnits} fields scored high.`}\n </p>\n ) : (\n <VerificationForm\n classified={classified}\n unmatched={unmatched}\n bindingIndex={bindingIndex}\n edits={edits}\n onEdit={handleEdit}\n readOnly={alreadyValidated}\n onFlash={handleFlash}\n pairErrors={pairErrors}\n rowMutableTables={loaded?.rowMutableTables}\n hidden={hidden}\n filterOn={filterOn}\n plannedTables={plannedTables}\n onAddRow={handleAddRow}\n onRemoveRow={handleRemoveRow}\n />\n )}\n </div>\n {reviewPhase.name === 'submit-error' && (\n <div\n className=\"gemina-verification__banner gemina-verification__banner--error gemina-verification__submit-error\"\n role=\"alert\"\n >\n <span>{reviewPhase.message}</span>\n <button\n type=\"button\"\n ref={retrySubmitButtonRef}\n className=\"gemina-verification__retry\"\n onClick={handleRetrySubmit}\n >\n Retry\n </button>\n </div>\n )}\n <div className=\"gemina-verification__footer\">\n {/* aria-live: a reviewer deep in a long form hears the count move\n as they confirm/correct without tabbing back to the footer.\n Hidden when read-only — the already-verified landing would\n otherwise show \"0 corrected\" noise about the ORIGINAL payload —\n while the disabled Submit stays for discoverability. */}\n {/* One job per element: while anything is invalid the footer states\n the blocker, and the progress count steps aside rather than\n competing with it for the same corner of the screen. */}\n {!alreadyValidated && (\n invalidCount > 0 ? (\n <div className=\"gemina-verification__attention\" aria-live=\"polite\">\n {invalidCount === 1\n ? '1 field needs attention'\n : `${invalidCount} fields need attention`}\n </div>\n ) : (\n <div className=\"gemina-verification__progress\" aria-live=\"polite\">\n {`${submission.confirmed} confirmed · ${submission.corrected} corrected`}\n </div>\n )\n )}\n {/* A VIEW MODE, so role=switch rather than a button that \"does\" something.\n Omitted entirely when nothing is scored — the same treatment the\n eye button gets when a field has no coordinates, and the reason\n is the same: an affordance that cannot do anything is noise.\n The count is the safety rail. A filtered form that looks\n unfiltered is how a reviewer concludes data went missing, so the\n live region announces the change to anyone not watching it. */}\n {canFilter && (\n <>\n <button\n type=\"button\"\n role=\"switch\"\n aria-checked={filterOn}\n className=\"gemina-verification__review-filter\"\n onClick={() => setFilterOn((on) => !on)}\n >\n Hide high-confidence fields\n </button>\n {/* The count sits OUTSIDE the switch on purpose. Inside, it would\n change the control's accessible NAME on every toggle and be\n re-announced whenever the button took focus; outside, the name\n stays constant, the visible label still matches it (WCAG\n 2.5.3), and the live region announces only what changed. */}\n {filterOn && (\n <span className=\"gemina-verification__filter-count\" aria-live=\"polite\">\n {`Showing ${visibleUnits} of ${totalUnits}`}\n </span>\n )}\n </>\n )}\n <button\n type=\"button\"\n ref={submitButtonRef}\n className=\"gemina-verification__submit\"\n disabled={alreadyValidated || reviewPhase.name !== 'review' || invalidCount > 0}\n onClick={handleSubmitClick}\n >\n Submit\n </button>\n </div>\n {overlayUp && (\n <div\n className=\"gemina-verification__confirm\"\n onKeyDown={handleConfirmKeyDown}\n // A press anywhere NON-interactive — the scrim AND the dialog's\n // own interior (the confirm text, padding, actions row) — must not\n // blur the dialog: preventDefault on mousedown suppresses the\n // browser's focus-move default, so activeElement stays on a dialog\n // button and the subtree keydown handler above stays in the focus\n // path (focus on <body> would put Escape/Tab out of its reach).\n // Only presses on a button keep their default. Trade-off, accepted:\n // the dialog copy (one sentence) can't be text-selected by mouse.\n onMouseDown={(event) => {\n if (!(event.target as Element).closest('button')) {\n event.preventDefault();\n }\n }}\n >\n <div\n className=\"gemina-verification__confirm-dialog\"\n role=\"dialog\"\n aria-modal=\"true\"\n aria-labelledby={dialogTextId}\n >\n <p id={dialogTextId} className=\"gemina-verification__confirm-text\">\n {reviewPhase.name === 'submitting' ? SUBMITTING_TEXT : CONFIRM_TEXT}\n </p>\n <div className=\"gemina-verification__confirm-actions\">\n <button\n type=\"button\"\n ref={cancelButtonRef}\n className=\"gemina-verification__confirm-cancel\"\n onClick={handleCancelConfirm}\n disabled={reviewPhase.name === 'submitting'}\n >\n Cancel\n </button>\n <button\n type=\"button\"\n ref={confirmButtonRef}\n className=\"gemina-verification__submit\"\n onClick={handleConfirm}\n disabled={reviewPhase.name === 'submitting'}\n >\n Confirm submission\n </button>\n </div>\n </div>\n </div>\n )}\n </>\n );\n };\n\n // EXHAUSTIVE by construction: the explicit return type makes a phase\n // variant without a case a compile error (the function could fall through\n // returning undefined) — a forgotten renderer can never ship as a blank\n // widget. No default clause, ever.\n const content = ((): React.JSX.Element => {\n switch (phase.name) {\n case 'loading':\n return (\n <div className=\"gemina-verification__state\" role=\"status\">\n {LOADING_TEXT}\n </div>\n );\n case 'unavailable':\n return (\n <div\n className=\"gemina-verification__state\"\n role={ALERT_REASONS.has(phase.reason) ? 'alert' : 'status'}\n >\n <div>{phase.message}</div>\n {phase.canRetry && (\n <button type=\"button\" className=\"gemina-verification__retry\" onClick={handleRetry}>\n Retry\n </button>\n )}\n </div>\n );\n case 'review':\n case 'confirming':\n case 'submitting':\n case 'submit-error':\n return renderReview(phase);\n case 'done':\n return (\n <div\n ref={doneStateRef}\n // Programmatic focus landing only — see the phase-entry focus\n // effect. Not tab-reachable; the stylesheet suppresses the ring.\n tabIndex={-1}\n className=\"gemina-verification__state gemina-verification__state--done\"\n role=\"status\"\n >\n <span className=\"gemina-verification__done-check\" aria-hidden=\"true\">\n <svg width=\"20\" height=\"20\" viewBox=\"0 0 20 20\" fill=\"none\">\n <path\n d=\"M4 10.5l4 4 8-9\"\n stroke=\"currentColor\"\n strokeWidth=\"2.4\"\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n />\n </svg>\n </span>\n <div className=\"gemina-verification__done-title\">{DONE_TITLE_TEXT}</div>\n <div className=\"gemina-verification__progress\">\n {`${phase.confirmed} confirmed · ${phase.corrected} corrected`}\n </div>\n </div>\n );\n }\n })();\n\n return (\n <div ref={rootRef} className={rootClassName} dir={effectiveDir}>\n {content}\n </div>\n );\n}\n","/**\n * The typed side of the validation contract.\n *\n * The backend publishes a descriptor per submittable field alongside the\n * opaque key list (`meta.validationFeedback.validationFields`, and per-column\n * in `rowMutableTables[].columns`). They are derived from the pydantic models,\n * so they are the same source of truth the scorer uses — which is why the\n * client can validate against them and be sure the server will agree.\n *\n * The descriptor is declared STRUCTURALLY here rather than imported from\n * `@gemina/sdk`, so this module compiles against any SDK version. That is a\n * convenience for development only: it does NOT rescue the data. Elements\n * consumes the generated DTO, and a generated converter drops properties it\n * was not generated with, so a host on a pre-1.5.0 SDK receives `undefined`\n * here no matter what the server sent. Every consumer must therefore treat an\n * absent descriptor as \"render the plain text input we always rendered\".\n */\n\n/** The JSON types the generator emits (`schema_generator.JsonType`). */\nexport type FieldType = 'string' | 'number' | 'integer' | 'boolean' | 'date';\n\nexport interface ValidationFieldDescriptor {\n /** The opaque schema key this describes. The ONLY identity — labels repeat. */\n key?: string;\n label?: string;\n type?: FieldType;\n /**\n * A closed roster. Note the wire name: the generator renames the reserved\n * word, so the SDK property is `_enum`; callers normalise before handing a\n * descriptor here.\n */\n enum?: string[] | null;\n /** A closed external standard the annotation cannot express, e.g. `iso4217`. */\n format?: string | null;\n /** The model's own field description — shown to the reviewer verbatim. */\n description?: string | null;\n}\n\n/**\n * Active ISO 4217 codes, for the currency field's `<datalist>`.\n *\n * SUGGESTIONS ONLY — `validateInput` deliberately does not require membership.\n * A reviewer looking at a real invoice is the authority on what currency it is\n * in, and blocking submission because a legitimate code is missing from a list\n * baked into a client release is a worse failure than accepting an odd one.\n * The server does not check membership either; it compares values.\n */\nexport const ISO_4217_CODES: readonly string[] = [\n 'AED', 'ARS', 'AUD', 'BGN', 'BRL', 'CAD', 'CHF', 'CLP', 'CNY', 'COP', 'CZK',\n 'DKK', 'EGP', 'EUR', 'GBP', 'HKD', 'HRK', 'HUF', 'IDR', 'ILS', 'INR', 'ISK',\n 'JPY', 'KRW', 'MAD', 'MXN', 'MYR', 'NGN', 'NOK', 'NZD', 'PEN', 'PHP', 'PLN',\n 'RON', 'RSD', 'RUB', 'SAR', 'SEK', 'SGD', 'THB', 'TRY', 'TWD', 'UAH', 'USD',\n 'VND', 'ZAR',\n];\n\nconst ISO_4217_SHAPE = /^[A-Za-z]{3}$/;\nconst DATE_SHAPE = /^\\d{4}-\\d{2}-\\d{2}$/;\n/** Digits with optional sign/decimal, allowing the separators the server strips. */\nconst NUMERIC_SHAPE = /^[+-]?[\\d,_]*\\.?\\d+$/;\n\n/** The server's own leniency (`utils._strip_numeric`) — match it, don't exceed it. */\nfunction toNumber(value: string): number | null {\n if (!NUMERIC_SHAPE.test(value)) {\n return null;\n }\n const parsed = Number(value.replace(/[,_]/g, ''));\n return Number.isFinite(parsed) ? parsed : null;\n}\n\n/**\n * Why a value cannot be submitted, or `null` if it can.\n *\n * The message is the FIX, not the complaint: \"Enter a whole number\", not\n * \"Invalid integer\". A reviewer correcting an invoice should never have to\n * infer what the form wants from a restatement of what it rejected.\n *\n * Two rules are load-bearing rather than cosmetic:\n *\n * - An EMPTY value is always valid. `composeSubmission` reads a cleared input\n * as \"the user asserts this field is absent\", which is a legitimate and\n * common correction. Validating emptiness would make the field unclearable.\n * - NO DESCRIPTOR means valid. Untyped is not the same as invalid, and the\n * component must stay usable against a backend or an SDK that predates the\n * typed contract.\n */\nexport function validateInput(\n value: string,\n field: ValidationFieldDescriptor | undefined,\n): string | null {\n const trimmed = value.trim();\n if (trimmed === '' || !field) {\n return null;\n }\n\n // A published roster wins over the annotation's type: the server emits enum\n // and type together, and the roster is the narrower statement.\n if (field.enum && field.enum.length > 0) {\n return field.enum.includes(trimmed)\n ? null\n : `Choose one of: ${field.enum.join(', ')}`;\n }\n\n if (field.format === 'iso4217') {\n return ISO_4217_SHAPE.test(trimmed) ? null : 'Use a 3-letter ISO 4217 code, e.g. USD';\n }\n\n switch (field.type) {\n case 'number':\n return toNumber(trimmed) === null ? 'Enter a number' : null;\n case 'integer': {\n const parsed = toNumber(trimmed);\n if (parsed === null || !Number.isInteger(parsed)) {\n return 'Enter a whole number';\n }\n return null;\n }\n case 'date': {\n if (!DATE_SHAPE.test(trimmed)) {\n return 'Enter a date as YYYY-MM-DD';\n }\n // Shape alone accepts 2026-02-30. Round-trip through Date and require\n // the parts to survive, which rejects overflowed days and months.\n const [year, month, day] = trimmed.split('-').map(Number);\n const date = new Date(Date.UTC(year!, month! - 1, day!));\n const survives = date.getUTCFullYear() === year\n && date.getUTCMonth() === month! - 1\n && date.getUTCDate() === day;\n return survives ? null : 'Enter a date as YYYY-MM-DD';\n }\n default:\n return null;\n }\n}\n\n/**\n * A table the server declares row-mutable — the reviewer may add and delete\n * its rows, and the client may send a `rowSources` alignment for it.\n *\n * SERVER-DECLARED, never inferred. Any wide array of objects looks like a\n * table to the classifier — `custom_template`'s do — and offering row controls\n * on one the scorer cannot align would mis-score permanently, on a submission\n * that only happens once.\n */\nexport interface RowMutableTable {\n /** JSON pointer to the array, e.g. `/line_items`. */\n pointer: string;\n /** `label:line_{index}_{field}|ptr:/line_items/{index}/{field}`. */\n keyTemplate: string;\n /**\n * Every column of a row, derived by the backend from the MODEL rather than\n * from a sampled row — so they exist even when the extraction found nothing,\n * which is exactly when a reviewer most needs to type a line in.\n */\n columns: ValidationFieldDescriptor[];\n}\n\n/** Normalise the SDK's `rowMutableTables`, including each column's `_enum`. */\nexport function readRowMutableTables(raw: unknown): RowMutableTable[] {\n if (!Array.isArray(raw)) {\n return [];\n }\n const out: RowMutableTable[] = [];\n for (const item of raw) {\n if (item === null || typeof item !== 'object') {\n continue;\n }\n const source = item as Record<string, unknown>;\n if (typeof source.pointer !== 'string' || typeof source.keyTemplate !== 'string') {\n continue;\n }\n out.push({\n pointer: source.pointer,\n keyTemplate: source.keyTemplate,\n // Columns are descriptors keyed by `name` rather than `key`, so they get\n // the same treatment with the name standing in as the identity.\n columns: readDescriptors(\n (Array.isArray(source.columns) ? source.columns : []).map((column) => {\n const record = (column ?? {}) as Record<string, unknown>;\n return { ...record, key: record.name };\n }),\n ),\n });\n }\n return out;\n}\n\n/** The cell key a table's rows mint, with `{index}`/`{field}` filled in. */\nexport function cellSchemaKey(template: string, index: number, field: string): string {\n return template.replace(/\\{index\\}/g, String(index)).replace(/\\{field\\}/g, field);\n}\n\n/**\n * Turn a reviewer's typed string into the value that goes on the wire.\n *\n * Typed rendering without typed parsing leaves the approval payload as\n * unusable as it was before, for two independent reasons:\n *\n * - ON THE WIRE, the server's `coerce_like` adopts the EXTRACTED value's type\n * before comparing — but skips coercion entirely when the target resolves\n * NOT_FOUND, which is exactly the never-extracted and added-row cases. There\n * a string `\"12\"` is compared against a number and scores incorrect.\n * - IN `onComplete`, the host receives the client-side values, never the\n * backend-normalised ones. A host consuming approved data would get `\"12\"`\n * where it expects `12`.\n *\n * Anything that does not parse is returned UNCHANGED rather than as `NaN`.\n * Task 6.4's gate means an unparseable value cannot reach here, but `NaN`\n * would `JSON.stringify` to `null` and score as a deliberate assertion of\n * absence — the one wrong answer worse than the raw string.\n */\nexport function coerceInput(\n value: string,\n field: ValidationFieldDescriptor | undefined,\n): unknown {\n if (!field) {\n return value;\n }\n switch (field.type) {\n case 'number':\n case 'integer': {\n const parsed = toNumber(value);\n return parsed === null ? value : parsed;\n }\n case 'boolean': {\n const lowered = value.trim().toLowerCase();\n if (lowered === 'true') return true;\n if (lowered === 'false') return false;\n return value;\n }\n // `date` stays a string: the wire format IS the ISO string, and a Date\n // object would serialise with a time component the extraction never had.\n default:\n return value;\n }\n}\n\n/**\n * Normalise the SDK's descriptors into the shape the rest of this module uses.\n *\n * Exists for one word: `enum` is reserved, so the generator emits the property\n * as `_enum` in TypeScript (and would in a future regen too — it is the\n * generator's rule, not a one-off). Reading `field.enum` off a generated DTO\n * therefore yields `undefined` silently, and every enum would quietly render\n * as a free-text input. Accepting BOTH spellings also keeps the function\n * correct for a caller handing over raw JSON rather than a parsed DTO.\n *\n * Anything unusable — not an object, no string key — is dropped rather than\n * carried as a half-descriptor that later code has to re-check.\n */\nexport function readDescriptors(raw: unknown): ValidationFieldDescriptor[] {\n if (!Array.isArray(raw)) {\n return [];\n }\n const out: ValidationFieldDescriptor[] = [];\n for (const item of raw) {\n if (item === null || typeof item !== 'object') {\n continue;\n }\n const source = item as Record<string, unknown>;\n if (typeof source.key !== 'string') {\n continue;\n }\n const roster = source._enum ?? source.enum;\n out.push({\n key: source.key,\n label: typeof source.label === 'string' ? source.label : undefined,\n type: typeof source.type === 'string' ? (source.type as FieldType) : undefined,\n enum: Array.isArray(roster) ? roster.map(String) : null,\n format: typeof source.format === 'string' ? source.format : null,\n description: typeof source.description === 'string' ? source.description : null,\n });\n }\n return out;\n}\n","/**\n * Shape classifier for arbitrary extraction payloads.\n *\n * Near-verbatim port of the console's battle-tested classifier\n * (gemina-console `src/pages/extractions/components/FormView/utils.ts`).\n * It buckets a payload into headers / simpleLists / tables / entities /\n * fallback. The heuristics are intentionally unchanged — they are proven\n * against every extraction type.\n *\n * ONE structural addition over the console: every emitted leaf carries the\n * JSON pointer at which it lives in the ORIGINAL payload, so bindings can\n * match fields to server-generated schema keys. Pointers point at the\n * value-object WRAPPER (e.g. `/supplier_name`, not `/supplier_name/value`);\n * `/value` normalization happens at binding time. When the payload wraps its\n * fields in a root `{ data: ... }` object, inner pointers keep the `/data`\n * prefix because server pointers resolve against the payload root.\n *\n * Pointer segments are RFC-6901 escaped (`~` → `~0` first, then `/` → `~1`)\n * so emitted pointers round-trip through `resolvePointer`.\n *\n * Pure and dependency-free: no React, no DOM, no antd.\n */\n\n/**\n * Common acronyms that should stay uppercase\n */\nconst ACRONYMS = new Set(['ID', 'VAT', 'OCR', 'PDF', 'URL', 'API', 'HTML', 'CSS', 'JSON', 'XML', 'UUID']);\n\n/**\n * Convert camelCase or snake_case to Title Case with acronym handling\n * Examples:\n * supplierName -> \"Supplier Name\"\n * vat_amount -> \"VAT Amount\"\n * ocr_text -> \"OCR Text\"\n * businessNumber -> \"Business Number\"\n */\nexport function formatLabel(key: string): string {\n // First, split by underscores and camelCase\n const words = key\n // Insert space before uppercase letters (camelCase)\n .replace(/([a-z])([A-Z])/g, '$1 $2')\n // Replace underscores with spaces\n .replace(/_/g, ' ')\n // Split into words\n .split(' ')\n .filter(Boolean);\n\n return words\n .map((word) => {\n const upper = word.toUpperCase();\n if (ACRONYMS.has(upper)) {\n return upper;\n }\n return word.charAt(0).toUpperCase() + word.slice(1).toLowerCase();\n })\n .join(' ');\n}\n\n/**\n * Format a value for display based on its type.\n *\n * DISPLAY ONLY — never feed this into inputs or submissions; the raw\n * `value` on each classified leaf is the source of truth.\n */\nexport function formatValue(value: unknown, fieldName?: string): string {\n if (value === null || value === undefined) {\n return '-';\n }\n\n if (typeof value === 'boolean') {\n return value ? 'Yes' : 'No';\n }\n\n if (typeof value === 'number') {\n // Check if it looks like a percentage (field name contains rate/percent)\n if (fieldName && /rate|percent/i.test(fieldName)) {\n return `${value}%`;\n }\n // Don't format identifier fields with thousand separators\n if (fieldName && /number|num|id|code|phone|fax|postal|zip/i.test(fieldName)) {\n return String(value);\n }\n // Format numbers with thousand separators\n return value.toLocaleString();\n }\n\n if (typeof value === 'string') {\n // Try to detect and format ISO dates\n if (/^\\d{4}-\\d{2}-\\d{2}(T|$)/.test(value)) {\n try {\n const date = new Date(value);\n if (!isNaN(date.getTime())) {\n return date.toLocaleDateString();\n }\n } catch {\n // Fall through to return original\n }\n }\n return value;\n }\n\n return String(value);\n}\n\n/**\n * Check if a value is a \"value object\" with { value, coordinates?, confidence? }\n */\nexport function isValueObject(obj: unknown): obj is { value: unknown; coordinates?: unknown; confidence?: string; confidence_reasons?: string[] } {\n if (!obj || typeof obj !== 'object' || Array.isArray(obj)) {\n return false;\n }\n return 'value' in obj;\n}\n\n/**\n * Check if an array contains only primitives\n */\nexport function isPrimitiveArray(arr: unknown[]): boolean {\n if (arr.length === 0) return false;\n return arr.every((item) => item === null || typeof item !== 'object');\n}\n\n/**\n * Check if an array is a \"simple value array\" (Type C)\n * Array of { value, coordinates? } objects\n */\nexport function isSimpleValueArray(arr: unknown[]): boolean {\n if (arr.length === 0) return false;\n return arr.every((item) => isValueObject(item) && Object.keys(item as object).every(k => ['value', 'coordinates', 'confidence', 'confidence_reasons'].includes(k)));\n}\n\n/**\n * Check if an array is a \"table array\" (Type A)\n * Array of flat objects with many fields\n */\nexport function isTableArray(arr: unknown[]): boolean {\n if (arr.length === 0) return false;\n const first = arr[0];\n if (!first || typeof first !== 'object' || Array.isArray(first)) return false;\n\n // Count non-metadata fields\n const metaFields = new Set(['confidence', 'confidence_reasons', 'coordinates']);\n const keys = Object.keys(first as object).filter(k => !metaFields.has(k));\n\n // If objects have >3 non-meta fields and those values are primitives or value objects, it's a table\n if (keys.length > 3) {\n const firstObj = first as Record<string, unknown>;\n // Only check the non-metadata field values\n const nonMetaValues = keys.map(k => firstObj[k]);\n const allSimple = nonMetaValues.every(v =>\n v === null ||\n typeof v !== 'object' ||\n isValueObject(v)\n );\n return allSimple;\n }\n return false;\n}\n\n/**\n * Check if an array is an \"entity array\" (Type B)\n * Array of objects that aren't tables - includes both wrapped value objects\n * and plain object arrays with few fields\n */\nexport function isEntityArray(arr: unknown[]): boolean {\n if (arr.length === 0) return false;\n if (isPrimitiveArray(arr)) return false;\n if (isSimpleValueArray(arr)) return false;\n if (isTableArray(arr)) return false;\n\n const first = arr[0];\n if (!first || typeof first !== 'object' || Array.isArray(first)) return false;\n\n // Any array of objects that isn't a table or simple value array is an entity array\n // This includes objects with nested value wrappers OR plain objects with few fields\n return true;\n}\n\n/**\n * Extract the actual value from a field (handles value objects)\n */\nexport function extractValue(field: unknown): unknown {\n if (isValueObject(field)) {\n return field.value;\n }\n return field;\n}\n\n/**\n * Extract coordinates from a field if present\n */\nexport function extractCoordinates(field: unknown): { points: [number, number][] } | null {\n if (isValueObject(field) && field.coordinates) {\n const coords = field.coordinates as { relative?: [number, number][] };\n if (coords.relative) {\n return { points: coords.relative };\n }\n }\n return null;\n}\n\n/**\n * Extract confidence from a field if present\n */\nexport function extractConfidence(field: unknown): { level: string; reasons: string[] } | null {\n if (isValueObject(field) && field.confidence) {\n return {\n level: field.confidence,\n reasons: field.confidence_reasons || [],\n };\n }\n return null;\n}\n\n/**\n * Escape one JSON-pointer segment per RFC 6901 (`~` before `/`, mirroring the\n * resolver's unescape order of `~1` before `~0`).\n */\nfunction escapeSegment(segment: string): string {\n return segment.replace(/~/g, '~0').replace(/\\//g, '~1');\n}\n\n/**\n * One classified leaf field. `pointer` locates the field's value-object\n * wrapper (or raw value) in the ORIGINAL payload.\n */\nexport interface ClassifiedField {\n key: string; // display label source (formatLabel applied at render)\n pointer: string; // pointer to this field in the ORIGINAL payload\n value: unknown; // unwrapped raw value\n coordinates: { points: [number, number][] } | null;\n confidence: { level: string; reasons: string[] } | null;\n}\n\n/**\n * Key under which a table row's synthetic row-level confidence cell is\n * stored. Not a real payload field — it never binds to a server schema key.\n */\nexport const ROW_META_KEY = '_rowMeta';\n\n/** A cell inside a table row or entity card (no own display key). */\nexport interface ClassifiedCell {\n pointer: string;\n value: unknown;\n coordinates: { points: [number, number][] } | null;\n confidence: { level: string; reasons: string[] } | null;\n}\n\n/**\n * Classify all fields in a data object\n */\nexport interface ClassifiedData {\n overallConfidence: { level: string; reasons: string[] } | null;\n headers: ClassifiedField[];\n simpleLists: Array<{\n key: string;\n pointer: string;\n items: ClassifiedCell[];\n }>;\n entities: Array<{\n key: string;\n pointer: string;\n items: Array<Record<string, ClassifiedCell>>;\n }>;\n tables: Array<{\n key: string;\n pointer: string;\n columns: string[];\n rows: Array<Record<string, ClassifiedCell>>;\n overallConfidence: { level: string; reasons: string[] } | null;\n }>;\n fallback: Array<{\n key: string;\n data: unknown;\n }>;\n}\n\nexport function classifyData(data: unknown): ClassifiedData {\n const result: ClassifiedData = {\n overallConfidence: null,\n headers: [],\n simpleLists: [],\n entities: [],\n tables: [],\n fallback: [],\n };\n\n if (!data || typeof data !== 'object' || Array.isArray(data)) {\n return result;\n }\n\n // Handle wrapped data (some extractions wrap in { data: ... })\n let rootData = data as Record<string, unknown>;\n result.overallConfidence = readOverallConfidence(rootData);\n let basePointer = '';\n if ('data' in rootData && typeof rootData.data === 'object' && rootData.data !== null && !Array.isArray(rootData.data)) {\n // Process top-level non-data fields first (like total_lines, overall_confidence)\n for (const [key, value] of Object.entries(rootData)) {\n if (key === 'data') continue;\n processField(key, value, result, rootData, '');\n }\n rootData = rootData.data as Record<string, unknown>;\n result.overallConfidence ??= readOverallConfidence(rootData);\n // Inner fields live under the wrapper in the original payload — server\n // pointers resolve against the payload root, so keep the /data prefix.\n basePointer = '/data';\n }\n\n for (const [key, value] of Object.entries(rootData)) {\n processField(key, value, result, rootData, basePointer);\n }\n\n return result;\n}\n\nfunction readOverallConfidence(\n source: Record<string, unknown>,\n): { level: string; reasons: string[] } | null {\n const rawLevel = source.overall_confidence ?? source.overallConfidence;\n const value = extractValue(rawLevel);\n if (typeof value !== 'string' || value.length === 0) return null;\n\n const rawReasons = source.confidence_reasons ?? source.confidenceReasons;\n const reasons = Array.isArray(rawReasons)\n ? rawReasons.filter((reason): reason is string => typeof reason === 'string')\n : [];\n return { level: value, reasons };\n}\n\nfunction processField(\n key: string,\n value: unknown,\n result: ClassifiedData,\n parentObj: Record<string, unknown> | undefined,\n basePointer: string,\n): void {\n // Skip metadata fields at root level\n // Overall confidence has a dedicated summary above the form. Accept both\n // wire spellings because Pydantic aliases vary between processor payloads.\n if ([\n 'confidence', 'confidence_reasons', 'confidenceReasons', 'coordinates',\n 'overall_confidence', 'overallConfidence',\n ].includes(key)) {\n return;\n }\n\n const pointer = `${basePointer}/${escapeSegment(key)}`;\n\n // Primitive or null\n if (value === null || typeof value !== 'object') {\n result.headers.push({\n key,\n pointer,\n value,\n coordinates: null,\n confidence: null,\n });\n return;\n }\n\n // Value object (has 'value' property)\n if (isValueObject(value)) {\n result.headers.push({\n key,\n pointer,\n value: extractValue(value),\n coordinates: extractCoordinates(value),\n confidence: extractConfidence(value),\n });\n return;\n }\n\n // Array\n if (Array.isArray(value)) {\n if (value.length === 0) {\n result.headers.push({\n key,\n pointer,\n value: null,\n coordinates: null,\n confidence: null,\n });\n return;\n }\n\n // Array of primitives - display as simple list\n if (isPrimitiveArray(value)) {\n result.simpleLists.push({\n key,\n pointer,\n items: value.map((item, index) => ({\n pointer: `${pointer}/${index}`,\n value: item,\n coordinates: null,\n confidence: null,\n })),\n });\n return;\n }\n\n // Simple value array (Type C) - array of { value, coordinates? }\n if (isSimpleValueArray(value)) {\n result.simpleLists.push({\n key,\n pointer,\n items: value.map((item, index) => ({\n pointer: `${pointer}/${index}`,\n value: extractValue(item),\n coordinates: extractCoordinates(item),\n confidence: extractConfidence(item),\n })),\n });\n return;\n }\n\n // Table array (Type A) - array of flat objects with many fields\n if (isTableArray(value)) {\n const first = value[0] as Record<string, unknown>;\n const metaFields = new Set(['confidence', 'confidence_reasons', 'coordinates']);\n const columns = Object.keys(first).filter(k => !metaFields.has(k));\n\n // A table-specific confidence belongs in its section header. Global\n // overall confidence is intentionally not copied into every table.\n let overallConfidence: { level: string; reasons: string[] } | null = null;\n if (parentObj) {\n // First check for specific key pattern (e.g., line_items_confidence)\n const confidenceKey = `${key}_confidence`;\n const reasonsKey = `${key}_confidence_reasons`;\n if (parentObj[confidenceKey]) {\n overallConfidence = {\n level: parentObj[confidenceKey] as string,\n reasons: (parentObj[reasonsKey] as string[]) || [],\n };\n }\n }\n\n result.tables.push({\n key,\n pointer,\n columns,\n overallConfidence,\n rows: value.map((row, rowIndex) => {\n const rowPointer = `${pointer}/${rowIndex}`;\n const rowData: Record<string, ClassifiedCell> = {};\n // isTableArray samples only the first element; a null/non-object row\n // later in the array must not crash — its cells emit with undefined.\n const rowObj = (row ?? {}) as Record<string, unknown>;\n\n for (const col of columns) {\n const cell = rowObj[col];\n rowData[col] = {\n pointer: `${rowPointer}/${escapeSegment(col)}`,\n value: extractValue(cell),\n coordinates: extractCoordinates(cell),\n confidence: extractConfidence(cell),\n };\n }\n\n // Also extract row-level confidence if present\n if (rowObj.confidence || rowObj.confidence_reasons) {\n // _rowMeta is synthetic (no real field behind it); its pointer is\n // the ROW pointer, and it never binds to a server schema key.\n rowData[ROW_META_KEY] = {\n pointer: rowPointer,\n value: null,\n coordinates: null,\n confidence: {\n level: rowObj.confidence as string || '',\n reasons: (rowObj.confidence_reasons as string[]) || [],\n },\n };\n }\n\n return rowData;\n }),\n });\n return;\n }\n\n // Entity array (Type B) - array of objects (cards)\n if (isEntityArray(value)) {\n result.entities.push({\n key,\n pointer,\n items: value.map((item, index) => {\n const entity: Record<string, ClassifiedCell> = {};\n\n // isEntityArray samples only the first element; a null/non-object\n // item later in the array emits an empty entity so indices (and\n // therefore sibling pointers) stay aligned with the payload.\n if (item === null || typeof item !== 'object' || Array.isArray(item)) {\n return entity;\n }\n\n for (const [fieldKey, fieldValue] of Object.entries(item as Record<string, unknown>)) {\n // Skip metadata fields\n if (['confidence', 'confidence_reasons', 'coordinates'].includes(fieldKey)) {\n continue;\n }\n entity[fieldKey] = {\n pointer: `${pointer}/${index}/${escapeSegment(fieldKey)}`,\n value: extractValue(fieldValue),\n coordinates: extractCoordinates(fieldValue),\n confidence: extractConfidence(fieldValue),\n };\n }\n\n return entity;\n }),\n });\n return;\n }\n\n // Fallback for unrecognized arrays\n result.fallback.push({ key, data: value });\n return;\n }\n\n // Nested object without 'value' property - try to recurse into it\n const nestedObj = value as Record<string, unknown>;\n const nestedKeys = Object.keys(nestedObj).filter(k => !['confidence', 'confidence_reasons', 'coordinates'].includes(k));\n\n // If the nested object has fields, process them recursively with prefixed keys\n if (nestedKeys.length > 0 && nestedKeys.length <= 10) {\n // Small nested objects get flattened into headers with grouped key names\n for (const nestedKey of nestedKeys) {\n const nestedValue = nestedObj[nestedKey];\n const combinedKey = `${key}.${nestedKey}`;\n const nestedPointer = `${pointer}/${escapeSegment(nestedKey)}`;\n\n // Process primitives and value objects as headers\n if (nestedValue === null || typeof nestedValue !== 'object') {\n result.headers.push({\n key: combinedKey,\n pointer: nestedPointer,\n value: nestedValue,\n coordinates: null,\n confidence: null,\n });\n } else if (isValueObject(nestedValue)) {\n result.headers.push({\n key: combinedKey,\n pointer: nestedPointer,\n value: extractValue(nestedValue),\n coordinates: extractCoordinates(nestedValue),\n confidence: extractConfidence(nestedValue),\n });\n } else {\n // Complex nested values go to fallback\n result.fallback.push({ key: combinedKey, data: nestedValue });\n }\n }\n return;\n }\n\n // Large or empty nested objects go to fallback\n result.fallback.push({ key, data: value });\n}\n","/**\n * Server-generated submission keys and JSON-pointer resolution.\n *\n * Mirrors the backend exactly (gemina-api-v2 `data_validator.py` /\n * `validator/utils.py`) so that what the component resolves client-side is\n * what the server will resolve when it scores the submission:\n * - key regex `^label:([^|]+)\\|ptr:(/.*)$`\n * - `~1` unescaped before `~0`\n * - list segments must be all digits\n * - unresolvable paths are a sentinel, distinct from a stored `null`.\n *\n * Known divergences from the backend (all client-stricter; unreachable via\n * server-generated keys):\n * - Python's `$` in the key regex also matches before a trailing newline;\n * JS `$` (no `m` flag) matches only at end-of-string.\n * - The backend's `pointer.lstrip(\"/\")` collapses multiple leading slashes\n * (`//a` resolves `doc[\"a\"]`); here that is NOT_FOUND (RFC-6901-correct).\n * - Python's `isdigit()` accepts non-ASCII unicode digits as list indices;\n * `/^\\d+$/` here is ASCII-only.\n */\n\nexport interface SchemaKey {\n /** The raw key — submitted verbatim as a property name in the feedback body. */\n raw: string;\n /** Human-meaningful label; the only key format the host app ever sees. */\n label: string;\n /** JSON pointer into the extraction values payload. */\n pointer: string;\n}\n\nconst KEY_RE = /^label:([^|]+)\\|ptr:(\\/.*)$/;\n\n/** Parse one schema key, or null for a malformed entry (the backend skips those quietly too). */\nexport function parseSchemaKey(raw: string): SchemaKey | null {\n const match = KEY_RE.exec(raw);\n if (match === null) {\n return null;\n }\n return { raw, label: match[1] as string, pointer: match[2] as string };\n}\n\n/** \"Path did not resolve\" — deliberately distinct from a stored null value. */\nexport const NOT_FOUND: unique symbol = Symbol('gemina-verification-not-found');\nexport type NotFound = typeof NOT_FOUND;\n\n/** Resolve a JSON pointer against a document, backend-compatible (see module docs). */\nexport function resolvePointer(doc: unknown, pointer: string): unknown | NotFound {\n if (pointer === '') {\n return doc;\n }\n if (!pointer.startsWith('/')) {\n return NOT_FOUND;\n }\n let current: unknown = doc;\n for (const rawSegment of pointer.slice(1).split('/')) {\n const segment = rawSegment.replace(/~1/g, '/').replace(/~0/g, '~');\n if (Array.isArray(current)) {\n if (!/^\\d+$/.test(segment)) {\n return NOT_FOUND;\n }\n const index = Number(segment);\n if (index >= current.length) {\n return NOT_FOUND;\n }\n current = current[index];\n } else if (current !== null && typeof current === 'object') {\n if (!Object.prototype.hasOwnProperty.call(current, segment)) {\n return NOT_FOUND;\n }\n current = (current as Record<string, unknown>)[segment];\n } else {\n return NOT_FOUND;\n }\n }\n return current;\n}\n\n/**\n * `vendor_name` -> `vendorName`. The client's ONLY casing rule.\n *\n * Lives here, alone, on purpose. Schema pointers are snake_case while the\n * payload is camelCase, so this rule decides whether a pointer resolves at\n * all — and a second copy that drifts from it is exactly how a field silently\n * stops resolving (see the grossLinePrice alias bug: a wire name this rule\n * could not reproduce made an extracted value render as \"Not detected\" and\n * score a false `extra` on every row).\n */\nexport function snakeToCamel(segment: string): string {\n return segment.replace(/_([a-zA-Z0-9])/g, (_unused, ch: string) => ch.toUpperCase());\n}\n","import { isValueObject } from './classify';\nimport { coerceInput } from './field-types';\nimport type { CellView } from './row-cells';\nimport type { ValidationFieldDescriptor } from './field-types';\nimport { NOT_FOUND, parseSchemaKey, snakeToCamel } from './pointer';\nimport type { NotFound, SchemaKey } from './pointer';\n\n/** One server-mandated submission slot, bound to whatever was extracted there. */\nexport interface FieldBinding {\n key: SchemaKey;\n /**\n * The RAW resolved node — never unwrapped — or NOT_FOUND. This is what an\n * untouched binding submits verbatim: the server resolves the same pointer\n * against the same model tree (casing aside), so wrapper objects compare\n * dict-vs-dict and score correct. Note: dict-valued submissions additionally\n * require INNER-key casing identity with the server's scoring dict — which\n * holds for custom_template's uncamelized dicts, the only reachable case.\n */\n serverValue: unknown | NotFound;\n /** DISPLAY value: serverValue unwrapped via isValueObject, else serverValue. */\n extracted: unknown | NotFound;\n /**\n * The actually-RESOLVED pointer (payload casing — camel in prod) minus a\n * trailing `/value` segment; the pointer the classifier reports for this\n * field. For NOT_FOUND bindings: best-effort camelized schema pointer.\n */\n fieldPointer: string;\n /**\n * False when serverValue is a container (object/array, including value-object\n * wrappers): the server's `coerce_like` does nothing for containers, so a\n * string edit could never score correct. True for NOT_FOUND (fill-in), null,\n * and primitives.\n */\n editable: boolean;\n /**\n * The server's type metadata for this field, matched by exact key.\n *\n * `undefined` whenever the backend predates the typed contract OR the host\n * is on an SDK generated before it — the converter drops what it does not\n * know. Every consumer treats that as \"the plain text input we always had\",\n * which is why nothing here is required.\n */\n field?: ValidationFieldDescriptor;\n}\n\nfunction unescapeSegment(raw: string): string {\n return raw.replace(/~1/g, '/').replace(/~0/g, '~');\n}\n\nfunction escapeSegment(segment: string): string {\n return segment.replace(/~/g, '~0').replace(/\\//g, '~1');\n}\n\n/** Best-effort camelization of a whole pointer (used when resolution fails). */\nfunction camelizePointer(pointer: string): string {\n if (!pointer.startsWith('/')) {\n return pointer;\n }\n return '/' + pointer\n .slice(1)\n .split('/')\n .map((raw) => escapeSegment(snakeToCamel(unescapeSegment(raw))))\n .join('/');\n}\n\ninterface Resolution {\n node: unknown | NotFound;\n /** The pointer as actually matched in the payload (camel in prod). */\n resolvedPointer: string;\n}\n\n/**\n * Resolve a schema pointer against the view payload, casing-aware (review C1):\n * schema pointers are snake_case while the prod payload is camelCase, so each\n * object-key segment tries exact first, then snake→camel. The server scores\n * against its own snake dict, so the mismatch is client-only; structurally the\n * walk mirrors `resolvePointer` (backend parity — no fallbacks, no unwrapping).\n */\nfunction resolveCasingAware(doc: unknown, pointer: string): Resolution {\n const missing: Resolution = { node: NOT_FOUND, resolvedPointer: camelizePointer(pointer) };\n if (pointer === '') {\n return { node: doc, resolvedPointer: '' };\n }\n if (!pointer.startsWith('/')) {\n return missing;\n }\n let current: unknown = doc;\n const matched: string[] = [];\n for (const rawSegment of pointer.slice(1).split('/')) {\n const segment = unescapeSegment(rawSegment);\n if (Array.isArray(current)) {\n if (!/^\\d+$/.test(segment)) {\n return missing;\n }\n const index = Number(segment);\n if (index >= current.length) {\n return missing;\n }\n current = current[index];\n matched.push(rawSegment);\n } else if (current !== null && typeof current === 'object') {\n let key: string;\n if (Object.prototype.hasOwnProperty.call(current, segment)) {\n key = segment;\n } else {\n const camel = snakeToCamel(segment);\n if (camel === segment || !Object.prototype.hasOwnProperty.call(current, camel)) {\n return missing;\n }\n key = camel;\n }\n current = (current as Record<string, unknown>)[key];\n matched.push(escapeSegment(key));\n } else {\n return missing;\n }\n }\n return { node: current, resolvedPointer: '/' + matched.join('/') };\n}\n\n/** A schema pointer `P/value` and a classifier pointer `P` are the same field. */\nfunction stripValueSuffix(pointer: string): string {\n return pointer.endsWith('/value') ? pointer.slice(0, -'/value'.length) : pointer;\n}\n\n/**\n * Parse + resolve every schema key. Malformed entries are skipped (backend\n * parity).\n *\n * `fields` is the server's typed descriptors, indexed here by their opaque\n * key. Matching is by key and ONLY by key: labels repeat across rows of a\n * table (`total` appears once per line item), so a label match would type one\n * row's cell from another row's descriptor.\n */\nexport function buildBindings(\n validationSchema: string[],\n values: unknown,\n fields?: ValidationFieldDescriptor[],\n): FieldBinding[] {\n const descriptors = new Map<string, ValidationFieldDescriptor>();\n for (const descriptor of fields ?? []) {\n if (typeof descriptor?.key === 'string') {\n descriptors.set(descriptor.key, descriptor);\n }\n }\n const bindings: FieldBinding[] = [];\n for (const raw of validationSchema) {\n const key = parseSchemaKey(raw);\n if (key === null) {\n continue;\n }\n const { node: serverValue, resolvedPointer } = resolveCasingAware(values, key.pointer);\n const extracted = serverValue !== NOT_FOUND && isValueObject(serverValue)\n ? serverValue.value\n : serverValue;\n const editable = serverValue === NOT_FOUND\n || serverValue === null\n || typeof serverValue !== 'object';\n bindings.push({\n key,\n serverValue,\n extracted,\n fieldPointer: stripValueSuffix(resolvedPointer),\n editable,\n field: descriptors.get(key.raw),\n });\n }\n return bindings;\n}\n\n/**\n * Index bindings by the pointer the CLASSIFIER reports for a field. The\n * classifier walks the same payload the bindings resolved against, so its\n * pointers carry the payload's casing — which is exactly what `fieldPointer`\n * recorded during resolution.\n */\nexport function indexBindingsByFieldPointer(bindings: FieldBinding[]): Map<string, FieldBinding> {\n const map = new Map<string, FieldBinding>();\n for (const binding of bindings) {\n map.set(binding.fieldPointer, binding);\n }\n return map;\n}\n\n/**\n * What an editable input is prefilled with. RAW value stringification only —\n * display formatting (`formatValue`) must never round-trip into a submission\n * (a locale-formatted \"1,500\" or date would score as a correction).\n */\nexport function toInputString(extracted: unknown | NotFound): string {\n if (extracted === NOT_FOUND || extracted === null || extracted === undefined) {\n return '';\n }\n if (typeof extracted === 'object') {\n return JSON.stringify(extracted);\n }\n return String(extracted);\n}\n\n/** One table's alignment, exactly as `ExtractionValidationInDTO.rowSources`. */\nexport interface RowSourcesEntry {\n table: string;\n sources: Array<number | null>;\n}\n\nexport interface SubmissionResult {\n /** Body for `ExtractionValidationInDTO.data` — raw schema keys, ALL asserted fields. */\n data: Record<string, unknown>;\n /** The same entries keyed by human label — handed to `onComplete`. */\n byLabel: Record<string, unknown>;\n confirmed: number;\n corrected: number;\n /**\n * How the submitted tables align to the extracted ones. EMPTY when no row\n * was added or removed, so an untouched submission's wire payload stays\n * byte-identical to what it was before row editing existed.\n */\n rowSources: RowSourcesEntry[];\n}\n\n/**\n * Compose the one-shot feedback body.\n *\n * `edits` holds ONLY dirty keys (raw schema key → current input string; the\n * UI removes an entry when the input returns to its initial string). The\n * counts trust that contract: a caller that fails to delete-on-revert\n * relabels a confirmation as a correction in `confirmed`/`corrected`; the\n * server-side scoring itself survives, since the unchanged string coerces\n * back to a value equal to the extracted one.\n *\n * Rules (verified against the backend DataValidator):\n * - untouched + resolved (even resolved-null): submit `serverValue` verbatim\n * — the raw node, wrappers included — the server resolves the same node\n * and compares equal → scored a confirmation;\n * - untouched + never extracted: OMIT — the user asserted nothing, and\n * submitting null would force a false \"missing\";\n * - dirty, non-empty: submit the trimmed string (only scalar-valued bindings\n * are editable, and for scalar targets the server's `coerce_like` adopts\n * the extracted value's type before comparing; containers are never\n * editable — see `FieldBinding.editable`);\n * - dirty, cleared: the user asserts the field is absent/wrong → null;\n * unless nothing was extracted either, in which case there is nothing\n * to assert → OMIT.\n */\nexport function composeSubmission(\n bindings: FieldBinding[],\n edits: ReadonlyMap<string, string>,\n options: {\n /**\n * The resolved cells, when the caller has them. Supplying these is what\n * makes row editing work: they carry the SUBMITTED key for each cell and\n * mark the ones belonging to rows the reviewer added. Omitted, every\n * binding is submitted under its own raw key — exactly today's behaviour.\n */\n cells?: readonly CellView[];\n rowSources?: RowSourcesEntry[];\n } = {},\n): SubmissionResult {\n const cells: readonly CellView[] = options.cells ?? bindings.map((binding) => ({\n editKey: binding.key.raw,\n submitKey: binding.key.raw,\n column: binding.key.label,\n rowKey: binding.key.raw,\n binding,\n added: false,\n }));\n const data: Record<string, unknown> = {};\n const byLabel: Record<string, unknown> = {};\n let confirmed = 0;\n let corrected = 0;\n\n for (const cell of cells) {\n const { binding } = cell;\n // The label follows the SUBMITTED key, not the source binding. After a\n // deletion, source row 1 is submitted as row 0 — handing the host\n // `line_1_description` for what the wire calls row 0 would have\n // `onComplete` disagree with the payload it describes.\n const label = parseSchemaKey(cell.submitKey)?.label ?? binding.key.label;\n const edit = edits.get(cell.editKey);\n if (edit !== undefined) {\n const trimmed = edit.trim();\n // Nothing extracted and nothing typed: there is no assertion to make.\n // For an ADDED row this is also what keeps an empty cell out of the\n // payload — its aligned counterpart does not exist, so an omission\n // cannot become an `extra`.\n if (trimmed === '' && binding.serverValue === NOT_FOUND) {\n continue;\n }\n // Typed by the field's own descriptor, so a number reaches the server as\n // a number. A cleared input stays null — it asserts absence and must\n // never become 0 or an empty string.\n const value = trimmed === '' ? null : coerceInput(trimmed, binding.field);\n data[cell.submitKey] = value;\n byLabel[label] = value;\n corrected += 1;\n } else {\n if (binding.serverValue === NOT_FOUND) {\n continue;\n }\n // Untouched cells of a row that still maps to a source submit that\n // source's extracted value — under its SUBMITTED key, so the payload\n // mirrors the approved table rather than the extracted one.\n data[cell.submitKey] = binding.serverValue;\n byLabel[label] = binding.serverValue;\n confirmed += 1;\n }\n }\n return { data, byLabel, confirmed, corrected, rowSources: options.rowSources ?? [] };\n}\n\n/**\n * How many rows the extraction actually found at a table pointer.\n *\n * Reuses the SAME casing-aware walk the bindings use, because the server's\n * pointers are snake_case while the payload is camelCase — counting with a\n * naive lookup would report 0 for every table in production and quietly\n * disable every row control.\n *\n * 0 for a pointer that resolves to anything but an array, which covers both\n * \"no such table\" and the zero-row case identically — and both want the same\n * empty plan.\n */\nexport function countRowsAt(values: unknown, pointer: string): number {\n const { node } = resolveCasingAware(values, pointer);\n return Array.isArray(node) ? node.length : 0;\n}\n","/**\n * The row plan — which submitted row came from which extracted row.\n *\n * Pure, no React. This is the client half of the backend's `rowSources`\n * contract: the server aligns the submitted table to the extracted one using\n * it, which is what lets an inserted row score `missing` and a deleted one\n * score `extra` WITHOUT cascading a correction onto every row below.\n *\n * Encoding the same information as insert/delete OPS was rejected: two inserts\n * before the same index produce two identical ops whose reconstruction depends\n * on unstated ordering rules. The plan is unambiguous by construction — it IS\n * the alignment, not a recipe for reproducing one.\n *\n * Row IDENTITY is the other half of the job. Edits are keyed by row id rather\n * than by position, so a correction typed into the third row stays with that\n * row after the first is deleted. Keying by position would silently move a\n * reviewer's correction onto a different line item: wrong data, no symptom.\n */\n\nexport interface RowPlanEntry {\n /** Stable for the lifetime of the plan. Edits are keyed by this. */\n id: string;\n /** Index in the EXTRACTED table, or null for a row the reviewer added. */\n source: number | null;\n}\n\n/**\n * Ids for added rows. A counter rather than a random id so a render is\n * reproducible and a test can reason about it; uniqueness is all that is\n * required of it, and it never leaves the client.\n */\nlet addedRowCounter = 0;\n\n/**\n * The identity mapping: every extracted row, in order, unmoved.\n *\n * `scope` is the table's pointer, and it is NOT decoration. Edit keys are\n * derived from row ids and every table shares one edits map, so unscoped ids\n * would give two row-mutable tables the same `row-0` — and typing into one\n * table's first row would silently rewrite the other's. `rowMutableTables` is\n * a list, so nothing but this prevents that.\n */\nexport function initialRowPlan(extractedCount: number, scope = ''): RowPlanEntry[] {\n return Array.from({ length: Math.max(0, extractedCount) }, (_unused, index) => ({\n // Derived from the source index, so it is stable across re-renders without\n // any state to carry — an extracted row's identity never changes.\n id: `${scope}#row-${index}`,\n source: index,\n }));\n}\n\n/**\n * Mint an id for a row about to be added.\n *\n * Called OUTSIDE the state updater on purpose: an updater must be pure, and\n * React invokes it twice under Strict Mode, so incrementing a counter inside\n * one makes ids depend on how many times React chose to call it.\n */\nexport function nextAddedRowId(scope = ''): string {\n addedRowCounter += 1;\n return `${scope}#added-${addedRowCounter}`;\n}\n\n/** Drop the row at `position`. Out-of-range is a no-op, not a throw. */\nexport function removeRow(plan: RowPlanEntry[], position: number): RowPlanEntry[] {\n if (position < 0 || position >= plan.length) {\n return plan;\n }\n return plan.filter((_entry, index) => index !== position);\n}\n\n/**\n * Insert a blank user-added row after `position`.\n *\n * `-1` prepends, which is also how the zero-row table gets its first line.\n */\nexport function insertRowAfter(plan: RowPlanEntry[], position: number, id?: string): RowPlanEntry[] {\n const added: RowPlanEntry = { id: id ?? nextAddedRowId(), source: null };\n const at = Math.min(Math.max(position + 1, 0), plan.length);\n return [...plan.slice(0, at), added, ...plan.slice(at)];\n}\n\n/**\n * The edit-map key for one table cell.\n *\n * Table cells and header fields share ONE edits map, so this namespace must\n * not collide with a raw schema key — hence the prefix, and hence the test\n * asserting it never looks like `label:…`.\n */\nexport function cellEditKey(rowId: string, column: string): string {\n return `cell:${rowId}|col:${column}`;\n}\n\n/** The `sources` array for the wire, in submitted order. */\nexport function rowSourcesOf(plan: RowPlanEntry[]): Array<number | null> {\n return plan.map((entry) => entry.source);\n}\n\n/**\n * True when the reviewer has neither added nor removed a row.\n *\n * The wire payload for an untouched row set must be byte-identical to what it\n * was before this feature existed, so `composeSubmission` omits the table's\n * `rowSources` entry entirely in that case. Comparing against\n * `extractedCount` is what catches rows removed from the END, whose remaining\n * sources still read 0..n-1.\n */\nexport function isIdentityPlan(plan: RowPlanEntry[], extractedCount: number): boolean {\n return plan.length === extractedCount\n && plan.every((entry, index) => entry.source === index);\n}\n","/**\n * The one model of \"what cells does this table currently have\".\n *\n * Four consumers need it — the form's rendering, the unit-size pair rule,\n * Phase 6's submit gate, and `composeSubmission` — and deriving it four times\n * would let them disagree about which row a cell belongs to. Under row editing\n * that disagreement is not cosmetic: it silently attributes a reviewer's\n * correction to the wrong line item.\n *\n * Every cell carries THREE identities, because they genuinely differ:\n *\n * - `editKey` follows the ROW (`cellEditKey(rowId, column)`), so an edit stays\n * with its row when rows above it are deleted.\n * - `submitKey` follows the SUBMITTED POSITION, because the payload must mirror\n * the approved table — row 3 of what the reviewer sees is `/line_items/2/…`\n * on the wire regardless of where it was extracted from.\n * - `binding.key` follows the EXTRACTED position, because that is where the\n * value and its coordinates actually live.\n *\n * For an untouched table all three agree, which is why this never mattered\n * before.\n */\n\nimport { toInputString } from './bindings';\nimport type { FieldBinding } from './bindings';\nimport { cellSchemaKey } from './field-types';\nimport type { RowMutableTable, ValidationFieldDescriptor } from './field-types';\nimport { NOT_FOUND, parseSchemaKey, snakeToCamel } from './pointer';\nimport { cellEditKey } from './row-plan';\nimport type { RowPlanEntry } from './row-plan';\n\nexport interface PlannedCell {\n column: string;\n /** Where this cell's edit is stored. Stable across row moves. */\n editKey: string;\n /** The raw schema key this cell is submitted under. Follows position. */\n submitKey: string;\n /** Real for an extracted row; synthesized for one the reviewer added. */\n binding: FieldBinding;\n /** True when there is no extracted value behind this cell. */\n added: boolean;\n}\n\nexport interface PlannedRow {\n entry: RowPlanEntry;\n cells: PlannedCell[];\n}\n\n/**\n * A binding for a cell of a row that was never extracted.\n *\n * Deliberately the SAME shape the \"Not detected\" fill-in path already renders:\n * `NOT_FOUND` with `editable: true`. That is not a convenience — it is what\n * makes an added row's cells behave identically to a field the model missed,\n * which is exactly what they are.\n */\nfunction syntheticBinding(\n submitKey: string,\n descriptor: ValidationFieldDescriptor | undefined,\n): FieldBinding | null {\n const key = parseSchemaKey(submitKey);\n if (key === null) {\n return null;\n }\n return {\n key,\n serverValue: NOT_FOUND,\n extracted: NOT_FOUND,\n // No extracted node, so nothing to point at on the document.\n fieldPointer: key.pointer,\n editable: true,\n field: descriptor,\n };\n}\n\n/**\n * Resolve every cell of a row-mutable table under its current plan.\n *\n * `columns` is the display order — the classifier's for a table with rows, the\n * server's declared column list for one with none.\n */\nexport function planTableCells(\n table: RowMutableTable,\n plan: readonly RowPlanEntry[],\n columns: readonly string[],\n bindingsByRawKey: ReadonlyMap<string, FieldBinding>,\n): PlannedRow[] {\n const descriptors = new Map<string, ValidationFieldDescriptor>();\n for (const column of table.columns) {\n if (typeof column.key === 'string') {\n descriptors.set(column.key, column);\n }\n }\n\n return plan.map((entry, submittedIndex) => {\n const cells: PlannedCell[] = [];\n for (const column of columns) {\n const submitKey = cellSchemaKey(table.keyTemplate, submittedIndex, column);\n const editKey = cellEditKey(entry.id, column);\n const extractedKey = entry.source === null\n ? null\n : cellSchemaKey(table.keyTemplate, entry.source, column);\n const existing = extractedKey === null ? undefined : bindingsByRawKey.get(extractedKey);\n const binding = existing ?? syntheticBinding(submitKey, descriptors.get(column));\n if (binding === null) {\n continue;\n }\n cells.push({ column, editKey, submitKey, binding, added: existing === undefined });\n }\n return { entry, cells };\n });\n}\n\n/**\n * The display columns for a table: the server's declaration, plus anything the\n * classifier saw that the server did not declare.\n *\n * The SERVER's list is canonical because it is derived from the model, so it is\n * complete and present even for a zero-row table — the case a reviewer most\n * needs, since the model found nothing at all.\n *\n * The classifier's list cannot be trusted alone: it samples column names from\n * ROW 0 ONLY (`Object.keys(first)`), so a field absent from the first row but\n * present in a later one would not appear here — and because a planned table\n * suppresses every binding under its pointer, that value would be dropped from\n * the submission entirely, silently, even with no row edits. Merging is what\n * makes the suppression safe.\n */\nexport function displayColumns(\n table: RowMutableTable,\n classifiedColumns: readonly string[],\n): string[] {\n const declared = table.columns\n .map((column) => column.key)\n .filter((name): name is string => typeof name === 'string');\n // The schema uses model field names (snake_case), while the response DTO\n // serializes those same fields as camelCase. Exact comparison rendered the\n // entire table twice: every declared column followed by its classified\n // alias. Keep the server spelling as the canonical display/submission name,\n // and use the client's one shared casing rule only for de-duplication.\n // Declared names themselves are never collapsed, so a dynamic template that\n // genuinely declares both spellings still keeps both columns.\n const declaredAliases = new Set(declared.map(snakeToCamel));\n return [\n ...declared,\n ...classifiedColumns.filter((name) => !declaredAliases.has(snakeToCamel(name))),\n ];\n}\n\n/**\n * `/line_items` and the payload's `/lineItems` are the same table.\n *\n * Uses the SHARED casing rule rather than a local copy: two copies that drift\n * is precisely how a pointer silently stops resolving.\n */\nexport function matchesTablePointer(serverPointer: string, classifiedPointer: string): boolean {\n return serverPointer === classifiedPointer || snakeToCamel(serverPointer) === classifiedPointer;\n}\n\n/**\n * Every editable cell in the form, as one flat list.\n *\n * The pair rule and the submit gate both need \"what can be edited, and under\n * which key\" — and BOTH were previously derived from raw schema keys, which a\n * planned table cell no longer uses. Deriving them separately is how they\n * would drift apart; this is the single source they now share.\n *\n * `rowKey` groups cells that belong to the same row. For a planned table that\n * is the row's stable id; elsewhere it is the pointer prefix, which is what\n * the pre-row-editing code effectively used.\n */\nexport interface CellView {\n editKey: string;\n /** The raw schema key this cell goes on the wire under. */\n submitKey: string;\n column: string;\n rowKey: string;\n binding: FieldBinding;\n /** True when nothing was extracted here — a row the reviewer added. */\n added: boolean;\n}\n\n/** `/line_items/3/unit_size` -> `{ row: '/line_items/3', field: 'unit_size' }`. */\nfunction splitPointer(pointer: string): { row: string; field: string } | null {\n const cut = pointer.lastIndexOf('/');\n return cut <= 0 ? null : { row: pointer.slice(0, cut), field: pointer.slice(cut + 1) };\n}\n\n/**\n * Flatten bindings and planned tables into one list of cell views.\n *\n * A planned table OWNS every binding under its pointer — not merely the ones\n * its surviving rows still reference. Skipping only the referenced ones leaves\n * a DELETED row's bindings in the list, and since they carry their original\n * raw key as their submit key they overwrite whichever row moved up into that\n * position: the deletion silently does nothing, and the payload claims a row\n * the reviewer removed. Ownership is by pointer prefix, so the whole table\n * comes from the plan or none of it does.\n */\nexport function collectCellViews(\n bindings: readonly FieldBinding[],\n plannedTables: ReadonlyMap<string, PlannedRow[]>,\n): CellView[] {\n const views: CellView[] = [];\n const ownedPrefixes = [...plannedTables.keys()].map((pointer) => `${pointer}/`);\n\n for (const rows of plannedTables.values()) {\n for (const row of rows) {\n for (const cell of row.cells) {\n views.push({\n editKey: cell.editKey,\n submitKey: cell.submitKey,\n column: cell.column,\n rowKey: row.entry.id,\n binding: cell.binding,\n added: cell.added,\n });\n }\n }\n }\n\n for (const binding of bindings) {\n if (ownedPrefixes.some((prefix) => binding.key.pointer.startsWith(prefix))) {\n continue;\n }\n const split = splitPointer(binding.key.pointer);\n views.push({\n // Outside a plan all three identities coincide, which is why none of\n // this was needed before row editing.\n editKey: binding.key.raw,\n submitKey: binding.key.raw,\n column: split?.field ?? binding.key.label,\n rowKey: split?.row ?? binding.key.raw,\n binding,\n added: false,\n });\n }\n return views;\n}\n\n/** The one cross-field rule the server enforces. Deliberately not a rules engine. */\nconst UNIT_SIZE = 'unit_size';\nconst UNIT_SIZE_UOM = 'unit_size_uom';\nexport const UNIT_PAIR_MESSAGE = 'Enter both value and unit';\n\n/**\n * Rows where exactly one half of the unit-size pair is filled in.\n *\n * The server treats `unit_size` and `unit_size_uom` as both-or-nothing:\n * `_unit_size_pair_rule` (invoice_line_item.py:50-56) nulls BOTH whenever\n * either is missing, on every parse INCLUDING the scorer's. So a reviewer who\n * fills one and not the other has both silently zeroed before scoring, and\n * `onComplete` would hand the host a value the backend had already discarded.\n * Flagging it is the only way the reviewer ever learns.\n *\n * Keyed by EDIT key, and grouped by `rowKey`, so it works identically for an\n * extracted row and one the reviewer added — an added row is exactly where a\n * half-filled pair is most likely.\n *\n * Deliberately hard-coded to this pair rather than generalised. Exactly one\n * such rule exists in the models; a cross-field rules DSL would be speculative\n * flexibility with no second caller.\n */\nexport function unitSizePairErrors(\n cells: readonly CellView[],\n edits: ReadonlyMap<string, string>,\n): Map<string, string> {\n const rows = new Map<string, { size?: CellView; uom?: CellView }>();\n for (const cell of cells) {\n if (cell.column !== UNIT_SIZE && cell.column !== UNIT_SIZE_UOM) {\n continue;\n }\n const row = rows.get(cell.rowKey) ?? {};\n if (cell.column === UNIT_SIZE) {\n row.size = cell;\n } else {\n row.uom = cell;\n }\n rows.set(cell.rowKey, row);\n }\n\n const errors = new Map<string, string>();\n for (const { size, uom } of rows.values()) {\n // A row missing one half of the pair from its schema entirely cannot be\n // half-filled, so there is nothing to enforce.\n if (!size || !uom) {\n continue;\n }\n const filled = (cell: CellView) =>\n (edits.get(cell.editKey) ?? toInputString(cell.binding.extracted)).trim() !== '';\n if (filled(size) !== filled(uom)) {\n errors.set(size.editKey, UNIT_PAIR_MESSAGE);\n errors.set(uom.editKey, UNIT_PAIR_MESSAGE);\n }\n }\n return errors;\n}\n\n/**\n * Drop added rows the reviewer never typed into.\n *\n * Clicking \"Add line\" and then changing your mind is ordinary. Every cell of\n * such a row is already omitted from `data` — but its `null` source would\n * remain in the alignment, asserting to the scorer that a row exists there.\n * On a submission that happens exactly once, that is a phantom line item on\n * the record with nothing in it.\n *\n * Only ADDED rows are pruned. An extracted row the reviewer emptied is a\n * deliberate assertion that its content is wrong, and must survive.\n */\nexport function pruneEmptyAddedRows(\n plannedTables: ReadonlyMap<string, PlannedRow[]>,\n edits: ReadonlyMap<string, string>,\n): Map<string, PlannedRow[]> {\n const out = new Map<string, PlannedRow[]>();\n for (const [pointer, rows] of plannedTables) {\n out.set(pointer, rows.filter((row) => {\n if (row.entry.source !== null) {\n return true;\n }\n return row.cells.some((cell) => (edits.get(cell.editKey) ?? '').trim() !== '');\n }));\n }\n return out;\n}\n","/**\n * Verification form — field primitives (Task 12).\n *\n * Port of the console's `FieldValue.tsx` through the house-style\n * transformation table: antd `<Tooltip>` becomes a native `title` attribute\n * paired with an aria-label, `@ant-design/icons` becomes the hand-drawn\n * `IconEye`, SCSS-module classes become the Task 6 `.gemina-verification__*`\n * contract classes, and NO inline colors — every visual state is a class\n * driven by the theme tokens.\n *\n * Accessibility contract (load-bearing, not decorative):\n * - The confidence dot is a color-only signal, so it always carries\n * `role=\"img\"` + a text `aria-label` and a `title` tooltip listing the\n * formatted reasons (WCAG 1.4.1 / 1.4.11).\n * - The dirty state pairs the `--dirty` border color with a visible \"edited\"\n * text badge, linked to the input via `aria-describedby`. When a missed\n * field is filled in, `--missed`'s error border wins the CSS cascade — the\n * badge is then the ONLY visible dirty channel, which is why it is a word\n * and not another color.\n *\n * Editing contract: dirtiness is exactly `edit !== undefined`. The PARENT\n * owns revert detection (it deletes the edits entry when the value returns to\n * the initial string) — nothing here compares against the initial value.\n *\n * Layout contract: FieldInput renders a FRAGMENT (input + \"edited\" badge) and\n * expects a flex-row container — `__dd`, `__cell`, and the simple-list items\n * provide it.\n *\n * Shape sections (Task 13): VerificationForm renders the classifier's buckets\n * in the CONSOLE's section order (FormView/index.tsx): Details (headers +\n * simple lists), entity cards, tables, fallback — then the SDK-only\n * \"Not detected\" section for bindings that matched no rendered field.\n */\nimport React from 'react';\nimport type { FieldBinding } from './bindings';\nimport { toInputString } from './bindings';\nimport type { ClassifiedCell, ClassifiedData, ClassifiedField } from './classify';\nimport { ROW_META_KEY, formatLabel, formatValue } from './classify';\nimport { ISO_4217_CODES, cellSchemaKey, validateInput } from './field-types';\nimport type { RowMutableTable, ValidationFieldDescriptor } from './field-types';\nimport { displayColumns, matchesTablePointer } from './row-cells';\nimport type { PlannedCell, PlannedRow } from './row-cells';\nimport { cellEditKey } from './row-plan';\nimport { NOTHING_HIDDEN, unplannedRowKey } from './review-filter';\nimport type { HiddenSets } from './review-filter';\nimport type { RowPlanEntry } from './row-plan';\nimport { NOT_FOUND, parseSchemaKey, snakeToCamel } from './pointer';\nimport { Tip } from './tip';\nimport { IconEye } from './viewer';\n\n/** Colored dot + native tooltip. Absent (or blank-level) confidence renders nothing. */\nexport function ConfidenceDot(props: {\n confidence: { level: string; reasons: string[] } | null;\n}): React.JSX.Element | null {\n const { confidence } = props;\n if (!confidence?.level) {\n return null;\n }\n\n let variant: 'high' | 'medium' | 'low' | 'unknown';\n let label: string;\n switch (confidence.level.toLowerCase()) {\n case 'high':\n variant = 'high';\n label = 'High confidence';\n break;\n case 'medium':\n variant = 'medium';\n label = 'Medium confidence';\n break;\n case 'low':\n variant = 'low';\n label = 'Low confidence';\n break;\n default:\n variant = 'unknown';\n label = `${confidence.level} confidence`;\n }\n\n const reasons = confidence.reasons.map(formatLabel);\n // The reasons must reach AT (and the keyboard) regardless of the tooltip, so\n // the accessible NAME carries them: \"Low confidence: Blurry Region, Low OCR\n // Quality\". One string, no extra DOM. The tip is the SIGHTED channel for the\n // same facts — hence `aria-describedby` is all Tip adds, and the name is\n // left alone so nothing is announced twice.\n const ariaLabel = reasons.length > 0 ? `${label}: ${reasons.join(', ')}` : label;\n // A heading over a list — the shape `title=` could never express, and the\n // reason this component exists. Matches the console's FieldValue treatment.\n const tip = (\n <>\n <strong className=\"gemina-verification__tip-title\">{label}</strong>\n {reasons.length > 0 ? (\n <ul className=\"gemina-verification__tip-list\">\n {reasons.map((reason) => <li key={reason}>{reason}</li>)}\n </ul>\n ) : null}\n </>\n );\n return (\n <Tip content={tip}>\n <span\n className={`gemina-verification__dot gemina-verification__dot--${variant}`}\n role=\"img\"\n aria-label={ariaLabel}\n />\n </Tip>\n );\n}\n\n/** Eye button that flashes the field's rects on the document. */\nexport function EyeButton(props: {\n coordinates: { points: [number, number][] } | null;\n onFlash: () => void;\n}): React.JSX.Element | null {\n const { coordinates, onFlash } = props;\n if (!coordinates) {\n return null;\n }\n return (\n <Tip content=\"Show on document\">\n <button\n type=\"button\"\n className=\"gemina-verification__eye\"\n aria-label=\"Show on document\"\n onClick={(event) => {\n // Rows use click-to-flash (Task 13); the field eye must not double-fire it.\n event.stopPropagation();\n onFlash();\n }}\n >\n <IconEye />\n </button>\n </Tip>\n );\n}\n\n/** One editable field: input prefilled with the RAW value, dirty + missed states. */\nexport function FieldInput(props: {\n binding: FieldBinding;\n /** Current value if dirty, else undefined (input falls back to initial). */\n edit: string | undefined;\n /** Parent deletes the edits entry when value returns to the initial string. */\n /** `binding` travels with the change so revert detection never has to\n * resolve an edit key back to a field — a cell key could not be. */\n onEdit: (editKey: string, value: string, binding: FieldBinding) => void;\n readOnly: boolean;\n /** formatLabel(label) — the visible label lives in the surrounding layout. */\n ariaLabel: string;\n /**\n * A row-level error decided outside this field (the unit-size pair rule).\n * Wins over per-field validation and applies even when untouched: the field\n * is invalid because of its SIBLING, so dirtiness here is irrelevant.\n */\n pairError?: string;\n /**\n * The key this field's edit is stored under. Defaults to the raw schema key\n * (headers, and tables with no row plan); a row-mutable table passes a\n * `cellEditKey` so the edit follows the ROW rather than the position.\n */\n editKey?: string;\n}): React.JSX.Element {\n const { binding, edit, onEdit, readOnly, ariaLabel, pairError } = props;\n const editKey = props.editKey ?? binding.key.raw;\n const editedBadgeId = React.useId();\n const errorId = React.useId();\n const currencyListId = React.useId();\n\n // Container serverValues (value-object wrappers, arrays, objects) can never\n // score correct from a string edit — the server's coerce_like only adopts\n // types for scalar targets — so they render read-only (C1/C2 amendment).\n // NOTE: this branch deliberately DISCARDS `edit` and shows the extracted\n // value — correct for the 409 already-validated path. Task 17: keep\n // submit-in-progress as disabled buttons, NOT a readOnly flip, or the\n // user's pending edits would visually vanish mid-submit.\n if (readOnly || !binding.editable) {\n const display = binding.extracted === NOT_FOUND ? null : binding.extracted;\n return <span>{formatValue(display, binding.key.label)}</span>;\n }\n\n const dirty = edit !== undefined;\n const missed = binding.serverValue === NOT_FOUND;\n const field = binding.field;\n const value = dirty ? edit : toInputString(binding.extracted);\n\n // Only a value the reviewer TYPED can be invalid. An extracted value that is\n // off-roster is the model's output, not their mistake: it is preserved (see\n // the pinned option below) and must not block a submission they never\n // touched. Task 6.4's gate reads the same rule.\n const error = pairError ?? (dirty ? validateInput(value, field) : null);\n const className = [\n 'gemina-verification__input',\n dirty ? 'gemina-verification__input--dirty' : '',\n missed ? 'gemina-verification__input--missed' : '',\n error ? 'gemina-verification__input--invalid' : '',\n ]\n .filter(Boolean)\n .join(' ');\n\n // Space-separated, never overwritten: the edited badge and the error are\n // both descriptions of the same control and a reviewer needs to hear both.\n const describedBy = [dirty ? editedBadgeId : '', error ? errorId : '']\n .filter(Boolean)\n .join(' ');\n const shared = {\n className,\n 'aria-label': ariaLabel,\n 'aria-describedby': describedBy || undefined,\n 'aria-invalid': error ? (true as const) : undefined,\n onChange: (event: React.ChangeEvent<HTMLInputElement | HTMLSelectElement>) =>\n onEdit(editKey, event.target.value, binding),\n };\n\n // A closed roster is a choice, not a spelling test. The extracted value is\n // PINNED as an option when it is off-roster, so opening the select can never\n // silently destroy what the model found.\n const roster = field?.enum && field.enum.length > 0 ? field.enum : null;\n const offRoster = roster && value !== '' && !roster.includes(value) ? value : null;\n\n const control = roster ? (\n <select {...shared} value={value} dir=\"auto\">\n {/* Clearing stays possible: an empty submission asserts \"not present\". */}\n <option value=\"\">—</option>\n {offRoster ? <option value={offRoster}>{offRoster} (as extracted)</option> : null}\n {roster.map((option) => <option key={option} value={option}>{option}</option>)}\n </select>\n ) : (\n <input\n {...shared}\n // `date` gets the native picker; everything else stays text so the\n // server's own leniency (commas, underscores) is not fought by the\n // browser's number parsing.\n type={field?.type === 'date' ? 'date' : 'text'}\n // Per-input bidi: a Latin value inside an RTL (Hebrew) document — or\n // vice versa — must lay out by its own content, not the widget's dir.\n dir=\"auto\"\n // RAW value only — a display-formatted \"1,500\" round-tripped into the\n // submission would score as a correction (see toInputString).\n value={value}\n // A hint to the soft keyboard, NOT validation — validateInput is that.\n inputMode={field?.type === 'number' || field?.type === 'integer' ? 'decimal' : undefined}\n list={field?.format === 'iso4217' ? currencyListId : undefined}\n placeholder={missed ? 'Not detected — fill in if present' : undefined}\n autoComplete=\"off\"\n />\n );\n\n return (\n <>\n {control}\n {field?.format === 'iso4217' ? (\n <datalist id={currencyListId}>\n {ISO_4217_CODES.map((code) => <option key={code} value={code} />)}\n </datalist>\n ) : null}\n {error ? (\n <span className=\"gemina-verification__field-error\" id={errorId} role=\"alert\">\n {error}\n </span>\n ) : null}\n {dirty ? (\n // The badge is where the ORIGINAL belongs, now that the input holds\n // the edit — otherwise the extracted value is simply gone from the\n // screen the moment someone corrects it.\n //\n // Known limit: the badge is a non-focusable span, so this channel is\n // hover-only. AT is not worse off than before (nothing carried the\n // original previously), and the input's aria-describedby still names\n // the field as edited. Giving it a keyboard path needs a focusable\n // affordance, which belongs with the Phase 8 row work, not here.\n <Tip\n content={\n <>\n <span className=\"gemina-verification__tip-label\">Was: </span>\n {formatValue(binding.extracted === NOT_FOUND ? null : binding.extracted,\n binding.key.label)}\n </>\n }\n >\n <span className=\"gemina-verification__edited\" id={editedBadgeId}>\n edited\n </span>\n </Tip>\n ) : null}\n </>\n );\n}\n\n// --- Shape sections (Task 13) ------------------------------------------------\n\ninterface FlashRect {\n points: [number, number][];\n}\n\n/** State + callbacks every section threads down to its fields.\n *\n * STABILITY CONTRACT (callers, i.e. Task 14): `onEdit`, `onFlash`, and\n * `bindingIndex` MUST be referentially stable across renders (useCallback /\n * useMemo) — the table-row memo compares them by reference, so an unstable\n * handler silently degrades every row bail-out to a full re-render. `edits`\n * MUST be replaced immutably on every change, never mutated in place: the\n * comparator short-circuits on `prevEdits === nextEdits`, so an in-place\n * mutation renders no update at all. */\ninterface SectionShared {\n /** Edit key -> row-level error. Empty for every extraction without the pair. */\n pairErrors: ReadonlyMap<string, string>;\n /** Server-declared row-mutable tables. Empty disables every row control. */\n rowMutableTables: readonly RowMutableTable[];\n /**\n * Table pointer -> its rows, already resolved to cells. Computed ONCE by the\n * parent: computing it here as well would produce a second object per render\n * and defeat the row memo, which compares it by reference.\n */\n plannedTables: ReadonlyMap<string, PlannedRow[]>;\n onAddRow: (tablePointer: string, afterPosition: number) => void;\n onRemoveRow: (tablePointer: string, position: number) => void;\n\n bindingIndex: Map<string, FieldBinding>;\n edits: ReadonlyMap<string, string>;\n /** `binding` travels with the change so revert detection never has to\n * resolve an edit key back to a field — a cell key could not be. */\n onEdit: (editKey: string, value: string, binding: FieldBinding) => void;\n readOnly: boolean;\n onFlash: (rects: FlashRect[]) => void;\n /**\n * Fields and rows the review filter is hiding. `NOTHING_HIDDEN` when off.\n *\n * NOT part of `areRowPropsEqual`, on purpose: it is derived from `edits`, so\n * a new object arrives on every keystroke and comparing it would re-render\n * every row in the table — the same cost `pairErrors` is excluded to avoid.\n * It costs nothing to leave out, because a hidden row is never rendered at\n * all; only the sections need to read it.\n */\n hidden: HiddenSets;\n /**\n * Whether the filter is engaged. Rows DO react to this — they drop their\n * add/remove controls, because \"insert below row 3\" is meaningless when row\n * 4 is hidden — so unlike `hidden` it must be compared. It is a stable\n * boolean, so that is free.\n */\n filterOn: boolean;\n}\n\n/** Props for the whole form pane.\n *\n * The SectionShared stability contract applies (see above), and `classified`\n * must be the memoized product of one `classifyData` call — a fresh object\n * per render defeats both the row memo and the fallback-section memo. */\n/** One shared empty instance: `shared` is compared by reference downstream, so\n * \"no row errors\" must always be the SAME object. */\nconst NO_PAIR_ERRORS: ReadonlyMap<string, string> = new Map();\nconst NO_TABLES: readonly RowMutableTable[] = [];\nconst NO_PLANNED: ReadonlyMap<string, PlannedRow[]> = new Map();\nconst NOOP_ROW = () => {};\n\nexport interface VerificationFormProps\n extends Omit<SectionShared,\n 'pairErrors' | 'rowMutableTables' | 'plannedTables' | 'onAddRow' | 'onRemoveRow' | 'hidden' | 'filterOn'> {\n /** Review filter. Omitted = off, hiding nothing — same contract as the row\n * props above: a host rendering the form directly need not know it exists. */\n hidden?: HiddenSets;\n filterOn?: boolean;\n /**\n * All optional on the public surface. The pair rule and the row plans are\n * internal details of the full component, and a host — or a test — rendering\n * the form directly should not have to know they exist. Omitting them yields\n * exactly the pre-row-editing form: no controls, raw-key edits.\n */\n pairErrors?: ReadonlyMap<string, string>;\n rowMutableTables?: readonly RowMutableTable[];\n plannedTables?: ReadonlyMap<string, PlannedRow[]>;\n onAddRow?: (tablePointer: string, afterPosition: number) => void;\n onRemoveRow?: (tablePointer: string, position: number) => void;\n classified: ClassifiedData;\n /** Bindings whose pointer matched NO rendered field — the \"model missed the\n * whole field\" case; rendered as an extra \"Not detected\" section of empty inputs. */\n unmatched: FieldBinding[];\n}\n\n/** True when the click started on an interactive element — row click-to-flash\n * must never hijack typing, button presses, or link follows. */\nfunction isInteractiveTarget(target: EventTarget | null): boolean {\n return target instanceof Element && target.closest('input, button, a, select, textarea') !== null;\n}\n\n/**\n * A field label, with the model's description as a tooltip when there is one.\n *\n * Plain text when there is not: an empty tooltip trigger is worse than none,\n * because it promises information it does not have.\n */\nfunction FieldLabel(props: { label: string; description?: string | null }): React.JSX.Element {\n const { label, description } = props;\n if (!description) {\n return <span>{label}</span>;\n }\n return (\n <Tip content={description}>\n <span className=\"gemina-verification__label-described\" tabIndex={0}>{label}</span>\n </Tip>\n );\n}\n\n/** One label/value pair inside a description list (headers + entity cards). */\nfunction FieldPair(props: {\n label: string;\n ariaLabel: string;\n cell: ClassifiedCell | ClassifiedField;\n shared: SectionShared;\n}): React.JSX.Element {\n const { label, ariaLabel, cell, shared } = props;\n const binding = shared.bindingIndex.get(cell.pointer);\n return (\n <>\n <dt className=\"gemina-verification__dt\">\n <ConfidenceDot confidence={cell.confidence} />\n {/* The model's own field description, which the backend publishes per\n field. Without this it is carried all the way to the client and\n then dropped — and it is the only place a reviewer can learn what\n a field like \"assignment number\" is actually supposed to contain. */}\n <FieldLabel label={label} description={binding?.field?.description} />\n </dt>\n <dd className=\"gemina-verification__dd\">\n {binding !== undefined ? (\n <FieldInput\n binding={binding}\n pairError={shared.pairErrors.get(binding.key.raw)}\n edit={shared.edits.get(binding.key.raw)}\n onEdit={shared.onEdit}\n readOnly={shared.readOnly}\n ariaLabel={ariaLabel}\n />\n ) : (\n <span>{formatValue(cell.value, label)}</span>\n )}\n <EyeButton\n coordinates={cell.coordinates}\n onFlash={() => {\n if (cell.coordinates) {\n shared.onFlash([cell.coordinates]);\n }\n }}\n />\n </dd>\n </>\n );\n}\n\n/** \"Details\": header fields + simple lists in one description-list section. */\nfunction HeaderSection(props: {\n headers: ClassifiedField[];\n simpleLists: ClassifiedData['simpleLists'];\n shared: SectionShared;\n}): React.JSX.Element | null {\n const { headers, simpleLists, shared } = props;\n // The review filter hides what already scored high. Applied here rather than\n // at the call site so simple lists get the same treatment as headers.\n const visibleHeaders = headers.filter((field) => !shared.hidden.fields.has(field.pointer));\n const visibleLists = simpleLists\n .map((list) => ({ ...list, items: list.items.filter((item) => !shared.hidden.fields.has(item.pointer)) }))\n .filter((list) => list.items.length > 0);\n if (visibleHeaders.length === 0 && visibleLists.length === 0) {\n return null;\n }\n return (\n <section className=\"gemina-verification__section\" aria-label=\"Details\">\n <div className=\"gemina-verification__section-header\">Details</div>\n <dl className=\"gemina-verification__dl\">\n {visibleHeaders.map((field) => (\n <FieldPair\n key={field.pointer}\n label={formatLabel(field.key)}\n ariaLabel={formatLabel(field.key)}\n cell={field}\n shared={shared}\n />\n ))}\n {visibleLists.map((list) => (\n <React.Fragment key={list.pointer}>\n <dt className=\"gemina-verification__dt\">\n <span>{formatLabel(list.key)}</span>\n </dt>\n <dd className=\"gemina-verification__dd\">\n <ul className=\"gemina-verification__list\">\n {list.items.map((item, index) => {\n const binding = shared.bindingIndex.get(item.pointer);\n return (\n <li key={item.pointer} className=\"gemina-verification__cell\">\n {binding !== undefined ? (\n <FieldInput\n binding={binding}\n pairError={shared.pairErrors.get(binding.key.raw)}\n edit={shared.edits.get(binding.key.raw)}\n onEdit={shared.onEdit}\n readOnly={shared.readOnly}\n ariaLabel={`${formatLabel(list.key)} item ${index + 1}`}\n />\n ) : (\n <span>{formatValue(item.value)}</span>\n )}\n <ConfidenceDot confidence={item.confidence} />\n <EyeButton\n coordinates={item.coordinates}\n onFlash={() => {\n if (item.coordinates) {\n shared.onFlash([item.coordinates]);\n }\n }}\n />\n </li>\n );\n })}\n </ul>\n </dd>\n </React.Fragment>\n ))}\n </dl>\n </section>\n );\n}\n\n/** Entity bucket: one card per item, headers singularized console-style. */\nfunction EntitySection(props: {\n entity: ClassifiedData['entities'][number];\n shared: SectionShared;\n}): React.JSX.Element {\n const { entity, shared } = props;\n // Drop a card only when ALL of its cells are hidden — a card with one\n // remaining medium-confidence field is still worth reviewing.\n // The ORIGINAL index travels with each surviving card. Renumbering after a\n // filter would relabel \"Supplier 2\" as \"Supplier 1\" — in the visible header\n // AND in the aria-label, telling a screen-reader user they are editing a\n // different entity than they are. Same reason the table keeps plan positions.\n const visibleItems = entity.items\n .map((item, index) => ({\n index,\n cells: Object.fromEntries(\n Object.entries(item).filter(([, cellValue]) => !shared.hidden.fields.has(cellValue.pointer)),\n ),\n }))\n .filter(({ cells }) => Object.keys(cells).length > 0);\n const label = formatLabel(entity.key);\n // The console's naive strip-trailing-s, ported verbatim (\"Suppliers\" →\n // \"Supplier\"; yes, \"Parties\" → \"Partie\" — console parity over grammar).\n const singular = label.replace(/s$/, '');\n return (\n <section className=\"gemina-verification__section\" aria-label={label}>\n <div className=\"gemina-verification__section-header\">\n {/* The true count, not the filtered one: the heading says how many\n entities the document has, and the filter never changes that. */}\n {label} ({entity.items.length})\n </div>\n <div className=\"gemina-verification__section-body\">\n {visibleItems.map(({ index, cells }) => (\n // Keyed by the original index, never the filtered position, or React\n // reuses a hidden card's DOM (and its focus) for its successor.\n <div key={index} className=\"gemina-verification__card\">\n <div className=\"gemina-verification__card-header\">\n {singular} {index + 1}\n </div>\n <dl className=\"gemina-verification__dl\">\n {Object.entries(cells).map(([fieldKey, cell]) => (\n <FieldPair\n key={fieldKey}\n label={formatLabel(fieldKey)}\n // Card context: two \"Supplier\" cards both announcing a bare\n // \"Name\" would be ambiguous to a screen reader.\n ariaLabel={`${singular} ${index + 1} — ${formatLabel(fieldKey)}`}\n cell={cell}\n shared={shared}\n />\n ))}\n </dl>\n </div>\n ))}\n </div>\n </section>\n );\n}\n\ninterface TableRowViewProps {\n /** The classified row behind this render — undefined for a row the reviewer added. */\n row: Record<string, ClassifiedCell> | undefined;\n /** Position in the SUBMITTED table: what the reviewer sees, and what labels count. */\n rowIndex: number;\n columns: string[];\n /** formatLabel(tableKey), precomputed once per table. */\n tableLabel: string;\n hasCoords: boolean;\n hasRowConfidence: boolean;\n shared: SectionShared;\n /** Resolved cells + row identity. Present ONLY for a row-mutable table. */\n planned?: PlannedRow;\n /** The server's pointer for this table — the key the row handlers take. */\n tablePointer?: string;\n}\n\nfunction TableRowView(props: TableRowViewProps): React.JSX.Element {\n const { row, rowIndex, columns, tableLabel, hasCoords, hasRowConfidence, shared, planned, tablePointer } = props;\n const { bindingIndex, edits, onEdit, readOnly, onFlash } = shared;\n\n const rects = React.useMemo(() => {\n const collected: FlashRect[] = [];\n for (const [key, cell] of Object.entries(row ?? {})) {\n if (key !== ROW_META_KEY && cell.coordinates) {\n collected.push(cell.coordinates);\n }\n }\n return collected;\n }, [row]);\n\n const handleRowClick = React.useCallback(\n (event: React.MouseEvent<HTMLTableRowElement>) => {\n if (isInteractiveTarget(event.target)) {\n return;\n }\n if (rects.length > 0) {\n onFlash(rects);\n }\n },\n [rects, onFlash],\n );\n\n /** Cells by column: from the plan when there is one, else today's lookup. */\n const cellFor = (column: string) => {\n // Server-declared table columns use model names (snake_case), but response\n // DTOs expose the same keys in camelCase. Prefer an exact key (important\n // for dynamic templates that genuinely use either spelling), then match\n // through the one shared casing rule.\n const direct = row?.[column];\n const alias = direct === undefined ? row?.[snakeToCamel(column)] : undefined;\n const fallbackKey = direct === undefined && alias === undefined && row !== undefined\n ? Object.keys(row).find((key) => snakeToCamel(key) === snakeToCamel(column))\n : undefined;\n const classified = direct ?? alias ?? (fallbackKey === undefined ? undefined : row?.[fallbackKey]);\n const fromPlan = planned?.cells.find((cell: PlannedCell) => cell.column === column);\n if (fromPlan) {\n return { classified, binding: fromPlan.binding, editKey: fromPlan.editKey };\n }\n const binding = classified === undefined ? undefined : bindingIndex.get(classified.pointer);\n return { classified, binding, editKey: binding?.key.raw };\n };\n\n const firstRect = rects.length > 0 ? rects[0]! : null;\n // Row controls are OMITTED while filtering, not disabled: \"insert below\n // row 3\" is meaningless when row 4 is hidden, and a disabled button\n // cannot carry its own explanation — Tip attaches hover/focus handlers to\n // its child, and a disabled button dispatches neither.\n const showControls = planned !== undefined && tablePointer !== undefined && !readOnly\n && !shared.filterOn;\n // A REDUNDANT channel: the confidence dot and its tooltip already carry the\n // meaning, so this marker does not have to pass contrast on its own — it is\n // there so a reviewer can find the rows worth checking by scanning the edge\n // of a 150-line table instead of reading every dot.\n const rowLevel = (row?.[ROW_META_KEY]?.confidence?.level ?? '').toLowerCase();\n const rowClass = rowLevel === 'low' || rowLevel === 'medium'\n ? `gemina-verification__row--${rowLevel}`\n : undefined;\n return (\n <tr onClick={handleRowClick} className={rowClass}>\n {hasCoords ? (\n <td>\n {/* EyeButton's coordinates prop is only the render gate here — the\n click flashes ALL the row's rects, console DataTable style. */}\n <EyeButton coordinates={firstRect} onFlash={() => onFlash(rects)} />\n </td>\n ) : null}\n {hasRowConfidence ? (\n <td>\n <ConfidenceDot confidence={row?.[ROW_META_KEY]?.confidence ?? null} />\n </td>\n ) : null}\n {columns.map((column) => {\n const { classified, binding, editKey } = cellFor(column);\n return (\n <td key={column}>\n <div className=\"gemina-verification__cell\">\n {binding !== undefined ? (\n <FieldInput\n binding={binding}\n editKey={editKey}\n pairError={editKey === undefined ? undefined : shared.pairErrors.get(editKey)}\n edit={editKey === undefined ? undefined : edits.get(editKey)}\n onEdit={onEdit}\n readOnly={readOnly}\n ariaLabel={`${tableLabel} row ${rowIndex + 1} — ${formatLabel(column)}`}\n />\n ) : (\n <span>{classified === undefined ? '-' : formatValue(classified.value, column)}</span>\n )}\n <ConfidenceDot confidence={classified?.confidence ?? null} />\n </div>\n </td>\n );\n })}\n {showControls ? (\n <td className=\"gemina-verification__row-actions\">\n {/* Row-numbered labels: \"Remove line\" repeated N times is unusable\n with a screen reader, and the number is what the reviewer sees. */}\n <Tip content=\"Insert a line below\">\n <button\n type=\"button\"\n className=\"gemina-verification__row-btn\"\n aria-label={`Insert line below line ${rowIndex + 1}`}\n onClick={() => shared.onAddRow(tablePointer!, rowIndex)}\n >\n +\n </button>\n </Tip>\n <Tip content=\"Remove this line\">\n <button\n type=\"button\"\n className=\"gemina-verification__row-btn\"\n aria-label={`Remove line ${rowIndex + 1}`}\n onClick={() => shared.onRemoveRow(tablePointer!, rowIndex)}\n >\n ×\n </button>\n </Tip>\n </td>\n ) : null}\n </tr>\n );\n}\n\n/** Bail out unless THIS row's data or its slice of the edits changed. The\n * comparator inspects only edits for this row's cells, so one keystroke\n * re-renders one row. Callbacks are compared by reference: the parent must\n * pass referentially stable `onEdit`/`onFlash` (and a stable\n * `classified`/`bindingIndex`) or the memoization degrades to plain renders. */\nfunction areRowPropsEqual(prev: TableRowViewProps, next: TableRowViewProps): boolean {\n if (\n prev.row !== next.row\n || prev.rowIndex !== next.rowIndex\n || prev.columns !== next.columns\n || prev.tableLabel !== next.tableLabel\n || prev.hasCoords !== next.hasCoords\n || prev.hasRowConfidence !== next.hasRowConfidence\n || prev.planned !== next.planned\n || prev.tablePointer !== next.tablePointer\n || prev.shared.bindingIndex !== next.shared.bindingIndex\n || prev.shared.onEdit !== next.shared.onEdit\n || prev.shared.onFlash !== next.shared.onFlash\n || prev.shared.readOnly !== next.shared.readOnly\n // Stable boolean, and rows must react to it (controls disappear).\n // `shared.hidden` is deliberately absent — see SectionShared.\n || prev.shared.filterOn !== next.shared.filterOn\n ) {\n // NOT compared by reference: `pairErrors` is derived from `edits`, so a new\n // Map arrives on EVERY keystroke and a blanket check would re-render every\n // row in the table. Its per-cell values are checked below instead.\n return false;\n }\n if (prev.shared.edits === next.shared.edits) {\n return true;\n }\n // Compare by EDIT key, which under a row plan is the cell key rather than\n // the raw schema key — comparing raw keys would leave a row stale after an\n // edit to a row that moved.\n for (const column of next.columns) {\n const planned = next.planned?.cells.find((cell: PlannedCell) => cell.column === column);\n const classified = next.row?.[column];\n const editKey = planned?.editKey\n ?? (classified === undefined ? undefined : next.shared.bindingIndex.get(classified.pointer)?.key.raw);\n if (editKey === undefined) {\n continue;\n }\n if (prev.shared.edits.get(editKey) !== next.shared.edits.get(editKey)\n || prev.shared.pairErrors.get(editKey) !== next.shared.pairErrors.get(editKey)) {\n return false;\n }\n }\n return true;\n}\n\nconst TableRow = React.memo(TableRowView, areRowPropsEqual);\n\n\n/**\n * Promote a row-mutable table the classifier could not see as one.\n *\n * An EMPTY array classifies as a header, not a table (classify.ts) — so an\n * extraction that found no line items has no table, no columns and nowhere to\n * put \"Add line\". That is the case this feature exists for: the model found\n * nothing and the reviewer types it in.\n *\n * Done as a post-classification promotion driven by the SERVER's contract\n * rather than by changing the classifier, whose heuristics are shared with the\n * console and proven. The header the empty array produced is suppressed, or it\n * would render twice — once as \"Line Items: []\" and once as the table.\n */\nexport function withEmptyMutableTables(\n classified: ClassifiedData,\n tables: readonly RowMutableTable[],\n): { tables: ClassifiedData['tables']; suppressed: ReadonlySet<string> } {\n if (tables.length === 0) {\n return { tables: classified.tables, suppressed: EMPTY_SUPPRESSED };\n }\n const promoted = [...classified.tables];\n const suppressed = new Set<string>();\n for (const table of tables) {\n if (classified.tables.some((candidate) => matchesTablePointer(table.pointer, candidate.pointer))) {\n continue;\n }\n const header = classified.headers.find(\n (candidate) => matchesTablePointer(table.pointer, candidate.pointer),\n );\n // The classifier normalises an empty array to `value: null`, so BOTH\n // spellings mean \"no rows\". Nothing else is promoted: a pointer that\n // resolved to real data is a contract mismatch, and inventing a table for\n // it would put row controls over data the scorer cannot align. The\n // server's own declaration is what makes this safe — the reviewer can only\n // ever add rows to a table the scorer knows how to align.\n const empty = header !== undefined\n && (header.value === null || (Array.isArray(header.value) && header.value.length === 0));\n if (!empty) {\n continue;\n }\n suppressed.add(header!.pointer);\n promoted.push({\n key: header!.key,\n pointer: header!.pointer,\n columns: [],\n rows: [],\n overallConfidence: null,\n });\n }\n return { tables: promoted, suppressed };\n}\n\nconst EMPTY_SUPPRESSED: ReadonlySet<string> = new Set();\n\n/** Table bucket: the console DataTable's column model without antd. */\nfunction TableSection(props: {\n table: ClassifiedData['tables'][number];\n shared: SectionShared;\n}): React.JSX.Element {\n const { table, shared } = props;\n const label = formatLabel(table.key);\n\n // Row editing is offered ONLY where the server declared it. Any wide array\n // of objects looks like a table to the classifier — custom_template's do —\n // and controls on one the scorer cannot align would mis-score permanently.\n const mutable = React.useMemo(\n () => shared.rowMutableTables.find((entry) => matchesTablePointer(entry.pointer, table.pointer)),\n [shared.rowMutableTables, table.pointer],\n );\n const columns = React.useMemo(\n () => (mutable ? displayColumns(mutable, table.columns) : table.columns),\n [mutable, table.columns],\n );\n const planned = mutable ? shared.plannedTables.get(mutable.pointer) : undefined;\n\n // Full-row scans — memoized so keystroke re-renders don't re-walk every cell.\n const hasCoords = React.useMemo(\n () =>\n table.rows.some((row) =>\n Object.entries(row).some(([key, cell]) => key !== ROW_META_KEY && cell.coordinates !== null),\n ),\n [table],\n );\n const hasRowConfidence = React.useMemo(\n () => table.rows.some((row) => Boolean(row[ROW_META_KEY]?.confidence?.level)),\n [table],\n );\n // Column descriptions come from the server's declared columns, so they are\n // present even for a zero-row table — the case where a reviewer typing a\n // line in most needs to know what each column means.\n const columnDescriptions = React.useMemo(() => {\n const map = new Map<string, string>();\n for (const column of mutable?.columns ?? []) {\n if (typeof column.key === 'string' && column.description) {\n map.set(column.key, column.description);\n }\n }\n return map;\n }, [mutable]);\n const rowCount = planned ? planned.length : table.rows.length;\n // `ConfidenceModel` is a closed high|medium|low, so the scale is total: a row\n // with no confidence at all is not \"needing review\", it is unmeasured.\n const needsReview = React.useMemo(\n () => table.rows.filter((row) => {\n const level = (row[ROW_META_KEY]?.confidence?.level ?? '').toLowerCase();\n return level === 'low' || level === 'medium';\n }).length,\n [table.rows],\n );\n const showControls = planned !== undefined && mutable !== undefined && !shared.readOnly\n && !shared.filterOn;\n\n // The review filter, applied to whichever collection actually renders. A\n // planned row is addressed by `entry.id` — already table-scoped by\n // initialRowPlan — and an unplanned one by its row pointer, which is exactly\n // what CellView.rowKey uses in each case.\n // `position` is the row's index in the UNFILTERED plan and travels with it:\n // onAddRow/onRemoveRow take a plan position, so renumbering after a filter\n // would target the wrong row. (Controls are hidden while filtering anyway —\n // this keeps the two facts independent rather than relying on that.)\n const visiblePlanned = planned\n ?.map((plannedRow, position) => ({ plannedRow, position }))\n .filter(({ plannedRow }) => !shared.hidden.rows.has(plannedRow.entry.id));\n // Empty rather than null when a plan exists: the two are mutually exclusive\n // by construction, and an always-array keeps the render below free of\n // non-null assertions that only restate that fact.\n const visibleRowIndices = planned\n ? []\n : table.rows.map((_row, index) => index)\n .filter((index) => !shared.hidden.rows.has(unplannedRowKey(table.pointer, index)));\n const visibleCount = visiblePlanned ? visiblePlanned.length : visibleRowIndices.length;\n // Never an empty <tbody>: say why the rows are gone, or a filtered table\n // reads as a table that lost its data.\n const allHidden = visibleCount === 0 && rowCount > 0;\n\n return (\n <section className=\"gemina-verification__section\" aria-label={label}>\n <div className=\"gemina-verification__section-header\">\n <span>\n {label} ({rowCount} rows{needsReview > 0 ? ` · ${needsReview} need review` : ''})\n </span>\n {/* Row controls vanish while filtering (insert-below is meaningless\n when the neighbour is hidden). Their absence has to be explained\n where it is noticed, and it cannot be explained on the controls\n themselves — a disabled button carries no reachable tooltip. */}\n {shared.filterOn && mutable !== undefined && !shared.readOnly ? (\n <span className=\"gemina-verification__filter-note\">Row editing is off while filtering</span>\n ) : null}\n {table.overallConfidence ? (\n <span className=\"gemina-verification__overall-confidence\">\n <span>Overall confidence</span>\n <ConfidenceDot confidence={table.overallConfidence} />\n </span>\n ) : null}\n </div>\n {allHidden ? (\n <p className=\"gemina-verification__all-scored\">All {rowCount} rows scored high</p>\n ) : (\n <div className=\"gemina-verification__table-wrap\">\n <table className=\"gemina-verification__table\">\n <thead>\n <tr>\n {hasCoords ? <th aria-label=\"Show row on document\" /> : null}\n {hasRowConfidence ? <th aria-label=\"Row confidence\" /> : null}\n {columns.map((column) => (\n <th key={column}>\n <FieldLabel\n label={formatLabel(column)}\n description={columnDescriptions.get(column)}\n />\n </th>\n ))}\n {showControls ? <th aria-label=\"Row actions\" /> : null}\n </tr>\n </thead>\n <tbody>\n {visiblePlanned\n ? visiblePlanned.map(({ plannedRow, position }) => (\n <TableRow\n // Keyed by ROW ID, not position: a position key would make\n // React reuse a deleted row's DOM (and its focus) for its\n // successor.\n key={plannedRow.entry.id}\n row={plannedRow.entry.source === null ? undefined : table.rows[plannedRow.entry.source]}\n rowIndex={position}\n columns={columns}\n tableLabel={label}\n hasCoords={hasCoords}\n hasRowConfidence={hasRowConfidence}\n shared={shared}\n planned={plannedRow}\n tablePointer={mutable!.pointer}\n />\n ))\n : visibleRowIndices.map((rowIndex) => (\n <TableRow\n key={rowIndex}\n row={table.rows[rowIndex]}\n rowIndex={rowIndex}\n columns={columns}\n tableLabel={label}\n hasCoords={hasCoords}\n hasRowConfidence={hasRowConfidence}\n shared={shared}\n />\n ))}\n </tbody>\n </table>\n </div>\n )}\n {showControls ? (\n <div className=\"gemina-verification__table-footer\">\n <button\n type=\"button\"\n className=\"gemina-verification__add-row\"\n onClick={() => shared.onAddRow(mutable!.pointer, rowCount - 1)}\n >\n Add line\n </button>\n </div>\n ) : null}\n </section>\n );\n}\n\n/** Unclassifiable blobs: native <details> + pretty-printed JSON (no viewer dep).\n * Memoized: fallback is exactly where large unclassifiable payloads land, and\n * without the memo every parent render (i.e., every keystroke) would re-run\n * JSON.stringify over all of them. `classified.fallback` is referentially\n * stable (the parent memoizes classifyData), so the memo is a complete fix. */\nconst FallbackSection = React.memo(function FallbackSection(\n props: { fallback: ClassifiedData['fallback'] },\n): React.JSX.Element | null {\n const { fallback } = props;\n if (fallback.length === 0) {\n return null;\n }\n return (\n <section className=\"gemina-verification__section\" aria-label=\"Additional Data\">\n <div className=\"gemina-verification__section-header\">Additional Data</div>\n <div className=\"gemina-verification__section-body\">\n {fallback.map((item) => (\n <details key={item.key} className=\"gemina-verification__fallback\">\n <summary>{formatLabel(item.key)}</summary>\n <pre>{JSON.stringify(item.data, null, 2)}</pre>\n </details>\n ))}\n </div>\n </section>\n );\n});\n\n/** Bindings the model missed entirely: a section of empty fill-in inputs. */\nfunction UnmatchedSection(props: {\n unmatched: FieldBinding[];\n shared: SectionShared;\n}): React.JSX.Element | null {\n const { unmatched, shared } = props;\n if (unmatched.length === 0) {\n return null;\n }\n return (\n <section className=\"gemina-verification__section\" aria-label=\"Not detected\">\n <div className=\"gemina-verification__section-header\">Not detected</div>\n <dl className=\"gemina-verification__dl\">\n {unmatched.map((binding) => (\n <React.Fragment key={binding.key.raw}>\n {/* Schema labels are already human text — formatLabel is for raw\n payload keys only (it would mangle \"PO Number\" → \"Po Number\"). */}\n <dt className=\"gemina-verification__dt\">\n <span>{binding.key.label}</span>\n </dt>\n <dd className=\"gemina-verification__dd\">\n <FieldInput\n binding={binding}\n pairError={shared.pairErrors.get(binding.key.raw)}\n edit={shared.edits.get(binding.key.raw)}\n onEdit={shared.onEdit}\n readOnly={shared.readOnly}\n ariaLabel={binding.key.label}\n />\n </dd>\n </React.Fragment>\n ))}\n </dl>\n </section>\n );\n}\n\n/** The whole form pane: every classified bucket in console order, then the\n * unmatched \"Not detected\" section. Empty buckets render nothing. */\nexport function VerificationForm(props: VerificationFormProps): React.JSX.Element {\n const {\n classified, unmatched, bindingIndex, edits, onEdit, readOnly, onFlash,\n pairErrors, rowMutableTables, plannedTables, onAddRow, onRemoveRow,\n hidden, filterOn,\n } = props;\n const { tables: promotedTables, suppressed } = React.useMemo(\n () => withEmptyMutableTables(classified, rowMutableTables ?? NO_TABLES),\n [classified, rowMutableTables],\n );\n const shared: SectionShared = {\n bindingIndex, edits, onEdit, readOnly, onFlash,\n pairErrors: pairErrors ?? NO_PAIR_ERRORS,\n rowMutableTables: rowMutableTables ?? NO_TABLES,\n plannedTables: plannedTables ?? NO_PLANNED,\n onAddRow: onAddRow ?? NOOP_ROW,\n onRemoveRow: onRemoveRow ?? NOOP_ROW,\n hidden: hidden ?? NOTHING_HIDDEN,\n filterOn: filterOn ?? false,\n };\n return (\n // A real, labeled <form> (role \"form\" landmark): AT users can jump\n // straight to the editable fields. Submission is owned by the root's\n // footer button, never by the form element itself — preventDefault stops\n // implicit submission (Enter in a payload with exactly one input would\n // otherwise navigate).\n <form\n className=\"gemina-verification__form\"\n aria-label=\"Extraction fields\"\n onSubmit={(event) => event.preventDefault()}\n >\n {classified.overallConfidence ? (\n <div className=\"gemina-verification__confidence-summary\">\n <span>Overall confidence</span>\n <ConfidenceDot confidence={classified.overallConfidence} />\n </div>\n ) : null}\n <HeaderSection\n headers={classified.headers.filter((header) => !suppressed.has(header.pointer))}\n simpleLists={classified.simpleLists}\n shared={shared}\n />\n {classified.entities.map((entity) => (\n <EntitySection key={entity.pointer} entity={entity} shared={shared} />\n ))}\n {promotedTables.map((table) => (\n <TableSection key={table.pointer} table={table} shared={shared} />\n ))}\n <FallbackSection fallback={classified.fallback} />\n <UnmatchedSection unmatched={unmatched} shared={shared} />\n </form>\n );\n}\n","/**\n * The review filter: which fields and rows the reviewer can hide because the\n * model already scored them `high`.\n *\n * Kept separate from the form so the rule is testable without rendering, and\n * so there is exactly ONE definition of \"already reviewed\" rather than one per\n * section component.\n *\n * Three design constraints run through this file, all learned the hard way:\n *\n * 1. Identity comes from `CellView`/`PlannedRow`, never from a pointer built\n * by hand. Under row editing a cell's edit key, its submitted key and its\n * extracted binding genuinely differ (see row-cells.ts), and reconstructing\n * any of them from a JSON pointer is exactly what row planning exists to\n * prevent. Get it wrong and an edited row is hidden anyway.\n *\n * 2. Unmeasured is not reviewed. A field with no confidence at all has not\n * been checked by anything; hiding it would drop it from review silently.\n * Only an explicit `high` hides.\n *\n * 3. Counting and hiding must walk the SAME units. When they disagree, the\n * footer's \"Showing X of Y\" contradicts the screen — which reads to a\n * reviewer as data having gone missing. That is why every consumer here\n * shares the two traversals below instead of re-deriving the buckets.\n */\n\nimport { ROW_META_KEY } from './classify';\nimport type { ClassifiedData } from './classify';\nimport type { FieldBinding } from './bindings';\nimport { matchesTablePointer } from './row-cells';\nimport type { CellView, PlannedRow } from './row-cells';\n\nexport type ConfidenceLike = { level: string; reasons: string[] } | null | undefined;\n\n/** Only an explicit `high` hides. */\nexport function isHighConfidence(confidence: ConfidenceLike): boolean {\n return (confidence?.level ?? '').toLowerCase() === 'high';\n}\n\nexport interface HiddenSets {\n /** Field pointers (headers, list items, entity cells). */\n fields: ReadonlySet<string>;\n /** Row keys, in the same spelling `CellView.rowKey` uses. */\n rows: ReadonlySet<string>;\n}\n\n/** Shared empty result, so \"nothing hidden\" is always the same object and the\n * section memos see no change. The readonly TYPE is the guarantee — a Set\n * stays mutable at runtime even under Object.freeze — so nothing may write to\n * these. */\nexport const NOTHING_HIDDEN: HiddenSets = {\n fields: new Set<string>(),\n rows: new Set<string>(),\n};\n\n/**\n * How a row of an UNPLANNED table is addressed: its row pointer, which is what\n * `collectCellViews` derives by splitting the cell pointer.\n *\n * A planned row is addressed by `entry.id` instead, and that id is ALREADY\n * scoped with the table pointer by `initialRowPlan` (`/taxes#row-0`) — so it\n * is used verbatim. Prefixing it again would produce `/taxes#/taxes#row-0` and\n * match nothing, hiding silently.\n */\nexport const unplannedRowKey = (tablePointer: string, index: number): string => `${tablePointer}/${index}`;\n\n/** The tables the FORM renders — `withEmptyMutableTables`' output, not\n * `classified.tables`. They differ: an empty server-declared row-mutable\n * table is promoted into the rendered list without existing in the\n * classifier's output, and rows the reviewer adds to one would otherwise\n * render uncounted. */\ntype RenderedTables = ClassifiedData['tables'];\n\n/**\n * Every non-table review unit, once: header fields, simple-list items and\n * entity-card cells.\n *\n * One traversal shared by the hide rule, the counter and the\n * \"is there anything to filter\" check — when those three disagreed about which\n * buckets exist, the counter contradicted the screen.\n */\nfunction forEachFieldUnit(\n classified: ClassifiedData,\n visit: (pointer: string, confidence: ConfidenceLike) => void,\n): void {\n for (const header of classified.headers) visit(header.pointer, header.confidence);\n for (const list of classified.simpleLists) {\n for (const item of list.items) visit(item.pointer, item.confidence);\n }\n for (const entity of classified.entities) {\n for (const item of entity.items) {\n for (const cell of Object.values(item)) visit(cell.pointer, cell.confidence);\n }\n }\n}\n\n/**\n * Every table ROW the form renders, once, with the key it is addressed by.\n *\n * A row counts and hides as a whole, never per cell. The plan wins where there\n * is one: it carries the rows the reviewer added and drops the ones they\n * removed, so it — not the extracted array — is what is on screen.\n */\nfunction forEachRowUnit(\n tables: RenderedTables,\n plannedTables: ReadonlyMap<string, PlannedRow[]>,\n visit: (rowKey: string, confidence: ConfidenceLike, added: boolean) => void,\n): void {\n const confidenceOf = (row: unknown): ConfidenceLike => {\n const meta = (row as Record<string, unknown> | undefined)?.[ROW_META_KEY] as\n { confidence?: ConfidenceLike } | undefined;\n return meta?.confidence ?? null;\n };\n\n // `plannedTables` is keyed by the SERVER-declared pointer, which need not\n // match the payload's spelling — a server `/line_items` can classify as\n // `/lineItems`. TableSection resolves this with matchesTablePointer before\n // looking the plan up (form.tsx), and so must this: an exact lookup silently\n // falls through to the unplanned branch, generating `/lineItems/0` keys\n // while the rendered rows are keyed `/line_items#row-0`. Nothing would ever\n // hide, and no error would be raised.\n const planFor = (tablePointer: string): PlannedRow[] | undefined => {\n const exact = plannedTables.get(tablePointer);\n if (exact !== undefined) return exact;\n for (const [serverPointer, planned] of plannedTables) {\n if (matchesTablePointer(serverPointer, tablePointer)) return planned;\n }\n return undefined;\n };\n\n for (const table of tables) {\n const planned = planFor(table.pointer);\n if (planned) {\n for (const row of planned) {\n // An added row was never extracted, so it has no confidence and is not\n // in `table.rows` at all — it can only be reached through the plan.\n // Narrowed via a local so the extracted branch needs no assertion.\n const { source } = row.entry;\n visit(row.entry.id, source === null ? null : confidenceOf(table.rows[source]), source === null);\n }\n continue;\n }\n table.rows.forEach((row, index) => {\n visit(unplannedRowKey(table.pointer, index), confidenceOf(row), false);\n });\n }\n}\n\ninterface HiddenInput {\n classified: ClassifiedData;\n /** What the form renders — see RenderedTables. */\n tables: RenderedTables;\n /** Table pointer -> planned rows. Absent entry = unplanned table. */\n plannedTables: ReadonlyMap<string, PlannedRow[]>;\n /** Authoritative cell identities (editKey + rowKey). */\n cellViews: readonly CellView[];\n /** Pointer-keyed — `indexBindingsByFieldPointer`. */\n bindingIndex: ReadonlyMap<string, FieldBinding>;\n edits: ReadonlyMap<string, string>;\n pairErrors: ReadonlyMap<string, string>;\n /** Promoted-header pointers the form does not render. Skipped, because they\n * are excluded from the unit count too — hiding one would make\n * `visible = total − hidden` miscount. */\n suppressed: ReadonlySet<string>;\n}\n\n/** Fields and rows the filter may hide: high-confidence AND untouched AND\n * error-free. */\nexport function computeHidden(input: HiddenInput): HiddenSets {\n const {\n classified, tables, plannedTables, cellViews, bindingIndex, edits, pairErrors, suppressed,\n } = input;\n\n const fields = new Set<string>();\n const rows = new Set<string>();\n\n // \"Touched\" is edits OR pairErrors: a pair error arrives with ZERO edits when\n // the extraction itself is half-filled, so edits alone would hide a field\n // that is already invalid.\n const touched = (editKey: string): boolean => edits.has(editKey) || pairErrors.has(editKey);\n\n // rowKey -> its cells' edit keys. One pass; the row walk below only looks up.\n const editKeysByRow = new Map<string, string[]>();\n for (const view of cellViews) {\n const list = editKeysByRow.get(view.rowKey);\n if (list) list.push(view.editKey);\n else editKeysByRow.set(view.rowKey, [view.editKey]);\n }\n\n forEachFieldUnit(classified, (pointer, confidence) => {\n if (suppressed.has(pointer) || !isHighConfidence(confidence)) return;\n // With no binding, nothing can resolve this field's edit key, so whether it\n // was touched is unknowable. Never hide what cannot be reasoned about.\n const editKey = bindingIndex.get(pointer)?.key.raw;\n if (editKey === undefined || touched(editKey)) return;\n fields.add(pointer);\n });\n\n forEachRowUnit(tables, plannedTables, (rowKey, confidence, added) => {\n if (added || !isHighConfidence(confidence)) return;\n if ((editKeysByRow.get(rowKey) ?? []).some(touched)) return;\n rows.add(rowKey);\n });\n\n if (fields.size === 0 && rows.size === 0) return NOTHING_HIDDEN;\n return { fields, rows };\n}\n\n/**\n * How many things the reviewer can act on — the denominator of \"Showing X of Y\".\n *\n * Walks the same two traversals `computeHidden` does, so the two cannot drift.\n * Suppressed (promoted) headers are excluded from both.\n *\n * Note this does NOT include `unmatched` bindings: they are review units too,\n * but they live outside `ClassifiedData` and the caller adds them.\n */\nexport function countUnits(\n classified: ClassifiedData,\n tables: RenderedTables,\n plannedTables: ReadonlyMap<string, PlannedRow[]>,\n suppressed: ReadonlySet<string>,\n): number {\n let total = 0;\n forEachFieldUnit(classified, (pointer) => {\n if (!suppressed.has(pointer)) total += 1;\n });\n forEachRowUnit(tables, plannedTables, () => {\n total += 1;\n });\n return total;\n}\n\n/**\n * True when any FIELD or ROW carries a confidence level — i.e. whether the\n * filter has anything at all to act on.\n *\n * Overall confidence is excluded deliberately: it renders as its own summary\n * line, is not a review unit and cannot be hidden, so offering a switch on its\n * account would give the reviewer a control that does nothing. Row confidence\n * alone qualifies, because an `invoice_line_items` extraction has no header\n * fields whatsoever and scores every row.\n */\nexport function hasAnyConfidence(\n classified: ClassifiedData,\n tables: RenderedTables,\n plannedTables: ReadonlyMap<string, PlannedRow[]>,\n): boolean {\n let found = false;\n forEachFieldUnit(classified, (_pointer, confidence) => {\n if (confidence?.level) found = true;\n });\n if (found) return true;\n forEachRowUnit(tables, plannedTables, (_rowKey, confidence) => {\n if (confidence?.level) found = true;\n });\n return found;\n}\n","/**\n * A tooltip primitive, portalled and themed.\n *\n * Replaces `title=`, which could not do any of the four things this component\n * needs: carry structure (the confidence annotation is a heading plus a list\n * of reasons), be styled to match the surface it floats over, appear on\n * keyboard focus, or be announced predictably.\n *\n * WHY A PORTAL. The console hosts `<GeminaVerification>` inside a modal body\n * with `max-height` + `overflow-y: auto`. Any in-flow tooltip is clipped at\n * that scroll edge, and the fields most likely to carry one — the low-\n * confidence rows — are exactly the ones a reviewer scrolls to. So the tip\n * renders into `document.body` and positions itself `fixed`.\n *\n * The cost of leaving the root is that `--gemina-verification-*` no longer\n * resolves, so the portal wraps its content in a div carrying the root's own\n * class list, read off the nearest `.gemina-verification` ancestor when the\n * tip opens. That keeps theme, dark mode and RTL correct without duplicating\n * a single value.\n *\n * Being `fixed`, it cannot follow a trigger that scrolls away — so it closes\n * on scroll rather than detaching from what it describes.\n */\n\nimport {\n cloneElement,\n isValidElement,\n useCallback,\n useEffect,\n useId,\n useLayoutEffect,\n useRef,\n useState,\n} from 'react';\nimport type { ReactElement, ReactNode, RefCallback } from 'react';\nimport { createPortal } from 'react-dom';\n\n/** Distance between the trigger and the tip, in px. */\nconst GAP = 8;\n/** Minimum breathing room from the viewport edge, in px. */\nconst MARGIN = 8;\n\nexport interface TipProps {\n /** Rich content — a fragment, a list, anything. Empty renders no tip. */\n content: ReactNode;\n /** The trigger. Receives handlers, a ref and `aria-describedby`. */\n children: ReactElement;\n}\n\ninterface Position {\n top: number;\n left: number;\n}\n\n/** `content` that would produce an empty bubble. */\nfunction isEmpty(content: ReactNode): boolean {\n return content == null || content === '' || content === false;\n}\n\n/**\n * The theme classes to reproduce outside the root.\n *\n * Copies the ancestor's whole class list rather than sniffing for known\n * modifiers, so a host that adds its own scoping class keeps working and this\n * never needs updating when a new modifier is introduced.\n */\nfunction rootClassesOf(node: Element | null): string {\n const root = node?.closest('.gemina-verification');\n return root ? root.className : 'gemina-verification';\n}\n\n/** Attach our ref without dropping one the child already had. */\nfunction mergeRefs<T>(ours: RefCallback<T>, theirs: unknown): RefCallback<T> {\n return (value: T) => {\n ours(value);\n if (typeof theirs === 'function') {\n (theirs as RefCallback<T>)(value);\n } else if (theirs && typeof theirs === 'object') {\n (theirs as { current: T | null }).current = value;\n }\n };\n}\n\nexport function Tip({ content, children }: TipProps) {\n const [open, setOpen] = useState(false);\n const [position, setPosition] = useState<Position | null>(null);\n const [rootClasses, setRootClasses] = useState('gemina-verification');\n const triggerRef = useRef<HTMLElement | null>(null);\n const tipRef = useRef<HTMLDivElement | null>(null);\n const id = useId();\n\n const empty = isEmpty(content);\n\n const show = useCallback(() => {\n if (empty) {\n return;\n }\n setRootClasses(rootClassesOf(triggerRef.current));\n setPosition(null); // re-measure; a stale position would flash in the wrong place\n setOpen(true);\n }, [empty]);\n\n const hide = useCallback(() => setOpen(false), []);\n\n // Measure AFTER paint but BEFORE the browser shows it: the tip renders\n // hidden until it has a position, so it never flashes at the origin.\n useLayoutEffect(() => {\n if (!open) {\n return;\n }\n const trigger = triggerRef.current;\n const tip = tipRef.current;\n if (!trigger || !tip) {\n return;\n }\n const anchor = trigger.getBoundingClientRect();\n const bubble = tip.getBoundingClientRect();\n const viewportWidth = window.innerWidth || 0;\n const viewportHeight = window.innerHeight || 0;\n\n // Prefer above; flip below only when there is genuinely no room, so the\n // tip does not cover the control the pointer is already on.\n const fitsAbove = anchor.top - bubble.height - GAP >= MARGIN;\n const fitsBelow = anchor.bottom + bubble.height + GAP <= viewportHeight - MARGIN;\n const top = fitsAbove || !fitsBelow\n ? anchor.top - bubble.height - GAP\n : anchor.bottom + GAP;\n\n // Centre on the trigger, then clamp so a tip near either edge stays whole.\n const centred = anchor.left + anchor.width / 2 - bubble.width / 2;\n const rightLimit = Math.max(MARGIN, viewportWidth - bubble.width - MARGIN);\n const left = Math.min(Math.max(centred, MARGIN), rightLimit);\n\n setPosition({ top: Math.max(top, MARGIN), left });\n }, [open, content]);\n\n // Escape dismisses the annotation without disturbing focus; scroll closes\n // because a fixed tip would otherwise drift away from its trigger.\n useEffect(() => {\n if (!open) {\n return;\n }\n const onKeyDown = (event: KeyboardEvent) => {\n if (event.key === 'Escape') {\n hide();\n }\n };\n const onScrollOrResize = () => hide();\n document.addEventListener('keydown', onKeyDown);\n // Capture phase: scrolls inside the host's overflow container do not\n // bubble to document, and that container is the common case here.\n document.addEventListener('scroll', onScrollOrResize, true);\n window.addEventListener('resize', onScrollOrResize);\n return () => {\n document.removeEventListener('keydown', onKeyDown);\n document.removeEventListener('scroll', onScrollOrResize, true);\n window.removeEventListener('resize', onScrollOrResize);\n };\n }, [open, hide]);\n\n if (!isValidElement(children)) {\n return children;\n }\n\n const childProps = children.props as Record<string, unknown>;\n const call = (name: string, event: unknown) => {\n const handler = childProps[name];\n if (typeof handler === 'function') {\n (handler as (arg: unknown) => void)(event);\n }\n };\n\n const trigger = cloneElement(children, {\n ref: mergeRefs<HTMLElement>((node) => {\n triggerRef.current = node;\n }, (children as unknown as { ref?: unknown }).ref),\n // The tip is a DESCRIPTION. `aria-label` stays untouched — it already\n // carries the reason into the accessible NAME, and duplicating it here\n // would have a screen reader announce it twice.\n 'aria-describedby': open && !empty ? id : undefined,\n onMouseEnter: (event: unknown) => { call('onMouseEnter', event); show(); },\n onMouseLeave: (event: unknown) => { call('onMouseLeave', event); hide(); },\n onFocus: (event: unknown) => { call('onFocus', event); show(); },\n onBlur: (event: unknown) => { call('onBlur', event); hide(); },\n } as Record<string, unknown>);\n\n const canPortal = typeof document !== 'undefined' && document.body;\n\n return (\n <>\n {trigger}\n {open && !empty && canPortal\n ? createPortal(\n <div className={rootClasses}>\n <div\n ref={tipRef}\n id={id}\n role=\"tooltip\"\n className=\"gemina-verification__tip\"\n style={{\n top: position ? `${position.top}px` : '0px',\n left: position ? `${position.left}px` : '0px',\n visibility: position ? 'visible' : 'hidden',\n }}\n >\n {content}\n </div>\n </div>,\n document.body,\n )\n : null}\n </>\n );\n}\n","/**\n * Internal document viewer for <GeminaVerification> — image canvas with a\n * zoom/rotate toolbar. Port of the console's ZoomableImageViewer skeleton\n * (gemina-console/src/components/viewers/ZoomableImageViewer.tsx): same\n * state/refs/effects shape, with the gesture/travel transform math delegated\n * to `viewer-math.ts` (the magnifier's presentation math stays local, exactly\n * as inline as the console's) and all styling on the Task 6\n * `.gemina-verification__*` classes. Tasks 8+9 add wheel zoom, mouse pan, the\n * double-click fit/100% toggle, and touch pan + pinch zoom; Task 10 adds\n * coordinate overlays, the flash-zoom travel animation, and the image-expiry\n * hook; Task 11 adds the magnifier loupe.\n *\n * Coordinate spaces: the console's zoomAtPoint takes clientX/Y and subtracts\n * the canvas rect INSIDE itself; the elements zoomAtPoint (viewer-math.ts) is\n * container-relative, so every DOM call site converts via\n * `zoomAtClientPoint` (Task 7 review carry-forward — a verbatim port anchors\n * wrong in any scrolled/offset layout).\n *\n * SSR-safe: no `window`/`document` access at import time; `ResizeObserver`\n * is only touched inside an effect (with a one-shot measure fallback).\n */\nimport { useCallback, useEffect, useLayoutEffect, useRef, useState } from 'react';\nimport type * as React from 'react';\nimport {\n centeredTranslation,\n clampScale,\n easeOutCubic,\n fitScaleFor,\n flashZoomTarget,\n zoomAtPoint,\n} from './viewer-math';\nimport type { Size, Transform } from './viewer-math';\nimport { Tip } from './tip';\n\n/** Axis-aligned detection region in relative image coordinates (0–1). */\nexport interface RelativeRect {\n points: [number, number][];\n}\n\nexport interface VerificationViewerProps {\n src: string;\n alt?: string;\n relativeRects?: RelativeRect[];\n flashRects?: RelativeRect[] | null;\n onFlashComplete?: () => void;\n /** Fired when the <img> errors AFTER at least one successful load (URL expiry). */\n onImageExpired?: () => void;\n}\n\n// --- Icons ------------------------------------------------------------------\n// One hand-drawn family: 16×16 grid, 1.5px stroke, round caps/joins, painted\n// with currentColor so the toolbar's normal/active colors flow through. The\n// only fills are the two dots of the 1:1 colon. Each icon stays ≤ 6 segments.\n\nfunction IconBase({ children }: { children: React.ReactNode }): React.JSX.Element {\n return (\n <svg\n width=\"16\"\n height=\"16\"\n viewBox=\"0 0 16 16\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth=\"1.5\"\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n aria-hidden=\"true\"\n focusable=\"false\"\n >\n {children}\n </svg>\n );\n}\n\n/** Shared magnifying-glass body (lens + handle) for the zoom/magnifier trio. */\nfunction GlassBody(): React.JSX.Element {\n return (\n <>\n <circle cx=\"6.75\" cy=\"6.75\" r=\"4.25\" />\n <line x1=\"9.9\" y1=\"9.9\" x2=\"13.5\" y2=\"13.5\" />\n </>\n );\n}\n\nexport function IconZoomIn(): React.JSX.Element {\n return (\n <IconBase>\n <GlassBody />\n <line x1=\"4.9\" y1=\"6.75\" x2=\"8.6\" y2=\"6.75\" />\n <line x1=\"6.75\" y1=\"4.9\" x2=\"6.75\" y2=\"8.6\" />\n </IconBase>\n );\n}\n\nexport function IconZoomOut(): React.JSX.Element {\n return (\n <IconBase>\n <GlassBody />\n <line x1=\"4.9\" y1=\"6.75\" x2=\"8.6\" y2=\"6.75\" />\n </IconBase>\n );\n}\n\nexport function IconMagnifier(): React.JSX.Element {\n return (\n <IconBase>\n <GlassBody />\n </IconBase>\n );\n}\n\n/** \"1:1\" drawn as numeral strokes — actual pixel size. */\nexport function IconActualSize(): React.JSX.Element {\n return (\n <IconBase>\n <polyline points=\"2.8 6.2 4 5 4 11\" />\n <polyline points=\"10.8 6.2 12 5 12 11\" />\n <circle cx=\"8\" cy=\"6.75\" r=\"0.8\" fill=\"currentColor\" stroke=\"none\" />\n <circle cx=\"8\" cy=\"9.25\" r=\"0.8\" fill=\"currentColor\" stroke=\"none\" />\n </IconBase>\n );\n}\n\n/** Two arrows collapsing inward — fit to screen. */\nexport function IconFit(): React.JSX.Element {\n return (\n <IconBase>\n <line x1=\"13.8\" y1=\"2.2\" x2=\"9.6\" y2=\"6.4\" />\n <polyline points=\"9.6 3.9 9.6 6.4 12.1 6.4\" />\n <line x1=\"2.2\" y1=\"13.8\" x2=\"6.4\" y2=\"9.6\" />\n <polyline points=\"6.4 12.1 6.4 9.6 3.9 9.6\" />\n </IconBase>\n );\n}\n\n/** Clockwise circular arrow. */\nexport function IconRotate(): React.JSX.Element {\n return (\n <IconBase>\n <path d=\"M11.83 4.79A5 5 0 1 1 8 3\" />\n <polyline points=\"6 1.7 8 3 6 4.3\" />\n </IconBase>\n );\n}\n\n/** Dashed square — detection overlay regions. */\nexport function IconOverlay(): React.JSX.Element {\n return (\n <IconBase>\n <rect x=\"2.75\" y=\"2.75\" width=\"10.5\" height=\"10.5\" rx=\"1.5\" strokeDasharray=\"3 2.2\" />\n </IconBase>\n );\n}\n\n/** Eye — used by the form's field-peek buttons (Task 12+). */\nexport function IconEye(): React.JSX.Element {\n return (\n <IconBase>\n <path d=\"M1.5 8s2.4-4.5 6.5-4.5S14.5 8 14.5 8s-2.4 4.5-6.5 4.5S1.5 8 1.5 8z\" />\n <circle cx=\"8\" cy=\"8\" r=\"2.1\" />\n </IconBase>\n );\n}\n\n// --- Toolbar ----------------------------------------------------------------\n\ninterface ToolbarButtonProps {\n label: string;\n onClick: () => void;\n disabled?: boolean;\n /** aria-pressed toggle button (overlay toggle). */\n pressed?: boolean;\n /** role=\"switch\" + aria-checked (magnifier). */\n checked?: boolean;\n children: React.ReactNode;\n}\n\nfunction ToolbarButton({\n label,\n onClick,\n disabled,\n pressed,\n checked,\n children,\n}: ToolbarButtonProps): React.JSX.Element {\n const active = (pressed ?? checked) === true;\n // Icon-only controls: the label is the ONLY thing naming them, so it needs a\n // sighted channel as well as the accessible name.\n return (\n <Tip content={label}>\n <button\n type=\"button\"\n className={\n active\n ? 'gemina-verification__toolbar-btn gemina-verification__toolbar-btn--active'\n : 'gemina-verification__toolbar-btn'\n }\n aria-label={label}\n role={checked === undefined ? undefined : 'switch'}\n aria-checked={checked}\n aria-pressed={pressed}\n disabled={disabled}\n onClick={onClick}\n >\n {children}\n </button>\n </Tip>\n );\n}\n\n// --- Viewer -----------------------------------------------------------------\n\nconst ZOOM_STEP = 1.2;\nconst IDENTITY: Transform = { scale: 1, tx: 0, ty: 0 };\n\n// Console flash constants (ZoomableImageViewer ~56-57): the rect fades over\n// 1500ms while the transform travels for its first 350ms.\nconst FLASH_DURATION = 1500; // ms\nconst ZOOM_ANIMATION_DURATION = 350; // ms - smooth but fast travel animation\n/** Reduced motion: no travel, no fade — jump to the target and hold the rect\n * at full opacity for a beat long enough to register, then complete. */\nconst REDUCED_MOTION_FLASH_MS = 800;\n\n/** Console's minimum visible rect size, as a ratio of the natural dimension\n * (~750): hairline detection boxes stay clickable-eye-visible. */\nconst MIN_SIZE_RATIO = 0.008;\n\n// Console magnifier constants (ZoomableImageViewer ~59-60).\nconst MAG_RADIUS = 150; // px — loupe radius (console: 140-160px)\nconst MAG_ZOOM = 2.5; // magnification applied on top of the current scale\n// Must equal the loupe's ring width in styles.ts (`.gemina-verification__\n// magnifier { border: 2px }`). The inner img is absolutely positioned, so its\n// containing block is the loupe's PADDING box — inset by exactly this much —\n// while the centring maths is expressed against the border box. Without the\n// correction the loupe shows a point (2, 2) px off its own centre, everywhere,\n// including over the image. Pinned by a test that reads the width back out of\n// the stylesheet, so restyling the ring cannot silently reintroduce the skew.\nconst MAG_BORDER = 2;\n\n/** Rect geometry in image pixel space — the overlays render INSIDE the\n * transform layer, so left/top/width/height are natural-size pixels and the\n * layer's scale/rotate carries them (console ~742-756). Returns null for\n * degenerate rects (a single point, or no points at all). */\nfunction rectGeometry(\n rect: RelativeRect,\n natural: Size,\n): { left: number; top: number; width: number; height: number } | null {\n const xs = rect.points.map((point) => point[0]);\n const ys = rect.points.map((point) => point[1]);\n const minX = Math.min(...xs);\n const minY = Math.min(...ys);\n const rawWidthRatio = Math.max(0, Math.max(...xs) - minX);\n const rawHeightRatio = Math.max(0, Math.max(...ys) - minY);\n if (rawWidthRatio <= 0 && rawHeightRatio <= 0) return null;\n return {\n left: minX * natural.w,\n top: minY * natural.h,\n width: Math.max(rawWidthRatio, MIN_SIZE_RATIO) * natural.w,\n height: Math.max(rawHeightRatio, MIN_SIZE_RATIO) * natural.h,\n };\n}\n\nexport function VerificationViewer(props: VerificationViewerProps): React.JSX.Element {\n const { src, alt, relativeRects, flashRects, onFlashComplete, onImageExpired } = props;\n\n const canvasRef = useRef<HTMLDivElement | null>(null);\n const imgRef = useRef<HTMLImageElement | null>(null);\n\n const [natural, setNatural] = useState<Size | null>(null);\n const [container, setContainer] = useState<Size>({ w: 0, h: 0 });\n const [transform, setTransform] = useState<Transform>(IDENTITY);\n const [rotation, setRotation] = useState(0); // degrees, multiples of 90\n\n const [showRects, setShowRects] = useState(false);\n const [magnifierOn, setMagnifierOn] = useState(false);\n\n // Loupe pointer state (console ~37-38): showMag flips on canvas\n // mousemove/mouseleave, mousePos is container-relative. Both track on EVERY\n // move regardless of the switch — console parity — so toggling the switch\n // with the pointer resting over the canvas (keyboard toggle) shows the\n // loupe at the right spot. The per-move re-render is the console's own\n // accepted cost; the loupe subtree is tiny.\n const [showMag, setShowMag] = useState(false);\n const [mousePos, setMousePos] = useState<{ x: number; y: number }>({ x: 0, y: 0 });\n // Client coordinates are the stable source while an ancestor scrolls. A\n // canvas-relative point goes stale as soon as the host modal moves beneath\n // a stationary pointer, which made the loupe sample a visibly different\n // spot from the one being hovered.\n const lastMouseClientRef = useRef<{ x: number; y: number } | null>(null);\n\n const [isPanning, setIsPanning] = useState(false);\n const panStart = useRef<{ x: number; y: number; tx: number; ty: number } | null>(null);\n\n // Flash animation state (console ~43-57).\n const [flashOpacity, setFlashOpacity] = useState(0);\n const [activeFlashRects, setActiveFlashRects] = useState<RelativeRect[] | null>(null);\n const travelRafRef = useRef<number | null>(null);\n const fadeRafRef = useRef<number | null>(null);\n const reducedFlashTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);\n\n // Render-synced mirror of the transform (console's scaleRef/txRef/tyRef):\n // the travel animation reads its from-values here instead of closing over\n // state inside the rAF loop (review carry-forward).\n const transformRef = useRef(transform);\n transformRef.current = transform;\n\n // Latest-value ref so an inline onFlashComplete prop cannot restart the\n // flash effect on every parent render.\n const onFlashCompleteRef = useRef(onFlashComplete);\n onFlashCompleteRef.current = onFlashComplete;\n\n // True once the CURRENT src has loaded successfully — the expiry gate.\n const hasLoadedRef = useRef(false);\n\n // Measure the canvas (console lines ~124-133), with a one-shot fallback for\n // environments without ResizeObserver. contentRect on purpose (unlike the\n // root's stacked observer, which reads border-box): the fit/zoom math needs\n // the CONTENT area the image is positioned within.\n useLayoutEffect(() => {\n const el = canvasRef.current;\n if (!el) return;\n if (typeof ResizeObserver === 'undefined') {\n const rect = el.getBoundingClientRect();\n setContainer({ w: rect.width, h: rect.height });\n return;\n }\n const ro = new ResizeObserver((entries) => {\n const cr = entries[0]?.contentRect;\n if (cr) setContainer({ w: cr.width, h: cr.height });\n });\n ro.observe(el);\n return () => ro.disconnect();\n }, []);\n\n // Natural image size (console ~136-139), with an identity-preserving setter\n // (review carry-forward): a re-minted URL for the SAME image (the\n // onImageExpired flow) reports identical dimensions, and returning the prev\n // object keeps the fit effect from re-running and resetting the user's\n // zoom/pan mid-review.\n const handleImgLoad = useCallback(() => {\n const img = imgRef.current;\n if (!img) return;\n hasLoadedRef.current = true;\n const w = img.naturalWidth;\n const h = img.naturalHeight;\n setNatural((prev) => (prev && prev.w === w && prev.h === h ? prev : { w, h }));\n }, []);\n\n // Expiry hook — replaces the console's fallbackSrc error handler (~374-378).\n // The loaded flag resets on every src change: a NEW src that fails before it\n // ever loads is a broken URL, not an expired one, and firing onImageExpired\n // there would re-mint forever in a loop. It also disarms when it fires, so\n // one load reports at most one expiry (the re-minted load re-arms it).\n useEffect(() => {\n hasLoadedRef.current = false;\n }, [src]);\n\n const handleImgError = useCallback(() => {\n if (!hasLoadedRef.current) return;\n hasLoadedRef.current = false;\n onImageExpired?.();\n }, [onImageExpired]);\n\n /** The console's `fitScale` memo, including its degenerate-size guard. */\n const currentFitScale = useCallback((): number => {\n if (!natural || !container.w || !container.h) return 1;\n return fitScaleFor(natural, container, rotation);\n }, [natural, container, rotation]);\n\n // Fit + center on first load, and re-fit on container/rotation changes\n // (console ~186-196).\n useEffect(() => {\n if (!natural || !container.w || !container.h) return;\n const fit = fitScaleFor(natural, container, rotation);\n const { tx, ty } = centeredTranslation(natural, container, fit, rotation);\n setTransform((prev) =>\n Math.abs(prev.scale - fit) < 0.0001 && prev.tx === tx && prev.ty === ty\n ? prev\n : { scale: fit, tx, ty },\n );\n }, [natural, container, rotation]);\n\n // DELIBERATE IMPROVEMENT over the console (reviewer-endorsed): the console\n // never cancels the flash travel on user input, so its rAF loop keeps\n // stomping wheel/drag transforms for the rest of its 350ms window. Here any\n // canvas gesture (wheel, mousedown, touchstart, dblclick) AND any toolbar\n // zoom (zoom in/out, fit, 100%) stops the travel — the user just took the\n // wheel. Only the transform drive stops: the flash rect keeps fading, and\n // the fade loop still fires onFlashComplete.\n const cancelFlashTravel = useCallback(() => {\n if (travelRafRef.current !== null) {\n cancelAnimationFrame(travelRafRef.current);\n travelRafRef.current = null;\n }\n }, []);\n\n // Toolbar handlers (console ~251-278). zoomAtPoint returns the SAME object\n // on clamped no-ops, so the updater form bails out of re-rendering.\n const zoomBy = useCallback(\n (factor: number) => {\n const node = canvasRef.current;\n if (!node || !natural) return;\n cancelFlashTravel();\n const rect = node.getBoundingClientRect();\n const fit = currentFitScale();\n setTransform((prev) =>\n zoomAtPoint(prev, factor, rect.width / 2, rect.height / 2, rotation, fit),\n );\n },\n [natural, rotation, currentFitScale, cancelFlashTravel],\n );\n\n const handleZoomIn = useCallback(() => zoomBy(ZOOM_STEP), [zoomBy]);\n const handleZoomOut = useCallback(() => zoomBy(1 / ZOOM_STEP), [zoomBy]);\n\n /** Client -> container-relative conversion lives HERE, at the call sites\n * (wheel, double-click; pinch joins in Task 9) — viewer-math's zoomAtPoint\n * is container-relative by contract. */\n const zoomAtClientPoint = useCallback(\n (factor: number, clientX: number, clientY: number) => {\n const node = canvasRef.current;\n if (!node || !natural) return;\n const rect = node.getBoundingClientRect();\n const fit = currentFitScale();\n setTransform((prev) =>\n zoomAtPoint(prev, factor, clientX - rect.left, clientY - rect.top, rotation, fit),\n );\n },\n [natural, rotation, currentFitScale],\n );\n\n // Wheel zoom (console ~232-249): React's onWheel is passive, so attach a\n // NON-PASSIVE native listener — preventDefault must keep the page from\n // scrolling under the zoom.\n const handleWheel = useCallback(\n (event: WheelEvent) => {\n event.preventDefault();\n event.stopPropagation();\n cancelFlashTravel();\n const factor = event.deltaY > 0 ? 0.92 : 1.08; // console's wheel constants\n zoomAtClientPoint(factor, event.clientX, event.clientY);\n },\n [zoomAtClientPoint, cancelFlashTravel],\n );\n\n useEffect(() => {\n const node = canvasRef.current;\n if (!node) return;\n const listener = (event: WheelEvent) => handleWheel(event);\n node.addEventListener('wheel', listener, { passive: false });\n return () => node.removeEventListener('wheel', listener);\n }, [handleWheel]);\n\n // Beyond fit there is something to pan; at fit the drag is inert and the\n // cursor honestly says zoom-in (console ~296-322 policy). Shared by the\n // mousedown gate and the cursor state below.\n const atFitScale = transform.scale <= currentFitScale() + 0.001;\n\n // Mouse pan. Deliberate deviation from the console: move/up listen on\n // `document` while panning so the drag survives leaving the canvas instead\n // of dropping at the edge.\n const handleMouseDown = useCallback(\n (e: React.MouseEvent<HTMLDivElement>) => {\n // Any press grabs the canvas — stop the flash travel before the gates.\n cancelFlashTravel();\n // Primary button only: with document-level listeners a right-click's\n // context menu would swallow the mouseup and leave the pan stuck.\n // (Tap-synthesized compat mouse events report button 0 and pass — fine;\n // Task 9's touch handlers own that path.)\n if (e.button !== 0) return;\n if (atFitScale) return;\n e.preventDefault(); // document-level drag: don't start selections outside the widget\n panStart.current = { x: e.clientX, y: e.clientY, tx: transform.tx, ty: transform.ty };\n setIsPanning(true);\n },\n [atFitScale, transform.tx, transform.ty, cancelFlashTravel],\n );\n\n useEffect(() => {\n if (!isPanning) return;\n const onMove = (e: MouseEvent) => {\n const start = panStart.current;\n if (!start) return;\n const dx = e.clientX - start.x;\n const dy = e.clientY - start.y;\n setTransform((prev) => ({ scale: prev.scale, tx: start.tx + dx, ty: start.ty + dy }));\n };\n const onUp = () => {\n panStart.current = null;\n setIsPanning(false);\n };\n document.addEventListener('mousemove', onMove);\n document.addEventListener('mouseup', onUp);\n // Cleanup runs on mouseup (isPanning flips false) AND on unmount mid-pan.\n return () => {\n document.removeEventListener('mousemove', onMove);\n document.removeEventListener('mouseup', onUp);\n };\n }, [isPanning]);\n\n // Touch: one-finger pan (only beyond fit — the mousedown gate's twin) and\n // two-finger pinch zoom. Verbatim console port (~324-369) except the pinch\n // factor routes through zoomAtClientPoint — client → container conversion\n // plus the shared fit-floor clamp — instead of any local math.\n // `touch-action: none` on __canvas (styles.ts) hands these gestures to us,\n // so React's passive onTouch* handlers suffice; no preventDefault needed.\n // Gesture state lives in a ref: nothing re-renders per touch-move except\n // the transform update itself, and isPanning/data-cursor stay mouse-only\n // (a touch screen shows no cursor).\n const touchState = useRef<\n | { mode: 'pan'; x: number; y: number; tx: number; ty: number }\n | { mode: 'pinch'; dist: number }\n | null\n >(null);\n\n const handleTouchStart = useCallback(\n (e: React.TouchEvent<HTMLDivElement>) => {\n // A finger on the canvas grabs it — stop the flash travel.\n cancelFlashTravel();\n // Length checks don't narrow TouchList indexing under\n // noUncheckedIndexedAccess, so a/b/their truthiness carry the guard.\n const a = e.touches[0];\n const b = e.touches[1];\n if (e.touches.length === 2 && a && b) {\n // Only the start distance seeds a pinch — no midpoint is stored,\n // because every move re-anchors at the CURRENT midpoint (console\n // policy). A second finger landing mid-pan arrives here too, so 1→2\n // hands the gesture off to pinch automatically.\n touchState.current = {\n mode: 'pinch',\n dist: Math.hypot(a.clientX - b.clientX, a.clientY - b.clientY),\n };\n } else if (e.touches.length === 1 && a && !atFitScale) {\n touchState.current = { mode: 'pan', x: a.clientX, y: a.clientY, tx: transform.tx, ty: transform.ty };\n } else {\n touchState.current = null;\n }\n },\n [atFitScale, transform.tx, transform.ty, cancelFlashTravel],\n );\n\n const handleTouchMove = useCallback(\n (e: React.TouchEvent<HTMLDivElement>) => {\n const state = touchState.current;\n if (!state) return;\n if (state.mode === 'pinch' && e.touches.length === 2) {\n const a = e.touches[0];\n const b = e.touches[1];\n if (!a || !b) return;\n const dist = Math.hypot(a.clientX - b.clientX, a.clientY - b.clientY);\n if (state.dist > 0) {\n // Per-move ratio, re-seeded below: each factor is relative to the\n // LAST move, and the updater-form zoomAtPoint composes it onto the\n // accumulated transform, so React batching can't double-apply a\n // step. Two-finger travel without spread is factor 1 — zoomAtPoint's\n // same-object bail-out makes it a no-op (console policy: a pinch\n // never pans; the image only shifts through the moving anchor while\n // the scale is changing).\n zoomAtClientPoint(dist / state.dist, (a.clientX + b.clientX) / 2, (a.clientY + b.clientY) / 2);\n }\n state.dist = dist;\n } else if (state.mode === 'pan' && e.touches.length === 1) {\n // START-RELATIVE deltas (the established pan pattern) — never\n // accumulated per event, so a dropped move can't skew the drag.\n const t = e.touches[0];\n if (!t) return;\n setTransform((prev) => ({\n scale: prev.scale,\n tx: state.tx + (t.clientX - state.x),\n ty: state.ty + (t.clientY - state.y),\n }));\n }\n },\n [zoomAtClientPoint],\n );\n\n // 2→1 deliberately leaves an INERT pinch until every finger lifts\n // (console-faithful): the remaining finger matches neither move branch, so\n // nothing jumps; the next touchstart begins a fresh gesture.\n const handleTouchEnd = useCallback((e: React.TouchEvent<HTMLDivElement>) => {\n if (e.touches.length === 0) touchState.current = null;\n }, []);\n\n // Loupe pointer tracking (console ~305-308, ~695-703), container-relative\n // like every other pointer path (Task 7 carry-forward). Show on any canvas\n // mousemove, hide only on mouseleave — console policy verbatim. On a touch\n // device a tap synthesizes compat mousemoves that PARK the loupe at the tap\n // point while the switch is on; the console does nothing about that either\n // (its loupe is a desktop pattern), and the parked loupe clears on the next\n // compat mouseleave. Pan is untouched: it lives on document-level listeners.\n const syncMagnifierToClientPoint = useCallback((\n clientX: number,\n clientY: number,\n assumeInside = false,\n ) => {\n const rect = canvasRef.current?.getBoundingClientRect();\n if (!rect) return;\n const x = clientX - rect.left;\n const y = clientY - rect.top;\n // A mousemove dispatched by the canvas is authoritative even in DOMs\n // without layout (and during a resize frame whose rect is momentarily\n // zero). Scroll/resize resyncs use the real bounds so a stationary pointer\n // that the canvas moved away from hides the lens.\n const inside = assumeInside\n || (x >= 0 && y >= 0 && x <= rect.width && y <= rect.height);\n setShowMag(inside);\n if (inside) {\n setMousePos({ x, y });\n }\n }, []);\n\n const handleCanvasMouseMove = useCallback((e: React.MouseEvent<HTMLDivElement>) => {\n lastMouseClientRef.current = { x: e.clientX, y: e.clientY };\n syncMagnifierToClientPoint(e.clientX, e.clientY, true);\n }, [syncMagnifierToClientPoint]);\n\n const handleCanvasMouseLeave = useCallback(() => {\n lastMouseClientRef.current = null;\n setShowMag(false);\n }, []);\n\n // Scroll events do not reliably dispatch mousemove/mouseleave. Re-project\n // the last client point whenever ANY scroll container moves (capture=true),\n // and on viewport resize, so both the lens and its sampled point stay under\n // the real pointer inside host-scrolled modals.\n useEffect(() => {\n if (!magnifierOn || !showMag) return;\n const sync = () => {\n const point = lastMouseClientRef.current;\n if (point) syncMagnifierToClientPoint(point.x, point.y);\n };\n document.addEventListener('scroll', sync, true);\n window.addEventListener('resize', sync);\n return () => {\n document.removeEventListener('scroll', sync, true);\n window.removeEventListener('resize', sync);\n };\n }, [magnifierOn, showMag, syncMagnifierToClientPoint]);\n\n // Double-click toggle (console ~281-294): near fit -> 100% anchored at the\n // click point; otherwise back to centered fit.\n const handleDoubleClick = useCallback(\n (e: React.MouseEvent<HTMLDivElement>) => {\n cancelFlashTravel();\n if (!natural) return;\n const fit = currentFitScale();\n const nearFit = Math.abs(transform.scale - fit) < 0.001;\n if (nearFit) {\n const target = clampScale(1, fit);\n zoomAtClientPoint(target / transform.scale, e.clientX, e.clientY);\n } else {\n setTransform({ scale: fit, ...centeredTranslation(natural, container, fit, rotation) });\n }\n },\n [natural, container, rotation, transform.scale, currentFitScale, zoomAtClientPoint, cancelFlashTravel],\n );\n\n const handleFit = useCallback(() => {\n if (!natural) return;\n cancelFlashTravel();\n const fit = currentFitScale();\n setTransform({ scale: fit, ...centeredTranslation(natural, container, fit, rotation) });\n }, [natural, container, rotation, currentFitScale, cancelFlashTravel]);\n\n const handleActualSize = useCallback(() => {\n if (!natural) return;\n cancelFlashTravel();\n const target = clampScale(1, currentFitScale());\n setTransform({ scale: target, ...centeredTranslation(natural, container, target, rotation) });\n }, [natural, container, rotation, currentFitScale, cancelFlashTravel]);\n\n // Deliberately does NOT cancelFlashTravel: `rotation` is a dep of the flash\n // effect, so a rotate mid-travel re-runs it — cleanup cancels both loops,\n // then the effect recomputes flashZoomTarget for the NEW rotation and\n // restarts travel (and fade, from full opacity) from the current transform.\n // The rect therefore lands rotation-correct instead of coasting toward a\n // stale pre-rotation target (pinned by the rotate-mid-travel test).\n const handleRotate = useCallback(() => {\n setRotation((r) => (r + 90) % 360);\n }, []);\n\n // Overlay toggle only means something while rects exist (console ~450-456).\n const hasRects = relativeRects !== undefined && relativeRects.length > 0;\n useEffect(() => {\n if (!hasRects) setShowRects(false);\n }, [hasRects]);\n\n // Flash animation + zoom-to-rect travel (console ~458-581). Two parallel\n // drives: the transform travels to flashZoomTarget over 350ms (easeOutCubic,\n // from-values read off transformRef), while the flash rect fades 1 - p²\n // over 1500ms. The FADE loop owns completion: it clears the rects and fires\n // onFlashComplete — so a gesture-canceled travel never swallows the\n // callback. Cleanup cancels BOTH loops, which covers unmount mid-flash and\n // makes a re-trigger (rapid eye-clicks re-running this effect) a clean\n // restart; the console leaked its fade loop here and only canceled the\n // travel — fixed deliberately.\n useEffect(() => {\n if (!flashRects || flashRects.length === 0 || !natural || !container.w || !container.h) {\n // A parent nulling flashRects mid-flash declares the flash over: clear\n // the display (cleanup already canceled both loops) WITHOUT firing\n // onFlashComplete — the parent initiated this, echoing back would loop.\n // (The console coasted here on its leaked fade loop to clear the rect;\n // with the leak fixed, the clear must be explicit.) The prev-identity\n // bail keeps the common null→null path render-free.\n setActiveFlashRects((prev) => (prev === null ? prev : null));\n setFlashOpacity(0);\n return;\n }\n\n const fit = fitScaleFor(natural, container, rotation);\n const target = flashZoomTarget(flashRects, natural, container, rotation, fit);\n\n setActiveFlashRects(flashRects);\n setFlashOpacity(1);\n\n const prefersReduced =\n typeof window !== 'undefined' &&\n typeof window.matchMedia === 'function' &&\n window.matchMedia('(prefers-reduced-motion: reduce)').matches;\n\n if (prefersReduced) {\n // No travel, no fade: jump to the target and hold the rect long enough\n // to register, then complete. (The stylesheet's reduced-motion block is\n // the CSS backstop; this is the JS half.)\n setTransform(target);\n reducedFlashTimeoutRef.current = setTimeout(() => {\n reducedFlashTimeoutRef.current = null;\n setActiveFlashRects(null);\n setFlashOpacity(0);\n onFlashCompleteRef.current?.();\n }, REDUCED_MOTION_FLASH_MS);\n return () => {\n if (reducedFlashTimeoutRef.current !== null) {\n clearTimeout(reducedFlashTimeoutRef.current);\n reducedFlashTimeoutRef.current = null;\n }\n };\n }\n\n // Travel: capture the from-values ONCE from the render-synced ref (review\n // carry-forward — no state reads inside the rAF loop).\n const from = transformRef.current;\n const zoomStartTime = Date.now();\n const animateZoom = () => {\n const progress = Math.min((Date.now() - zoomStartTime) / ZOOM_ANIMATION_DURATION, 1);\n const eased = easeOutCubic(progress);\n setTransform({\n scale: from.scale + (target.scale - from.scale) * eased,\n tx: from.tx + (target.tx - from.tx) * eased,\n ty: from.ty + (target.ty - from.ty) * eased,\n });\n travelRafRef.current = progress < 1 ? requestAnimationFrame(animateZoom) : null;\n };\n travelRafRef.current = requestAnimationFrame(animateZoom);\n\n // Flash fade, in parallel: 1 - p² over the 1500ms window, then complete.\n const flashStartTime = Date.now();\n const animateFlash = () => {\n const progress = Math.min((Date.now() - flashStartTime) / FLASH_DURATION, 1);\n setFlashOpacity(1 - progress * progress);\n if (progress < 1) {\n fadeRafRef.current = requestAnimationFrame(animateFlash);\n } else {\n fadeRafRef.current = null;\n setActiveFlashRects(null);\n setFlashOpacity(0);\n onFlashCompleteRef.current?.();\n }\n };\n fadeRafRef.current = requestAnimationFrame(animateFlash);\n\n return () => {\n cancelFlashTravel();\n if (fadeRafRef.current !== null) {\n cancelAnimationFrame(fadeRafRef.current);\n fadeRafRef.current = null;\n }\n };\n // container is identity-replaced per resize; depend on its values (like\n // the console) so a same-size measurement can't restart a live flash.\n }, [flashRects, natural, container.w, container.h, rotation, cancelFlashTravel]);\n\n // Cursor is the promise of what a drag will do (console ~371-372): zoom-in\n // while the whole page fits (drag is inert; wheel/double-click zooms), grab\n // once zoomed beyond fit, grabbing mid-pan. CSS maps data-cursor to cursors.\n const cursorMode = atFitScale ? 'zoom-in' : isPanning ? 'grabbing' : 'grab';\n\n // Magnifier loupe (console ~380-431), rotation-aware: invert the current\n // transform to find the image point under the pointer, clamp it inside the\n // image, then re-project it at scale × MAG_ZOOM so that point lands at the\n // loupe's center. The inverse map mirrors zoomAtPoint's — inline here just\n // as it is in the console (presentation math, not gesture math). NOT\n // ported: the console's opacity-0 placeholder div for switch-on/pointer-away\n // (~432-448) — nothing visible ever animated on it, pure dead weight. The\n // inner img is bare (no onLoad/onError): wiring the expiry handler here\n // would double-fire onImageExpired for one dying URL.\n let magnifier: React.ReactNode = null;\n if (magnifierOn && showMag && natural && transform.scale > 0) {\n const rad = (rotation * Math.PI) / 180;\n const cosA = Math.cos(rad);\n const sinA = Math.sin(rad);\n const dx = mousePos.x - transform.tx;\n const dy = mousePos.y - transform.ty;\n const cxRaw = (cosA * dx + sinA * dy) / transform.scale;\n const cyRaw = (-sinA * dx + cosA * dy) / transform.scale;\n // Off-image, there is nothing under the pointer to magnify. This USED to\n // clamp the sampled point into [0, natural], which meant the loupe showed\n // the nearest edge of the document as confidently as if it were the spot\n // being pointed at — measured at 340 image px of error one pixel outside\n // the left edge, at fit scale. At fit the image is letterboxed, so that is\n // a large share of the canvas. Inclusive bounds: container x=125 maps to\n // image x=0, and a strict `<` would blink the loupe out along the whole\n // left edge of the document.\n const onImage = cxRaw >= 0 && cyRaw >= 0 && cxRaw <= natural.w && cyRaw <= natural.h;\n const zoomScale = transform.scale * MAG_ZOOM;\n const px = cxRaw * zoomScale;\n const py = cyRaw * zoomScale;\n const rotatedX = px * cosA - py * sinA;\n const rotatedY = px * sinA + py * cosA;\n // MAG_BORDER: the img is absolutely positioned, so it lands against the\n // loupe's PADDING box while this centring is expressed against the border\n // box. See the constant.\n const translateX = MAG_RADIUS - MAG_BORDER - rotatedX;\n const translateY = MAG_RADIUS - MAG_BORDER - rotatedY;\n if (onImage) {\n magnifier = (\n <div\n className=\"gemina-verification__magnifier\"\n style={{\n width: MAG_RADIUS * 2,\n height: MAG_RADIUS * 2,\n top: mousePos.y - MAG_RADIUS,\n left: mousePos.x - MAG_RADIUS,\n }}\n >\n <img\n src={src}\n alt=\"\"\n draggable={false}\n style={{\n position: 'absolute',\n width: natural.w,\n height: natural.h,\n transformOrigin: '0 0',\n transform: `translate(${translateX}px, ${translateY}px) rotate(${rotation}deg) scale(${zoomScale})`,\n }}\n />\n </div>\n );\n }\n }\n\n return (\n <div className=\"gemina-verification__viewer\">\n <div className=\"gemina-verification__toolbar\">\n <ToolbarButton label=\"Zoom out\" onClick={handleZoomOut}>\n <IconZoomOut />\n </ToolbarButton>\n <ToolbarButton label=\"Zoom in\" onClick={handleZoomIn}>\n <IconZoomIn />\n </ToolbarButton>\n <ToolbarButton label=\"Actual size (100%)\" onClick={handleActualSize}>\n <IconActualSize />\n </ToolbarButton>\n <ToolbarButton label=\"Fit to screen\" onClick={handleFit}>\n <IconFit />\n </ToolbarButton>\n <ToolbarButton label=\"Rotate 90 degrees\" onClick={handleRotate}>\n <IconRotate />\n </ToolbarButton>\n <ToolbarButton\n label=\"Toggle detection overlays\"\n pressed={showRects}\n disabled={!hasRects}\n onClick={() => setShowRects((prev) => !prev)}\n >\n <IconOverlay />\n </ToolbarButton>\n <ToolbarButton\n label=\"Magnifier\"\n checked={magnifierOn}\n onClick={() => setMagnifierOn((prev) => !prev)}\n >\n <IconMagnifier />\n </ToolbarButton>\n </div>\n\n <div\n ref={canvasRef}\n className=\"gemina-verification__canvas\"\n data-cursor={cursorMode}\n // One composite picture to AT: the inner <img>, overlay boxes, flash\n // and loupe are all facets of \"the document image\" — announcing each\n // separately would be noise, so the canvas is the labeled image and\n // everything inside is presentational. The host's `alt` prop names\n // THIS label (the inner img's alt is unread by AT here but kept for\n // non-AT contexts: broken-image text, save/copy affordances).\n role=\"img\"\n aria-label={alt ?? 'Document image'}\n onDoubleClick={handleDoubleClick}\n onMouseDown={handleMouseDown}\n onMouseMove={handleCanvasMouseMove}\n onMouseLeave={handleCanvasMouseLeave}\n onTouchStart={handleTouchStart}\n onTouchMove={handleTouchMove}\n onTouchEnd={handleTouchEnd}\n // The browser cancelling a gesture (edge swipe, notification shade)\n // must reset it exactly like a full lift — a stale touchState would\n // make the NEXT touch continue a dead pan/pinch.\n onTouchCancel={handleTouchEnd}\n >\n {/* Canvas geometry (not layout) — inline by design; CSS owns appearance. */}\n <div\n style={{\n position: 'absolute',\n left: transform.tx,\n top: transform.ty,\n transform: `rotate(${rotation}deg) scale(${transform.scale})`,\n transformOrigin: 'top left',\n willChange: 'transform,left,top',\n }}\n >\n <img\n ref={imgRef}\n src={src}\n alt={alt ?? 'Document'}\n draggable={false}\n onLoad={handleImgLoad}\n onError={handleImgError}\n />\n {/* Detection overlays (toggle-controlled, console ~742-792). Index\n keys are stable here: rect arrays are replaced wholesale and the\n boxes are stateless leaves. Geometry inline; appearance in CSS.\n aria-hidden per rect (badge included): the canvas is one labeled\n image to AT — the \"#N\" chips are visual decoration on it. */}\n {showRects &&\n natural &&\n relativeRects?.map((rect, idx) => {\n const geometry = rectGeometry(rect, natural);\n if (!geometry) return null;\n return (\n <div\n key={`rect-${idx}`}\n className=\"gemina-verification__rect\"\n style={geometry}\n aria-hidden=\"true\"\n >\n <span className=\"gemina-verification__rect-badge\">#{idx + 1}</span>\n </div>\n );\n })}\n {/* Flash overlay (temporary, independent of the toggle). Element-level\n opacity is equivalent to the console's per-channel alpha fade\n modulo overlapping-layer compositing — see the __flash-rect\n comment in styles.ts. aria-hidden: purely decorative highlight. */}\n {activeFlashRects &&\n natural &&\n activeFlashRects.map((rect, idx) => {\n const geometry = rectGeometry(rect, natural);\n if (!geometry) return null;\n return (\n <div\n key={`flash-rect-${idx}`}\n className=\"gemina-verification__flash-rect\"\n style={{ ...geometry, opacity: flashOpacity }}\n aria-hidden=\"true\"\n />\n );\n })}\n </div>\n {magnifier}\n </div>\n </div>\n );\n}\n","/**\n * Pure zoom/rotation math for the verification document viewer.\n *\n * Direct ports from the console's viewer\n * (gemina-console/src/components/viewers/ZoomableImageViewer.tsx):\n * fit scale (lines ~142-149), rotated bounding box (~152-172), centered\n * translation (~174-183), scale clamp + zoom-at-point (~198-230), flash-zoom\n * target (~459-509, math portion), easeOutCubic (~523). Bodies must stay\n * behavior-identical so the elements viewer renders pixel-identically to the\n * console's. No DOM, no React.\n */\n\nexport interface Size {\n w: number;\n h: number;\n}\n\nexport interface Transform {\n scale: number;\n tx: number;\n ty: number;\n}\n\n/** Scale that fits a (possibly rotated) natural size into a container.\n * rotationDeg is expected in multiples of 90; other angles fall back to the\n * unrotated box (matching the console). */\nexport function fitScaleFor(natural: Size, container: Size, rotationDeg: number): number {\n const rot = ((rotationDeg % 180) + 180) % 180;\n const w = rot === 90 ? natural.h : natural.w;\n const h = rot === 90 ? natural.w : natural.h;\n const s = Math.min(container.w / w, container.h / h);\n // The console's memo also early-returns 1 when the container has no size;\n // a zero container makes s = 0 here, so this guard yields the same 1.\n return isFinite(s) && s > 0 ? s : 1;\n}\n\n/** Rotated bounding box extents; minX/minY compensate rotation offsets.\n * rotationDeg is expected in multiples of 90; other angles fall back to the\n * unrotated box (matching the console). zoomAtPoint/flashZoomTarget use real\n * trig and work at any angle. */\nexport function rotatedBox(\n natural: Size,\n scale: number,\n rotationDeg: number,\n): { W: number; H: number; minX: number; minY: number } {\n const w0 = natural.w;\n const h0 = natural.h;\n const s = scale;\n const rot = ((rotationDeg % 360) + 360) % 360;\n switch (rot) {\n case 0:\n return { W: w0 * s, H: h0 * s, minX: 0, minY: 0 };\n case 90:\n return { W: h0 * s, H: w0 * s, minX: -h0 * s, minY: 0 };\n case 180:\n return { W: w0 * s, H: h0 * s, minX: -w0 * s, minY: -h0 * s };\n case 270:\n return { W: h0 * s, H: w0 * s, minX: 0, minY: -w0 * s };\n default:\n return { W: w0 * s, H: h0 * s, minX: 0, minY: 0 };\n }\n}\n\n/** Translation that centers the rotated image. */\nexport function centeredTranslation(\n natural: Size,\n container: Size,\n scale: number,\n rotationDeg: number,\n): { tx: number; ty: number } {\n const { W, H, minX, minY } = rotatedBox(natural, scale, rotationDeg);\n const nx = (container.w - W) / 2 - minX;\n const ny = (container.h - H) / 2 - minY;\n return { tx: nx, ty: ny };\n}\n\nexport function clampScale(s: number, fitScale: number, max = 8): number {\n return Math.max(fitScale, Math.min(max, s));\n}\n\n/** New transform after zooming by `factor` anchored at container point (px,py). */\nexport function zoomAtPoint(\n current: Transform,\n factor: number,\n px: number,\n py: number,\n rotationDeg: number,\n fitScale: number,\n): Transform {\n const { scale, tx, ty } = current;\n const newScale = clampScale(scale * factor, fitScale);\n if (newScale === scale) return current;\n\n const rad = (rotationDeg * Math.PI) / 180;\n const cosA = Math.cos(rad);\n const sinA = Math.sin(rad);\n\n const dx = px - tx;\n const dy = py - ty;\n const cx = (cosA * dx + sinA * dy) / scale;\n const cy = (-sinA * dx + cosA * dy) / scale;\n\n const ntx = px - (cosA * (newScale * cx) - sinA * (newScale * cy));\n const nty = py - (sinA * (newScale * cx) + cosA * (newScale * cy));\n\n return { scale: newScale, tx: ntx, ty: nty };\n}\n\n/** Target transform for the flash-zoom travel: center the rects' bbox at a\n * comfortable size (100px target, scale clamped to [fitScale, 1.8]). */\nexport function flashZoomTarget(\n rects: Array<{ points: [number, number][] }>,\n natural: Size,\n container: Size,\n rotationDeg: number,\n fitScale: number,\n): Transform {\n // Calculate bounding box of all flash rects (in relative coords 0-1)\n let minX = 1,\n minY = 1,\n maxX = 0,\n maxY = 0;\n for (const rect of rects) {\n for (const [px, py] of rect.points) {\n minX = Math.min(minX, px);\n minY = Math.min(minY, py);\n maxX = Math.max(maxX, px);\n maxY = Math.max(maxY, py);\n }\n }\n\n // Calculate center of the bounding box in image pixel coordinates\n const centerX = ((minX + maxX) / 2) * natural.w;\n const centerY = ((minY + maxY) / 2) * natural.h;\n const bboxWidth = (maxX - minX) * natural.w;\n const bboxHeight = (maxY - minY) * natural.h;\n\n // Calculate target zoom level from a FIXED baseline (not current zoom)\n // Goal: make the field a comfortable, consistent size on screen\n const rad = (rotationDeg * Math.PI) / 180;\n const cosA = Math.cos(rad);\n const sinA = Math.sin(rad);\n\n // Target: make the bbox render at approximately this size\n const TARGET_RENDERED_SIZE = 100; // pixels - comfortable reading size\n\n // Calculate scale needed to render bbox at target size\n // Use the larger dimension to determine scale (so it fits nicely)\n const largerDimension = Math.max(bboxWidth, bboxHeight);\n const scaleForTargetSize = largerDimension > 0 ? TARGET_RENDERED_SIZE / largerDimension : 1;\n\n // Clamp: at least fitScale (don't zoom out), at most 1.8x (reasonable max)\n const targetScale = Math.max(fitScale, Math.min(scaleForTargetSize, 1.8));\n\n // Calculate target position to center on the field\n const newScreenX = cosA * centerX * targetScale - sinA * centerY * targetScale;\n const newScreenY = sinA * centerX * targetScale + cosA * centerY * targetScale;\n const targetTx = container.w / 2 - newScreenX;\n const targetTy = container.h / 2 - newScreenY;\n\n return { scale: targetScale, tx: targetTx, ty: targetTy };\n}\n\n// Ease out cubic for smooth deceleration\nexport const easeOutCubic = (t: number): number => 1 - Math.pow(1 - t, 3);\n","import { VERSION } from '../version';\n\n// --- Styles -----------------------------------------------------------------\n// Hand-rolled, no UI deps. Everything is scoped under .gemina-verification and\n// driven by CSS custom properties so host apps can re-theme without touching\n// the DOM. The palette and rhythm deliberately match the chat widget\n// (chat.tsx) so both widgets read as one product when embedded side by side.\n//\n// Design intent: a focused reviewing tool. Document viewer on one pane, form\n// on the other; quiet neutral surfaces everywhere; the confidence dots are the\n// only saturated color in the form, and the overlay blue is reserved for the\n// document canvas. Values are set in tabular numerals so amounts line up with\n// the scanned document the reviewer is comparing them against.\n//\n// Layout uses logical properties exclusively (margin-inline-*, padding-inline,\n// border-block-*) so RTL works for free. Physical left/top appear only inside\n// the viewer canvas, where later tasks position geometry inline from JS —\n// that is geometry, not layout.\n\nconst DARK_VARS = `\n --gemina-verification-bg: #101418;\n --gemina-verification-fg: #e6e9ee;\n --gemina-verification-border: #2a323c;\n --gemina-verification-accent: #4c8dff;\n --gemina-verification-accent-fg: #ffffff;\n --gemina-verification-surface: #1c232b;\n --gemina-verification-muted: #98a2b3;\n --gemina-verification-error: #f97066;\n --gemina-verification-input-bg: #12171d;\n --gemina-verification-input-border: #2a323c;\n --gemina-verification-dirty: #f7b27a;\n`;\n\nconst VERIFICATION_CSS = `\n.gemina-verification {\n --gemina-verification-bg: #ffffff;\n --gemina-verification-fg: #1a1d21;\n --gemina-verification-border: #d9dce1;\n --gemina-verification-accent: #2f6fed;\n --gemina-verification-accent-fg: #ffffff;\n --gemina-verification-surface: #f2f4f7;\n --gemina-verification-muted: #667085;\n --gemina-verification-error: #b42318;\n --gemina-verification-input-bg: #ffffff;\n --gemina-verification-input-border: #d0d5e2;\n --gemina-verification-dirty: #b54708;\n --gemina-verification-confidence-high: #52c41a;\n --gemina-verification-confidence-medium: #faad14;\n --gemina-verification-confidence-low: #ff4d4f;\n --gemina-verification-confidence-unknown: #d9d9d9;\n --gemina-verification-overlay-rgb: 24, 144, 255;\n --gemina-verification-radius: 10px;\n --gemina-verification-font: system-ui, -apple-system, \"Segoe UI\", Roboto, sans-serif;\n\n box-sizing: border-box;\n position: relative; /* anchors __confirm; never overflow:hidden here — it would break the stacked sticky viewer */\n display: flex;\n flex-direction: column;\n gap: 16px;\n padding: 16px;\n background: var(--gemina-verification-bg);\n color: var(--gemina-verification-fg);\n border: 1px solid var(--gemina-verification-border);\n border-radius: var(--gemina-verification-radius);\n font-family: var(--gemina-verification-font);\n font-size: 14px;\n line-height: 1.5;\n}\n.gemina-verification *, .gemina-verification *::before, .gemina-verification *::after { box-sizing: border-box; }\n.gemina-verification--dark { ${DARK_VARS} }\n@media (prefers-color-scheme: dark) {\n .gemina-verification--auto { ${DARK_VARS} }\n}\n.gemina-verification--rtl { direction: rtl; }\n/* Content is not chrome: the document pane never mirrors (industry rule —\n images/players/clocks keep their physical position under RTL), and dir=\"auto\"\n flips per DOCUMENT, so mirroring would make the image jump side per row.\n Forcing the grid container LTR pins physical order (image inline-left, form\n right, every language); the form pane alone restores RTL so Hebrew labels\n and values keep their natural direction (per-input dir=\"auto\" still handles\n mixed-language values). The viewer subtree deliberately stays LTR: it is\n pure geometry (scroll math, loupe projection, absolute positioning) and none\n of that math may be direction-dependent.\n\n That last point is not theoretical — it IS the magnifier bug. The loupe's\n magnified inner layer is absolutely positioned with no inset (viewer.tsx\n gives it only a transform), so its static position is wherever the inherited\n direction puts the inline start. Under RTL that flips to the right edge and\n the layer lands (layerWidth - loupeWidth) away — measured as a constant\n -704px skew in BOTH chromium and firefox, at every pointer position, leaving\n the user an empty circle rather than a shifted one. Pinning this subtree LTR\n restores the skew to (0, 0), matching the LTR baseline exactly. Do not\n \"simplify\" this by mirroring the panes again. */\n.gemina-verification--rtl .gemina-verification__panes { direction: ltr; }\n.gemina-verification--rtl .gemina-verification__form { direction: rtl; }\n\n/* --- Two-pane layout ------------------------------------------------------ */\n.gemina-verification__panes {\n display: grid;\n grid-template-columns: minmax(0, 1fr) minmax(0, 1fr);\n gap: 16px;\n}\n.gemina-verification--stacked .gemina-verification__panes {\n /* Flex column, NOT a one-column grid: a sticky GRID item is confined to its\n own grid area — whose auto row is exactly its own height, leaving zero\n travel — while a sticky FLEX child's containing block is the whole panes\n box, so the viewer genuinely floats over the form as it scrolls. The gap\n carries over from the base rule. */\n display: flex;\n flex-direction: column;\n}\n.gemina-verification--stacked .gemina-verification__viewer {\n position: sticky;\n top: 0; /* block axis, not inline — RTL-safe */\n z-index: 2;\n /* Cap AND height in one declaration: the canvas is absolutely-positioned\n geometry with no intrinsic height (it contributes only its min-height),\n so a max-block-size alone would never bind — the explicit block-size is\n what the canvas fills. 48vh keeps the majority of a short viewport for\n the form the reviewer is working through; 420px stops a tall narrow\n window from devoting a huge sticky band to the document. The dvh line\n wins where supported (mobile browser chrome shrinks the visual viewport). */\n flex: 0 0 auto;\n block-size: min(48vh, 420px);\n block-size: min(48dvh, 420px);\n}\n.gemina-verification--stacked .gemina-verification__canvas {\n /* The stacked cap owns the height; the side-by-side 280px floor would\n overflow it on short viewports (48vh of a 568px screen is ~273px). */\n min-height: 120px;\n}\n\n/* --- Document viewer ------------------------------------------------------ */\n.gemina-verification__viewer {\n display: flex;\n flex-direction: column;\n min-width: 0;\n background: var(--gemina-verification-bg);\n border: 1px solid var(--gemina-verification-border);\n border-radius: var(--gemina-verification-radius);\n /* overflow hidden creates a scroll container and prevents the toolbar's sticky\n positioning from following the host modal's scrollport. Clip keeps the\n rounded frame without stealing sticky containment. */\n overflow: clip;\n}\n.gemina-verification__toolbar {\n position: sticky;\n top: 0;\n z-index: 5;\n display: flex;\n /* Narrow roots (~<330px) can't fit all 7 buttons on one line: wrap to a\n second row instead of clipping past the canvas edge. The gap shorthand\n below already provides the 6px row-gap between wrapped rows. */\n flex-wrap: wrap;\n align-items: center;\n gap: 6px;\n flex: 0 0 auto;\n padding: 8px 10px;\n background: var(--gemina-verification-bg);\n border-block-end: 1px solid var(--gemina-verification-border);\n}\n.gemina-verification__toolbar-btn {\n font: inherit;\n font-size: 12px;\n padding: 4px 10px;\n border-radius: calc(var(--gemina-verification-radius) - 4px);\n border: 1px solid var(--gemina-verification-border);\n background: transparent;\n color: var(--gemina-verification-fg);\n cursor: pointer;\n transition: border-color 120ms ease, background-color 120ms ease, color 120ms ease;\n}\n.gemina-verification__toolbar-btn svg { display: block; } /* no inline-baseline slack under the icons */\n.gemina-verification__toolbar-btn:hover:not(:disabled) { border-color: var(--gemina-verification-accent); }\n.gemina-verification__toolbar-btn:disabled { opacity: 0.5; cursor: default; }\n.gemina-verification__toolbar-btn--active {\n background: var(--gemina-verification-accent);\n border-color: var(--gemina-verification-accent);\n color: var(--gemina-verification-accent-fg);\n}\n.gemina-verification__canvas {\n position: relative;\n flex: 1;\n min-height: 280px;\n overflow: hidden;\n background: var(--gemina-verification-surface);\n touch-action: none;\n cursor: zoom-in; /* initial truth: at fit a drag is inert, wheel/dblclick zooms */\n user-select: none;\n -webkit-user-select: none;\n}\n/* Cursor is the promise of what a drag will do, so it follows viewer state\n (data-cursor), never :active — a bare :active rule would claim \"grabbing\"\n at fit scale where pan never engages. */\n.gemina-verification__canvas[data-cursor='zoom-in'] { cursor: zoom-in; }\n.gemina-verification__canvas[data-cursor='grab'] { cursor: grab; }\n.gemina-verification__canvas[data-cursor='grabbing'] { cursor: grabbing; }\n/* The document image is geometry, not layout: a block box at natural size,\n positioned purely by the JS transform layer above it. */\n.gemina-verification__canvas img {\n display: block;\n max-width: unset;\n max-height: unset;\n}\n/* Overlay geometry (left/top/width/height) is set inline by the viewer from\n transform math; CSS owns only the appearance. */\n.gemina-verification__rect {\n position: absolute;\n z-index: 2;\n pointer-events: none;\n border: 2px solid rgba(var(--gemina-verification-overlay-rgb), 0.85);\n background: rgba(var(--gemina-verification-overlay-rgb), 0.16);\n border-radius: 2px;\n}\n/* Numbered \"#1\" chip on each overlay rect. Physical left/top: the badge lives\n in image coordinate space inside the transform layer (geometry, not layout),\n so it scales and rotates with the document exactly like the console's.\n Explicit line-height pins the chip height across host font stacks. */\n.gemina-verification__rect-badge {\n position: absolute;\n top: -18px;\n left: 0;\n font-size: 11px;\n font-weight: 600;\n line-height: 16px;\n color: rgb(var(--gemina-verification-overlay-rgb));\n background: rgba(255, 255, 255, 0.92); /* floats over the document, not the theme surface */\n padding: 0 6px;\n border-radius: 12px;\n box-shadow: 0 1px 4px rgba(0, 0, 0, 0.16);\n pointer-events: none;\n}\n.gemina-verification__flash-rect {\n /* Fade is driven by JS via element-level opacity (rAF travel animation);\n no CSS animation here so the two never fight. Element-level opacity is\n equivalent to the console's per-channel fade — border (1·o), background\n (0.25·o), glow (0.6·o / 0.3·o) — modulo overlapping-layer compositing:\n per-channel alphas blend border-over-background where they overlap,\n element opacity flattens the group first. Indistinguishable in practice. */\n position: absolute;\n z-index: 3;\n pointer-events: none;\n border: 5px solid rgba(var(--gemina-verification-overlay-rgb), 1);\n background: rgba(var(--gemina-verification-overlay-rgb), 0.25);\n box-shadow: 0 0 20px rgba(var(--gemina-verification-overlay-rgb), 0.6),\n inset 0 0 10px rgba(var(--gemina-verification-overlay-rgb), 0.3);\n border-radius: 2px;\n}\n.gemina-verification__magnifier {\n position: absolute;\n z-index: 4;\n pointer-events: none;\n overflow: hidden;\n border-radius: 50%;\n border: 2px solid rgba(255, 255, 255, 0.85);\n box-shadow: 0 2px 12px rgba(0, 0, 0, 0.35);\n background: var(--gemina-verification-surface);\n}\n\n/* --- Form pane ------------------------------------------------------------ */\n/* A real <form> element (labeled AT landmark) — margin reset guards against\n host/UA form margins. */\n.gemina-verification__form {\n display: flex;\n flex-direction: column;\n gap: 12px;\n min-width: 0;\n margin: 0;\n /* Every z-index inside the form is form-internal business, and nothing in\n here may ever paint over the document. Without a stacking context of its\n own, the form's descendants resolve against the SAME context as the\n stacked-mode viewer (position: sticky, z-index: 2) — so the sticky header\n row (z-index: 3) painted straight over the document image as the form\n scrolled under the floating viewer. Confirmed in chromium and firefox\n before this line existed. Isolating caps the whole subtree beneath the\n viewer no matter what numbers it uses later. */\n isolation: isolate;\n}\n.gemina-verification__confidence-summary {\n display: flex;\n align-items: center;\n justify-content: space-between;\n gap: 12px;\n padding: 9px 12px;\n background: var(--gemina-verification-surface);\n border: 1px solid var(--gemina-verification-border);\n border-radius: var(--gemina-verification-radius);\n color: var(--gemina-verification-muted);\n font-size: 12px;\n font-weight: 600;\n}\n.gemina-verification__section {\n background: var(--gemina-verification-bg);\n border: 1px solid var(--gemina-verification-border);\n border-radius: var(--gemina-verification-radius);\n overflow: hidden;\n}\n.gemina-verification__section-header {\n display: flex;\n align-items: center;\n gap: 8px;\n padding: 8px 12px;\n background: var(--gemina-verification-surface);\n border-block-end: 1px solid var(--gemina-verification-border);\n font-size: 13px;\n font-weight: 600;\n}\n.gemina-verification__overall-confidence {\n display: inline-flex;\n align-items: center;\n gap: 6px;\n margin-inline-start: auto;\n color: var(--gemina-verification-muted);\n font-size: 11px;\n font-weight: 500;\n white-space: nowrap;\n}\n.gemina-verification__dl {\n display: grid;\n grid-template-columns: minmax(0, 2fr) minmax(0, 3fr);\n column-gap: 12px;\n margin: 0;\n padding: 8px 12px;\n}\n.gemina-verification__dt {\n display: flex;\n align-items: center;\n gap: 6px;\n padding-block: 5px;\n min-width: 0;\n font-size: 12px;\n color: var(--gemina-verification-muted);\n overflow-wrap: break-word;\n}\n.gemina-verification__dd {\n display: flex;\n /* Wrap so a field error takes its OWN line (it sets flex-basis:100%).\n Without this it competes with the input for width, and at 390px the\n message wrapped to one word per line while the input shrank to ~55px. */\n flex-wrap: wrap;\n align-items: center;\n gap: 6px;\n margin: 0; /* resets the UA's margin-inline-start on <dd> */\n padding-block: 5px;\n min-width: 0;\n font-size: 13px;\n font-variant-numeric: tabular-nums;\n overflow-wrap: break-word;\n}\n.gemina-verification__input {\n width: 100%;\n font: inherit;\n font-size: 13px;\n color: var(--gemina-verification-fg);\n background: var(--gemina-verification-input-bg);\n border: 1px solid var(--gemina-verification-input-border);\n border-radius: calc(var(--gemina-verification-radius) - 4px);\n padding: 5px 8px;\n}\n/* FieldInput is a fragment. Let its control take the remaining row width\n instead of forcing width:100%, so a coordinate eye can sit beside it rather\n than wrapping onto a visually disconnected second line. */\n.gemina-verification__dd > .gemina-verification__input,\n.gemina-verification__cell > .gemina-verification__input {\n flex: 1 1 8ch;\n width: auto;\n min-width: 0;\n}\n.gemina-verification__input--dirty { border-color: var(--gemina-verification-dirty); }\n.gemina-verification__input--missed {\n border-color: var(--gemina-verification-error);\n box-shadow: 0 0 0 1px var(--gemina-verification-error);\n}\n/* Non-color dirty channel: the word itself is the signal (WCAG 1.4.1) — it\n stays legible when --missed's error border overrides the dirty border. */\n.gemina-verification__edited {\n flex: 0 0 auto;\n font-size: 10px;\n font-weight: 600;\n letter-spacing: 0.06em;\n text-transform: uppercase;\n color: var(--gemina-verification-dirty);\n}\n.gemina-verification__dot {\n display: inline-block;\n flex: 0 0 auto;\n width: 8px;\n height: 8px;\n border-radius: 50%;\n background: var(--gemina-verification-confidence-unknown);\n}\n.gemina-verification__dot--high { background: var(--gemina-verification-confidence-high); }\n.gemina-verification__dot--medium { background: var(--gemina-verification-confidence-medium); }\n.gemina-verification__dot--low { background: var(--gemina-verification-confidence-low); }\n.gemina-verification__dot--unknown { background: var(--gemina-verification-confidence-unknown); }\n.gemina-verification__eye {\n display: inline-flex;\n align-items: center;\n justify-content: center;\n flex: 0 0 auto;\n width: 24px;\n height: 24px;\n padding: 0;\n border: 0;\n border-radius: calc(var(--gemina-verification-radius) - 4px);\n background: transparent;\n color: var(--gemina-verification-muted);\n cursor: pointer;\n transition: background-color 120ms ease, color 120ms ease;\n}\n.gemina-verification__eye:hover {\n color: var(--gemina-verification-accent);\n background: var(--gemina-verification-surface);\n}\n\n/* --- Tables and cards ----------------------------------------------------- */\n/* Section content that is not flush with the section frame (cards, fallback\n details) sits inside this padded body. */\n.gemina-verification__section-body { padding: 8px 12px; }\n/* Flex row for FieldInput's fragment (input + \"edited\" badge) inside <td>s\n and list items — the fragment has no container of its own. */\n.gemina-verification__cell {\n display: flex;\n flex-wrap: wrap; /* same reason as __dd: the field error needs its own line */\n align-items: center;\n gap: 6px;\n min-width: 0;\n}\n/* Simple-list items stack inside a __dd; each item row is a __cell. */\n.gemina-verification__list {\n display: flex;\n flex-direction: column;\n gap: 4px;\n flex: 1 1 auto;\n min-width: 0;\n margin: 0;\n padding: 0;\n list-style: none;\n}\n.gemina-verification__table-wrap {\n overflow-x: auto;\n /* Sticky binds to the nearest scrollport, and in an embedded widget that\n must be THIS wrapper (no per-host offset math). Bounding the block size\n turns it into a vertical scrollport too: long tables scroll internally\n with the header row pinned; short tables never reach the cap and are\n unchanged. */\n overflow-y: auto;\n max-block-size: min(56vh, 520px);\n}\n.gemina-verification__table {\n width: 100%;\n /* separate, not collapse: collapsed borders belong to the row grid, so a\n stuck header sheds its underline mid-scroll. With separate borders the\n border-block-end travels with the th. */\n border-collapse: separate;\n border-spacing: 0;\n font-size: 13px;\n font-variant-numeric: tabular-nums;\n}\n.gemina-verification__table th {\n position: sticky;\n inset-block-start: 0;\n /* Above cell content and focus rings; below the viewer toolbar (5) and the\n confirm scrim. */\n z-index: 3;\n text-align: start;\n padding: 6px 10px;\n font-size: 12px;\n font-weight: 600;\n color: var(--gemina-verification-muted);\n background: var(--gemina-verification-surface);\n border-block-end: 1px solid var(--gemina-verification-border);\n}\n.gemina-verification__table td {\n padding: 6px 10px;\n vertical-align: top;\n border-block-end: 1px solid var(--gemina-verification-border);\n}\n.gemina-verification__table tr:last-child td { border-block-end: 0; }\n/* Wide tables lean on __table-wrap's scroll; the clamp keeps a cell input\n usable instead of letting the table squeeze it to nothing. */\n.gemina-verification__table .gemina-verification__input { min-width: 6ch; }\n.gemina-verification__card {\n display: flex;\n flex-direction: column;\n gap: 6px;\n padding: 10px 12px;\n background: var(--gemina-verification-bg);\n border: 1px solid var(--gemina-verification-border);\n border-radius: calc(var(--gemina-verification-radius) - 4px);\n}\n.gemina-verification__card + .gemina-verification__card { margin-block-start: 8px; }\n.gemina-verification__card-header {\n font-size: 12px;\n font-weight: 600;\n color: var(--gemina-verification-muted);\n}\n/* The card already pads; its inner description list must not double it. */\n.gemina-verification__card .gemina-verification__dl { padding: 0; }\n/* Fallback blobs are a native <details>: summary is the toggle, the JSON\n lives in a <pre> so only the code is monospace/pre-wrapped. */\n.gemina-verification__fallback {\n margin: 0;\n padding: 8px 12px;\n font-size: 12px;\n background: var(--gemina-verification-surface);\n border-radius: calc(var(--gemina-verification-radius) - 4px);\n}\n.gemina-verification__fallback + .gemina-verification__fallback { margin-block-start: 8px; }\n.gemina-verification__fallback summary {\n cursor: pointer;\n font-weight: 600;\n user-select: none;\n}\n.gemina-verification__fallback pre {\n margin: 0;\n margin-block-start: 8px;\n font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;\n white-space: pre-wrap;\n overflow-wrap: break-word;\n overflow-x: auto;\n}\n\n/* --- Messaging, progress, actions ----------------------------------------- */\n.gemina-verification__banner {\n padding: 10px 12px;\n font-size: 13px;\n background: var(--gemina-verification-surface);\n border: 1px solid var(--gemina-verification-border);\n border-radius: var(--gemina-verification-radius);\n}\n.gemina-verification__banner--error {\n background: transparent;\n border-color: var(--gemina-verification-error);\n color: var(--gemina-verification-error);\n}\n.gemina-verification__progress {\n font-size: 12px;\n color: var(--gemina-verification-muted);\n font-variant-numeric: tabular-nums;\n /* The counts copy (\"N confirmed · M corrected\") is untranslated English\n chrome; under dir=\"rtl\" the RTL paragraph direction reorders its\n leading-number run (\"confirmed · 0 corrected 7\"). plaintext makes the\n line take its base direction from its own first strong character, so\n the English copy lays out LTR inside the RTL widget. The done-state\n recap reuses this same class, so it is covered too. */\n unicode-bidi: plaintext;\n}\n.gemina-verification__footer {\n display: flex;\n /* Wraps because the review filter adds two more items to this row, and at\n 320 the four together overflow: Submit was pushed 28px past the inline\n start and clipped. Measured RTL, where the overflow runs the other way\n and a scrollWidth-minus-clientWidth check on the document never sees it. */\n flex-wrap: wrap;\n align-items: center;\n gap: 10px;\n padding-block-start: 12px;\n border-block-start: 1px solid var(--gemina-verification-border);\n}\n.gemina-verification__footer .gemina-verification__submit { margin-inline-start: auto; }\n.gemina-verification__submit {\n font: inherit;\n border: none;\n border-radius: var(--gemina-verification-radius);\n background: var(--gemina-verification-accent);\n color: var(--gemina-verification-accent-fg);\n padding: 8px 16px;\n cursor: pointer;\n}\n.gemina-verification__submit:disabled { opacity: 0.5; cursor: default; }\n/* The review filter is a VIEW MODE, not an action, so it stays quiet: an\n outline control in the muted color, next to the one loud thing in the\n footer. Turning it on fills it from the same accent token — the state has\n to be unmistakable, because the form is hiding content while it is on. */\n.gemina-verification__review-filter {\n font: inherit;\n font-size: 12px;\n padding: 4px 12px;\n border-radius: var(--gemina-verification-radius);\n border: 1px solid var(--gemina-verification-border);\n background: transparent;\n color: var(--gemina-verification-muted);\n cursor: pointer;\n}\n.gemina-verification__review-filter:hover {\n color: var(--gemina-verification-accent);\n border-color: var(--gemina-verification-accent);\n}\n.gemina-verification__review-filter[aria-checked='true'] {\n background: var(--gemina-verification-accent);\n border-color: var(--gemina-verification-accent);\n color: var(--gemina-verification-accent-fg);\n}\n/* Stands in for a table's grid when every row of it scored high. Muted and\n unemphatic on purpose — it reports an absence, it is not a finding. */\n.gemina-verification__filter-count {\n font-size: 12px;\n color: var(--gemina-verification-muted);\n}\n.gemina-verification__filter-note {\n font-size: 12px;\n color: var(--gemina-verification-muted);\n}\n.gemina-verification__all-scored {\n margin: 0;\n padding: 12px;\n color: var(--gemina-verification-muted);\n font-size: 13px;\n}\n.gemina-verification__retry {\n font: inherit;\n font-size: 12px;\n padding: 2px 10px;\n border-radius: var(--gemina-verification-radius);\n border: 1px solid var(--gemina-verification-error);\n background: transparent;\n color: var(--gemina-verification-error);\n cursor: pointer;\n}\n.gemina-verification__state {\n display: flex;\n flex-direction: column;\n align-items: center;\n justify-content: center;\n gap: 8px;\n min-height: 220px;\n padding: 24px;\n text-align: center;\n font-size: 13px;\n color: var(--gemina-verification-muted);\n}\n/* Submit-error banner: message + inline Retry on one line. */\n.gemina-verification__submit-error {\n display: flex;\n align-items: center;\n justify-content: space-between;\n gap: 10px;\n}\n/* Done: the one saturated moment outside the form — a single accent check. */\n.gemina-verification__state--done { color: var(--gemina-verification-fg); }\n/* Programmatic focus landing (tabIndex -1), not an interactive control: no\n ring — the accent check IS the visual landing; focus moves here purely so\n keyboard/AT users don't drop to <body> when the dialog unmounts. */\n.gemina-verification__state--done:focus,\n.gemina-verification__state--done:focus-visible { outline: none; }\n.gemina-verification__done-check {\n display: flex;\n align-items: center;\n justify-content: center;\n width: 40px;\n height: 40px;\n border-radius: 50%;\n background: var(--gemina-verification-accent);\n color: var(--gemina-verification-accent-fg);\n}\n.gemina-verification__done-title {\n font-size: 14px;\n font-weight: 600;\n}\n.gemina-verification__state--done .gemina-verification__progress { font-size: 13px; }\n\n/* --- Confirm dialog ------------------------------------------------------- */\n.gemina-verification__confirm {\n position: absolute;\n inset: 0;\n z-index: 10;\n display: flex;\n /* flex-start + a sticky dialog: the scrim spans the whole component, but the\n dialog slides with the page so it is in view even when the user is\n scrolled deep into a long stacked form. Sticky (not fixed) so it survives\n transformed-ancestor hosts where fixed re-anchors. */\n align-items: flex-start;\n justify-content: center;\n padding: 16px;\n background: rgba(16, 20, 24, 0.45);\n border-radius: var(--gemina-verification-radius);\n}\n.gemina-verification__confirm-dialog {\n position: sticky;\n top: 20vh; /* block axis — RTL-safe */\n display: flex;\n flex-direction: column;\n gap: 12px;\n width: 100%;\n max-width: 380px;\n padding: 16px;\n background: var(--gemina-verification-bg);\n color: var(--gemina-verification-fg);\n border: 1px solid var(--gemina-verification-border);\n border-radius: var(--gemina-verification-radius);\n box-shadow: 0 12px 32px rgba(16, 20, 24, 0.24);\n}\n.gemina-verification__confirm-text {\n margin: 0;\n font-size: 13px;\n}\n.gemina-verification__confirm-actions {\n display: flex;\n justify-content: flex-end;\n gap: 8px;\n}\n/* Quiet counterpart to __submit: same geometry, bordered, no fill — the\n accent stays on the final action. */\n.gemina-verification__confirm-cancel {\n font: inherit;\n padding: 8px 16px;\n border: 1px solid var(--gemina-verification-border);\n border-radius: var(--gemina-verification-radius);\n background: transparent;\n color: var(--gemina-verification-fg);\n cursor: pointer;\n transition: border-color 120ms ease;\n}\n.gemina-verification__confirm-cancel:hover:not(:disabled) {\n border-color: var(--gemina-verification-accent);\n}\n.gemina-verification__confirm-cancel:disabled { opacity: 0.5; cursor: default; }\n\n/* --- Focus ---------------------------------------------------------------- */\n.gemina-verification__input:focus-visible {\n outline: 2px solid var(--gemina-verification-accent);\n outline-offset: -1px;\n}\n.gemina-verification__toolbar-btn:focus-visible,\n.gemina-verification__eye:focus-visible,\n.gemina-verification__submit:focus-visible,\n.gemina-verification__retry:focus-visible,\n.gemina-verification__confirm-cancel:focus-visible,\n.gemina-verification__fallback summary:focus-visible {\n outline: 2px solid var(--gemina-verification-accent);\n outline-offset: 1px;\n}\n\n/* --- Reduced motion -------------------------------------------------------- */\n/* The viewer also checks this in JS before animating; the CSS block is the\n backstop that stills the canvas (flash, travel, micro-transitions). */\n@media (prefers-reduced-motion: reduce) {\n .gemina-verification__flash-rect,\n .gemina-verification__rect,\n .gemina-verification__canvas,\n .gemina-verification__canvas * {\n animation: none;\n transition: none;\n }\n}\n\n/* A label that carries a description. Dotted underline is the long-standing\n convention for \"there is more here\", and tabIndex makes it reachable, so the\n tooltip is not mouse-only. */\n.gemina-verification__label-described {\n text-decoration: underline dotted;\n text-underline-offset: 3px;\n cursor: help;\n}\n.gemina-verification__label-described:focus-visible {\n outline: 2px solid var(--gemina-verification-accent);\n outline-offset: 2px;\n}\n\n/* Rows worth a second look. Uses the EXISTING confidence tokens — no new\n colours — as a start-edge rule, which is the one edge a reviewer scans down\n a long table. Logical property, so it lands on the right side under RTL. */\n.gemina-verification__row--low > td:first-child,\n.gemina-verification__row--medium > td:first-child {\n border-inline-start: 3px solid transparent;\n}\n.gemina-verification__row--low > td:first-child {\n border-inline-start-color: var(--gemina-verification-confidence-low);\n}\n.gemina-verification__row--medium > td:first-child {\n border-inline-start-color: var(--gemina-verification-confidence-medium);\n}\n\n/* --- Row editing ----------------------------------------------------------\n Quiet by design: adding and removing lines is a correction, not the primary\n action, so the controls stay muted until hovered and the accent is left to\n Submit. */\n.gemina-verification__row-actions {\n white-space: nowrap;\n text-align: end; /* logical — RTL for free */\n}\n.gemina-verification__row-btn {\n font: inherit;\n line-height: 1;\n padding: 2px 7px;\n margin-inline-start: 4px;\n border-radius: calc(var(--gemina-verification-radius) - 5px);\n border: 1px solid var(--gemina-verification-border);\n background: transparent;\n color: var(--gemina-verification-muted);\n cursor: pointer;\n transition: border-color 120ms ease, color 120ms ease;\n}\n.gemina-verification__row-btn:hover {\n border-color: var(--gemina-verification-accent);\n color: var(--gemina-verification-fg);\n}\n.gemina-verification__table-footer {\n display: flex;\n padding: 8px 10px;\n}\n.gemina-verification__add-row {\n font: inherit;\n font-size: 12px;\n padding: 4px 10px;\n border-radius: calc(var(--gemina-verification-radius) - 4px);\n border: 1px dashed var(--gemina-verification-border);\n background: transparent;\n color: var(--gemina-verification-muted);\n cursor: pointer;\n}\n.gemina-verification__add-row:hover {\n border-style: solid;\n border-color: var(--gemina-verification-accent);\n color: var(--gemina-verification-fg);\n}\n\n/* --- Typed controls -------------------------------------------------------\n A <select> for a closed roster must sit on the same baseline as the text\n inputs beside it in a table row, so it inherits the input's box entirely and\n only overrides what a select needs. */\n.gemina-verification__input:is(select) {\n cursor: pointer;\n /* A select's intrinsic width follows its longest option — the 24-member unit\n roster would blow out the column. */\n max-width: 100%;\n}\n/* The error border must beat --dirty and --missed: an invalid value is the\n most urgent thing true about the field, and the reviewer cannot submit\n until it is fixed. Placed after both for cascade order. */\n.gemina-verification__input--invalid,\n.gemina-verification__input--invalid:focus-visible {\n border-color: var(--gemina-verification-error);\n}\n/* Sits under the control it describes. Basis 100% breaks it onto its own line\n inside the flex row FieldInput renders into, so it never squeezes the\n input. */\n.gemina-verification__field-error {\n flex-basis: 100%;\n margin-block-start: 4px;\n color: var(--gemina-verification-error);\n font-size: 12px;\n line-height: 1.35;\n}\n\n/* Replaces __progress while anything is invalid — same slot, so the footer\n never grows a second status line competing for the same attention. */\n.gemina-verification__attention {\n color: var(--gemina-verification-error);\n font-size: 13px;\n}\n\n/* --- Tooltip -------------------------------------------------------------\n Renders in a portal on document.body, inside a div carrying the root's\n class list — so these rules and every --gemina-verification-* custom\n property resolve exactly as they do in the component.\n\n Quieter than __confirm-dialog on purpose: an annotation, not a decision.\n Same border and shadow family, one step down in radius (the nested-element\n convention used by __chip et al), surface rather than bg so it separates\n from the panel it floats over, and a shorter shadow so it reads as sitting\n just above the page rather than over a scrim. */\n.gemina-verification__tip {\n position: fixed;\n z-index: 2147483000; /* above the host's own modal — this is the topmost layer */\n max-width: 260px; /* ~60 characters: past that a tooltip should be body copy */\n padding: 8px 10px;\n background: var(--gemina-verification-surface);\n color: var(--gemina-verification-fg);\n border: 1px solid var(--gemina-verification-border);\n border-radius: calc(var(--gemina-verification-radius) - 4px);\n box-shadow: 0 6px 16px rgba(16, 20, 24, 0.18);\n font-family: var(--gemina-verification-font);\n font-size: 12px;\n line-height: 1.45;\n text-align: start; /* logical — RTL for free */\n pointer-events: none; /* never eat the hover that opened it */\n}\n/* Structured content: a level heading over a reasons list. The list is the\n reason this exists at all — title= could only ever have been one line. */\n.gemina-verification__tip-title {\n display: block;\n font-weight: 600;\n margin-block-end: 4px;\n}\n.gemina-verification__tip-list {\n margin: 0;\n padding-inline-start: 16px;\n}\n.gemina-verification__tip-list li + li {\n margin-block-start: 2px;\n}\n/* A muted lead-in for single-fact tips (\"Was:\"), so the VALUE reads first. */\n.gemina-verification__tip-label {\n color: var(--gemina-verification-muted);\n}\n`;\n\nconst STYLE_ATTR = 'data-gemina-verification';\n\n/**\n * Inject the verification stylesheet once per document (idempotent across\n * instances; intentionally not removed on unmount so sibling instances and\n * quick remounts never flash unstyled). Safe to call during SSR: it no-ops\n * when there is no document, and importing this module never touches it.\n */\nexport function ensureVerificationStylesInjected(): void {\n if (typeof document === 'undefined') {\n return;\n }\n if (document.head.querySelector(`style[${STYLE_ATTR}]`) !== null) {\n return;\n }\n const style = document.createElement('style');\n style.setAttribute(STYLE_ATTR, VERSION);\n style.textContent = VERIFICATION_CSS;\n document.head.appendChild(style);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;AC8DA,IAAM,gBAAgB;AAEtB,IAAM,gBACJ;AAqBF,IAAM,SAAS,oBAAI,QAAwC;AAE3D,SAAS,SAAS,SAAyC;AACzD,QAAM,QAAQ,OAAO,IAAI,OAAO;AAChC,MAAI,UAAU,QAAW;AACvB,UAAM,IAAI;AAAA,MACR;AAAA,IAEF;AAAA,EACF;AACA,SAAO;AACT;AAMA,SAAS,qBAAqB,QAAkC;AAC9D,MAAI,WAAW,QAAQ,OAAO,WAAW,UAAU;AACjD,UAAM,IAAI;AAAA,MACR,8EACU,WAAW,OAAO,SAAS,OAAO,MAAM;AAAA,IACpD;AAAA,EACF;AACA,QAAM,EAAE,OAAO,UAAU,IAAI;AAC7B,MAAI,OAAO,UAAU,YAAY,MAAM,WAAW,GAAG;AACnD,UAAM,IAAI;AAAA,MACR;AAAA,IAEF;AAAA,EACF;AACA,MAAI,cAAc,KAAK,KAAK,GAAG;AAC7B,UAAM,IAAI,MAAM,aAAa;AAAA,EAC/B;AAEA,QAAM,WAAW,MAAM,MAAM,GAAG;AAChC,MAAI,SAAS,WAAW,KAAK,SAAS,KAAK,CAAC,YAAY,QAAQ,WAAW,CAAC,GAAG;AAC7E,UAAM,IAAI;AAAA,M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SAAI,KAAK,SAAS,WAAW,eAAe,KAAK,cAC/C,mBACH;AAEJ;","names":["import_react","import_sdk","escapeSegment","import_react","import_react","import_jsx_runtime","trigger","import_react","import_jsx_runtime","import_jsx_runtime","React","FallbackSection","DARK_VARS","STYLE_ATTR","import_jsx_runtime","HEBREW_RE","SESSION_EXPIRED_TEXT","rendered","next"]}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../src/token-manager.ts","../src/chat.tsx","../src/internal/response-like.ts","../src/version.ts","../src/verification/index.tsx","../src/verification/field-types.ts","../src/verification/classify.ts","../src/verification/pointer.ts","../src/verification/bindings.ts","../src/verification/row-plan.ts","../src/verification/row-cells.ts","../src/verification/form.tsx","../src/verification/review-filter.ts","../src/verification/tip.tsx","../src/verification/viewer.tsx","../src/verification/viewer-math.ts","../src/verification/styles.ts"],"sourcesContent":["// Token management (no React required — also available as\n// `@gemina/elements/token-manager`).\nexport { GeminaTokenManager } from './token-manager';\nexport type { FetchTokenResult, GeminaTokenManagerOptions } from './token-manager';\n\n// Chat UI (React — also available as `@gemina/elements/chat`).\nexport { GeminaChat } from './chat';\nexport type { GeminaChatProps, GeminaChatTheme, GeminaChatDirection } from './chat';\n\n// Verification UI (React — also available as `@gemina/elements/verification`).\nexport { GeminaVerification } from './verification/index';\nexport type {\n GeminaVerificationProps,\n GeminaVerificationTheme,\n GeminaVerificationDirection,\n VerificationErrorReason,\n VerificationErrorDetail,\n VerificationCompletion,\n} from './verification/index';\n\nexport { VERSION } from './version';\n","/**\n * GeminaTokenManager — in-memory holder for short-lived Gemina session\n * tokens, per the Document Intelligence token spec (PRD §6.11.1).\n *\n * Security model (the five footguns this file designs out):\n *\n * 1. **The API key never enters the browser.** The constructor throws if it\n * is handed a raw string instead of a `fetchToken` callback, and\n * `getToken()` rejects if the callback ever resolves with an\n * API-key-shaped string (32 alphanumerics, no dots).\n * 2. **The token is never persisted.** No `localStorage`, `sessionStorage`,\n * cookies, or IndexedDB anywhere in this package — the token lives only\n * in memory, inside state that is not an own property of the instance.\n * 3. **The browser never asserts its own scope.** This manager carries no\n * scope parameters at all; scope is signed into the token server-side.\n * 4. **No refresh token is held in the browser.** Renewal always goes back\n * through the tenant's own authenticated backend via `fetchToken`.\n * 5. **The SDK cannot mint or widen TTL/scope.** This class only *stores*\n * what the tenant backend minted; it has no code path to\n * `POST /v1/sessions/token`.\n *\n * Storage choice: internal state (including the token) lives in a\n * module-scoped `WeakMap` keyed by the instance rather than in an ordinary\n * class field. An ordinary field — even a `#private` one via devtools — is\n * trivially discoverable by enumerating the instance; the WeakMap keeps the\n * token out of `Object.keys`, `JSON.stringify`, spread copies, and casual\n * inspection, and it is unreachable without a reference to both the WeakMap\n * (module-private) and the instance. This is hardening against accidental\n * exposure/serialization, not encryption: code running in the same realm\n * with a debugger can still read process memory. The upgrade path for\n * stronger isolation is a Web Worker (see PRD §6.11.1).\n *\n * SSR-safe: this module touches no `window`/`document` at import time and\n * starts no timers — refresh happens lazily inside `getToken()`, so an idle\n * manager consumes nothing and never keeps a Node process alive.\n */\n\n/** What `fetchToken` must resolve with (mirror of the mint response). */\nexport interface FetchTokenResult {\n /** The raw session token (a JWT). Pass it WITHOUT a \"Bearer \" prefix. */\n token: string;\n /** Token lifetime in seconds, as returned by the mint endpoint. */\n expiresIn: number;\n}\n\n/** Constructor options for {@link GeminaTokenManager}. */\nexport interface GeminaTokenManagerOptions {\n /**\n * Callback that obtains a fresh session token from the TENANT'S OWN\n * backend (which in turn calls Gemina's `POST /v1/sessions/token` with\n * the API key, server-side). It must resolve with\n * `{ token, expiresIn }`. It must NEVER return a Gemina API key.\n */\n fetchToken: () => Promise<FetchTokenResult>;\n /**\n * How many seconds before the token's expiry `getToken()` starts\n * refreshing. Default 60 (the PRD's `exp − 60s` refresh point).\n */\n refreshSkewSeconds?: number;\n}\n\n/** Gemina API keys are exactly 32 alphanumerics with no prefix. */\nconst API_KEY_SHAPE = /^[A-Za-z0-9]{32}$/;\n\nconst API_KEY_ERROR =\n 'GeminaTokenManager received an API-key-shaped credential (32 alphanumeric ' +\n 'characters). Gemina API keys are master keys and must NEVER enter the ' +\n 'browser: mint a short-lived session token on YOUR backend via ' +\n 'POST /v1/sessions/token (sessions.mintRetrievalToken in @gemina/sdk) and ' +\n 'return { token, expiresIn } from fetchToken instead.';\n\ninterface TokenState {\n fetchToken: () => Promise<FetchTokenResult>;\n refreshSkewMs: number;\n /** The cached raw token, or null when absent/invalidated. */\n token: string | null;\n /** Epoch ms after which the cached token is considered expired. */\n expiresAtMs: number;\n /** Shared in-flight refresh, so concurrent callers never stampede. */\n inFlight: Promise<string> | null;\n /** Bumped by invalidate(); stale refreshes must not repopulate the cache. */\n epoch: number;\n}\n\n// Module-private state store — see the header comment for why the token is\n// deliberately NOT an own property of the instance.\nconst STATES = new WeakMap<GeminaTokenManager, TokenState>();\n\nfunction getState(manager: GeminaTokenManager): TokenState {\n const state = STATES.get(manager);\n if (state === undefined) {\n throw new Error(\n 'GeminaTokenManager state missing — was the instance constructed normally? ' +\n '(Object.create/deserialization is not supported.)',\n );\n }\n return state;\n}\n\n/**\n * Validate what `fetchToken` resolved with and return the raw token.\n * Rejects API-key-shaped strings and anything that is not JWT-shaped.\n */\nfunction validateFetchedToken(result: FetchTokenResult): string {\n if (result === null || typeof result !== 'object') {\n throw new Error(\n 'GeminaTokenManager: fetchToken must resolve with { token, expiresIn } ' +\n `(got ${result === null ? 'null' : typeof result}).`,\n );\n }\n const { token, expiresIn } = result;\n if (typeof token !== 'string' || token.length === 0) {\n throw new Error(\n 'GeminaTokenManager: fetchToken resolved without a token string. ' +\n 'Return { token, expiresIn } from the mint response.',\n );\n }\n if (API_KEY_SHAPE.test(token)) {\n throw new Error(API_KEY_ERROR);\n }\n // Session tokens are JWTs: exactly three non-empty dot-separated segments.\n const segments = token.split('.');\n if (segments.length !== 3 || segments.some((segment) => segment.length === 0)) {\n throw new Error(\n 'GeminaTokenManager: fetchToken resolved with a value that is not a ' +\n 'session token. Gemina session tokens are JWTs (three dot-separated ' +\n 'segments); return the `token` field from POST /v1/sessions/token.',\n );\n }\n if (typeof expiresIn !== 'number' || !Number.isFinite(expiresIn) || expiresIn <= 0) {\n throw new Error(\n 'GeminaTokenManager: fetchToken resolved with an invalid expiresIn ' +\n `(${String(expiresIn)}). Return the mint response's expiresIn (seconds > 0).`,\n );\n }\n return token;\n}\n\n/**\n * Holds a short-lived Gemina session token in memory and keeps it fresh.\n *\n * ```ts\n * const tokenManager = new GeminaTokenManager({\n * // YOUR backend endpoint — it holds the API key and mints the token.\n * fetchToken: async () => {\n * const res = await fetch(\"/api/gemina-session\", { method: \"POST\" });\n * if (!res.ok) throw new Error(\"Failed to mint Gemina session token\");\n * return res.json(); // { token, expiresIn }\n * },\n * });\n * ```\n *\n * - `getToken()` fetches lazily on first use, then auto-refreshes when the\n * cached token is within `refreshSkewSeconds` of expiry. Concurrent\n * callers share a single in-flight fetch.\n * - `invalidate()` drops the cache so the next `getToken()` refetches\n * (use after a 401).\n * - No timers run while idle; nothing is ever written to storage.\n */\nexport class GeminaTokenManager {\n constructor(options: GeminaTokenManagerOptions) {\n if (typeof options === 'string') {\n // Someone did `new GeminaTokenManager(\"<api key or token>\")`.\n throw new Error(\n API_KEY_SHAPE.test(options)\n ? API_KEY_ERROR\n : 'GeminaTokenManager takes { fetchToken } — a callback that asks ' +\n 'YOUR backend for a fresh session token — not a raw string. ' +\n 'Never pass a Gemina API key to browser code.',\n );\n }\n if (options === null || typeof options !== 'object') {\n throw new Error(\n 'GeminaTokenManager requires an options object: new GeminaTokenManager({ fetchToken }).',\n );\n }\n const { fetchToken, refreshSkewSeconds = 60 } = options;\n if (typeof fetchToken === 'string') {\n throw new Error(\n (API_KEY_SHAPE.test(fetchToken) ? `${API_KEY_ERROR} ` : '') +\n 'GeminaTokenManager: fetchToken must be a function returning ' +\n 'Promise<{ token, expiresIn }>, not a string.',\n );\n }\n if (typeof fetchToken !== 'function') {\n throw new Error(\n 'GeminaTokenManager: fetchToken is required and must be a function ' +\n 'returning Promise<{ token, expiresIn }>.',\n );\n }\n if (\n typeof refreshSkewSeconds !== 'number' ||\n !Number.isFinite(refreshSkewSeconds) ||\n refreshSkewSeconds < 0\n ) {\n throw new Error(\n `GeminaTokenManager: refreshSkewSeconds must be a non-negative number (got ${String(\n refreshSkewSeconds,\n )}).`,\n );\n }\n\n STATES.set(this, {\n fetchToken,\n refreshSkewMs: refreshSkewSeconds * 1000,\n token: null,\n expiresAtMs: 0,\n inFlight: null,\n epoch: 0,\n });\n }\n\n /**\n * Return a valid session token, fetching or refreshing as needed.\n *\n * A cached token is reused until `now >= expiry - refreshSkewSeconds`\n * (expiry computed as `Date.now() + expiresIn * 1000` at fetch time).\n * All concurrent callers during a refresh share ONE in-flight fetch.\n * A failed fetch is not cached — the next call retries.\n */\n getToken(): Promise<string> {\n const state = getState(this);\n\n if (state.token !== null && Date.now() < state.expiresAtMs - state.refreshSkewMs) {\n return Promise.resolve(state.token);\n }\n\n if (state.inFlight !== null) {\n return state.inFlight;\n }\n\n const epoch = state.epoch;\n const fetchStartedAtMs = Date.now();\n // Start the user callback immediately (getToken() should fire the mint\n // request right away), but convert a synchronous throw into a rejection\n // so the in-flight bookkeeping below stays consistent.\n let fetched: Promise<FetchTokenResult>;\n try {\n fetched = Promise.resolve(state.fetchToken());\n } catch (error) {\n fetched = Promise.reject(error);\n }\n const inFlight: Promise<string> = fetched\n .then((result) => {\n const token = validateFetchedToken(result);\n if (state.epoch === epoch) {\n state.token = token;\n state.expiresAtMs = fetchStartedAtMs + result.expiresIn * 1000;\n }\n // If invalidate() ran mid-flight, still hand this (already-minted)\n // token to the callers who asked before the invalidation — but do\n // not cache it; the next getToken() fetches fresh.\n return token;\n })\n .finally(() => {\n if (state.inFlight === inFlight) {\n state.inFlight = null;\n }\n });\n\n state.inFlight = inFlight;\n return inFlight;\n }\n\n /**\n * Drop the cached token (and detach any in-flight refresh) so the next\n * `getToken()` fetches a fresh one. Call this when the API answers 401,\n * then retry the request once with a new `getToken()`.\n */\n invalidate(): void {\n const state = getState(this);\n state.token = null;\n state.expiresAtMs = 0;\n state.inFlight = null;\n state.epoch += 1;\n }\n}\n","/**\n * <GeminaChat> — drop-in chat UI over Gemina Document Intelligence.\n *\n * Auth flows exclusively through a {@link GeminaTokenManager}: the component\n * asks it for a short-lived session token per turn and calls\n * `POST /v1/chat/query` through `@gemina/sdk`. It never sees — and cannot\n * accept — a Gemina API key (the token manager throws on API-key-shaped\n * credentials).\n *\n * SSR-safe: no `window`/`document` access at import time; styles are\n * injected on mount.\n */\nimport { useCallback, useEffect, useRef, useState } from 'react';\nimport type * as React from 'react';\nimport { GeminaClient } from '@gemina/sdk';\nimport type { ChatQueryOutDTO } from '@gemina/sdk';\nimport { getResponseLike, httpStatus, readErrorEnvelope } from './internal/response-like';\nimport type { GeminaTokenManager } from './token-manager';\nimport { VERSION } from './version';\n\n/** Visual theme. `\"auto\"` follows `prefers-color-scheme`. */\nexport type GeminaChatTheme = 'light' | 'dark' | 'auto';\n\n/**\n * Text direction. `\"auto\"` flips the widget to RTL when the user's latest\n * message contains Hebrew, and lets each bubble resolve its own direction.\n */\nexport type GeminaChatDirection = 'ltr' | 'rtl' | 'auto';\n\nexport interface GeminaChatProps {\n /** Token source. Required — see {@link GeminaTokenManager}. */\n tokenManager: GeminaTokenManager;\n /** Gemina API base URL (default `https://api.gemina.co`). */\n baseUrl?: string;\n /**\n * Optional end-user id forwarded with each query. On the session-token\n * path the token's SIGNED scope always wins server-side — this is a\n * hint, not a security control.\n */\n endUserId?: string;\n /** Visual theme (default `\"auto\"`). */\n theme?: GeminaChatTheme;\n /** Text direction (default `\"auto\"`). */\n dir?: GeminaChatDirection;\n /** Input placeholder text. */\n placeholder?: string;\n /**\n * Header text — whatever identity the embedding platform wants the chat\n * to carry: a brand (\"Acme Invoices\"), an assistant persona (\"Gemina's\n * AI Rep\"), anything. Text only, rendered verbatim. When set, the header\n * is always visible; without it the header appears only once a\n * conversation has started (to host \"New chat\"). Colors and fonts are\n * themeable separately via the `--gemina-chat-*` CSS variables\n * (including `--gemina-chat-header-bg` for the header bar).\n */\n title?: string;\n /**\n * Plain text shown centered in the empty conversation area until the\n * first message. Use it to set expectations about what the assistant\n * can and can't see (e.g. \"Answers come from your indexed document\n * data\"). Newlines split it into separately spaced paragraphs — no\n * markup, so the string stays safe and portable.\n */\n intro?: string;\n /** Called with the cited `documentId` when a citation chip is clicked. */\n onCitationClick?: (documentId: string) => void;\n /** Extra class name(s) for the root element (e.g. to override CSS vars). */\n className?: string;\n}\n\ninterface UserMessage {\n id: number;\n role: 'user';\n text: string;\n}\n\ninterface AssistantMessage {\n id: number;\n role: 'assistant';\n text: string;\n citations: string[];\n confident: boolean;\n}\n\ninterface ErrorMessage {\n id: number;\n role: 'error';\n text: string;\n /** Present only when a retry is offered; holds the original user text. */\n retryText?: string;\n}\n\ntype ChatMessage = UserMessage | AssistantMessage | ErrorMessage;\n\n/** `Omit` that distributes over each member of a union. */\ntype DistributiveOmit<T, K extends PropertyKey> = T extends unknown ? Omit<T, K> : never;\n\ntype ChatMessageInput = DistributiveOmit<ChatMessage, 'id'>;\n\n/** Hebrew Unicode block (U+0590–U+05FF). */\nconst HEBREW_RE = /[\\u0590-\\u05FF]/;\n\n// Stable backend error codes. These survive production's `detail`-stripping\n// (see the chat-pricing handoff); we switch on HTTP status first and refine\n// with these where the same status can mean two different things.\nconst ERR_CHAT_QUOTA_EXCEEDED = 'CHAT_QUOTA_EXCEEDED';\nconst ERR_DI_NOT_IN_PLAN = 'DOCUMENT_INTELLIGENCE_NOT_IN_PLAN';\nconst ERR_UNPROCESSABLE = 'UNPROCESSABLE_ERROR';\nconst ERR_BAD_GATEWAY = 'BAD_GATEWAY_ERROR';\n// A conversation id that the server no longer knows (24h idle TTL, explicit\n// reset, or end-user scope drift). A turn that CARRIED a session and 404s is\n// this by construction — the chat/query handler raises 404 for nothing else —\n// so the component drops the id and restarts the conversation transparently.\nconst ERR_CHAT_SESSION_NOT_FOUND = 'CHAT_SESSION_NOT_FOUND';\n\ninterface ChatErrorInfo {\n status: number | undefined;\n errorCode: string | undefined;\n /** Human-readable server fallback (`errors[0].description`). */\n description: string | undefined;\n /** Whole seconds until reset, from the `Retry-After` header (429). */\n retryAfterSeconds: number | undefined;\n}\n\n/**\n * Read what the backend actually sent on an error. Only the HTTP status, the\n * stable `errors[0].error_code` / `description`, and the `Retry-After` header\n * are reliable across environments — production strips `errors[0].detail`, so\n * we never touch it. The envelope parsing (with its defensive clone/json\n * dance) lives in `readErrorEnvelope`; only the `Retry-After` header handling\n * is chat-specific.\n */\nasync function readChatError(error: unknown): Promise<ChatErrorInfo> {\n const envelope = await readErrorEnvelope(error);\n const info: ChatErrorInfo = { ...envelope, retryAfterSeconds: undefined };\n\n const rawRetryAfter = getResponseLike(error)?.headers?.get?.('retry-after');\n if (rawRetryAfter !== null && rawRetryAfter !== undefined) {\n const seconds = Number(rawRetryAfter);\n if (Number.isFinite(seconds) && seconds > 0) {\n info.retryAfterSeconds = seconds;\n }\n }\n return info;\n}\n\nconst SESSION_EXPIRED_TEXT = 'Session expired — please reload the page or sign in again.';\nconst CONVERSATION_RESET_TEXT =\n 'This conversation is no longer available — send your message again to start a new one.';\nconst RATE_LIMIT_TEXT = \"You're sending messages too quickly — try again shortly.\";\nconst PLAN_GATE_TEXT = \"Chat isn't included in your plan.\";\nconst UNANSWERABLE_TEXT = \"We couldn't answer that. Try rephrasing your question.\";\nconst SERVICE_UNAVAILABLE_TEXT = 'The chat service is temporarily unavailable. Please try again.';\nconst GENERIC_ERROR_TEXT = \"Something went wrong and your message wasn't answered.\";\n\n/** Friendly \"resets in about N days/hours/minutes\" from Retry-After seconds. */\nfunction formatResetHint(seconds: number | undefined): string {\n if (seconds === undefined || !Number.isFinite(seconds) || seconds <= 0) {\n return 'at the next billing cycle';\n }\n const days = Math.round(seconds / 86400);\n if (days >= 1) {\n return `in about ${days} day${days === 1 ? '' : 's'}`;\n }\n const hours = Math.round(seconds / 3600);\n if (hours >= 1) {\n return `in about ${hours} hour${hours === 1 ? '' : 's'}`;\n }\n const minutes = Math.max(1, Math.round(seconds / 60));\n return `in about ${minutes} minute${minutes === 1 ? '' : 's'}`;\n}\n\n/**\n * Map a chat error to the bubble we render. Switches on HTTP status, refined by\n * the stable backend `error_code`. `retryText` is set only when resending the\n * same text could plausibly succeed — never for quota / plan / validation\n * outcomes, where an identical retry would just fail the same way.\n */\nfunction describeChatError(info: ChatErrorInfo, originalText: string): ChatMessageInput {\n const { status, errorCode } = info;\n\n // Over the included cap AND out of credits — the chat is blocked. Retrying\n // won't help; point at the reset time from the Retry-After header.\n if (status === 429 && errorCode === ERR_CHAT_QUOTA_EXCEEDED) {\n return {\n role: 'error',\n text: `You've used your included chats and are out of credits. Included chats reset ${formatResetHint(\n info.retryAfterSeconds,\n )}.`,\n };\n }\n // Any other 429 is a transient rate limit — a retry after a moment is fine.\n if (status === 429) {\n return { role: 'error', text: RATE_LIMIT_TEXT, retryText: originalText };\n }\n // Document Intelligence not in the plan/contract. NOT an auth failure.\n if (status === 402 || status === 403 || errorCode === ERR_DI_NOT_IN_PLAN) {\n return { role: 'error', text: PLAN_GATE_TEXT };\n }\n // Session expired — only surfaces after the 401-invalidate-retry-once path\n // has already failed a second time.\n if (status === 401) {\n return { role: 'error', text: SESSION_EXPIRED_TEXT };\n }\n // A stale conversation id that slipped past the transparent restart — only\n // the stable error_code reliably means \"the conversation is gone\". A bare 404\n // is a routing/gateway miss (e.g. the endpoint isn't deployed), which reads\n // better as a transient service error than a confusing \"conversation reset\".\n if (errorCode === ERR_CHAT_SESSION_NOT_FOUND) {\n return { role: 'error', text: CONVERSATION_RESET_TEXT, retryText: originalText };\n }\n if (status === 404) {\n return { role: 'error', text: SERVICE_UNAVAILABLE_TEXT, retryText: originalText };\n }\n // The question couldn't be answered (e.g. no searchable text). Expected, not\n // a server error — invite a rephrase rather than a blind retry.\n if (status === 422 || errorCode === ERR_UNPROCESSABLE) {\n return { role: 'error', text: UNANSWERABLE_TEXT };\n }\n // Chat backend timed out / unreachable — transient, offer retry.\n if (status === 502 || errorCode === ERR_BAD_GATEWAY) {\n return { role: 'error', text: SERVICE_UNAVAILABLE_TEXT, retryText: originalText };\n }\n // Anything else (incl. 500): prefer the server's description if it sent one.\n return {\n role: 'error',\n text: info.description ?? GENERIC_ERROR_TEXT,\n retryText: originalText,\n };\n}\n\n/**\n * The API reports citations as an array of `documentId` strings; normalize\n * defensively so `{ documentId }` objects also work if the shape evolves.\n */\nfunction normalizeCitations(citations: unknown): string[] {\n if (!Array.isArray(citations)) {\n return [];\n }\n const ids: string[] = [];\n for (const item of citations) {\n if (typeof item === 'string' && item.length > 0) {\n ids.push(item);\n } else if (\n item !== null &&\n typeof item === 'object' &&\n typeof (item as { documentId?: unknown }).documentId === 'string'\n ) {\n ids.push((item as { documentId: string }).documentId);\n }\n }\n return ids;\n}\n\n// --- Styles -----------------------------------------------------------------\n// Hand-rolled, no UI deps. Everything is scoped under .gemina-chat and driven\n// by CSS custom properties so host apps can re-theme without touching the DOM.\n\nconst DARK_VARS = `\n --gemina-chat-bg: #101418;\n --gemina-chat-fg: #e6e9ee;\n --gemina-chat-border: #2a323c;\n --gemina-chat-accent: #4c8dff;\n --gemina-chat-accent-fg: #ffffff;\n --gemina-chat-assistant-bg: #1c232b;\n --gemina-chat-assistant-fg: #e6e9ee;\n --gemina-chat-muted: #98a2b3;\n --gemina-chat-error: #f97066;\n --gemina-chat-low-confidence: #f7b27a;\n`;\n\nconst CHAT_CSS = `\n.gemina-chat {\n --gemina-chat-bg: #ffffff;\n --gemina-chat-fg: #1a1d21;\n --gemina-chat-border: #d9dce1;\n --gemina-chat-accent: #2f6fed;\n --gemina-chat-accent-fg: #ffffff;\n --gemina-chat-assistant-bg: #f2f4f7;\n --gemina-chat-assistant-fg: #1a1d21;\n --gemina-chat-muted: #667085;\n --gemina-chat-error: #b42318;\n --gemina-chat-low-confidence: #b54708;\n --gemina-chat-header-bg: transparent;\n --gemina-chat-radius: 10px;\n --gemina-chat-font: system-ui, -apple-system, \"Segoe UI\", Roboto, sans-serif;\n\n box-sizing: border-box;\n display: flex;\n flex-direction: column;\n min-height: 320px;\n max-height: 600px;\n background: var(--gemina-chat-bg);\n color: var(--gemina-chat-fg);\n border: 1px solid var(--gemina-chat-border);\n border-radius: var(--gemina-chat-radius);\n font-family: var(--gemina-chat-font);\n font-size: 14px;\n line-height: 1.5;\n}\n.gemina-chat *, .gemina-chat *::before, .gemina-chat *::after { box-sizing: border-box; }\n.gemina-chat--dark { ${DARK_VARS} }\n@media (prefers-color-scheme: dark) {\n .gemina-chat--auto { ${DARK_VARS} }\n}\n.gemina-chat__header {\n display: flex;\n align-items: center;\n /* Guaranteed minimum separation. The pushing itself is the button's\n auto margin below — NOT a margin on the title, whose dir=\"auto\" can\n resolve opposite to the widget (English title in an RTL chat) and\n collapse an inline-aware margin to the wrong side. */\n gap: 12px;\n flex: 0 0 auto;\n padding: 6px 10px;\n border-bottom: 1px solid var(--gemina-chat-border);\n background: var(--gemina-chat-header-bg);\n}\n.gemina-chat__title {\n font-size: 13px;\n font-weight: 600;\n overflow: hidden;\n text-overflow: ellipsis;\n white-space: nowrap;\n}\n.gemina-chat__newchat {\n margin-inline-start: auto;\n flex-shrink: 0;\n font: inherit;\n font-size: 12px;\n padding: 3px 10px;\n border-radius: var(--gemina-chat-radius);\n border: 1px solid var(--gemina-chat-border);\n background: transparent;\n color: var(--gemina-chat-accent);\n cursor: pointer;\n}\n.gemina-chat__newchat:hover:not(:disabled) { border-color: var(--gemina-chat-accent); }\n.gemina-chat__newchat:disabled { opacity: 0.5; cursor: default; }\n.gemina-chat__log {\n flex: 1;\n overflow-y: auto;\n padding: 12px;\n display: flex;\n flex-direction: column;\n gap: 8px;\n}\n.gemina-chat__msg {\n max-width: 85%;\n padding: 8px 12px;\n border-radius: var(--gemina-chat-radius);\n white-space: pre-wrap;\n overflow-wrap: break-word;\n}\n.gemina-chat__msg--user {\n align-self: flex-end;\n background: var(--gemina-chat-accent);\n color: var(--gemina-chat-accent-fg);\n}\n.gemina-chat--rtl .gemina-chat__msg--user, .gemina-chat[dir=\"rtl\"] .gemina-chat__msg--user {\n align-self: flex-start;\n}\n.gemina-chat--rtl .gemina-chat__msg--assistant, .gemina-chat[dir=\"rtl\"] .gemina-chat__msg--assistant {\n align-self: flex-end;\n}\n.gemina-chat__msg--assistant {\n align-self: flex-start;\n background: var(--gemina-chat-assistant-bg);\n color: var(--gemina-chat-assistant-fg);\n}\n.gemina-chat__msg--low-confidence {\n border: 1px dashed var(--gemina-chat-low-confidence);\n}\n.gemina-chat__low-confidence-note {\n margin-top: 6px;\n font-size: 12px;\n color: var(--gemina-chat-low-confidence);\n}\n.gemina-chat__citations {\n display: flex;\n flex-wrap: wrap;\n gap: 4px;\n margin-top: 6px;\n}\n.gemina-chat__citation {\n font: inherit;\n font-size: 12px;\n padding: 2px 8px;\n border-radius: 999px;\n border: 1px solid var(--gemina-chat-border);\n background: transparent;\n color: var(--gemina-chat-accent);\n cursor: pointer;\n}\n.gemina-chat__citation:hover { border-color: var(--gemina-chat-accent); }\n.gemina-chat__msg--error {\n align-self: flex-start;\n background: transparent;\n border: 1px solid var(--gemina-chat-error);\n color: var(--gemina-chat-error);\n}\n.gemina-chat__retry {\n font: inherit;\n font-size: 12px;\n margin-top: 6px;\n display: block;\n padding: 2px 10px;\n border-radius: var(--gemina-chat-radius);\n border: 1px solid var(--gemina-chat-error);\n background: transparent;\n color: var(--gemina-chat-error);\n cursor: pointer;\n}\n.gemina-chat__intro {\n display: flex;\n flex-direction: column;\n gap: 10px;\n margin: auto;\n max-width: 46ch;\n padding: 16px;\n text-align: center;\n font-size: 13px;\n color: var(--gemina-chat-muted);\n}\n.gemina-chat__intro-line { margin: 0; }\n.gemina-chat__typing {\n align-self: flex-start;\n display: flex;\n align-items: center;\n gap: 5px;\n color: var(--gemina-chat-muted);\n font-size: 12px;\n padding: 0 4px;\n}\n.gemina-chat__typing-dots {\n display: inline-flex;\n align-items: center;\n gap: 3px;\n}\n.gemina-chat__typing-dots span {\n width: 4px;\n height: 4px;\n border-radius: 50%;\n background: currentColor;\n opacity: 0.25;\n animation: gemina-chat-thinking 1.2s infinite ease-in-out;\n}\n.gemina-chat__typing-dots span:nth-child(2) { animation-delay: 0.2s; }\n.gemina-chat__typing-dots span:nth-child(3) { animation-delay: 0.4s; }\n@keyframes gemina-chat-thinking {\n 0%, 60%, 100% { opacity: 0.25; transform: translateY(0); }\n 30% { opacity: 1; transform: translateY(-2px); }\n}\n@media (prefers-reduced-motion: reduce) {\n .gemina-chat__typing-dots span { animation: none; opacity: 0.6; }\n}\n.gemina-chat__composer {\n display: flex;\n gap: 8px;\n padding: 10px;\n border-top: 1px solid var(--gemina-chat-border);\n}\n.gemina-chat__input {\n flex: 1;\n resize: none;\n font: inherit;\n color: inherit;\n background: transparent;\n border: 1px solid var(--gemina-chat-border);\n border-radius: var(--gemina-chat-radius);\n padding: 8px 10px;\n min-height: 38px;\n}\n.gemina-chat__input:focus {\n outline: 2px solid var(--gemina-chat-accent);\n outline-offset: -1px;\n}\n.gemina-chat__send {\n font: inherit;\n align-self: flex-end;\n border: none;\n border-radius: var(--gemina-chat-radius);\n background: var(--gemina-chat-accent);\n color: var(--gemina-chat-accent-fg);\n padding: 8px 16px;\n cursor: pointer;\n}\n.gemina-chat__send:disabled { opacity: 0.5; cursor: default; }\n`;\n\nconst STYLE_ATTR = 'data-gemina-chat';\n\n/**\n * Inject the widget stylesheet once per document (idempotent across\n * instances; intentionally not removed on unmount so sibling instances and\n * quick remounts never flash unstyled).\n */\nfunction ensureStylesInjected(): void {\n if (typeof document === 'undefined') {\n return;\n }\n if (document.head.querySelector(`style[${STYLE_ATTR}]`) !== null) {\n return;\n }\n const style = document.createElement('style');\n style.setAttribute(STYLE_ATTR, VERSION);\n style.textContent = CHAT_CSS;\n document.head.appendChild(style);\n}\n\n/**\n * Embeddable Gemina Document Intelligence chat.\n *\n * ```tsx\n * <GeminaChat\n * tokenManager={tokenManager}\n * onCitationClick={(documentId) => openDocument(documentId)}\n * />\n * ```\n */\nexport function GeminaChat(props: GeminaChatProps): React.JSX.Element {\n const {\n tokenManager,\n baseUrl,\n endUserId,\n theme = 'auto',\n dir = 'auto',\n placeholder = 'Ask about your documents…',\n title,\n intro,\n onCitationClick,\n className,\n } = props;\n\n const [messages, setMessages] = useState<ChatMessage[]>([]);\n const [draft, setDraft] = useState('');\n const [busy, setBusy] = useState(false);\n const nextIdRef = useRef(0);\n const mountedRef = useRef(false);\n const logRef = useRef<HTMLDivElement | null>(null);\n // The conversation id (server-issued) that gives the chat memory across\n // turns. Held in a ref, not state: it changes per turn but must never\n // trigger a re-render, and the send flow reads its latest value directly.\n // Distinct from the auth session TOKEN the token manager holds.\n const sessionIdRef = useRef<string | undefined>(undefined);\n\n useEffect(() => {\n mountedRef.current = true;\n ensureStylesInjected();\n return () => {\n mountedRef.current = false;\n };\n }, []);\n\n // Keep the newest message in view.\n useEffect(() => {\n const log = logRef.current;\n if (log !== null) {\n log.scrollTop = log.scrollHeight;\n }\n }, [messages, busy]);\n\n const appendMessage = useCallback((message: ChatMessageInput) => {\n const id = nextIdRef.current++;\n setMessages((prev) => [...prev, { ...message, id }]);\n }, []);\n\n const chatOnce = useCallback(\n (token: string, message: string): Promise<ChatQueryOutDTO> => {\n const client = GeminaClient.withSessionToken(token, baseUrl);\n const sessionId = sessionIdRef.current;\n return client.chat.chatQuery({\n // Thread the conversation id when we have one so follow-ups resolve\n // referents (\"what about the total?\"); omit it to start a new one.\n chatQueryInDTO: { message, endUserId, ...(sessionId ? { sessionId } : {}) },\n });\n },\n [baseUrl, endUserId],\n );\n\n /** One turn, with the mandated 401-invalidate-retry-once behavior. */\n const queryWithRetry = useCallback(\n async (message: string): Promise<ChatQueryOutDTO> => {\n const token = await tokenManager.getToken();\n try {\n return await chatOnce(token, message);\n } catch (error) {\n if (httpStatus(error) !== 401) {\n throw error;\n }\n // Token likely expired mid-session: drop it, re-mint via the\n // tenant backend, retry exactly once. A second 401 propagates.\n tokenManager.invalidate();\n const freshToken = await tokenManager.getToken();\n return await chatOnce(freshToken, message);\n }\n },\n [tokenManager, chatOnce],\n );\n\n const performSend = useCallback(\n async (text: string) => {\n setBusy(true);\n try {\n let result: ChatQueryOutDTO;\n const hadSession = sessionIdRef.current !== undefined;\n try {\n result = await queryWithRetry(text);\n } catch (error) {\n // A turn that CARRIED a session and 404s means the conversation is\n // gone (24h idle TTL, an explicit reset, or end-user scope drift).\n // Drop the stale id and retry once as a fresh conversation, so the\n // expiry is transparent — the user just gets an answer, no memory.\n if (hadSession && httpStatus(error) === 404) {\n sessionIdRef.current = undefined;\n result = await queryWithRetry(text);\n } else {\n throw error;\n }\n }\n if (!mountedRef.current) {\n return;\n }\n // The response always returns the (possibly newly created) conversation\n // id — store it so the next turn continues this thread.\n sessionIdRef.current = result.sessionId ?? sessionIdRef.current;\n appendMessage({\n role: 'assistant',\n text: result.answer,\n citations: normalizeCitations(result.citations),\n confident: result.confident !== false,\n });\n } catch (error) {\n if (!mountedRef.current) {\n return;\n }\n // Reading the error body is async (fetch), so re-check mount after.\n const info = await readChatError(error);\n if (!mountedRef.current) {\n return;\n }\n appendMessage(describeChatError(info, text));\n } finally {\n if (mountedRef.current) {\n setBusy(false);\n }\n }\n },\n [queryWithRetry, appendMessage],\n );\n\n /**\n * Reset to a brand-new conversation: clear the transcript and forget the\n * session id so the next message starts fresh. The old session is deleted\n * server-side best-effort — the local reset is authoritative, and a failed\n * delete just leaves the session to lapse on its idle TTL.\n */\n const startNewChat = useCallback(() => {\n if (busy) {\n return;\n }\n const staleSession = sessionIdRef.current;\n sessionIdRef.current = undefined;\n setMessages([]);\n setDraft('');\n if (staleSession !== undefined) {\n void (async () => {\n try {\n const token = await tokenManager.getToken();\n await GeminaClient.withSessionToken(token, baseUrl).chat.deleteChatSession({\n sessionId: staleSession,\n });\n } catch {\n // Unreachable/expired session: nothing to clean up client-side.\n }\n })();\n }\n }, [busy, tokenManager, baseUrl]);\n\n const submitDraft = useCallback(() => {\n const text = draft.trim();\n if (text.length === 0 || busy) {\n return;\n }\n setDraft('');\n appendMessage({ role: 'user', text });\n void performSend(text);\n }, [draft, busy, appendMessage, performSend]);\n\n const retryMessage = useCallback(\n (failed: ErrorMessage) => {\n if (busy || failed.retryText === undefined) {\n return;\n }\n const text = failed.retryText;\n // Replace the error entry; the original user bubble is still there.\n setMessages((prev) => prev.filter((message) => message.id !== failed.id));\n void performSend(text);\n },\n [busy, performSend],\n );\n\n const handleKeyDown = useCallback(\n (event: React.KeyboardEvent<HTMLTextAreaElement>) => {\n if (event.key === 'Enter' && !event.shiftKey) {\n event.preventDefault();\n submitDraft();\n }\n },\n [submitDraft],\n );\n\n const handleSubmit = useCallback(\n (event: React.FormEvent<HTMLFormElement>) => {\n event.preventDefault();\n submitDraft();\n },\n [submitDraft],\n );\n\n // dir=\"auto\": follow the user's latest message (Hebrew → RTL); individual\n // bubbles additionally resolve their own direction via dir=\"auto\".\n let effectiveDir: 'ltr' | 'rtl';\n if (dir === 'auto') {\n let lastUserText = '';\n for (let i = messages.length - 1; i >= 0; i--) {\n const message = messages[i];\n if (message !== undefined && message.role === 'user') {\n lastUserText = message.text;\n break;\n }\n }\n effectiveDir = HEBREW_RE.test(lastUserText) ? 'rtl' : 'ltr';\n } else {\n effectiveDir = dir;\n }\n const bubbleDir = dir === 'auto' ? 'auto' : undefined;\n\n const rootClassName = [\n 'gemina-chat',\n `gemina-chat--${theme}`,\n effectiveDir === 'rtl' ? 'gemina-chat--rtl' : '',\n className ?? '',\n ]\n .filter((part) => part.length > 0)\n .join(' ');\n\n return (\n <div className={rootClassName} dir={effectiveDir}>\n {(title !== undefined || messages.length > 0) && (\n <div className=\"gemina-chat__header\">\n {title !== undefined && (\n <div className=\"gemina-chat__title\" dir={bubbleDir}>\n {title}\n </div>\n )}\n {messages.length > 0 && (\n <button\n type=\"button\"\n className=\"gemina-chat__newchat\"\n onClick={startNewChat}\n disabled={busy}\n >\n New chat\n </button>\n )}\n </div>\n )}\n <div\n ref={logRef}\n role=\"log\"\n aria-live=\"polite\"\n aria-busy={busy}\n aria-label=\"Chat messages\"\n className=\"gemina-chat__log\"\n >\n {messages.length === 0 && intro !== undefined && (\n <div className=\"gemina-chat__intro\" dir={bubbleDir}>\n {intro\n .split('\\n')\n .filter((line) => line.trim().length > 0)\n .map((line, index) => (\n <p key={index} className=\"gemina-chat__intro-line\">\n {line}\n </p>\n ))}\n </div>\n )}\n {messages.map((message) => {\n if (message.role === 'user') {\n return (\n <div\n key={message.id}\n className=\"gemina-chat__msg gemina-chat__msg--user\"\n dir={bubbleDir}\n >\n {message.text}\n </div>\n );\n }\n if (message.role === 'assistant') {\n const lowConfidence = !message.confident;\n return (\n <div\n key={message.id}\n className={\n 'gemina-chat__msg gemina-chat__msg--assistant' +\n (lowConfidence ? ' gemina-chat__msg--low-confidence' : '')\n }\n dir={bubbleDir}\n >\n {message.text}\n {lowConfidence && (\n <div className=\"gemina-chat__low-confidence-note\">\n Low confidence — please verify against the cited documents.\n </div>\n )}\n {message.citations.length > 0 && (\n <div className=\"gemina-chat__citations\">\n {message.citations.map((documentId, index) => (\n <button\n key={`${documentId}-${index}`}\n type=\"button\"\n className=\"gemina-chat__citation\"\n title={`Open document ${documentId}`}\n onClick={() => onCitationClick?.(documentId)}\n >\n {documentId}\n </button>\n ))}\n </div>\n )}\n </div>\n );\n }\n return (\n <div\n key={message.id}\n role=\"alert\"\n className=\"gemina-chat__msg gemina-chat__msg--error\"\n >\n {message.text}\n {message.retryText !== undefined && (\n <button\n type=\"button\"\n className=\"gemina-chat__retry\"\n onClick={() => retryMessage(message)}\n >\n Retry\n </button>\n )}\n </div>\n );\n })}\n {busy && (\n // The label alone is what the aria-live log announces; the dots are\n // decoration (aria-hidden), and prefers-reduced-motion freezes them.\n <div className=\"gemina-chat__typing\">\n Thinking\n <span className=\"gemina-chat__typing-dots\" aria-hidden=\"true\">\n <span />\n <span />\n <span />\n </span>\n </div>\n )}\n </div>\n <form className=\"gemina-chat__composer\" onSubmit={handleSubmit}>\n <textarea\n className=\"gemina-chat__input\"\n aria-label=\"Chat message\"\n rows={1}\n value={draft}\n placeholder={placeholder}\n dir={bubbleDir}\n onChange={(event) => setDraft(event.target.value)}\n onKeyDown={handleKeyDown}\n />\n <button\n type=\"submit\"\n className=\"gemina-chat__send\"\n aria-label=\"Send message\"\n disabled={busy || draft.trim().length === 0}\n >\n Send\n </button>\n </form>\n </div>\n );\n}\n","/**\n * Shared transport-error helpers for the widgets (chat + verification).\n *\n * Extracted verbatim from chat.tsx so both components read thrown SDK errors\n * the same way. Pure and dependency-free: no React, no DOM.\n */\n\n/**\n * The response-like object carried by a thrown transport error. We pull it off\n * by shape rather than `instanceof ResponseError` — robust against duplicated\n * `@gemina/sdk` copies in a bundle (class identity is not shared across\n * copies). On the fetch transport this is the raw `Response`, so `status`,\n * `headers`, and the JSON body are all reachable from here.\n */\nexport interface ResponseLike {\n status?: number;\n headers?: { get?: (name: string) => string | null };\n json?: () => Promise<unknown>;\n clone?: () => ResponseLike;\n}\n\nexport function getResponseLike(error: unknown): ResponseLike | undefined {\n if (error !== null && typeof error === 'object' && 'response' in error) {\n const response = (error as { response?: unknown }).response;\n if (response !== null && typeof response === 'object') {\n return response as ResponseLike;\n }\n }\n return undefined;\n}\n\n/** Extract an HTTP status from a thrown value, or `undefined`. */\nexport function httpStatus(error: unknown): number | undefined {\n const status = getResponseLike(error)?.status;\n return typeof status === 'number' ? status : undefined;\n}\n\n/** What the standard backend error envelope reliably carries. */\nexport interface ErrorEnvelope {\n status: number | undefined;\n /** Stable backend `errors[0].error_code`. */\n errorCode: string | undefined;\n /** Human-readable server fallback (`errors[0].description`). */\n description: string | undefined;\n}\n\n/**\n * Read what the backend actually sent on an error. Only the HTTP status and\n * the stable `errors[0].error_code` / `description` are reliable across\n * environments — production strips `errors[0].detail`, so we never touch it.\n * The fetch body can be read once, so we clone defensively; if that fails\n * (non-JSON, empty, or already consumed) the status still stands.\n */\nexport async function readErrorEnvelope(error: unknown): Promise<ErrorEnvelope> {\n const response = getResponseLike(error);\n const info: ErrorEnvelope = {\n status: typeof response?.status === 'number' ? response.status : undefined,\n errorCode: undefined,\n description: undefined,\n };\n if (response === undefined) {\n return info;\n }\n\n let body: unknown;\n try {\n const source = typeof response.clone === 'function' ? response.clone() : response;\n body = typeof source.json === 'function' ? await source.json() : undefined;\n } catch {\n body = undefined;\n }\n if (body !== null && typeof body === 'object') {\n const errors = (body as { errors?: unknown }).errors;\n if (\n Array.isArray(errors) &&\n errors.length > 0 &&\n errors[0] !== null &&\n typeof errors[0] === 'object'\n ) {\n const first = errors[0] as { error_code?: unknown; description?: unknown };\n if (typeof first.error_code === 'string') {\n info.errorCode = first.error_code;\n }\n if (typeof first.description === 'string') {\n info.description = first.description;\n }\n }\n }\n return info;\n}\n","/** Package version. Keep in sync with package.json. */\nexport const VERSION = '0.13.3';\n","/**\n * <GeminaVerification> — drop-in human verification UI for one extraction.\n *\n * Auth flows exclusively through a {@link GeminaTokenManager} (chat parity):\n * the component asks it for a short-lived session token and calls\n * `GET /v1/documents/extractions/{id}` through `@gemina/sdk`. It never sees —\n * and cannot accept — a Gemina API key.\n *\n * This module owns the fetch + state machine + edge states (Task 14):\n * loading → unavailable | review — the layout/flash/RTL layer (Task 15):\n * the stacked-below-860px root observer, eye-click → viewer flash wiring,\n * chat-parity Hebrew direction autodetect, and the silent expired-image-URL\n * refresh — the edit state + progress footer (Task 16): the immutable\n * edits map with delete-on-revert dirty tracking, and the\n * \"N confirmed · M corrected\" line fed by composeSubmission — and the submit\n * flow (Task 17): the confirm-final dialog, the PUT with 401\n * invalidate-retry-once, the 409 silent-refetch landing, submit-error with\n * edits preserved, and the exactly-once onComplete.\n *\n * SSR-safe: no `window`/`document` access at import time; styles are\n * injected on mount.\n */\nimport { useCallback, useEffect, useId, useMemo, useRef, useState } from 'react';\nimport type * as React from 'react';\nimport { GeminaClient } from '@gemina/sdk';\nimport type { ExtractionPrimaryViewOutDTO } from '@gemina/sdk';\nimport { httpStatus, readErrorEnvelope } from '../internal/response-like';\nimport { readDescriptors, readRowMutableTables, validateInput } from './field-types';\nimport type { RowMutableTable, ValidationFieldDescriptor } from './field-types';\nimport {\n buildBindings,\n composeSubmission,\n countRowsAt,\n indexBindingsByFieldPointer,\n toInputString,\n} from './bindings';\nimport type { FieldBinding, RowSourcesEntry } from './bindings';\nimport {\n collectCellViews, displayColumns, matchesTablePointer, planTableCells, pruneEmptyAddedRows,\n unitSizePairErrors,\n} from './row-cells';\nimport type { PlannedRow } from './row-cells';\nimport {\n initialRowPlan, insertRowAfter, isIdentityPlan, nextAddedRowId, removeRow, rowSourcesOf,\n} from './row-plan';\nimport type { RowPlanEntry } from './row-plan';\nimport { classifyData, ROW_META_KEY } from './classify';\nimport { VerificationForm } from './form';\nimport { withEmptyMutableTables } from './form';\nimport {\n computeHidden, countUnits, hasAnyConfidence, NOTHING_HIDDEN,\n} from './review-filter';\nimport { ensureVerificationStylesInjected } from './styles';\nimport type {\n GeminaVerificationProps,\n VerificationErrorDetail,\n VerificationErrorReason,\n} from './types';\nimport { VerificationViewer } from './viewer';\nimport type { RelativeRect } from './viewer';\n\nexport type {\n GeminaVerificationProps,\n GeminaVerificationTheme,\n GeminaVerificationDirection,\n VerificationErrorReason,\n VerificationErrorDetail,\n VerificationCompletion,\n} from './types';\n\n/**\n * The component's complete phase model. `review`, `confirming`, `submitting`,\n * and `submit-error` form the REVIEW FAMILY: all four render the same review\n * content (form, edits, aria-live progress — kept mounted so edits stay\n * visible through the whole submit sequence); confirming/submitting add the\n * overlay on top, submit-error the inline error banner. The read-only flag\n * lives in separate `alreadyValidated` state, not in the variants, so the\n * family shares it without every variant re-carrying it.\n */\ntype Phase =\n | { name: 'loading' }\n | { name: 'unavailable'; reason: VerificationErrorReason; message: string; canRetry: boolean }\n | { name: 'review' }\n | { name: 'confirming' } // confirm dialog open over review\n | { name: 'submitting' } // PUT in flight; dialog stays, buttons disabled\n | { name: 'submit-error'; message: string }\n | { name: 'done'; confirmed: number; corrected: number };\n\n/** The four phases that render the review content. */\ntype ReviewFamilyPhase = Extract<\n Phase,\n { name: 'review' | 'confirming' | 'submitting' | 'submit-error' }\n>;\n\n/** Hebrew Unicode block (U+0590–U+05FF) — chat.tsx's exact detector. */\nconst HEBREW_RE = /[\\u0590-\\u05FF]/;\n\n/** Below this root width the two panes stack (one column, sticky viewer). */\nconst STACKED_BREAKPOINT = 860; // px\n\n/** At most one silent image-URL refresh per window — the refetch-loop brake. */\nconst IMAGE_REFRESH_THROTTLE_MS = 60_000;\n\nconst LOADING_TEXT = 'Loading extraction…';\nconst SESSION_EXPIRED_TEXT = 'Session expired — please reload the page or sign in again.';\n// The SUBMIT-side 401 copy must NOT suggest reloading: the reviewer's edits\n// live only in component state, and a reload would destroy them — while a\n// fresh sign-in in another tab plus Retry preserves and submits them.\nconst SUBMIT_SESSION_EXPIRED_TEXT =\n 'Session expired — sign in again in another tab, then press Retry. Your corrections are still here.';\nconst NOT_AVAILABLE_TEXT = 'This extraction is not available.';\nconst LOAD_FAILED_TEXT = \"Couldn't load the extraction.\";\nconst PURGED_TEXT = 'Document no longer available (retention policy).';\nconst NOT_COMPLETED_TEXT = 'This extraction did not complete, so there is nothing to verify.';\nconst VERIFICATION_UNAVAILABLE_TEXT = \"Verification isn't available for this extraction.\";\n// Deliberately does NOT imply the shown data is the corrected data — the\n// primary view returns the ORIGINAL extraction, not the validated values.\nconst ALREADY_VALIDATED_TEXT = 'Already verified — showing the original extraction.';\n// \"Feedback\" is retired from every user-visible string: it framed the\n// reviewer's corrections as an optional opinion collected for someone else,\n// when they are the values that get recorded. The word survives only in code\n// comments and in the API surface (`meta.validationFeedback`, the `onError`\n// reason names), which are contract rather than copy.\nconst CONFIRM_TEXT =\n \"Submit these values? This is final — they can be submitted once and can't be changed.\";\nconst SUBMITTING_TEXT = 'Submitting…';\nconst SUBMIT_FAILED_TEXT = 'Submission failed — your corrections are still here.';\n// Same verb as the action that produced it: Submit -> Submitted.\nconst DONE_TITLE_TEXT = 'Submitted';\n\n/** What a successful load pins for the review phase (values + schema together,\n * so the derived memos see one consistent snapshot). */\ninterface LoadedData {\n values: unknown;\n schema: string[];\n /** Empty whenever the backend or the host's SDK predates the typed contract. */\n fields: ValidationFieldDescriptor[];\n /**\n * Tables the SERVER declares row-mutable. Empty means no row controls\n * anywhere — the correct behaviour against a pre-1.5.0 backend, and the\n * reason a `custom_template` table never grows an Add line button.\n */\n rowMutableTables: RowMutableTable[];\n}\n\n/** The empty edits map — the initial state AND every load's reset value.\n * One shared instance (SectionShared contract: `edits` is compared by\n * reference, so \"no edits\" must always be the same object). */\nconst NO_EDITS: ReadonlyMap<string, string> = new Map();\n\n/** Same reference-stability contract as NO_EDITS, for the row plans. */\nconst NO_ROW_PLANS: ReadonlyMap<string, RowPlanEntry[]> = new Map();\nconst NO_PLANNED_TABLES: ReadonlyMap<string, PlannedRow[]> = new Map();\n\n/**\n * The identity plan for every table the server declared row-mutable.\n *\n * Returns the shared empty map when there are none, so a pre-1.5.0 backend\n * keeps the exact reference-equality behaviour the row memo depends on.\n */\nfunction seedRowPlans(tables: RowMutableTable[], values: unknown): ReadonlyMap<string, RowPlanEntry[]> {\n if (tables.length === 0) {\n return NO_ROW_PLANS;\n }\n const plans = new Map<string, RowPlanEntry[]>();\n for (const table of tables) {\n plans.set(table.pointer, initialRowPlan(countRowsAt(values, table.pointer), table.pointer));\n }\n return plans;\n}\n\n/**\n * Unavailable reasons that are FAILURES (a thrown fetch: 401/404/network/5xx)\n * announce assertively as role=\"alert\". The meta-derived landings (purged,\n * not-completed, verification-unavailable) are calm facts about the extraction\n * — the load succeeded, there is just nothing to verify — and announce\n * politely as role=\"status\".\n */\nconst ALERT_REASONS: ReadonlySet<VerificationErrorReason> = new Set([\n 'session-expired',\n 'not-available',\n 'load-failed',\n]);\n\n/**\n * Embeddable Gemina extraction-verification UI.\n *\n * ```tsx\n * <GeminaVerification\n * extractionId={extractionId}\n * tokenManager={tokenManager}\n * onComplete={(result) => console.log(result.summary)}\n * />\n * ```\n */\nexport function GeminaVerification(props: GeminaVerificationProps): React.JSX.Element {\n const {\n extractionId,\n tokenManager,\n baseUrl,\n theme = 'auto',\n dir = 'auto',\n onComplete,\n onError,\n className,\n } = props;\n\n const [phase, setPhase] = useState<Phase>({ name: 'loading' });\n // Lifted OUT of the review phase variant (Task 17 restructure): the whole\n // review family reads it (read-only form, banner, hidden progress line)\n // while confirming/submitting/submit-error carry no flags of their own.\n // In every load path read-only ⇔ already-validated, so ONE flag serves both.\n const [alreadyValidated, setAlreadyValidated] = useState(false);\n const [loaded, setLoaded] = useState<LoadedData | null>(null);\n // One plan per row-mutable table, keyed by its pointer. Reset with the\n // edits on every load: a plan outliving its extraction would map rows to\n // sources that no longer exist.\n const [rowPlans, setRowPlans] = useState<ReadonlyMap<string, RowPlanEntry[]>>(NO_ROW_PLANS);\n // Dirty fields only: raw schema key → current input string, VERBATIM (no\n // trim/normalize — that is the composer's job at submit). Replaced\n // immutably on every change; delete-on-revert keeps composeSubmission's\n // confirmed/corrected counts honest (see its edits-map contract).\n const [edits, setEdits] = useState<ReadonlyMap<string, string>>(NO_EDITS);\n // Held separately from `loaded`: the expiry refresh swaps an expired URL in\n // place without disturbing the (memo-feeding) values/schema snapshot.\n const [imageUrl, setImageUrl] = useState<string | null>(null);\n // The rects currently flashing on the viewer (null = no flash in flight).\n const [flashRects, setFlashRects] = useState<RelativeRect[] | null>(null);\n // One-column layout, driven by the ROOT's own width (see the observer below).\n const [stacked, setStacked] = useState(false);\n // The review filter hides fields and rows that already scored `high`.\n // OFF by default: this component ships to every embedder, so an unfiltered\n // form is the default everywhere, and the state is never persisted.\n const [filterOn, setFilterOn] = useState(false);\n\n const rootRef = useRef<HTMLDivElement | null>(null);\n const mountedRef = useRef(false);\n // Monotonic load id: a load that lost the race (prop change re-ran the\n // effect, or Retry started a newer attempt) must not write its result.\n const loadSeqRef = useRef(0);\n // Timestamp of the last expiry-triggered refetch (the 60s throttle).\n const lastImageRefreshRef = useRef(0);\n // Latest onError without threading its identity through the load callback.\n const onErrorRef = useRef(onError);\n onErrorRef.current = onError;\n const onCompleteRef = useRef(onComplete);\n onCompleteRef.current = onComplete;\n // onComplete fires EXACTLY once per loaded extraction; load() resets it.\n const completedRef = useRef(false);\n // Re-entry latch for doSubmit (the disabled Confirm button is the UI guard;\n // this is the belt for a re-dispatch racing the disabling re-render).\n const submitInFlightRef = useRef(false);\n // Set by Cancel: focus returns to the Submit button, but only from the\n // effect AFTER the review re-render — while the handler runs the phase is\n // still `confirming`, so the footer button is still disabled and unfocusable.\n const restoreFocusRef = useRef(false);\n const submitButtonRef = useRef<HTMLButtonElement | null>(null);\n const confirmButtonRef = useRef<HTMLButtonElement | null>(null);\n const cancelButtonRef = useRef<HTMLButtonElement | null>(null);\n // Focus landings for the phases that unmount the dialog under the keyboard\n // user: the submit-error Retry button, and the done state (tabIndex -1).\n const retrySubmitButtonRef = useRef<HTMLButtonElement | null>(null);\n const doneStateRef = useRef<HTMLDivElement | null>(null);\n\n /**\n * Enter a terminal unavailable state and notify the host. onError fires\n * once per terminal-state ENTRY (see the prop's JSDoc): each resolved load\n * attempt calls this at most once, and a Retry that fails again re-enters —\n * and therefore re-fires.\n */\n const enterUnavailable = useCallback(\n (\n reason: VerificationErrorReason,\n message: string,\n canRetry: boolean,\n detail?: VerificationErrorDetail,\n ) => {\n setPhase({ name: 'unavailable', reason, message, canRetry });\n onErrorRef.current?.(reason, detail);\n },\n [],\n );\n\n const fetchOnce = useCallback(async () => {\n const token = await tokenManager.getToken();\n return GeminaClient.withSessionToken(token, baseUrl).documents.getDocumentExtraction({\n documentExtractionId: extractionId,\n });\n }, [tokenManager, baseUrl, extractionId]);\n\n /** The chat widget's mandated 401 pattern: invalidate + retry exactly once. */\n const fetchWithRetry = useCallback(async () => {\n try {\n return await fetchOnce();\n } catch (error) {\n if (httpStatus(error) !== 401) {\n throw error;\n }\n tokenManager.invalidate();\n return await fetchOnce();\n }\n }, [fetchOnce, tokenManager]);\n\n const load = useCallback(async () => {\n const seq = ++loadSeqRef.current;\n /** Guard on EVERY async setState: unmount AND stale-load protection. */\n const live = () => mountedRef.current && loadSeqRef.current === seq;\n\n setPhase({ name: 'loading' });\n // Per-extraction onComplete semantics: a new load (extractionId change,\n // Retry, the 409 refetch) re-arms the exactly-once guard.\n completedRef.current = false;\n // A stale flash must not survive into the next review: the viewer\n // unmounts during loading, and a REMOUNTED viewer handed old non-null\n // flashRects would phantom-flash the new document once it sizes up.\n setFlashRects(null);\n // A new load must not inherit the previous extraction's expiry-refresh\n // throttle window (the viewer is unmounted until review re-enters, so\n // nothing can race this reset).\n lastImageRefreshRef.current = 0;\n let view: ExtractionPrimaryViewOutDTO;\n try {\n view = await fetchWithRetry();\n } catch (error) {\n // Reading the error body is async (fetch), so re-check liveness after.\n const detail = await readErrorEnvelope(error);\n if (!live()) {\n return;\n }\n if (detail.status === 401) {\n // Only reachable after the invalidate-retry-once path failed again.\n enterUnavailable('session-expired', SESSION_EXPIRED_TEXT, false, detail);\n } else if (detail.status === 404) {\n enterUnavailable('not-available', NOT_AVAILABLE_TEXT, false, detail);\n } else {\n // Everything else — 5xx, network failures, and a tokenManager whose\n // fetchToken rejected (no HTTP status at all) — is retryable: the\n // server or the tenant's token backend may recover.\n enterUnavailable('load-failed', LOAD_FAILED_TEXT, true, detail);\n }\n return;\n }\n if (!live()) {\n return;\n }\n\n const enterReview = (validated: boolean) => {\n const schema = view.meta.validationFeedback?.validationSchema;\n setLoaded({\n values: view.values,\n schema: Array.isArray(schema) ? schema : [],\n fields: readDescriptors(view.meta.validationFeedback?.validationFields),\n rowMutableTables: readRowMutableTables(view.meta.validationFeedback?.rowMutableTables),\n });\n // Fresh extraction data → clean editing slate, batched with setLoaded so\n // new bindings never pair with old edits for even one commit. Covers the\n // extractionId change, Retry, AND the Task-17 409-refetch (all of which\n // route through load()).\n setEdits(NO_EDITS);\n // The filter is a view mode on THIS extraction, so it resets with the\n // slate. Without this, the same mounted component opens the next\n // extraction already filtered, which reads as missing fields.\n setFilterOn(false);\n setRowPlans(seedRowPlans(readRowMutableTables(view.meta.validationFeedback?.rowMutableTables), view.values));\n const url = view.document.imageUrl;\n setImageUrl(typeof url === 'string' && url.length > 0 ? url : null);\n setAlreadyValidated(validated);\n setPhase({ name: 'review' });\n };\n\n // Result mapping — EXACT order: purge before status, validated before\n // schema (an already-validated extraction with a null schema must land in\n // review-readOnly, not verification-unavailable).\n if (view.meta.purgedAt != null) {\n enterUnavailable('purged', PURGED_TEXT, false);\n } else if (view.meta.processingStatus !== 'success') {\n enterUnavailable('not-completed', NOT_COMPLETED_TEXT, false);\n } else if (view.meta.validated === true) {\n enterReview(true);\n } else if (\n !Array.isArray(view.meta.validationFeedback?.validationSchema) ||\n view.meta.validationFeedback.validationSchema.length === 0\n ) {\n enterUnavailable('verification-unavailable', VERIFICATION_UNAVAILABLE_TEXT, false);\n } else {\n enterReview(false);\n }\n }, [fetchWithRetry, enterUnavailable]);\n\n useEffect(() => {\n mountedRef.current = true;\n ensureVerificationStylesInjected();\n void load();\n return () => {\n mountedRef.current = false;\n };\n }, [load]);\n\n // Stacked layout: the ROOT observes its OWN width — not the window, because\n // the host may embed the widget in a narrow column of a wide page — and\n // flips to one column below the breakpoint. useEffect (not layout effect)\n // keeps server rendering warning-free; the first client frame corrects.\n // SSR/test-safe: no ResizeObserver → a one-shot measure; a width of 0\n // (unmeasured or hidden host) never forces a layout flip.\n useEffect(() => {\n const el = rootRef.current;\n if (el === null) {\n return;\n }\n const apply = (width: number) => setStacked(width > 0 && width < STACKED_BREAKPOINT);\n if (typeof ResizeObserver === 'undefined') {\n apply(el.getBoundingClientRect().width);\n return;\n }\n const observer = new ResizeObserver((entries) => {\n const entry = entries[0];\n if (!entry) {\n return;\n }\n // Border-box width: the element's OUTER width — the same box the\n // no-ResizeObserver fallback's getBoundingClientRect measures, so the\n // 860px breakpoint means one thing on both paths. contentRect is the\n // pre-borderBoxSize fallback (Safari < 15.4), off by padding + border.\n const width = entry.borderBoxSize?.[0]?.inlineSize ?? entry.contentRect.width;\n apply(width);\n });\n observer.observe(el);\n return () => observer.disconnect();\n }, []);\n\n // --- Derived review data — computed ONCE per load (form stability contract:\n // `classified`/`bindingIndex` are compared by reference in the row memo). ---\n // classifyData is total (null/garbage values → empty buckets) — no guard.\n const classified = useMemo(() => classifyData(loaded?.values), [loaded]);\n const bindings = useMemo(\n () => buildBindings(loaded?.schema ?? [], loaded?.values, loaded?.fields),\n [loaded],\n );\n const bindingIndex = useMemo(() => indexBindingsByFieldPointer(bindings), [bindings]);\n // By RAW key — how a planned table cell finds the extracted value behind it.\n const bindingsByRawKey = useMemo(() => {\n const map = new Map<string, FieldBinding>();\n for (const binding of bindings) {\n map.set(binding.key.raw, binding);\n }\n return map;\n }, [bindings]);\n // Bindings whose fieldPointer matches no classified leaf — the \"model\n // missed the whole field\" case, rendered as the form's Not-detected section.\n const unmatched = useMemo(() => {\n const rendered = new Set<string>();\n for (const field of classified.headers) {\n rendered.add(field.pointer);\n }\n for (const list of classified.simpleLists) {\n for (const item of list.items) {\n rendered.add(item.pointer);\n }\n }\n for (const entity of classified.entities) {\n for (const item of entity.items) {\n for (const cell of Object.values(item)) {\n rendered.add(cell.pointer);\n }\n }\n }\n for (const table of classified.tables) {\n for (const row of table.rows) {\n for (const [key, cell] of Object.entries(row)) {\n // _rowMeta is synthetic (its pointer is the ROW pointer) — it never\n // corresponds to a binding, so it must not mask one.\n if (key !== ROW_META_KEY) {\n rendered.add(cell.pointer);\n }\n }\n }\n }\n return bindings.filter((binding) => !rendered.has(binding.fieldPointer));\n }, [classified, bindings]);\n // Every detection region the extraction carries, feeding the viewer's\n // overlay toggle. Memoized on the classified snapshot (stability contract):\n // the viewer sees ONE stable array per load. undefined when there is\n // genuinely nothing to overlay — the viewer's hasRects check treats\n // undefined and empty alike (toggle disabled); undefined states the intent.\n const overlayRects = useMemo(() => {\n const rects: RelativeRect[] = [];\n for (const field of classified.headers) {\n if (field.coordinates) {\n rects.push(field.coordinates);\n }\n }\n for (const list of classified.simpleLists) {\n for (const item of list.items) {\n if (item.coordinates) {\n rects.push(item.coordinates);\n }\n }\n }\n for (const entity of classified.entities) {\n for (const item of entity.items) {\n for (const cell of Object.values(item)) {\n if (cell.coordinates) {\n rects.push(cell.coordinates);\n }\n }\n }\n }\n for (const table of classified.tables) {\n for (const row of table.rows) {\n for (const [key, cell] of Object.entries(row)) {\n // _rowMeta is synthetic (coordinates null by construction) — skip\n // it so a future row-level coordinate never renders a stray box.\n if (key !== ROW_META_KEY && cell.coordinates) {\n rects.push(cell.coordinates);\n }\n }\n }\n }\n return rects.length > 0 ? rects : undefined;\n }, [classified]);\n\n // dir=\"auto\" (chat parity): Hebrew anywhere in the bound DISPLAY values —\n // toInputString over binding.extracted, the same strings the inputs prefill,\n // never the raw JSON payload — flips the whole widget to RTL. Computed once\n // per load: `bindings` is memoized on the loaded snapshot.\n const hasHebrewContent = useMemo(\n () => bindings.some((binding) => HEBREW_RE.test(toInputString(binding.extracted))),\n [bindings],\n );\n const effectiveDir: 'ltr' | 'rtl' = dir === 'auto' ? (hasHebrewContent ? 'rtl' : 'ltr') : dir;\n\n // Revert detection needs the binding behind a raw key. Read through a ref\n // so handleEdit stays permanently stable (SectionShared contract: the\n // table-row memo compares onEdit by reference; a per-load identity would\n // silently re-render every row once per load).\n\n // The edit tracker. The value is stored VERBATIM — never trimmed or\n // normalized (IME safety: the input must echo exactly what the user is\n // composing; composeSubmission trims at submit time). Dirty-tracking\n // contract (Task 4): the entry is DELETED when the value returns to the\n // binding's initial input string, so composeSubmission's counts stay honest.\n // Every change builds a NEW Map (SectionShared: the row-memo comparator\n // short-circuits on reference equality, so in-place mutation renders nothing);\n // no-op updates return `prev` unchanged to keep that same short-circuit.\n const handleEdit = useCallback((editKey: string, value: string, binding: FieldBinding) => {\n // Pristine = the input shows exactly what an untouched input would show:\n // toInputString of the binding's DISPLAY value (FieldInput's prefill) —\n // including '' for a never-extracted fill-in.\n const pristine = value === toInputString(binding.extracted);\n setEdits((prev) => {\n if (pristine) {\n if (!prev.has(editKey)) {\n return prev;\n }\n const next = new Map(prev);\n next.delete(editKey);\n return next;\n }\n if (prev.get(editKey) === value) {\n return prev;\n }\n const next = new Map(prev);\n next.set(editKey, value);\n return next;\n });\n }, []);\n\n // Progress counts — composeSubmission IS the source of truth (the same call\n // Task 17 submits), so the line can never disagree with what would be sent.\n /**\n * Every row-mutable table's rows, resolved to cells. Computed once and shared\n * with the form, the pair rule and the submit gate — deriving it per consumer\n * is how they would come to disagree about which row a cell belongs to.\n */\n const plannedTables = useMemo(() => {\n const tables = loaded?.rowMutableTables ?? [];\n if (tables.length === 0) {\n return NO_PLANNED_TABLES;\n }\n const out = new Map<string, PlannedRow[]>();\n for (const table of tables) {\n const plan = rowPlans.get(table.pointer);\n if (plan === undefined) {\n continue;\n }\n const classifiedTable = classified.tables.find(\n (candidate) => matchesTablePointer(table.pointer, candidate.pointer),\n );\n const columns = displayColumns(table, classifiedTable?.columns ?? []);\n out.set(table.pointer, planTableCells(table, plan, columns, bindingsByRawKey));\n }\n return out;\n }, [loaded, rowPlans, classified, bindingsByRawKey]);\n\n /** Every editable cell, planned or not — the pair rule and the gate share it. */\n const cellViews = useMemo(\n () => collectCellViews(bindings, plannedTables),\n [bindings, plannedTables],\n );\n\n /**\n * The same tables, minus added rows nobody typed into. Used for SUBMISSION\n * only — the empty row stays on screen so the reviewer can still fill it in.\n */\n const submissionTables = useMemo(\n () => pruneEmptyAddedRows(plannedTables, edits),\n [plannedTables, edits],\n );\n const submissionCells = useMemo(\n () => collectCellViews(bindings, submissionTables),\n [bindings, submissionTables],\n );\n\n /**\n * The alignment for every table whose row set the reviewer actually changed.\n *\n * Identity plans are OMITTED, not sent as a no-op: the wire payload for an\n * untouched submission has to stay byte-identical to what it was before row\n * editing existed, and a pre-2b backend silently ignores the key anyway.\n */\n const rowSources = useMemo(() => {\n const entries: RowSourcesEntry[] = [];\n for (const table of loaded?.rowMutableTables ?? []) {\n // From the PRUNED rows, so an abandoned \"Add line\" leaves no trace.\n const rows = submissionTables.get(table.pointer);\n if (rows === undefined) {\n continue;\n }\n const plan = rows.map((row) => row.entry);\n if (isIdentityPlan(plan, countRowsAt(loaded?.values, table.pointer))) {\n continue;\n }\n entries.push({ table: table.pointer, sources: rowSourcesOf(plan) });\n }\n return entries;\n }, [loaded, submissionTables]);\n\n const submission = useMemo(\n () => composeSubmission(bindings, edits, { cells: submissionCells, rowSources }),\n [bindings, edits, submissionCells, rowSources],\n );\n\n // Flash wiring (form → viewer). STABLE callback — the table-row memo\n // compares onFlash by reference, so rows never re-render on unrelated\n // flashes — that stores a FRESH array per eye-click: TableRow memoizes its\n // row rects, so without the copy a second click on the same row would hand\n // the viewer's flash effect an identical reference and never restart.\n const handleFlash = useCallback((rects: Array<{ points: [number, number][] }>) => {\n setFlashRects(rects.map((rect) => ({ points: rect.points })));\n }, []);\n\n // The viewer announces the fade finished: drop our reference so the next\n // click is a fresh transition. NEVER gate anything beyond this cleanup on\n // onFlashComplete — it may never fire (the image may never load).\n const handleFlashComplete = useCallback(() => {\n setFlashRects(null);\n }, []);\n\n /**\n * Silent expired-image-URL refresh. Swaps ONLY `imageUrl` — deliberately\n * NOT `loaded` (values/meta): replacing the loaded snapshot would re-create\n * the memoized classified/bindings objects and shift the dirty-tracking\n * baseline mid-edit, yanking the form out from under the reviewer. (The\n * plan's \"and refreshed values/meta\" parenthetical is superseded by review.)\n * Throttled to one refetch per 60s so a signed URL that keeps dying (e.g. a\n * document purged mid-review) cannot refetch-loop; the viewer's own\n * has-loaded gate already stops the loop for URLs that never load at all.\n *\n * INVARIANT: any future refetch that writes state must bump loadSeqRef or\n * route through load() — a refetch that writes without owning the sequence\n * can be overtaken by a newer load and clobber its state.\n */\n const handleImageExpired = useCallback(() => {\n const now = Date.now();\n if (now - lastImageRefreshRef.current < IMAGE_REFRESH_THROTTLE_MS) {\n return;\n }\n lastImageRefreshRef.current = now;\n const seq = loadSeqRef.current;\n fetchWithRetry()\n .then((view) => {\n // A newer load owns the state now (or we unmounted) — drop it.\n if (!mountedRef.current || loadSeqRef.current !== seq) {\n return;\n }\n const url = view.document.imageUrl;\n if (typeof url === 'string' && url.length > 0) {\n setImageUrl(url);\n }\n })\n // Swallowed by design: the refresh is best-effort background work — the\n // review (and any pending edits) must stay put on failure. The reviewer\n // keeps a broken image until the next throttle window; phase/loaded/\n // edits are never touched from here.\n .catch(() => {});\n }, [fetchWithRetry]);\n\n const handleRetry = useCallback(() => {\n void load();\n }, [load]);\n\n /** Row controls. Both replace the whole map so the row memo sees a new\n * reference exactly when a plan actually changed. */\n const handleAddRow = useCallback((tablePointer: string, afterPosition: number) => {\n // Minted HERE, not inside the updater: an updater must be pure, and React\n // invokes it twice under Strict Mode.\n const id = nextAddedRowId(tablePointer);\n setRowPlans((prev) => {\n const plan = prev.get(tablePointer);\n if (plan === undefined) {\n return prev;\n }\n const next = new Map(prev);\n next.set(tablePointer, insertRowAfter(plan, afterPosition, id));\n return next;\n });\n }, []);\n\n const handleRemoveRow = useCallback((tablePointer: string, position: number) => {\n setRowPlans((prev) => {\n const plan = prev.get(tablePointer);\n if (plan === undefined) {\n return prev;\n }\n const nextPlan = removeRow(plan, position);\n if (nextPlan === plan) {\n return prev;\n }\n const next = new Map(prev);\n next.set(tablePointer, nextPlan);\n return next;\n });\n }, []);\n\n /**\n * How many edited fields the reviewer must fix before this can be submitted.\n *\n * Derived from `edits` x descriptors, NOT from every binding: an extracted\n * value that fails validation is the model's output, not the reviewer's\n * mistake, and blocking a submission on a field they never touched would be\n * indefensible. FieldInput applies the identical rule when deciding whether\n * to show its inline error, so the count and the red borders can never\n * disagree.\n *\n * Validation is one-shot and irreversible, so the gate is a hard disable\n * rather than a warning.\n */\n /**\n * The one cross-field rule the server enforces, surfaced before submission\n * rather than discovered after it. See `unitSizePairErrors`.\n */\n const pairErrors = useMemo(() => unitSizePairErrors(cellViews, edits), [cellViews, edits]);\n\n // --- review filter -------------------------------------------------------\n // The SAME suppression the form applies, computed from the SAME helper, so\n // the two can never disagree about which promoted headers exist. A pointer\n // counted here but skipped there (or vice versa) makes \"Showing X of Y\" lie.\n // The SAME promotion the form applies, from the SAME helper, so the two can\n // never disagree about which tables are rendered or which headers are\n // suppressed. `tables` matters as much as `suppressed`: an empty\n // server-declared row-mutable table is promoted into the rendered list\n // without existing in `classified.tables`, so rows added to one would\n // otherwise render without being counted.\n const rendered = useMemo(\n () => withEmptyMutableTables(classified, loaded?.rowMutableTables ?? []),\n [classified, loaded?.rowMutableTables],\n );\n // Offering the switch on an unscored extraction would be a control that\n // does nothing. Overall confidence does not count — it is not a review unit\n // and cannot be hidden.\n const canFilter = useMemo(\n () => hasAnyConfidence(classified, rendered.tables, plannedTables),\n [classified, rendered, plannedTables],\n );\n const hidden = useMemo(\n () => (filterOn && canFilter\n ? computeHidden({\n classified,\n tables: rendered.tables,\n plannedTables,\n cellViews,\n bindingIndex,\n edits,\n pairErrors,\n suppressed: rendered.suppressed,\n })\n : NOTHING_HIDDEN),\n [filterOn, canFilter, classified, rendered, plannedTables, cellViews, bindingIndex, edits, pairErrors],\n );\n // `unmatched` bindings render as the \"Not detected\" section — editable\n // fields the reviewer can fill in — so they are review units too. They carry\n // no confidence and are therefore never hidden, which is why they add to\n // both totals equally. Leaving them out made the count contradict the screen.\n const totalUnits = useMemo(\n () => countUnits(classified, rendered.tables, plannedTables, rendered.suppressed) + unmatched.length,\n [classified, rendered, plannedTables, unmatched],\n );\n const visibleUnits = totalUnits - hidden.fields.size - hidden.rows.size;\n // Only while filtering, and only when there was something to begin with:\n // a genuinely empty extraction is a different state with its own copy.\n const allClear = filterOn && totalUnits > 0 && visibleUnits === 0;\n\n const invalidCount = useMemo(() => {\n // Row-level errors count even with no edits at all: the extraction itself\n // can arrive with one half of the pair filled.\n const rowLevel = pairErrors.size;\n if (edits.size === 0) {\n return rowLevel;\n }\n const byEditKey = new Map(cellViews.map((view) => [view.editKey, view.binding]));\n let count = 0;\n for (const [editKey, value] of edits) {\n // A cell already flagged by the row rule must not be counted twice.\n if (!pairErrors.has(editKey) && validateInput(value, byEditKey.get(editKey)?.field) !== null) {\n count += 1;\n }\n }\n return count + rowLevel;\n }, [edits, cellViews, pairErrors]);\n\n /**\n * The PUT. Reuses the `submission` memo — the SAME pure composeSubmission\n * result the progress line displays — so what the reviewer was just shown\n * (\"N confirmed · M corrected\") is by construction what goes on the wire.\n * 401 handling mirrors the GET: invalidate + retry exactly once. Outcomes:\n * success → done (+ exactly-once onComplete); 409 → SILENT refetch through\n * load() (the seq-guard invariant), landing in the already-validated\n * read-only review with no onError; 401 after the retry → submit-error with\n * the session-expired copy; anything else → submit-error with the server's\n * description when present. Edits are NEVER cleared on failure — the\n * submit-error review keeps the form (and the corrections) mounted.\n */\n const doSubmit = useCallback(async () => {\n if (submitInFlightRef.current) {\n return;\n }\n submitInFlightRef.current = true;\n const seq = loadSeqRef.current;\n /** Same liveness rule as load(): a newer load owns the state now. */\n const live = () => mountedRef.current && loadSeqRef.current === seq;\n setPhase({ name: 'submitting' });\n const body = submission;\n const submitOnce = async () => {\n const token = await tokenManager.getToken();\n return GeminaClient.withSessionToken(token, baseUrl).documents.validateDocumentExtraction({\n targetDocumentExtractionId: extractionId,\n // Conditional spread, matching the house pattern: without a row edit\n // the request body is byte-identical to what it was before this\n // feature, so nothing changes for the overwhelmingly common path.\n extractionValidationInDTO: {\n data: body.data,\n ...(body.rowSources.length > 0 ? { rowSources: body.rowSources } : {}),\n },\n });\n };\n try {\n let result: Awaited<ReturnType<typeof submitOnce>>;\n try {\n try {\n result = await submitOnce();\n } catch (error) {\n if (httpStatus(error) !== 401) {\n throw error;\n }\n tokenManager.invalidate();\n result = await submitOnce();\n }\n } catch (error) {\n const detail = await readErrorEnvelope(error);\n if (!live()) {\n return;\n }\n if (detail.status === 409) {\n // Someone verified concurrently. Refetch and land in the\n // already-validated read-only banner state — deliberately NO\n // onError (the extraction IS verified; that is a success shape),\n // and the brief loading flash is accepted.\n void load();\n return;\n }\n if (detail.status === 401) {\n // Only after the one mandated retry. Edits are kept: a fresh\n // sign-in elsewhere + Retry can still succeed — hence the\n // submit-specific copy (never \"reload the page\").\n setPhase({ name: 'submit-error', message: SUBMIT_SESSION_EXPIRED_TEXT });\n onErrorRef.current?.('session-expired', detail);\n return;\n }\n setPhase({\n name: 'submit-error',\n message: detail.description ?? SUBMIT_FAILED_TEXT,\n });\n onErrorRef.current?.('submit-failed', detail);\n return;\n }\n if (!live()) {\n return;\n }\n setPhase({ name: 'done', confirmed: body.confirmed, corrected: body.corrected });\n if (!completedRef.current) {\n completedRef.current = true;\n // The generated client resolves ExtractionValidationResultOutDTO;\n // its `.data` is the ComparisonSummaryModel the host is promised.\n onCompleteRef.current?.({ correctedValues: body.byLabel, summary: result.data });\n }\n } finally {\n submitInFlightRef.current = false;\n }\n }, [submission, tokenManager, baseUrl, extractionId, load]);\n\n const handleSubmitClick = useCallback(() => {\n setPhase({ name: 'confirming' });\n }, []);\n\n const handleConfirm = useCallback(() => {\n void doSubmit();\n }, [doSubmit]);\n\n const handleCancelConfirm = useCallback(() => {\n restoreFocusRef.current = true;\n setPhase({ name: 'review' });\n }, []);\n\n /** Retry goes STRAIGHT back to submitting — confirm-final is never re-asked. */\n const handleRetrySubmit = useCallback(() => {\n void doSubmit();\n }, [doSubmit]);\n\n const handleConfirmKeyDown = useCallback(\n (event: React.KeyboardEvent) => {\n // Keys only act while the QUESTION is open. During `submitting` the\n // in-flight PUT cannot be aborted (Escape is ignored) and both dialog\n // buttons are disabled — nothing inside is focusable, so there is\n // nothing to trap either; the phase resolves to done/submit-error in\n // one round-trip and the phase-entry effect re-anchors focus there.\n if (phase.name !== 'confirming') {\n return;\n }\n if (event.key === 'Escape') {\n event.stopPropagation();\n handleCancelConfirm();\n return;\n }\n // Minimal focus trap: the dialog has exactly two tabbables (Cancel and\n // Confirm), so Tab/Shift+Tab wrap between them instead of escaping into\n // the scrimmed background the overlay only covers visually.\n if (event.key === 'Tab') {\n const cancel = cancelButtonRef.current;\n const confirm = confirmButtonRef.current;\n if (cancel === null || confirm === null) {\n return;\n }\n const active = document.activeElement;\n if (event.shiftKey && active === cancel) {\n event.preventDefault();\n confirm.focus();\n } else if (!event.shiftKey && active === confirm) {\n event.preventDefault();\n cancel.focus();\n } else if (active !== cancel && active !== confirm) {\n // Belt only: focus INSIDE the overlay subtree but on neither button\n // (no such element exists today). This is NOT scrim-click recovery —\n // a blur to <body> would put keydowns outside this subtree handler\n // entirely; the scrim's mousedown preventDefault is what keeps that\n // blur from ever happening.\n event.preventDefault();\n confirm.focus();\n }\n }\n },\n [phase.name, handleCancelConfirm],\n );\n\n // Phase-entry focus anchoring. Entering `confirming` moves focus to the\n // final-action button (Enter submits, Escape cancels); a Cancel hands it\n // back to the Submit button — from here, AFTER the review re-render\n // re-enabled it. The two phases that unmount the dialog under the keyboard\n // user get their own landings (without them focus drops to <body>):\n // submit-error → the inline Retry button; done → the state container\n // (tabIndex -1, no ring — a non-interactive announcement landing).\n useEffect(() => {\n if (phase.name === 'confirming') {\n confirmButtonRef.current?.focus();\n } else if (phase.name === 'review' && restoreFocusRef.current) {\n restoreFocusRef.current = false;\n submitButtonRef.current?.focus();\n } else if (phase.name === 'submit-error') {\n retrySubmitButtonRef.current?.focus();\n } else if (phase.name === 'done') {\n doneStateRef.current?.focus();\n }\n }, [phase.name]);\n\n const rootClassName = [\n 'gemina-verification',\n `gemina-verification--${theme}`,\n effectiveDir === 'rtl' ? 'gemina-verification--rtl' : '',\n stacked ? 'gemina-verification--stacked' : '',\n className ?? '',\n ]\n .filter((part) => part.length > 0)\n .join(' ');\n\n // One id per instance for the dialog's label (multiple widgets may coexist).\n const dialogTextId = useId();\n\n /**\n * The review family: review | confirming | submitting | submit-error all\n * render THIS content, so the form (edits included!) and the aria-live\n * progress region stay mounted through the whole submit sequence. Only the\n * decorations differ per member: confirming/submitting put the overlay up\n * (same dialog shell — the copy flips to \"Submitting…\" and both buttons\n * disable, which is the double-click guard), submit-error adds the inline\n * error banner. The form is never readOnly-flipped mid-flight — that would\n * visually discard the reviewer's edits.\n */\n const renderReview = (reviewPhase: ReviewFamilyPhase): React.JSX.Element => {\n const overlayUp = reviewPhase.name === 'confirming' || reviewPhase.name === 'submitting';\n return (\n <>\n {alreadyValidated && (\n <div className=\"gemina-verification__banner\">{ALREADY_VALIDATED_TEXT}</div>\n )}\n <div className=\"gemina-verification__panes\">\n {imageUrl !== null && (\n <VerificationViewer\n src={imageUrl}\n relativeRects={overlayRects}\n flashRects={flashRects}\n onFlashComplete={handleFlashComplete}\n onImageExpired={handleImageExpired}\n />\n )}\n {/* Everything scored high and the reviewer asked to see only what\n needs attention — so the form would be empty. An empty form is\n indistinguishable from a broken one, so say which it is. */}\n {allClear ? (\n <p className=\"gemina-verification__all-scored\" role=\"status\">\n {`Nothing needs review — all ${totalUnits} fields scored high.`}\n </p>\n ) : (\n <VerificationForm\n classified={classified}\n unmatched={unmatched}\n bindingIndex={bindingIndex}\n edits={edits}\n onEdit={handleEdit}\n readOnly={alreadyValidated}\n onFlash={handleFlash}\n pairErrors={pairErrors}\n rowMutableTables={loaded?.rowMutableTables}\n hidden={hidden}\n filterOn={filterOn}\n plannedTables={plannedTables}\n onAddRow={handleAddRow}\n onRemoveRow={handleRemoveRow}\n />\n )}\n </div>\n {reviewPhase.name === 'submit-error' && (\n <div\n className=\"gemina-verification__banner gemina-verification__banner--error gemina-verification__submit-error\"\n role=\"alert\"\n >\n <span>{reviewPhase.message}</span>\n <button\n type=\"button\"\n ref={retrySubmitButtonRef}\n className=\"gemina-verification__retry\"\n onClick={handleRetrySubmit}\n >\n Retry\n </button>\n </div>\n )}\n <div className=\"gemina-verification__footer\">\n {/* aria-live: a reviewer deep in a long form hears the count move\n as they confirm/correct without tabbing back to the footer.\n Hidden when read-only — the already-verified landing would\n otherwise show \"0 corrected\" noise about the ORIGINAL payload —\n while the disabled Submit stays for discoverability. */}\n {/* One job per element: while anything is invalid the footer states\n the blocker, and the progress count steps aside rather than\n competing with it for the same corner of the screen. */}\n {!alreadyValidated && (\n invalidCount > 0 ? (\n <div className=\"gemina-verification__attention\" aria-live=\"polite\">\n {invalidCount === 1\n ? '1 field needs attention'\n : `${invalidCount} fields need attention`}\n </div>\n ) : (\n <div className=\"gemina-verification__progress\" aria-live=\"polite\">\n {`${submission.confirmed} confirmed · ${submission.corrected} corrected`}\n </div>\n )\n )}\n {/* A VIEW MODE, so role=switch rather than a button that \"does\" something.\n Omitted entirely when nothing is scored — the same treatment the\n eye button gets when a field has no coordinates, and the reason\n is the same: an affordance that cannot do anything is noise.\n The count is the safety rail. A filtered form that looks\n unfiltered is how a reviewer concludes data went missing, so the\n live region announces the change to anyone not watching it. */}\n {canFilter && (\n <>\n <button\n type=\"button\"\n role=\"switch\"\n aria-checked={filterOn}\n className=\"gemina-verification__review-filter\"\n onClick={() => setFilterOn((on) => !on)}\n >\n Hide high-confidence fields\n </button>\n {/* The count sits OUTSIDE the switch on purpose. Inside, it would\n change the control's accessible NAME on every toggle and be\n re-announced whenever the button took focus; outside, the name\n stays constant, the visible label still matches it (WCAG\n 2.5.3), and the live region announces only what changed. */}\n {filterOn && (\n <span className=\"gemina-verification__filter-count\" aria-live=\"polite\">\n {`Showing ${visibleUnits} of ${totalUnits}`}\n </span>\n )}\n </>\n )}\n <button\n type=\"button\"\n ref={submitButtonRef}\n className=\"gemina-verification__submit\"\n disabled={alreadyValidated || reviewPhase.name !== 'review' || invalidCount > 0}\n onClick={handleSubmitClick}\n >\n Submit\n </button>\n </div>\n {overlayUp && (\n <div\n className=\"gemina-verification__confirm\"\n onKeyDown={handleConfirmKeyDown}\n // A press anywhere NON-interactive — the scrim AND the dialog's\n // own interior (the confirm text, padding, actions row) — must not\n // blur the dialog: preventDefault on mousedown suppresses the\n // browser's focus-move default, so activeElement stays on a dialog\n // button and the subtree keydown handler above stays in the focus\n // path (focus on <body> would put Escape/Tab out of its reach).\n // Only presses on a button keep their default. Trade-off, accepted:\n // the dialog copy (one sentence) can't be text-selected by mouse.\n onMouseDown={(event) => {\n if (!(event.target as Element).closest('button')) {\n event.preventDefault();\n }\n }}\n >\n <div\n className=\"gemina-verification__confirm-dialog\"\n role=\"dialog\"\n aria-modal=\"true\"\n aria-labelledby={dialogTextId}\n >\n <p id={dialogTextId} className=\"gemina-verification__confirm-text\">\n {reviewPhase.name === 'submitting' ? SUBMITTING_TEXT : CONFIRM_TEXT}\n </p>\n <div className=\"gemina-verification__confirm-actions\">\n <button\n type=\"button\"\n ref={cancelButtonRef}\n className=\"gemina-verification__confirm-cancel\"\n onClick={handleCancelConfirm}\n disabled={reviewPhase.name === 'submitting'}\n >\n Cancel\n </button>\n <button\n type=\"button\"\n ref={confirmButtonRef}\n className=\"gemina-verification__submit\"\n onClick={handleConfirm}\n disabled={reviewPhase.name === 'submitting'}\n >\n Confirm submission\n </button>\n </div>\n </div>\n </div>\n )}\n </>\n );\n };\n\n // EXHAUSTIVE by construction: the explicit return type makes a phase\n // variant without a case a compile error (the function could fall through\n // returning undefined) — a forgotten renderer can never ship as a blank\n // widget. No default clause, ever.\n const content = ((): React.JSX.Element => {\n switch (phase.name) {\n case 'loading':\n return (\n <div className=\"gemina-verification__state\" role=\"status\">\n {LOADING_TEXT}\n </div>\n );\n case 'unavailable':\n return (\n <div\n className=\"gemina-verification__state\"\n role={ALERT_REASONS.has(phase.reason) ? 'alert' : 'status'}\n >\n <div>{phase.message}</div>\n {phase.canRetry && (\n <button type=\"button\" className=\"gemina-verification__retry\" onClick={handleRetry}>\n Retry\n </button>\n )}\n </div>\n );\n case 'review':\n case 'confirming':\n case 'submitting':\n case 'submit-error':\n return renderReview(phase);\n case 'done':\n return (\n <div\n ref={doneStateRef}\n // Programmatic focus landing only — see the phase-entry focus\n // effect. Not tab-reachable; the stylesheet suppresses the ring.\n tabIndex={-1}\n className=\"gemina-verification__state gemina-verification__state--done\"\n role=\"status\"\n >\n <span className=\"gemina-verification__done-check\" aria-hidden=\"true\">\n <svg width=\"20\" height=\"20\" viewBox=\"0 0 20 20\" fill=\"none\">\n <path\n d=\"M4 10.5l4 4 8-9\"\n stroke=\"currentColor\"\n strokeWidth=\"2.4\"\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n />\n </svg>\n </span>\n <div className=\"gemina-verification__done-title\">{DONE_TITLE_TEXT}</div>\n <div className=\"gemina-verification__progress\">\n {`${phase.confirmed} confirmed · ${phase.corrected} corrected`}\n </div>\n </div>\n );\n }\n })();\n\n return (\n <div ref={rootRef} className={rootClassName} dir={effectiveDir}>\n {content}\n </div>\n );\n}\n","/**\n * The typed side of the validation contract.\n *\n * The backend publishes a descriptor per submittable field alongside the\n * opaque key list (`meta.validationFeedback.validationFields`, and per-column\n * in `rowMutableTables[].columns`). They are derived from the pydantic models,\n * so they are the same source of truth the scorer uses — which is why the\n * client can validate against them and be sure the server will agree.\n *\n * The descriptor is declared STRUCTURALLY here rather than imported from\n * `@gemina/sdk`, so this module compiles against any SDK version. That is a\n * convenience for development only: it does NOT rescue the data. Elements\n * consumes the generated DTO, and a generated converter drops properties it\n * was not generated with, so a host on a pre-1.5.0 SDK receives `undefined`\n * here no matter what the server sent. Every consumer must therefore treat an\n * absent descriptor as \"render the plain text input we always rendered\".\n */\n\n/** The JSON types the generator emits (`schema_generator.JsonType`). */\nexport type FieldType = 'string' | 'number' | 'integer' | 'boolean' | 'date';\n\nexport interface ValidationFieldDescriptor {\n /** The opaque schema key this describes. The ONLY identity — labels repeat. */\n key?: string;\n label?: string;\n type?: FieldType;\n /**\n * A closed roster. Note the wire name: the generator renames the reserved\n * word, so the SDK property is `_enum`; callers normalise before handing a\n * descriptor here.\n */\n enum?: string[] | null;\n /** A closed external standard the annotation cannot express, e.g. `iso4217`. */\n format?: string | null;\n /** The model's own field description — shown to the reviewer verbatim. */\n description?: string | null;\n}\n\n/**\n * Active ISO 4217 codes, for the currency field's `<datalist>`.\n *\n * SUGGESTIONS ONLY — `validateInput` deliberately does not require membership.\n * A reviewer looking at a real invoice is the authority on what currency it is\n * in, and blocking submission because a legitimate code is missing from a list\n * baked into a client release is a worse failure than accepting an odd one.\n * The server does not check membership either; it compares values.\n */\nexport const ISO_4217_CODES: readonly string[] = [\n 'AED', 'ARS', 'AUD', 'BGN', 'BRL', 'CAD', 'CHF', 'CLP', 'CNY', 'COP', 'CZK',\n 'DKK', 'EGP', 'EUR', 'GBP', 'HKD', 'HRK', 'HUF', 'IDR', 'ILS', 'INR', 'ISK',\n 'JPY', 'KRW', 'MAD', 'MXN', 'MYR', 'NGN', 'NOK', 'NZD', 'PEN', 'PHP', 'PLN',\n 'RON', 'RSD', 'RUB', 'SAR', 'SEK', 'SGD', 'THB', 'TRY', 'TWD', 'UAH', 'USD',\n 'VND', 'ZAR',\n];\n\nconst ISO_4217_SHAPE = /^[A-Za-z]{3}$/;\nconst DATE_SHAPE = /^\\d{4}-\\d{2}-\\d{2}$/;\n/** Digits with optional sign/decimal, allowing the separators the server strips. */\nconst NUMERIC_SHAPE = /^[+-]?[\\d,_]*\\.?\\d+$/;\n\n/** The server's own leniency (`utils._strip_numeric`) — match it, don't exceed it. */\nfunction toNumber(value: string): number | null {\n if (!NUMERIC_SHAPE.test(value)) {\n return null;\n }\n const parsed = Number(value.replace(/[,_]/g, ''));\n return Number.isFinite(parsed) ? parsed : null;\n}\n\n/**\n * Why a value cannot be submitted, or `null` if it can.\n *\n * The message is the FIX, not the complaint: \"Enter a whole number\", not\n * \"Invalid integer\". A reviewer correcting an invoice should never have to\n * infer what the form wants from a restatement of what it rejected.\n *\n * Two rules are load-bearing rather than cosmetic:\n *\n * - An EMPTY value is always valid. `composeSubmission` reads a cleared input\n * as \"the user asserts this field is absent\", which is a legitimate and\n * common correction. Validating emptiness would make the field unclearable.\n * - NO DESCRIPTOR means valid. Untyped is not the same as invalid, and the\n * component must stay usable against a backend or an SDK that predates the\n * typed contract.\n */\nexport function validateInput(\n value: string,\n field: ValidationFieldDescriptor | undefined,\n): string | null {\n const trimmed = value.trim();\n if (trimmed === '' || !field) {\n return null;\n }\n\n // A published roster wins over the annotation's type: the server emits enum\n // and type together, and the roster is the narrower statement.\n if (field.enum && field.enum.length > 0) {\n return field.enum.includes(trimmed)\n ? null\n : `Choose one of: ${field.enum.join(', ')}`;\n }\n\n if (field.format === 'iso4217') {\n return ISO_4217_SHAPE.test(trimmed) ? null : 'Use a 3-letter ISO 4217 code, e.g. USD';\n }\n\n switch (field.type) {\n case 'number':\n return toNumber(trimmed) === null ? 'Enter a number' : null;\n case 'integer': {\n const parsed = toNumber(trimmed);\n if (parsed === null || !Number.isInteger(parsed)) {\n return 'Enter a whole number';\n }\n return null;\n }\n case 'date': {\n if (!DATE_SHAPE.test(trimmed)) {\n return 'Enter a date as YYYY-MM-DD';\n }\n // Shape alone accepts 2026-02-30. Round-trip through Date and require\n // the parts to survive, which rejects overflowed days and months.\n const [year, month, day] = trimmed.split('-').map(Number);\n const date = new Date(Date.UTC(year!, month! - 1, day!));\n const survives = date.getUTCFullYear() === year\n && date.getUTCMonth() === month! - 1\n && date.getUTCDate() === day;\n return survives ? null : 'Enter a date as YYYY-MM-DD';\n }\n default:\n return null;\n }\n}\n\n/**\n * A table the server declares row-mutable — the reviewer may add and delete\n * its rows, and the client may send a `rowSources` alignment for it.\n *\n * SERVER-DECLARED, never inferred. Any wide array of objects looks like a\n * table to the classifier — `custom_template`'s do — and offering row controls\n * on one the scorer cannot align would mis-score permanently, on a submission\n * that only happens once.\n */\nexport interface RowMutableTable {\n /** JSON pointer to the array, e.g. `/line_items`. */\n pointer: string;\n /** `label:line_{index}_{field}|ptr:/line_items/{index}/{field}`. */\n keyTemplate: string;\n /**\n * Every column of a row, derived by the backend from the MODEL rather than\n * from a sampled row — so they exist even when the extraction found nothing,\n * which is exactly when a reviewer most needs to type a line in.\n */\n columns: ValidationFieldDescriptor[];\n}\n\n/** Normalise the SDK's `rowMutableTables`, including each column's `_enum`. */\nexport function readRowMutableTables(raw: unknown): RowMutableTable[] {\n if (!Array.isArray(raw)) {\n return [];\n }\n const out: RowMutableTable[] = [];\n for (const item of raw) {\n if (item === null || typeof item !== 'object') {\n continue;\n }\n const source = item as Record<string, unknown>;\n if (typeof source.pointer !== 'string' || typeof source.keyTemplate !== 'string') {\n continue;\n }\n out.push({\n pointer: source.pointer,\n keyTemplate: source.keyTemplate,\n // Columns are descriptors keyed by `name` rather than `key`, so they get\n // the same treatment with the name standing in as the identity.\n columns: readDescriptors(\n (Array.isArray(source.columns) ? source.columns : []).map((column) => {\n const record = (column ?? {}) as Record<string, unknown>;\n return { ...record, key: record.name };\n }),\n ),\n });\n }\n return out;\n}\n\n/** The cell key a table's rows mint, with `{index}`/`{field}` filled in. */\nexport function cellSchemaKey(template: string, index: number, field: string): string {\n return template.replace(/\\{index\\}/g, String(index)).replace(/\\{field\\}/g, field);\n}\n\n/**\n * Turn a reviewer's typed string into the value that goes on the wire.\n *\n * Typed rendering without typed parsing leaves the approval payload as\n * unusable as it was before, for two independent reasons:\n *\n * - ON THE WIRE, the server's `coerce_like` adopts the EXTRACTED value's type\n * before comparing — but skips coercion entirely when the target resolves\n * NOT_FOUND, which is exactly the never-extracted and added-row cases. There\n * a string `\"12\"` is compared against a number and scores incorrect.\n * - IN `onComplete`, the host receives the client-side values, never the\n * backend-normalised ones. A host consuming approved data would get `\"12\"`\n * where it expects `12`.\n *\n * Anything that does not parse is returned UNCHANGED rather than as `NaN`.\n * Task 6.4's gate means an unparseable value cannot reach here, but `NaN`\n * would `JSON.stringify` to `null` and score as a deliberate assertion of\n * absence — the one wrong answer worse than the raw string.\n */\nexport function coerceInput(\n value: string,\n field: ValidationFieldDescriptor | undefined,\n): unknown {\n if (!field) {\n return value;\n }\n switch (field.type) {\n case 'number':\n case 'integer': {\n const parsed = toNumber(value);\n return parsed === null ? value : parsed;\n }\n case 'boolean': {\n const lowered = value.trim().toLowerCase();\n if (lowered === 'true') return true;\n if (lowered === 'false') return false;\n return value;\n }\n // `date` stays a string: the wire format IS the ISO string, and a Date\n // object would serialise with a time component the extraction never had.\n default:\n return value;\n }\n}\n\n/**\n * Normalise the SDK's descriptors into the shape the rest of this module uses.\n *\n * Exists for one word: `enum` is reserved, so the generator emits the property\n * as `_enum` in TypeScript (and would in a future regen too — it is the\n * generator's rule, not a one-off). Reading `field.enum` off a generated DTO\n * therefore yields `undefined` silently, and every enum would quietly render\n * as a free-text input. Accepting BOTH spellings also keeps the function\n * correct for a caller handing over raw JSON rather than a parsed DTO.\n *\n * Anything unusable — not an object, no string key — is dropped rather than\n * carried as a half-descriptor that later code has to re-check.\n */\nexport function readDescriptors(raw: unknown): ValidationFieldDescriptor[] {\n if (!Array.isArray(raw)) {\n return [];\n }\n const out: ValidationFieldDescriptor[] = [];\n for (const item of raw) {\n if (item === null || typeof item !== 'object') {\n continue;\n }\n const source = item as Record<string, unknown>;\n if (typeof source.key !== 'string') {\n continue;\n }\n const roster = source._enum ?? source.enum;\n out.push({\n key: source.key,\n label: typeof source.label === 'string' ? source.label : undefined,\n type: typeof source.type === 'string' ? (source.type as FieldType) : undefined,\n enum: Array.isArray(roster) ? roster.map(String) : null,\n format: typeof source.format === 'string' ? source.format : null,\n description: typeof source.description === 'string' ? source.description : null,\n });\n }\n return out;\n}\n","/**\n * Shape classifier for arbitrary extraction payloads.\n *\n * Near-verbatim port of the console's battle-tested classifier\n * (gemina-console `src/pages/extractions/components/FormView/utils.ts`).\n * It buckets a payload into headers / simpleLists / tables / entities /\n * fallback. The heuristics are intentionally unchanged — they are proven\n * against every extraction type.\n *\n * ONE structural addition over the console: every emitted leaf carries the\n * JSON pointer at which it lives in the ORIGINAL payload, so bindings can\n * match fields to server-generated schema keys. Pointers point at the\n * value-object WRAPPER (e.g. `/supplier_name`, not `/supplier_name/value`);\n * `/value` normalization happens at binding time. When the payload wraps its\n * fields in a root `{ data: ... }` object, inner pointers keep the `/data`\n * prefix because server pointers resolve against the payload root.\n *\n * Pointer segments are RFC-6901 escaped (`~` → `~0` first, then `/` → `~1`)\n * so emitted pointers round-trip through `resolvePointer`.\n *\n * Pure and dependency-free: no React, no DOM, no antd.\n */\n\n/**\n * Common acronyms that should stay uppercase\n */\nconst ACRONYMS = new Set(['ID', 'VAT', 'OCR', 'PDF', 'URL', 'API', 'HTML', 'CSS', 'JSON', 'XML', 'UUID']);\n\n/**\n * Convert camelCase or snake_case to Title Case with acronym handling\n * Examples:\n * supplierName -> \"Supplier Name\"\n * vat_amount -> \"VAT Amount\"\n * ocr_text -> \"OCR Text\"\n * businessNumber -> \"Business Number\"\n */\nexport function formatLabel(key: string): string {\n // First, split by underscores and camelCase\n const words = key\n // Insert space before uppercase letters (camelCase)\n .replace(/([a-z])([A-Z])/g, '$1 $2')\n // Replace underscores with spaces\n .replace(/_/g, ' ')\n // Split into words\n .split(' ')\n .filter(Boolean);\n\n return words\n .map((word) => {\n const upper = word.toUpperCase();\n if (ACRONYMS.has(upper)) {\n return upper;\n }\n return word.charAt(0).toUpperCase() + word.slice(1).toLowerCase();\n })\n .join(' ');\n}\n\n/**\n * Format a value for display based on its type.\n *\n * DISPLAY ONLY — never feed this into inputs or submissions; the raw\n * `value` on each classified leaf is the source of truth.\n */\nexport function formatValue(value: unknown, fieldName?: string): string {\n if (value === null || value === undefined) {\n return '-';\n }\n\n if (typeof value === 'boolean') {\n return value ? 'Yes' : 'No';\n }\n\n if (typeof value === 'number') {\n // Check if it looks like a percentage (field name contains rate/percent)\n if (fieldName && /rate|percent/i.test(fieldName)) {\n return `${value}%`;\n }\n // Don't format identifier fields with thousand separators\n if (fieldName && /number|num|id|code|phone|fax|postal|zip/i.test(fieldName)) {\n return String(value);\n }\n // Format numbers with thousand separators\n return value.toLocaleString();\n }\n\n if (typeof value === 'string') {\n // Try to detect and format ISO dates\n if (/^\\d{4}-\\d{2}-\\d{2}(T|$)/.test(value)) {\n try {\n const date = new Date(value);\n if (!isNaN(date.getTime())) {\n return date.toLocaleDateString();\n }\n } catch {\n // Fall through to return original\n }\n }\n return value;\n }\n\n return String(value);\n}\n\n/**\n * Check if a value is a \"value object\" with { value, coordinates?, confidence? }\n */\nexport function isValueObject(obj: unknown): obj is { value: unknown; coordinates?: unknown; confidence?: string; confidence_reasons?: string[] } {\n if (!obj || typeof obj !== 'object' || Array.isArray(obj)) {\n return false;\n }\n return 'value' in obj;\n}\n\n/**\n * Check if an array contains only primitives\n */\nexport function isPrimitiveArray(arr: unknown[]): boolean {\n if (arr.length === 0) return false;\n return arr.every((item) => item === null || typeof item !== 'object');\n}\n\n/**\n * Check if an array is a \"simple value array\" (Type C)\n * Array of { value, coordinates? } objects\n */\nexport function isSimpleValueArray(arr: unknown[]): boolean {\n if (arr.length === 0) return false;\n return arr.every((item) => isValueObject(item) && Object.keys(item as object).every(k => ['value', 'coordinates', 'confidence', 'confidence_reasons'].includes(k)));\n}\n\n/**\n * Check if an array is a \"table array\" (Type A)\n * Array of flat objects with many fields\n */\nexport function isTableArray(arr: unknown[]): boolean {\n if (arr.length === 0) return false;\n const first = arr[0];\n if (!first || typeof first !== 'object' || Array.isArray(first)) return false;\n\n // Count non-metadata fields\n const metaFields = new Set(['confidence', 'confidence_reasons', 'coordinates']);\n const keys = Object.keys(first as object).filter(k => !metaFields.has(k));\n\n // If objects have >3 non-meta fields and those values are primitives or value objects, it's a table\n if (keys.length > 3) {\n const firstObj = first as Record<string, unknown>;\n // Only check the non-metadata field values\n const nonMetaValues = keys.map(k => firstObj[k]);\n const allSimple = nonMetaValues.every(v =>\n v === null ||\n typeof v !== 'object' ||\n isValueObject(v)\n );\n return allSimple;\n }\n return false;\n}\n\n/**\n * Check if an array is an \"entity array\" (Type B)\n * Array of objects that aren't tables - includes both wrapped value objects\n * and plain object arrays with few fields\n */\nexport function isEntityArray(arr: unknown[]): boolean {\n if (arr.length === 0) return false;\n if (isPrimitiveArray(arr)) return false;\n if (isSimpleValueArray(arr)) return false;\n if (isTableArray(arr)) return false;\n\n const first = arr[0];\n if (!first || typeof first !== 'object' || Array.isArray(first)) return false;\n\n // Any array of objects that isn't a table or simple value array is an entity array\n // This includes objects with nested value wrappers OR plain objects with few fields\n return true;\n}\n\n/**\n * Extract the actual value from a field (handles value objects)\n */\nexport function extractValue(field: unknown): unknown {\n if (isValueObject(field)) {\n return field.value;\n }\n return field;\n}\n\n/**\n * Extract coordinates from a field if present\n */\nexport function extractCoordinates(field: unknown): { points: [number, number][] } | null {\n if (isValueObject(field) && field.coordinates) {\n const coords = field.coordinates as { relative?: [number, number][] };\n if (coords.relative) {\n return { points: coords.relative };\n }\n }\n return null;\n}\n\n/**\n * Extract confidence from a field if present\n */\nexport function extractConfidence(field: unknown): { level: string; reasons: string[] } | null {\n if (isValueObject(field) && field.confidence) {\n return {\n level: field.confidence,\n reasons: field.confidence_reasons || [],\n };\n }\n return null;\n}\n\n/**\n * Escape one JSON-pointer segment per RFC 6901 (`~` before `/`, mirroring the\n * resolver's unescape order of `~1` before `~0`).\n */\nfunction escapeSegment(segment: string): string {\n return segment.replace(/~/g, '~0').replace(/\\//g, '~1');\n}\n\n/**\n * One classified leaf field. `pointer` locates the field's value-object\n * wrapper (or raw value) in the ORIGINAL payload.\n */\nexport interface ClassifiedField {\n key: string; // display label source (formatLabel applied at render)\n pointer: string; // pointer to this field in the ORIGINAL payload\n value: unknown; // unwrapped raw value\n coordinates: { points: [number, number][] } | null;\n confidence: { level: string; reasons: string[] } | null;\n}\n\n/**\n * Key under which a table row's synthetic row-level confidence cell is\n * stored. Not a real payload field — it never binds to a server schema key.\n */\nexport const ROW_META_KEY = '_rowMeta';\n\n/** A cell inside a table row or entity card (no own display key). */\nexport interface ClassifiedCell {\n pointer: string;\n value: unknown;\n coordinates: { points: [number, number][] } | null;\n confidence: { level: string; reasons: string[] } | null;\n}\n\n/**\n * Classify all fields in a data object\n */\nexport interface ClassifiedData {\n overallConfidence: { level: string; reasons: string[] } | null;\n headers: ClassifiedField[];\n simpleLists: Array<{\n key: string;\n pointer: string;\n items: ClassifiedCell[];\n }>;\n entities: Array<{\n key: string;\n pointer: string;\n items: Array<Record<string, ClassifiedCell>>;\n }>;\n tables: Array<{\n key: string;\n pointer: string;\n columns: string[];\n rows: Array<Record<string, ClassifiedCell>>;\n overallConfidence: { level: string; reasons: string[] } | null;\n }>;\n fallback: Array<{\n key: string;\n data: unknown;\n }>;\n}\n\nexport function classifyData(data: unknown): ClassifiedData {\n const result: ClassifiedData = {\n overallConfidence: null,\n headers: [],\n simpleLists: [],\n entities: [],\n tables: [],\n fallback: [],\n };\n\n if (!data || typeof data !== 'object' || Array.isArray(data)) {\n return result;\n }\n\n // Handle wrapped data (some extractions wrap in { data: ... })\n let rootData = data as Record<string, unknown>;\n result.overallConfidence = readOverallConfidence(rootData);\n let basePointer = '';\n if ('data' in rootData && typeof rootData.data === 'object' && rootData.data !== null && !Array.isArray(rootData.data)) {\n // Process top-level non-data fields first (like total_lines, overall_confidence)\n for (const [key, value] of Object.entries(rootData)) {\n if (key === 'data') continue;\n processField(key, value, result, rootData, '');\n }\n rootData = rootData.data as Record<string, unknown>;\n result.overallConfidence ??= readOverallConfidence(rootData);\n // Inner fields live under the wrapper in the original payload — server\n // pointers resolve against the payload root, so keep the /data prefix.\n basePointer = '/data';\n }\n\n for (const [key, value] of Object.entries(rootData)) {\n processField(key, value, result, rootData, basePointer);\n }\n\n return result;\n}\n\nfunction readOverallConfidence(\n source: Record<string, unknown>,\n): { level: string; reasons: string[] } | null {\n const rawLevel = source.overall_confidence ?? source.overallConfidence;\n const value = extractValue(rawLevel);\n if (typeof value !== 'string' || value.length === 0) return null;\n\n const rawReasons = source.confidence_reasons ?? source.confidenceReasons;\n const reasons = Array.isArray(rawReasons)\n ? rawReasons.filter((reason): reason is string => typeof reason === 'string')\n : [];\n return { level: value, reasons };\n}\n\nfunction processField(\n key: string,\n value: unknown,\n result: ClassifiedData,\n parentObj: Record<string, unknown> | undefined,\n basePointer: string,\n): void {\n // Skip metadata fields at root level\n // Overall confidence has a dedicated summary above the form. Accept both\n // wire spellings because Pydantic aliases vary between processor payloads.\n if ([\n 'confidence', 'confidence_reasons', 'confidenceReasons', 'coordinates',\n 'overall_confidence', 'overallConfidence',\n ].includes(key)) {\n return;\n }\n\n const pointer = `${basePointer}/${escapeSegment(key)}`;\n\n // Primitive or null\n if (value === null || typeof value !== 'object') {\n result.headers.push({\n key,\n pointer,\n value,\n coordinates: null,\n confidence: null,\n });\n return;\n }\n\n // Value object (has 'value' property)\n if (isValueObject(value)) {\n result.headers.push({\n key,\n pointer,\n value: extractValue(value),\n coordinates: extractCoordinates(value),\n confidence: extractConfidence(value),\n });\n return;\n }\n\n // Array\n if (Array.isArray(value)) {\n if (value.length === 0) {\n result.headers.push({\n key,\n pointer,\n value: null,\n coordinates: null,\n confidence: null,\n });\n return;\n }\n\n // Array of primitives - display as simple list\n if (isPrimitiveArray(value)) {\n result.simpleLists.push({\n key,\n pointer,\n items: value.map((item, index) => ({\n pointer: `${pointer}/${index}`,\n value: item,\n coordinates: null,\n confidence: null,\n })),\n });\n return;\n }\n\n // Simple value array (Type C) - array of { value, coordinates? }\n if (isSimpleValueArray(value)) {\n result.simpleLists.push({\n key,\n pointer,\n items: value.map((item, index) => ({\n pointer: `${pointer}/${index}`,\n value: extractValue(item),\n coordinates: extractCoordinates(item),\n confidence: extractConfidence(item),\n })),\n });\n return;\n }\n\n // Table array (Type A) - array of flat objects with many fields\n if (isTableArray(value)) {\n const first = value[0] as Record<string, unknown>;\n const metaFields = new Set(['confidence', 'confidence_reasons', 'coordinates']);\n const columns = Object.keys(first).filter(k => !metaFields.has(k));\n\n // A table-specific confidence belongs in its section header. Global\n // overall confidence is intentionally not copied into every table.\n let overallConfidence: { level: string; reasons: string[] } | null = null;\n if (parentObj) {\n // First check for specific key pattern (e.g., line_items_confidence)\n const confidenceKey = `${key}_confidence`;\n const reasonsKey = `${key}_confidence_reasons`;\n if (parentObj[confidenceKey]) {\n overallConfidence = {\n level: parentObj[confidenceKey] as string,\n reasons: (parentObj[reasonsKey] as string[]) || [],\n };\n }\n }\n\n result.tables.push({\n key,\n pointer,\n columns,\n overallConfidence,\n rows: value.map((row, rowIndex) => {\n const rowPointer = `${pointer}/${rowIndex}`;\n const rowData: Record<string, ClassifiedCell> = {};\n // isTableArray samples only the first element; a null/non-object row\n // later in the array must not crash — its cells emit with undefined.\n const rowObj = (row ?? {}) as Record<string, unknown>;\n\n for (const col of columns) {\n const cell = rowObj[col];\n rowData[col] = {\n pointer: `${rowPointer}/${escapeSegment(col)}`,\n value: extractValue(cell),\n coordinates: extractCoordinates(cell),\n confidence: extractConfidence(cell),\n };\n }\n\n // Also extract row-level confidence if present\n if (rowObj.confidence || rowObj.confidence_reasons) {\n // _rowMeta is synthetic (no real field behind it); its pointer is\n // the ROW pointer, and it never binds to a server schema key.\n rowData[ROW_META_KEY] = {\n pointer: rowPointer,\n value: null,\n coordinates: null,\n confidence: {\n level: rowObj.confidence as string || '',\n reasons: (rowObj.confidence_reasons as string[]) || [],\n },\n };\n }\n\n return rowData;\n }),\n });\n return;\n }\n\n // Entity array (Type B) - array of objects (cards)\n if (isEntityArray(value)) {\n result.entities.push({\n key,\n pointer,\n items: value.map((item, index) => {\n const entity: Record<string, ClassifiedCell> = {};\n\n // isEntityArray samples only the first element; a null/non-object\n // item later in the array emits an empty entity so indices (and\n // therefore sibling pointers) stay aligned with the payload.\n if (item === null || typeof item !== 'object' || Array.isArray(item)) {\n return entity;\n }\n\n for (const [fieldKey, fieldValue] of Object.entries(item as Record<string, unknown>)) {\n // Skip metadata fields\n if (['confidence', 'confidence_reasons', 'coordinates'].includes(fieldKey)) {\n continue;\n }\n entity[fieldKey] = {\n pointer: `${pointer}/${index}/${escapeSegment(fieldKey)}`,\n value: extractValue(fieldValue),\n coordinates: extractCoordinates(fieldValue),\n confidence: extractConfidence(fieldValue),\n };\n }\n\n return entity;\n }),\n });\n return;\n }\n\n // Fallback for unrecognized arrays\n result.fallback.push({ key, data: value });\n return;\n }\n\n // Nested object without 'value' property - try to recurse into it\n const nestedObj = value as Record<string, unknown>;\n const nestedKeys = Object.keys(nestedObj).filter(k => !['confidence', 'confidence_reasons', 'coordinates'].includes(k));\n\n // If the nested object has fields, process them recursively with prefixed keys\n if (nestedKeys.length > 0 && nestedKeys.length <= 10) {\n // Small nested objects get flattened into headers with grouped key names\n for (const nestedKey of nestedKeys) {\n const nestedValue = nestedObj[nestedKey];\n const combinedKey = `${key}.${nestedKey}`;\n const nestedPointer = `${pointer}/${escapeSegment(nestedKey)}`;\n\n // Process primitives and value objects as headers\n if (nestedValue === null || typeof nestedValue !== 'object') {\n result.headers.push({\n key: combinedKey,\n pointer: nestedPointer,\n value: nestedValue,\n coordinates: null,\n confidence: null,\n });\n } else if (isValueObject(nestedValue)) {\n result.headers.push({\n key: combinedKey,\n pointer: nestedPointer,\n value: extractValue(nestedValue),\n coordinates: extractCoordinates(nestedValue),\n confidence: extractConfidence(nestedValue),\n });\n } else {\n // Complex nested values go to fallback\n result.fallback.push({ key: combinedKey, data: nestedValue });\n }\n }\n return;\n }\n\n // Large or empty nested objects go to fallback\n result.fallback.push({ key, data: value });\n}\n","/**\n * Server-generated submission keys and JSON-pointer resolution.\n *\n * Mirrors the backend exactly (gemina-api-v2 `data_validator.py` /\n * `validator/utils.py`) so that what the component resolves client-side is\n * what the server will resolve when it scores the submission:\n * - key regex `^label:([^|]+)\\|ptr:(/.*)$`\n * - `~1` unescaped before `~0`\n * - list segments must be all digits\n * - unresolvable paths are a sentinel, distinct from a stored `null`.\n *\n * Known divergences from the backend (all client-stricter; unreachable via\n * server-generated keys):\n * - Python's `$` in the key regex also matches before a trailing newline;\n * JS `$` (no `m` flag) matches only at end-of-string.\n * - The backend's `pointer.lstrip(\"/\")` collapses multiple leading slashes\n * (`//a` resolves `doc[\"a\"]`); here that is NOT_FOUND (RFC-6901-correct).\n * - Python's `isdigit()` accepts non-ASCII unicode digits as list indices;\n * `/^\\d+$/` here is ASCII-only.\n */\n\nexport interface SchemaKey {\n /** The raw key — submitted verbatim as a property name in the feedback body. */\n raw: string;\n /** Human-meaningful label; the only key format the host app ever sees. */\n label: string;\n /** JSON pointer into the extraction values payload. */\n pointer: string;\n}\n\nconst KEY_RE = /^label:([^|]+)\\|ptr:(\\/.*)$/;\n\n/** Parse one schema key, or null for a malformed entry (the backend skips those quietly too). */\nexport function parseSchemaKey(raw: string): SchemaKey | null {\n const match = KEY_RE.exec(raw);\n if (match === null) {\n return null;\n }\n return { raw, label: match[1] as string, pointer: match[2] as string };\n}\n\n/** \"Path did not resolve\" — deliberately distinct from a stored null value. */\nexport const NOT_FOUND: unique symbol = Symbol('gemina-verification-not-found');\nexport type NotFound = typeof NOT_FOUND;\n\n/** Resolve a JSON pointer against a document, backend-compatible (see module docs). */\nexport function resolvePointer(doc: unknown, pointer: string): unknown | NotFound {\n if (pointer === '') {\n return doc;\n }\n if (!pointer.startsWith('/')) {\n return NOT_FOUND;\n }\n let current: unknown = doc;\n for (const rawSegment of pointer.slice(1).split('/')) {\n const segment = rawSegment.replace(/~1/g, '/').replace(/~0/g, '~');\n if (Array.isArray(current)) {\n if (!/^\\d+$/.test(segment)) {\n return NOT_FOUND;\n }\n const index = Number(segment);\n if (index >= current.length) {\n return NOT_FOUND;\n }\n current = current[index];\n } else if (current !== null && typeof current === 'object') {\n if (!Object.prototype.hasOwnProperty.call(current, segment)) {\n return NOT_FOUND;\n }\n current = (current as Record<string, unknown>)[segment];\n } else {\n return NOT_FOUND;\n }\n }\n return current;\n}\n\n/**\n * `vendor_name` -> `vendorName`. The client's ONLY casing rule.\n *\n * Lives here, alone, on purpose. Schema pointers are snake_case while the\n * payload is camelCase, so this rule decides whether a pointer resolves at\n * all — and a second copy that drifts from it is exactly how a field silently\n * stops resolving (see the grossLinePrice alias bug: a wire name this rule\n * could not reproduce made an extracted value render as \"Not detected\" and\n * score a false `extra` on every row).\n */\nexport function snakeToCamel(segment: string): string {\n return segment.replace(/_([a-zA-Z0-9])/g, (_unused, ch: string) => ch.toUpperCase());\n}\n","import { isValueObject } from './classify';\nimport { coerceInput } from './field-types';\nimport type { CellView } from './row-cells';\nimport type { ValidationFieldDescriptor } from './field-types';\nimport { NOT_FOUND, parseSchemaKey, snakeToCamel } from './pointer';\nimport type { NotFound, SchemaKey } from './pointer';\n\n/** One server-mandated submission slot, bound to whatever was extracted there. */\nexport interface FieldBinding {\n key: SchemaKey;\n /**\n * The RAW resolved node — never unwrapped — or NOT_FOUND. This is what an\n * untouched binding submits verbatim: the server resolves the same pointer\n * against the same model tree (casing aside), so wrapper objects compare\n * dict-vs-dict and score correct. Note: dict-valued submissions additionally\n * require INNER-key casing identity with the server's scoring dict — which\n * holds for custom_template's uncamelized dicts, the only reachable case.\n */\n serverValue: unknown | NotFound;\n /** DISPLAY value: serverValue unwrapped via isValueObject, else serverValue. */\n extracted: unknown | NotFound;\n /**\n * The actually-RESOLVED pointer (payload casing — camel in prod) minus a\n * trailing `/value` segment; the pointer the classifier reports for this\n * field. For NOT_FOUND bindings: best-effort camelized schema pointer.\n */\n fieldPointer: string;\n /**\n * False when serverValue is a container (object/array, including value-object\n * wrappers): the server's `coerce_like` does nothing for containers, so a\n * string edit could never score correct. True for NOT_FOUND (fill-in), null,\n * and primitives.\n */\n editable: boolean;\n /**\n * The server's type metadata for this field, matched by exact key.\n *\n * `undefined` whenever the backend predates the typed contract OR the host\n * is on an SDK generated before it — the converter drops what it does not\n * know. Every consumer treats that as \"the plain text input we always had\",\n * which is why nothing here is required.\n */\n field?: ValidationFieldDescriptor;\n}\n\nfunction unescapeSegment(raw: string): string {\n return raw.replace(/~1/g, '/').replace(/~0/g, '~');\n}\n\nfunction escapeSegment(segment: string): string {\n return segment.replace(/~/g, '~0').replace(/\\//g, '~1');\n}\n\n/** Best-effort camelization of a whole pointer (used when resolution fails). */\nfunction camelizePointer(pointer: string): string {\n if (!pointer.startsWith('/')) {\n return pointer;\n }\n return '/' + pointer\n .slice(1)\n .split('/')\n .map((raw) => escapeSegment(snakeToCamel(unescapeSegment(raw))))\n .join('/');\n}\n\ninterface Resolution {\n node: unknown | NotFound;\n /** The pointer as actually matched in the payload (camel in prod). */\n resolvedPointer: string;\n}\n\n/**\n * Resolve a schema pointer against the view payload, casing-aware (review C1):\n * schema pointers are snake_case while the prod payload is camelCase, so each\n * object-key segment tries exact first, then snake→camel. The server scores\n * against its own snake dict, so the mismatch is client-only; structurally the\n * walk mirrors `resolvePointer` (backend parity — no fallbacks, no unwrapping).\n */\nfunction resolveCasingAware(doc: unknown, pointer: string): Resolution {\n const missing: Resolution = { node: NOT_FOUND, resolvedPointer: camelizePointer(pointer) };\n if (pointer === '') {\n return { node: doc, resolvedPointer: '' };\n }\n if (!pointer.startsWith('/')) {\n return missing;\n }\n let current: unknown = doc;\n const matched: string[] = [];\n for (const rawSegment of pointer.slice(1).split('/')) {\n const segment = unescapeSegment(rawSegment);\n if (Array.isArray(current)) {\n if (!/^\\d+$/.test(segment)) {\n return missing;\n }\n const index = Number(segment);\n if (index >= current.length) {\n return missing;\n }\n current = current[index];\n matched.push(rawSegment);\n } else if (current !== null && typeof current === 'object') {\n let key: string;\n if (Object.prototype.hasOwnProperty.call(current, segment)) {\n key = segment;\n } else {\n const camel = snakeToCamel(segment);\n if (camel === segment || !Object.prototype.hasOwnProperty.call(current, camel)) {\n return missing;\n }\n key = camel;\n }\n current = (current as Record<string, unknown>)[key];\n matched.push(escapeSegment(key));\n } else {\n return missing;\n }\n }\n return { node: current, resolvedPointer: '/' + matched.join('/') };\n}\n\n/** A schema pointer `P/value` and a classifier pointer `P` are the same field. */\nfunction stripValueSuffix(pointer: string): string {\n return pointer.endsWith('/value') ? pointer.slice(0, -'/value'.length) : pointer;\n}\n\n/**\n * Parse + resolve every schema key. Malformed entries are skipped (backend\n * parity).\n *\n * `fields` is the server's typed descriptors, indexed here by their opaque\n * key. Matching is by key and ONLY by key: labels repeat across rows of a\n * table (`total` appears once per line item), so a label match would type one\n * row's cell from another row's descriptor.\n */\nexport function buildBindings(\n validationSchema: string[],\n values: unknown,\n fields?: ValidationFieldDescriptor[],\n): FieldBinding[] {\n const descriptors = new Map<string, ValidationFieldDescriptor>();\n for (const descriptor of fields ?? []) {\n if (typeof descriptor?.key === 'string') {\n descriptors.set(descriptor.key, descriptor);\n }\n }\n const bindings: FieldBinding[] = [];\n for (const raw of validationSchema) {\n const key = parseSchemaKey(raw);\n if (key === null) {\n continue;\n }\n const { node: serverValue, resolvedPointer } = resolveCasingAware(values, key.pointer);\n const extracted = serverValue !== NOT_FOUND && isValueObject(serverValue)\n ? serverValue.value\n : serverValue;\n const editable = serverValue === NOT_FOUND\n || serverValue === null\n || typeof serverValue !== 'object';\n bindings.push({\n key,\n serverValue,\n extracted,\n fieldPointer: stripValueSuffix(resolvedPointer),\n editable,\n field: descriptors.get(key.raw),\n });\n }\n return bindings;\n}\n\n/**\n * Index bindings by the pointer the CLASSIFIER reports for a field. The\n * classifier walks the same payload the bindings resolved against, so its\n * pointers carry the payload's casing — which is exactly what `fieldPointer`\n * recorded during resolution.\n */\nexport function indexBindingsByFieldPointer(bindings: FieldBinding[]): Map<string, FieldBinding> {\n const map = new Map<string, FieldBinding>();\n for (const binding of bindings) {\n map.set(binding.fieldPointer, binding);\n }\n return map;\n}\n\n/**\n * What an editable input is prefilled with. RAW value stringification only —\n * display formatting (`formatValue`) must never round-trip into a submission\n * (a locale-formatted \"1,500\" or date would score as a correction).\n */\nexport function toInputString(extracted: unknown | NotFound): string {\n if (extracted === NOT_FOUND || extracted === null || extracted === undefined) {\n return '';\n }\n if (typeof extracted === 'object') {\n return JSON.stringify(extracted);\n }\n return String(extracted);\n}\n\n/** One table's alignment, exactly as `ExtractionValidationInDTO.rowSources`. */\nexport interface RowSourcesEntry {\n table: string;\n sources: Array<number | null>;\n}\n\nexport interface SubmissionResult {\n /** Body for `ExtractionValidationInDTO.data` — raw schema keys, ALL asserted fields. */\n data: Record<string, unknown>;\n /** The same entries keyed by human label — handed to `onComplete`. */\n byLabel: Record<string, unknown>;\n confirmed: number;\n corrected: number;\n /**\n * How the submitted tables align to the extracted ones. EMPTY when no row\n * was added or removed, so an untouched submission's wire payload stays\n * byte-identical to what it was before row editing existed.\n */\n rowSources: RowSourcesEntry[];\n}\n\n/**\n * Compose the one-shot feedback body.\n *\n * `edits` holds ONLY dirty keys (raw schema key → current input string; the\n * UI removes an entry when the input returns to its initial string). The\n * counts trust that contract: a caller that fails to delete-on-revert\n * relabels a confirmation as a correction in `confirmed`/`corrected`; the\n * server-side scoring itself survives, since the unchanged string coerces\n * back to a value equal to the extracted one.\n *\n * Rules (verified against the backend DataValidator):\n * - untouched + resolved (even resolved-null): submit `serverValue` verbatim\n * — the raw node, wrappers included — the server resolves the same node\n * and compares equal → scored a confirmation;\n * - untouched + never extracted: OMIT — the user asserted nothing, and\n * submitting null would force a false \"missing\";\n * - dirty, non-empty: submit the trimmed string (only scalar-valued bindings\n * are editable, and for scalar targets the server's `coerce_like` adopts\n * the extracted value's type before comparing; containers are never\n * editable — see `FieldBinding.editable`);\n * - dirty, cleared: the user asserts the field is absent/wrong → null;\n * unless nothing was extracted either, in which case there is nothing\n * to assert → OMIT.\n */\nexport function composeSubmission(\n bindings: FieldBinding[],\n edits: ReadonlyMap<string, string>,\n options: {\n /**\n * The resolved cells, when the caller has them. Supplying these is what\n * makes row editing work: they carry the SUBMITTED key for each cell and\n * mark the ones belonging to rows the reviewer added. Omitted, every\n * binding is submitted under its own raw key — exactly today's behaviour.\n */\n cells?: readonly CellView[];\n rowSources?: RowSourcesEntry[];\n } = {},\n): SubmissionResult {\n const cells: readonly CellView[] = options.cells ?? bindings.map((binding) => ({\n editKey: binding.key.raw,\n submitKey: binding.key.raw,\n column: binding.key.label,\n rowKey: binding.key.raw,\n binding,\n added: false,\n }));\n const data: Record<string, unknown> = {};\n const byLabel: Record<string, unknown> = {};\n let confirmed = 0;\n let corrected = 0;\n\n for (const cell of cells) {\n const { binding } = cell;\n // The label follows the SUBMITTED key, not the source binding. After a\n // deletion, source row 1 is submitted as row 0 — handing the host\n // `line_1_description` for what the wire calls row 0 would have\n // `onComplete` disagree with the payload it describes.\n const label = parseSchemaKey(cell.submitKey)?.label ?? binding.key.label;\n const edit = edits.get(cell.editKey);\n if (edit !== undefined) {\n const trimmed = edit.trim();\n // Nothing extracted and nothing typed: there is no assertion to make.\n // For an ADDED row this is also what keeps an empty cell out of the\n // payload — its aligned counterpart does not exist, so an omission\n // cannot become an `extra`.\n if (trimmed === '' && binding.serverValue === NOT_FOUND) {\n continue;\n }\n // Typed by the field's own descriptor, so a number reaches the server as\n // a number. A cleared input stays null — it asserts absence and must\n // never become 0 or an empty string.\n const value = trimmed === '' ? null : coerceInput(trimmed, binding.field);\n data[cell.submitKey] = value;\n byLabel[label] = value;\n corrected += 1;\n } else {\n if (binding.serverValue === NOT_FOUND) {\n continue;\n }\n // Untouched cells of a row that still maps to a source submit that\n // source's extracted value — under its SUBMITTED key, so the payload\n // mirrors the approved table rather than the extracted one.\n data[cell.submitKey] = binding.serverValue;\n byLabel[label] = binding.serverValue;\n confirmed += 1;\n }\n }\n return { data, byLabel, confirmed, corrected, rowSources: options.rowSources ?? [] };\n}\n\n/**\n * How many rows the extraction actually found at a table pointer.\n *\n * Reuses the SAME casing-aware walk the bindings use, because the server's\n * pointers are snake_case while the payload is camelCase — counting with a\n * naive lookup would report 0 for every table in production and quietly\n * disable every row control.\n *\n * 0 for a pointer that resolves to anything but an array, which covers both\n * \"no such table\" and the zero-row case identically — and both want the same\n * empty plan.\n */\nexport function countRowsAt(values: unknown, pointer: string): number {\n const { node } = resolveCasingAware(values, pointer);\n return Array.isArray(node) ? node.length : 0;\n}\n","/**\n * The row plan — which submitted row came from which extracted row.\n *\n * Pure, no React. This is the client half of the backend's `rowSources`\n * contract: the server aligns the submitted table to the extracted one using\n * it, which is what lets an inserted row score `missing` and a deleted one\n * score `extra` WITHOUT cascading a correction onto every row below.\n *\n * Encoding the same information as insert/delete OPS was rejected: two inserts\n * before the same index produce two identical ops whose reconstruction depends\n * on unstated ordering rules. The plan is unambiguous by construction — it IS\n * the alignment, not a recipe for reproducing one.\n *\n * Row IDENTITY is the other half of the job. Edits are keyed by row id rather\n * than by position, so a correction typed into the third row stays with that\n * row after the first is deleted. Keying by position would silently move a\n * reviewer's correction onto a different line item: wrong data, no symptom.\n */\n\nexport interface RowPlanEntry {\n /** Stable for the lifetime of the plan. Edits are keyed by this. */\n id: string;\n /** Index in the EXTRACTED table, or null for a row the reviewer added. */\n source: number | null;\n}\n\n/**\n * Ids for added rows. A counter rather than a random id so a render is\n * reproducible and a test can reason about it; uniqueness is all that is\n * required of it, and it never leaves the client.\n */\nlet addedRowCounter = 0;\n\n/**\n * The identity mapping: every extracted row, in order, unmoved.\n *\n * `scope` is the table's pointer, and it is NOT decoration. Edit keys are\n * derived from row ids and every table shares one edits map, so unscoped ids\n * would give two row-mutable tables the same `row-0` — and typing into one\n * table's first row would silently rewrite the other's. `rowMutableTables` is\n * a list, so nothing but this prevents that.\n */\nexport function initialRowPlan(extractedCount: number, scope = ''): RowPlanEntry[] {\n return Array.from({ length: Math.max(0, extractedCount) }, (_unused, index) => ({\n // Derived from the source index, so it is stable across re-renders without\n // any state to carry — an extracted row's identity never changes.\n id: `${scope}#row-${index}`,\n source: index,\n }));\n}\n\n/**\n * Mint an id for a row about to be added.\n *\n * Called OUTSIDE the state updater on purpose: an updater must be pure, and\n * React invokes it twice under Strict Mode, so incrementing a counter inside\n * one makes ids depend on how many times React chose to call it.\n */\nexport function nextAddedRowId(scope = ''): string {\n addedRowCounter += 1;\n return `${scope}#added-${addedRowCounter}`;\n}\n\n/** Drop the row at `position`. Out-of-range is a no-op, not a throw. */\nexport function removeRow(plan: RowPlanEntry[], position: number): RowPlanEntry[] {\n if (position < 0 || position >= plan.length) {\n return plan;\n }\n return plan.filter((_entry, index) => index !== position);\n}\n\n/**\n * Insert a blank user-added row after `position`.\n *\n * `-1` prepends, which is also how the zero-row table gets its first line.\n */\nexport function insertRowAfter(plan: RowPlanEntry[], position: number, id?: string): RowPlanEntry[] {\n const added: RowPlanEntry = { id: id ?? nextAddedRowId(), source: null };\n const at = Math.min(Math.max(position + 1, 0), plan.length);\n return [...plan.slice(0, at), added, ...plan.slice(at)];\n}\n\n/**\n * The edit-map key for one table cell.\n *\n * Table cells and header fields share ONE edits map, so this namespace must\n * not collide with a raw schema key — hence the prefix, and hence the test\n * asserting it never looks like `label:…`.\n */\nexport function cellEditKey(rowId: string, column: string): string {\n return `cell:${rowId}|col:${column}`;\n}\n\n/** The `sources` array for the wire, in submitted order. */\nexport function rowSourcesOf(plan: RowPlanEntry[]): Array<number | null> {\n return plan.map((entry) => entry.source);\n}\n\n/**\n * True when the reviewer has neither added nor removed a row.\n *\n * The wire payload for an untouched row set must be byte-identical to what it\n * was before this feature existed, so `composeSubmission` omits the table's\n * `rowSources` entry entirely in that case. Comparing against\n * `extractedCount` is what catches rows removed from the END, whose remaining\n * sources still read 0..n-1.\n */\nexport function isIdentityPlan(plan: RowPlanEntry[], extractedCount: number): boolean {\n return plan.length === extractedCount\n && plan.every((entry, index) => entry.source === index);\n}\n","/**\n * The one model of \"what cells does this table currently have\".\n *\n * Four consumers need it — the form's rendering, the unit-size pair rule,\n * Phase 6's submit gate, and `composeSubmission` — and deriving it four times\n * would let them disagree about which row a cell belongs to. Under row editing\n * that disagreement is not cosmetic: it silently attributes a reviewer's\n * correction to the wrong line item.\n *\n * Every cell carries THREE identities, because they genuinely differ:\n *\n * - `editKey` follows the ROW (`cellEditKey(rowId, column)`), so an edit stays\n * with its row when rows above it are deleted.\n * - `submitKey` follows the SUBMITTED POSITION, because the payload must mirror\n * the approved table — row 3 of what the reviewer sees is `/line_items/2/…`\n * on the wire regardless of where it was extracted from.\n * - `binding.key` follows the EXTRACTED position, because that is where the\n * value and its coordinates actually live.\n *\n * For an untouched table all three agree, which is why this never mattered\n * before.\n */\n\nimport { toInputString } from './bindings';\nimport type { FieldBinding } from './bindings';\nimport { cellSchemaKey } from './field-types';\nimport type { RowMutableTable, ValidationFieldDescriptor } from './field-types';\nimport { NOT_FOUND, parseSchemaKey, snakeToCamel } from './pointer';\nimport { cellEditKey } from './row-plan';\nimport type { RowPlanEntry } from './row-plan';\n\nexport interface PlannedCell {\n column: string;\n /** Where this cell's edit is stored. Stable across row moves. */\n editKey: string;\n /** The raw schema key this cell is submitted under. Follows position. */\n submitKey: string;\n /** Real for an extracted row; synthesized for one the reviewer added. */\n binding: FieldBinding;\n /** True when there is no extracted value behind this cell. */\n added: boolean;\n}\n\nexport interface PlannedRow {\n entry: RowPlanEntry;\n cells: PlannedCell[];\n}\n\n/**\n * A binding for a cell of a row that was never extracted.\n *\n * Deliberately the SAME shape the \"Not detected\" fill-in path already renders:\n * `NOT_FOUND` with `editable: true`. That is not a convenience — it is what\n * makes an added row's cells behave identically to a field the model missed,\n * which is exactly what they are.\n */\nfunction syntheticBinding(\n submitKey: string,\n descriptor: ValidationFieldDescriptor | undefined,\n): FieldBinding | null {\n const key = parseSchemaKey(submitKey);\n if (key === null) {\n return null;\n }\n return {\n key,\n serverValue: NOT_FOUND,\n extracted: NOT_FOUND,\n // No extracted node, so nothing to point at on the document.\n fieldPointer: key.pointer,\n editable: true,\n field: descriptor,\n };\n}\n\n/**\n * Resolve every cell of a row-mutable table under its current plan.\n *\n * `columns` is the display order — the classifier's for a table with rows, the\n * server's declared column list for one with none.\n */\nexport function planTableCells(\n table: RowMutableTable,\n plan: readonly RowPlanEntry[],\n columns: readonly string[],\n bindingsByRawKey: ReadonlyMap<string, FieldBinding>,\n): PlannedRow[] {\n const descriptors = new Map<string, ValidationFieldDescriptor>();\n for (const column of table.columns) {\n if (typeof column.key === 'string') {\n descriptors.set(column.key, column);\n }\n }\n\n return plan.map((entry, submittedIndex) => {\n const cells: PlannedCell[] = [];\n for (const column of columns) {\n const submitKey = cellSchemaKey(table.keyTemplate, submittedIndex, column);\n const editKey = cellEditKey(entry.id, column);\n const extractedKey = entry.source === null\n ? null\n : cellSchemaKey(table.keyTemplate, entry.source, column);\n const existing = extractedKey === null ? undefined : bindingsByRawKey.get(extractedKey);\n const binding = existing ?? syntheticBinding(submitKey, descriptors.get(column));\n if (binding === null) {\n continue;\n }\n cells.push({ column, editKey, submitKey, binding, added: existing === undefined });\n }\n return { entry, cells };\n });\n}\n\n/**\n * The display columns for a table: the server's declaration, plus anything the\n * classifier saw that the server did not declare.\n *\n * The SERVER's list is canonical because it is derived from the model, so it is\n * complete and present even for a zero-row table — the case a reviewer most\n * needs, since the model found nothing at all.\n *\n * The classifier's list cannot be trusted alone: it samples column names from\n * ROW 0 ONLY (`Object.keys(first)`), so a field absent from the first row but\n * present in a later one would not appear here — and because a planned table\n * suppresses every binding under its pointer, that value would be dropped from\n * the submission entirely, silently, even with no row edits. Merging is what\n * makes the suppression safe.\n */\nexport function displayColumns(\n table: RowMutableTable,\n classifiedColumns: readonly string[],\n): string[] {\n const declared = table.columns\n .map((column) => column.key)\n .filter((name): name is string => typeof name === 'string');\n // The schema uses model field names (snake_case), while the response DTO\n // serializes those same fields as camelCase. Exact comparison rendered the\n // entire table twice: every declared column followed by its classified\n // alias. Keep the server spelling as the canonical display/submission name,\n // and use the client's one shared casing rule only for de-duplication.\n // Declared names themselves are never collapsed, so a dynamic template that\n // genuinely declares both spellings still keeps both columns.\n const declaredAliases = new Set(declared.map(snakeToCamel));\n return [\n ...declared,\n ...classifiedColumns.filter((name) => !declaredAliases.has(snakeToCamel(name))),\n ];\n}\n\n/**\n * `/line_items` and the payload's `/lineItems` are the same table.\n *\n * Uses the SHARED casing rule rather than a local copy: two copies that drift\n * is precisely how a pointer silently stops resolving.\n */\nexport function matchesTablePointer(serverPointer: string, classifiedPointer: string): boolean {\n return serverPointer === classifiedPointer || snakeToCamel(serverPointer) === classifiedPointer;\n}\n\n/**\n * Every editable cell in the form, as one flat list.\n *\n * The pair rule and the submit gate both need \"what can be edited, and under\n * which key\" — and BOTH were previously derived from raw schema keys, which a\n * planned table cell no longer uses. Deriving them separately is how they\n * would drift apart; this is the single source they now share.\n *\n * `rowKey` groups cells that belong to the same row. For a planned table that\n * is the row's stable id; elsewhere it is the pointer prefix, which is what\n * the pre-row-editing code effectively used.\n */\nexport interface CellView {\n editKey: string;\n /** The raw schema key this cell goes on the wire under. */\n submitKey: string;\n column: string;\n rowKey: string;\n binding: FieldBinding;\n /** True when nothing was extracted here — a row the reviewer added. */\n added: boolean;\n}\n\n/** `/line_items/3/unit_size` -> `{ row: '/line_items/3', field: 'unit_size' }`. */\nfunction splitPointer(pointer: string): { row: string; field: string } | null {\n const cut = pointer.lastIndexOf('/');\n return cut <= 0 ? null : { row: pointer.slice(0, cut), field: pointer.slice(cut + 1) };\n}\n\n/**\n * Flatten bindings and planned tables into one list of cell views.\n *\n * A planned table OWNS every binding under its pointer — not merely the ones\n * its surviving rows still reference. Skipping only the referenced ones leaves\n * a DELETED row's bindings in the list, and since they carry their original\n * raw key as their submit key they overwrite whichever row moved up into that\n * position: the deletion silently does nothing, and the payload claims a row\n * the reviewer removed. Ownership is by pointer prefix, so the whole table\n * comes from the plan or none of it does.\n */\nexport function collectCellViews(\n bindings: readonly FieldBinding[],\n plannedTables: ReadonlyMap<string, PlannedRow[]>,\n): CellView[] {\n const views: CellView[] = [];\n const ownedPrefixes = [...plannedTables.keys()].map((pointer) => `${pointer}/`);\n\n for (const rows of plannedTables.values()) {\n for (const row of rows) {\n for (const cell of row.cells) {\n views.push({\n editKey: cell.editKey,\n submitKey: cell.submitKey,\n column: cell.column,\n rowKey: row.entry.id,\n binding: cell.binding,\n added: cell.added,\n });\n }\n }\n }\n\n for (const binding of bindings) {\n if (ownedPrefixes.some((prefix) => binding.key.pointer.startsWith(prefix))) {\n continue;\n }\n const split = splitPointer(binding.key.pointer);\n views.push({\n // Outside a plan all three identities coincide, which is why none of\n // this was needed before row editing.\n editKey: binding.key.raw,\n submitKey: binding.key.raw,\n column: split?.field ?? binding.key.label,\n rowKey: split?.row ?? binding.key.raw,\n binding,\n added: false,\n });\n }\n return views;\n}\n\n/** The one cross-field rule the server enforces. Deliberately not a rules engine. */\nconst UNIT_SIZE = 'unit_size';\nconst UNIT_SIZE_UOM = 'unit_size_uom';\nexport const UNIT_PAIR_MESSAGE = 'Enter both value and unit';\n\n/**\n * Rows where exactly one half of the unit-size pair is filled in.\n *\n * The server treats `unit_size` and `unit_size_uom` as both-or-nothing:\n * `_unit_size_pair_rule` (invoice_line_item.py:50-56) nulls BOTH whenever\n * either is missing, on every parse INCLUDING the scorer's. So a reviewer who\n * fills one and not the other has both silently zeroed before scoring, and\n * `onComplete` would hand the host a value the backend had already discarded.\n * Flagging it is the only way the reviewer ever learns.\n *\n * Keyed by EDIT key, and grouped by `rowKey`, so it works identically for an\n * extracted row and one the reviewer added — an added row is exactly where a\n * half-filled pair is most likely.\n *\n * Deliberately hard-coded to this pair rather than generalised. Exactly one\n * such rule exists in the models; a cross-field rules DSL would be speculative\n * flexibility with no second caller.\n */\nexport function unitSizePairErrors(\n cells: readonly CellView[],\n edits: ReadonlyMap<string, string>,\n): Map<string, string> {\n const rows = new Map<string, { size?: CellView; uom?: CellView }>();\n for (const cell of cells) {\n if (cell.column !== UNIT_SIZE && cell.column !== UNIT_SIZE_UOM) {\n continue;\n }\n const row = rows.get(cell.rowKey) ?? {};\n if (cell.column === UNIT_SIZE) {\n row.size = cell;\n } else {\n row.uom = cell;\n }\n rows.set(cell.rowKey, row);\n }\n\n const errors = new Map<string, string>();\n for (const { size, uom } of rows.values()) {\n // A row missing one half of the pair from its schema entirely cannot be\n // half-filled, so there is nothing to enforce.\n if (!size || !uom) {\n continue;\n }\n const filled = (cell: CellView) =>\n (edits.get(cell.editKey) ?? toInputString(cell.binding.extracted)).trim() !== '';\n if (filled(size) !== filled(uom)) {\n errors.set(size.editKey, UNIT_PAIR_MESSAGE);\n errors.set(uom.editKey, UNIT_PAIR_MESSAGE);\n }\n }\n return errors;\n}\n\n/**\n * Drop added rows the reviewer never typed into.\n *\n * Clicking \"Add line\" and then changing your mind is ordinary. Every cell of\n * such a row is already omitted from `data` — but its `null` source would\n * remain in the alignment, asserting to the scorer that a row exists there.\n * On a submission that happens exactly once, that is a phantom line item on\n * the record with nothing in it.\n *\n * Only ADDED rows are pruned. An extracted row the reviewer emptied is a\n * deliberate assertion that its content is wrong, and must survive.\n */\nexport function pruneEmptyAddedRows(\n plannedTables: ReadonlyMap<string, PlannedRow[]>,\n edits: ReadonlyMap<string, string>,\n): Map<string, PlannedRow[]> {\n const out = new Map<string, PlannedRow[]>();\n for (const [pointer, rows] of plannedTables) {\n out.set(pointer, rows.filter((row) => {\n if (row.entry.source !== null) {\n return true;\n }\n return row.cells.some((cell) => (edits.get(cell.editKey) ?? '').trim() !== '');\n }));\n }\n return out;\n}\n","/**\n * Verification form — field primitives (Task 12).\n *\n * Port of the console's `FieldValue.tsx` through the house-style\n * transformation table: antd `<Tooltip>` becomes a native `title` attribute\n * paired with an aria-label, `@ant-design/icons` becomes the hand-drawn\n * `IconEye`, SCSS-module classes become the Task 6 `.gemina-verification__*`\n * contract classes, and NO inline colors — every visual state is a class\n * driven by the theme tokens.\n *\n * Accessibility contract (load-bearing, not decorative):\n * - The confidence dot is a color-only signal, so it always carries\n * `role=\"img\"` + a text `aria-label` and a `title` tooltip listing the\n * formatted reasons (WCAG 1.4.1 / 1.4.11).\n * - The dirty state pairs the `--dirty` border color with a visible \"edited\"\n * text badge, linked to the input via `aria-describedby`. When a missed\n * field is filled in, `--missed`'s error border wins the CSS cascade — the\n * badge is then the ONLY visible dirty channel, which is why it is a word\n * and not another color.\n *\n * Editing contract: dirtiness is exactly `edit !== undefined`. The PARENT\n * owns revert detection (it deletes the edits entry when the value returns to\n * the initial string) — nothing here compares against the initial value.\n *\n * Layout contract: FieldInput renders a FRAGMENT (input + \"edited\" badge) and\n * expects a flex-row container — `__dd`, `__cell`, and the simple-list items\n * provide it.\n *\n * Shape sections (Task 13): VerificationForm renders the classifier's buckets\n * in the CONSOLE's section order (FormView/index.tsx): Details (headers +\n * simple lists), entity cards, tables, fallback — then the SDK-only\n * \"Not detected\" section for bindings that matched no rendered field.\n */\nimport React from 'react';\nimport type { FieldBinding } from './bindings';\nimport { toInputString } from './bindings';\nimport type { ClassifiedCell, ClassifiedData, ClassifiedField } from './classify';\nimport { ROW_META_KEY, formatLabel, formatValue } from './classify';\nimport { ISO_4217_CODES, cellSchemaKey, validateInput } from './field-types';\nimport type { RowMutableTable, ValidationFieldDescriptor } from './field-types';\nimport { displayColumns, matchesTablePointer } from './row-cells';\nimport type { PlannedCell, PlannedRow } from './row-cells';\nimport { cellEditKey } from './row-plan';\nimport { NOTHING_HIDDEN, unplannedRowKey } from './review-filter';\nimport type { HiddenSets } from './review-filter';\nimport type { RowPlanEntry } from './row-plan';\nimport { NOT_FOUND, parseSchemaKey, snakeToCamel } from './pointer';\nimport { Tip } from './tip';\nimport { IconEye } from './viewer';\n\n/** Colored dot + native tooltip. Absent (or blank-level) confidence renders nothing. */\nexport function ConfidenceDot(props: {\n confidence: { level: string; reasons: string[] } | null;\n}): React.JSX.Element | null {\n const { confidence } = props;\n if (!confidence?.level) {\n return null;\n }\n\n let variant: 'high' | 'medium' | 'low' | 'unknown';\n let label: string;\n switch (confidence.level.toLowerCase()) {\n case 'high':\n variant = 'high';\n label = 'High confidence';\n break;\n case 'medium':\n variant = 'medium';\n label = 'Medium confidence';\n break;\n case 'low':\n variant = 'low';\n label = 'Low confidence';\n break;\n default:\n variant = 'unknown';\n label = `${confidence.level} confidence`;\n }\n\n const reasons = confidence.reasons.map(formatLabel);\n // The reasons must reach AT (and the keyboard) regardless of the tooltip, so\n // the accessible NAME carries them: \"Low confidence: Blurry Region, Low OCR\n // Quality\". One string, no extra DOM. The tip is the SIGHTED channel for the\n // same facts — hence `aria-describedby` is all Tip adds, and the name is\n // left alone so nothing is announced twice.\n const ariaLabel = reasons.length > 0 ? `${label}: ${reasons.join(', ')}` : label;\n // A heading over a list — the shape `title=` could never express, and the\n // reason this component exists. Matches the console's FieldValue treatment.\n const tip = (\n <>\n <strong className=\"gemina-verification__tip-title\">{label}</strong>\n {reasons.length > 0 ? (\n <ul className=\"gemina-verification__tip-list\">\n {reasons.map((reason) => <li key={reason}>{reason}</li>)}\n </ul>\n ) : null}\n </>\n );\n return (\n <Tip content={tip}>\n <span\n className={`gemina-verification__dot gemina-verification__dot--${variant}`}\n role=\"img\"\n aria-label={ariaLabel}\n />\n </Tip>\n );\n}\n\n/** Eye button that flashes the field's rects on the document. */\nexport function EyeButton(props: {\n coordinates: { points: [number, number][] } | null;\n onFlash: () => void;\n}): React.JSX.Element | null {\n const { coordinates, onFlash } = props;\n if (!coordinates) {\n return null;\n }\n return (\n <Tip content=\"Show on document\">\n <button\n type=\"button\"\n className=\"gemina-verification__eye\"\n aria-label=\"Show on document\"\n onClick={(event) => {\n // Rows use click-to-flash (Task 13); the field eye must not double-fire it.\n event.stopPropagation();\n onFlash();\n }}\n >\n <IconEye />\n </button>\n </Tip>\n );\n}\n\n/** One editable field: input prefilled with the RAW value, dirty + missed states. */\nexport function FieldInput(props: {\n binding: FieldBinding;\n /** Current value if dirty, else undefined (input falls back to initial). */\n edit: string | undefined;\n /** Parent deletes the edits entry when value returns to the initial string. */\n /** `binding` travels with the change so revert detection never has to\n * resolve an edit key back to a field — a cell key could not be. */\n onEdit: (editKey: string, value: string, binding: FieldBinding) => void;\n readOnly: boolean;\n /** formatLabel(label) — the visible label lives in the surrounding layout. */\n ariaLabel: string;\n /**\n * A row-level error decided outside this field (the unit-size pair rule).\n * Wins over per-field validation and applies even when untouched: the field\n * is invalid because of its SIBLING, so dirtiness here is irrelevant.\n */\n pairError?: string;\n /**\n * The key this field's edit is stored under. Defaults to the raw schema key\n * (headers, and tables with no row plan); a row-mutable table passes a\n * `cellEditKey` so the edit follows the ROW rather than the position.\n */\n editKey?: string;\n}): React.JSX.Element {\n const { binding, edit, onEdit, readOnly, ariaLabel, pairError } = props;\n const editKey = props.editKey ?? binding.key.raw;\n const editedBadgeId = React.useId();\n const errorId = React.useId();\n const currencyListId = React.useId();\n\n // Container serverValues (value-object wrappers, arrays, objects) can never\n // score correct from a string edit — the server's coerce_like only adopts\n // types for scalar targets — so they render read-only (C1/C2 amendment).\n // NOTE: this branch deliberately DISCARDS `edit` and shows the extracted\n // value — correct for the 409 already-validated path. Task 17: keep\n // submit-in-progress as disabled buttons, NOT a readOnly flip, or the\n // user's pending edits would visually vanish mid-submit.\n if (readOnly || !binding.editable) {\n const display = binding.extracted === NOT_FOUND ? null : binding.extracted;\n return <span>{formatValue(display, binding.key.label)}</span>;\n }\n\n const dirty = edit !== undefined;\n const missed = binding.serverValue === NOT_FOUND;\n const field = binding.field;\n const value = dirty ? edit : toInputString(binding.extracted);\n\n // Only a value the reviewer TYPED can be invalid. An extracted value that is\n // off-roster is the model's output, not their mistake: it is preserved (see\n // the pinned option below) and must not block a submission they never\n // touched. Task 6.4's gate reads the same rule.\n const error = pairError ?? (dirty ? validateInput(value, field) : null);\n const className = [\n 'gemina-verification__input',\n dirty ? 'gemina-verification__input--dirty' : '',\n missed ? 'gemina-verification__input--missed' : '',\n error ? 'gemina-verification__input--invalid' : '',\n ]\n .filter(Boolean)\n .join(' ');\n\n // Space-separated, never overwritten: the edited badge and the error are\n // both descriptions of the same control and a reviewer needs to hear both.\n const describedBy = [dirty ? editedBadgeId : '', error ? errorId : '']\n .filter(Boolean)\n .join(' ');\n const shared = {\n className,\n 'aria-label': ariaLabel,\n 'aria-describedby': describedBy || undefined,\n 'aria-invalid': error ? (true as const) : undefined,\n onChange: (event: React.ChangeEvent<HTMLInputElement | HTMLSelectElement>) =>\n onEdit(editKey, event.target.value, binding),\n };\n\n // A closed roster is a choice, not a spelling test. The extracted value is\n // PINNED as an option when it is off-roster, so opening the select can never\n // silently destroy what the model found.\n const roster = field?.enum && field.enum.length > 0 ? field.enum : null;\n const offRoster = roster && value !== '' && !roster.includes(value) ? value : null;\n\n const control = roster ? (\n <select {...shared} value={value} dir=\"auto\">\n {/* Clearing stays possible: an empty submission asserts \"not present\". */}\n <option value=\"\">—</option>\n {offRoster ? <option value={offRoster}>{offRoster} (as extracted)</option> : null}\n {roster.map((option) => <option key={option} value={option}>{option}</option>)}\n </select>\n ) : (\n <input\n {...shared}\n // `date` gets the native picker; everything else stays text so the\n // server's own leniency (commas, underscores) is not fought by the\n // browser's number parsing.\n type={field?.type === 'date' ? 'date' : 'text'}\n // Per-input bidi: a Latin value inside an RTL (Hebrew) document — or\n // vice versa — must lay out by its own content, not the widget's dir.\n dir=\"auto\"\n // RAW value only — a display-formatted \"1,500\" round-tripped into the\n // submission would score as a correction (see toInputString).\n value={value}\n // A hint to the soft keyboard, NOT validation — validateInput is that.\n inputMode={field?.type === 'number' || field?.type === 'integer' ? 'decimal' : undefined}\n list={field?.format === 'iso4217' ? currencyListId : undefined}\n placeholder={missed ? 'Not detected — fill in if present' : undefined}\n autoComplete=\"off\"\n />\n );\n\n return (\n <>\n {control}\n {field?.format === 'iso4217' ? (\n <datalist id={currencyListId}>\n {ISO_4217_CODES.map((code) => <option key={code} value={code} />)}\n </datalist>\n ) : null}\n {error ? (\n <span className=\"gemina-verification__field-error\" id={errorId} role=\"alert\">\n {error}\n </span>\n ) : null}\n {dirty ? (\n // The badge is where the ORIGINAL belongs, now that the input holds\n // the edit — otherwise the extracted value is simply gone from the\n // screen the moment someone corrects it.\n //\n // Known limit: the badge is a non-focusable span, so this channel is\n // hover-only. AT is not worse off than before (nothing carried the\n // original previously), and the input's aria-describedby still names\n // the field as edited. Giving it a keyboard path needs a focusable\n // affordance, which belongs with the Phase 8 row work, not here.\n <Tip\n content={\n <>\n <span className=\"gemina-verification__tip-label\">Was: </span>\n {formatValue(binding.extracted === NOT_FOUND ? null : binding.extracted,\n binding.key.label)}\n </>\n }\n >\n <span className=\"gemina-verification__edited\" id={editedBadgeId}>\n edited\n </span>\n </Tip>\n ) : null}\n </>\n );\n}\n\n// --- Shape sections (Task 13) ------------------------------------------------\n\ninterface FlashRect {\n points: [number, number][];\n}\n\n/** State + callbacks every section threads down to its fields.\n *\n * STABILITY CONTRACT (callers, i.e. Task 14): `onEdit`, `onFlash`, and\n * `bindingIndex` MUST be referentially stable across renders (useCallback /\n * useMemo) — the table-row memo compares them by reference, so an unstable\n * handler silently degrades every row bail-out to a full re-render. `edits`\n * MUST be replaced immutably on every change, never mutated in place: the\n * comparator short-circuits on `prevEdits === nextEdits`, so an in-place\n * mutation renders no update at all. */\ninterface SectionShared {\n /** Edit key -> row-level error. Empty for every extraction without the pair. */\n pairErrors: ReadonlyMap<string, string>;\n /** Server-declared row-mutable tables. Empty disables every row control. */\n rowMutableTables: readonly RowMutableTable[];\n /**\n * Table pointer -> its rows, already resolved to cells. Computed ONCE by the\n * parent: computing it here as well would produce a second object per render\n * and defeat the row memo, which compares it by reference.\n */\n plannedTables: ReadonlyMap<string, PlannedRow[]>;\n onAddRow: (tablePointer: string, afterPosition: number) => void;\n onRemoveRow: (tablePointer: string, position: number) => void;\n\n bindingIndex: Map<string, FieldBinding>;\n edits: ReadonlyMap<string, string>;\n /** `binding` travels with the change so revert detection never has to\n * resolve an edit key back to a field — a cell key could not be. */\n onEdit: (editKey: string, value: string, binding: FieldBinding) => void;\n readOnly: boolean;\n onFlash: (rects: FlashRect[]) => void;\n /**\n * Fields and rows the review filter is hiding. `NOTHING_HIDDEN` when off.\n *\n * NOT part of `areRowPropsEqual`, on purpose: it is derived from `edits`, so\n * a new object arrives on every keystroke and comparing it would re-render\n * every row in the table — the same cost `pairErrors` is excluded to avoid.\n * It costs nothing to leave out, because a hidden row is never rendered at\n * all; only the sections need to read it.\n */\n hidden: HiddenSets;\n /**\n * Whether the filter is engaged. Rows DO react to this — they drop their\n * add/remove controls, because \"insert below row 3\" is meaningless when row\n * 4 is hidden — so unlike `hidden` it must be compared. It is a stable\n * boolean, so that is free.\n */\n filterOn: boolean;\n}\n\n/** Props for the whole form pane.\n *\n * The SectionShared stability contract applies (see above), and `classified`\n * must be the memoized product of one `classifyData` call — a fresh object\n * per render defeats both the row memo and the fallback-section memo. */\n/** One shared empty instance: `shared` is compared by reference downstream, so\n * \"no row errors\" must always be the SAME object. */\nconst NO_PAIR_ERRORS: ReadonlyMap<string, string> = new Map();\nconst NO_TABLES: readonly RowMutableTable[] = [];\nconst NO_PLANNED: ReadonlyMap<string, PlannedRow[]> = new Map();\nconst NOOP_ROW = () => {};\n\nexport interface VerificationFormProps\n extends Omit<SectionShared,\n 'pairErrors' | 'rowMutableTables' | 'plannedTables' | 'onAddRow' | 'onRemoveRow' | 'hidden' | 'filterOn'> {\n /** Review filter. Omitted = off, hiding nothing — same contract as the row\n * props above: a host rendering the form directly need not know it exists. */\n hidden?: HiddenSets;\n filterOn?: boolean;\n /**\n * All optional on the public surface. The pair rule and the row plans are\n * internal details of the full component, and a host — or a test — rendering\n * the form directly should not have to know they exist. Omitting them yields\n * exactly the pre-row-editing form: no controls, raw-key edits.\n */\n pairErrors?: ReadonlyMap<string, string>;\n rowMutableTables?: readonly RowMutableTable[];\n plannedTables?: ReadonlyMap<string, PlannedRow[]>;\n onAddRow?: (tablePointer: string, afterPosition: number) => void;\n onRemoveRow?: (tablePointer: string, position: number) => void;\n classified: ClassifiedData;\n /** Bindings whose pointer matched NO rendered field — the \"model missed the\n * whole field\" case; rendered as an extra \"Not detected\" section of empty inputs. */\n unmatched: FieldBinding[];\n}\n\n/** True when the click started on an interactive element — row click-to-flash\n * must never hijack typing, button presses, or link follows. */\nfunction isInteractiveTarget(target: EventTarget | null): boolean {\n return target instanceof Element && target.closest('input, button, a, select, textarea') !== null;\n}\n\n/**\n * A field label, with the model's description as a tooltip when there is one.\n *\n * Plain text when there is not: an empty tooltip trigger is worse than none,\n * because it promises information it does not have.\n */\nfunction FieldLabel(props: { label: string; description?: string | null }): React.JSX.Element {\n const { label, description } = props;\n if (!description) {\n return <span>{label}</span>;\n }\n return (\n <Tip content={description}>\n <span className=\"gemina-verification__label-described\" tabIndex={0}>{label}</span>\n </Tip>\n );\n}\n\n/** One label/value pair inside a description list (headers + entity cards). */\nfunction FieldPair(props: {\n label: string;\n ariaLabel: string;\n cell: ClassifiedCell | ClassifiedField;\n shared: SectionShared;\n}): React.JSX.Element {\n const { label, ariaLabel, cell, shared } = props;\n const binding = shared.bindingIndex.get(cell.pointer);\n return (\n <>\n <dt className=\"gemina-verification__dt\">\n <ConfidenceDot confidence={cell.confidence} />\n {/* The model's own field description, which the backend publishes per\n field. Without this it is carried all the way to the client and\n then dropped — and it is the only place a reviewer can learn what\n a field like \"assignment number\" is actually supposed to contain. */}\n <FieldLabel label={label} description={binding?.field?.description} />\n </dt>\n <dd className=\"gemina-verification__dd\">\n {binding !== undefined ? (\n <FieldInput\n binding={binding}\n pairError={shared.pairErrors.get(binding.key.raw)}\n edit={shared.edits.get(binding.key.raw)}\n onEdit={shared.onEdit}\n readOnly={shared.readOnly}\n ariaLabel={ariaLabel}\n />\n ) : (\n <span>{formatValue(cell.value, label)}</span>\n )}\n <EyeButton\n coordinates={cell.coordinates}\n onFlash={() => {\n if (cell.coordinates) {\n shared.onFlash([cell.coordinates]);\n }\n }}\n />\n </dd>\n </>\n );\n}\n\n/** \"Details\": header fields + simple lists in one description-list section. */\nfunction HeaderSection(props: {\n headers: ClassifiedField[];\n simpleLists: ClassifiedData['simpleLists'];\n shared: SectionShared;\n}): React.JSX.Element | null {\n const { headers, simpleLists, shared } = props;\n // The review filter hides what already scored high. Applied here rather than\n // at the call site so simple lists get the same treatment as headers.\n const visibleHeaders = headers.filter((field) => !shared.hidden.fields.has(field.pointer));\n const visibleLists = simpleLists\n .map((list) => ({ ...list, items: list.items.filter((item) => !shared.hidden.fields.has(item.pointer)) }))\n .filter((list) => list.items.length > 0);\n if (visibleHeaders.length === 0 && visibleLists.length === 0) {\n return null;\n }\n return (\n <section className=\"gemina-verification__section\" aria-label=\"Details\">\n <div className=\"gemina-verification__section-header\">Details</div>\n <dl className=\"gemina-verification__dl\">\n {visibleHeaders.map((field) => (\n <FieldPair\n key={field.pointer}\n label={formatLabel(field.key)}\n ariaLabel={formatLabel(field.key)}\n cell={field}\n shared={shared}\n />\n ))}\n {visibleLists.map((list) => (\n <React.Fragment key={list.pointer}>\n <dt className=\"gemina-verification__dt\">\n <span>{formatLabel(list.key)}</span>\n </dt>\n <dd className=\"gemina-verification__dd\">\n <ul className=\"gemina-verification__list\">\n {list.items.map((item, index) => {\n const binding = shared.bindingIndex.get(item.pointer);\n return (\n <li key={item.pointer} className=\"gemina-verification__cell\">\n {binding !== undefined ? (\n <FieldInput\n binding={binding}\n pairError={shared.pairErrors.get(binding.key.raw)}\n edit={shared.edits.get(binding.key.raw)}\n onEdit={shared.onEdit}\n readOnly={shared.readOnly}\n ariaLabel={`${formatLabel(list.key)} item ${index + 1}`}\n />\n ) : (\n <span>{formatValue(item.value)}</span>\n )}\n <ConfidenceDot confidence={item.confidence} />\n <EyeButton\n coordinates={item.coordinates}\n onFlash={() => {\n if (item.coordinates) {\n shared.onFlash([item.coordinates]);\n }\n }}\n />\n </li>\n );\n })}\n </ul>\n </dd>\n </React.Fragment>\n ))}\n </dl>\n </section>\n );\n}\n\n/** Entity bucket: one card per item, headers singularized console-style. */\nfunction EntitySection(props: {\n entity: ClassifiedData['entities'][number];\n shared: SectionShared;\n}): React.JSX.Element {\n const { entity, shared } = props;\n // Drop a card only when ALL of its cells are hidden — a card with one\n // remaining medium-confidence field is still worth reviewing.\n // The ORIGINAL index travels with each surviving card. Renumbering after a\n // filter would relabel \"Supplier 2\" as \"Supplier 1\" — in the visible header\n // AND in the aria-label, telling a screen-reader user they are editing a\n // different entity than they are. Same reason the table keeps plan positions.\n const visibleItems = entity.items\n .map((item, index) => ({\n index,\n cells: Object.fromEntries(\n Object.entries(item).filter(([, cellValue]) => !shared.hidden.fields.has(cellValue.pointer)),\n ),\n }))\n .filter(({ cells }) => Object.keys(cells).length > 0);\n const label = formatLabel(entity.key);\n // The console's naive strip-trailing-s, ported verbatim (\"Suppliers\" →\n // \"Supplier\"; yes, \"Parties\" → \"Partie\" — console parity over grammar).\n const singular = label.replace(/s$/, '');\n return (\n <section className=\"gemina-verification__section\" aria-label={label}>\n <div className=\"gemina-verification__section-header\">\n {/* The true count, not the filtered one: the heading says how many\n entities the document has, and the filter never changes that. */}\n {label} ({entity.items.length})\n </div>\n <div className=\"gemina-verification__section-body\">\n {visibleItems.map(({ index, cells }) => (\n // Keyed by the original index, never the filtered position, or React\n // reuses a hidden card's DOM (and its focus) for its successor.\n <div key={index} className=\"gemina-verification__card\">\n <div className=\"gemina-verification__card-header\">\n {singular} {index + 1}\n </div>\n <dl className=\"gemina-verification__dl\">\n {Object.entries(cells).map(([fieldKey, cell]) => (\n <FieldPair\n key={fieldKey}\n label={formatLabel(fieldKey)}\n // Card context: two \"Supplier\" cards both announcing a bare\n // \"Name\" would be ambiguous to a screen reader.\n ariaLabel={`${singular} ${index + 1} — ${formatLabel(fieldKey)}`}\n cell={cell}\n shared={shared}\n />\n ))}\n </dl>\n </div>\n ))}\n </div>\n </section>\n );\n}\n\ninterface TableRowViewProps {\n /** The classified row behind this render — undefined for a row the reviewer added. */\n row: Record<string, ClassifiedCell> | undefined;\n /** Position in the SUBMITTED table: what the reviewer sees, and what labels count. */\n rowIndex: number;\n columns: string[];\n /** formatLabel(tableKey), precomputed once per table. */\n tableLabel: string;\n hasCoords: boolean;\n hasRowConfidence: boolean;\n shared: SectionShared;\n /** Resolved cells + row identity. Present ONLY for a row-mutable table. */\n planned?: PlannedRow;\n /** The server's pointer for this table — the key the row handlers take. */\n tablePointer?: string;\n}\n\nfunction TableRowView(props: TableRowViewProps): React.JSX.Element {\n const { row, rowIndex, columns, tableLabel, hasCoords, hasRowConfidence, shared, planned, tablePointer } = props;\n const { bindingIndex, edits, onEdit, readOnly, onFlash } = shared;\n\n const rects = React.useMemo(() => {\n const collected: FlashRect[] = [];\n for (const [key, cell] of Object.entries(row ?? {})) {\n if (key !== ROW_META_KEY && cell.coordinates) {\n collected.push(cell.coordinates);\n }\n }\n return collected;\n }, [row]);\n\n const handleRowClick = React.useCallback(\n (event: React.MouseEvent<HTMLTableRowElement>) => {\n if (isInteractiveTarget(event.target)) {\n return;\n }\n if (rects.length > 0) {\n onFlash(rects);\n }\n },\n [rects, onFlash],\n );\n\n /** Cells by column: from the plan when there is one, else today's lookup. */\n const cellFor = (column: string) => {\n // Server-declared table columns use model names (snake_case), but response\n // DTOs expose the same keys in camelCase. Prefer an exact key (important\n // for dynamic templates that genuinely use either spelling), then match\n // through the one shared casing rule.\n const direct = row?.[column];\n const alias = direct === undefined ? row?.[snakeToCamel(column)] : undefined;\n const fallbackKey = direct === undefined && alias === undefined && row !== undefined\n ? Object.keys(row).find((key) => snakeToCamel(key) === snakeToCamel(column))\n : undefined;\n const classified = direct ?? alias ?? (fallbackKey === undefined ? undefined : row?.[fallbackKey]);\n const fromPlan = planned?.cells.find((cell: PlannedCell) => cell.column === column);\n if (fromPlan) {\n return { classified, binding: fromPlan.binding, editKey: fromPlan.editKey };\n }\n const binding = classified === undefined ? undefined : bindingIndex.get(classified.pointer);\n return { classified, binding, editKey: binding?.key.raw };\n };\n\n const firstRect = rects.length > 0 ? rects[0]! : null;\n // Row controls are OMITTED while filtering, not disabled: \"insert below\n // row 3\" is meaningless when row 4 is hidden, and a disabled button\n // cannot carry its own explanation — Tip attaches hover/focus handlers to\n // its child, and a disabled button dispatches neither.\n const showControls = planned !== undefined && tablePointer !== undefined && !readOnly\n && !shared.filterOn;\n // A REDUNDANT channel: the confidence dot and its tooltip already carry the\n // meaning, so this marker does not have to pass contrast on its own — it is\n // there so a reviewer can find the rows worth checking by scanning the edge\n // of a 150-line table instead of reading every dot.\n const rowLevel = (row?.[ROW_META_KEY]?.confidence?.level ?? '').toLowerCase();\n const rowClass = rowLevel === 'low' || rowLevel === 'medium'\n ? `gemina-verification__row--${rowLevel}`\n : undefined;\n return (\n <tr onClick={handleRowClick} className={rowClass}>\n {hasCoords ? (\n <td>\n {/* EyeButton's coordinates prop is only the render gate here — the\n click flashes ALL the row's rects, console DataTable style. */}\n <EyeButton coordinates={firstRect} onFlash={() => onFlash(rects)} />\n </td>\n ) : null}\n {hasRowConfidence ? (\n <td>\n <ConfidenceDot confidence={row?.[ROW_META_KEY]?.confidence ?? null} />\n </td>\n ) : null}\n {columns.map((column) => {\n const { classified, binding, editKey } = cellFor(column);\n return (\n <td key={column}>\n <div className=\"gemina-verification__cell\">\n {binding !== undefined ? (\n <FieldInput\n binding={binding}\n editKey={editKey}\n pairError={editKey === undefined ? undefined : shared.pairErrors.get(editKey)}\n edit={editKey === undefined ? undefined : edits.get(editKey)}\n onEdit={onEdit}\n readOnly={readOnly}\n ariaLabel={`${tableLabel} row ${rowIndex + 1} — ${formatLabel(column)}`}\n />\n ) : (\n <span>{classified === undefined ? '-' : formatValue(classified.value, column)}</span>\n )}\n <ConfidenceDot confidence={classified?.confidence ?? null} />\n </div>\n </td>\n );\n })}\n {showControls ? (\n <td className=\"gemina-verification__row-actions\">\n {/* Row-numbered labels: \"Remove line\" repeated N times is unusable\n with a screen reader, and the number is what the reviewer sees. */}\n <Tip content=\"Insert a line below\">\n <button\n type=\"button\"\n className=\"gemina-verification__row-btn\"\n aria-label={`Insert line below line ${rowIndex + 1}`}\n onClick={() => shared.onAddRow(tablePointer!, rowIndex)}\n >\n +\n </button>\n </Tip>\n <Tip content=\"Remove this line\">\n <button\n type=\"button\"\n className=\"gemina-verification__row-btn\"\n aria-label={`Remove line ${rowIndex + 1}`}\n onClick={() => shared.onRemoveRow(tablePointer!, rowIndex)}\n >\n ×\n </button>\n </Tip>\n </td>\n ) : null}\n </tr>\n );\n}\n\n/** Bail out unless THIS row's data or its slice of the edits changed. The\n * comparator inspects only edits for this row's cells, so one keystroke\n * re-renders one row. Callbacks are compared by reference: the parent must\n * pass referentially stable `onEdit`/`onFlash` (and a stable\n * `classified`/`bindingIndex`) or the memoization degrades to plain renders. */\nfunction areRowPropsEqual(prev: TableRowViewProps, next: TableRowViewProps): boolean {\n if (\n prev.row !== next.row\n || prev.rowIndex !== next.rowIndex\n || prev.columns !== next.columns\n || prev.tableLabel !== next.tableLabel\n || prev.hasCoords !== next.hasCoords\n || prev.hasRowConfidence !== next.hasRowConfidence\n || prev.planned !== next.planned\n || prev.tablePointer !== next.tablePointer\n || prev.shared.bindingIndex !== next.shared.bindingIndex\n || prev.shared.onEdit !== next.shared.onEdit\n || prev.shared.onFlash !== next.shared.onFlash\n || prev.shared.readOnly !== next.shared.readOnly\n // Stable boolean, and rows must react to it (controls disappear).\n // `shared.hidden` is deliberately absent — see SectionShared.\n || prev.shared.filterOn !== next.shared.filterOn\n ) {\n // NOT compared by reference: `pairErrors` is derived from `edits`, so a new\n // Map arrives on EVERY keystroke and a blanket check would re-render every\n // row in the table. Its per-cell values are checked below instead.\n return false;\n }\n if (prev.shared.edits === next.shared.edits) {\n return true;\n }\n // Compare by EDIT key, which under a row plan is the cell key rather than\n // the raw schema key — comparing raw keys would leave a row stale after an\n // edit to a row that moved.\n for (const column of next.columns) {\n const planned = next.planned?.cells.find((cell: PlannedCell) => cell.column === column);\n const classified = next.row?.[column];\n const editKey = planned?.editKey\n ?? (classified === undefined ? undefined : next.shared.bindingIndex.get(classified.pointer)?.key.raw);\n if (editKey === undefined) {\n continue;\n }\n if (prev.shared.edits.get(editKey) !== next.shared.edits.get(editKey)\n || prev.shared.pairErrors.get(editKey) !== next.shared.pairErrors.get(editKey)) {\n return false;\n }\n }\n return true;\n}\n\nconst TableRow = React.memo(TableRowView, areRowPropsEqual);\n\n\n/**\n * Promote a row-mutable table the classifier could not see as one.\n *\n * An EMPTY array classifies as a header, not a table (classify.ts) — so an\n * extraction that found no line items has no table, no columns and nowhere to\n * put \"Add line\". That is the case this feature exists for: the model found\n * nothing and the reviewer types it in.\n *\n * Done as a post-classification promotion driven by the SERVER's contract\n * rather than by changing the classifier, whose heuristics are shared with the\n * console and proven. The header the empty array produced is suppressed, or it\n * would render twice — once as \"Line Items: []\" and once as the table.\n */\nexport function withEmptyMutableTables(\n classified: ClassifiedData,\n tables: readonly RowMutableTable[],\n): { tables: ClassifiedData['tables']; suppressed: ReadonlySet<string> } {\n if (tables.length === 0) {\n return { tables: classified.tables, suppressed: EMPTY_SUPPRESSED };\n }\n const promoted = [...classified.tables];\n const suppressed = new Set<string>();\n for (const table of tables) {\n if (classified.tables.some((candidate) => matchesTablePointer(table.pointer, candidate.pointer))) {\n continue;\n }\n const header = classified.headers.find(\n (candidate) => matchesTablePointer(table.pointer, candidate.pointer),\n );\n // The classifier normalises an empty array to `value: null`, so BOTH\n // spellings mean \"no rows\". Nothing else is promoted: a pointer that\n // resolved to real data is a contract mismatch, and inventing a table for\n // it would put row controls over data the scorer cannot align. The\n // server's own declaration is what makes this safe — the reviewer can only\n // ever add rows to a table the scorer knows how to align.\n const empty = header !== undefined\n && (header.value === null || (Array.isArray(header.value) && header.value.length === 0));\n if (!empty) {\n continue;\n }\n suppressed.add(header!.pointer);\n promoted.push({\n key: header!.key,\n pointer: header!.pointer,\n columns: [],\n rows: [],\n overallConfidence: null,\n });\n }\n return { tables: promoted, suppressed };\n}\n\nconst EMPTY_SUPPRESSED: ReadonlySet<string> = new Set();\n\n/** Table bucket: the console DataTable's column model without antd. */\nfunction TableSection(props: {\n table: ClassifiedData['tables'][number];\n shared: SectionShared;\n}): React.JSX.Element {\n const { table, shared } = props;\n const label = formatLabel(table.key);\n\n // Row editing is offered ONLY where the server declared it. Any wide array\n // of objects looks like a table to the classifier — custom_template's do —\n // and controls on one the scorer cannot align would mis-score permanently.\n const mutable = React.useMemo(\n () => shared.rowMutableTables.find((entry) => matchesTablePointer(entry.pointer, table.pointer)),\n [shared.rowMutableTables, table.pointer],\n );\n const columns = React.useMemo(\n () => (mutable ? displayColumns(mutable, table.columns) : table.columns),\n [mutable, table.columns],\n );\n const planned = mutable ? shared.plannedTables.get(mutable.pointer) : undefined;\n\n // Full-row scans — memoized so keystroke re-renders don't re-walk every cell.\n const hasCoords = React.useMemo(\n () =>\n table.rows.some((row) =>\n Object.entries(row).some(([key, cell]) => key !== ROW_META_KEY && cell.coordinates !== null),\n ),\n [table],\n );\n const hasRowConfidence = React.useMemo(\n () => table.rows.some((row) => Boolean(row[ROW_META_KEY]?.confidence?.level)),\n [table],\n );\n // Column descriptions come from the server's declared columns, so they are\n // present even for a zero-row table — the case where a reviewer typing a\n // line in most needs to know what each column means.\n const columnDescriptions = React.useMemo(() => {\n const map = new Map<string, string>();\n for (const column of mutable?.columns ?? []) {\n if (typeof column.key === 'string' && column.description) {\n map.set(column.key, column.description);\n }\n }\n return map;\n }, [mutable]);\n const rowCount = planned ? planned.length : table.rows.length;\n // `ConfidenceModel` is a closed high|medium|low, so the scale is total: a row\n // with no confidence at all is not \"needing review\", it is unmeasured.\n const needsReview = React.useMemo(\n () => table.rows.filter((row) => {\n const level = (row[ROW_META_KEY]?.confidence?.level ?? '').toLowerCase();\n return level === 'low' || level === 'medium';\n }).length,\n [table.rows],\n );\n const showControls = planned !== undefined && mutable !== undefined && !shared.readOnly\n && !shared.filterOn;\n\n // The review filter, applied to whichever collection actually renders. A\n // planned row is addressed by `entry.id` — already table-scoped by\n // initialRowPlan — and an unplanned one by its row pointer, which is exactly\n // what CellView.rowKey uses in each case.\n // `position` is the row's index in the UNFILTERED plan and travels with it:\n // onAddRow/onRemoveRow take a plan position, so renumbering after a filter\n // would target the wrong row. (Controls are hidden while filtering anyway —\n // this keeps the two facts independent rather than relying on that.)\n const visiblePlanned = planned\n ?.map((plannedRow, position) => ({ plannedRow, position }))\n .filter(({ plannedRow }) => !shared.hidden.rows.has(plannedRow.entry.id));\n // Empty rather than null when a plan exists: the two are mutually exclusive\n // by construction, and an always-array keeps the render below free of\n // non-null assertions that only restate that fact.\n const visibleRowIndices = planned\n ? []\n : table.rows.map((_row, index) => index)\n .filter((index) => !shared.hidden.rows.has(unplannedRowKey(table.pointer, index)));\n const visibleCount = visiblePlanned ? visiblePlanned.length : visibleRowIndices.length;\n // Never an empty <tbody>: say why the rows are gone, or a filtered table\n // reads as a table that lost its data.\n const allHidden = visibleCount === 0 && rowCount > 0;\n\n return (\n <section className=\"gemina-verification__section\" aria-label={label}>\n <div className=\"gemina-verification__section-header\">\n <span>\n {label} ({rowCount} rows{needsReview > 0 ? ` · ${needsReview} need review` : ''})\n </span>\n {/* Row controls vanish while filtering (insert-below is meaningless\n when the neighbour is hidden). Their absence has to be explained\n where it is noticed, and it cannot be explained on the controls\n themselves — a disabled button carries no reachable tooltip. */}\n {shared.filterOn && mutable !== undefined && !shared.readOnly ? (\n <span className=\"gemina-verification__filter-note\">Row editing is off while filtering</span>\n ) : null}\n {table.overallConfidence ? (\n <span className=\"gemina-verification__overall-confidence\">\n <span>Overall confidence</span>\n <ConfidenceDot confidence={table.overallConfidence} />\n </span>\n ) : null}\n </div>\n {allHidden ? (\n <p className=\"gemina-verification__all-scored\">All {rowCount} rows scored high</p>\n ) : (\n <div className=\"gemina-verification__table-wrap\">\n <table className=\"gemina-verification__table\">\n <thead>\n <tr>\n {hasCoords ? <th aria-label=\"Show row on document\" /> : null}\n {hasRowConfidence ? <th aria-label=\"Row confidence\" /> : null}\n {columns.map((column) => (\n <th key={column}>\n <FieldLabel\n label={formatLabel(column)}\n description={columnDescriptions.get(column)}\n />\n </th>\n ))}\n {showControls ? <th aria-label=\"Row actions\" /> : null}\n </tr>\n </thead>\n <tbody>\n {visiblePlanned\n ? visiblePlanned.map(({ plannedRow, position }) => (\n <TableRow\n // Keyed by ROW ID, not position: a position key would make\n // React reuse a deleted row's DOM (and its focus) for its\n // successor.\n key={plannedRow.entry.id}\n row={plannedRow.entry.source === null ? undefined : table.rows[plannedRow.entry.source]}\n rowIndex={position}\n columns={columns}\n tableLabel={label}\n hasCoords={hasCoords}\n hasRowConfidence={hasRowConfidence}\n shared={shared}\n planned={plannedRow}\n tablePointer={mutable!.pointer}\n />\n ))\n : visibleRowIndices.map((rowIndex) => (\n <TableRow\n key={rowIndex}\n row={table.rows[rowIndex]}\n rowIndex={rowIndex}\n columns={columns}\n tableLabel={label}\n hasCoords={hasCoords}\n hasRowConfidence={hasRowConfidence}\n shared={shared}\n />\n ))}\n </tbody>\n </table>\n </div>\n )}\n {showControls ? (\n <div className=\"gemina-verification__table-footer\">\n <button\n type=\"button\"\n className=\"gemina-verification__add-row\"\n onClick={() => shared.onAddRow(mutable!.pointer, rowCount - 1)}\n >\n Add line\n </button>\n </div>\n ) : null}\n </section>\n );\n}\n\n/** Unclassifiable blobs: native <details> + pretty-printed JSON (no viewer dep).\n * Memoized: fallback is exactly where large unclassifiable payloads land, and\n * without the memo every parent render (i.e., every keystroke) would re-run\n * JSON.stringify over all of them. `classified.fallback` is referentially\n * stable (the parent memoizes classifyData), so the memo is a complete fix. */\nconst FallbackSection = React.memo(function FallbackSection(\n props: { fallback: ClassifiedData['fallback'] },\n): React.JSX.Element | null {\n const { fallback } = props;\n if (fallback.length === 0) {\n return null;\n }\n return (\n <section className=\"gemina-verification__section\" aria-label=\"Additional Data\">\n <div className=\"gemina-verification__section-header\">Additional Data</div>\n <div className=\"gemina-verification__section-body\">\n {fallback.map((item) => (\n <details key={item.key} className=\"gemina-verification__fallback\">\n <summary>{formatLabel(item.key)}</summary>\n <pre>{JSON.stringify(item.data, null, 2)}</pre>\n </details>\n ))}\n </div>\n </section>\n );\n});\n\n/** Bindings the model missed entirely: a section of empty fill-in inputs. */\nfunction UnmatchedSection(props: {\n unmatched: FieldBinding[];\n shared: SectionShared;\n}): React.JSX.Element | null {\n const { unmatched, shared } = props;\n if (unmatched.length === 0) {\n return null;\n }\n return (\n <section className=\"gemina-verification__section\" aria-label=\"Not detected\">\n <div className=\"gemina-verification__section-header\">Not detected</div>\n <dl className=\"gemina-verification__dl\">\n {unmatched.map((binding) => (\n <React.Fragment key={binding.key.raw}>\n {/* Schema labels are already human text — formatLabel is for raw\n payload keys only (it would mangle \"PO Number\" → \"Po Number\"). */}\n <dt className=\"gemina-verification__dt\">\n <span>{binding.key.label}</span>\n </dt>\n <dd className=\"gemina-verification__dd\">\n <FieldInput\n binding={binding}\n pairError={shared.pairErrors.get(binding.key.raw)}\n edit={shared.edits.get(binding.key.raw)}\n onEdit={shared.onEdit}\n readOnly={shared.readOnly}\n ariaLabel={binding.key.label}\n />\n </dd>\n </React.Fragment>\n ))}\n </dl>\n </section>\n );\n}\n\n/** The whole form pane: every classified bucket in console order, then the\n * unmatched \"Not detected\" section. Empty buckets render nothing. */\nexport function VerificationForm(props: VerificationFormProps): React.JSX.Element {\n const {\n classified, unmatched, bindingIndex, edits, onEdit, readOnly, onFlash,\n pairErrors, rowMutableTables, plannedTables, onAddRow, onRemoveRow,\n hidden, filterOn,\n } = props;\n const { tables: promotedTables, suppressed } = React.useMemo(\n () => withEmptyMutableTables(classified, rowMutableTables ?? NO_TABLES),\n [classified, rowMutableTables],\n );\n const shared: SectionShared = {\n bindingIndex, edits, onEdit, readOnly, onFlash,\n pairErrors: pairErrors ?? NO_PAIR_ERRORS,\n rowMutableTables: rowMutableTables ?? NO_TABLES,\n plannedTables: plannedTables ?? NO_PLANNED,\n onAddRow: onAddRow ?? NOOP_ROW,\n onRemoveRow: onRemoveRow ?? NOOP_ROW,\n hidden: hidden ?? NOTHING_HIDDEN,\n filterOn: filterOn ?? false,\n };\n return (\n // A real, labeled <form> (role \"form\" landmark): AT users can jump\n // straight to the editable fields. Submission is owned by the root's\n // footer button, never by the form element itself — preventDefault stops\n // implicit submission (Enter in a payload with exactly one input would\n // otherwise navigate).\n <form\n className=\"gemina-verification__form\"\n aria-label=\"Extraction fields\"\n onSubmit={(event) => event.preventDefault()}\n >\n {classified.overallConfidence ? (\n <div className=\"gemina-verification__confidence-summary\">\n <span>Overall confidence</span>\n <ConfidenceDot confidence={classified.overallConfidence} />\n </div>\n ) : null}\n <HeaderSection\n headers={classified.headers.filter((header) => !suppressed.has(header.pointer))}\n simpleLists={classified.simpleLists}\n shared={shared}\n />\n {classified.entities.map((entity) => (\n <EntitySection key={entity.pointer} entity={entity} shared={shared} />\n ))}\n {promotedTables.map((table) => (\n <TableSection key={table.pointer} table={table} shared={shared} />\n ))}\n <FallbackSection fallback={classified.fallback} />\n <UnmatchedSection unmatched={unmatched} shared={shared} />\n </form>\n );\n}\n","/**\n * The review filter: which fields and rows the reviewer can hide because the\n * model already scored them `high`.\n *\n * Kept separate from the form so the rule is testable without rendering, and\n * so there is exactly ONE definition of \"already reviewed\" rather than one per\n * section component.\n *\n * Three design constraints run through this file, all learned the hard way:\n *\n * 1. Identity comes from `CellView`/`PlannedRow`, never from a pointer built\n * by hand. Under row editing a cell's edit key, its submitted key and its\n * extracted binding genuinely differ (see row-cells.ts), and reconstructing\n * any of them from a JSON pointer is exactly what row planning exists to\n * prevent. Get it wrong and an edited row is hidden anyway.\n *\n * 2. Unmeasured is not reviewed. A field with no confidence at all has not\n * been checked by anything; hiding it would drop it from review silently.\n * Only an explicit `high` hides.\n *\n * 3. Counting and hiding must walk the SAME units. When they disagree, the\n * footer's \"Showing X of Y\" contradicts the screen — which reads to a\n * reviewer as data having gone missing. That is why every consumer here\n * shares the two traversals below instead of re-deriving the buckets.\n */\n\nimport { ROW_META_KEY } from './classify';\nimport type { ClassifiedData } from './classify';\nimport type { FieldBinding } from './bindings';\nimport { matchesTablePointer } from './row-cells';\nimport type { CellView, PlannedRow } from './row-cells';\n\nexport type ConfidenceLike = { level: string; reasons: string[] } | null | undefined;\n\n/** Only an explicit `high` hides. */\nexport function isHighConfidence(confidence: ConfidenceLike): boolean {\n return (confidence?.level ?? '').toLowerCase() === 'high';\n}\n\nexport interface HiddenSets {\n /** Field pointers (headers, list items, entity cells). */\n fields: ReadonlySet<string>;\n /** Row keys, in the same spelling `CellView.rowKey` uses. */\n rows: ReadonlySet<string>;\n}\n\n/** Shared empty result, so \"nothing hidden\" is always the same object and the\n * section memos see no change. The readonly TYPE is the guarantee — a Set\n * stays mutable at runtime even under Object.freeze — so nothing may write to\n * these. */\nexport const NOTHING_HIDDEN: HiddenSets = {\n fields: new Set<string>(),\n rows: new Set<string>(),\n};\n\n/**\n * How a row of an UNPLANNED table is addressed: its row pointer, which is what\n * `collectCellViews` derives by splitting the cell pointer.\n *\n * A planned row is addressed by `entry.id` instead, and that id is ALREADY\n * scoped with the table pointer by `initialRowPlan` (`/taxes#row-0`) — so it\n * is used verbatim. Prefixing it again would produce `/taxes#/taxes#row-0` and\n * match nothing, hiding silently.\n */\nexport const unplannedRowKey = (tablePointer: string, index: number): string => `${tablePointer}/${index}`;\n\n/** The tables the FORM renders — `withEmptyMutableTables`' output, not\n * `classified.tables`. They differ: an empty server-declared row-mutable\n * table is promoted into the rendered list without existing in the\n * classifier's output, and rows the reviewer adds to one would otherwise\n * render uncounted. */\ntype RenderedTables = ClassifiedData['tables'];\n\n/**\n * Every non-table review unit, once: header fields, simple-list items and\n * entity-card cells.\n *\n * One traversal shared by the hide rule, the counter and the\n * \"is there anything to filter\" check — when those three disagreed about which\n * buckets exist, the counter contradicted the screen.\n */\nfunction forEachFieldUnit(\n classified: ClassifiedData,\n visit: (pointer: string, confidence: ConfidenceLike) => void,\n): void {\n for (const header of classified.headers) visit(header.pointer, header.confidence);\n for (const list of classified.simpleLists) {\n for (const item of list.items) visit(item.pointer, item.confidence);\n }\n for (const entity of classified.entities) {\n for (const item of entity.items) {\n for (const cell of Object.values(item)) visit(cell.pointer, cell.confidence);\n }\n }\n}\n\n/**\n * Every table ROW the form renders, once, with the key it is addressed by.\n *\n * A row counts and hides as a whole, never per cell. The plan wins where there\n * is one: it carries the rows the reviewer added and drops the ones they\n * removed, so it — not the extracted array — is what is on screen.\n */\nfunction forEachRowUnit(\n tables: RenderedTables,\n plannedTables: ReadonlyMap<string, PlannedRow[]>,\n visit: (rowKey: string, confidence: ConfidenceLike, added: boolean) => void,\n): void {\n const confidenceOf = (row: unknown): ConfidenceLike => {\n const meta = (row as Record<string, unknown> | undefined)?.[ROW_META_KEY] as\n { confidence?: ConfidenceLike } | undefined;\n return meta?.confidence ?? null;\n };\n\n // `plannedTables` is keyed by the SERVER-declared pointer, which need not\n // match the payload's spelling — a server `/line_items` can classify as\n // `/lineItems`. TableSection resolves this with matchesTablePointer before\n // looking the plan up (form.tsx), and so must this: an exact lookup silently\n // falls through to the unplanned branch, generating `/lineItems/0` keys\n // while the rendered rows are keyed `/line_items#row-0`. Nothing would ever\n // hide, and no error would be raised.\n const planFor = (tablePointer: string): PlannedRow[] | undefined => {\n const exact = plannedTables.get(tablePointer);\n if (exact !== undefined) return exact;\n for (const [serverPointer, planned] of plannedTables) {\n if (matchesTablePointer(serverPointer, tablePointer)) return planned;\n }\n return undefined;\n };\n\n for (const table of tables) {\n const planned = planFor(table.pointer);\n if (planned) {\n for (const row of planned) {\n // An added row was never extracted, so it has no confidence and is not\n // in `table.rows` at all — it can only be reached through the plan.\n // Narrowed via a local so the extracted branch needs no assertion.\n const { source } = row.entry;\n visit(row.entry.id, source === null ? null : confidenceOf(table.rows[source]), source === null);\n }\n continue;\n }\n table.rows.forEach((row, index) => {\n visit(unplannedRowKey(table.pointer, index), confidenceOf(row), false);\n });\n }\n}\n\ninterface HiddenInput {\n classified: ClassifiedData;\n /** What the form renders — see RenderedTables. */\n tables: RenderedTables;\n /** Table pointer -> planned rows. Absent entry = unplanned table. */\n plannedTables: ReadonlyMap<string, PlannedRow[]>;\n /** Authoritative cell identities (editKey + rowKey). */\n cellViews: readonly CellView[];\n /** Pointer-keyed — `indexBindingsByFieldPointer`. */\n bindingIndex: ReadonlyMap<string, FieldBinding>;\n edits: ReadonlyMap<string, string>;\n pairErrors: ReadonlyMap<string, string>;\n /** Promoted-header pointers the form does not render. Skipped, because they\n * are excluded from the unit count too — hiding one would make\n * `visible = total − hidden` miscount. */\n suppressed: ReadonlySet<string>;\n}\n\n/** Fields and rows the filter may hide: high-confidence AND untouched AND\n * error-free. */\nexport function computeHidden(input: HiddenInput): HiddenSets {\n const {\n classified, tables, plannedTables, cellViews, bindingIndex, edits, pairErrors, suppressed,\n } = input;\n\n const fields = new Set<string>();\n const rows = new Set<string>();\n\n // \"Touched\" is edits OR pairErrors: a pair error arrives with ZERO edits when\n // the extraction itself is half-filled, so edits alone would hide a field\n // that is already invalid.\n const touched = (editKey: string): boolean => edits.has(editKey) || pairErrors.has(editKey);\n\n // rowKey -> its cells' edit keys. One pass; the row walk below only looks up.\n const editKeysByRow = new Map<string, string[]>();\n for (const view of cellViews) {\n const list = editKeysByRow.get(view.rowKey);\n if (list) list.push(view.editKey);\n else editKeysByRow.set(view.rowKey, [view.editKey]);\n }\n\n forEachFieldUnit(classified, (pointer, confidence) => {\n if (suppressed.has(pointer) || !isHighConfidence(confidence)) return;\n // With no binding, nothing can resolve this field's edit key, so whether it\n // was touched is unknowable. Never hide what cannot be reasoned about.\n const editKey = bindingIndex.get(pointer)?.key.raw;\n if (editKey === undefined || touched(editKey)) return;\n fields.add(pointer);\n });\n\n forEachRowUnit(tables, plannedTables, (rowKey, confidence, added) => {\n if (added || !isHighConfidence(confidence)) return;\n if ((editKeysByRow.get(rowKey) ?? []).some(touched)) return;\n rows.add(rowKey);\n });\n\n if (fields.size === 0 && rows.size === 0) return NOTHING_HIDDEN;\n return { fields, rows };\n}\n\n/**\n * How many things the reviewer can act on — the denominator of \"Showing X of Y\".\n *\n * Walks the same two traversals `computeHidden` does, so the two cannot drift.\n * Suppressed (promoted) headers are excluded from both.\n *\n * Note this does NOT include `unmatched` bindings: they are review units too,\n * but they live outside `ClassifiedData` and the caller adds them.\n */\nexport function countUnits(\n classified: ClassifiedData,\n tables: RenderedTables,\n plannedTables: ReadonlyMap<string, PlannedRow[]>,\n suppressed: ReadonlySet<string>,\n): number {\n let total = 0;\n forEachFieldUnit(classified, (pointer) => {\n if (!suppressed.has(pointer)) total += 1;\n });\n forEachRowUnit(tables, plannedTables, () => {\n total += 1;\n });\n return total;\n}\n\n/**\n * True when any FIELD or ROW carries a confidence level — i.e. whether the\n * filter has anything at all to act on.\n *\n * Overall confidence is excluded deliberately: it renders as its own summary\n * line, is not a review unit and cannot be hidden, so offering a switch on its\n * account would give the reviewer a control that does nothing. Row confidence\n * alone qualifies, because an `invoice_line_items` extraction has no header\n * fields whatsoever and scores every row.\n */\nexport function hasAnyConfidence(\n classified: ClassifiedData,\n tables: RenderedTables,\n plannedTables: ReadonlyMap<string, PlannedRow[]>,\n): boolean {\n let found = false;\n forEachFieldUnit(classified, (_pointer, confidence) => {\n if (confidence?.level) found = true;\n });\n if (found) return true;\n forEachRowUnit(tables, plannedTables, (_rowKey, confidence) => {\n if (confidence?.level) found = true;\n });\n return found;\n}\n","/**\n * A tooltip primitive, portalled and themed.\n *\n * Replaces `title=`, which could not do any of the four things this component\n * needs: carry structure (the confidence annotation is a heading plus a list\n * of reasons), be styled to match the surface it floats over, appear on\n * keyboard focus, or be announced predictably.\n *\n * WHY A PORTAL. The console hosts `<GeminaVerification>` inside a modal body\n * with `max-height` + `overflow-y: auto`. Any in-flow tooltip is clipped at\n * that scroll edge, and the fields most likely to carry one — the low-\n * confidence rows — are exactly the ones a reviewer scrolls to. So the tip\n * renders into `document.body` and positions itself `fixed`.\n *\n * The cost of leaving the root is that `--gemina-verification-*` no longer\n * resolves, so the portal wraps its content in a div carrying the root's own\n * class list, read off the nearest `.gemina-verification` ancestor when the\n * tip opens. That keeps theme, dark mode and RTL correct without duplicating\n * a single value.\n *\n * Being `fixed`, it cannot follow a trigger that scrolls away — so it closes\n * on scroll rather than detaching from what it describes.\n */\n\nimport {\n cloneElement,\n isValidElement,\n useCallback,\n useEffect,\n useId,\n useLayoutEffect,\n useRef,\n useState,\n} from 'react';\nimport type { ReactElement, ReactNode, RefCallback } from 'react';\nimport { createPortal } from 'react-dom';\n\n/** Distance between the trigger and the tip, in px. */\nconst GAP = 8;\n/** Minimum breathing room from the viewport edge, in px. */\nconst MARGIN = 8;\n\nexport interface TipProps {\n /** Rich content — a fragment, a list, anything. Empty renders no tip. */\n content: ReactNode;\n /** The trigger. Receives handlers, a ref and `aria-describedby`. */\n children: ReactElement;\n}\n\ninterface Position {\n top: number;\n left: number;\n}\n\n/** `content` that would produce an empty bubble. */\nfunction isEmpty(content: ReactNode): boolean {\n return content == null || content === '' || content === false;\n}\n\n/**\n * The theme classes to reproduce outside the root.\n *\n * Copies the ancestor's whole class list rather than sniffing for known\n * modifiers, so a host that adds its own scoping class keeps working and this\n * never needs updating when a new modifier is introduced.\n */\nfunction rootClassesOf(node: Element | null): string {\n const root = node?.closest('.gemina-verification');\n return root ? root.className : 'gemina-verification';\n}\n\n/** Attach our ref without dropping one the child already had. */\nfunction mergeRefs<T>(ours: RefCallback<T>, theirs: unknown): RefCallback<T> {\n return (value: T) => {\n ours(value);\n if (typeof theirs === 'function') {\n (theirs as RefCallback<T>)(value);\n } else if (theirs && typeof theirs === 'object') {\n (theirs as { current: T | null }).current = value;\n }\n };\n}\n\nexport function Tip({ content, children }: TipProps) {\n const [open, setOpen] = useState(false);\n const [position, setPosition] = useState<Position | null>(null);\n const [rootClasses, setRootClasses] = useState('gemina-verification');\n const triggerRef = useRef<HTMLElement | null>(null);\n const tipRef = useRef<HTMLDivElement | null>(null);\n const id = useId();\n\n const empty = isEmpty(content);\n\n const show = useCallback(() => {\n if (empty) {\n return;\n }\n setRootClasses(rootClassesOf(triggerRef.current));\n setPosition(null); // re-measure; a stale position would flash in the wrong place\n setOpen(true);\n }, [empty]);\n\n const hide = useCallback(() => setOpen(false), []);\n\n // Measure AFTER paint but BEFORE the browser shows it: the tip renders\n // hidden until it has a position, so it never flashes at the origin.\n useLayoutEffect(() => {\n if (!open) {\n return;\n }\n const trigger = triggerRef.current;\n const tip = tipRef.current;\n if (!trigger || !tip) {\n return;\n }\n const anchor = trigger.getBoundingClientRect();\n const bubble = tip.getBoundingClientRect();\n const viewportWidth = window.innerWidth || 0;\n const viewportHeight = window.innerHeight || 0;\n\n // Prefer above; flip below only when there is genuinely no room, so the\n // tip does not cover the control the pointer is already on.\n const fitsAbove = anchor.top - bubble.height - GAP >= MARGIN;\n const fitsBelow = anchor.bottom + bubble.height + GAP <= viewportHeight - MARGIN;\n const top = fitsAbove || !fitsBelow\n ? anchor.top - bubble.height - GAP\n : anchor.bottom + GAP;\n\n // Centre on the trigger, then clamp so a tip near either edge stays whole.\n const centred = anchor.left + anchor.width / 2 - bubble.width / 2;\n const rightLimit = Math.max(MARGIN, viewportWidth - bubble.width - MARGIN);\n const left = Math.min(Math.max(centred, MARGIN), rightLimit);\n\n setPosition({ top: Math.max(top, MARGIN), left });\n }, [open, content]);\n\n // Escape dismisses the annotation without disturbing focus; scroll closes\n // because a fixed tip would otherwise drift away from its trigger.\n useEffect(() => {\n if (!open) {\n return;\n }\n const onKeyDown = (event: KeyboardEvent) => {\n if (event.key === 'Escape') {\n hide();\n }\n };\n const onScrollOrResize = () => hide();\n document.addEventListener('keydown', onKeyDown);\n // Capture phase: scrolls inside the host's overflow container do not\n // bubble to document, and that container is the common case here.\n document.addEventListener('scroll', onScrollOrResize, true);\n window.addEventListener('resize', onScrollOrResize);\n return () => {\n document.removeEventListener('keydown', onKeyDown);\n document.removeEventListener('scroll', onScrollOrResize, true);\n window.removeEventListener('resize', onScrollOrResize);\n };\n }, [open, hide]);\n\n if (!isValidElement(children)) {\n return children;\n }\n\n const childProps = children.props as Record<string, unknown>;\n const call = (name: string, event: unknown) => {\n const handler = childProps[name];\n if (typeof handler === 'function') {\n (handler as (arg: unknown) => void)(event);\n }\n };\n\n const trigger = cloneElement(children, {\n ref: mergeRefs<HTMLElement>((node) => {\n triggerRef.current = node;\n }, (children as unknown as { ref?: unknown }).ref),\n // The tip is a DESCRIPTION. `aria-label` stays untouched — it already\n // carries the reason into the accessible NAME, and duplicating it here\n // would have a screen reader announce it twice.\n 'aria-describedby': open && !empty ? id : undefined,\n onMouseEnter: (event: unknown) => { call('onMouseEnter', event); show(); },\n onMouseLeave: (event: unknown) => { call('onMouseLeave', event); hide(); },\n onFocus: (event: unknown) => { call('onFocus', event); show(); },\n onBlur: (event: unknown) => { call('onBlur', event); hide(); },\n } as Record<string, unknown>);\n\n const canPortal = typeof document !== 'undefined' && document.body;\n\n return (\n <>\n {trigger}\n {open && !empty && canPortal\n ? createPortal(\n <div className={rootClasses}>\n <div\n ref={tipRef}\n id={id}\n role=\"tooltip\"\n className=\"gemina-verification__tip\"\n style={{\n top: position ? `${position.top}px` : '0px',\n left: position ? `${position.left}px` : '0px',\n visibility: position ? 'visible' : 'hidden',\n }}\n >\n {content}\n </div>\n </div>,\n document.body,\n )\n : null}\n </>\n );\n}\n","/**\n * Internal document viewer for <GeminaVerification> — image canvas with a\n * zoom/rotate toolbar. Port of the console's ZoomableImageViewer skeleton\n * (gemina-console/src/components/viewers/ZoomableImageViewer.tsx): same\n * state/refs/effects shape, with the gesture/travel transform math delegated\n * to `viewer-math.ts` (the magnifier's presentation math stays local, exactly\n * as inline as the console's) and all styling on the Task 6\n * `.gemina-verification__*` classes. Tasks 8+9 add wheel zoom, mouse pan, the\n * double-click fit/100% toggle, and touch pan + pinch zoom; Task 10 adds\n * coordinate overlays, the flash-zoom travel animation, and the image-expiry\n * hook; Task 11 adds the magnifier loupe.\n *\n * Coordinate spaces: the console's zoomAtPoint takes clientX/Y and subtracts\n * the canvas rect INSIDE itself; the elements zoomAtPoint (viewer-math.ts) is\n * container-relative, so every DOM call site converts via\n * `zoomAtClientPoint` (Task 7 review carry-forward — a verbatim port anchors\n * wrong in any scrolled/offset layout).\n *\n * SSR-safe: no `window`/`document` access at import time; `ResizeObserver`\n * is only touched inside an effect (with a one-shot measure fallback).\n */\nimport { useCallback, useEffect, useLayoutEffect, useRef, useState } from 'react';\nimport type * as React from 'react';\nimport {\n centeredTranslation,\n clampScale,\n easeOutCubic,\n fitScaleFor,\n flashZoomTarget,\n zoomAtPoint,\n} from './viewer-math';\nimport type { Size, Transform } from './viewer-math';\nimport { Tip } from './tip';\n\n/** Axis-aligned detection region in relative image coordinates (0–1). */\nexport interface RelativeRect {\n points: [number, number][];\n}\n\nexport interface VerificationViewerProps {\n src: string;\n alt?: string;\n relativeRects?: RelativeRect[];\n flashRects?: RelativeRect[] | null;\n onFlashComplete?: () => void;\n /** Fired when the <img> errors AFTER at least one successful load (URL expiry). */\n onImageExpired?: () => void;\n}\n\n// --- Icons ------------------------------------------------------------------\n// One hand-drawn family: 16×16 grid, 1.5px stroke, round caps/joins, painted\n// with currentColor so the toolbar's normal/active colors flow through. The\n// only fills are the two dots of the 1:1 colon. Each icon stays ≤ 6 segments.\n\nfunction IconBase({ children }: { children: React.ReactNode }): React.JSX.Element {\n return (\n <svg\n width=\"16\"\n height=\"16\"\n viewBox=\"0 0 16 16\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth=\"1.5\"\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n aria-hidden=\"true\"\n focusable=\"false\"\n >\n {children}\n </svg>\n );\n}\n\n/** Shared magnifying-glass body (lens + handle) for the zoom/magnifier trio. */\nfunction GlassBody(): React.JSX.Element {\n return (\n <>\n <circle cx=\"6.75\" cy=\"6.75\" r=\"4.25\" />\n <line x1=\"9.9\" y1=\"9.9\" x2=\"13.5\" y2=\"13.5\" />\n </>\n );\n}\n\nexport function IconZoomIn(): React.JSX.Element {\n return (\n <IconBase>\n <GlassBody />\n <line x1=\"4.9\" y1=\"6.75\" x2=\"8.6\" y2=\"6.75\" />\n <line x1=\"6.75\" y1=\"4.9\" x2=\"6.75\" y2=\"8.6\" />\n </IconBase>\n );\n}\n\nexport function IconZoomOut(): React.JSX.Element {\n return (\n <IconBase>\n <GlassBody />\n <line x1=\"4.9\" y1=\"6.75\" x2=\"8.6\" y2=\"6.75\" />\n </IconBase>\n );\n}\n\nexport function IconMagnifier(): React.JSX.Element {\n return (\n <IconBase>\n <GlassBody />\n </IconBase>\n );\n}\n\n/** \"1:1\" drawn as numeral strokes — actual pixel size. */\nexport function IconActualSize(): React.JSX.Element {\n return (\n <IconBase>\n <polyline points=\"2.8 6.2 4 5 4 11\" />\n <polyline points=\"10.8 6.2 12 5 12 11\" />\n <circle cx=\"8\" cy=\"6.75\" r=\"0.8\" fill=\"currentColor\" stroke=\"none\" />\n <circle cx=\"8\" cy=\"9.25\" r=\"0.8\" fill=\"currentColor\" stroke=\"none\" />\n </IconBase>\n );\n}\n\n/** Two arrows collapsing inward — fit to screen. */\nexport function IconFit(): React.JSX.Element {\n return (\n <IconBase>\n <line x1=\"13.8\" y1=\"2.2\" x2=\"9.6\" y2=\"6.4\" />\n <polyline points=\"9.6 3.9 9.6 6.4 12.1 6.4\" />\n <line x1=\"2.2\" y1=\"13.8\" x2=\"6.4\" y2=\"9.6\" />\n <polyline points=\"6.4 12.1 6.4 9.6 3.9 9.6\" />\n </IconBase>\n );\n}\n\n/** Clockwise circular arrow. */\nexport function IconRotate(): React.JSX.Element {\n return (\n <IconBase>\n <path d=\"M11.83 4.79A5 5 0 1 1 8 3\" />\n <polyline points=\"6 1.7 8 3 6 4.3\" />\n </IconBase>\n );\n}\n\n/** Dashed square — detection overlay regions. */\nexport function IconOverlay(): React.JSX.Element {\n return (\n <IconBase>\n <rect x=\"2.75\" y=\"2.75\" width=\"10.5\" height=\"10.5\" rx=\"1.5\" strokeDasharray=\"3 2.2\" />\n </IconBase>\n );\n}\n\n/** Eye — used by the form's field-peek buttons (Task 12+). */\nexport function IconEye(): React.JSX.Element {\n return (\n <IconBase>\n <path d=\"M1.5 8s2.4-4.5 6.5-4.5S14.5 8 14.5 8s-2.4 4.5-6.5 4.5S1.5 8 1.5 8z\" />\n <circle cx=\"8\" cy=\"8\" r=\"2.1\" />\n </IconBase>\n );\n}\n\n// --- Toolbar ----------------------------------------------------------------\n\ninterface ToolbarButtonProps {\n label: string;\n onClick: () => void;\n disabled?: boolean;\n /** aria-pressed toggle button (overlay toggle). */\n pressed?: boolean;\n /** role=\"switch\" + aria-checked (magnifier). */\n checked?: boolean;\n children: React.ReactNode;\n}\n\nfunction ToolbarButton({\n label,\n onClick,\n disabled,\n pressed,\n checked,\n children,\n}: ToolbarButtonProps): React.JSX.Element {\n const active = (pressed ?? checked) === true;\n // Icon-only controls: the label is the ONLY thing naming them, so it needs a\n // sighted channel as well as the accessible name.\n return (\n <Tip content={label}>\n <button\n type=\"button\"\n className={\n active\n ? 'gemina-verification__toolbar-btn gemina-verification__toolbar-btn--active'\n : 'gemina-verification__toolbar-btn'\n }\n aria-label={label}\n role={checked === undefined ? undefined : 'switch'}\n aria-checked={checked}\n aria-pressed={pressed}\n disabled={disabled}\n onClick={onClick}\n >\n {children}\n </button>\n </Tip>\n );\n}\n\n// --- Viewer -----------------------------------------------------------------\n\nconst ZOOM_STEP = 1.2;\nconst IDENTITY: Transform = { scale: 1, tx: 0, ty: 0 };\n\n// Console flash constants (ZoomableImageViewer ~56-57): the rect fades over\n// 1500ms while the transform travels for its first 350ms.\nconst FLASH_DURATION = 1500; // ms\nconst ZOOM_ANIMATION_DURATION = 350; // ms - smooth but fast travel animation\n/** Reduced motion: no travel, no fade — jump to the target and hold the rect\n * at full opacity for a beat long enough to register, then complete. */\nconst REDUCED_MOTION_FLASH_MS = 800;\n\n/** Console's minimum visible rect size, as a ratio of the natural dimension\n * (~750): hairline detection boxes stay clickable-eye-visible. */\nconst MIN_SIZE_RATIO = 0.008;\n\n// Console magnifier constants (ZoomableImageViewer ~59-60).\nconst MAG_RADIUS = 150; // px — loupe radius (console: 140-160px)\nconst MAG_ZOOM = 2.5; // magnification applied on top of the current scale\n// Must equal the loupe's ring width in styles.ts (`.gemina-verification__\n// magnifier { border: 2px }`). The inner img is absolutely positioned, so its\n// containing block is the loupe's PADDING box — inset by exactly this much —\n// while the centring maths is expressed against the border box. Without the\n// correction the loupe shows a point (2, 2) px off its own centre, everywhere,\n// including over the image. Pinned by a test that reads the width back out of\n// the stylesheet, so restyling the ring cannot silently reintroduce the skew.\nconst MAG_BORDER = 2;\n\n/** Rect geometry in image pixel space — the overlays render INSIDE the\n * transform layer, so left/top/width/height are natural-size pixels and the\n * layer's scale/rotate carries them (console ~742-756). Returns null for\n * degenerate rects (a single point, or no points at all). */\nfunction rectGeometry(\n rect: RelativeRect,\n natural: Size,\n): { left: number; top: number; width: number; height: number } | null {\n const xs = rect.points.map((point) => point[0]);\n const ys = rect.points.map((point) => point[1]);\n const minX = Math.min(...xs);\n const minY = Math.min(...ys);\n const rawWidthRatio = Math.max(0, Math.max(...xs) - minX);\n const rawHeightRatio = Math.max(0, Math.max(...ys) - minY);\n if (rawWidthRatio <= 0 && rawHeightRatio <= 0) return null;\n return {\n left: minX * natural.w,\n top: minY * natural.h,\n width: Math.max(rawWidthRatio, MIN_SIZE_RATIO) * natural.w,\n height: Math.max(rawHeightRatio, MIN_SIZE_RATIO) * natural.h,\n };\n}\n\nexport function VerificationViewer(props: VerificationViewerProps): React.JSX.Element {\n const { src, alt, relativeRects, flashRects, onFlashComplete, onImageExpired } = props;\n\n const canvasRef = useRef<HTMLDivElement | null>(null);\n const imgRef = useRef<HTMLImageElement | null>(null);\n\n const [natural, setNatural] = useState<Size | null>(null);\n const [container, setContainer] = useState<Size>({ w: 0, h: 0 });\n const [transform, setTransform] = useState<Transform>(IDENTITY);\n const [rotation, setRotation] = useState(0); // degrees, multiples of 90\n\n const [showRects, setShowRects] = useState(false);\n const [magnifierOn, setMagnifierOn] = useState(false);\n\n // Loupe pointer state (console ~37-38): showMag flips on canvas\n // mousemove/mouseleave, mousePos is container-relative. Both track on EVERY\n // move regardless of the switch — console parity — so toggling the switch\n // with the pointer resting over the canvas (keyboard toggle) shows the\n // loupe at the right spot. The per-move re-render is the console's own\n // accepted cost; the loupe subtree is tiny.\n const [showMag, setShowMag] = useState(false);\n const [mousePos, setMousePos] = useState<{ x: number; y: number }>({ x: 0, y: 0 });\n // Client coordinates are the stable source while an ancestor scrolls. A\n // canvas-relative point goes stale as soon as the host modal moves beneath\n // a stationary pointer, which made the loupe sample a visibly different\n // spot from the one being hovered.\n const lastMouseClientRef = useRef<{ x: number; y: number } | null>(null);\n\n const [isPanning, setIsPanning] = useState(false);\n const panStart = useRef<{ x: number; y: number; tx: number; ty: number } | null>(null);\n\n // Flash animation state (console ~43-57).\n const [flashOpacity, setFlashOpacity] = useState(0);\n const [activeFlashRects, setActiveFlashRects] = useState<RelativeRect[] | null>(null);\n const travelRafRef = useRef<number | null>(null);\n const fadeRafRef = useRef<number | null>(null);\n const reducedFlashTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);\n\n // Render-synced mirror of the transform (console's scaleRef/txRef/tyRef):\n // the travel animation reads its from-values here instead of closing over\n // state inside the rAF loop (review carry-forward).\n const transformRef = useRef(transform);\n transformRef.current = transform;\n\n // Latest-value ref so an inline onFlashComplete prop cannot restart the\n // flash effect on every parent render.\n const onFlashCompleteRef = useRef(onFlashComplete);\n onFlashCompleteRef.current = onFlashComplete;\n\n // True once the CURRENT src has loaded successfully — the expiry gate.\n const hasLoadedRef = useRef(false);\n\n // Measure the canvas (console lines ~124-133), with a one-shot fallback for\n // environments without ResizeObserver. contentRect on purpose (unlike the\n // root's stacked observer, which reads border-box): the fit/zoom math needs\n // the CONTENT area the image is positioned within.\n useLayoutEffect(() => {\n const el = canvasRef.current;\n if (!el) return;\n if (typeof ResizeObserver === 'undefined') {\n const rect = el.getBoundingClientRect();\n setContainer({ w: rect.width, h: rect.height });\n return;\n }\n const ro = new ResizeObserver((entries) => {\n const cr = entries[0]?.contentRect;\n if (cr) setContainer({ w: cr.width, h: cr.height });\n });\n ro.observe(el);\n return () => ro.disconnect();\n }, []);\n\n // Natural image size (console ~136-139), with an identity-preserving setter\n // (review carry-forward): a re-minted URL for the SAME image (the\n // onImageExpired flow) reports identical dimensions, and returning the prev\n // object keeps the fit effect from re-running and resetting the user's\n // zoom/pan mid-review.\n const handleImgLoad = useCallback(() => {\n const img = imgRef.current;\n if (!img) return;\n hasLoadedRef.current = true;\n const w = img.naturalWidth;\n const h = img.naturalHeight;\n setNatural((prev) => (prev && prev.w === w && prev.h === h ? prev : { w, h }));\n }, []);\n\n // Expiry hook — replaces the console's fallbackSrc error handler (~374-378).\n // The loaded flag resets on every src change: a NEW src that fails before it\n // ever loads is a broken URL, not an expired one, and firing onImageExpired\n // there would re-mint forever in a loop. It also disarms when it fires, so\n // one load reports at most one expiry (the re-minted load re-arms it).\n useEffect(() => {\n hasLoadedRef.current = false;\n }, [src]);\n\n const handleImgError = useCallback(() => {\n if (!hasLoadedRef.current) return;\n hasLoadedRef.current = false;\n onImageExpired?.();\n }, [onImageExpired]);\n\n /** The console's `fitScale` memo, including its degenerate-size guard. */\n const currentFitScale = useCallback((): number => {\n if (!natural || !container.w || !container.h) return 1;\n return fitScaleFor(natural, container, rotation);\n }, [natural, container, rotation]);\n\n // Fit + center on first load, and re-fit on container/rotation changes\n // (console ~186-196).\n useEffect(() => {\n if (!natural || !container.w || !container.h) return;\n const fit = fitScaleFor(natural, container, rotation);\n const { tx, ty } = centeredTranslation(natural, container, fit, rotation);\n setTransform((prev) =>\n Math.abs(prev.scale - fit) < 0.0001 && prev.tx === tx && prev.ty === ty\n ? prev\n : { scale: fit, tx, ty },\n );\n }, [natural, container, rotation]);\n\n // DELIBERATE IMPROVEMENT over the console (reviewer-endorsed): the console\n // never cancels the flash travel on user input, so its rAF loop keeps\n // stomping wheel/drag transforms for the rest of its 350ms window. Here any\n // canvas gesture (wheel, mousedown, touchstart, dblclick) AND any toolbar\n // zoom (zoom in/out, fit, 100%) stops the travel — the user just took the\n // wheel. Only the transform drive stops: the flash rect keeps fading, and\n // the fade loop still fires onFlashComplete.\n const cancelFlashTravel = useCallback(() => {\n if (travelRafRef.current !== null) {\n cancelAnimationFrame(travelRafRef.current);\n travelRafRef.current = null;\n }\n }, []);\n\n // Toolbar handlers (console ~251-278). zoomAtPoint returns the SAME object\n // on clamped no-ops, so the updater form bails out of re-rendering.\n const zoomBy = useCallback(\n (factor: number) => {\n const node = canvasRef.current;\n if (!node || !natural) return;\n cancelFlashTravel();\n const rect = node.getBoundingClientRect();\n const fit = currentFitScale();\n setTransform((prev) =>\n zoomAtPoint(prev, factor, rect.width / 2, rect.height / 2, rotation, fit),\n );\n },\n [natural, rotation, currentFitScale, cancelFlashTravel],\n );\n\n const handleZoomIn = useCallback(() => zoomBy(ZOOM_STEP), [zoomBy]);\n const handleZoomOut = useCallback(() => zoomBy(1 / ZOOM_STEP), [zoomBy]);\n\n /** Client -> container-relative conversion lives HERE, at the call sites\n * (wheel, double-click; pinch joins in Task 9) — viewer-math's zoomAtPoint\n * is container-relative by contract. */\n const zoomAtClientPoint = useCallback(\n (factor: number, clientX: number, clientY: number) => {\n const node = canvasRef.current;\n if (!node || !natural) return;\n const rect = node.getBoundingClientRect();\n const fit = currentFitScale();\n setTransform((prev) =>\n zoomAtPoint(prev, factor, clientX - rect.left, clientY - rect.top, rotation, fit),\n );\n },\n [natural, rotation, currentFitScale],\n );\n\n // Wheel zoom (console ~232-249): React's onWheel is passive, so attach a\n // NON-PASSIVE native listener — preventDefault must keep the page from\n // scrolling under the zoom.\n const handleWheel = useCallback(\n (event: WheelEvent) => {\n event.preventDefault();\n event.stopPropagation();\n cancelFlashTravel();\n const factor = event.deltaY > 0 ? 0.92 : 1.08; // console's wheel constants\n zoomAtClientPoint(factor, event.clientX, event.clientY);\n },\n [zoomAtClientPoint, cancelFlashTravel],\n );\n\n useEffect(() => {\n const node = canvasRef.current;\n if (!node) return;\n const listener = (event: WheelEvent) => handleWheel(event);\n node.addEventListener('wheel', listener, { passive: false });\n return () => node.removeEventListener('wheel', listener);\n }, [handleWheel]);\n\n // Beyond fit there is something to pan; at fit the drag is inert and the\n // cursor honestly says zoom-in (console ~296-322 policy). Shared by the\n // mousedown gate and the cursor state below.\n const atFitScale = transform.scale <= currentFitScale() + 0.001;\n\n // Mouse pan. Deliberate deviation from the console: move/up listen on\n // `document` while panning so the drag survives leaving the canvas instead\n // of dropping at the edge.\n const handleMouseDown = useCallback(\n (e: React.MouseEvent<HTMLDivElement>) => {\n // Any press grabs the canvas — stop the flash travel before the gates.\n cancelFlashTravel();\n // Primary button only: with document-level listeners a right-click's\n // context menu would swallow the mouseup and leave the pan stuck.\n // (Tap-synthesized compat mouse events report button 0 and pass — fine;\n // Task 9's touch handlers own that path.)\n if (e.button !== 0) return;\n if (atFitScale) return;\n e.preventDefault(); // document-level drag: don't start selections outside the widget\n panStart.current = { x: e.clientX, y: e.clientY, tx: transform.tx, ty: transform.ty };\n setIsPanning(true);\n },\n [atFitScale, transform.tx, transform.ty, cancelFlashTravel],\n );\n\n useEffect(() => {\n if (!isPanning) return;\n const onMove = (e: MouseEvent) => {\n const start = panStart.current;\n if (!start) return;\n const dx = e.clientX - start.x;\n const dy = e.clientY - start.y;\n setTransform((prev) => ({ scale: prev.scale, tx: start.tx + dx, ty: start.ty + dy }));\n };\n const onUp = () => {\n panStart.current = null;\n setIsPanning(false);\n };\n document.addEventListener('mousemove', onMove);\n document.addEventListener('mouseup', onUp);\n // Cleanup runs on mouseup (isPanning flips false) AND on unmount mid-pan.\n return () => {\n document.removeEventListener('mousemove', onMove);\n document.removeEventListener('mouseup', onUp);\n };\n }, [isPanning]);\n\n // Touch: one-finger pan (only beyond fit — the mousedown gate's twin) and\n // two-finger pinch zoom. Verbatim console port (~324-369) except the pinch\n // factor routes through zoomAtClientPoint — client → container conversion\n // plus the shared fit-floor clamp — instead of any local math.\n // `touch-action: none` on __canvas (styles.ts) hands these gestures to us,\n // so React's passive onTouch* handlers suffice; no preventDefault needed.\n // Gesture state lives in a ref: nothing re-renders per touch-move except\n // the transform update itself, and isPanning/data-cursor stay mouse-only\n // (a touch screen shows no cursor).\n const touchState = useRef<\n | { mode: 'pan'; x: number; y: number; tx: number; ty: number }\n | { mode: 'pinch'; dist: number }\n | null\n >(null);\n\n const handleTouchStart = useCallback(\n (e: React.TouchEvent<HTMLDivElement>) => {\n // A finger on the canvas grabs it — stop the flash travel.\n cancelFlashTravel();\n // Length checks don't narrow TouchList indexing under\n // noUncheckedIndexedAccess, so a/b/their truthiness carry the guard.\n const a = e.touches[0];\n const b = e.touches[1];\n if (e.touches.length === 2 && a && b) {\n // Only the start distance seeds a pinch — no midpoint is stored,\n // because every move re-anchors at the CURRENT midpoint (console\n // policy). A second finger landing mid-pan arrives here too, so 1→2\n // hands the gesture off to pinch automatically.\n touchState.current = {\n mode: 'pinch',\n dist: Math.hypot(a.clientX - b.clientX, a.clientY - b.clientY),\n };\n } else if (e.touches.length === 1 && a && !atFitScale) {\n touchState.current = { mode: 'pan', x: a.clientX, y: a.clientY, tx: transform.tx, ty: transform.ty };\n } else {\n touchState.current = null;\n }\n },\n [atFitScale, transform.tx, transform.ty, cancelFlashTravel],\n );\n\n const handleTouchMove = useCallback(\n (e: React.TouchEvent<HTMLDivElement>) => {\n const state = touchState.current;\n if (!state) return;\n if (state.mode === 'pinch' && e.touches.length === 2) {\n const a = e.touches[0];\n const b = e.touches[1];\n if (!a || !b) return;\n const dist = Math.hypot(a.clientX - b.clientX, a.clientY - b.clientY);\n if (state.dist > 0) {\n // Per-move ratio, re-seeded below: each factor is relative to the\n // LAST move, and the updater-form zoomAtPoint composes it onto the\n // accumulated transform, so React batching can't double-apply a\n // step. Two-finger travel without spread is factor 1 — zoomAtPoint's\n // same-object bail-out makes it a no-op (console policy: a pinch\n // never pans; the image only shifts through the moving anchor while\n // the scale is changing).\n zoomAtClientPoint(dist / state.dist, (a.clientX + b.clientX) / 2, (a.clientY + b.clientY) / 2);\n }\n state.dist = dist;\n } else if (state.mode === 'pan' && e.touches.length === 1) {\n // START-RELATIVE deltas (the established pan pattern) — never\n // accumulated per event, so a dropped move can't skew the drag.\n const t = e.touches[0];\n if (!t) return;\n setTransform((prev) => ({\n scale: prev.scale,\n tx: state.tx + (t.clientX - state.x),\n ty: state.ty + (t.clientY - state.y),\n }));\n }\n },\n [zoomAtClientPoint],\n );\n\n // 2→1 deliberately leaves an INERT pinch until every finger lifts\n // (console-faithful): the remaining finger matches neither move branch, so\n // nothing jumps; the next touchstart begins a fresh gesture.\n const handleTouchEnd = useCallback((e: React.TouchEvent<HTMLDivElement>) => {\n if (e.touches.length === 0) touchState.current = null;\n }, []);\n\n // Loupe pointer tracking (console ~305-308, ~695-703), container-relative\n // like every other pointer path (Task 7 carry-forward). Show on any canvas\n // mousemove, hide only on mouseleave — console policy verbatim. On a touch\n // device a tap synthesizes compat mousemoves that PARK the loupe at the tap\n // point while the switch is on; the console does nothing about that either\n // (its loupe is a desktop pattern), and the parked loupe clears on the next\n // compat mouseleave. Pan is untouched: it lives on document-level listeners.\n const syncMagnifierToClientPoint = useCallback((\n clientX: number,\n clientY: number,\n assumeInside = false,\n ) => {\n const rect = canvasRef.current?.getBoundingClientRect();\n if (!rect) return;\n const x = clientX - rect.left;\n const y = clientY - rect.top;\n // A mousemove dispatched by the canvas is authoritative even in DOMs\n // without layout (and during a resize frame whose rect is momentarily\n // zero). Scroll/resize resyncs use the real bounds so a stationary pointer\n // that the canvas moved away from hides the lens.\n const inside = assumeInside\n || (x >= 0 && y >= 0 && x <= rect.width && y <= rect.height);\n setShowMag(inside);\n if (inside) {\n setMousePos({ x, y });\n }\n }, []);\n\n const handleCanvasMouseMove = useCallback((e: React.MouseEvent<HTMLDivElement>) => {\n lastMouseClientRef.current = { x: e.clientX, y: e.clientY };\n syncMagnifierToClientPoint(e.clientX, e.clientY, true);\n }, [syncMagnifierToClientPoint]);\n\n const handleCanvasMouseLeave = useCallback(() => {\n lastMouseClientRef.current = null;\n setShowMag(false);\n }, []);\n\n // Scroll events do not reliably dispatch mousemove/mouseleave. Re-project\n // the last client point whenever ANY scroll container moves (capture=true),\n // and on viewport resize, so both the lens and its sampled point stay under\n // the real pointer inside host-scrolled modals.\n useEffect(() => {\n if (!magnifierOn || !showMag) return;\n const sync = () => {\n const point = lastMouseClientRef.current;\n if (point) syncMagnifierToClientPoint(point.x, point.y);\n };\n document.addEventListener('scroll', sync, true);\n window.addEventListener('resize', sync);\n return () => {\n document.removeEventListener('scroll', sync, true);\n window.removeEventListener('resize', sync);\n };\n }, [magnifierOn, showMag, syncMagnifierToClientPoint]);\n\n // Double-click toggle (console ~281-294): near fit -> 100% anchored at the\n // click point; otherwise back to centered fit.\n const handleDoubleClick = useCallback(\n (e: React.MouseEvent<HTMLDivElement>) => {\n cancelFlashTravel();\n if (!natural) return;\n const fit = currentFitScale();\n const nearFit = Math.abs(transform.scale - fit) < 0.001;\n if (nearFit) {\n const target = clampScale(1, fit);\n zoomAtClientPoint(target / transform.scale, e.clientX, e.clientY);\n } else {\n setTransform({ scale: fit, ...centeredTranslation(natural, container, fit, rotation) });\n }\n },\n [natural, container, rotation, transform.scale, currentFitScale, zoomAtClientPoint, cancelFlashTravel],\n );\n\n const handleFit = useCallback(() => {\n if (!natural) return;\n cancelFlashTravel();\n const fit = currentFitScale();\n setTransform({ scale: fit, ...centeredTranslation(natural, container, fit, rotation) });\n }, [natural, container, rotation, currentFitScale, cancelFlashTravel]);\n\n const handleActualSize = useCallback(() => {\n if (!natural) return;\n cancelFlashTravel();\n const target = clampScale(1, currentFitScale());\n setTransform({ scale: target, ...centeredTranslation(natural, container, target, rotation) });\n }, [natural, container, rotation, currentFitScale, cancelFlashTravel]);\n\n // Deliberately does NOT cancelFlashTravel: `rotation` is a dep of the flash\n // effect, so a rotate mid-travel re-runs it — cleanup cancels both loops,\n // then the effect recomputes flashZoomTarget for the NEW rotation and\n // restarts travel (and fade, from full opacity) from the current transform.\n // The rect therefore lands rotation-correct instead of coasting toward a\n // stale pre-rotation target (pinned by the rotate-mid-travel test).\n const handleRotate = useCallback(() => {\n setRotation((r) => (r + 90) % 360);\n }, []);\n\n // Overlay toggle only means something while rects exist (console ~450-456).\n const hasRects = relativeRects !== undefined && relativeRects.length > 0;\n useEffect(() => {\n if (!hasRects) setShowRects(false);\n }, [hasRects]);\n\n // Flash animation + zoom-to-rect travel (console ~458-581). Two parallel\n // drives: the transform travels to flashZoomTarget over 350ms (easeOutCubic,\n // from-values read off transformRef), while the flash rect fades 1 - p²\n // over 1500ms. The FADE loop owns completion: it clears the rects and fires\n // onFlashComplete — so a gesture-canceled travel never swallows the\n // callback. Cleanup cancels BOTH loops, which covers unmount mid-flash and\n // makes a re-trigger (rapid eye-clicks re-running this effect) a clean\n // restart; the console leaked its fade loop here and only canceled the\n // travel — fixed deliberately.\n useEffect(() => {\n if (!flashRects || flashRects.length === 0 || !natural || !container.w || !container.h) {\n // A parent nulling flashRects mid-flash declares the flash over: clear\n // the display (cleanup already canceled both loops) WITHOUT firing\n // onFlashComplete — the parent initiated this, echoing back would loop.\n // (The console coasted here on its leaked fade loop to clear the rect;\n // with the leak fixed, the clear must be explicit.) The prev-identity\n // bail keeps the common null→null path render-free.\n setActiveFlashRects((prev) => (prev === null ? prev : null));\n setFlashOpacity(0);\n return;\n }\n\n const fit = fitScaleFor(natural, container, rotation);\n const target = flashZoomTarget(flashRects, natural, container, rotation, fit);\n\n setActiveFlashRects(flashRects);\n setFlashOpacity(1);\n\n const prefersReduced =\n typeof window !== 'undefined' &&\n typeof window.matchMedia === 'function' &&\n window.matchMedia('(prefers-reduced-motion: reduce)').matches;\n\n if (prefersReduced) {\n // No travel, no fade: jump to the target and hold the rect long enough\n // to register, then complete. (The stylesheet's reduced-motion block is\n // the CSS backstop; this is the JS half.)\n setTransform(target);\n reducedFlashTimeoutRef.current = setTimeout(() => {\n reducedFlashTimeoutRef.current = null;\n setActiveFlashRects(null);\n setFlashOpacity(0);\n onFlashCompleteRef.current?.();\n }, REDUCED_MOTION_FLASH_MS);\n return () => {\n if (reducedFlashTimeoutRef.current !== null) {\n clearTimeout(reducedFlashTimeoutRef.current);\n reducedFlashTimeoutRef.current = null;\n }\n };\n }\n\n // Travel: capture the from-values ONCE from the render-synced ref (review\n // carry-forward — no state reads inside the rAF loop).\n const from = transformRef.current;\n const zoomStartTime = Date.now();\n const animateZoom = () => {\n const progress = Math.min((Date.now() - zoomStartTime) / ZOOM_ANIMATION_DURATION, 1);\n const eased = easeOutCubic(progress);\n setTransform({\n scale: from.scale + (target.scale - from.scale) * eased,\n tx: from.tx + (target.tx - from.tx) * eased,\n ty: from.ty + (target.ty - from.ty) * eased,\n });\n travelRafRef.current = progress < 1 ? requestAnimationFrame(animateZoom) : null;\n };\n travelRafRef.current = requestAnimationFrame(animateZoom);\n\n // Flash fade, in parallel: 1 - p² over the 1500ms window, then complete.\n const flashStartTime = Date.now();\n const animateFlash = () => {\n const progress = Math.min((Date.now() - flashStartTime) / FLASH_DURATION, 1);\n setFlashOpacity(1 - progress * progress);\n if (progress < 1) {\n fadeRafRef.current = requestAnimationFrame(animateFlash);\n } else {\n fadeRafRef.current = null;\n setActiveFlashRects(null);\n setFlashOpacity(0);\n onFlashCompleteRef.current?.();\n }\n };\n fadeRafRef.current = requestAnimationFrame(animateFlash);\n\n return () => {\n cancelFlashTravel();\n if (fadeRafRef.current !== null) {\n cancelAnimationFrame(fadeRafRef.current);\n fadeRafRef.current = null;\n }\n };\n // container is identity-replaced per resize; depend on its values (like\n // the console) so a same-size measurement can't restart a live flash.\n }, [flashRects, natural, container.w, container.h, rotation, cancelFlashTravel]);\n\n // Cursor is the promise of what a drag will do (console ~371-372): zoom-in\n // while the whole page fits (drag is inert; wheel/double-click zooms), grab\n // once zoomed beyond fit, grabbing mid-pan. CSS maps data-cursor to cursors.\n const cursorMode = atFitScale ? 'zoom-in' : isPanning ? 'grabbing' : 'grab';\n\n // Magnifier loupe (console ~380-431), rotation-aware: invert the current\n // transform to find the image point under the pointer, clamp it inside the\n // image, then re-project it at scale × MAG_ZOOM so that point lands at the\n // loupe's center. The inverse map mirrors zoomAtPoint's — inline here just\n // as it is in the console (presentation math, not gesture math). NOT\n // ported: the console's opacity-0 placeholder div for switch-on/pointer-away\n // (~432-448) — nothing visible ever animated on it, pure dead weight. The\n // inner img is bare (no onLoad/onError): wiring the expiry handler here\n // would double-fire onImageExpired for one dying URL.\n let magnifier: React.ReactNode = null;\n if (magnifierOn && showMag && natural && transform.scale > 0) {\n const rad = (rotation * Math.PI) / 180;\n const cosA = Math.cos(rad);\n const sinA = Math.sin(rad);\n const dx = mousePos.x - transform.tx;\n const dy = mousePos.y - transform.ty;\n const cxRaw = (cosA * dx + sinA * dy) / transform.scale;\n const cyRaw = (-sinA * dx + cosA * dy) / transform.scale;\n // Off-image, there is nothing under the pointer to magnify. This USED to\n // clamp the sampled point into [0, natural], which meant the loupe showed\n // the nearest edge of the document as confidently as if it were the spot\n // being pointed at — measured at 340 image px of error one pixel outside\n // the left edge, at fit scale. At fit the image is letterboxed, so that is\n // a large share of the canvas. Inclusive bounds: container x=125 maps to\n // image x=0, and a strict `<` would blink the loupe out along the whole\n // left edge of the document.\n const onImage = cxRaw >= 0 && cyRaw >= 0 && cxRaw <= natural.w && cyRaw <= natural.h;\n const zoomScale = transform.scale * MAG_ZOOM;\n const px = cxRaw * zoomScale;\n const py = cyRaw * zoomScale;\n const rotatedX = px * cosA - py * sinA;\n const rotatedY = px * sinA + py * cosA;\n // MAG_BORDER: the img is absolutely positioned, so it lands against the\n // loupe's PADDING box while this centring is expressed against the border\n // box. See the constant.\n const translateX = MAG_RADIUS - MAG_BORDER - rotatedX;\n const translateY = MAG_RADIUS - MAG_BORDER - rotatedY;\n if (onImage) {\n magnifier = (\n <div\n className=\"gemina-verification__magnifier\"\n style={{\n width: MAG_RADIUS * 2,\n height: MAG_RADIUS * 2,\n top: mousePos.y - MAG_RADIUS,\n left: mousePos.x - MAG_RADIUS,\n }}\n >\n <img\n src={src}\n alt=\"\"\n draggable={false}\n style={{\n position: 'absolute',\n width: natural.w,\n height: natural.h,\n transformOrigin: '0 0',\n transform: `translate(${translateX}px, ${translateY}px) rotate(${rotation}deg) scale(${zoomScale})`,\n }}\n />\n </div>\n );\n }\n }\n\n return (\n <div className=\"gemina-verification__viewer\">\n <div className=\"gemina-verification__toolbar\">\n <ToolbarButton label=\"Zoom out\" onClick={handleZoomOut}>\n <IconZoomOut />\n </ToolbarButton>\n <ToolbarButton label=\"Zoom in\" onClick={handleZoomIn}>\n <IconZoomIn />\n </ToolbarButton>\n <ToolbarButton label=\"Actual size (100%)\" onClick={handleActualSize}>\n <IconActualSize />\n </ToolbarButton>\n <ToolbarButton label=\"Fit to screen\" onClick={handleFit}>\n <IconFit />\n </ToolbarButton>\n <ToolbarButton label=\"Rotate 90 degrees\" onClick={handleRotate}>\n <IconRotate />\n </ToolbarButton>\n <ToolbarButton\n label=\"Toggle detection overlays\"\n pressed={showRects}\n disabled={!hasRects}\n onClick={() => setShowRects((prev) => !prev)}\n >\n <IconOverlay />\n </ToolbarButton>\n <ToolbarButton\n label=\"Magnifier\"\n checked={magnifierOn}\n onClick={() => setMagnifierOn((prev) => !prev)}\n >\n <IconMagnifier />\n </ToolbarButton>\n </div>\n\n <div\n ref={canvasRef}\n className=\"gemina-verification__canvas\"\n data-cursor={cursorMode}\n // One composite picture to AT: the inner <img>, overlay boxes, flash\n // and loupe are all facets of \"the document image\" — announcing each\n // separately would be noise, so the canvas is the labeled image and\n // everything inside is presentational. The host's `alt` prop names\n // THIS label (the inner img's alt is unread by AT here but kept for\n // non-AT contexts: broken-image text, save/copy affordances).\n role=\"img\"\n aria-label={alt ?? 'Document image'}\n onDoubleClick={handleDoubleClick}\n onMouseDown={handleMouseDown}\n onMouseMove={handleCanvasMouseMove}\n onMouseLeave={handleCanvasMouseLeave}\n onTouchStart={handleTouchStart}\n onTouchMove={handleTouchMove}\n onTouchEnd={handleTouchEnd}\n // The browser cancelling a gesture (edge swipe, notification shade)\n // must reset it exactly like a full lift — a stale touchState would\n // make the NEXT touch continue a dead pan/pinch.\n onTouchCancel={handleTouchEnd}\n >\n {/* Canvas geometry (not layout) — inline by design; CSS owns appearance. */}\n <div\n style={{\n position: 'absolute',\n left: transform.tx,\n top: transform.ty,\n transform: `rotate(${rotation}deg) scale(${transform.scale})`,\n transformOrigin: 'top left',\n willChange: 'transform,left,top',\n }}\n >\n <img\n ref={imgRef}\n src={src}\n alt={alt ?? 'Document'}\n draggable={false}\n onLoad={handleImgLoad}\n onError={handleImgError}\n />\n {/* Detection overlays (toggle-controlled, console ~742-792). Index\n keys are stable here: rect arrays are replaced wholesale and the\n boxes are stateless leaves. Geometry inline; appearance in CSS.\n aria-hidden per rect (badge included): the canvas is one labeled\n image to AT — the \"#N\" chips are visual decoration on it. */}\n {showRects &&\n natural &&\n relativeRects?.map((rect, idx) => {\n const geometry = rectGeometry(rect, natural);\n if (!geometry) return null;\n return (\n <div\n key={`rect-${idx}`}\n className=\"gemina-verification__rect\"\n style={geometry}\n aria-hidden=\"true\"\n >\n <span className=\"gemina-verification__rect-badge\">#{idx + 1}</span>\n </div>\n );\n })}\n {/* Flash overlay (temporary, independent of the toggle). Element-level\n opacity is equivalent to the console's per-channel alpha fade\n modulo overlapping-layer compositing — see the __flash-rect\n comment in styles.ts. aria-hidden: purely decorative highlight. */}\n {activeFlashRects &&\n natural &&\n activeFlashRects.map((rect, idx) => {\n const geometry = rectGeometry(rect, natural);\n if (!geometry) return null;\n return (\n <div\n key={`flash-rect-${idx}`}\n className=\"gemina-verification__flash-rect\"\n style={{ ...geometry, opacity: flashOpacity }}\n aria-hidden=\"true\"\n />\n );\n })}\n </div>\n {magnifier}\n </div>\n </div>\n );\n}\n","/**\n * Pure zoom/rotation math for the verification document viewer.\n *\n * Direct ports from the console's viewer\n * (gemina-console/src/components/viewers/ZoomableImageViewer.tsx):\n * fit scale (lines ~142-149), rotated bounding box (~152-172), centered\n * translation (~174-183), scale clamp + zoom-at-point (~198-230), flash-zoom\n * target (~459-509, math portion), easeOutCubic (~523). Bodies must stay\n * behavior-identical so the elements viewer renders pixel-identically to the\n * console's. No DOM, no React.\n */\n\nexport interface Size {\n w: number;\n h: number;\n}\n\nexport interface Transform {\n scale: number;\n tx: number;\n ty: number;\n}\n\n/** Scale that fits a (possibly rotated) natural size into a container.\n * rotationDeg is expected in multiples of 90; other angles fall back to the\n * unrotated box (matching the console). */\nexport function fitScaleFor(natural: Size, container: Size, rotationDeg: number): number {\n const rot = ((rotationDeg % 180) + 180) % 180;\n const w = rot === 90 ? natural.h : natural.w;\n const h = rot === 90 ? natural.w : natural.h;\n const s = Math.min(container.w / w, container.h / h);\n // The console's memo also early-returns 1 when the container has no size;\n // a zero container makes s = 0 here, so this guard yields the same 1.\n return isFinite(s) && s > 0 ? s : 1;\n}\n\n/** Rotated bounding box extents; minX/minY compensate rotation offsets.\n * rotationDeg is expected in multiples of 90; other angles fall back to the\n * unrotated box (matching the console). zoomAtPoint/flashZoomTarget use real\n * trig and work at any angle. */\nexport function rotatedBox(\n natural: Size,\n scale: number,\n rotationDeg: number,\n): { W: number; H: number; minX: number; minY: number } {\n const w0 = natural.w;\n const h0 = natural.h;\n const s = scale;\n const rot = ((rotationDeg % 360) + 360) % 360;\n switch (rot) {\n case 0:\n return { W: w0 * s, H: h0 * s, minX: 0, minY: 0 };\n case 90:\n return { W: h0 * s, H: w0 * s, minX: -h0 * s, minY: 0 };\n case 180:\n return { W: w0 * s, H: h0 * s, minX: -w0 * s, minY: -h0 * s };\n case 270:\n return { W: h0 * s, H: w0 * s, minX: 0, minY: -w0 * s };\n default:\n return { W: w0 * s, H: h0 * s, minX: 0, minY: 0 };\n }\n}\n\n/** Translation that centers the rotated image. */\nexport function centeredTranslation(\n natural: Size,\n container: Size,\n scale: number,\n rotationDeg: number,\n): { tx: number; ty: number } {\n const { W, H, minX, minY } = rotatedBox(natural, scale, rotationDeg);\n const nx = (container.w - W) / 2 - minX;\n const ny = (container.h - H) / 2 - minY;\n return { tx: nx, ty: ny };\n}\n\nexport function clampScale(s: number, fitScale: number, max = 8): number {\n return Math.max(fitScale, Math.min(max, s));\n}\n\n/** New transform after zooming by `factor` anchored at container point (px,py). */\nexport function zoomAtPoint(\n current: Transform,\n factor: number,\n px: number,\n py: number,\n rotationDeg: number,\n fitScale: number,\n): Transform {\n const { scale, tx, ty } = current;\n const newScale = clampScale(scale * factor, fitScale);\n if (newScale === scale) return current;\n\n const rad = (rotationDeg * Math.PI) / 180;\n const cosA = Math.cos(rad);\n const sinA = Math.sin(rad);\n\n const dx = px - tx;\n const dy = py - ty;\n const cx = (cosA * dx + sinA * dy) / scale;\n const cy = (-sinA * dx + cosA * dy) / scale;\n\n const ntx = px - (cosA * (newScale * cx) - sinA * (newScale * cy));\n const nty = py - (sinA * (newScale * cx) + cosA * (newScale * cy));\n\n return { scale: newScale, tx: ntx, ty: nty };\n}\n\n/** Target transform for the flash-zoom travel: center the rects' bbox at a\n * comfortable size (100px target, scale clamped to [fitScale, 1.8]). */\nexport function flashZoomTarget(\n rects: Array<{ points: [number, number][] }>,\n natural: Size,\n container: Size,\n rotationDeg: number,\n fitScale: number,\n): Transform {\n // Calculate bounding box of all flash rects (in relative coords 0-1)\n let minX = 1,\n minY = 1,\n maxX = 0,\n maxY = 0;\n for (const rect of rects) {\n for (const [px, py] of rect.points) {\n minX = Math.min(minX, px);\n minY = Math.min(minY, py);\n maxX = Math.max(maxX, px);\n maxY = Math.max(maxY, py);\n }\n }\n\n // Calculate center of the bounding box in image pixel coordinates\n const centerX = ((minX + maxX) / 2) * natural.w;\n const centerY = ((minY + maxY) / 2) * natural.h;\n const bboxWidth = (maxX - minX) * natural.w;\n const bboxHeight = (maxY - minY) * natural.h;\n\n // Calculate target zoom level from a FIXED baseline (not current zoom)\n // Goal: make the field a comfortable, consistent size on screen\n const rad = (rotationDeg * Math.PI) / 180;\n const cosA = Math.cos(rad);\n const sinA = Math.sin(rad);\n\n // Target: make the bbox render at approximately this size\n const TARGET_RENDERED_SIZE = 100; // pixels - comfortable reading size\n\n // Calculate scale needed to render bbox at target size\n // Use the larger dimension to determine scale (so it fits nicely)\n const largerDimension = Math.max(bboxWidth, bboxHeight);\n const scaleForTargetSize = largerDimension > 0 ? TARGET_RENDERED_SIZE / largerDimension : 1;\n\n // Clamp: at least fitScale (don't zoom out), at most 1.8x (reasonable max)\n const targetScale = Math.max(fitScale, Math.min(scaleForTargetSize, 1.8));\n\n // Calculate target position to center on the field\n const newScreenX = cosA * centerX * targetScale - sinA * centerY * targetScale;\n const newScreenY = sinA * centerX * targetScale + cosA * centerY * targetScale;\n const targetTx = container.w / 2 - newScreenX;\n const targetTy = container.h / 2 - newScreenY;\n\n return { scale: targetScale, tx: targetTx, ty: targetTy };\n}\n\n// Ease out cubic for smooth deceleration\nexport const easeOutCubic = (t: number): number => 1 - Math.pow(1 - t, 3);\n","import { VERSION } from '../version';\n\n// --- Styles -----------------------------------------------------------------\n// Hand-rolled, no UI deps. Everything is scoped under .gemina-verification and\n// driven by CSS custom properties so host apps can re-theme without touching\n// the DOM. The palette and rhythm deliberately match the chat widget\n// (chat.tsx) so both widgets read as one product when embedded side by side.\n//\n// Design intent: a focused reviewing tool. Document viewer on one pane, form\n// on the other; quiet neutral surfaces everywhere; the confidence dots are the\n// only saturated color in the form, and the overlay blue is reserved for the\n// document canvas. Values are set in tabular numerals so amounts line up with\n// the scanned document the reviewer is comparing them against.\n//\n// Layout uses logical properties exclusively (margin-inline-*, padding-inline,\n// border-block-*) so RTL works for free. Physical left/top appear only inside\n// the viewer canvas, where later tasks position geometry inline from JS —\n// that is geometry, not layout.\n\nconst DARK_VARS = `\n --gemina-verification-bg: #101418;\n --gemina-verification-fg: #e6e9ee;\n --gemina-verification-border: #2a323c;\n --gemina-verification-accent: #4c8dff;\n --gemina-verification-accent-fg: #ffffff;\n --gemina-verification-surface: #1c232b;\n --gemina-verification-muted: #98a2b3;\n --gemina-verification-error: #f97066;\n --gemina-verification-input-bg: #12171d;\n --gemina-verification-input-border: #2a323c;\n --gemina-verification-dirty: #f7b27a;\n`;\n\nconst VERIFICATION_CSS = `\n.gemina-verification {\n --gemina-verification-bg: #ffffff;\n --gemina-verification-fg: #1a1d21;\n --gemina-verification-border: #d9dce1;\n --gemina-verification-accent: #2f6fed;\n --gemina-verification-accent-fg: #ffffff;\n --gemina-verification-surface: #f2f4f7;\n --gemina-verification-muted: #667085;\n --gemina-verification-error: #b42318;\n --gemina-verification-input-bg: #ffffff;\n --gemina-verification-input-border: #d0d5e2;\n --gemina-verification-dirty: #b54708;\n --gemina-verification-confidence-high: #52c41a;\n --gemina-verification-confidence-medium: #faad14;\n --gemina-verification-confidence-low: #ff4d4f;\n --gemina-verification-confidence-unknown: #d9d9d9;\n --gemina-verification-overlay-rgb: 24, 144, 255;\n --gemina-verification-radius: 10px;\n --gemina-verification-font: system-ui, -apple-system, \"Segoe UI\", Roboto, sans-serif;\n\n box-sizing: border-box;\n position: relative; /* anchors __confirm; never overflow:hidden here — it would break the stacked sticky viewer */\n display: flex;\n flex-direction: column;\n gap: 16px;\n padding: 16px;\n background: var(--gemina-verification-bg);\n color: var(--gemina-verification-fg);\n border: 1px solid var(--gemina-verification-border);\n border-radius: var(--gemina-verification-radius);\n font-family: var(--gemina-verification-font);\n font-size: 14px;\n line-height: 1.5;\n}\n.gemina-verification *, .gemina-verification *::before, .gemina-verification *::after { box-sizing: border-box; }\n.gemina-verification--dark { ${DARK_VARS} }\n@media (prefers-color-scheme: dark) {\n .gemina-verification--auto { ${DARK_VARS} }\n}\n.gemina-verification--rtl { direction: rtl; }\n/* Content is not chrome: the document pane never mirrors (industry rule —\n images/players/clocks keep their physical position under RTL), and dir=\"auto\"\n flips per DOCUMENT, so mirroring would make the image jump side per row.\n Forcing the grid container LTR pins physical order (image inline-left, form\n right, every language); the form pane alone restores RTL so Hebrew labels\n and values keep their natural direction (per-input dir=\"auto\" still handles\n mixed-language values). The viewer subtree deliberately stays LTR: it is\n pure geometry (scroll math, loupe projection, absolute positioning) and none\n of that math may be direction-dependent.\n\n That last point is not theoretical — it IS the magnifier bug. The loupe's\n magnified inner layer is absolutely positioned with no inset (viewer.tsx\n gives it only a transform), so its static position is wherever the inherited\n direction puts the inline start. Under RTL that flips to the right edge and\n the layer lands (layerWidth - loupeWidth) away — measured as a constant\n -704px skew in BOTH chromium and firefox, at every pointer position, leaving\n the user an empty circle rather than a shifted one. Pinning this subtree LTR\n restores the skew to (0, 0), matching the LTR baseline exactly. Do not\n \"simplify\" this by mirroring the panes again. */\n.gemina-verification--rtl .gemina-verification__panes { direction: ltr; }\n.gemina-verification--rtl .gemina-verification__form { direction: rtl; }\n\n/* --- Two-pane layout ------------------------------------------------------ */\n.gemina-verification__panes {\n display: grid;\n grid-template-columns: minmax(0, 1fr) minmax(0, 1fr);\n gap: 16px;\n}\n.gemina-verification--stacked .gemina-verification__panes {\n /* Flex column, NOT a one-column grid: a sticky GRID item is confined to its\n own grid area — whose auto row is exactly its own height, leaving zero\n travel — while a sticky FLEX child's containing block is the whole panes\n box, so the viewer genuinely floats over the form as it scrolls. The gap\n carries over from the base rule. */\n display: flex;\n flex-direction: column;\n}\n.gemina-verification--stacked .gemina-verification__viewer {\n position: sticky;\n top: 0; /* block axis, not inline — RTL-safe */\n z-index: 2;\n /* Cap AND height in one declaration: the canvas is absolutely-positioned\n geometry with no intrinsic height (it contributes only its min-height),\n so a max-block-size alone would never bind — the explicit block-size is\n what the canvas fills. 48vh keeps the majority of a short viewport for\n the form the reviewer is working through; 420px stops a tall narrow\n window from devoting a huge sticky band to the document. The dvh line\n wins where supported (mobile browser chrome shrinks the visual viewport). */\n flex: 0 0 auto;\n block-size: min(48vh, 420px);\n block-size: min(48dvh, 420px);\n}\n.gemina-verification--stacked .gemina-verification__canvas {\n /* The stacked cap owns the height; the side-by-side 280px floor would\n overflow it on short viewports (48vh of a 568px screen is ~273px). */\n min-height: 120px;\n}\n\n/* --- Document viewer ------------------------------------------------------ */\n.gemina-verification__viewer {\n display: flex;\n flex-direction: column;\n min-width: 0;\n background: var(--gemina-verification-bg);\n border: 1px solid var(--gemina-verification-border);\n border-radius: var(--gemina-verification-radius);\n /* overflow hidden creates a scroll container and prevents the toolbar's sticky\n positioning from following the host modal's scrollport. Clip keeps the\n rounded frame without stealing sticky containment. */\n overflow: clip;\n}\n.gemina-verification__toolbar {\n position: sticky;\n top: 0;\n z-index: 5;\n display: flex;\n /* Narrow roots (~<330px) can't fit all 7 buttons on one line: wrap to a\n second row instead of clipping past the canvas edge. The gap shorthand\n below already provides the 6px row-gap between wrapped rows. */\n flex-wrap: wrap;\n align-items: center;\n gap: 6px;\n flex: 0 0 auto;\n padding: 8px 10px;\n background: var(--gemina-verification-bg);\n border-block-end: 1px solid var(--gemina-verification-border);\n}\n.gemina-verification__toolbar-btn {\n font: inherit;\n font-size: 12px;\n padding: 4px 10px;\n border-radius: calc(var(--gemina-verification-radius) - 4px);\n border: 1px solid var(--gemina-verification-border);\n background: transparent;\n color: var(--gemina-verification-fg);\n cursor: pointer;\n transition: border-color 120ms ease, background-color 120ms ease, color 120ms ease;\n}\n.gemina-verification__toolbar-btn svg { display: block; } /* no inline-baseline slack under the icons */\n.gemina-verification__toolbar-btn:hover:not(:disabled) { border-color: var(--gemina-verification-accent); }\n.gemina-verification__toolbar-btn:disabled { opacity: 0.5; cursor: default; }\n.gemina-verification__toolbar-btn--active {\n background: var(--gemina-verification-accent);\n border-color: var(--gemina-verification-accent);\n color: var(--gemina-verification-accent-fg);\n}\n.gemina-verification__canvas {\n position: relative;\n flex: 1;\n min-height: 280px;\n overflow: hidden;\n background: var(--gemina-verification-surface);\n touch-action: none;\n cursor: zoom-in; /* initial truth: at fit a drag is inert, wheel/dblclick zooms */\n user-select: none;\n -webkit-user-select: none;\n}\n/* Cursor is the promise of what a drag will do, so it follows viewer state\n (data-cursor), never :active — a bare :active rule would claim \"grabbing\"\n at fit scale where pan never engages. */\n.gemina-verification__canvas[data-cursor='zoom-in'] { cursor: zoom-in; }\n.gemina-verification__canvas[data-cursor='grab'] { cursor: grab; }\n.gemina-verification__canvas[data-cursor='grabbing'] { cursor: grabbing; }\n/* The document image is geometry, not layout: a block box at natural size,\n positioned purely by the JS transform layer above it. */\n.gemina-verification__canvas img {\n display: block;\n max-width: unset;\n max-height: unset;\n}\n/* Overlay geometry (left/top/width/height) is set inline by the viewer from\n transform math; CSS owns only the appearance. */\n.gemina-verification__rect {\n position: absolute;\n z-index: 2;\n pointer-events: none;\n border: 2px solid rgba(var(--gemina-verification-overlay-rgb), 0.85);\n background: rgba(var(--gemina-verification-overlay-rgb), 0.16);\n border-radius: 2px;\n}\n/* Numbered \"#1\" chip on each overlay rect. Physical left/top: the badge lives\n in image coordinate space inside the transform layer (geometry, not layout),\n so it scales and rotates with the document exactly like the console's.\n Explicit line-height pins the chip height across host font stacks. */\n.gemina-verification__rect-badge {\n position: absolute;\n top: -18px;\n left: 0;\n font-size: 11px;\n font-weight: 600;\n line-height: 16px;\n color: rgb(var(--gemina-verification-overlay-rgb));\n background: rgba(255, 255, 255, 0.92); /* floats over the document, not the theme surface */\n padding: 0 6px;\n border-radius: 12px;\n box-shadow: 0 1px 4px rgba(0, 0, 0, 0.16);\n pointer-events: none;\n}\n.gemina-verification__flash-rect {\n /* Fade is driven by JS via element-level opacity (rAF travel animation);\n no CSS animation here so the two never fight. Element-level opacity is\n equivalent to the console's per-channel fade — border (1·o), background\n (0.25·o), glow (0.6·o / 0.3·o) — modulo overlapping-layer compositing:\n per-channel alphas blend border-over-background where they overlap,\n element opacity flattens the group first. Indistinguishable in practice. */\n position: absolute;\n z-index: 3;\n pointer-events: none;\n border: 5px solid rgba(var(--gemina-verification-overlay-rgb), 1);\n background: rgba(var(--gemina-verification-overlay-rgb), 0.25);\n box-shadow: 0 0 20px rgba(var(--gemina-verification-overlay-rgb), 0.6),\n inset 0 0 10px rgba(var(--gemina-verification-overlay-rgb), 0.3);\n border-radius: 2px;\n}\n.gemina-verification__magnifier {\n position: absolute;\n z-index: 4;\n pointer-events: none;\n overflow: hidden;\n border-radius: 50%;\n border: 2px solid rgba(255, 255, 255, 0.85);\n box-shadow: 0 2px 12px rgba(0, 0, 0, 0.35);\n background: var(--gemina-verification-surface);\n}\n\n/* --- Form pane ------------------------------------------------------------ */\n/* A real <form> element (labeled AT landmark) — margin reset guards against\n host/UA form margins. */\n.gemina-verification__form {\n display: flex;\n flex-direction: column;\n gap: 12px;\n min-width: 0;\n margin: 0;\n /* Every z-index inside the form is form-internal business, and nothing in\n here may ever paint over the document. Without a stacking context of its\n own, the form's descendants resolve against the SAME context as the\n stacked-mode viewer (position: sticky, z-index: 2) — so the sticky header\n row (z-index: 3) painted straight over the document image as the form\n scrolled under the floating viewer. Confirmed in chromium and firefox\n before this line existed. Isolating caps the whole subtree beneath the\n viewer no matter what numbers it uses later. */\n isolation: isolate;\n}\n.gemina-verification__confidence-summary {\n display: flex;\n align-items: center;\n justify-content: space-between;\n gap: 12px;\n padding: 9px 12px;\n background: var(--gemina-verification-surface);\n border: 1px solid var(--gemina-verification-border);\n border-radius: var(--gemina-verification-radius);\n color: var(--gemina-verification-muted);\n font-size: 12px;\n font-weight: 600;\n}\n.gemina-verification__section {\n background: var(--gemina-verification-bg);\n border: 1px solid var(--gemina-verification-border);\n border-radius: var(--gemina-verification-radius);\n overflow: hidden;\n}\n.gemina-verification__section-header {\n display: flex;\n align-items: center;\n gap: 8px;\n padding: 8px 12px;\n background: var(--gemina-verification-surface);\n border-block-end: 1px solid var(--gemina-verification-border);\n font-size: 13px;\n font-weight: 600;\n}\n.gemina-verification__overall-confidence {\n display: inline-flex;\n align-items: center;\n gap: 6px;\n margin-inline-start: auto;\n color: var(--gemina-verification-muted);\n font-size: 11px;\n font-weight: 500;\n white-space: nowrap;\n}\n.gemina-verification__dl {\n display: grid;\n grid-template-columns: minmax(0, 2fr) minmax(0, 3fr);\n column-gap: 12px;\n margin: 0;\n padding: 8px 12px;\n}\n.gemina-verification__dt {\n display: flex;\n align-items: center;\n gap: 6px;\n padding-block: 5px;\n min-width: 0;\n font-size: 12px;\n color: var(--gemina-verification-muted);\n overflow-wrap: break-word;\n}\n.gemina-verification__dd {\n display: flex;\n /* Wrap so a field error takes its OWN line (it sets flex-basis:100%).\n Without this it competes with the input for width, and at 390px the\n message wrapped to one word per line while the input shrank to ~55px. */\n flex-wrap: wrap;\n align-items: center;\n gap: 6px;\n margin: 0; /* resets the UA's margin-inline-start on <dd> */\n padding-block: 5px;\n min-width: 0;\n font-size: 13px;\n font-variant-numeric: tabular-nums;\n overflow-wrap: break-word;\n}\n.gemina-verification__input {\n width: 100%;\n font: inherit;\n font-size: 13px;\n color: var(--gemina-verification-fg);\n background: var(--gemina-verification-input-bg);\n border: 1px solid var(--gemina-verification-input-border);\n border-radius: calc(var(--gemina-verification-radius) - 4px);\n padding: 5px 8px;\n}\n/* FieldInput is a fragment. Let its control take the remaining row width\n instead of forcing width:100%, so a coordinate eye can sit beside it rather\n than wrapping onto a visually disconnected second line. */\n.gemina-verification__dd > .gemina-verification__input,\n.gemina-verification__cell > .gemina-verification__input {\n flex: 1 1 8ch;\n width: auto;\n min-width: 0;\n}\n.gemina-verification__input--dirty { border-color: var(--gemina-verification-dirty); }\n.gemina-verification__input--missed {\n border-color: var(--gemina-verification-error);\n box-shadow: 0 0 0 1px var(--gemina-verification-error);\n}\n/* Non-color dirty channel: the word itself is the signal (WCAG 1.4.1) — it\n stays legible when --missed's error border overrides the dirty border. */\n.gemina-verification__edited {\n flex: 0 0 auto;\n font-size: 10px;\n font-weight: 600;\n letter-spacing: 0.06em;\n text-transform: uppercase;\n color: var(--gemina-verification-dirty);\n}\n.gemina-verification__dot {\n display: inline-block;\n flex: 0 0 auto;\n width: 8px;\n height: 8px;\n border-radius: 50%;\n background: var(--gemina-verification-confidence-unknown);\n}\n.gemina-verification__dot--high { background: var(--gemina-verification-confidence-high); }\n.gemina-verification__dot--medium { background: var(--gemina-verification-confidence-medium); }\n.gemina-verification__dot--low { background: var(--gemina-verification-confidence-low); }\n.gemina-verification__dot--unknown { background: var(--gemina-verification-confidence-unknown); }\n.gemina-verification__eye {\n display: inline-flex;\n align-items: center;\n justify-content: center;\n flex: 0 0 auto;\n width: 24px;\n height: 24px;\n padding: 0;\n border: 0;\n border-radius: calc(var(--gemina-verification-radius) - 4px);\n background: transparent;\n color: var(--gemina-verification-muted);\n cursor: pointer;\n transition: background-color 120ms ease, color 120ms ease;\n}\n.gemina-verification__eye:hover {\n color: var(--gemina-verification-accent);\n background: var(--gemina-verification-surface);\n}\n\n/* --- Tables and cards ----------------------------------------------------- */\n/* Section content that is not flush with the section frame (cards, fallback\n details) sits inside this padded body. */\n.gemina-verification__section-body { padding: 8px 12px; }\n/* Flex row for FieldInput's fragment (input + \"edited\" badge) inside <td>s\n and list items — the fragment has no container of its own. */\n.gemina-verification__cell {\n display: flex;\n flex-wrap: wrap; /* same reason as __dd: the field error needs its own line */\n align-items: center;\n gap: 6px;\n min-width: 0;\n}\n/* Simple-list items stack inside a __dd; each item row is a __cell. */\n.gemina-verification__list {\n display: flex;\n flex-direction: column;\n gap: 4px;\n flex: 1 1 auto;\n min-width: 0;\n margin: 0;\n padding: 0;\n list-style: none;\n}\n.gemina-verification__table-wrap {\n overflow-x: auto;\n /* Sticky binds to the nearest scrollport, and in an embedded widget that\n must be THIS wrapper (no per-host offset math). Bounding the block size\n turns it into a vertical scrollport too: long tables scroll internally\n with the header row pinned; short tables never reach the cap and are\n unchanged. */\n overflow-y: auto;\n max-block-size: min(56vh, 520px);\n}\n.gemina-verification__table {\n width: 100%;\n /* separate, not collapse: collapsed borders belong to the row grid, so a\n stuck header sheds its underline mid-scroll. With separate borders the\n border-block-end travels with the th. */\n border-collapse: separate;\n border-spacing: 0;\n font-size: 13px;\n font-variant-numeric: tabular-nums;\n}\n.gemina-verification__table th {\n position: sticky;\n inset-block-start: 0;\n /* Above cell content and focus rings; below the viewer toolbar (5) and the\n confirm scrim. */\n z-index: 3;\n text-align: start;\n padding: 6px 10px;\n font-size: 12px;\n font-weight: 600;\n color: var(--gemina-verification-muted);\n background: var(--gemina-verification-surface);\n border-block-end: 1px solid var(--gemina-verification-border);\n}\n.gemina-verification__table td {\n padding: 6px 10px;\n vertical-align: top;\n border-block-end: 1px solid var(--gemina-verification-border);\n}\n.gemina-verification__table tr:last-child td { border-block-end: 0; }\n/* Wide tables lean on __table-wrap's scroll; the clamp keeps a cell input\n usable instead of letting the table squeeze it to nothing. */\n.gemina-verification__table .gemina-verification__input { min-width: 6ch; }\n.gemina-verification__card {\n display: flex;\n flex-direction: column;\n gap: 6px;\n padding: 10px 12px;\n background: var(--gemina-verification-bg);\n border: 1px solid var(--gemina-verification-border);\n border-radius: calc(var(--gemina-verification-radius) - 4px);\n}\n.gemina-verification__card + .gemina-verification__card { margin-block-start: 8px; }\n.gemina-verification__card-header {\n font-size: 12px;\n font-weight: 600;\n color: var(--gemina-verification-muted);\n}\n/* The card already pads; its inner description list must not double it. */\n.gemina-verification__card .gemina-verification__dl { padding: 0; }\n/* Fallback blobs are a native <details>: summary is the toggle, the JSON\n lives in a <pre> so only the code is monospace/pre-wrapped. */\n.gemina-verification__fallback {\n margin: 0;\n padding: 8px 12px;\n font-size: 12px;\n background: var(--gemina-verification-surface);\n border-radius: calc(var(--gemina-verification-radius) - 4px);\n}\n.gemina-verification__fallback + .gemina-verification__fallback { margin-block-start: 8px; }\n.gemina-verification__fallback summary {\n cursor: pointer;\n font-weight: 600;\n user-select: none;\n}\n.gemina-verification__fallback pre {\n margin: 0;\n margin-block-start: 8px;\n font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;\n white-space: pre-wrap;\n overflow-wrap: break-word;\n overflow-x: auto;\n}\n\n/* --- Messaging, progress, actions ----------------------------------------- */\n.gemina-verification__banner {\n padding: 10px 12px;\n font-size: 13px;\n background: var(--gemina-verification-surface);\n border: 1px solid var(--gemina-verification-border);\n border-radius: var(--gemina-verification-radius);\n}\n.gemina-verification__banner--error {\n background: transparent;\n border-color: var(--gemina-verification-error);\n color: var(--gemina-verification-error);\n}\n.gemina-verification__progress {\n font-size: 12px;\n color: var(--gemina-verification-muted);\n font-variant-numeric: tabular-nums;\n /* The counts copy (\"N confirmed · M corrected\") is untranslated English\n chrome; under dir=\"rtl\" the RTL paragraph direction reorders its\n leading-number run (\"confirmed · 0 corrected 7\"). plaintext makes the\n line take its base direction from its own first strong character, so\n the English copy lays out LTR inside the RTL widget. The done-state\n recap reuses this same class, so it is covered too. */\n unicode-bidi: plaintext;\n}\n.gemina-verification__footer {\n display: flex;\n /* Wraps because the review filter adds two more items to this row, and at\n 320 the four together overflow: Submit was pushed 28px past the inline\n start and clipped. Measured RTL, where the overflow runs the other way\n and a scrollWidth-minus-clientWidth check on the document never sees it. */\n flex-wrap: wrap;\n align-items: center;\n gap: 10px;\n padding-block-start: 12px;\n border-block-start: 1px solid var(--gemina-verification-border);\n}\n.gemina-verification__footer .gemina-verification__submit { margin-inline-start: auto; }\n.gemina-verification__submit {\n font: inherit;\n border: none;\n border-radius: var(--gemina-verification-radius);\n background: var(--gemina-verification-accent);\n color: var(--gemina-verification-accent-fg);\n padding: 8px 16px;\n cursor: pointer;\n}\n.gemina-verification__submit:disabled { opacity: 0.5; cursor: default; }\n/* The review filter is a VIEW MODE, not an action, so it stays quiet: an\n outline control in the muted color, next to the one loud thing in the\n footer. Turning it on fills it from the same accent token — the state has\n to be unmistakable, because the form is hiding content while it is on. */\n.gemina-verification__review-filter {\n font: inherit;\n font-size: 12px;\n padding: 4px 12px;\n border-radius: var(--gemina-verification-radius);\n border: 1px solid var(--gemina-verification-border);\n background: transparent;\n color: var(--gemina-verification-muted);\n cursor: pointer;\n}\n.gemina-verification__review-filter:hover {\n color: var(--gemina-verification-accent);\n border-color: var(--gemina-verification-accent);\n}\n.gemina-verification__review-filter[aria-checked='true'] {\n background: var(--gemina-verification-accent);\n border-color: var(--gemina-verification-accent);\n color: var(--gemina-verification-accent-fg);\n}\n/* Stands in for a table's grid when every row of it scored high. Muted and\n unemphatic on purpose — it reports an absence, it is not a finding. */\n.gemina-verification__filter-count {\n font-size: 12px;\n color: var(--gemina-verification-muted);\n}\n.gemina-verification__filter-note {\n font-size: 12px;\n color: var(--gemina-verification-muted);\n}\n.gemina-verification__all-scored {\n margin: 0;\n padding: 12px;\n color: var(--gemina-verification-muted);\n font-size: 13px;\n}\n.gemina-verification__retry {\n font: inherit;\n font-size: 12px;\n padding: 2px 10px;\n border-radius: var(--gemina-verification-radius);\n border: 1px solid var(--gemina-verification-error);\n background: transparent;\n color: var(--gemina-verification-error);\n cursor: pointer;\n}\n.gemina-verification__state {\n display: flex;\n flex-direction: column;\n align-items: center;\n justify-content: center;\n gap: 8px;\n min-height: 220px;\n padding: 24px;\n text-align: center;\n font-size: 13px;\n color: var(--gemina-verification-muted);\n}\n/* Submit-error banner: message + inline Retry on one line. */\n.gemina-verification__submit-error {\n display: flex;\n align-items: center;\n justify-content: space-between;\n gap: 10px;\n}\n/* Done: the one saturated moment outside the form — a single accent check. */\n.gemina-verification__state--done { color: var(--gemina-verification-fg); }\n/* Programmatic focus landing (tabIndex -1), not an interactive control: no\n ring — the accent check IS the visual landing; focus moves here purely so\n keyboard/AT users don't drop to <body> when the dialog unmounts. */\n.gemina-verification__state--done:focus,\n.gemina-verification__state--done:focus-visible { outline: none; }\n.gemina-verification__done-check {\n display: flex;\n align-items: center;\n justify-content: center;\n width: 40px;\n height: 40px;\n border-radius: 50%;\n background: var(--gemina-verification-accent);\n color: var(--gemina-verification-accent-fg);\n}\n.gemina-verification__done-title {\n font-size: 14px;\n font-weight: 600;\n}\n.gemina-verification__state--done .gemina-verification__progress { font-size: 13px; }\n\n/* --- Confirm dialog ------------------------------------------------------- */\n.gemina-verification__confirm {\n position: absolute;\n inset: 0;\n z-index: 10;\n display: flex;\n /* flex-start + a sticky dialog: the scrim spans the whole component, but the\n dialog slides with the page so it is in view even when the user is\n scrolled deep into a long stacked form. Sticky (not fixed) so it survives\n transformed-ancestor hosts where fixed re-anchors. */\n align-items: flex-start;\n justify-content: center;\n padding: 16px;\n background: rgba(16, 20, 24, 0.45);\n border-radius: var(--gemina-verification-radius);\n}\n.gemina-verification__confirm-dialog {\n position: sticky;\n top: 20vh; /* block axis — RTL-safe */\n display: flex;\n flex-direction: column;\n gap: 12px;\n width: 100%;\n max-width: 380px;\n padding: 16px;\n background: var(--gemina-verification-bg);\n color: var(--gemina-verification-fg);\n border: 1px solid var(--gemina-verification-border);\n border-radius: var(--gemina-verification-radius);\n box-shadow: 0 12px 32px rgba(16, 20, 24, 0.24);\n}\n.gemina-verification__confirm-text {\n margin: 0;\n font-size: 13px;\n}\n.gemina-verification__confirm-actions {\n display: flex;\n justify-content: flex-end;\n gap: 8px;\n}\n/* Quiet counterpart to __submit: same geometry, bordered, no fill — the\n accent stays on the final action. */\n.gemina-verification__confirm-cancel {\n font: inherit;\n padding: 8px 16px;\n border: 1px solid var(--gemina-verification-border);\n border-radius: var(--gemina-verification-radius);\n background: transparent;\n color: var(--gemina-verification-fg);\n cursor: pointer;\n transition: border-color 120ms ease;\n}\n.gemina-verification__confirm-cancel:hover:not(:disabled) {\n border-color: var(--gemina-verification-accent);\n}\n.gemina-verification__confirm-cancel:disabled { opacity: 0.5; cursor: default; }\n\n/* --- Focus ---------------------------------------------------------------- */\n.gemina-verification__input:focus-visible {\n outline: 2px solid var(--gemina-verification-accent);\n outline-offset: -1px;\n}\n.gemina-verification__toolbar-btn:focus-visible,\n.gemina-verification__eye:focus-visible,\n.gemina-verification__submit:focus-visible,\n.gemina-verification__retry:focus-visible,\n.gemina-verification__confirm-cancel:focus-visible,\n.gemina-verification__fallback summary:focus-visible {\n outline: 2px solid var(--gemina-verification-accent);\n outline-offset: 1px;\n}\n\n/* --- Reduced motion -------------------------------------------------------- */\n/* The viewer also checks this in JS before animating; the CSS block is the\n backstop that stills the canvas (flash, travel, micro-transitions). */\n@media (prefers-reduced-motion: reduce) {\n .gemina-verification__flash-rect,\n .gemina-verification__rect,\n .gemina-verification__canvas,\n .gemina-verification__canvas * {\n animation: none;\n transition: none;\n }\n}\n\n/* A label that carries a description. Dotted underline is the long-standing\n convention for \"there is more here\", and tabIndex makes it reachable, so the\n tooltip is not mouse-only. */\n.gemina-verification__label-described {\n text-decoration: underline dotted;\n text-underline-offset: 3px;\n cursor: help;\n}\n.gemina-verification__label-described:focus-visible {\n outline: 2px solid var(--gemina-verification-accent);\n outline-offset: 2px;\n}\n\n/* Rows worth a second look. Uses the EXISTING confidence tokens — no new\n colours — as a start-edge rule, which is the one edge a reviewer scans down\n a long table. Logical property, so it lands on the right side under RTL. */\n.gemina-verification__row--low > td:first-child,\n.gemina-verification__row--medium > td:first-child {\n border-inline-start: 3px solid transparent;\n}\n.gemina-verification__row--low > td:first-child {\n border-inline-start-color: var(--gemina-verification-confidence-low);\n}\n.gemina-verification__row--medium > td:first-child {\n border-inline-start-color: var(--gemina-verification-confidence-medium);\n}\n\n/* --- Row editing ----------------------------------------------------------\n Quiet by design: adding and removing lines is a correction, not the primary\n action, so the controls stay muted until hovered and the accent is left to\n Submit. */\n.gemina-verification__row-actions {\n white-space: nowrap;\n text-align: end; /* logical — RTL for free */\n}\n.gemina-verification__row-btn {\n font: inherit;\n line-height: 1;\n padding: 2px 7px;\n margin-inline-start: 4px;\n border-radius: calc(var(--gemina-verification-radius) - 5px);\n border: 1px solid var(--gemina-verification-border);\n background: transparent;\n color: var(--gemina-verification-muted);\n cursor: pointer;\n transition: border-color 120ms ease, color 120ms ease;\n}\n.gemina-verification__row-btn:hover {\n border-color: var(--gemina-verification-accent);\n color: var(--gemina-verification-fg);\n}\n.gemina-verification__table-footer {\n display: flex;\n padding: 8px 10px;\n}\n.gemina-verification__add-row {\n font: inherit;\n font-size: 12px;\n padding: 4px 10px;\n border-radius: calc(var(--gemina-verification-radius) - 4px);\n border: 1px dashed var(--gemina-verification-border);\n background: transparent;\n color: var(--gemina-verification-muted);\n cursor: pointer;\n}\n.gemina-verification__add-row:hover {\n border-style: solid;\n border-color: var(--gemina-verification-accent);\n color: var(--gemina-verification-fg);\n}\n\n/* --- Typed controls -------------------------------------------------------\n A <select> for a closed roster must sit on the same baseline as the text\n inputs beside it in a table row, so it inherits the input's box entirely and\n only overrides what a select needs. */\n.gemina-verification__input:is(select) {\n cursor: pointer;\n /* A select's intrinsic width follows its longest option — the 24-member unit\n roster would blow out the column. */\n max-width: 100%;\n}\n/* The error border must beat --dirty and --missed: an invalid value is the\n most urgent thing true about the field, and the reviewer cannot submit\n until it is fixed. Placed after both for cascade order. */\n.gemina-verification__input--invalid,\n.gemina-verification__input--invalid:focus-visible {\n border-color: var(--gemina-verification-error);\n}\n/* Sits under the control it describes. Basis 100% breaks it onto its own line\n inside the flex row FieldInput renders into, so it never squeezes the\n input. */\n.gemina-verification__field-error {\n flex-basis: 100%;\n margin-block-start: 4px;\n color: var(--gemina-verification-error);\n font-size: 12px;\n line-height: 1.35;\n}\n\n/* Replaces __progress while anything is invalid — same slot, so the footer\n never grows a second status line competing for the same attention. */\n.gemina-verification__attention {\n color: var(--gemina-verification-error);\n font-size: 13px;\n}\n\n/* --- Tooltip -------------------------------------------------------------\n Renders in a portal on document.body, inside a div carrying the root's\n class list — so these rules and every --gemina-verification-* custom\n property resolve exactly as they do in the component.\n\n Quieter than __confirm-dialog on purpose: an annotation, not a decision.\n Same border and shadow family, one step down in radius (the nested-element\n convention used by __chip et al), surface rather than bg so it separates\n from the panel it floats over, and a shorter shadow so it reads as sitting\n just above the page rather than over a scrim. */\n.gemina-verification__tip {\n position: fixed;\n z-index: 2147483000; /* above the host's own modal — this is the topmost layer */\n max-width: 260px; /* ~60 characters: past that a tooltip should be body copy */\n padding: 8px 10px;\n background: var(--gemina-verification-surface);\n color: var(--gemina-verification-fg);\n border: 1px solid var(--gemina-verification-border);\n border-radius: calc(var(--gemina-verification-radius) - 4px);\n box-shadow: 0 6px 16px rgba(16, 20, 24, 0.18);\n font-family: var(--gemina-verification-font);\n font-size: 12px;\n line-height: 1.45;\n text-align: start; /* logical — RTL for free */\n pointer-events: none; /* never eat the hover that opened it */\n}\n/* Structured content: a level heading over a reasons list. The list is the\n reason this exists at all — title= could only ever have been one line. */\n.gemina-verification__tip-title {\n display: block;\n font-weight: 600;\n margin-block-end: 4px;\n}\n.gemina-verification__tip-list {\n margin: 0;\n padding-inline-start: 16px;\n}\n.gemina-verification__tip-list li + li {\n margin-block-start: 2px;\n}\n/* A muted lead-in for single-fact tips (\"Was:\"), so the VALUE reads first. */\n.gemina-verification__tip-label {\n color: var(--gemina-verification-muted);\n}\n`;\n\nconst STYLE_ATTR = 'data-gemina-verification';\n\n/**\n * Inject the verification stylesheet once per document (idempotent across\n * instances; intentionally not removed on unmount so sibling instances and\n * quick remounts never flash unstyled). Safe to call during SSR: it no-ops\n * when there is no document, and importing this module never touches it.\n */\nexport function ensureVerificationStylesInjected(): void {\n if (typeof document === 'undefined') {\n return;\n }\n if (document.head.querySelector(`style[${STYLE_ATTR}]`) !== null) {\n return;\n }\n const style = document.createElement('style');\n style.setAttribute(STYLE_ATTR, VERSION);\n style.textContent = VERIFICATION_CSS;\n document.head.appendChild(style);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;AC8DA,IAAM,gBAAgB;AAEtB,I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6B,SAAS,aAAa,mBAEnF;AAAA;AAAA;AAAA,QAEJ;AAAA,MAEJ,KAAK;AAAA,MACL,KAAK;AAAA,MACL,KAAK;AAAA,MACL,KAAK;AACH,eAAO,aAAa,KAAK;AAAA,MAC3B,KAAK;AACH,eACE;AAAA,UAAC;AAAA;AAAA,YACC,KAAK;AAAA,YAGL,UAAU;AAAA,YACV,WAAU;AAAA,YACV,MAAK;AAAA,YAEL;AAAA,2DAAC,UAAK,WAAU,mCAAkC,eAAY,QAC5D,uDAAC,SAAI,OAAM,MAAK,QAAO,MAAK,SAAQ,aAAY,MAAK,QACnD;AAAA,gBAAC;AAAA;AAAA,kBACC,GAAE;AAAA,kBACF,QAAO;AAAA,kBACP,aAAY;AAAA,kBACZ,eAAc;AAAA,kBACd,gBAAe;AAAA;AAAA,cACjB,GACF,GACF;AAAA,cACA,6CAAC,SAAI,WAAU,mCAAmC,2BAAgB;AAAA,cAClE,6CAAC,SAAI,WAAU,iCACZ,aAAG,MAAM,SAAS,mBAAgB,MAAM,SAAS,cACpD;AAAA;AAAA;AAAA,QACF;AAAA,IAEN;AAAA,EACF,GAAG;AAEH,SACE,6CAAC,SAAI,KAAK,SAAS,WAAW,eAAe,KAAK,cAC/C,mBACH;AAEJ;","names":["import_react","import_sdk","escapeSegment","import_react","import_react","import_jsx_runtime","trigger","import_react","import_jsx_runtime","import_jsx_runtime","React","FallbackSection","DARK_VARS","STYLE_ATTR","import_jsx_runtime","HEBREW_RE","SESSION_EXPIRED_TEXT","rendered","next"]}
|