{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "pages-request-detail",
  "title": "Request detail page",
  "description": "One request against the register: its proposed change compared to the record it targets, why it was asked, its supporting documents, and the decision or lifecycle action open to this session.",
  "dependencies": [
    "@registrystack/app-runtime@~0.43.0-next.0",
    "lucide-react@1.43.0"
  ],
  "registryDependencies": [
    "@registrystack/pages-record",
    "@registrystack/pages-content",
    "@registrystack/pages-register-routes",
    "@registrystack/pages-record-attachments",
    "@registrystack/lib-content",
    "@registrystack/lib-notice",
    "@registrystack/lib-format",
    "@registrystack/field-renderers",
    "@registrystack/casework-shared",
    "@registrystack/request-actions",
    "@registrystack/request-changes",
    "@registrystack/request-status",
    "@registrystack/request-recovery-notices",
    "@registrystack/request-review-notes",
    "@registrystack/request-verified-prefill",
    "@registrystack/request-form",
    "@registrystack/request-attachment-slots",
    "@registrystack/document-preview",
    "@registrystack/shell-back-link",
    "@registrystack/shell-loading",
    "@registrystack/shell-error-panel",
    "@registrystack/shell-page-heading",
    "@registrystack/shell-status-badge",
    "@registrystack/shell-live-announcer",
    "@registrystack/shell-content",
    "@registrystack/shell-routing",
    "@registrystack/ui-button"
  ],
  "files": [
    {
      "path": "pages/request-detail-page.tsx",
      "content": "import { Fragment, useCallback, useEffect, useRef, useState } from \"react\";\nimport { ArrowUpRight } from \"lucide-react\";\nimport type {\n  EntityModel,\n  FieldModel,\n  RecordActionReference,\n  RecordTask,\n  RecordView,\n  RequestView,\n} from \"@registrystack/app-runtime\";\nimport { backOffInterval, unavailableError } from \"@registrystack/app-runtime\";\nimport {\n  recordTask,\n  useAuthority,\n  useRecord,\n  useRequesterReviewNotes,\n  useReviewHistory,\n} from \"@registrystack/app-runtime/react\";\nimport { Button } from \"@/components/ui/button\";\nimport { Notice } from \"@/blocks/lib/notice\";\nimport { fill, humanizeName, listOf, longDate } from \"@/blocks/lib/format\";\nimport {\n  useBlockContent,\n  useLocale,\n  type BlockContent,\n} from \"@/blocks/lib/content\";\nimport { FieldValue } from \"@/blocks/fields/field-value\";\nimport { InPhrase } from \"@/blocks/fields/values\";\nimport { BackLink } from \"@/blocks/shell/back-link\";\nimport { Loading } from \"@/blocks/shell/loading\";\nimport { splitRoute, useRoute } from \"@/blocks/shell/routing\";\nimport { ErrorPanel } from \"@/blocks/shell/error-panel\";\nimport { useShellContent } from \"@/blocks/shell/shell-content\";\nimport { PageHeading } from \"@/blocks/shell/page-heading\";\nimport { StatusBadge } from \"@/blocks/shell/status-badge\";\nimport { LiveAnnouncer, useAnnouncement } from \"@/blocks/shell/live-announcer\";\nimport {\n  usePagesContent,\n  type PagesContent,\n} from \"@/blocks/pages/pages-content\";\nimport { useRegisterRoutes } from \"@/blocks/pages/register-routes\";\nimport {\n  DecisionForm,\n  type DecisionOutcome,\n} from \"@/blocks/request/request-actions\";\nimport {\n  ChangeTable,\n  recordOfRequest,\n  writtenChangeRows,\n  writtenFields,\n  type ChangeRow,\n} from \"@/blocks/request/request-changes\";\nimport {\n  StateNotice,\n  approvedNotApplied,\n} from \"@/blocks/request/request-status\";\nimport { UnavailableNotice } from \"@/blocks/casework/shared\";\nimport { ReviewRecoveryNotices } from \"@/blocks/request/request-recovery-notices\";\nimport { ReviewNotes } from \"@/blocks/request/request-review-notes\";\nimport { VerifiedEvidenceSummary } from \"@/blocks/request/verified-prefill\";\nimport { AnswerList } from \"@/blocks/request/request-form\";\nimport type { UploadOutcome } from \"@/blocks/request/attachment-slots\";\nimport {\n  SupportingDocuments,\n  type RemovalOutcome,\n} from \"@/blocks/pages/record-attachments\";\nimport type { DocumentSource } from \"@/blocks/documents/document-view\";\nimport {\n  fieldOf,\n  readableTarget,\n  recordPath,\n  recordTitle,\n  requestRoute,\n  routedRequest,\n  useRegister,\n  type RegisterEntities,\n} from \"@/blocks/pages/record\";\n\n/** The decision this page submits: a lifecycle action against the request. */\nexport type RequestDecisionTask = DecisionOutcome & {\n  submit: (task: RecordTask) => Promise<unknown>;\n};\n\n/**\n * The sentence for a request's state. A holder reads their own request in the\n * second person; staff read it as someone else's.\n */\nfunction stateDescription(\n  state: string,\n  pages: PagesContent,\n  holder: boolean,\n): string {\n  const revision = holder\n    ? pages.revisionDescription\n    : pages.staffRevisionDescription;\n  const map: Record<string, string> = {\n    draft: pages.draftDescription,\n    submitted: holder\n      ? pages.submittedDescription\n      : pages.submittedReviewDescription,\n    \"revision-requested\": revision,\n    \"changes-requested\": revision,\n    \"approval-expired\": pages.approvalExpiredDescription,\n    approved: pages.approvedDescription,\n    applied: pages.appliedDescription,\n    rejected: pages.rejectedDescription,\n    cancelled: pages.cancelledDescription,\n  };\n  return map[state] ?? pages.actionExplanation;\n}\n\n/**\n * The sentence on a lifecycle action's check step. An apply names the fields\n * it changes when every written field's current value is known; otherwise it\n * keeps the general sentence.\n */\nfunction actionDescription(\n  name: string,\n  pages: PagesContent,\n  holder: boolean,\n  changes: readonly ChangeRow[],\n  locale: string,\n): string {\n  const changed = changes\n    .filter((row) => row.comparison === \"changed\")\n    .map((row) => row.label);\n  const nameable =\n    changed.length > 0 && changes.every((row) => row.comparison !== \"unknown\");\n  const map: Record<string, string> = {\n    submit: holder ? pages.confirmSubmit : pages.staffConfirmSubmit,\n    apply: nameable\n      ? fill(pages.confirmApplyFields, { fields: listOf(changed, locale) }, locale)\n      : pages.confirmApply,\n    revise: pages.confirmRevision,\n    rebase: pages.confirmRebase,\n    cancel: pages.confirmCancel,\n  };\n  return map[name] ?? pages.actionExplanation;\n}\n\n/**\n * An action's label: the app's own wording for its lifecycle action, before the\n * action's own, then the default wording for the lifecycle action, then its\n * name read as words.\n */\nfunction choiceLabel(\n  action: RecordActionReference,\n  pages: PagesContent,\n): string {\n  const key = action.action ?? action.name;\n  return (\n    pages.actionLabels[key] ??\n    action.label ??\n    pages.lifecycleActionLabels[key] ??\n    humanizeName(key)\n  );\n}\n\n/**\n * The label of the button that opens an action's check step: the default\n * wording for its lifecycle action, so it differs from the confirm button,\n * which carries the action's own label. An action with no default opener\n * opens the check by its own label.\n */\nfunction openerLabel(\n  action: RecordActionReference,\n  pages: PagesContent,\n): string {\n  return (\n    pages.lifecycleOpenerLabels[action.action ?? action.name] ??\n    choiceLabel(action, pages)\n  );\n}\n\n/**\n * The target record's context fields that the request does not write: the\n * context an officer reads the change against. Without a declared context,\n * the record's list columns other than its title.\n */\nfunction contextFields(\n  record: EntityModel,\n  written: readonly string[],\n): FieldModel[] {\n  const declared = record.context;\n  return (declared ?? record.list.columns).flatMap((id) => {\n    const field = fieldOf(record, id);\n    return field && (declared || id !== record.title) && !written.includes(id)\n      ? [field]\n      : [];\n  });\n}\n\n/**\n * The comparison rows for one request, one for each field it writes. Current\n * values come from the live target record, so before-values survive the\n * decision that removes the pending lifecycle action; the values the request\n * retained stand in only while the target is not marked unavailable. An\n * applied request's come from the record's history.\n */\nfunction changeRows(\n  record: EntityModel,\n  request: EntityModel,\n  view: RecordView,\n  target: RecordView | undefined,\n  c: BlockContent,\n): ChangeRow[] {\n  const written = writtenFields({ record, request }, request.fields);\n  const rows = writtenChangeRows(\n    written,\n    view,\n    target,\n    view.request?.state === \"applied\"\n      ? c.beforeUnavailable\n      : c.currentUnavailable,\n  );\n  if (target && written.length > 0)\n    for (const field of contextFields(\n      record,\n      written.map((item) => item.target.id),\n    ))\n      rows.push({\n        key: field.id,\n        label: field.label,\n        current: <FieldValue field={field} value={target.values[field.id]} />,\n        proposed: <FieldValue field={field} value={target.values[field.id]} />,\n        comparison: \"unchanged\",\n      });\n  return rows;\n}\n\nconst otherLifecycleNames = [\"submit\", \"cancel\", \"revise\", \"rebase\"];\n\n/** This page's own wording for the review's three recovery states, over the block's `ReviewRecoveryNotices`. */\nfunction RequestRecoveryNotices({\n  request,\n}: {\n  request: RequestView | undefined;\n}) {\n  const pages = usePagesContent();\n  const applicationBlocked =\n    (request?.review?.application ?? request?.application)?.state === \"blocked\";\n  return (\n    <ReviewRecoveryNotices\n      request={request}\n      withdrawalPendingTitle={pages.reviewWithdrawalPendingTitle}\n      withdrawalPendingBody={pages.reviewWithdrawalPendingBody}\n      submissionUnknownTitle={pages.reviewSubmissionUnknownTitle}\n      submissionUnknownBody={pages.reviewSubmissionUnknownBody}\n      operatorAttentionTitle={\n        applicationBlocked\n          ? pages.applicationOperatorAttentionTitle\n          : pages.reviewOperatorAttentionTitle\n      }\n      operatorAttentionBody={\n        applicationBlocked\n          ? pages.applicationOperatorAttentionBody\n          : pages.reviewOperatorAttentionBody\n      }\n      operatorAttentionBodies={\n        applicationBlocked\n          ? pages.applicationOperatorAttentionBodies\n          : pages.reviewOperatorAttentionBodies\n      }\n    />\n  );\n}\n\n/** The wait before a request awaiting its review result is first read again, in milliseconds. */\nconst reviewResultPollMs = 5_000;\n\n/** The longest wait between re-reads: a review can take days, so the poll slows to this and stays. */\nconst reviewResultPollCapMs = 60_000;\n\n/**\n * A submitted request is read again while it awaits a Casework result, while\n * a refusal waits for BReg to end the request as rejected, or while BReg is\n * automatically applying it, with or without a review, each wait twice the\n * last.\n */\nfunction awaitingReviewResult(\n  view: RecordView | undefined,\n  rereads: number,\n): number | false {\n  const request = view?.request;\n  const application = request?.review?.application ?? request?.application;\n  const automatic =\n    application?.mode === \"automatic\" &&\n    [\"pending\", \"applying\"].includes(application.state);\n  const waiting =\n    request?.state === \"submitted\" &&\n    [\"pending\", \"rejected\"].includes(request.review?.result.state ?? \"\");\n  return waiting ||\n    (automatic && [\"submitted\", \"approved\"].includes(request?.state ?? \"\"))\n    ? backOffInterval(reviewResultPollMs, reviewResultPollCapMs, rereads)\n    : false;\n}\n\n/**\n * The request screen for every role: a reviewer applies an approved request,\n * a holder or registrar tracks their own request. Document order: banner,\n * heading, comparison, reason asked, then the controls last.\n */\nexport function RequestDetailPage({\n  id,\n  useTask,\n  useUpload,\n  useRemoval,\n  openPdf,\n}: {\n  id: string;\n  /** The decision this page submits; a page instantiates it over its own host command. */\n  useTask: () => RequestDecisionTask;\n  useUpload: (slot: string) => UploadOutcome;\n  useRemoval: (slot: string) => RemovalOutcome;\n  /** Opens a supporting PDF's bytes in the preview; without it, a PDF stays download-only. */\n  openPdf?: (\n    bytes: ArrayBuffer,\n    signal: AbortSignal,\n  ) => Promise<DocumentSource>;\n}) {\n  const register = useRegister();\n  const shell = useShellContent();\n  const { query } = splitRoute(useRoute());\n  if (register.isPending) return <Loading />;\n  if (register.error)\n    return (\n      <ErrorPanel\n        error={register.error}\n        retry={() => void register.refetch()}\n      />\n    );\n  const entities = register.entities;\n  const request = entities && routedRequest(entities, query);\n  if (!entities || !request)\n    return <ErrorPanel error={unavailableError(shell.unavailable)} />;\n  return (\n    <RequestRead\n      key={`${request.id}:${id}`}\n      entities={entities}\n      request={request}\n      id={id}\n      useTask={useTask}\n      useUpload={useUpload}\n      useRemoval={useRemoval}\n      openPdf={openPdf}\n    />\n  );\n}\n\nfunction RequestRead({\n  entities,\n  request,\n  id,\n  useTask,\n  useUpload,\n  useRemoval,\n  openPdf,\n}: {\n  entities: RegisterEntities;\n  request: EntityModel;\n  id: string;\n  useTask: () => RequestDecisionTask;\n  useUpload: (slot: string) => UploadOutcome;\n  useRemoval: (slot: string) => RemovalOutcome;\n  openPdf?: (\n    bytes: ArrayBuffer,\n    signal: AbortSignal,\n  ) => Promise<DocumentSource>;\n}) {\n  const pages = usePagesContent(),\n    session = useAuthority(),\n    query = useRecord(request.id, id, undefined, awaitingReviewResult);\n  // A fresh first read needs no second trip. Cached data may have survived the\n  // edit page that invalidated it, so the request page explicitly reads again\n  // and keeps every write locked from its first render until that read settles.\n  const cachedOnEntry = useRef(query.data !== undefined);\n  const [entryReadSettled, setEntryReadSettled] = useState(\n    !cachedOnEntry.current,\n  );\n  useEffect(() => {\n    if (!cachedOnEntry.current) return;\n    let active = true;\n    // Join an invalidation already reading this request instead of cancelling\n    // it and briefly replacing one refresh with another.\n    void query.refetch({ cancelRefetch: false }).then((result) => {\n      if (active && !result.error) setEntryReadSettled(true);\n    });\n    return () => {\n      active = false;\n    };\n  }, [query.refetch]);\n  if (query.isPending) return <Loading />;\n  if (query.error || !query.data)\n    return (\n      <ErrorPanel\n        error={query.error}\n        retry={() =>\n          void query.refetch().then((result) => {\n            if (!result.error) setEntryReadSettled(true);\n          })\n        }\n        unavailableTitle={session.holder ? pages.requestUnavailable : undefined}\n      />\n    );\n  return (\n    <RequestWithTarget\n      entities={entities}\n      request={request}\n      view={query.data}\n      refetch={() => query.refetch()}\n      refreshing={!entryReadSettled || query.refreshing}\n      useTask={useTask}\n      useUpload={useUpload}\n      useRemoval={useRemoval}\n      openPdf={openPdf}\n    />\n  );\n}\n\n/** Reads the record the request changes; a target that cannot be read leaves the comparison to say so. */\nfunction RequestWithTarget({\n  entities,\n  request,\n  view,\n  refetch,\n  refreshing,\n  useTask,\n  useUpload,\n  useRemoval,\n  openPdf,\n}: {\n  entities: RegisterEntities;\n  request: EntityModel;\n  view: RecordView;\n  refetch: () => Promise<unknown>;\n  /** The request's own read is stale and already being refetched in the background. */\n  refreshing: boolean;\n  useTask: () => RequestDecisionTask;\n  useUpload: (slot: string) => UploadOutcome;\n  useRemoval: (slot: string) => RemovalOutcome;\n  openPdf?: (\n    bytes: ArrayBuffer,\n    signal: AbortSignal,\n  ) => Promise<DocumentSource>;\n}) {\n  const context = view.request?.entry ?? view.request?.target;\n  const record = recordOfRequest(entities, request, context?.entity);\n  const target = useRecord(\n    record.id,\n    readableTarget({ ...entities, record }, view.request),\n  );\n  if (target.isLoading) return <Loading />;\n  return (\n    <RequestDetail\n      entities={entities}\n      request={request}\n      view={view}\n      target={target.data}\n      refetch={refetch}\n      refreshing={refreshing}\n      useTask={useTask}\n      useUpload={useUpload}\n      useRemoval={useRemoval}\n      openPdf={openPdf}\n    />\n  );\n}\n\n/**\n * What the reviewer wrote for the request's holder, when the review sent it\n * back or rejected it. The host reads the notes from the review the record\n * names; any other account, and any read that fails, gets the not-available\n * wording.\n */\nfunction ReviewerNote({\n  entity,\n  id,\n  reason,\n}: {\n  entity: string;\n  id: string;\n  reason?: string;\n}) {\n  const notes = useRequesterReviewNotes(entity, id);\n  if (notes.isPending) return <Loading />;\n  // A read that settled without data (a fetch error the hook did not turn\n  // into a \"not-available\" state itself) gets the same undisclosed wording\n  // as any other state the block does not name explicitly.\n  return (\n    <ReviewNotes\n      notes={notes.data ?? { state: \"unavailable\", notes: [] }}\n      reason={reason}\n    />\n  );\n}\n\n/**\n * What the reviewer wrote for the request's holder, read by a Casework officer\n * from the review's own history on their own profile. Casework decides what\n * the officer may read; a read that fails gets the not-available wording.\n */\nfunction OfficerReviewerNote({\n  reviewId,\n  reason,\n}: {\n  reviewId: string;\n  reason?: string;\n}) {\n  const block = useBlockContent();\n  const history = useReviewHistory(reviewId);\n  const { hasNextPage, isFetchingNextPage, fetchNextPage } = history;\n  // The note may sit on a later page of the history.\n  useEffect(() => {\n    if (hasNextPage && !isFetchingNextPage) void fetchNextPage();\n  }, [hasNextPage, isFetchingNextPage, fetchNextPage]);\n  if (history.error && !history.data)\n    return (\n      <ReviewNotes\n        notes={{ state: \"unavailable\", notes: [] }}\n        reason={reason}\n      />\n    );\n  if (!history.data || hasNextPage) return <Loading />;\n  const notes = history.data.flatMap((entry) => {\n    const detail = entry.detail;\n    if (\n      entry.kind !== \"note\" ||\n      !detail ||\n      typeof detail !== \"object\" ||\n      Array.isArray(detail) ||\n      detail.audience !== \"requester\" ||\n      typeof detail.note !== \"string\" ||\n      !detail.note.trim()\n    )\n      return [];\n    return [\n      {\n        eventId: entry.eventId,\n        note: detail.note,\n        occurredAt: entry.occurredAt,\n      },\n    ];\n  });\n  return (\n    <ReviewNotes\n      notes={{ state: notes.length ? \"available\" : \"none\", notes }}\n      noNote={block.requesterNoNote}\n      reason={reason}\n    />\n  );\n}\n\nfunction RequestDetail({\n  entities,\n  request,\n  view,\n  target,\n  refetch,\n  refreshing,\n  useTask,\n  useUpload,\n  useRemoval,\n  openPdf,\n}: {\n  entities: RegisterEntities;\n  request: EntityModel;\n  view: RecordView;\n  target: RecordView | undefined;\n  refetch: () => Promise<unknown>;\n  /** The request's own read is stale and already being refetched in the background. */\n  refreshing: boolean;\n  useTask: () => RequestDecisionTask;\n  useUpload: (slot: string) => UploadOutcome;\n  useRemoval: (slot: string) => RemovalOutcome;\n  openPdf?: (\n    bytes: ArrayBuffer,\n    signal: AbortSignal,\n  ) => Promise<DocumentSource>;\n}) {\n  const pages = usePagesContent(),\n    block = useBlockContent(),\n    locale = useLocale(),\n    routes = useRegisterRoutes(),\n    session = useAuthority(),\n    task = useTask();\n  const [announcement, announce] = useAnnouncement();\n  const [writingAttachments, setWritingAttachments] = useState<Set<string>>(\n    () => new Set(),\n  );\n  const setAttachmentWriting = useCallback(\n    (slot: string, writing: boolean) =>\n      setWritingAttachments((current) => {\n        if (current.has(slot) === writing) return current;\n        const next = new Set(current);\n        if (writing) next.add(slot);\n        else next.delete(slot);\n        return next;\n      }),\n    [],\n  );\n  const requestContext = view.request?.entry ?? view.request?.target;\n  const record = recordOfRequest(entities, request, requestContext?.entity);\n  const state = view.request?.state ?? \"draft\";\n  const result = view.request?.review?.result.state;\n  // The human reference: the target record's title, never the UUID.\n  const reference =\n    (target && recordTitle(record, target, locale)) ?? recordTitle(request, view, locale);\n\n  const lifecycle = view.actions.filter(\n    (action) => action.name === \"lifecycle\",\n  );\n  const offeredApplyAction =\n    lifecycle.find((action) => action.action === \"apply\") ?? null;\n  const otherActions = lifecycle.filter((action) =>\n    otherLifecycleNames.includes(action.action ?? \"\"),\n  );\n  const patchAction = view.actions.find((action) => action.name === \"patch\");\n  const holder = session.holder;\n  const approved = approvedNotApplied(view.request);\n  // Some BReg policies advertise apply before the external result is\n  // reconciled and enforce the precondition on write. Keep that authority,\n  // while only inviting the action once the same native read confirms it.\n  const applyAction = approved ? offeredApplyAction : null;\n  // The wording follows the apply the registry offers, not the session's role.\n  const applying = applyAction !== null;\n  const applied = view.request?.applied;\n  // A send-back leaves the request submitted; its review result says so.\n  const sentBack =\n    state === \"changes-requested\" || result === \"changesRequested\";\n  // A refusal BReg has not yet ended as rejected is still being decided.\n  const rejected = !sentBack && state === \"rejected\";\n  const publicReason = view.request?.review?.result.publicReason;\n\n  const written = writtenFields({ record, request }, request.fields);\n  const changes = changeRows(record, request, view, target, block);\n  const writtenIds = written.map((item) => item.field.id);\n  const asked = request.sections\n    .flatMap((section) => section.fields)\n    .flatMap((id) => {\n      const field = fieldOf(request, id);\n      const value = view.values[id];\n      return field &&\n        !writtenIds.includes(id) &&\n        value !== undefined &&\n        value !== null\n        ? [field]\n        : [];\n    });\n  const evidence = view.request?.evidence;\n  const evidenceField = evidence\n    ? request.fields.find(\n        (field) =>\n          field.id === evidence.field || field.apiName === evidence.field,\n      )\n    : undefined;\n  const context =\n    target && written.length > 0\n      ? contextFields(\n          record,\n          written.map((item) => item.target.id),\n        )\n      : [];\n\n  const targetPath =\n    requestContext &&\n    recordPath(routes, entities, requestContext.entity, requestContext.id);\n  const resultLinks = (view.request?.results ?? []).flatMap((result) => {\n    if (\n      [view.request?.entry, view.request?.target].some(\n        (context) =>\n          context?.entity === result.entity && context.id === result.id,\n      )\n    )\n      return [];\n    const entity = (entities.records ?? [entities.record]).find(\n      (candidate) => candidate.id === result.entity,\n    );\n    const path =\n      entity?.operations.get &&\n      recordPath(routes, entities, result.entity, result.id);\n    return entity && path ? [{ ...result, entity, path }] : [];\n  });\n  const queuePath = requestRoute(entities, routes.requests, request.id);\n  const contextualBack = request.navigation === false && targetPath;\n  const hasActions =\n    applyAction !== null ||\n    otherActions.length > 0 ||\n    patchAction !== undefined;\n  const hasDecisionFeedback = Boolean(\n    task.pending ||\n    task.unknown ||\n    task.error ||\n    task.result ||\n    task.staleConflict ||\n    task.confirmed,\n  );\n\n  return (\n    <>\n      <BackLink href={contextualBack || queuePath}>\n        {contextualBack\n          ? pages.backToRecord\n          : session.decidesRequests\n            ? pages.reviewQueue\n            : holder\n              ? pages.ownRequests\n              : pages.requestsHome}\n      </BackLink>\n      {/* The state of the case comes before the h1. */}\n      {approved ? (\n        <Notice title={pages.reviewApprovedPendingApplicationTitle}>\n          <p>{pages.reviewApprovedPendingApplicationBody}</p>\n        </Notice>\n      ) : (\n        <StateNotice\n          state={state}\n          description={stateDescription(state, pages, holder)}\n        />\n      )}\n      {state === \"applied\" && applied && (applied.at || applied.by) && (\n        <p className=\"muted [overflow-wrap:anywhere]\">\n          {applied.at && (\n            <>\n              {pages.appliedOnLabel} {longDate(applied.at, locale)}\n            </>\n          )}\n          {applied.at && applied.by && \" · \"}\n          {applied.by && (\n            <>\n              {pages.appliedByLabel} {applied.by}\n            </>\n          )}\n        </p>\n      )}\n      <RequestRecoveryNotices request={view.request} />\n      {view.request?.reviewUnavailable && (\n        <UnavailableNotice {...view.request.reviewUnavailable} />\n      )}\n      <PageHeading\n        eyebrow={reference}\n        title={request.label}\n        action={\n          <StatusBadge\n            state={approved ? \"approved\" : state}\n            served={request.request?.stateLabels[approved ? \"approved\" : state]}\n          />\n        }\n      />\n      <LiveAnnouncer message={announcement} />\n      {(sentBack || rejected) && (\n        <section className=\"revision-next-step\">\n          <h2>\n            {sentBack\n              ? holder\n                ? pages.revisionReason\n                : pages.staffRevisionReason\n              : pages.rejectionReason}\n          </h2>\n          {holder ? (\n            <ReviewerNote\n              entity={view.entity}\n              id={view.id}\n              reason={publicReason}\n            />\n          ) : session.caseworkProfile &&\n            view.request?.review?.submission.requestId ? (\n            <OfficerReviewerNote\n              reviewId={view.request.review.submission.requestId}\n              reason={publicReason}\n            />\n          ) : (\n            <ReviewNotes\n              notes={{ state: \"unavailable\", notes: [] }}\n              reason={publicReason}\n            />\n          )}\n        </section>\n      )}\n      {changes.length > 0 ? (\n        <section>\n          <h2>\n            {state === \"applied\"\n              ? block.appliedChangesHeading\n              : block.proposedHeading}\n          </h2>\n          <ChangeTable\n            rows={changes}\n            labels={\n              state === \"applied\"\n                ? {\n                    caption: block.appliedChangesHeading,\n                    current: block.beforeColumn,\n                    proposed: block.afterColumn,\n                  }\n                : undefined\n            }\n          >\n            {targetPath && !contextualBack && (\n              <Button render={<a href={`#${targetPath}`} />} variant=\"outline\">\n                {pages.viewRecordLink}\n                <ArrowUpRight />\n              </Button>\n            )}\n          </ChangeTable>\n        </section>\n      ) : (\n        targetPath &&\n        !contextualBack && (\n          <div className=\"actions\">\n            <Button render={<a href={`#${targetPath}`} />} variant=\"outline\">\n              {pages.viewRecordLink}\n              <ArrowUpRight />\n            </Button>\n          </div>\n        )\n      )}\n      {(asked.length > 0 || evidence) && (\n        <section>\n          <h2>\n            {holder ? block.holderWhyAskedHeading : block.whyAskedHeading}\n          </h2>\n          {asked.length > 0 && (\n            <AnswerList\n              items={asked.map((field) => ({\n                key: field.id,\n                label: field.label,\n                value: (\n                  <FieldValue field={field} value={view.values[field.id]} />\n                ),\n              }))}\n            />\n          )}\n          {evidence && (\n            <VerifiedEvidenceSummary\n              evidence={evidence}\n              changedValue={\n                evidence.changedAfterVerification && evidenceField ? (\n                  <FieldValue\n                    field={evidenceField}\n                    value={view.values[evidenceField.id]}\n                  />\n                ) : undefined\n              }\n            />\n          )}\n        </section>\n      )}\n      {resultLinks.length > 0 && (\n        <section>\n          <h2>{pages.requestResultsHeading}</h2>\n          <div className=\"actions\">\n            {resultLinks.map((result) => (\n              <Button\n                key={`${result.entity.id}:${result.id}:${result.revision}`}\n                render={<a href={`#${result.path}`} />}\n                variant=\"outline\"\n              >\n                {fill(\n                  pages.viewRequestResult,\n                  { label: result.entity.label },\n                  locale,\n                )}\n                <ArrowUpRight />\n              </Button>\n            ))}\n          </div>\n        </section>\n      )}\n      <SupportingDocuments\n        record={{ entity: view.entity, id: view.id, revision: view.revision }}\n        slots={view.attachments}\n        useUpload={useUpload}\n        useRemoval={useRemoval}\n        openPdf={openPdf}\n        writesDisabled={\n          refreshing ||\n          task.pending ||\n          task.unknown ||\n          writingAttachments.size > 0\n        }\n        onWritingChange={setAttachmentWriting}\n      />\n      {(hasActions || hasDecisionFeedback) && (\n        <DecisionForm\n          title={\n            applying\n              ? pages.applyApproved\n              : holder\n                ? pages.holderActionsHeading\n                : pages.decideHeading\n          }\n          hint={\n            applying\n              ? pages.applyApprovedHint\n              : holder\n                ? pages.holderActionsHint\n                : pages.actionExplanation\n          }\n          reference={reference ?? pages.unnamedRequest}\n          choices={[]}\n          primaryAction={applyAction}\n          primaryReason={\n            applyAction\n              ? { label: pages.applyReasonLabel, hint: pages.applyReasonHint }\n              : undefined\n          }\n          secondaryActions={otherActions}\n          hasActions={hasActions}\n          needsReason={() => false}\n          describeAction={(action) =>\n            actionDescription(\n              action.action ?? action.name,\n              pages,\n              holder,\n              changes,\n              locale,\n            )\n          }\n          checkDetails={\n            target &&\n            context.length > 0 && (\n              <p className=\"muted\">\n                <InPhrase>\n                  {context.map((field, index) => (\n                    <Fragment key={field.id}>\n                      {index > 0 && \" · \"}\n                      <FieldValue\n                        field={field}\n                        value={target.values[field.id]}\n                      />\n                    </Fragment>\n                  ))}\n                </InPhrase>\n              </p>\n            )\n          }\n          header={\n            patchAction && (\n              <Button\n                render={\n                  <a\n                    href={`#${requestRoute(entities, routes.editRequest(view.id), request.id)}`}\n                  />\n                }\n                variant=\"outline\"\n              >\n                {pages.editDraft}\n              </Button>\n            )\n          }\n          task={task}\n          submit={(action: RecordActionReference, reason: string) =>\n            task.submit(\n              recordTask(\n                action,\n                { entity: view.entity, id: view.id },\n                {\n                  expectedRevision: view.revision,\n                  // Only an apply carries the optional reason; BReg bounds it.\n                  ...(action.action === \"apply\" && reason.trim()\n                    ? { body: { reason } }\n                    : {}),\n                },\n              ),\n            )\n          }\n          refetch={refetch}\n          announce={announce}\n          choiceLabel={(action) => choiceLabel(action, pages)}\n          openerLabel={(action) => openerLabel(action, pages)}\n          reconcileHref={`#${queuePath}`}\n          renderError={(error) => <ErrorPanel error={error} />}\n          refreshing={refreshing || writingAttachments.size > 0}\n          decidedBody={(action) =>\n            action?.action === \"apply\" || state === \"applied\"\n              ? pages.decidedAppliedBody\n              : pages.decidedBody\n          }\n        />\n      )}\n    </>\n  );\n}\n",
      "type": "registry:block",
      "target": "@components/pages/request-detail-page.tsx"
    }
  ],
  "type": "registry:block"
}