Skip to content

armgit / ui

Public Imported from GitHub
0
TypeScript
153 KB
Raw Blame
"use client"

import * as React from "react"
import {
  DataEditor,
  emptyGridSelection,
  GridCellKind,
  TextCellEntry,
  type EditableGridCell,
  type GridCell,
  type GridColumn,
  type GridMouseEventArgs,
  type GridSelection,
  type Item,
  type NumberCell,
  type ProvideEditorComponent,
  type Rectangle,
  type TextCell,
  type Theme,
} from "@glideapps/glide-data-grid"
import {
  ArrowLeft01Icon,
  CancelCircleIcon,
  InputNumericIcon,
  InputTextIcon,
  SecondBracketIcon,
  SourceCodeSquareIcon,
  TextCheckIcon,
  Undo02Icon,
} from "@hugeicons/core-free-icons"
import { HugeiconsIcon } from "@hugeicons/react"
import { Virtualizer as DiffsVirtualizer } from "@pierre/diffs"
import {
  File,
  MultiFileDiff,
  VirtualizerContext,
  WorkerPoolContextProvider,
  type VirtualFileMetrics,
  type WorkerInitializationRenderOptions,
  type WorkerPoolOptions,
} from "@pierre/diffs/react"
import { useTheme } from "next-themes"
import { flushSync } from "react-dom"

import { cn } from "@/lib/utils"
import { withUiBasePath } from "@/lib/zone-path"
import { useMounted } from "@/hooks/use-mounted"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { ScrollArea } from "@/components/ui/scroll-area"
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"
import {
  Tooltip,
  TooltipContent,
  TooltipProvider,
  TooltipTrigger,
} from "@/components/ui/tooltip"
import {
  DocsSourceCodeBlock,
  DocsViewCodeBlock,
} from "@/components/docs-code-block"
import { PdfBlockResizableShell } from "@/components/extend/pdf-block-resizable-shell"
import { PDFViewer, type PDFViewerHandle } from "@/components/extend/pdf-viewer"

import blockReviewOutput from "./bounding-box-citations-block-output.json"

import "@glideapps/glide-data-grid/dist/index.css"

type JsonPrimitive = string | number | boolean | null
type JsonValue = JsonPrimitive | JsonObject | JsonArray
type JsonObject = { [key: string]: JsonValue }
type JsonArray = JsonValue[]
type SchemaPropertyType =
  | "string"
  | "number"
  | "integer"
  | "boolean"
  | "object"
  | "array"

type ReviewFieldSchema = {
  type: SchemaPropertyType
  title?: string
  description?: string
  enum?: Array<string | number>
  properties?: Record<string, ReviewFieldSchema>
  items?: ReviewFieldSchema
}

type ReviewFieldDefinition = {
  key: string
  schema: ReviewFieldSchema
  actual: JsonValue
  expected: JsonValue
  location?: ReviewLocation
  metadataPath?: string
}

type HighlightArea = {
  left: number
  top: number
  width: number
  height: number
}

type ReviewLocation = {
  page: number
  area: HighlightArea
}

type HumanReviewBlockTransaction = {
  date: string
  amount: number
  category: string
  description: string
  merchant?: {
    name: string
    city: string
    risk_level: string
  }
  tags?: string[]
}

type HumanReviewBlockOutput = {
  transactions: HumanReviewBlockTransaction[]
  ending_balance: number | null
  account_details: {
    holder_name: string | null
    account_type: string | null
    account_last_four: string | null
    mailing_address?: {
      line_1: string
      city: string
      state: string
    }
    linked_accounts?: Array<{
      nickname: string
      last_four: string
    }>
  }
  statement_period: string
  overdraft_protection_enabled: boolean | null
}

type HumanReviewBlockCitation = {
  page: number
  polygon?: Array<{ x: number; y: number }>
  pageWidth: number
  pageHeight: number
  referenceText?: string
}

type HumanReviewBlockMetadataEntry = {
  citations?: HumanReviewBlockCitation[]
}

type HumanReviewBlockRawOutput = {
  value: HumanReviewBlockOutput
  metadata: Record<string, HumanReviewBlockMetadataEntry>
}

function ScrollAreaVirtualizer({
  children,
  className,
  contentClassName,
  contentStyle,
  scrollFade = true,
}: {
  children: React.ReactNode
  className?: string
  contentClassName?: string
  contentStyle?: React.CSSProperties
  scrollFade?: boolean
}) {
  const [virtualizer] = React.useState(() =>
    typeof window !== "undefined" ? new DiffsVirtualizer() : undefined
  )
  const viewportRef = React.useRef<HTMLDivElement | null>(null)
  const contentRef = React.useRef<HTMLDivElement | null>(null)
  const syncVirtualizer = React.useCallback(() => {
    if (!virtualizer) return

    const viewport = viewportRef.current
    const content = contentRef.current

    if (viewport && content) {
      virtualizer.setup(viewport, content)
      return
    }

    virtualizer.cleanUp()
  }, [virtualizer])
  const setViewportRef = React.useCallback(
    (node: HTMLDivElement | null) => {
      viewportRef.current = node
      syncVirtualizer()
    },
    [syncVirtualizer]
  )
  const setContentRef = React.useCallback(
    (node: HTMLDivElement | null) => {
      contentRef.current = node
      syncVirtualizer()
    },
    [syncVirtualizer]
  )

  React.useEffect(() => {
    return () => virtualizer?.cleanUp()
  }, [virtualizer])

  return (
    <VirtualizerContext.Provider value={virtualizer}>
      <ScrollArea
        className={className}
        scrollFade={scrollFade}
        scrollbarOverflowOnly
        viewportRef={setViewportRef}
      >
        <div
          ref={setContentRef}
          className={contentClassName}
          style={contentStyle}
        >
          {children}
        </div>
      </ScrollArea>
    </VirtualizerContext.Provider>
  )
}

const PDF_URL = withUiBasePath("/samples/attention.pdf")
const BLOCK_REVIEW_PDF_URL = withUiBasePath(
  "/samples/bank-statement-x4uhhi7t.pdf"
)
const DEFAULT_ZOOM = 1
const REVIEW_HIGHLIGHT_STYLE =
  "border-blue-500/70 bg-blue-500/12 shadow-[0_4px_16px_rgb(59_130_246_/_10%)]"

const CODE_FILE_THEME = {
  "--diffs-light-bg": "var(--color-code)",
  "--diffs-dark-bg": "var(--color-code)",
  "--diffs-light": "var(--color-code-foreground)",
  "--diffs-dark": "var(--color-code-foreground)",
  "--diffs-bg-context-override": "var(--color-code)",
  "--diffs-bg-context-gutter-override": "var(--color-code)",
  "--diffs-bg-buffer-override": "var(--color-code)",
  "--diffs-fg-number-override": "var(--color-muted-foreground)",
  "--diffs-font-size": "0.8rem",
  "--diffs-line-height": "1.625",
} as React.CSSProperties

const CODE_FONT_SIZE_PX = 12.8
const CODE_LINE_HEIGHT_PX = CODE_FONT_SIZE_PX * 1.625

const CODE_VIRTUAL_FILE_METRICS = {
  hunkLineCount: 50,
  lineHeight: CODE_LINE_HEIGHT_PX,
  diffHeaderHeight: 44,
  spacing: 8,
  paddingTop: 0,
  paddingBottom: 8,
} satisfies VirtualFileMetrics

const CODE_HIGHLIGHTER_OPTIONS = {
  theme: {
    light: "pierre-light-soft",
    dark: "pierre-dark-soft",
  },
  langs: ["json"],
} satisfies WorkerInitializationRenderOptions

const CODE_WORKER_POOL_OPTIONS = {
  poolSize: 2,
  workerFactory: () =>
    new Worker(new URL("@pierre/diffs/worker/worker.js", import.meta.url), {
      type: "module",
    }),
} satisfies WorkerPoolOptions

function readIsDarkTheme() {
  return (
    typeof document !== "undefined" &&
    document.documentElement.classList.contains("dark")
  )
}

// Share one observer across the paired array grids. The form can keep its
// tab mounted now, so avoiding per-grid observers keeps tab switches cheap.
const darkThemeListeners = new Set<(isDark: boolean) => void>()
let darkThemeObserver: MutationObserver | null = null
let sharedIsDarkTheme = false

function ensureDarkThemeObserver() {
  if (
    darkThemeObserver ||
    typeof document === "undefined" ||
    typeof MutationObserver === "undefined"
  ) {
    return
  }

  sharedIsDarkTheme = readIsDarkTheme()
  darkThemeObserver = new MutationObserver(() => {
    const nextIsDark = readIsDarkTheme()
    if (nextIsDark === sharedIsDarkTheme) return

    sharedIsDarkTheme = nextIsDark
    darkThemeListeners.forEach((listener) => listener(nextIsDark))
  })
  darkThemeObserver.observe(document.documentElement, {
    attributes: true,
    attributeFilter: ["class"],
  })
}

function subscribeToDarkTheme(listener: () => void) {
  ensureDarkThemeObserver()
  darkThemeListeners.add(listener)
  return () => {
    darkThemeListeners.delete(listener)
    if (darkThemeListeners.size === 0 && darkThemeObserver) {
      darkThemeObserver.disconnect()
      darkThemeObserver = null
    }
  }
}

function useIsDarkTheme() {
  return React.useSyncExternalStore(
    subscribeToDarkTheme,
    readIsDarkTheme,
    () => false
  )
}

function useHumanReviewGridTheme() {
  const isDark = useIsDarkTheme()

  return React.useMemo<Partial<Theme>>(
    () => ({
      accentColor: isDark ? "rgb(96, 165, 250)" : "rgb(37, 99, 235)",
      accentLight: isDark ? "rgba(29, 78, 216, 0.15)" : "rgb(219, 234, 254)",
      accentFg: "rgb(255, 255, 255)",
      textDark: isDark ? "rgb(229, 229, 229)" : "rgb(23, 23, 23)",
      textMedium: isDark ? "rgb(163, 163, 163)" : "rgb(82, 82, 82)",
      textLight: isDark ? "rgb(115, 115, 115)" : "rgb(163, 163, 163)",
      textBubble: isDark ? "rgb(245, 245, 245)" : "rgb(23, 23, 23)",
      textHeader: isDark ? "rgb(245, 245, 245)" : "rgb(23, 23, 23)",
      textGroupHeader: isDark ? "rgb(163, 163, 163)" : "rgb(82, 82, 82)",
      bgCell: isDark ? "rgb(10, 10, 10)" : "rgb(255, 255, 255)",
      bgCellMedium: isDark ? "rgb(23, 23, 23)" : "rgb(250, 250, 250)",
      bgHeader: isDark ? "rgb(23, 23, 23)" : "rgb(250, 250, 250)",
      bgHeaderHasFocus: isDark ? "rgb(38, 38, 38)" : "rgb(245, 245, 245)",
      bgHeaderHovered: isDark ? "rgb(38, 38, 38)" : "rgb(245, 245, 245)",
      borderColor: isDark ? "rgb(38, 38, 38)" : "rgb(229, 229, 229)",
      horizontalBorderColor: isDark ? "rgb(38, 38, 38)" : "rgb(229, 229, 229)",
      cellHorizontalPadding: 8,
      cellVerticalPadding: 3,
      headerIconSize: 18,
      baseFontStyle: "13px",
      headerFontStyle: "600 13px",
      markerFontStyle: "11px",
      fontFamily: '-apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif',
      editorFontSize: "13px",
    }),
    [isDark]
  )
}

const REVIEW_SCHEMA: ReviewFieldDefinition[] = [
  {
    key: "statement_period",
    schema: {
      type: "string",
      title: "Statement period",
      description: "Date range covered by the bank statement.",
    },
    actual: "Jan 1-31, 2026",
    expected: "January 1-31, 2026",
    location: {
      page: 1,
      area: { left: 31, top: 30, width: 40, height: 5.8 },
    },
  },
  {
    key: "transactions",
    schema: {
      type: "array",
      title: "Transactions",
      description: "Posted account activity during the statement period.",
      items: {
        type: "object",
        properties: {
          date: {
            type: "string",
            title: "Date",
          },
          description: {
            type: "string",
            title: "Description",
          },
          amount: {
            type: "number",
            title: "Amount",
          },
          category: {
            type: "string",
            title: "Category",
          },
          merchant: {
            type: "object",
            title: "Merchant",
            properties: {
              name: {
                type: "string",
                title: "Name",
              },
              city: {
                type: "string",
                title: "City",
              },
              risk_level: {
                type: "string",
                title: "Risk level",
              },
            },
          },
          tags: {
            type: "array",
            title: "Tags",
            items: {
              type: "string",
              title: "Tag",
            },
          },
        },
      },
    },
    actual: [
      {
        date: "2026-01-03",
        description: "ACH CREDIT PAYROLL",
        amount: 4250,
        category: "Deposit",
        merchant: {
          name: "Acme Payroll",
          city: "New York",
          risk_level: "low",
        },
        tags: ["payroll", "recurring"],
      },
      {
        date: "2026-01-12",
        description: "POS PURCHASE GROCERY MART",
        amount: -86.42,
        category: "Debit",
        merchant: {
          name: "Grocery Mart",
          city: "Brooklyn",
          risk_level: "medium",
        },
        tags: ["card", "groceries"],
      },
    ],
    expected: [
      {
        date: "2026-01-03",
        description: "ACH CREDIT PAYROLL",
        amount: 4250,
        category: "Deposit",
        merchant: {
          name: "Acme Payroll",
          city: "New York",
          risk_level: "low",
        },
        tags: ["payroll", "recurring"],
      },
      {
        date: "2026-01-12",
        description: "POS PURCHASE GROCERY MART",
        amount: -68.42,
        category: "Debit",
        merchant: {
          name: "Grocery Mart",
          city: "Brooklyn",
          risk_level: "low",
        },
        tags: ["card", "groceries", "needs_review"],
      },
    ],
    location: {
      page: 1,
      area: { left: 13.5, top: 66, width: 73.5, height: 7.5 },
    },
  },
  {
    key: "ending_balance",
    schema: {
      type: "number",
      title: "Ending balance",
      description: "Final account balance at the end of the statement period.",
    },
    actual: 12840.18,
    expected: 12858.18,
    location: {
      page: 1,
      area: { left: 13.5, top: 66, width: 73.5, height: 7.5 },
    },
  },
  {
    key: "overdraft_protection_enabled",
    schema: {
      type: "boolean",
      title: "Overdraft protection enabled",
      description: "Whether overdraft protection is enabled for the account.",
    },
    actual: false,
    expected: true,
    location: {
      page: 2,
      area: { left: 9.5, top: 12, width: 81, height: 11.5 },
    },
  },
  {
    key: "account_details",
    schema: {
      type: "object",
      title: "Account details",
      description: "Account owner and identifying details from the statement.",
      properties: {
        holder_name: {
          type: "string",
          title: "Holder name",
        },
        account_last_four: {
          type: "string",
          title: "Account last four",
        },
        account_type: {
          type: "string",
          title: "Account type",
        },
        mailing_address: {
          type: "object",
          title: "Mailing address",
          properties: {
            line_1: {
              type: "string",
              title: "Line 1",
            },
            city: {
              type: "string",
              title: "City",
            },
            state: {
              type: "string",
              title: "State",
            },
          },
        },
        linked_accounts: {
          type: "array",
          title: "Linked accounts",
          items: {
            type: "object",
            properties: {
              nickname: {
                type: "string",
                title: "Nickname",
              },
              last_four: {
                type: "string",
                title: "Last four",
              },
            },
          },
        },
      },
    },
    actual: {
      holder_name: "Jordan Lee",
      account_last_four: "4821",
      account_type: "Checking",
      mailing_address: {
        line_1: "42 Market Street",
        city: "Brooklyn",
        state: "NY",
      },
      linked_accounts: [
        {
          nickname: "Operations reserve",
          last_four: "1842",
        },
      ],
    },
    expected: {
      holder_name: "Jordan Lee",
      account_last_four: "4821",
      account_type: "Premier Checking",
      mailing_address: {
        line_1: "42 Market Street",
        city: "New York",
        state: "NY",
      },
      linked_accounts: [
        {
          nickname: "Operations reserve",
          last_four: "1842",
        },
        {
          nickname: "Payroll sweep",
          last_four: "9174",
        },
      ],
    },
  },
]

const BLOCK_REVIEW_OUTPUT = blockReviewOutput as HumanReviewBlockRawOutput
const BLOCK_REVIEW_EXPECTED_OUTPUT = BLOCK_REVIEW_OUTPUT.value
const BLOCK_REVIEW_METADATA = BLOCK_REVIEW_OUTPUT.metadata
const BLOCK_REVIEW_FIRST_INCLUDED_SOURCE_PAGE = 1
const BLOCK_REVIEW_LAST_INCLUDED_SOURCE_PAGE = 1

function addNestedTransactionSamples(
  transactions: HumanReviewBlockTransaction[]
) {
  return transactions.map((transaction, index) => ({
    ...transaction,
    merchant: {
      name: transaction.description,
      city: index % 2 === 0 ? "San Francisco" : "New York",
      risk_level: index % 3 === 0 ? "review" : "low",
    },
    tags:
      index % 2 === 0
        ? ["posted", "statement"]
        : ["card", "retail", "statement"],
  }))
}

const BLOCK_REVIEW_EXPECTED_TRANSACTIONS = addNestedTransactionSamples(
  BLOCK_REVIEW_EXPECTED_OUTPUT.transactions
)

const BLOCK_REVIEW_EXPECTED_ACCOUNT_DETAILS = {
  ...BLOCK_REVIEW_EXPECTED_OUTPUT.account_details,
  mailing_address: {
    line_1: "270 Park Avenue",
    city: "New York",
    state: "NY",
  },
  linked_accounts: [
    {
      nickname: "Operating account",
      last_four: "8221",
    },
    {
      nickname: "Payroll reserve",
      last_four: "1294",
    },
  ],
}

function getBlockReviewPdfPage(sourcePage: number) {
  if (
    sourcePage < BLOCK_REVIEW_FIRST_INCLUDED_SOURCE_PAGE ||
    sourcePage > BLOCK_REVIEW_LAST_INCLUDED_SOURCE_PAGE
  ) {
    return undefined
  }

  return sourcePage - BLOCK_REVIEW_FIRST_INCLUDED_SOURCE_PAGE + 1
}

function getCitationLocation(
  citation: HumanReviewBlockCitation
): ReviewLocation | undefined {
  const polygon = citation.polygon
  if (!polygon?.length || !citation.pageWidth || !citation.pageHeight) {
    return undefined
  }

  const xs = polygon.map((point) => point.x)
  const ys = polygon.map((point) => point.y)
  const left = Math.min(...xs)
  const top = Math.min(...ys)
  const right = Math.max(...xs)
  const bottom = Math.max(...ys)

  return {
    page: citation.page,
    area: {
      left: (left / citation.pageWidth) * 100,
      top: (top / citation.pageHeight) * 100,
      width: ((right - left) / citation.pageWidth) * 100,
      height: ((bottom - top) / citation.pageHeight) * 100,
    },
  }
}

function normalizeCitationSearchText(value: unknown) {
  return String(value ?? "")
    .toLowerCase()
    .replace(/[^a-z0-9]+/g, " ")
    .trim()
}

function getTransactionDateSearchText(value: unknown) {
  if (typeof value !== "string") return null

  const match = value.match(/^(\d{4})-(\d{2})-(\d{2})$/)
  return match ? `${match[2]} ${match[3]}` : normalizeCitationSearchText(value)
}

function getNumberSearchTexts(value: unknown) {
  if (typeof value !== "number") return []

  const absoluteValue = Math.abs(value)

  return [
    absoluteValue.toString(),
    absoluteValue.toFixed(2),
    absoluteValue.toLocaleString("en-US", {
      minimumFractionDigits: 2,
      maximumFractionDigits: 2,
    }),
  ].map(normalizeCitationSearchText)
}

function citationMatchesTransaction(
  citation: HumanReviewBlockCitation | undefined,
  transaction: JsonValue
) {
  if (!citation?.referenceText || !isJsonObject(transaction)) return false

  const referenceText = normalizeCitationSearchText(citation.referenceText)
  const dateText = getTransactionDateSearchText(transaction.date)
  const descriptionText = normalizeCitationSearchText(transaction.description)
    .split(" ")
    .slice(0, 4)
    .join(" ")
  const amountTexts = getNumberSearchTexts(transaction.amount)

  return (
    Boolean(dateText && referenceText.includes(dateText)) &&
    Boolean(descriptionText && referenceText.includes(descriptionText)) &&
    amountTexts.some((amountText) => referenceText.includes(amountText))
  )
}

function resolveBlockReviewArrayItemMetadataPath(
  metadataPath: string,
  rowIndex: number,
  rowValue: JsonValue
) {
  if (metadataPath !== "transactions") return `${metadataPath}[${rowIndex}]`

  const rowMetadataPath = `${metadataPath}[${rowIndex}]`
  const rowCitation = BLOCK_REVIEW_METADATA[rowMetadataPath]?.citations?.find(
    (candidate) => candidate.polygon?.length
  )

  if (citationMatchesTransaction(rowCitation, rowValue)) {
    return rowMetadataPath
  }

  const matchedEntry = Object.entries(BLOCK_REVIEW_METADATA).find(
    ([candidatePath, entry]) =>
      candidatePath.startsWith(`${metadataPath}[`) &&
      !candidatePath.includes(".") &&
      citationMatchesTransaction(
        entry.citations?.find((candidate) => candidate.polygon?.length),
        rowValue
      )
  )

  return matchedEntry?.[0]
}

function getBlockReviewLocation(metadataPath: string | undefined) {
  if (!metadataPath) return undefined

  const citation = BLOCK_REVIEW_METADATA[metadataPath]?.citations?.find(
    (candidate) => candidate.polygon?.length
  )
  const localPage = citation ? getBlockReviewPdfPage(citation.page) : undefined

  if (!citation || localPage === undefined) return undefined

  const location = getCitationLocation(citation)

  return location ? { ...location, page: localPage } : undefined
}

function getReviewFieldLocation(
  field: ReviewFieldDefinition | undefined,
  resolveLocation?: (metadataPath: string) => ReviewLocation | undefined
) {
  if (!field) return undefined

  return (
    field.location ??
    resolveLocation?.(field.metadataPath ?? field.key) ??
    undefined
  )
}

function getReviewLocationKey(location: ReviewLocation | undefined) {
  if (!location) return null

  const { area } = location
  return [location.page, area.left, area.top, area.width, area.height].join(":")
}

const BLOCK_REVIEW_ACTUAL_OUTPUT = {
  ...BLOCK_REVIEW_EXPECTED_OUTPUT,
  transactions: BLOCK_REVIEW_EXPECTED_TRANSACTIONS.map((transaction, index) => {
    if (index === 0) {
      return {
        ...transaction,
        category: "Card Activity",
        merchant: {
          ...transaction.merchant,
          risk_level: "medium",
        },
        tags: ["posted", "card_activity"],
      }
    }

    if (index === 15) {
      return {
        ...transaction,
        category: "Retail Spend",
        merchant: {
          ...transaction.merchant,
          city: "San Jose",
        },
        tags: ["card", "retail", "needs_review"],
      }
    }

    if (index === 28) {
      return {
        ...transaction,
        category: "Food & Dining",
        merchant: {
          ...transaction.merchant,
          risk_level: "review",
        },
      }
    }

    return transaction
  }),
  account_details: {
    ...BLOCK_REVIEW_EXPECTED_ACCOUNT_DETAILS,
    account_type: "Chase Business Checking",
    mailing_address: {
      ...BLOCK_REVIEW_EXPECTED_ACCOUNT_DETAILS.mailing_address,
      city: "Brooklyn",
    },
    linked_accounts: [
      ...BLOCK_REVIEW_EXPECTED_ACCOUNT_DETAILS.linked_accounts,
      {
        nickname: "Tax savings",
        last_four: "4402",
      },
    ],
  },
  statement_period: "Oct 01-31, 2021",
  overdraft_protection_enabled: false,
} satisfies HumanReviewBlockOutput

const BLOCK_REVIEW_SCHEMA: ReviewFieldDefinition[] = [
  {
    key: "transactions",
    schema: {
      type: "array",
      title: "Transactions",
      description: "Posted account activity during the statement period.",
      items: {
        type: "object",
        properties: {
          date: {
            type: "string",
            title: "Date",
          },
          description: {
            type: "string",
            title: "Description",
          },
          amount: {
            type: "number",
            title: "Amount",
          },
          category: {
            type: "string",
            title: "Category",
          },
          merchant: {
            type: "object",
            title: "Merchant",
            properties: {
              name: {
                type: "string",
                title: "Name",
              },
              city: {
                type: "string",
                title: "City",
              },
              risk_level: {
                type: "string",
                title: "Risk level",
              },
            },
          },
          tags: {
            type: "array",
            title: "Tags",
            items: {
              type: "string",
              title: "Tag",
            },
          },
        },
      },
    },
    actual: BLOCK_REVIEW_ACTUAL_OUTPUT.transactions,
    expected: BLOCK_REVIEW_EXPECTED_TRANSACTIONS,
    metadataPath: "transactions",
  },
  {
    key: "account_details",
    schema: {
      type: "object",
      title: "Account details",
      description: "Account owner and identifying details from the statement.",
      properties: {
        holder_name: {
          type: "string",
          title: "Holder name",
        },
        account_type: {
          type: "string",
          title: "Account type",
        },
        account_last_four: {
          type: "string",
          title: "Account last four",
        },
        mailing_address: {
          type: "object",
          title: "Mailing address",
          properties: {
            line_1: {
              type: "string",
              title: "Line 1",
            },
            city: {
              type: "string",
              title: "City",
            },
            state: {
              type: "string",
              title: "State",
            },
          },
        },
        linked_accounts: {
          type: "array",
          title: "Linked accounts",
          items: {
            type: "object",
            properties: {
              nickname: {
                type: "string",
                title: "Nickname",
              },
              last_four: {
                type: "string",
                title: "Last four",
              },
            },
          },
        },
      },
    },
    actual: BLOCK_REVIEW_ACTUAL_OUTPUT.account_details,
    expected: BLOCK_REVIEW_EXPECTED_ACCOUNT_DETAILS,
    metadataPath: "account_details",
  },
  {
    key: "statement_period",
    schema: {
      type: "string",
      title: "Statement period",
      description: "Date range covered by the bank statement.",
    },
    actual: BLOCK_REVIEW_ACTUAL_OUTPUT.statement_period,
    expected: BLOCK_REVIEW_EXPECTED_OUTPUT.statement_period,
    metadataPath: "statement_period",
  },
  {
    key: "overdraft_protection_enabled",
    schema: {
      type: "boolean",
      title: "Overdraft protection enabled",
      description: "Whether overdraft protection is enabled for the account.",
    },
    actual: BLOCK_REVIEW_ACTUAL_OUTPUT.overdraft_protection_enabled,
    expected: BLOCK_REVIEW_EXPECTED_OUTPUT.overdraft_protection_enabled,
    metadataPath: "overdraft_protection_enabled",
  },
]

function getExpectedValues(fields: ReviewFieldDefinition[]) {
  return fields.reduce<JsonObject>((values, field) => {
    values[field.key] = field.expected
    return values
  }, {})
}

function getActualValues(fields: ReviewFieldDefinition[]) {
  return fields.reduce<JsonObject>((values, field) => {
    values[field.key] = field.actual
    return values
  }, {})
}

function formatJson(value: unknown) {
  return JSON.stringify(value, null, 2)
}

function isJsonObject(value: JsonValue): value is JsonObject {
  return typeof value === "object" && value !== null && !Array.isArray(value)
}

function isJsonArray(value: JsonValue): value is JsonArray {
  return Array.isArray(value)
}

function getObjectValue(value: JsonValue, key: string): JsonValue {
  if (!isJsonObject(value)) return null
  return value[key] ?? null
}

function setObjectValue(
  value: JsonValue,
  key: string,
  childValue: JsonValue
): JsonObject {
  return {
    ...(isJsonObject(value) ? value : {}),
    [key]: childValue,
  }
}

function getArrayValue(value: JsonValue): JsonArray {
  return isJsonArray(value) ? value : []
}

function setArrayItemValue(
  value: JsonValue,
  index: number,
  childValue: JsonValue
): JsonArray {
  const nextValue = getArrayValue(value).slice()
  nextValue[index] = childValue
  return nextValue
}

function getPrimitiveValue(value: JsonValue): JsonPrimitive {
  return isJsonObject(value) || isJsonArray(value) ? null : value
}

function jsonValuesEqual(left: JsonValue, right: JsonValue) {
  return formatJson(left) === formatJson(right)
}

function findReviewField(
  fields: ReviewFieldDefinition[],
  fieldKey: string | undefined
): ReviewFieldDefinition | undefined {
  if (!fieldKey) return undefined

  for (const field of fields) {
    if (field.key === fieldKey) return field

    if (field.schema.type === "object") {
      const childFields = Object.entries(field.schema.properties ?? {}).map(
        ([key, schema]): ReviewFieldDefinition => ({
          key: `${field.key}.${key}`,
          schema,
          actual: getObjectValue(field.actual, key),
          expected: getObjectValue(field.expected, key),
          metadataPath: `${field.metadataPath ?? field.key}.${key}`,
        })
      )
      const childField = findReviewField(childFields, fieldKey)
      if (childField) return childField
    }
  }

  return undefined
}

function formatValue(value: JsonValue) {
  if (value === null) return "NULL"
  if (isJsonObject(value) || isJsonArray(value)) return formatJson(value)
  if (typeof value === "boolean") return value ? "true" : "false"
  return String(value)
}

function areGridRangesEqual(
  left: Readonly<Rectangle> | undefined,
  right: Readonly<Rectangle> | undefined
) {
  return (
    left === right ||
    (left !== undefined &&
      right !== undefined &&
      left.x === right.x &&
      left.y === right.y &&
      left.width === right.width &&
      left.height === right.height)
  )
}

function areGridRangeStacksEqual(
  left: readonly Readonly<Rectangle>[] | undefined,
  right: readonly Readonly<Rectangle>[] | undefined
) {
  if (left === right) return true
  if (!left || !right || left.length !== right.length) return false

  return left.every((range, index) => areGridRangesEqual(range, right[index]))
}

function areGridSelectionsEqual(left: GridSelection, right: GridSelection) {
  const leftCurrent = left.current
  const rightCurrent = right.current

  return (
    leftCurrent?.cell[0] === rightCurrent?.cell[0] &&
    leftCurrent?.cell[1] === rightCurrent?.cell[1] &&
    areGridRangesEqual(leftCurrent?.range, rightCurrent?.range) &&
    areGridRangeStacksEqual(
      leftCurrent?.rangeStack,
      rightCurrent?.rangeStack
    ) &&
    left.columns.equals(right.columns) &&
    left.rows.equals(right.rows)
  )
}

function getGridSelectionRanges(selection: GridSelection | undefined) {
  const current = selection?.current
  if (!current) return []

  return [...(current.rangeStack ?? []), current.range]
}

function areArrayNestedViewsEqual(
  left: ArrayNestedView[],
  right: ArrayNestedView[]
) {
  if (left === right) return true
  if (left.length !== right.length) return false

  return left.every((view, index) => {
    const other = right[index]

    return (
      view.rowIndex === other?.rowIndex &&
      view.columnId === other.columnId &&
      view.title === other.title &&
      view.schema === other.schema &&
      Object.is(view.value, other.value)
    )
  })
}

type HumanReviewOverlayCell = TextCell | NumberCell

type HumanReviewTextOverlayEditorProps = React.ComponentProps<
  ProvideEditorComponent<HumanReviewOverlayCell>
> & {
  overlayOpenRef: React.RefObject<boolean>
  readOnly?: boolean
}

function HumanReviewTextOverlayEditor({
  isHighlighted,
  onFinishedEditing,
  overlayOpenRef,
  readOnly = false,
  validatedSelection,
  value,
}: HumanReviewTextOverlayEditorProps) {
  const initialValue =
    value.kind === GridCellKind.Number ? value.displayData : value.data
  const [entryValue, setEntryValue] = React.useState(initialValue)
  const latestValueRef = React.useRef(initialValue)
  const finishedRef = React.useRef(false)

  const finishEditing = React.useCallback(
    (
      shouldSave: boolean,
      movement: readonly [-1 | 0 | 1, -1 | 0 | 1] = [0, 0]
    ) => {
      if (finishedRef.current) return

      finishedRef.current = true
      overlayOpenRef.current = false

      if (!shouldSave || readOnly) {
        onFinishedEditing(undefined, movement)
        return
      }

      if (value.kind === GridCellKind.Number) {
        const numericValue = Number(latestValueRef.current)

        onFinishedEditing(
          {
            ...value,
            data: Number.isFinite(numericValue) ? numericValue : value.data,
            displayData: latestValueRef.current,
          },
          movement
        )
        return
      }

      onFinishedEditing(
        {
          ...value,
          data: latestValueRef.current,
          displayData: latestValueRef.current,
        },
        movement
      )
    },
    [onFinishedEditing, overlayOpenRef, readOnly, value]
  )

  const handleEntryChange = React.useCallback(
    (event: React.ChangeEvent<HTMLTextAreaElement>) => {
      event.stopPropagation()
      latestValueRef.current = event.target.value
      setEntryValue(event.target.value)
    },
    []
  )
  const handleKeyDown = React.useCallback(
    (event: React.KeyboardEvent<HTMLTextAreaElement>) => {
      event.stopPropagation()

      if (event.key === "Escape") {
        event.preventDefault()
        finishEditing(false)
        return
      }

      if (event.key === "Tab") {
        event.preventDefault()
        finishEditing(true, [event.shiftKey ? -1 : 1, 0])
        return
      }

      if (event.key === "Enter" && !event.shiftKey) {
        event.preventDefault()
        finishEditing(true, [0, 1])
      }
    },
    [finishEditing]
  )

  React.useEffect(() => {
    overlayOpenRef.current = true

    return () => {
      overlayOpenRef.current = false
    }
  }, [overlayOpenRef])

  React.useEffect(() => {
    const handlePointerOutside = (event: PointerEvent | MouseEvent) => {
      const input = document.querySelector<HTMLTextAreaElement>(".gdg-input")
      const overlayRoot = input?.closest(".gdg-clip-region")

      if (!overlayRoot || overlayRoot.contains(event.target as Node | null)) {
        return
      }

      finishEditing(true)
    }

    document.addEventListener("pointerdown", handlePointerOutside, true)
    document.addEventListener("contextmenu", handlePointerOutside, true)

    return () => {
      document.removeEventListener("pointerdown", handlePointerOutside, true)
      document.removeEventListener("contextmenu", handlePointerOutside, true)
    }
  }, [finishEditing])

  return (
    <TextCellEntry
      autoFocus={!readOnly}
      disabled={readOnly}
      highlight={isHighlighted}
      value={entryValue}
      validatedSelection={validatedSelection}
      altNewline
      onChange={handleEntryChange}
      onKeyDown={handleKeyDown}
    />
  )
}

function getFieldIcon(type: SchemaPropertyType) {
  if (type === "number" || type === "integer") return InputNumericIcon
  if (type === "boolean") return TextCheckIcon
  if (type === "array") return SecondBracketIcon
  if (type === "object") return SourceCodeSquareIcon
  return InputTextIcon
}

function HumanReviewValueInput({
  readOnly = false,
  schema,
  value,
  onChange,
}: {
  readOnly?: boolean
  schema: ReviewFieldSchema
  value: JsonPrimitive
  onChange: (value: JsonPrimitive) => void
}) {
  if (schema.enum?.length) {
    return (
      <span className="relative inline-flex w-full rounded-lg border border-input bg-background text-sm text-foreground shadow-xs/5 dark:bg-input/32">
        <select
          disabled={readOnly}
          value={value === null ? "" : String(value)}
          onChange={(event) => onChange(event.target.value)}
          className="h-8.5 w-full appearance-none rounded-[inherit] bg-transparent px-3 text-sm outline-none sm:h-7.5"
        >
          {schema.enum.map((option) => (
            <option key={String(option)} value={String(option)}>
              {String(option)}
            </option>
          ))}
        </select>
      </span>
    )
  }

  if (schema.type === "number" || schema.type === "integer") {
    return (
      <Input
        nativeInput
        readOnly={readOnly}
        type="number"
        value={value === null ? "" : String(value)}
        onChange={(event) => {
          const nextValue = event.currentTarget.value
          onChange(nextValue === "" ? null : Number(nextValue))
        }}
      />
    )
  }

  if (schema.type === "boolean") {
    return (
      <div className="grid grid-cols-2 gap-1 rounded-lg bg-muted p-0.5">
        {[true, false].map((option) => (
          <Button
            key={String(option)}
            type="button"
            size="sm"
            variant={value === option ? "outline" : "ghost"}
            className={cn(
              "h-7 shadow-none",
              value === option && "bg-background dark:bg-input"
            )}
            disabled={readOnly}
            onClick={() => onChange(option)}
          >
            {option ? "True" : "False"}
          </Button>
        ))}
      </div>
    )
  }

  return (
    <Input
      nativeInput
      readOnly={readOnly}
      value={value === null ? "" : String(value)}
      onChange={(event) => onChange(event.currentTarget.value)}
    />
  )
}

function getArrayItemSchema(schema: ReviewFieldSchema): ReviewFieldSchema {
  return schema.items ?? { type: "string" }
}

function isComplexSchema(schema: ReviewFieldSchema) {
  return schema.type === "object" || schema.type === "array"
}

function summarizeComplexValue(value: JsonValue) {
  if (isJsonArray(value)) return `${value.length} items`
  if (isJsonObject(value)) return `${Object.keys(value).length} fields`
  return formatValue(value)
}

function getCellValueForArrayColumn(
  rowValue: JsonValue,
  itemSchema: ReviewFieldSchema,
  columnId: string
) {
  if (itemSchema.type === "object") {
    return getObjectValue(rowValue, columnId)
  }

  return rowValue
}

function getCellSchemaForArrayColumn(
  itemSchema: ReviewFieldSchema,
  columnId: string
) {
  if (itemSchema.type === "object") {
    return itemSchema.properties?.[columnId] ?? { type: "string" }
  }

  return itemSchema
}

function applyPrimitiveEdit(
  schema: ReviewFieldSchema,
  value: EditableGridCell
): JsonValue | undefined {
  if (schema.type === "boolean" && value.kind === GridCellKind.Boolean) {
    return value.data
  }

  if (
    (schema.type === "number" || schema.type === "integer") &&
    value.kind === GridCellKind.Number
  ) {
    return value.data ?? null
  }

  if (value.kind === GridCellKind.Text) {
    if (schema.type === "number" || schema.type === "integer") {
      return value.data.trim() === "" ? null : Number(value.data)
    }

    return value.data
  }

  return undefined
}

type ArrayNestedView = {
  rowIndex: number
  columnId: string
  title: string
  schema: ReviewFieldSchema
  value: JsonValue
}

type ArrayReviewSide = "actual" | "expected"

type SyncedArrayNestedView = {
  activeSide: ArrayReviewSide | null
  stack: ArrayNestedView[]
}

type SyncedArraySelection = {
  activeSide: ArrayReviewSide | null
  depth: number
  gridSelection: GridSelection
}

type HumanReviewTheme = "light" | "dark"

const EMPTY_SYNCED_ARRAY_NESTED_VIEW: SyncedArrayNestedView = {
  activeSide: null,
  stack: [],
}

const EMPTY_SYNCED_ARRAY_SELECTION: SyncedArraySelection = {
  activeSide: null,
  depth: 0,
  gridSelection: emptyGridSelection,
}

function setNestedArrayValue({
  value,
  schema,
  nestedStack,
  nextNestedValue,
}: {
  value: JsonValue
  schema: ReviewFieldSchema
  nestedStack: ArrayNestedView[]
  nextNestedValue: JsonValue
}): JsonValue {
  const [currentView, ...remainingViews] = nestedStack

  if (!currentView) return nextNestedValue

  const itemSchema = getArrayItemSchema(schema)
  const rowValue = getArrayValue(value)[currentView.rowIndex] ?? null
  const cellSchema = getCellSchemaForArrayColumn(
    itemSchema,
    currentView.columnId
  )
  const currentCellValue = getCellValueForArrayColumn(
    rowValue,
    itemSchema,
    currentView.columnId
  )
  const nextCellValue: JsonValue = remainingViews.length
    ? setNestedArrayValue({
        value: currentCellValue,
        schema: cellSchema,
        nestedStack: remainingViews,
        nextNestedValue,
      })
    : nextNestedValue
  const nextRowValue: JsonValue =
    itemSchema.type === "object"
      ? setObjectValue(rowValue, currentView.columnId, nextCellValue)
      : nextCellValue

  return setArrayItemValue(value, currentView.rowIndex, nextRowValue)
}

function getNestedArrayValue({
  value,
  schema,
  nestedStack,
}: {
  value: JsonValue
  schema: ReviewFieldSchema
  nestedStack: ArrayNestedView[]
}): JsonValue {
  const [currentView, ...remainingViews] = nestedStack

  if (!currentView) return value

  const itemSchema = getArrayItemSchema(schema)
  const rowValue = getArrayValue(value)[currentView.rowIndex] ?? null
  const cellSchema = getCellSchemaForArrayColumn(
    itemSchema,
    currentView.columnId
  )
  const cellValue = getCellValueForArrayColumn(
    rowValue,
    itemSchema,
    currentView.columnId
  )

  if (!remainingViews.length) return cellValue

  return getNestedArrayValue({
    value: cellValue,
    schema: cellSchema,
    nestedStack: remainingViews,
  })
}

function HumanReviewArrayValueGrid({
  activeNestedSide = null,
  activeSelectionSide = null,
  label,
  metadataPath,
  nestedStackBaseDepth = 0,
  readOnly = false,
  schema,
  selectionDepth = 0,
  sharedGridSelection,
  sharedNestedStack,
  value,
  viewSide = "expected",
  onChange,
  onGridSelectionChange,
  onLocationHover,
  onNestedStackChange,
  resolveLocation,
  resolveArrayItemMetadataPath,
}: {
  activeNestedSide?: ArrayReviewSide | null
  activeSelectionSide?: ArrayReviewSide | null
  label: string
  nestedStackBaseDepth?: number
  readOnly?: boolean
  schema: ReviewFieldSchema
  selectionDepth?: number
  sharedGridSelection?: GridSelection
  sharedNestedStack?: ArrayNestedView[]
  value: JsonValue
  viewSide?: ArrayReviewSide
  onChange?: (value: JsonValue) => void
  onGridSelectionChange?: (
    selection: GridSelection,
    side: ArrayReviewSide,
    depth: number
  ) => void
  onLocationHover?: (location?: ReviewLocation) => void
  onNestedStackChange?: (
    stack: ArrayNestedView[],
    side: ArrayReviewSide
  ) => void
  resolveLocation?: (metadataPath: string) => ReviewLocation | undefined
  resolveArrayItemMetadataPath?: (
    metadataPath: string,
    rowIndex: number,
    rowValue: JsonValue
  ) => string | undefined
  metadataPath?: string
}) {
  const rows = getArrayValue(value)
  const itemSchema = getArrayItemSchema(schema)
  const gridTheme = useHumanReviewGridTheme()
  const isMounted = useMounted()
  const isDark = useIsDarkTheme()
  const [localNestedStack, setLocalNestedStack] = React.useState<
    ArrayNestedView[]
  >([])
  const [localGridSelection, setLocalGridSelection] =
    React.useState<GridSelection>(emptyGridSelection)
  const fastTextOverlayOpenRef = React.useRef(false)
  const nestedStack = sharedNestedStack ?? localNestedStack
  const visibleNestedStack = nestedStack.slice(nestedStackBaseDepth)
  const activeNestedView = visibleNestedStack[0] ?? null
  const activeNestedValue = activeNestedView
    ? getNestedArrayValue({
        value,
        schema,
        nestedStack: [activeNestedView],
      })
    : null
  const isActiveNestedSource =
    Boolean(activeNestedView) && activeNestedSide === viewSide
  const isMirroredNestedTarget =
    Boolean(activeNestedView) &&
    activeNestedSide !== null &&
    activeNestedSide !== viewSide
  const blueCellText = isDark ? "rgb(147, 197, 253)" : "rgb(37, 99, 235)"
  const selectedCellBackground = isDark
    ? "rgba(37, 99, 235, 0.2)"
    : "rgba(219, 234, 254, 0.85)"
  const mirroredCellBackground = isDark
    ? "rgba(167, 139, 250, 0.18)"
    : "rgba(237, 233, 254, 0.9)"
  const mirroredHighlightRegions = React.useMemo<
    React.ComponentProps<typeof DataEditor>["highlightRegions"]
  >(() => {
    if (
      !activeSelectionSide ||
      activeSelectionSide === viewSide ||
      selectionDepth !== nestedStackBaseDepth
    ) {
      return undefined
    }

    const ranges = getGridSelectionRanges(sharedGridSelection)
    if (!ranges.length) return undefined

    return ranges.map((range) => ({
      color: mirroredCellBackground,
      range,
      style: "dashed" as const,
    }))
  }, [
    activeSelectionSide,
    mirroredCellBackground,
    nestedStackBaseDepth,
    selectionDepth,
    sharedGridSelection,
    viewSide,
  ])

  const setNestedStack = React.useCallback(
    (
      updater:
        | ArrayNestedView[]
        | ((current: ArrayNestedView[]) => ArrayNestedView[])
    ) => {
      if (onNestedStackChange) {
        const nextStack =
          typeof updater === "function" ? updater(nestedStack) : updater

        onNestedStackChange(nextStack, viewSide)
        return
      }

      setLocalNestedStack(updater)
    },
    [nestedStack, onNestedStackChange, viewSide]
  )

  const handleGridSelectionChange = React.useCallback(
    (selection: GridSelection) => {
      flushSync(() => {
        setLocalGridSelection((current) =>
          areGridSelectionsEqual(current, selection) ? current : selection
        )
      })

      if (onGridSelectionChange) {
        if (
          activeSelectionSide === viewSide &&
          sharedGridSelection &&
          areGridSelectionsEqual(sharedGridSelection, selection)
        ) {
          return
        }

        React.startTransition(() => {
          onGridSelectionChange(selection, viewSide, nestedStackBaseDepth)
        })
        return
      }
    },
    [
      activeSelectionSide,
      nestedStackBaseDepth,
      onGridSelectionChange,
      sharedGridSelection,
      viewSide,
    ]
  )

  const columns = React.useMemo<GridColumn[]>(() => {
    if (itemSchema.type === "object") {
      const propertyEntries = Object.entries(itemSchema.properties ?? {})

      if (propertyEntries.length) {
        return propertyEntries.map(([key, propertySchema]) => ({
          id: key,
          title: propertySchema.title ?? key,
          width: isComplexSchema(propertySchema) ? 148 : 132,
        }))
      }
    }

    return [
      {
        id: "value",
        title: itemSchema.title ?? "Value",
        width: isComplexSchema(itemSchema) ? 148 : 180,
      },
    ]
  }, [itemSchema])

  const getCellContent = React.useCallback(
    ([col, row]: Item): GridCell => {
      const column = columns[col]
      const columnId = String(column?.id ?? "value")
      const rowValue = rows[row] ?? null
      const cellSchema = getCellSchemaForArrayColumn(itemSchema, columnId)
      const cellValue = getCellValueForArrayColumn(
        rowValue,
        itemSchema,
        columnId
      )
      const matchedNestedCell =
        activeNestedView?.rowIndex === row &&
        activeNestedView.columnId === columnId
      const nestedCellTheme: Partial<Theme> | undefined = matchedNestedCell
        ? {
            bgCell: isMirroredNestedTarget
              ? mirroredCellBackground
              : selectedCellBackground,
            textDark: blueCellText,
          }
        : undefined

      if (isComplexSchema(cellSchema)) {
        return {
          kind: GridCellKind.Text,
          data: summarizeComplexValue(cellValue),
          displayData: summarizeComplexValue(cellValue),
          allowOverlay: false,
          readonly: true,
          cursor: "pointer",
          activationBehaviorOverride: "double-click",
          themeOverride: {
            textDark: blueCellText,
            ...(nestedCellTheme ?? {}),
          },
        }
      }

      if (cellSchema.type === "boolean") {
        return {
          kind: GridCellKind.Boolean,
          data: typeof cellValue === "boolean" ? cellValue : false,
          allowOverlay: false,
          readonly: readOnly,
        }
      }

      if (cellSchema.type === "number" || cellSchema.type === "integer") {
        return {
          kind: GridCellKind.Number,
          data: typeof cellValue === "number" ? cellValue : undefined,
          displayData: typeof cellValue === "number" ? String(cellValue) : "",
          allowOverlay: true,
          readonly: false,
        }
      }

      return {
        kind: GridCellKind.Text,
        data:
          cellValue === null ||
          isJsonObject(cellValue) ||
          isJsonArray(cellValue)
            ? ""
            : String(cellValue),
        displayData:
          cellValue === null ||
          isJsonObject(cellValue) ||
          isJsonArray(cellValue)
            ? ""
            : String(cellValue),
        allowOverlay: true,
        readonly: false,
      }
    },
    [
      activeNestedView,
      blueCellText,
      columns,
      isMirroredNestedTarget,
      itemSchema,
      mirroredCellBackground,
      readOnly,
      rows,
      selectedCellBackground,
    ]
  )

  const updateCellValue = React.useCallback(
    ([col, row]: Item, nextCell: EditableGridCell) => {
      if (readOnly || !onChange) return

      const column = columns[col]
      const columnId = String(column?.id ?? "value")
      const rowValue = rows[row] ?? null
      const cellSchema = getCellSchemaForArrayColumn(itemSchema, columnId)
      const nextValue = applyPrimitiveEdit(cellSchema, nextCell)

      if (nextValue === undefined) return

      const nextRowValue =
        itemSchema.type === "object"
          ? setObjectValue(rowValue, columnId, nextValue)
          : nextValue

      onChange(setArrayItemValue(value, row, nextRowValue))
    },
    [columns, itemSchema, onChange, readOnly, rows, value]
  )
  const provideEditor = React.useCallback<
    NonNullable<React.ComponentProps<typeof DataEditor>["provideEditor"]>
  >(
    (cell) => {
      if (
        cell.kind !== GridCellKind.Text &&
        cell.kind !== GridCellKind.Number
      ) {
        return undefined
      }

      return {
        editor: (props) => {
          if (
            props.value.kind !== GridCellKind.Text &&
            props.value.kind !== GridCellKind.Number
          ) {
            return null
          }

          return (
            <HumanReviewTextOverlayEditor
              {...(props as React.ComponentProps<
                ProvideEditorComponent<HumanReviewOverlayCell>
              >)}
              overlayOpenRef={fastTextOverlayOpenRef}
              readOnly={readOnly}
            />
          )
        },
      }
    },
    [readOnly]
  )
  const handleOutsideClick = React.useCallback(
    () => !fastTextOverlayOpenRef.current,
    []
  )
  const handleItemHovered = React.useCallback(
    (args: GridMouseEventArgs) => {
      if (!onLocationHover || !resolveLocation || !metadataPath) return

      if (args.kind !== "cell") {
        onLocationHover(undefined)
        return
      }

      const [col, row] = args.location
      const column = columns[col]
      const rowValue = rows[row]
      if (!column || rowValue === undefined) {
        onLocationHover(undefined)
        return
      }

      const columnId = String(column.id ?? "value")
      const rowMetadataPath = resolveArrayItemMetadataPath
        ? resolveArrayItemMetadataPath(metadataPath, row, rowValue)
        : `${metadataPath}[${row}]`
      if (!rowMetadataPath) {
        onLocationHover(undefined)
        return
      }

      const propertyMetadataPath =
        itemSchema.type === "object"
          ? `${rowMetadataPath}.${columnId}`
          : rowMetadataPath

      onLocationHover(
        resolveLocation(propertyMetadataPath) ??
          resolveLocation(rowMetadataPath)
      )
    },
    [
      columns,
      itemSchema.type,
      metadataPath,
      onLocationHover,
      resolveArrayItemMetadataPath,
      resolveLocation,
      rows,
    ]
  )

  const openNestedCell = React.useCallback(
    ([col, row]: Item) => {
      const column = columns[col]
      const columnId = String(column?.id ?? "value")
      const rowValue = rows[row] ?? null
      const cellSchema = getCellSchemaForArrayColumn(itemSchema, columnId)

      if (!isComplexSchema(cellSchema)) return

      setNestedStack((current) => {
        const nextView = {
          rowIndex: row,
          columnId,
          title: `${column?.title ?? columnId} / row ${row + 1}`,
          schema: cellSchema,
          value: getCellValueForArrayColumn(rowValue, itemSchema, columnId),
        }
        const currentView = current[nestedStackBaseDepth]

        if (
          currentView?.rowIndex === nextView.rowIndex &&
          currentView.columnId === nextView.columnId
        ) {
          return current
        }

        return [...current.slice(0, nestedStackBaseDepth), nextView]
      })
    },
    [columns, itemSchema, nestedStackBaseDepth, rows, setNestedStack]
  )

  const updateNestedValue = React.useCallback(
    (nextNestedValue: JsonValue) => {
      if (!activeNestedView || readOnly || !onChange) return

      onChange(
        setNestedArrayValue({
          value,
          schema,
          nestedStack: visibleNestedStack.slice(0, 1),
          nextNestedValue,
        })
      )
      setNestedStack((current) =>
        current.map((view, index) =>
          index === nestedStackBaseDepth
            ? { ...view, value: nextNestedValue }
            : view
        )
      )
    },
    [
      activeNestedView,
      nestedStackBaseDepth,
      onChange,
      readOnly,
      schema,
      setNestedStack,
      value,
      visibleNestedStack,
    ]
  )

  return (
    <div
      onMouseLeave={() => onLocationHover?.(undefined)}
      className={cn(
        "relative overflow-hidden rounded-md border bg-background transition-[border-color,background-color,box-shadow] focus-within:border-blue-500/50 focus-within:shadow-[0_0_0_1px_rgb(59_130_246_/_8%)] hover:border-blue-500/50",
        isActiveNestedSource &&
          "border-blue-500/60 bg-blue-500/5 shadow-[0_0_0_1px_rgb(59_130_246_/_10%)]"
      )}
    >
      <div>
        <div className="flex h-8 items-center justify-between gap-2 border-b px-2 text-[11px] font-medium text-muted-foreground">
          <span>{label}</span>
          <span>{rows.length} rows</span>
        </div>
        <div className="h-[220px]">
          {isMounted ? (
            <DataEditor
              columns={columns}
              rows={rows.length}
              getCellContent={getCellContent}
              cellActivationBehavior="double-click"
              gridSelection={localGridSelection}
              highlightRegions={mirroredHighlightRegions}
              onCellEdited={updateCellValue}
              onCellActivated={openNestedCell}
              onGridSelectionChange={handleGridSelectionChange}
              onItemHovered={handleItemHovered}
              provideEditor={provideEditor}
              isOutsideClick={handleOutsideClick}
              rowMarkers="number"
              smoothScrollX
              smoothScrollY
              theme={gridTheme}
              width="100%"
              height="100%"
              rowHeight={32}
              headerHeight={34}
            />
          ) : (
            <div className="h-full bg-muted/20" />
          )}
        </div>
      </div>
      {activeNestedView ? (
        <div className="absolute inset-0 z-10 flex flex-col bg-background">
          <div className="flex h-8 items-center gap-2 border-b px-2">
            <Button
              type="button"
              variant="ghost"
              size="icon-sm"
              className="size-6 text-muted-foreground"
              onClick={() =>
                setNestedStack((current) =>
                  current.slice(
                    0,
                    Math.max(nestedStackBaseDepth, current.length - 1)
                  )
                )
              }
              aria-label="Back to parent array"
            >
              <HugeiconsIcon icon={ArrowLeft01Icon} className="size-3.5" />
            </Button>
            <div className="min-w-0 flex-1 truncate text-xs font-medium text-foreground">
              {activeNestedView.title}
            </div>
          </div>
          <div className="min-h-0 flex-1 overflow-auto p-2">
            {activeNestedView.schema.type === "array" ? (
              <HumanReviewArrayValueGrid
                label={
                  activeNestedView.schema.title ?? activeNestedView.columnId
                }
                nestedStackBaseDepth={nestedStackBaseDepth + 1}
                readOnly={readOnly}
                schema={activeNestedView.schema}
                sharedGridSelection={sharedGridSelection}
                sharedNestedStack={sharedNestedStack}
                value={activeNestedValue}
                viewSide={viewSide}
                activeNestedSide={activeNestedSide}
                activeSelectionSide={activeSelectionSide}
                selectionDepth={selectionDepth}
                onChange={updateNestedValue}
                onGridSelectionChange={onGridSelectionChange}
                onNestedStackChange={onNestedStackChange}
                resolveArrayItemMetadataPath={resolveArrayItemMetadataPath}
                resolveLocation={resolveLocation}
              />
            ) : (
              <HumanReviewObjectValueEditor
                schema={activeNestedView.schema}
                value={activeNestedValue}
                originalValue={activeNestedValue}
                readOnly={readOnly}
                onChange={updateNestedValue}
              />
            )}
          </div>
        </div>
      ) : null}
    </div>
  )
}

function HumanReviewObjectValueEditor({
  schema,
  value,
  originalValue,
  readOnly = false,
  onChange,
}: {
  schema: ReviewFieldSchema
  value: JsonValue
  originalValue: JsonValue
  readOnly?: boolean
  onChange: (value: JsonValue) => void
}) {
  const propertyEntries = Object.entries(schema.properties ?? {})

  if (!propertyEntries.length) {
    return (
      <div className="rounded-md bg-background px-2 py-1.5 text-sm text-muted-foreground">
        No properties
      </div>
    )
  }

  return (
    <div className="space-y-2">
      {propertyEntries.map(([propertyKey, propertySchema]) => (
        <HumanReviewFieldCard
          key={propertyKey}
          field={{
            key: propertyKey,
            schema: propertySchema,
            actual: getObjectValue(originalValue, propertyKey),
            expected: getObjectValue(originalValue, propertyKey),
          }}
          value={getObjectValue(value, propertyKey)}
          originalValue={getObjectValue(originalValue, propertyKey)}
          readOnly={readOnly}
          onChange={(childValue) =>
            !readOnly &&
            onChange(setObjectValue(value, propertyKey, childValue))
          }
          onUndo={() =>
            !readOnly &&
            onChange(
              setObjectValue(
                value,
                propertyKey,
                getObjectValue(originalValue, propertyKey)
              )
            )
          }
          onSetNull={() =>
            !readOnly && onChange(setObjectValue(value, propertyKey, null))
          }
        />
      ))}
    </div>
  )
}

type HumanReviewFieldCardProps = {
  field: ReviewFieldDefinition
  value: JsonValue
  originalValue: JsonValue
  active?: boolean
  activeFieldKey?: string
  readOnly?: boolean
  showExpected?: boolean
  onChange: (value: JsonValue) => void
  onFieldFocus?: (field: ReviewFieldDefinition) => void
  onLocationHover?: (location?: ReviewLocation) => void
  onUndo: () => void
  onSetNull: () => void
  resolveArrayItemMetadataPath?: (
    metadataPath: string,
    rowIndex: number,
    rowValue: JsonValue
  ) => string | undefined
  resolveLocation?: (metadataPath: string) => ReviewLocation | undefined
}

function areHumanReviewFieldCardPropsEqual(
  previous: HumanReviewFieldCardProps,
  next: HumanReviewFieldCardProps
) {
  return (
    previous.field === next.field &&
    Object.is(previous.value, next.value) &&
    Object.is(previous.originalValue, next.originalValue) &&
    previous.active === next.active &&
    previous.activeFieldKey === next.activeFieldKey &&
    previous.readOnly === next.readOnly &&
    previous.showExpected === next.showExpected &&
    previous.onFieldFocus === next.onFieldFocus &&
    previous.onLocationHover === next.onLocationHover &&
    previous.resolveArrayItemMetadataPath ===
      next.resolveArrayItemMetadataPath &&
    previous.resolveLocation === next.resolveLocation
  )
}

const HumanReviewFieldCard = React.memo(
  HumanReviewFieldCardBase,
  areHumanReviewFieldCardPropsEqual
)

function HumanReviewFieldCardBase({
  field,
  value,
  originalValue,
  active,
  activeFieldKey,
  readOnly = false,
  showExpected = true,
  onChange,
  onFieldFocus,
  onLocationHover,
  onUndo,
  onSetNull,
  resolveArrayItemMetadataPath,
  resolveLocation,
}: HumanReviewFieldCardProps) {
  const isExpectedEditable = showExpected && !readOnly
  const modified = showExpected && !jsonValuesEqual(value, originalValue)
  const Icon = getFieldIcon(field.schema.type)
  const propertyEntries = Object.entries(field.schema.properties ?? {})
  const [syncedArrayNestedView, setSyncedArrayNestedView] =
    React.useState<SyncedArrayNestedView>(EMPTY_SYNCED_ARRAY_NESTED_VIEW)
  const [syncedArraySelection, setSyncedArraySelection] =
    React.useState<SyncedArraySelection>(EMPTY_SYNCED_ARRAY_SELECTION)
  const updateSyncedArrayNestedView = React.useCallback(
    (stack: ArrayNestedView[], side: ArrayReviewSide) => {
      const activeSide = stack.length ? side : null

      setSyncedArrayNestedView((current) =>
        current.activeSide === activeSide &&
        areArrayNestedViewsEqual(current.stack, stack)
          ? current
          : {
              activeSide,
              stack,
            }
      )
    },
    []
  )
  const updateSyncedArraySelection = React.useCallback(
    (gridSelection: GridSelection, side: ArrayReviewSide, depth: number) => {
      const activeSide = gridSelection.current ? side : null

      setSyncedArraySelection((current) =>
        current.activeSide === activeSide &&
        current.depth === depth &&
        areGridSelectionsEqual(current.gridSelection, gridSelection)
          ? current
          : {
              activeSide,
              depth,
              gridSelection,
            }
      )
    },
    []
  )
  const focusAndHoverField = React.useCallback(() => {
    onFieldFocus?.(field)
    onLocationHover?.(getReviewFieldLocation(field, resolveLocation))
  }, [field, onFieldFocus, onLocationHover, resolveLocation])

  return (
    <div
      tabIndex={0}
      onFocusCapture={focusAndHoverField}
      onMouseEnter={focusAndHoverField}
      onMouseLeave={() => onLocationHover?.(undefined)}
      className={cn(
        "rounded-lg border bg-background p-3 transition-[border-color,background-color,box-shadow] focus-within:border-blue-500/50 focus-within:bg-blue-500/5 hover:border-blue-500/50 hover:bg-blue-500/5 focus-visible:ring-2 focus-visible:ring-blue-500/20 focus-visible:outline-none",
        active &&
          "border-blue-500/60 bg-blue-500/5 shadow-[0_0_0_1px_rgb(59_130_246_/_8%)]"
      )}
    >
      <div className="mb-3 flex min-h-8 items-start justify-between gap-3">
        <div className="min-w-0">
          <div className="flex min-w-0 items-center gap-2">
            <div className="min-w-0">
              <div className="truncate text-sm font-medium">
                {field.schema.title ?? field.key}
              </div>
            </div>
            <span
              className={cn(
                "size-2 shrink-0 rounded-full bg-amber-400",
                !modified && "opacity-0"
              )}
            />
          </div>
          {field.schema.description ? (
            <div className="mt-0.5 line-clamp-2 text-xs text-muted-foreground">
              {field.schema.description}
            </div>
          ) : null}
        </div>
        <div className="flex shrink-0 items-center gap-1">
          {isExpectedEditable && modified ? (
            <Tooltip>
              <TooltipTrigger asChild>
                <Button
                  type="button"
                  variant="ghost"
                  size="icon-sm"
                  className="text-muted-foreground"
                  onClick={onUndo}
                  aria-label={`Undo ${field.key}`}
                >
                  <HugeiconsIcon icon={Undo02Icon} className="size-4" />
                </Button>
              </TooltipTrigger>
              <TooltipContent>Revert changes</TooltipContent>
            </Tooltip>
          ) : null}
          {isExpectedEditable ? (
            <Tooltip>
              <TooltipTrigger asChild>
                <Button
                  type="button"
                  variant="ghost"
                  size="icon-sm"
                  className="text-muted-foreground"
                  onClick={onSetNull}
                  aria-label={`Set ${field.key} to null`}
                >
                  <HugeiconsIcon icon={CancelCircleIcon} className="size-4" />
                </Button>
              </TooltipTrigger>
              <TooltipContent>Set to NULL</TooltipContent>
            </Tooltip>
          ) : null}
          <div className="flex h-6 items-center gap-1 rounded-md border bg-muted/50 px-1.5 text-xs text-muted-foreground">
            <HugeiconsIcon icon={Icon} className="size-3.5" />
            {field.schema.type}
          </div>
        </div>
      </div>
      {field.schema.type === "object" ? (
        <div className="rounded-md border bg-muted/25 p-2">
          <div className="mb-2 flex items-center justify-between gap-3 text-[11px] font-medium text-muted-foreground">
            <span>Properties</span>
            <span>{propertyEntries.length} fields</span>
          </div>
          <div className="space-y-2">
            {propertyEntries.length ? (
              propertyEntries.map(([propertyKey, schema]) => {
                const childField: ReviewFieldDefinition = {
                  key: `${field.key}.${propertyKey}`,
                  schema,
                  actual: getObjectValue(field.actual, propertyKey),
                  expected: getObjectValue(originalValue, propertyKey),
                  metadataPath: `${field.metadataPath ?? field.key}.${propertyKey}`,
                }

                return (
                  <HumanReviewFieldCard
                    key={childField.key}
                    field={childField}
                    value={getObjectValue(value, propertyKey)}
                    originalValue={childField.expected}
                    active={childField.key === activeFieldKey}
                    activeFieldKey={activeFieldKey}
                    readOnly={readOnly}
                    showExpected={showExpected}
                    onChange={(childValue) =>
                      onChange(setObjectValue(value, propertyKey, childValue))
                    }
                    onFieldFocus={onFieldFocus}
                    onLocationHover={onLocationHover}
                    onUndo={() =>
                      onChange(
                        setObjectValue(value, propertyKey, childField.expected)
                      )
                    }
                    onSetNull={() =>
                      onChange(setObjectValue(value, propertyKey, null))
                    }
                    resolveArrayItemMetadataPath={resolveArrayItemMetadataPath}
                    resolveLocation={resolveLocation}
                  />
                )
              })
            ) : (
              <div className="rounded-md bg-background px-2 py-1.5 text-sm text-muted-foreground">
                No properties
              </div>
            )}
          </div>
        </div>
      ) : field.schema.type === "array" ? (
        <div className="grid gap-2">
          <HumanReviewArrayValueGrid
            activeNestedSide={syncedArrayNestedView.activeSide}
            activeSelectionSide={syncedArraySelection.activeSide}
            label="Actual"
            metadataPath={field.metadataPath ?? field.key}
            readOnly
            resolveArrayItemMetadataPath={resolveArrayItemMetadataPath}
            resolveLocation={resolveLocation}
            schema={field.schema}
            selectionDepth={syncedArraySelection.depth}
            sharedGridSelection={syncedArraySelection.gridSelection}
            sharedNestedStack={syncedArrayNestedView.stack}
            value={field.actual}
            viewSide="actual"
            onGridSelectionChange={updateSyncedArraySelection}
            onLocationHover={onLocationHover}
            onNestedStackChange={updateSyncedArrayNestedView}
          />
          {showExpected ? (
            <HumanReviewArrayValueGrid
              activeNestedSide={syncedArrayNestedView.activeSide}
              activeSelectionSide={syncedArraySelection.activeSide}
              label="Expected"
              metadataPath={field.metadataPath ?? field.key}
              readOnly={readOnly}
              resolveArrayItemMetadataPath={resolveArrayItemMetadataPath}
              resolveLocation={resolveLocation}
              schema={field.schema}
              selectionDepth={syncedArraySelection.depth}
              sharedGridSelection={syncedArraySelection.gridSelection}
              sharedNestedStack={syncedArrayNestedView.stack}
              value={value}
              viewSide="expected"
              onChange={onChange}
              onGridSelectionChange={updateSyncedArraySelection}
              onLocationHover={onLocationHover}
              onNestedStackChange={updateSyncedArrayNestedView}
            />
          ) : null}
        </div>
      ) : (
        <div className={cn("grid gap-2", showExpected && "sm:grid-cols-2")}>
          <div className="rounded-md border bg-muted/30 p-2">
            <div className="mb-1 text-[11px] font-medium text-muted-foreground">
              Actual
            </div>
            <div className="min-h-7 rounded-md bg-background px-2 py-1.5 text-sm">
              {formatValue(field.actual)}
            </div>
          </div>
          {showExpected ? (
            <div className="rounded-md border bg-muted/30 p-2">
              <div className="mb-1 text-[11px] font-medium text-muted-foreground">
                Expected
              </div>
              <HumanReviewValueInput
                readOnly={readOnly}
                schema={field.schema}
                value={getPrimitiveValue(value)}
                onChange={onChange}
              />
            </div>
          ) : null}
        </div>
      )}
    </div>
  )
}

function HumanReviewHighlight({ location }: { location: ReviewLocation }) {
  const area = location.area

  return (
    <div
      className={cn(
        "pointer-events-none absolute z-10 border",
        REVIEW_HIGHLIGHT_STYLE
      )}
      style={{
        left: `${area.left}%`,
        top: `${area.top}%`,
        width: `${area.width}%`,
        height: `${area.height}%`,
      }}
    />
  )
}

function JsonDiffView({
  actual,
  expected,
  theme,
}: {
  actual: JsonObject
  expected: JsonObject
  theme: HumanReviewTheme
}) {
  const oldFile = React.useMemo(
    () => ({
      name: "actual.json",
      contents: formatJson(actual),
      lang: "json",
    }),
    [actual]
  )
  const newFile = React.useMemo(
    () => ({
      name: "expected.json",
      contents: formatJson(expected),
      lang: "json",
    }),
    [expected]
  )

  return (
    <ScrollAreaVirtualizer
      className="h-full bg-surface/60"
      contentClassName="min-w-full"
    >
      <div className="bounding-box-citations-diff h-full text-xs">
        <MultiFileDiff
          className="block min-w-full"
          oldFile={oldFile}
          newFile={newFile}
          options={{
            diffStyle: "split",
            disableFileHeader: true,
            diffIndicators: "bars",
            hunkSeparators: "line-info-basic",
            overflow: "wrap",
            themeType: theme,
            theme: {
              light: "pierre-light-soft",
              dark: "pierre-dark-soft",
            },
          }}
        />
      </div>
    </ScrollAreaVirtualizer>
  )
}

function JsonCodeView({
  name = "actual.json",
  theme,
  value,
}: {
  name?: string
  theme: HumanReviewTheme
  value: JsonValue
}) {
  const file = React.useMemo(() => {
    const contents = formatJson(value)

    return {
      name,
      contents,
      lang: "json" as const,
      cacheKey: contents,
    }
  }, [name, value])

  return (
    <div
      data-rehype-pretty-code-figure
      className="relative m-0! h-full overflow-hidden rounded-none! bg-code text-code-foreground"
    >
      <WorkerPoolContextProvider
        poolOptions={CODE_WORKER_POOL_OPTIONS}
        highlighterOptions={CODE_HIGHLIGHTER_OPTIONS}
      >
        <ScrollAreaVirtualizer
          key={`${file.cacheKey}:${theme}`}
          className="h-full min-w-0"
          contentClassName="min-w-full"
        >
          <File
            key={`${file.cacheKey}:${theme}`}
            className="block min-w-full"
            file={file}
            metrics={CODE_VIRTUAL_FILE_METRICS}
            style={CODE_FILE_THEME}
            options={{
              disableFileHeader: true,
              overflow: "scroll",
              themeType: theme,
              theme: {
                light: "pierre-light-soft",
                dark: "pierre-dark-soft",
              },
            }}
          />
        </ScrollAreaVirtualizer>
      </WorkerPoolContextProvider>
    </div>
  )
}

function HumanReviewPanel({
  activeFieldKey,
  className,
  fields = REVIEW_SCHEMA,
  onFieldFocus,
  onLocationHover,
  resolveArrayItemMetadataPath,
  resolveLocation,
  showExpected = true,
  theme = "light",
}: {
  activeFieldKey?: string
  className?: string
  fields?: ReviewFieldDefinition[]
  onFieldFocus?: (field: ReviewFieldDefinition) => void
  onLocationHover?: (location?: ReviewLocation) => void
  resolveArrayItemMetadataPath?: (
    metadataPath: string,
    rowIndex: number,
    rowValue: JsonValue
  ) => string | undefined
  resolveLocation?: (metadataPath: string) => ReviewLocation | undefined
  showExpected?: boolean
  theme?: HumanReviewTheme
} = {}) {
  const [activeTab, setActiveTab] = React.useState("form")
  const actualValues = React.useMemo(() => getActualValues(fields), [fields])
  const initialExpectedValues = React.useMemo(
    () => getExpectedValues(fields),
    [fields]
  )
  const [expected, setExpected] = React.useState<JsonObject>(
    initialExpectedValues
  )

  const [previousInputs, setPreviousInputs] = React.useState({
    initialExpectedValues,
  })
  if (previousInputs.initialExpectedValues !== initialExpectedValues) {
    setPreviousInputs({ initialExpectedValues })
    setExpected(initialExpectedValues)
  }

  const updateValue = React.useCallback((key: string, value: JsonValue) => {
    setExpected((current) =>
      Object.is(current[key], value) ? current : { ...current, [key]: value }
    )
  }, [])

  return (
    <TooltipProvider delay={200}>
      <Tabs
        value={activeTab}
        onValueChange={setActiveTab}
        className={cn("flex h-[560px] flex-col gap-0 bg-background", className)}
      >
        <div className="flex min-h-12 items-center justify-between gap-3 border-b px-3">
          <TabsList className="h-8 sm:h-7">
            <TabsTrigger value="form" className="h-7 sm:h-6">
              <HugeiconsIcon icon={TextCheckIcon} className="size-4" />
              Form
            </TabsTrigger>
            <TabsTrigger value="json" className="h-7 sm:h-6">
              <HugeiconsIcon icon={SourceCodeSquareIcon} className="size-4" />
              JSON
            </TabsTrigger>
          </TabsList>
        </div>
        <TabsContent value="form" keepMounted className="min-h-0 flex-1">
          <ScrollArea className="h-full" scrollFade>
            <div className="space-y-3 p-3">
              {fields.map((field) => (
                <HumanReviewFieldCard
                  key={field.key}
                  field={field}
                  value={
                    showExpected ? (expected[field.key] ?? null) : field.actual
                  }
                  originalValue={showExpected ? field.expected : field.actual}
                  active={
                    field.key === activeFieldKey ||
                    activeFieldKey?.startsWith(`${field.key}.`)
                  }
                  activeFieldKey={activeFieldKey}
                  showExpected={showExpected}
                  onChange={(value) => updateValue(field.key, value)}
                  onFieldFocus={onFieldFocus}
                  onLocationHover={onLocationHover}
                  onUndo={() => updateValue(field.key, field.expected)}
                  onSetNull={() => updateValue(field.key, null)}
                  resolveArrayItemMetadataPath={resolveArrayItemMetadataPath}
                  resolveLocation={resolveLocation}
                />
              ))}
            </div>
          </ScrollArea>
        </TabsContent>
        <TabsContent value="json" className="min-h-0 flex-1">
          {showExpected ? (
            <JsonDiffView
              actual={actualValues}
              expected={expected}
              theme={theme}
            />
          ) : (
            <JsonCodeView value={actualValues} theme={theme} />
          )}
        </TabsContent>
      </Tabs>
    </TooltipProvider>
  )
}

export function HumanReviewBlock({
  defaultViewerZoom = DEFAULT_ZOOM,
  showExpected = true,
}: {
  defaultViewerZoom?: number
  showExpected?: boolean
} = {}) {
  const { resolvedTheme } = useTheme()
  const fields = BLOCK_REVIEW_SCHEMA
  const [activeFieldKey, setActiveFieldKey] = React.useState(fields[0].key)
  const [hoverLocation, setHoverLocation] =
    React.useState<ReviewLocation | null>(null)
  const viewerRef = React.useRef<PDFViewerHandle>(null)
  const hoverLocationKeyRef = React.useRef<string | null>(null)
  const activeField = findReviewField(fields, activeFieldKey) ?? fields[0]
  const activeLocation =
    hoverLocation ?? getReviewFieldLocation(activeField, getBlockReviewLocation)
  const reviewTheme: HumanReviewTheme =
    resolvedTheme === "dark" ? "dark" : "light"

  const focusField = React.useCallback(
    (field: ReviewFieldDefinition) => {
      if (field.key === activeFieldKey) return

      setActiveFieldKey(field.key)

      const location = getReviewFieldLocation(field, getBlockReviewLocation)
      if (location) {
        viewerRef.current?.scrollToPageArea(location.page, location.area)
      }
    },
    [activeFieldKey]
  )
  const handleLocationHover = React.useCallback((location?: ReviewLocation) => {
    setHoverLocation(location ?? null)

    const locationKey = getReviewLocationKey(location)
    if (!location) {
      hoverLocationKeyRef.current = null
      return
    }
    if (locationKey === hoverLocationKeyRef.current) return

    hoverLocationKeyRef.current = locationKey
    viewerRef.current?.scrollToPageArea(location.page, location.area, {
      behavior: "auto",
    })
  }, [])

  return (
    <PdfBlockResizableShell
      autoSaveId="pdf-block-bounding-box-citations"
      rightDefaultSize={42}
      rightMaxSize={60}
      rightMinSize={30}
      left={
        <PDFViewer
          ref={viewerRef}
          src={BLOCK_REVIEW_PDF_URL}
          defaultZoom={defaultViewerZoom}
          renderPageOverlay={({ pageNumber }) =>
            activeLocation?.page === pageNumber ? (
              <HumanReviewHighlight location={activeLocation} />
            ) : null
          }
        />
      }
      right={
        <HumanReviewPanel
          activeFieldKey={activeField.key}
          className="h-full min-h-0"
          fields={fields}
          showExpected={showExpected}
          theme={reviewTheme}
          onFieldFocus={focusField}
          onLocationHover={handleLocationHover}
          resolveArrayItemMetadataPath={resolveBlockReviewArrayItemMetadataPath}
          resolveLocation={getBlockReviewLocation}
        />
      }
    />
  )
}

export function HumanReviewDemo() {
  const { resolvedTheme } = useTheme()
  const reviewTheme: HumanReviewTheme =
    resolvedTheme === "dark" ? "dark" : "light"

  return (
    <div
      data-slot="component-preview"
      className="group relative mt-4 mb-12 flex flex-col overflow-hidden rounded-xl border"
    >
      <HumanReviewPanel theme={reviewTheme} />
      <DocsViewCodeBlock code={humanReviewUsageCode} />
    </div>
  )
}

const humanReviewUsageCode = `"use client";

import * as React from "react";

import { HumanReviewPanel, type ReviewField } from "@/components/extend/bounding-box-citations";

const fields: ReviewField[] = [
  {
    key: "statement_period",
    schema: {
      type: "string",
      title: "Statement period",
      description: "Date range covered by the bank statement.",
    },
    actual: "Jan 1-31, 2026",
    expected: "January 1-31, 2026",
  },
  {
    key: "transactions",
    schema: {
      type: "array",
      title: "Transactions",
      items: {
        type: "object",
        properties: {
          date: { type: "string", title: "Date" },
          description: { type: "string", title: "Description" },
          amount: { type: "number", title: "Amount" },
          category: { type: "string", title: "Category" },
          merchant: {
            type: "object",
            title: "Merchant",
            properties: {
              name: { type: "string", title: "Name" },
              city: { type: "string", title: "City" },
              risk_level: { type: "string", title: "Risk level" },
            },
          },
          tags: {
            type: "array",
            title: "Tags",
            items: { type: "string", title: "Tag" },
          },
        },
      },
    },
    actual: [
      {
        date: "2026-01-12",
        description: "POS PURCHASE GROCERY MART",
        amount: -86.42,
        category: "Debit",
        merchant: {
          name: "Grocery Mart",
          city: "Brooklyn",
          risk_level: "medium",
        },
        tags: ["card", "groceries"],
      },
    ],
    expected: [
      {
        date: "2026-01-12",
        description: "POS PURCHASE GROCERY MART",
        amount: -68.42,
        category: "Debit",
        merchant: {
          name: "Grocery Mart",
          city: "Brooklyn",
          risk_level: "low",
        },
        tags: ["card", "groceries", "needs_review"],
      },
    ],
  },
  {
    key: "ending_balance",
    schema: {
      type: "number",
      title: "Ending balance",
      description: "Final account balance at the end of the statement period.",
    },
    actual: 12840.18,
    expected: 12858.18,
  },
  {
    key: "overdraft_protection_enabled",
    schema: {
      type: "boolean",
      title: "Overdraft protection enabled",
      description: "Whether overdraft protection is enabled for the account.",
    },
    actual: false,
    expected: true,
  },
  {
    key: "account_details",
    schema: {
      type: "object",
      title: "Account details",
      description: "Account owner and identifying details from the statement.",
      properties: {
        holder_name: {
          type: "string",
          title: "Holder name",
        },
        account_last_four: {
          type: "string",
          title: "Account last four",
        },
        account_type: {
          type: "string",
          title: "Account type",
        },
        mailing_address: {
          type: "object",
          title: "Mailing address",
          properties: {
            line_1: { type: "string", title: "Line 1" },
            city: { type: "string", title: "City" },
            state: { type: "string", title: "State" },
          },
        },
        linked_accounts: {
          type: "array",
          title: "Linked accounts",
          items: {
            type: "object",
            properties: {
              nickname: { type: "string", title: "Nickname" },
              last_four: { type: "string", title: "Last four" },
            },
          },
        },
      },
    },
    actual: {
      holder_name: "Jordan Lee",
      account_last_four: "4821",
      account_type: "Checking",
      mailing_address: {
        line_1: "42 Market Street",
        city: "Brooklyn",
        state: "NY",
      },
      linked_accounts: [
        {
          nickname: "Operations reserve",
          last_four: "1842",
        },
      ],
    },
    expected: {
      holder_name: "Jordan Lee",
      account_last_four: "4821",
      account_type: "Premier Checking",
      mailing_address: {
        line_1: "42 Market Street",
        city: "New York",
        state: "NY",
      },
      linked_accounts: [
        {
          nickname: "Operations reserve",
          last_four: "1842",
        },
        {
          nickname: "Payroll sweep",
          last_four: "9174",
        },
      ],
    },
  },
];

export function HumanReviewExample() {
  const [values, setValues] = React.useState(() =>
    Object.fromEntries(fields.map((field) => [field.key, field.expected])),
  );

  return (
    <HumanReviewPanel
      fields={fields}
      values={values}
      onValuesChange={setValues}
      className="h-[560px]"
    />
  );
}`

const humanReviewSourceCode =
  '"use client"\n\nimport * as React from "react"\nimport {\n  DataEditor,\n  emptyGridSelection,\n  GridCellKind,\n  TextCellEntry,\n  type EditableGridCell,\n  type GridCell,\n  type GridColumn,\n  type GridMouseEventArgs,\n  type GridSelection,\n  type Item,\n  type NumberCell,\n  type ProvideEditorComponent,\n  type Rectangle,\n  type TextCell,\n  type Theme,\n} from "@glideapps/glide-data-grid"\nimport { Virtualizer as DiffsVirtualizer } from "@pierre/diffs"\nimport {\n  File,\n  MultiFileDiff,\n  VirtualizerContext,\n  WorkerPoolContextProvider,\n  type VirtualFileMetrics,\n  type WorkerInitializationRenderOptions,\n  type WorkerPoolOptions,\n} from "@pierre/diffs/react"\nimport { flushSync } from "react-dom"\n\nimport type { RegistryIconProps } from "@/lib/registry-icon-props"\nimport { cn } from "@/lib/utils"\nimport { Button } from "@/components/ui/button"\nimport { Input } from "@/components/ui/input"\nimport { ScrollArea } from "@/components/ui/scroll-area"\nimport { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"\nimport {\n  Tooltip,\n  TooltipContent,\n  TooltipProvider,\n  TooltipTrigger,\n} from "@/components/ui/tooltip"\nimport { IconPlaceholder } from "@/components/icon-placeholder"\n\nimport "@glideapps/glide-data-grid/dist/index.css"\n\nfunction InputNumericGlyph(props: RegistryIconProps) {\n  return (\n    <IconPlaceholder\n      lucide="Hash"\n      tabler="IconNumber123"\n      hugeicons="InputNumericIcon"\n      phosphor="NumpadIcon"\n      remixicon="RiHashtag"\n      {...props}\n    />\n  )\n}\n\nfunction InputTextGlyph(props: RegistryIconProps) {\n  return (\n    <IconPlaceholder\n      lucide="TextCursorInput"\n      tabler="IconForms"\n      hugeicons="InputTextIcon"\n      phosphor="TextboxIcon"\n      remixicon="RiInputField"\n      {...props}\n    />\n  )\n}\n\nfunction SecondBracketGlyph(props: RegistryIconProps) {\n  return (\n    <IconPlaceholder\n      lucide="Brackets"\n      tabler="IconBrackets"\n      hugeicons="SecondBracketIcon"\n      phosphor="BracketsSquareIcon"\n      remixicon="RiBracketsLine"\n      {...props}\n    />\n  )\n}\n\nfunction SourceCodeSquareGlyph(props: RegistryIconProps) {\n  return (\n    <IconPlaceholder\n      lucide="SquareCode"\n      tabler="IconSourceCode"\n      hugeicons="SourceCodeSquareIcon"\n      phosphor="CodeIcon"\n      remixicon="RiCodeBlock"\n      {...props}\n    />\n  )\n}\n\nfunction TextCheckGlyph(props: RegistryIconProps) {\n  return (\n    <IconPlaceholder\n      lucide="CaptionsIcon"\n      tabler="IconTextCaption"\n      hugeicons="TextCheckIcon"\n      phosphor="TextTIcon"\n      remixicon="RiTextWrap"\n      {...props}\n    />\n  )\n}\n\nexport type JsonPrimitive = string | number | boolean | null\nexport type JsonValue = JsonPrimitive | JsonObject | JsonArray\nexport type JsonObject = { [key: string]: JsonValue }\nexport type JsonArray = JsonValue[]\nexport type SchemaPropertyType =\n  | "string"\n  | "number"\n  | "integer"\n  | "boolean"\n  | "object"\n  | "array"\n\nexport type ReviewFieldSchema = {\n  type: SchemaPropertyType\n  title?: string\n  description?: string\n  enum?: Array<string | number>\n  properties?: Record<string, ReviewFieldSchema>\n  items?: ReviewFieldSchema\n}\n\nexport type HighlightArea = {\n  left: number\n  top: number\n  width: number\n  height: number\n}\n\nexport type ReviewField = {\n  key: string\n  schema: ReviewFieldSchema\n  actual: JsonValue\n  expected: JsonValue\n  location?: ReviewLocation\n  metadataPath?: string\n}\n\nexport type ReviewLocation = {\n  page: number\n  area: HighlightArea\n}\n\nexport type ReviewCitation = {\n  page: number\n  polygon?: Array<{ x: number; y: number }>\n  pageWidth: number\n  pageHeight: number\n}\n\nexport type ReviewMetadataEntry = {\n  citations?: ReviewCitation[]\n}\n\nfunction ScrollAreaVirtualizer({\n  children,\n  className,\n  contentClassName,\n  contentStyle,\n  scrollFade = true,\n}: {\n  children: React.ReactNode\n  className?: string\n  contentClassName?: string\n  contentStyle?: React.CSSProperties\n  scrollFade?: boolean\n}) {\n  const [virtualizer] = React.useState(() =>\n    typeof window !== "undefined" ? new DiffsVirtualizer() : undefined\n  )\n  const viewportRef = React.useRef<HTMLDivElement | null>(null)\n  const contentRef = React.useRef<HTMLDivElement | null>(null)\n  const syncVirtualizer = React.useCallback(() => {\n    if (!virtualizer) return\n\n    const viewport = viewportRef.current\n    const content = contentRef.current\n\n    if (viewport && content) {\n      virtualizer.setup(viewport, content)\n      return\n    }\n\n    virtualizer.cleanUp()\n  }, [virtualizer])\n  const setViewportRef = React.useCallback(\n    (node: HTMLDivElement | null) => {\n      viewportRef.current = node\n      syncVirtualizer()\n    },\n    [syncVirtualizer]\n  )\n  const setContentRef = React.useCallback(\n    (node: HTMLDivElement | null) => {\n      contentRef.current = node\n      syncVirtualizer()\n    },\n    [syncVirtualizer]\n  )\n\n  React.useEffect(() => {\n    return () => virtualizer?.cleanUp()\n  }, [virtualizer])\n\n  return (\n    <VirtualizerContext.Provider value={virtualizer}>\n      <ScrollArea\n        className={className}\n        scrollFade={scrollFade}\n        scrollbarOverflowOnly\n        viewportRef={setViewportRef}\n      >\n        <div\n          ref={setContentRef}\n          className={contentClassName}\n          style={contentStyle}\n        >\n          {children}\n        </div>\n      </ScrollArea>\n    </VirtualizerContext.Provider>\n  )\n}\n\nconst REVIEW_HIGHLIGHT_STYLE =\n  "border-blue-500/70 bg-blue-500/12 shadow-[0_4px_16px_rgb(59_130_246_/_10%)]"\n\nconst CODE_FILE_THEME = {\n  "--diffs-light-bg": "var(--color-code)",\n  "--diffs-dark-bg": "var(--color-code)",\n  "--diffs-light": "var(--color-code-foreground)",\n  "--diffs-dark": "var(--color-code-foreground)",\n  "--diffs-bg-context-override": "var(--color-code)",\n  "--diffs-bg-context-gutter-override": "var(--color-code)",\n  "--diffs-bg-buffer-override": "var(--color-code)",\n  "--diffs-fg-number-override": "var(--color-muted-foreground)",\n  "--diffs-font-size": "0.8rem",\n  "--diffs-line-height": "1.625",\n} as React.CSSProperties\n\nconst CODE_FONT_SIZE_PX = 12.8\nconst CODE_LINE_HEIGHT_PX = CODE_FONT_SIZE_PX * 1.625\n\nconst CODE_VIRTUAL_FILE_METRICS = {\n  hunkLineCount: 50,\n  lineHeight: CODE_LINE_HEIGHT_PX,\n  diffHeaderHeight: 44,\n  spacing: 8,\n  paddingTop: 0,\n  paddingBottom: 8,\n} satisfies VirtualFileMetrics\n\nconst CODE_HIGHLIGHTER_OPTIONS = {\n  theme: {\n    light: "pierre-light-soft",\n    dark: "pierre-dark-soft",\n  },\n  langs: ["json"],\n} satisfies WorkerInitializationRenderOptions\n\nconst CODE_WORKER_POOL_OPTIONS = {\n  poolSize: 2,\n  workerFactory: () =>\n    new Worker(new URL("@pierre/diffs/worker/worker.js", import.meta.url), {\n      type: "module",\n    }),\n} satisfies WorkerPoolOptions\n\nfunction readIsDarkTheme() {\n  return (\n    typeof document !== "undefined" &&\n    document.documentElement.classList.contains("dark")\n  )\n}\n\n// A single shared MutationObserver backs every consumer. Each grid previously\n// created its own observer (two, via useHumanReviewGridTheme), so opening a\n// nested array view spun up and tore down several observers at once.\nconst darkThemeListeners = new Set<(isDark: boolean) => void>()\nlet darkThemeObserver: MutationObserver | null = null\nlet sharedIsDarkTheme = false\n\nfunction ensureDarkThemeObserver() {\n  if (\n    darkThemeObserver ||\n    typeof document === "undefined" ||\n    typeof MutationObserver === "undefined"\n  ) {\n    return\n  }\n\n  sharedIsDarkTheme = readIsDarkTheme()\n  darkThemeObserver = new MutationObserver(() => {\n    const nextIsDark = readIsDarkTheme()\n    if (nextIsDark === sharedIsDarkTheme) return\n\n    sharedIsDarkTheme = nextIsDark\n    darkThemeListeners.forEach((listener) => listener(nextIsDark))\n  })\n  darkThemeObserver.observe(document.documentElement, {\n    attributes: true,\n    attributeFilter: ["class"],\n  })\n}\n\nfunction subscribeToDarkTheme(listener: () => void) {\n  ensureDarkThemeObserver()\n  darkThemeListeners.add(listener)\n  return () => {\n    darkThemeListeners.delete(listener)\n    if (darkThemeListeners.size === 0 && darkThemeObserver) {\n      darkThemeObserver.disconnect()\n      darkThemeObserver = null\n    }\n  }\n}\n\nfunction useIsDarkTheme() {\n  return React.useSyncExternalStore(\n    subscribeToDarkTheme,\n    readIsDarkTheme,\n    () => false\n  )\n}\n\nfunction useHumanReviewGridTheme() {\n  const isDark = useIsDarkTheme()\n\n  return React.useMemo<Partial<Theme>>(\n    () => ({\n      accentColor: isDark ? "rgb(96, 165, 250)" : "rgb(37, 99, 235)",\n      accentLight: isDark ? "rgba(29, 78, 216, 0.15)" : "rgb(219, 234, 254)",\n      accentFg: "rgb(255, 255, 255)",\n      textDark: isDark ? "rgb(229, 229, 229)" : "rgb(23, 23, 23)",\n      textMedium: isDark ? "rgb(163, 163, 163)" : "rgb(82, 82, 82)",\n      textLight: isDark ? "rgb(115, 115, 115)" : "rgb(163, 163, 163)",\n      textBubble: isDark ? "rgb(245, 245, 245)" : "rgb(23, 23, 23)",\n      textHeader: isDark ? "rgb(245, 245, 245)" : "rgb(23, 23, 23)",\n      textGroupHeader: isDark ? "rgb(163, 163, 163)" : "rgb(82, 82, 82)",\n      bgCell: isDark ? "rgb(10, 10, 10)" : "rgb(255, 255, 255)",\n      bgCellMedium: isDark ? "rgb(23, 23, 23)" : "rgb(250, 250, 250)",\n      bgHeader: isDark ? "rgb(23, 23, 23)" : "rgb(250, 250, 250)",\n      bgHeaderHasFocus: isDark ? "rgb(38, 38, 38)" : "rgb(245, 245, 245)",\n      bgHeaderHovered: isDark ? "rgb(38, 38, 38)" : "rgb(245, 245, 245)",\n      borderColor: isDark ? "rgb(38, 38, 38)" : "rgb(229, 229, 229)",\n      horizontalBorderColor: isDark ? "rgb(38, 38, 38)" : "rgb(229, 229, 229)",\n      cellHorizontalPadding: 8,\n      cellVerticalPadding: 3,\n      headerIconSize: 18,\n      baseFontStyle: "13px",\n      headerFontStyle: "600 13px",\n      markerFontStyle: "11px",\n      fontFamily: \'-apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif\',\n      editorFontSize: "13px",\n    }),\n    [isDark]\n  )\n}\n\nexport const REVIEW_FIELDS: ReviewField[] = [\n  {\n    key: "statement_period",\n    schema: {\n      type: "string",\n      title: "Statement period",\n      description: "Date range covered by the bank statement.",\n    },\n    actual: "Jan 1-31, 2026",\n    expected: "January 1-31, 2026",\n    location: {\n      page: 1,\n      area: { left: 31, top: 30, width: 40, height: 5.8 },\n    },\n  },\n  {\n    key: "transactions",\n    schema: {\n      type: "array",\n      title: "Transactions",\n      description: "Posted account activity during the statement period.",\n      items: {\n        type: "object",\n        properties: {\n          date: {\n            type: "string",\n            title: "Date",\n          },\n          description: {\n            type: "string",\n            title: "Description",\n          },\n          amount: {\n            type: "number",\n            title: "Amount",\n          },\n          category: {\n            type: "string",\n            title: "Category",\n          },\n          merchant: {\n            type: "object",\n            title: "Merchant",\n            properties: {\n              name: {\n                type: "string",\n                title: "Name",\n              },\n              city: {\n                type: "string",\n                title: "City",\n              },\n              risk_level: {\n                type: "string",\n                title: "Risk level",\n              },\n            },\n          },\n          tags: {\n            type: "array",\n            title: "Tags",\n            items: {\n              type: "string",\n              title: "Tag",\n            },\n          },\n        },\n      },\n    },\n    actual: [\n      {\n        date: "2026-01-03",\n        description: "ACH CREDIT PAYROLL",\n        amount: 4250,\n        category: "Deposit",\n        merchant: {\n          name: "Acme Payroll",\n          city: "New York",\n          risk_level: "low",\n        },\n        tags: ["payroll", "recurring"],\n      },\n      {\n        date: "2026-01-12",\n        description: "POS PURCHASE GROCERY MART",\n        amount: -86.42,\n        category: "Debit",\n        merchant: {\n          name: "Grocery Mart",\n          city: "Brooklyn",\n          risk_level: "medium",\n        },\n        tags: ["card", "groceries"],\n      },\n    ],\n    expected: [\n      {\n        date: "2026-01-03",\n        description: "ACH CREDIT PAYROLL",\n        amount: 4250,\n        category: "Deposit",\n        merchant: {\n          name: "Acme Payroll",\n          city: "New York",\n          risk_level: "low",\n        },\n        tags: ["payroll", "recurring"],\n      },\n      {\n        date: "2026-01-12",\n        description: "POS PURCHASE GROCERY MART",\n        amount: -68.42,\n        category: "Debit",\n        merchant: {\n          name: "Grocery Mart",\n          city: "Brooklyn",\n          risk_level: "low",\n        },\n        tags: ["card", "groceries", "needs_review"],\n      },\n    ],\n    location: {\n      page: 1,\n      area: { left: 13.5, top: 66, width: 73.5, height: 7.5 },\n    },\n  },\n  {\n    key: "ending_balance",\n    schema: {\n      type: "number",\n      title: "Ending balance",\n      description: "Final account balance at the end of the statement period.",\n    },\n    actual: 12840.18,\n    expected: 12858.18,\n    location: {\n      page: 1,\n      area: { left: 13.5, top: 66, width: 73.5, height: 7.5 },\n    },\n  },\n  {\n    key: "overdraft_protection_enabled",\n    schema: {\n      type: "boolean",\n      title: "Overdraft protection enabled",\n      description: "Whether overdraft protection is enabled for the account.",\n    },\n    actual: false,\n    expected: true,\n    location: {\n      page: 2,\n      area: { left: 9.5, top: 12, width: 81, height: 11.5 },\n    },\n  },\n  {\n    key: "account_details",\n    schema: {\n      type: "object",\n      title: "Account details",\n      description: "Account owner and identifying details from the statement.",\n      properties: {\n        holder_name: {\n          type: "string",\n          title: "Holder name",\n        },\n        account_last_four: {\n          type: "string",\n          title: "Account last four",\n        },\n        account_type: {\n          type: "string",\n          title: "Account type",\n        },\n        mailing_address: {\n          type: "object",\n          title: "Mailing address",\n          properties: {\n            line_1: {\n              type: "string",\n              title: "Line 1",\n            },\n            city: {\n              type: "string",\n              title: "City",\n            },\n            state: {\n              type: "string",\n              title: "State",\n            },\n          },\n        },\n        linked_accounts: {\n          type: "array",\n          title: "Linked accounts",\n          items: {\n            type: "object",\n            properties: {\n              nickname: {\n                type: "string",\n                title: "Nickname",\n              },\n              last_four: {\n                type: "string",\n                title: "Last four",\n              },\n            },\n          },\n        },\n      },\n    },\n    actual: {\n      holder_name: "Jordan Lee",\n      account_last_four: "4821",\n      account_type: "Checking",\n      mailing_address: {\n        line_1: "42 Market Street",\n        city: "Brooklyn",\n        state: "NY",\n      },\n      linked_accounts: [\n        {\n          nickname: "Operations reserve",\n          last_four: "1842",\n        },\n      ],\n    },\n    expected: {\n      holder_name: "Jordan Lee",\n      account_last_four: "4821",\n      account_type: "Premier Checking",\n      mailing_address: {\n        line_1: "42 Market Street",\n        city: "New York",\n        state: "NY",\n      },\n      linked_accounts: [\n        {\n          nickname: "Operations reserve",\n          last_four: "1842",\n        },\n        {\n          nickname: "Payroll sweep",\n          last_four: "9174",\n        },\n      ],\n    },\n  },\n]\n\nfunction getCitationLocation(\n  citation: ReviewCitation\n): ReviewLocation | undefined {\n  const polygon = citation.polygon\n  if (!polygon?.length || !citation.pageWidth || !citation.pageHeight) {\n    return undefined\n  }\n\n  const xs = polygon.map((point) => point.x)\n  const ys = polygon.map((point) => point.y)\n  const left = Math.min(...xs)\n  const top = Math.min(...ys)\n  const right = Math.max(...xs)\n  const bottom = Math.max(...ys)\n\n  return {\n    page: citation.page,\n    area: {\n      left: (left / citation.pageWidth) * 100,\n      top: (top / citation.pageHeight) * 100,\n      width: ((right - left) / citation.pageWidth) * 100,\n      height: ((bottom - top) / citation.pageHeight) * 100,\n    },\n  }\n}\n\nexport function getMetadataLocation(\n  metadata: Record<string, ReviewMetadataEntry> | undefined,\n  metadataPath: string | undefined\n) {\n  if (!metadata || !metadataPath) return undefined\n\n  const citation = metadata[metadataPath]?.citations?.find(\n    (candidate) => candidate.polygon?.length\n  )\n\n  return citation ? getCitationLocation(citation) : undefined\n}\n\nexport function getReviewFieldLocation(\n  field: ReviewField | undefined,\n  resolveLocation?: (metadataPath: string) => ReviewLocation | undefined\n) {\n  if (!field) return undefined\n\n  return (\n    field.location ??\n    resolveLocation?.(field.metadataPath ?? field.key) ??\n    undefined\n  )\n}\n\nexport function getReviewLocationKey(location: ReviewLocation | undefined) {\n  if (!location) return null\n\n  const { area } = location\n  return [location.page, area.left, area.top, area.width, area.height].join(":")\n}\n\nfunction valuesFromFields(\n  fields: ReviewField[],\n  valueKey: "actual" | "expected"\n) {\n  return fields.reduce<JsonObject>((values, field) => {\n    values[field.key] = field[valueKey]\n    return values\n  }, {})\n}\n\nfunction formatJson(value: unknown) {\n  return JSON.stringify(value, null, 2)\n}\n\nfunction isJsonObject(value: JsonValue): value is JsonObject {\n  return typeof value === "object" && value !== null && !Array.isArray(value)\n}\n\nfunction isJsonArray(value: JsonValue): value is JsonArray {\n  return Array.isArray(value)\n}\n\nfunction getObjectValue(value: JsonValue, key: string): JsonValue {\n  if (!isJsonObject(value)) return null\n  return value[key] ?? null\n}\n\nfunction setObjectValue(\n  value: JsonValue,\n  key: string,\n  childValue: JsonValue\n): JsonObject {\n  return {\n    ...(isJsonObject(value) ? value : {}),\n    [key]: childValue,\n  }\n}\n\nfunction getArrayValue(value: JsonValue): JsonArray {\n  return isJsonArray(value) ? value : []\n}\n\nfunction setArrayItemValue(\n  value: JsonValue,\n  index: number,\n  childValue: JsonValue\n): JsonArray {\n  const nextValue = getArrayValue(value).slice()\n  nextValue[index] = childValue\n  return nextValue\n}\n\nfunction getPrimitiveValue(value: JsonValue): JsonPrimitive {\n  return isJsonObject(value) || isJsonArray(value) ? null : value\n}\n\nfunction jsonValuesEqual(left: JsonValue, right: JsonValue) {\n  return formatJson(left) === formatJson(right)\n}\n\nexport function findReviewField(\n  fields: ReviewField[],\n  fieldKey: string | undefined\n): ReviewField | undefined {\n  if (!fieldKey) return undefined\n\n  for (const field of fields) {\n    if (field.key === fieldKey) return field\n\n    if (field.schema.type === "object") {\n      const childFields = Object.entries(field.schema.properties ?? {}).map(\n        ([key, schema]): ReviewField => ({\n          key: `${field.key}.${key}`,\n          schema,\n          actual: getObjectValue(field.actual, key),\n          expected: getObjectValue(field.expected, key),\n          metadataPath: `${field.metadataPath ?? field.key}.${key}`,\n        })\n      )\n      const childField = findReviewField(childFields, fieldKey)\n      if (childField) return childField\n    }\n  }\n\n  return undefined\n}\n\nfunction formatValue(value: JsonValue) {\n  if (value === null) return "NULL"\n  if (isJsonObject(value) || isJsonArray(value)) return formatJson(value)\n  if (typeof value === "boolean") return value ? "true" : "false"\n  return String(value)\n}\n\nfunction areGridRangesEqual(\n  left: Readonly<Rectangle> | undefined,\n  right: Readonly<Rectangle> | undefined\n) {\n  return (\n    left === right ||\n    (left !== undefined &&\n      right !== undefined &&\n      left.x === right.x &&\n      left.y === right.y &&\n      left.width === right.width &&\n      left.height === right.height)\n  )\n}\n\nfunction areGridRangeStacksEqual(\n  left: readonly Readonly<Rectangle>[] | undefined,\n  right: readonly Readonly<Rectangle>[] | undefined\n) {\n  if (left === right) return true\n  if (!left || !right || left.length !== right.length) return false\n\n  return left.every((range, index) => areGridRangesEqual(range, right[index]))\n}\n\nfunction areGridSelectionsEqual(left: GridSelection, right: GridSelection) {\n  const leftCurrent = left.current\n  const rightCurrent = right.current\n\n  return (\n    leftCurrent?.cell[0] === rightCurrent?.cell[0] &&\n    leftCurrent?.cell[1] === rightCurrent?.cell[1] &&\n    areGridRangesEqual(leftCurrent?.range, rightCurrent?.range) &&\n    areGridRangeStacksEqual(\n      leftCurrent?.rangeStack,\n      rightCurrent?.rangeStack\n    ) &&\n    left.columns.equals(right.columns) &&\n    left.rows.equals(right.rows)\n  )\n}\n\nfunction getGridSelectionRanges(selection: GridSelection | undefined) {\n  const current = selection?.current\n  if (!current) return []\n\n  return [...(current.rangeStack ?? []), current.range]\n}\n\nfunction areArrayNestedViewsEqual(\n  left: ArrayNestedView[],\n  right: ArrayNestedView[]\n) {\n  if (left === right) return true\n  if (left.length !== right.length) return false\n\n  return left.every((view, index) => {\n    const other = right[index]\n\n    return (\n      view.rowIndex === other?.rowIndex &&\n      view.columnId === other.columnId &&\n      view.title === other.title &&\n      view.schema === other.schema &&\n      Object.is(view.value, other.value)\n    )\n  })\n}\n\ntype HumanReviewOverlayCell = TextCell | NumberCell\n\ntype HumanReviewTextOverlayEditorProps = React.ComponentProps<\n  ProvideEditorComponent<HumanReviewOverlayCell>\n> & {\n  overlayOpenRef: React.RefObject<boolean>\n  readOnly?: boolean\n}\n\nfunction HumanReviewTextOverlayEditor({\n  isHighlighted,\n  onFinishedEditing,\n  overlayOpenRef,\n  readOnly = false,\n  validatedSelection,\n  value,\n}: HumanReviewTextOverlayEditorProps) {\n  const initialValue =\n    value.kind === GridCellKind.Number ? value.displayData : value.data\n  const [entryValue, setEntryValue] = React.useState(initialValue)\n  const latestValueRef = React.useRef(initialValue)\n  const finishedRef = React.useRef(false)\n\n  const finishEditing = React.useCallback(\n    (\n      shouldSave: boolean,\n      movement: readonly [-1 | 0 | 1, -1 | 0 | 1] = [0, 0]\n    ) => {\n      if (finishedRef.current) return\n\n      finishedRef.current = true\n      overlayOpenRef.current = false\n\n      if (!shouldSave || readOnly) {\n        onFinishedEditing(undefined, movement)\n        return\n      }\n\n      if (value.kind === GridCellKind.Number) {\n        const numericValue = Number(latestValueRef.current)\n\n        onFinishedEditing(\n          {\n            ...value,\n            data: Number.isFinite(numericValue) ? numericValue : value.data,\n            displayData: latestValueRef.current,\n          },\n          movement\n        )\n        return\n      }\n\n      onFinishedEditing(\n        {\n          ...value,\n          data: latestValueRef.current,\n          displayData: latestValueRef.current,\n        },\n        movement\n      )\n    },\n    [onFinishedEditing, overlayOpenRef, readOnly, value]\n  )\n\n  const handleEntryChange = React.useCallback(\n    (event: React.ChangeEvent<HTMLTextAreaElement>) => {\n      event.stopPropagation()\n      latestValueRef.current = event.target.value\n      setEntryValue(event.target.value)\n    },\n    []\n  )\n  const handleKeyDown = React.useCallback(\n    (event: React.KeyboardEvent<HTMLTextAreaElement>) => {\n      event.stopPropagation()\n\n      if (event.key === "Escape") {\n        event.preventDefault()\n        finishEditing(false)\n        return\n      }\n\n      if (event.key === "Tab") {\n        event.preventDefault()\n        finishEditing(true, [event.shiftKey ? -1 : 1, 0])\n        return\n      }\n\n      if (event.key === "Enter" && !event.shiftKey) {\n        event.preventDefault()\n        finishEditing(true, [0, 1])\n      }\n    },\n    [finishEditing]\n  )\n\n  React.useEffect(() => {\n    overlayOpenRef.current = true\n\n    return () => {\n      overlayOpenRef.current = false\n    }\n  }, [overlayOpenRef])\n\n  React.useEffect(() => {\n    const handlePointerOutside = (event: PointerEvent | MouseEvent) => {\n      const input = document.querySelector<HTMLTextAreaElement>(".gdg-input")\n      const overlayRoot = input?.closest(".gdg-clip-region")\n\n      if (!overlayRoot || overlayRoot.contains(event.target as Node | null)) {\n        return\n      }\n\n      finishEditing(true)\n    }\n\n    document.addEventListener("pointerdown", handlePointerOutside, true)\n    document.addEventListener("contextmenu", handlePointerOutside, true)\n\n    return () => {\n      document.removeEventListener("pointerdown", handlePointerOutside, true)\n      document.removeEventListener("contextmenu", handlePointerOutside, true)\n    }\n  }, [finishEditing])\n\n  return (\n    <TextCellEntry\n      autoFocus={!readOnly}\n      disabled={readOnly}\n      highlight={isHighlighted}\n      value={entryValue}\n      validatedSelection={validatedSelection}\n      altNewline\n      onChange={handleEntryChange}\n      onKeyDown={handleKeyDown}\n    />\n  )\n}\n\nfunction getFieldIcon(type: SchemaPropertyType) {\n  if (type === "number" || type === "integer") return InputNumericGlyph\n  if (type === "boolean") return TextCheckGlyph\n  if (type === "array") return SecondBracketGlyph\n  if (type === "object") return SourceCodeSquareGlyph\n  return InputTextGlyph\n}\n\nfunction HumanReviewValueInput({\n  readOnly = false,\n  schema,\n  value,\n  onChange,\n}: {\n  readOnly?: boolean\n  schema: ReviewFieldSchema\n  value: JsonPrimitive\n  onChange: (value: JsonPrimitive) => void\n}) {\n  if (schema.enum?.length) {\n    return (\n      <span className="relative inline-flex w-full rounded-lg border border-input bg-background text-sm text-foreground shadow-xs/5 dark:bg-input/32">\n        <select\n          disabled={readOnly}\n          value={value === null ? "" : String(value)}\n          onChange={(event) => onChange(event.target.value)}\n          className="h-8.5 w-full appearance-none rounded-[inherit] bg-transparent px-3 text-sm outline-none sm:h-7.5"\n        >\n          {schema.enum.map((option) => (\n            <option key={String(option)} value={String(option)}>\n              {String(option)}\n            </option>\n          ))}\n        </select>\n      </span>\n    )\n  }\n\n  if (schema.type === "number" || schema.type === "integer") {\n    return (\n      <Input\n        nativeInput\n        readOnly={readOnly}\n        type="number"\n        value={value === null ? "" : String(value)}\n        onChange={(event) => {\n          const nextValue = event.currentTarget.value\n          onChange(nextValue === "" ? null : Number(nextValue))\n        }}\n      />\n    )\n  }\n\n  if (schema.type === "boolean") {\n    return (\n      <div className="grid grid-cols-2 gap-1 rounded-lg bg-muted p-0.5">\n        {[true, false].map((option) => (\n          <Button\n            key={String(option)}\n            type="button"\n            size="sm"\n            variant={value === option ? "outline" : "ghost"}\n            className={cn(\n              "h-7 shadow-none",\n              value === option && "bg-background dark:bg-input"\n            )}\n            disabled={readOnly}\n            onClick={() => onChange(option)}\n          >\n            {option ? "True" : "False"}\n          </Button>\n        ))}\n      </div>\n    )\n  }\n\n  return (\n    <Input\n      nativeInput\n      readOnly={readOnly}\n      value={value === null ? "" : String(value)}\n      onChange={(event) => onChange(event.currentTarget.value)}\n    />\n  )\n}\n\nfunction getArrayItemSchema(schema: ReviewFieldSchema): ReviewFieldSchema {\n  return schema.items ?? { type: "string" }\n}\n\nfunction isComplexSchema(schema: ReviewFieldSchema) {\n  return schema.type === "object" || schema.type === "array"\n}\n\nfunction summarizeComplexValue(value: JsonValue) {\n  if (isJsonArray(value)) return `${value.length} items`\n  if (isJsonObject(value)) return `${Object.keys(value).length} fields`\n  return formatValue(value)\n}\n\nfunction getCellValueForArrayColumn(\n  rowValue: JsonValue,\n  itemSchema: ReviewFieldSchema,\n  columnId: string\n) {\n  if (itemSchema.type === "object") {\n    return getObjectValue(rowValue, columnId)\n  }\n\n  return rowValue\n}\n\nfunction getCellSchemaForArrayColumn(\n  itemSchema: ReviewFieldSchema,\n  columnId: string\n) {\n  if (itemSchema.type === "object") {\n    return itemSchema.properties?.[columnId] ?? { type: "string" }\n  }\n\n  return itemSchema\n}\n\nfunction applyPrimitiveEdit(\n  schema: ReviewFieldSchema,\n  value: EditableGridCell\n): JsonValue | undefined {\n  if (schema.type === "boolean" && value.kind === GridCellKind.Boolean) {\n    return value.data\n  }\n\n  if (\n    (schema.type === "number" || schema.type === "integer") &&\n    value.kind === GridCellKind.Number\n  ) {\n    return value.data ?? null\n  }\n\n  if (value.kind === GridCellKind.Text) {\n    if (schema.type === "number" || schema.type === "integer") {\n      return value.data.trim() === "" ? null : Number(value.data)\n    }\n\n    return value.data\n  }\n\n  return undefined\n}\n\ntype ArrayNestedView = {\n  rowIndex: number\n  columnId: string\n  title: string\n  schema: ReviewFieldSchema\n  value: JsonValue\n}\n\ntype ArrayReviewSide = "actual" | "expected"\n\ntype SyncedArrayNestedView = {\n  activeSide: ArrayReviewSide | null\n  stack: ArrayNestedView[]\n}\n\ntype SyncedArraySelection = {\n  activeSide: ArrayReviewSide | null\n  depth: number\n  gridSelection: GridSelection\n}\n\nexport type HumanReviewTheme = "light" | "dark"\n\nconst EMPTY_SYNCED_ARRAY_NESTED_VIEW: SyncedArrayNestedView = {\n  activeSide: null,\n  stack: [],\n}\n\nconst EMPTY_SYNCED_ARRAY_SELECTION: SyncedArraySelection = {\n  activeSide: null,\n  depth: 0,\n  gridSelection: emptyGridSelection,\n}\n\nfunction setNestedArrayValue({\n  value,\n  schema,\n  nestedStack,\n  nextNestedValue,\n}: {\n  value: JsonValue\n  schema: ReviewFieldSchema\n  nestedStack: ArrayNestedView[]\n  nextNestedValue: JsonValue\n}): JsonValue {\n  const [currentView, ...remainingViews] = nestedStack\n\n  if (!currentView) return nextNestedValue\n\n  const itemSchema = getArrayItemSchema(schema)\n  const rowValue = getArrayValue(value)[currentView.rowIndex] ?? null\n  const cellSchema = getCellSchemaForArrayColumn(\n    itemSchema,\n    currentView.columnId\n  )\n  const currentCellValue = getCellValueForArrayColumn(\n    rowValue,\n    itemSchema,\n    currentView.columnId\n  )\n  const nextCellValue: JsonValue = remainingViews.length\n    ? setNestedArrayValue({\n        value: currentCellValue,\n        schema: cellSchema,\n        nestedStack: remainingViews,\n        nextNestedValue,\n      })\n    : nextNestedValue\n  const nextRowValue: JsonValue =\n    itemSchema.type === "object"\n      ? setObjectValue(rowValue, currentView.columnId, nextCellValue)\n      : nextCellValue\n\n  return setArrayItemValue(value, currentView.rowIndex, nextRowValue)\n}\n\nfunction getNestedArrayValue({\n  value,\n  schema,\n  nestedStack,\n}: {\n  value: JsonValue\n  schema: ReviewFieldSchema\n  nestedStack: ArrayNestedView[]\n}): JsonValue {\n  const [currentView, ...remainingViews] = nestedStack\n\n  if (!currentView) return value\n\n  const itemSchema = getArrayItemSchema(schema)\n  const rowValue = getArrayValue(value)[currentView.rowIndex] ?? null\n  const cellSchema = getCellSchemaForArrayColumn(\n    itemSchema,\n    currentView.columnId\n  )\n  const cellValue = getCellValueForArrayColumn(\n    rowValue,\n    itemSchema,\n    currentView.columnId\n  )\n\n  if (!remainingViews.length) return cellValue\n\n  return getNestedArrayValue({\n    value: cellValue,\n    schema: cellSchema,\n    nestedStack: remainingViews,\n  })\n}\n\nfunction HumanReviewArrayValueGrid({\n  activeNestedSide = null,\n  activeSelectionSide = null,\n  label,\n  nestedStackBaseDepth = 0,\n  readOnly = false,\n  schema,\n  selectionDepth = 0,\n  sharedGridSelection,\n  sharedNestedStack,\n  value,\n  viewSide = "expected",\n  metadataPath,\n  onChange,\n  onGridSelectionChange,\n  onLocationHover,\n  onNestedStackChange,\n  resolveArrayItemMetadataPath,\n  resolveLocation,\n}: {\n  activeNestedSide?: ArrayReviewSide | null\n  activeSelectionSide?: ArrayReviewSide | null\n  label: string\n  nestedStackBaseDepth?: number\n  readOnly?: boolean\n  schema: ReviewFieldSchema\n  selectionDepth?: number\n  sharedGridSelection?: GridSelection\n  sharedNestedStack?: ArrayNestedView[]\n  value: JsonValue\n  viewSide?: ArrayReviewSide\n  metadataPath?: string\n  onChange?: (value: JsonValue) => void\n  onGridSelectionChange?: (\n    selection: GridSelection,\n    side: ArrayReviewSide,\n    depth: number\n  ) => void\n  onNestedStackChange?: (\n    stack: ArrayNestedView[],\n    side: ArrayReviewSide\n  ) => void\n  onLocationHover?: (location?: ReviewLocation) => void\n  resolveArrayItemMetadataPath?: (\n    metadataPath: string,\n    rowIndex: number,\n    rowValue: JsonValue\n  ) => string | undefined\n  resolveLocation?: (metadataPath: string) => ReviewLocation | undefined\n}) {\n  const rows = getArrayValue(value)\n  const itemSchema = getArrayItemSchema(schema)\n  const gridTheme = useHumanReviewGridTheme()\n  const isDark = useIsDarkTheme()\n  const [localNestedStack, setLocalNestedStack] = React.useState<\n    ArrayNestedView[]\n  >([])\n  const [localGridSelection, setLocalGridSelection] =\n    React.useState<GridSelection>(emptyGridSelection)\n  const fastTextOverlayOpenRef = React.useRef(false)\n  const nestedStack = sharedNestedStack ?? localNestedStack\n  const visibleNestedStack = nestedStack.slice(nestedStackBaseDepth)\n  const activeNestedView = visibleNestedStack[0] ?? null\n  const activeNestedValue = activeNestedView\n    ? getNestedArrayValue({\n        value,\n        schema,\n        nestedStack: [activeNestedView],\n      })\n    : null\n  const isActiveNestedSource =\n    Boolean(activeNestedView) && activeNestedSide === viewSide\n  const isMirroredNestedTarget =\n    Boolean(activeNestedView) &&\n    activeNestedSide !== null &&\n    activeNestedSide !== viewSide\n  const blueCellText = isDark ? "rgb(147, 197, 253)" : "rgb(37, 99, 235)"\n  const selectedCellBackground = isDark\n    ? "rgba(37, 99, 235, 0.2)"\n    : "rgba(219, 234, 254, 0.85)"\n  const mirroredCellBackground = isDark\n    ? "rgba(167, 139, 250, 0.18)"\n    : "rgba(237, 233, 254, 0.9)"\n  const mirroredHighlightRegions = React.useMemo<\n    React.ComponentProps<typeof DataEditor>["highlightRegions"]\n  >(() => {\n    if (\n      !activeSelectionSide ||\n      activeSelectionSide === viewSide ||\n      selectionDepth !== nestedStackBaseDepth\n    ) {\n      return undefined\n    }\n\n    const ranges = getGridSelectionRanges(sharedGridSelection)\n    if (!ranges.length) return undefined\n\n    return ranges.map((range) => ({\n      color: mirroredCellBackground,\n      range,\n      style: "dashed" as const,\n    }))\n  }, [\n    activeSelectionSide,\n    mirroredCellBackground,\n    nestedStackBaseDepth,\n    selectionDepth,\n    sharedGridSelection,\n    viewSide,\n  ])\n\n  const setNestedStack = React.useCallback(\n    (\n      updater:\n        | ArrayNestedView[]\n        | ((current: ArrayNestedView[]) => ArrayNestedView[])\n    ) => {\n      if (onNestedStackChange) {\n        const nextStack =\n          typeof updater === "function" ? updater(nestedStack) : updater\n\n        onNestedStackChange(nextStack, viewSide)\n        return\n      }\n\n      setLocalNestedStack(updater)\n    },\n    [nestedStack, onNestedStackChange, viewSide]\n  )\n\n  const handleGridSelectionChange = React.useCallback(\n    (selection: GridSelection) => {\n      flushSync(() => {\n        setLocalGridSelection((current) =>\n          areGridSelectionsEqual(current, selection) ? current : selection\n        )\n      })\n\n      if (onGridSelectionChange) {\n        if (\n          activeSelectionSide === viewSide &&\n          sharedGridSelection &&\n          areGridSelectionsEqual(sharedGridSelection, selection)\n        ) {\n          return\n        }\n\n        React.startTransition(() => {\n          onGridSelectionChange(selection, viewSide, nestedStackBaseDepth)\n        })\n        return\n      }\n    },\n    [\n      activeSelectionSide,\n      nestedStackBaseDepth,\n      onGridSelectionChange,\n      sharedGridSelection,\n      viewSide,\n    ]\n  )\n\n  const columns = React.useMemo<GridColumn[]>(() => {\n    if (itemSchema.type === "object") {\n      const propertyEntries = Object.entries(itemSchema.properties ?? {})\n\n      if (propertyEntries.length) {\n        return propertyEntries.map(([key, propertySchema]) => ({\n          id: key,\n          title: propertySchema.title ?? key,\n          width: isComplexSchema(propertySchema) ? 148 : 132,\n        }))\n      }\n    }\n\n    return [\n      {\n        id: "value",\n        title: itemSchema.title ?? "Value",\n        width: isComplexSchema(itemSchema) ? 148 : 180,\n      },\n    ]\n  }, [itemSchema])\n\n  const getCellContent = React.useCallback(\n    ([col, row]: Item): GridCell => {\n      const column = columns[col]\n      const columnId = String(column?.id ?? "value")\n      const rowValue = rows[row] ?? null\n      const cellSchema = getCellSchemaForArrayColumn(itemSchema, columnId)\n      const cellValue = getCellValueForArrayColumn(\n        rowValue,\n        itemSchema,\n        columnId\n      )\n      const matchedNestedCell =\n        activeNestedView?.rowIndex === row &&\n        activeNestedView.columnId === columnId\n      const nestedCellTheme: Partial<Theme> | undefined = matchedNestedCell\n        ? {\n            bgCell: isMirroredNestedTarget\n              ? mirroredCellBackground\n              : selectedCellBackground,\n            textDark: blueCellText,\n          }\n        : undefined\n\n      if (isComplexSchema(cellSchema)) {\n        return {\n          kind: GridCellKind.Text,\n          data: summarizeComplexValue(cellValue),\n          displayData: summarizeComplexValue(cellValue),\n          allowOverlay: false,\n          readonly: true,\n          cursor: "pointer",\n          activationBehaviorOverride: "double-click",\n          themeOverride: {\n            textDark: blueCellText,\n            ...(nestedCellTheme ?? {}),\n          },\n        }\n      }\n\n      if (cellSchema.type === "boolean") {\n        return {\n          kind: GridCellKind.Boolean,\n          data: typeof cellValue === "boolean" ? cellValue : false,\n          allowOverlay: false,\n          readonly: readOnly,\n        }\n      }\n\n      if (cellSchema.type === "number" || cellSchema.type === "integer") {\n        return {\n          kind: GridCellKind.Number,\n          data: typeof cellValue === "number" ? cellValue : undefined,\n          displayData: typeof cellValue === "number" ? String(cellValue) : "",\n          allowOverlay: true,\n          readonly: false,\n        }\n      }\n\n      return {\n        kind: GridCellKind.Text,\n        data:\n          cellValue === null ||\n          isJsonObject(cellValue) ||\n          isJsonArray(cellValue)\n            ? ""\n            : String(cellValue),\n        displayData:\n          cellValue === null ||\n          isJsonObject(cellValue) ||\n          isJsonArray(cellValue)\n            ? ""\n            : String(cellValue),\n        allowOverlay: true,\n        readonly: false,\n      }\n    },\n    [\n      activeNestedView,\n      blueCellText,\n      columns,\n      isMirroredNestedTarget,\n      itemSchema,\n      mirroredCellBackground,\n      readOnly,\n      rows,\n      selectedCellBackground,\n    ]\n  )\n\n  const updateCellValue = React.useCallback(\n    ([col, row]: Item, nextCell: EditableGridCell) => {\n      if (readOnly || !onChange) return\n\n      const column = columns[col]\n      const columnId = String(column?.id ?? "value")\n      const rowValue = rows[row] ?? null\n      const cellSchema = getCellSchemaForArrayColumn(itemSchema, columnId)\n      const nextValue = applyPrimitiveEdit(cellSchema, nextCell)\n\n      if (nextValue === undefined) return\n\n      const nextRowValue =\n        itemSchema.type === "object"\n          ? setObjectValue(rowValue, columnId, nextValue)\n          : nextValue\n\n      onChange(setArrayItemValue(value, row, nextRowValue))\n    },\n    [columns, itemSchema, onChange, readOnly, rows, value]\n  )\n  const provideEditor = React.useCallback<\n    NonNullable<React.ComponentProps<typeof DataEditor>["provideEditor"]>\n  >(\n    (cell) => {\n      if (\n        cell.kind !== GridCellKind.Text &&\n        cell.kind !== GridCellKind.Number\n      ) {\n        return undefined\n      }\n\n      return {\n        editor: (props) => {\n          if (\n            props.value.kind !== GridCellKind.Text &&\n            props.value.kind !== GridCellKind.Number\n          ) {\n            return null\n          }\n\n          return (\n            <HumanReviewTextOverlayEditor\n              {...(props as React.ComponentProps<\n                ProvideEditorComponent<HumanReviewOverlayCell>\n              >)}\n              overlayOpenRef={fastTextOverlayOpenRef}\n              readOnly={readOnly}\n            />\n          )\n        },\n      }\n    },\n    [readOnly]\n  )\n  const handleOutsideClick = React.useCallback(\n    () => !fastTextOverlayOpenRef.current,\n    []\n  )\n  const handleItemHovered = React.useCallback(\n    (args: GridMouseEventArgs) => {\n      if (!onLocationHover || !resolveLocation || !metadataPath) return\n\n      if (args.kind !== "cell") {\n        onLocationHover(undefined)\n        return\n      }\n\n      const [col, row] = args.location\n      const column = columns[col]\n      const rowValue = rows[row]\n      if (!column || rowValue === undefined) {\n        onLocationHover(undefined)\n        return\n      }\n\n      const columnId = String(column.id ?? "value")\n      const rowMetadataPath = resolveArrayItemMetadataPath\n        ? resolveArrayItemMetadataPath(metadataPath, row, rowValue)\n        : `${metadataPath}[${row}]`\n      if (!rowMetadataPath) {\n        onLocationHover(undefined)\n        return\n      }\n\n      const propertyMetadataPath =\n        itemSchema.type === "object"\n          ? `${rowMetadataPath}.${columnId}`\n          : rowMetadataPath\n\n      onLocationHover(\n        resolveLocation(propertyMetadataPath) ??\n          resolveLocation(rowMetadataPath)\n      )\n    },\n    [\n      columns,\n      itemSchema.type,\n      metadataPath,\n      onLocationHover,\n      resolveArrayItemMetadataPath,\n      resolveLocation,\n      rows,\n    ]\n  )\n\n  const openNestedCell = React.useCallback(\n    ([col, row]: Item) => {\n      const column = columns[col]\n      const columnId = String(column?.id ?? "value")\n      const rowValue = rows[row] ?? null\n      const cellSchema = getCellSchemaForArrayColumn(itemSchema, columnId)\n\n      if (!isComplexSchema(cellSchema)) return\n\n      setNestedStack((current) => {\n        const nextView = {\n          rowIndex: row,\n          columnId,\n          title: `${column?.title ?? columnId} / row ${row + 1}`,\n          schema: cellSchema,\n          value: getCellValueForArrayColumn(rowValue, itemSchema, columnId),\n        }\n        const currentView = current[nestedStackBaseDepth]\n\n        if (\n          currentView?.rowIndex === nextView.rowIndex &&\n          currentView.columnId === nextView.columnId\n        ) {\n          return current\n        }\n\n        return [...current.slice(0, nestedStackBaseDepth), nextView]\n      })\n    },\n    [columns, itemSchema, nestedStackBaseDepth, rows, setNestedStack]\n  )\n\n  const updateNestedValue = React.useCallback(\n    (nextNestedValue: JsonValue) => {\n      if (!activeNestedView || readOnly || !onChange) return\n\n      onChange(\n        setNestedArrayValue({\n          value,\n          schema,\n          nestedStack: visibleNestedStack.slice(0, 1),\n          nextNestedValue,\n        })\n      )\n      setNestedStack((current) =>\n        current.map((view, index) =>\n          index === nestedStackBaseDepth\n            ? { ...view, value: nextNestedValue }\n            : view\n        )\n      )\n    },\n    [\n      activeNestedView,\n      nestedStackBaseDepth,\n      onChange,\n      readOnly,\n      schema,\n      setNestedStack,\n      value,\n      visibleNestedStack,\n    ]\n  )\n\n  return (\n    <div\n      onMouseLeave={() => onLocationHover?.(undefined)}\n      className={cn(\n        "relative overflow-hidden rounded-md border bg-background transition-[border-color,background-color,box-shadow] focus-within:border-blue-500/50 focus-within:shadow-[0_0_0_1px_rgb(59_130_246_/_8%)] hover:border-blue-500/50",\n        isActiveNestedSource &&\n          "border-blue-500/60 bg-blue-500/5 shadow-[0_0_0_1px_rgb(59_130_246_/_10%)]"\n      )}\n    >\n      <div>\n        <div className="flex h-8 items-center justify-between gap-2 border-b px-2 text-[11px] font-medium text-muted-foreground">\n          <span>{label}</span>\n          <span>{rows.length} rows</span>\n        </div>\n        <div className="h-[220px]">\n          <DataEditor\n            columns={columns}\n            rows={rows.length}\n            getCellContent={getCellContent}\n            cellActivationBehavior="double-click"\n            gridSelection={localGridSelection}\n            highlightRegions={mirroredHighlightRegions}\n            onCellEdited={updateCellValue}\n            onCellActivated={openNestedCell}\n            onGridSelectionChange={handleGridSelectionChange}\n            onItemHovered={handleItemHovered}\n            provideEditor={provideEditor}\n            isOutsideClick={handleOutsideClick}\n            rowMarkers="number"\n            smoothScrollX\n            smoothScrollY\n            theme={gridTheme}\n            width="100%"\n            height="100%"\n            rowHeight={32}\n            headerHeight={34}\n          />\n        </div>\n      </div>\n      {activeNestedView ? (\n        <div className="absolute inset-0 z-10 flex flex-col bg-background">\n          <div className="flex h-8 items-center gap-2 border-b px-2">\n            <Button\n              type="button"\n              variant="ghost"\n              size="icon-sm"\n              className="size-6 text-muted-foreground"\n              onClick={() =>\n                setNestedStack((current) =>\n                  current.slice(\n                    0,\n                    Math.max(nestedStackBaseDepth, current.length - 1)\n                  )\n                )\n              }\n              aria-label="Back to parent array"\n            >\n              <IconPlaceholder\n                lucide="ChevronLeft"\n                tabler="IconChevronLeft"\n                hugeicons="ArrowLeft01Icon"\n                phosphor="CaretLeftIcon"\n                remixicon="RiArrowLeftSLine"\n                className="size-3.5"\n              />\n            </Button>\n            <div className="min-w-0 flex-1 truncate text-xs font-medium text-foreground">\n              {activeNestedView.title}\n            </div>\n          </div>\n          <div className="min-h-0 flex-1 overflow-auto p-2">\n            {activeNestedView.schema.type === "array" ? (\n              <HumanReviewArrayValueGrid\n                label={\n                  activeNestedView.schema.title ?? activeNestedView.columnId\n                }\n                nestedStackBaseDepth={nestedStackBaseDepth + 1}\n                readOnly={readOnly}\n                schema={activeNestedView.schema}\n                sharedGridSelection={sharedGridSelection}\n                sharedNestedStack={sharedNestedStack}\n                value={activeNestedValue}\n                viewSide={viewSide}\n                activeNestedSide={activeNestedSide}\n                activeSelectionSide={activeSelectionSide}\n                selectionDepth={selectionDepth}\n                onChange={updateNestedValue}\n                onGridSelectionChange={onGridSelectionChange}\n                onNestedStackChange={onNestedStackChange}\n                resolveArrayItemMetadataPath={resolveArrayItemMetadataPath}\n                resolveLocation={resolveLocation}\n              />\n            ) : (\n              <HumanReviewObjectValueEditor\n                schema={activeNestedView.schema}\n                value={activeNestedValue}\n                originalValue={activeNestedValue}\n                readOnly={readOnly}\n                onChange={updateNestedValue}\n              />\n            )}\n          </div>\n        </div>\n      ) : null}\n    </div>\n  )\n}\n\nfunction HumanReviewObjectValueEditor({\n  schema,\n  value,\n  originalValue,\n  readOnly = false,\n  onChange,\n}: {\n  schema: ReviewFieldSchema\n  value: JsonValue\n  originalValue: JsonValue\n  readOnly?: boolean\n  onChange: (value: JsonValue) => void\n}) {\n  const propertyEntries = Object.entries(schema.properties ?? {})\n\n  if (!propertyEntries.length) {\n    return (\n      <div className="rounded-md bg-background px-2 py-1.5 text-sm text-muted-foreground">\n        No properties\n      </div>\n    )\n  }\n\n  return (\n    <div className="space-y-2">\n      {propertyEntries.map(([propertyKey, propertySchema]) => (\n        <HumanReviewFieldCard\n          key={propertyKey}\n          field={{\n            key: propertyKey,\n            schema: propertySchema,\n            actual: getObjectValue(originalValue, propertyKey),\n            expected: getObjectValue(originalValue, propertyKey),\n          }}\n          value={getObjectValue(value, propertyKey)}\n          originalValue={getObjectValue(originalValue, propertyKey)}\n          readOnly={readOnly}\n          onChange={(childValue) =>\n            !readOnly &&\n            onChange(setObjectValue(value, propertyKey, childValue))\n          }\n          onUndo={() =>\n            !readOnly &&\n            onChange(\n              setObjectValue(\n                value,\n                propertyKey,\n                getObjectValue(originalValue, propertyKey)\n              )\n            )\n          }\n          onSetNull={() =>\n            !readOnly && onChange(setObjectValue(value, propertyKey, null))\n          }\n        />\n      ))}\n    </div>\n  )\n}\n\ntype HumanReviewFieldCardProps = {\n  field: ReviewField\n  value: JsonValue\n  originalValue: JsonValue\n  active?: boolean\n  activeFieldKey?: string\n  readOnly?: boolean\n  showExpected?: boolean\n  onChange: (value: JsonValue) => void\n  onFieldFocus?: (field: ReviewField) => void\n  onLocationHover?: (location?: ReviewLocation) => void\n  onUndo: () => void\n  onSetNull: () => void\n  resolveArrayItemMetadataPath?: (\n    metadataPath: string,\n    rowIndex: number,\n    rowValue: JsonValue\n  ) => string | undefined\n  resolveLocation?: (metadataPath: string) => ReviewLocation | undefined\n}\n\nfunction areHumanReviewFieldCardPropsEqual(\n  previous: HumanReviewFieldCardProps,\n  next: HumanReviewFieldCardProps\n) {\n  return (\n    previous.field === next.field &&\n    Object.is(previous.value, next.value) &&\n    Object.is(previous.originalValue, next.originalValue) &&\n    previous.active === next.active &&\n    previous.activeFieldKey === next.activeFieldKey &&\n    previous.readOnly === next.readOnly &&\n    previous.showExpected === next.showExpected &&\n    previous.onFieldFocus === next.onFieldFocus &&\n    previous.onLocationHover === next.onLocationHover &&\n    previous.resolveArrayItemMetadataPath ===\n      next.resolveArrayItemMetadataPath &&\n    previous.resolveLocation === next.resolveLocation\n  )\n}\n\nconst HumanReviewFieldCard = React.memo(\n  HumanReviewFieldCardBase,\n  areHumanReviewFieldCardPropsEqual\n)\n\nfunction HumanReviewFieldCardBase({\n  field,\n  value,\n  originalValue,\n  active,\n  activeFieldKey,\n  readOnly = false,\n  showExpected = true,\n  onChange,\n  onFieldFocus,\n  onLocationHover,\n  onUndo,\n  onSetNull,\n  resolveArrayItemMetadataPath,\n  resolveLocation,\n}: HumanReviewFieldCardProps) {\n  const isExpectedEditable = showExpected && !readOnly\n  const modified = showExpected && !jsonValuesEqual(value, originalValue)\n  const fieldTypeIcon = React.createElement(getFieldIcon(field.schema.type), {\n    className: "size-3.5",\n  })\n  const propertyEntries = Object.entries(field.schema.properties ?? {})\n  const [syncedArrayNestedView, setSyncedArrayNestedView] =\n    React.useState<SyncedArrayNestedView>(EMPTY_SYNCED_ARRAY_NESTED_VIEW)\n  const [syncedArraySelection, setSyncedArraySelection] =\n    React.useState<SyncedArraySelection>(EMPTY_SYNCED_ARRAY_SELECTION)\n  const updateSyncedArrayNestedView = React.useCallback(\n    (stack: ArrayNestedView[], side: ArrayReviewSide) => {\n      const activeSide = stack.length ? side : null\n\n      setSyncedArrayNestedView((current) =>\n        current.activeSide === activeSide &&\n        areArrayNestedViewsEqual(current.stack, stack)\n          ? current\n          : {\n              activeSide,\n              stack,\n            }\n      )\n    },\n    []\n  )\n  const updateSyncedArraySelection = React.useCallback(\n    (gridSelection: GridSelection, side: ArrayReviewSide, depth: number) => {\n      const activeSide = gridSelection.current ? side : null\n\n      setSyncedArraySelection((current) =>\n        current.activeSide === activeSide &&\n        current.depth === depth &&\n        areGridSelectionsEqual(current.gridSelection, gridSelection)\n          ? current\n          : {\n              activeSide,\n              depth,\n              gridSelection,\n            }\n      )\n    },\n    []\n  )\n  const focusAndHoverField = React.useCallback(() => {\n    onFieldFocus?.(field)\n    onLocationHover?.(getReviewFieldLocation(field, resolveLocation))\n  }, [field, onFieldFocus, onLocationHover, resolveLocation])\n\n  return (\n    <div\n      tabIndex={0}\n      onFocusCapture={focusAndHoverField}\n      onMouseEnter={focusAndHoverField}\n      onMouseLeave={() => onLocationHover?.(undefined)}\n      className={cn(\n        "rounded-lg border bg-background p-3 transition-[border-color,background-color,box-shadow] focus-within:border-blue-500/50 focus-within:bg-blue-500/5 hover:border-blue-500/50 hover:bg-blue-500/5 focus-visible:ring-2 focus-visible:ring-blue-500/20 focus-visible:outline-none",\n        active &&\n          "border-blue-500/60 bg-blue-500/5 shadow-[0_0_0_1px_rgb(59_130_246_/_8%)]"\n      )}\n    >\n      <div className="mb-3 flex min-h-8 items-start justify-between gap-3">\n        <div className="min-w-0">\n          <div className="flex min-w-0 items-center gap-2">\n            <div className="min-w-0">\n              <div className="truncate text-sm font-medium">\n                {field.schema.title ?? field.key}\n              </div>\n            </div>\n            <span\n              className={cn(\n                "size-2 shrink-0 rounded-full bg-amber-400",\n                !modified && "opacity-0"\n              )}\n            />\n          </div>\n          <div className="truncate text-xs text-muted-foreground">\n            {field.key}\n          </div>\n        </div>\n        <div className="flex shrink-0 items-center gap-1">\n          {isExpectedEditable && modified ? (\n            <Tooltip>\n              <TooltipTrigger asChild>\n                <Button\n                  type="button"\n                  variant="ghost"\n                  size="icon-sm"\n                  className="text-muted-foreground"\n                  onClick={onUndo}\n                  aria-label={`Undo ${field.key}`}\n                >\n                  <IconPlaceholder\n                    lucide="Undo2"\n                    tabler="IconArrowBackUp"\n                    hugeicons="Undo02Icon"\n                    phosphor="ArrowUUpLeftIcon"\n                    remixicon="RiArrowGoBackLine"\n                    className="size-4"\n                  />\n                </Button>\n              </TooltipTrigger>\n              <TooltipContent>Revert changes</TooltipContent>\n            </Tooltip>\n          ) : null}\n          {isExpectedEditable ? (\n            <Tooltip>\n              <TooltipTrigger asChild>\n                <Button\n                  type="button"\n                  variant="ghost"\n                  size="icon-sm"\n                  className="text-muted-foreground"\n                  onClick={onSetNull}\n                  aria-label={`Set ${field.key} to null`}\n                >\n                  <IconPlaceholder\n                    lucide="CircleX"\n                    tabler="IconCircleX"\n                    hugeicons="CancelCircleIcon"\n                    phosphor="XCircleIcon"\n                    remixicon="RiCloseCircleLine"\n                    className="size-4"\n                  />\n                </Button>\n              </TooltipTrigger>\n              <TooltipContent>Set to NULL</TooltipContent>\n            </Tooltip>\n          ) : null}\n          <div className="flex h-6 items-center gap-1 rounded-md border bg-muted/50 px-1.5 text-xs text-muted-foreground">\n            {fieldTypeIcon}\n            {field.schema.type}\n          </div>\n        </div>\n      </div>\n      {field.schema.type === "object" ? (\n        <div className="rounded-md border bg-muted/25 p-2">\n          <div className="mb-2 flex items-center justify-between gap-3 text-[11px] font-medium text-muted-foreground">\n            <span>Properties</span>\n            <span>{propertyEntries.length} fields</span>\n          </div>\n          <div className="space-y-2">\n            {propertyEntries.length ? (\n              propertyEntries.map(([propertyKey, schema]) => {\n                const childField: ReviewField = {\n                  key: `${field.key}.${propertyKey}`,\n                  schema,\n                  actual: getObjectValue(field.actual, propertyKey),\n                  expected: getObjectValue(originalValue, propertyKey),\n                  metadataPath: `${field.metadataPath ?? field.key}.${propertyKey}`,\n                }\n\n                return (\n                  <HumanReviewFieldCard\n                    key={childField.key}\n                    field={childField}\n                    value={getObjectValue(value, propertyKey)}\n                    originalValue={childField.expected}\n                    active={childField.key === activeFieldKey}\n                    activeFieldKey={activeFieldKey}\n                    readOnly={readOnly}\n                    showExpected={showExpected}\n                    onChange={(childValue) =>\n                      onChange(setObjectValue(value, propertyKey, childValue))\n                    }\n                    onFieldFocus={onFieldFocus}\n                    onLocationHover={onLocationHover}\n                    onUndo={() =>\n                      onChange(\n                        setObjectValue(value, propertyKey, childField.expected)\n                      )\n                    }\n                    onSetNull={() =>\n                      onChange(setObjectValue(value, propertyKey, null))\n                    }\n                    resolveArrayItemMetadataPath={resolveArrayItemMetadataPath}\n                    resolveLocation={resolveLocation}\n                  />\n                )\n              })\n            ) : (\n              <div className="rounded-md bg-background px-2 py-1.5 text-sm text-muted-foreground">\n                No properties\n              </div>\n            )}\n          </div>\n        </div>\n      ) : field.schema.type === "array" ? (\n        <div className="grid gap-2">\n          <HumanReviewArrayValueGrid\n            activeNestedSide={syncedArrayNestedView.activeSide}\n            activeSelectionSide={syncedArraySelection.activeSide}\n            label="Actual"\n            metadataPath={field.metadataPath ?? field.key}\n            readOnly\n            resolveArrayItemMetadataPath={resolveArrayItemMetadataPath}\n            resolveLocation={resolveLocation}\n            schema={field.schema}\n            selectionDepth={syncedArraySelection.depth}\n            sharedGridSelection={syncedArraySelection.gridSelection}\n            sharedNestedStack={syncedArrayNestedView.stack}\n            value={field.actual}\n            viewSide="actual"\n            onGridSelectionChange={updateSyncedArraySelection}\n            onLocationHover={onLocationHover}\n            onNestedStackChange={updateSyncedArrayNestedView}\n          />\n          {showExpected ? (\n            <HumanReviewArrayValueGrid\n              activeNestedSide={syncedArrayNestedView.activeSide}\n              activeSelectionSide={syncedArraySelection.activeSide}\n              label="Expected"\n              metadataPath={field.metadataPath ?? field.key}\n              readOnly={readOnly}\n              resolveArrayItemMetadataPath={resolveArrayItemMetadataPath}\n              resolveLocation={resolveLocation}\n              schema={field.schema}\n              selectionDepth={syncedArraySelection.depth}\n              sharedGridSelection={syncedArraySelection.gridSelection}\n              sharedNestedStack={syncedArrayNestedView.stack}\n              value={value}\n              viewSide="expected"\n              onChange={onChange}\n              onGridSelectionChange={updateSyncedArraySelection}\n              onLocationHover={onLocationHover}\n              onNestedStackChange={updateSyncedArrayNestedView}\n            />\n          ) : null}\n        </div>\n      ) : (\n        <div className={cn("grid gap-2", showExpected && "sm:grid-cols-2")}>\n          <div className="rounded-md border bg-muted/30 p-2">\n            {field.schema.description ? (\n              <p className="mb-2 text-xs text-muted-foreground">\n                {field.schema.description}\n              </p>\n            ) : null}\n            <div className="mb-1 text-[11px] font-medium text-muted-foreground">\n              Actual\n            </div>\n            <div className="min-h-7 rounded-md bg-background px-2 py-1.5 text-sm">\n              {formatValue(field.actual)}\n            </div>\n          </div>\n          {showExpected ? (\n            <div className="rounded-md border bg-muted/30 p-2">\n              <div className="mb-1 text-[11px] font-medium text-muted-foreground">\n                Expected\n              </div>\n              <HumanReviewValueInput\n                readOnly={readOnly}\n                schema={field.schema}\n                value={getPrimitiveValue(value)}\n                onChange={onChange}\n              />\n            </div>\n          ) : null}\n        </div>\n      )}\n    </div>\n  )\n}\n\nexport function HumanReviewHighlight({\n  location,\n}: {\n  location: ReviewLocation\n}) {\n  const area = location.area\n\n  return (\n    <div\n      className={cn(\n        "pointer-events-none absolute z-10 border",\n        REVIEW_HIGHLIGHT_STYLE\n      )}\n      style={{\n        left: `${area.left}%`,\n        top: `${area.top}%`,\n        width: `${area.width}%`,\n        height: `${area.height}%`,\n      }}\n    />\n  )\n}\n\nexport function JsonDiffView({\n  actual,\n  expected,\n  theme = "light",\n}: {\n  actual: JsonObject\n  expected: JsonObject\n  theme?: HumanReviewTheme\n}) {\n  const oldFile = React.useMemo(\n    () => ({\n      name: "actual.json",\n      contents: formatJson(actual),\n      lang: "json",\n    }),\n    [actual]\n  )\n  const newFile = React.useMemo(\n    () => ({\n      name: "expected.json",\n      contents: formatJson(expected),\n      lang: "json",\n    }),\n    [expected]\n  )\n\n  return (\n    <ScrollAreaVirtualizer\n      className="h-full bg-surface/60"\n      contentClassName="min-w-full"\n    >\n      <div className="bounding-box-citations-diff h-full text-xs">\n        <MultiFileDiff\n          className="block min-w-full"\n          oldFile={oldFile}\n          newFile={newFile}\n          options={{\n            diffStyle: "split",\n            disableFileHeader: true,\n            diffIndicators: "bars",\n            hunkSeparators: "line-info-basic",\n            overflow: "wrap",\n            themeType: theme,\n            theme: {\n              light: "pierre-light-soft",\n              dark: "pierre-dark-soft",\n            },\n          }}\n        />\n      </div>\n    </ScrollAreaVirtualizer>\n  )\n}\n\nexport function JsonCodeView({\n  name = "actual.json",\n  theme = "light",\n  value,\n}: {\n  name?: string\n  theme?: HumanReviewTheme\n  value: JsonValue\n}) {\n  const file = React.useMemo(() => {\n    const contents = formatJson(value)\n\n    return {\n      name,\n      contents,\n      lang: "json" as const,\n      cacheKey: contents,\n    }\n  }, [name, value])\n\n  return (\n    <div\n      data-rehype-pretty-code-figure\n      className="relative m-0! h-full overflow-hidden rounded-none! bg-code text-code-foreground"\n    >\n      <WorkerPoolContextProvider\n        poolOptions={CODE_WORKER_POOL_OPTIONS}\n        highlighterOptions={CODE_HIGHLIGHTER_OPTIONS}\n      >\n        <ScrollAreaVirtualizer\n          key={`${file.cacheKey}:${theme}`}\n          className="h-full min-w-0"\n          contentClassName="min-w-full"\n        >\n          <File\n            key={`${file.cacheKey}:${theme}`}\n            className="block min-w-full"\n            file={file}\n            metrics={CODE_VIRTUAL_FILE_METRICS}\n            style={CODE_FILE_THEME}\n            options={{\n              disableFileHeader: true,\n              overflow: "scroll",\n              themeType: theme,\n              theme: {\n                light: "pierre-light-soft",\n                dark: "pierre-dark-soft",\n              },\n            }}\n          />\n        </ScrollAreaVirtualizer>\n      </WorkerPoolContextProvider>\n    </div>\n  )\n}\n\nexport function HumanReviewPanel({\n  fields = REVIEW_FIELDS,\n  activeFieldKey,\n  className,\n  onFieldFocus,\n  onLocationHover,\n  resolveArrayItemMetadataPath,\n  resolveLocation,\n  showExpected = true,\n  theme = "light",\n}: {\n  fields?: ReviewField[]\n  activeFieldKey?: string\n  className?: string\n  onFieldFocus?: (field: ReviewField) => void\n  onLocationHover?: (location?: ReviewLocation) => void\n  resolveArrayItemMetadataPath?: (\n    metadataPath: string,\n    rowIndex: number,\n    rowValue: JsonValue\n  ) => string | undefined\n  resolveLocation?: (metadataPath: string) => ReviewLocation | undefined\n  showExpected?: boolean\n  theme?: HumanReviewTheme\n} = {}) {\n  const [activeTab, setActiveTab] = React.useState("form")\n  const actualValues = React.useMemo(\n    () => valuesFromFields(fields, "actual"),\n    [fields]\n  )\n  const initialExpectedValues = React.useMemo(\n    () => valuesFromFields(fields, "expected"),\n    [fields]\n  )\n  const [expected, setExpected] = React.useState<JsonObject>(\n    initialExpectedValues\n  )\n\n  const [previousExpectedValues, setPreviousExpectedValues] = React.useState(\n    initialExpectedValues\n  )\n  if (!Object.is(previousExpectedValues, initialExpectedValues)) {\n    setPreviousExpectedValues(initialExpectedValues)\n    setExpected(initialExpectedValues)\n  }\n\n  const updateValue = React.useCallback((key: string, value: JsonValue) => {\n    setExpected((current) =>\n      Object.is(current[key], value) ? current : { ...current, [key]: value }\n    )\n  }, [])\n\n  return (\n    <TooltipProvider delay={200}>\n      <Tabs\n        value={activeTab}\n        onValueChange={setActiveTab}\n        className={cn("flex h-[560px] flex-col gap-0 bg-background", className)}\n      >\n        <div className="flex min-h-12 items-center justify-between gap-3 border-b px-3">\n          <TabsList className="h-8 sm:h-7">\n            <TabsTrigger value="form" className="h-7 sm:h-6">\n              <IconPlaceholder\n                lucide="CaptionsIcon"\n                tabler="IconTextCaption"\n                hugeicons="TextCheckIcon"\n                phosphor="TextTIcon"\n                remixicon="RiTextWrap"\n                className="size-4"\n              />\n              Form\n            </TabsTrigger>\n            <TabsTrigger value="json" className="h-7 sm:h-6">\n              <IconPlaceholder\n                lucide="SquareCode"\n                tabler="IconSourceCode"\n                hugeicons="SourceCodeSquareIcon"\n                phosphor="CodeIcon"\n                remixicon="RiCodeBlock"\n                className="size-4"\n              />\n              JSON\n            </TabsTrigger>\n          </TabsList>\n        </div>\n        <TabsContent value="form" keepMounted className="min-h-0 flex-1">\n          <ScrollArea className="h-full" scrollFade>\n            <div className="space-y-3 p-3">\n              {fields.map((field) => (\n                <HumanReviewFieldCard\n                  key={field.key}\n                  field={field}\n                  value={\n                    showExpected ? (expected[field.key] ?? null) : field.actual\n                  }\n                  originalValue={showExpected ? field.expected : field.actual}\n                  active={\n                    field.key === activeFieldKey ||\n                    activeFieldKey?.startsWith(`${field.key}.`)\n                  }\n                  activeFieldKey={activeFieldKey}\n                  showExpected={showExpected}\n                  onChange={(value) => updateValue(field.key, value)}\n                  onFieldFocus={onFieldFocus}\n                  onLocationHover={onLocationHover}\n                  onUndo={() => updateValue(field.key, field.expected)}\n                  onSetNull={() => updateValue(field.key, null)}\n                  resolveArrayItemMetadataPath={resolveArrayItemMetadataPath}\n                  resolveLocation={resolveLocation}\n                />\n              ))}\n            </div>\n          </ScrollArea>\n        </TabsContent>\n        <TabsContent value="json" className="min-h-0 flex-1">\n          {showExpected ? (\n            <JsonDiffView\n              actual={actualValues}\n              expected={expected}\n              theme={theme}\n            />\n          ) : (\n            <JsonCodeView value={actualValues} theme={theme} />\n          )}\n        </TabsContent>\n      </Tabs>\n    </TooltipProvider>\n  )\n}\n'

export function HumanReviewSource() {
  return (
    <DocsSourceCodeBlock
      code={humanReviewSourceCode}
      fileName="components/extend/bounding-box-citations.tsx"
    />
  )
}