All files / web/src/app/vision-training/train/components/data-panel UnifiedDataPanel.tsx

0% Statements 0/1335
0% Branches 0/1
0% Functions 0/1
0% Lines 0/1335

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               
'use client'

import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import { useRouter } from 'next/navigation'
import { useVirtualizer } from '@tanstack/react-virtual'
import { css } from '../../../../../../styled-system/css'
import type { ModelType } from '../wizard/types'
import type { QuadCorners } from '@/types/vision'
import { BOUNDARY_SAMPLE_CHANNEL } from '@/lib/vision/saveBoundarySample'
import { NumeralSelector } from '../NumeralSelector'
import {
  type AnyDataItem,
  type BoundaryDataItem,
  type ColumnDataItem,
  type DataPanelFilters as FilterState,
  type SyncStatus,
  type SyncProgress,
  getDefaultFilters,
  applyFilters,
  isBoundaryDataItem,
  isColumnDataItem,
} from './types'
import { DataPanelHeader } from './DataPanelHeader'
import { DataPanelFilters } from './DataPanelFilters'
import { DataPanelDetailPanel } from './DataPanelDetailPanel'
import { DataPanelCapturePanel } from './DataPanelCapturePanel'
import { BoundaryGridItem } from './BoundaryGridItem'
import { ColumnGridItem } from './ColumnGridItem'

type MobileTab = 'browse' | 'capture'
type RightPanelMode = 'capture' | 'detail'

export interface UnifiedDataPanelProps {
  /** Model type determines which UI elements to show */
  modelType: ModelType
  /** Callback when data changes (for parent refresh) */
  onDataChanged?: () => void
}

/**
 * Unified Data Panel
 *
 * A shared component for managing training data for both model types.
 * Provides consistent layout with model-specific content.
 *
 * Layout:
 * - Header: Model name, count, quality, sync button
 * - Numeral selector (column-classifier only)
 * - Filter bar (collapsible)
 * - Split view: Browse grid (left) + Capture/Detail panel (right)
 * - Mobile: Tab toggle between browse and capture/detail
 */
export function UnifiedDataPanel({ modelType, onDataChanged }: UnifiedDataPanelProps) {
  const router = useRouter()

  // === State ===

  // Items
  const [items, setItems] = useState<AnyDataItem[]>([])
  const [loading, setLoading] = useState(true)

  // Selection - multi-select support
  const [selectedIds, setSelectedIds] = useState<Set<string>>(new Set())
  const [lastClickedIndex, setLastClickedIndex] = useState<number | null>(null)
  const [focusedItem, setFocusedItem] = useState<AnyDataItem | null>(null) // For detail panel
  const [selectedDigit, setSelectedDigit] = useState(0) // column-classifier only

  // Bulk action state
  const [bulkActionInProgress, setBulkActionInProgress] = useState(false)

  // Manifest creation state (for "Train on Filtered" feature)
  const [creatingManifest, setCreatingManifest] = useState(false)

  // Filters
  const [filters, setFilters] = useState<FilterState>(getDefaultFilters)
  const [filtersExpanded, setFiltersExpanded] = useState(false)

  // UI state
  const [mobileTab, setMobileTab] = useState<MobileTab>('capture')
  const [rightPanelMode, setRightPanelMode] = useState<RightPanelMode>('capture')

  // Actions
  const [deleting, setDeleting] = useState<string | null>(null)
  const [reclassifying, setReclassifying] = useState(false)

  // Sync state
  const [syncStatus, setSyncStatus] = useState<SyncStatus | null>(null)
  const [syncProgress, setSyncProgress] = useState<SyncProgress>({
    phase: 'idle',
    message: '',
  })
  const [syncHistoryRefreshTrigger, setSyncHistoryRefreshTrigger] = useState(0)

  // Live capture tracking (boundary only)
  const [newSamplesCount, setNewSamplesCount] = useState(0)
  const lastRefreshTimeRef = useRef<number>(Date.now())

  // Virtualized grid refs and state
  const gridScrollContainerRef = useRef<HTMLDivElement>(null)
  const [gridWidth, setGridWidth] = useState(0)

  // Grid constants
  const MIN_ITEM_WIDTH = 120
  const ITEM_GAP = 8 // gap: 2 = 0.5rem = 8px
  const GRID_PADDING = 12 // p: 3 = 0.75rem = 12px

  // Calculate items per row based on container width
  const itemsPerRow = useMemo(() => {
    if (gridWidth === 0) return 4 // Default fallback
    const availableWidth = gridWidth - GRID_PADDING * 2
    // Account for gaps: n items need n-1 gaps
    // availableWidth = n * itemWidth + (n-1) * gap
    // Solve for n: n = (availableWidth + gap) / (itemWidth + gap)
    const cols = Math.floor((availableWidth + ITEM_GAP) / (MIN_ITEM_WIDTH + ITEM_GAP))
    return Math.max(1, cols)
  }, [gridWidth])

  // Calculate actual item width for the current layout
  const actualItemWidth = useMemo(() => {
    if (gridWidth === 0) return MIN_ITEM_WIDTH
    const availableWidth = gridWidth - GRID_PADDING * 2
    // Distribute available space evenly: itemWidth = (availableWidth - (n-1)*gap) / n
    return (availableWidth - (itemsPerRow - 1) * ITEM_GAP) / itemsPerRow
  }, [gridWidth, itemsPerRow])

  // Item height based on aspect ratio:
  // - boundary-detector: 4:3 ratio (0.75)
  // - column-classifier: 1:1 ratio (1.0)
  const aspectRatio = modelType === 'column-classifier' ? 1.0 : 0.75
  const itemHeight = useMemo(() => actualItemWidth * aspectRatio, [actualItemWidth, aspectRatio])

  // Row height including gap
  const rowHeight = useMemo(() => itemHeight + ITEM_GAP, [itemHeight])

  // === Computed values ===

  // Apply filters to items
  const filteredItems = useMemo(() => {
    let result = applyFilters(items, filters)

    // For column classifier, also filter by selected digit
    if (modelType === 'column-classifier') {
      result = result.filter((item) => isColumnDataItem(item) && item.digit === selectedDigit)
    }

    return result
  }, [items, filters, modelType, selectedDigit])

  // Total number of rows for virtualization
  const totalRows = useMemo(
    () => Math.ceil(filteredItems.length / itemsPerRow),
    [filteredItems.length, itemsPerRow]
  )

  // Digit counts for column classifier
  const digitCounts = useMemo(() => {
    if (modelType !== 'column-classifier') return {}
    const counts: Record<number, number> = {}
    for (let i = 0; i <= 9; i++) {
      counts[i] = items.filter((item) => isColumnDataItem(item) && item.digit === i).length
    }
    return counts
  }, [items, modelType])

  // Total count and quality
  const totalCount = items.length
  const dataQuality = useMemo(() => {
    if (totalCount === 0) return 'none'
    if (totalCount < 50) return 'insufficient'
    if (totalCount < 200) return 'minimal'
    if (totalCount < 500) return 'good'
    return 'excellent'
  }, [totalCount])

  // Item label for filters
  const itemLabel = modelType === 'boundary-detector' ? 'frames' : 'images'

  // Selected items (objects, not just IDs)
  const selectedItems = useMemo(
    () => filteredItems.filter((item) => selectedIds.has(item.id)),
    [filteredItems, selectedIds]
  )

  // === Data fetching ===

  const loadItems = useCallback(async () => {
    setLoading(true)
    try {
      if (modelType === 'boundary-detector') {
        const response = await fetch('/api/vision-training/boundary-samples?list=true')
        if (response.ok) {
          const data = await response.json()
          const frames: BoundaryDataItem[] = (data.frames || []).map(
            (f: {
              baseName: string
              deviceId: string
              imagePath: string
              capturedAt: string
              corners: QuadCorners
              frameWidth: number
              frameHeight: number
              sessionId: string | null
              playerId: string | null
            }) => ({
              type: 'boundary' as const,
              id: f.baseName,
              baseName: f.baseName,
              deviceId: f.deviceId,
              imagePath: f.imagePath,
              capturedAt: f.capturedAt,
              corners: f.corners,
              frameWidth: f.frameWidth,
              frameHeight: f.frameHeight,
              sessionId: f.sessionId,
              playerId: f.playerId,
            })
          )
          setItems(frames)
          setNewSamplesCount(0)
          lastRefreshTimeRef.current = Date.now()
        }
      } else {
        // Column classifier - fetch all digits
        const allImages: ColumnDataItem[] = []
        for (let digit = 0; digit <= 9; digit++) {
          const response = await fetch(`/api/vision-training/images?digit=${digit}`)
          if (response.ok) {
            const data = await response.json()
            const images: ColumnDataItem[] = (data.images || []).map(
              (img: {
                filename: string
                digit: number
                timestamp?: number
                playerId?: string
                sessionId?: string
              }) => ({
                type: 'column' as const,
                id: `${digit}-${img.filename}`,
                filename: img.filename,
                digit: img.digit,
                imagePath: `/api/vision-training/images/${digit}/${img.filename}`,
                // Convert Unix timestamp to ISO string for timeline
                capturedAt: img.timestamp ? new Date(img.timestamp).toISOString() : '',
                deviceId: img.playerId || 'unknown',
                sessionId: img.sessionId || null,
                playerId: img.playerId || null,
              })
            )
            allImages.push(...images)
          }
        }
        setItems(allImages)
      }
    } catch (error) {
      console.error('[UnifiedDataPanel] Failed to load items:', error)
    } finally {
      setLoading(false)
    }
  }, [modelType])

  // Load items on mount
  useEffect(() => {
    loadItems()
  }, [loadItems])

  // Fetch sync status (works for both model types)
  useEffect(() => {
    const fetchSyncStatus = async () => {
      try {
        const response = await fetch(`/api/vision-training/sync?modelType=${modelType}`)
        if (response.ok) {
          const data = await response.json()
          setSyncStatus(data)
        }
      } catch (error) {
        console.error('[UnifiedDataPanel] Failed to fetch sync status:', error)
      }
    }

    fetchSyncStatus()
  }, [modelType])

  // Listen for cross-tab notifications (boundary only)
  useEffect(() => {
    if (modelType !== 'boundary-detector') return
    if (typeof BroadcastChannel === 'undefined') return

    const channel = new BroadcastChannel(BOUNDARY_SAMPLE_CHANNEL)

    const handleMessage = (event: MessageEvent) => {
      if (event.data?.type === 'sample-saved') {
        setNewSamplesCount((prev) => prev + 1)
        loadItems()
      }
    }

    channel.addEventListener('message', handleMessage)

    return () => {
      channel.removeEventListener('message', handleMessage)
      channel.close()
    }
  }, [modelType, loadItems])

  // Track grid container width for virtualization
  useEffect(() => {
    const element = gridScrollContainerRef.current
    if (!element) return

    const observer = new ResizeObserver((entries) => {
      for (const entry of entries) {
        setGridWidth(entry.contentRect.width)
      }
    })

    observer.observe(element)
    // Set initial width
    setGridWidth(element.clientWidth)

    return () => observer.disconnect()
  }, [loading]) // Re-run when loading changes so we observe the grid when it mounts

  // Virtualizer for the grid rows
  const rowVirtualizer = useVirtualizer({
    count: totalRows,
    getScrollElement: () => gridScrollContainerRef.current,
    estimateSize: () => rowHeight,
    overscan: 3, // Render 3 extra rows above/below viewport
  })

  // === Handlers ===

  // Handle selection with shift+click support for range selection
  // Also opens detail panel for the clicked item (unless shift-clicking)
  const toggleSelect = useCallback(
    (id: string, index: number, shiftKey: boolean) => {
      setSelectedIds((prev) => {
        // Shift+click for range selection (add to existing selection)
        if (shiftKey && lastClickedIndex !== null) {
          const next = new Set(prev)
          const start = Math.min(lastClickedIndex, index)
          const end = Math.max(lastClickedIndex, index)
          // Add all items in range to selection
          for (let i = start; i <= end; i++) {
            if (filteredItems[i]) {
              next.add(filteredItems[i].id)
            }
          }
          return next
        } else {
          // Normal click: replace selection with just this item
          return new Set([id])
        }
      })

      // Update last clicked index (but not for shift clicks to allow extending range)
      if (!shiftKey) {
        setLastClickedIndex(index)

        // Also open detail panel for the clicked item (not for shift+click range selection)
        const clickedItem = filteredItems[index]
        if (clickedItem) {
          setFocusedItem(clickedItem)
          setRightPanelMode('detail')
        }
      }
    },
    [lastClickedIndex, filteredItems]
  )

  const selectAll = useCallback(() => {
    setSelectedIds(new Set(filteredItems.map((item) => item.id)))
  }, [filteredItems])

  const clearSelection = useCallback(() => {
    setSelectedIds(new Set())
    setLastClickedIndex(null)
  }, [])

  // Open detail panel for an item (double-click or dedicated button)
  const handleViewDetails = useCallback((item: AnyDataItem) => {
    setFocusedItem(item)
    setRightPanelMode('detail')
  }, [])

  const handleCloseDetail = useCallback(() => {
    setFocusedItem(null)
    setRightPanelMode('capture')
  }, [])

  // Delete a single item
  const handleDelete = useCallback(
    async (item: AnyDataItem) => {
      if (!confirm('Delete this item? This cannot be undone.')) return

      setDeleting(item.id)
      try {
        if (isBoundaryDataItem(item)) {
          const response = await fetch(
            `/api/vision-training/boundary-samples?deviceId=${item.deviceId}&baseName=${item.baseName}`,
            { method: 'DELETE' }
          )
          if (response.ok) {
            setItems((prev) => prev.filter((i) => i.id !== item.id))
            setSelectedIds((prev) => {
              const next = new Set(prev)
              next.delete(item.id)
              return next
            })
            if (focusedItem?.id === item.id) {
              handleCloseDetail()
            }
            onDataChanged?.()
          } else {
            alert('Failed to delete frame')
          }
        } else if (isColumnDataItem(item)) {
          const response = await fetch('/api/vision-training/images', {
            method: 'DELETE',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({
              filenames: [{ digit: item.digit, filename: item.filename }],
              confirm: true,
            }),
          })
          if (response.ok) {
            setItems((prev) => prev.filter((i) => i.id !== item.id))
            setSelectedIds((prev) => {
              const next = new Set(prev)
              next.delete(item.id)
              return next
            })
            if (focusedItem?.id === item.id) {
              handleCloseDetail()
            }
            onDataChanged?.()
          } else {
            alert('Failed to delete image')
          }
        }
      } catch (error) {
        console.error('[UnifiedDataPanel] Delete error:', error)
        alert('Failed to delete item')
      } finally {
        setDeleting(null)
      }
    },
    [focusedItem, handleCloseDetail, onDataChanged]
  )

  // Bulk delete selected items
  const handleBulkDelete = useCallback(async () => {
    if (selectedItems.length === 0) return
    if (!confirm(`Delete ${selectedItems.length} ${itemLabel}? This cannot be undone.`)) return

    setBulkActionInProgress(true)

    // Optimistically remove from UI
    const idsToDelete = new Set(selectedItems.map((item) => item.id))
    setItems((prev) => prev.filter((item) => !idsToDelete.has(item.id)))
    setSelectedIds(new Set())

    try {
      if (modelType === 'boundary-detector') {
        // Delete boundary frames one by one (API doesn't support bulk)
        for (const item of selectedItems) {
          if (isBoundaryDataItem(item)) {
            await fetch(
              `/api/vision-training/boundary-samples?deviceId=${item.deviceId}&baseName=${item.baseName}`,
              { method: 'DELETE' }
            )
          }
        }
      } else {
        // Column classifier supports bulk delete
        const filenames = selectedItems
          .filter(isColumnDataItem)
          .map((item) => ({ digit: item.digit, filename: item.filename }))

        await fetch('/api/vision-training/images', {
          method: 'DELETE',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ filenames, confirm: true }),
        })
      }

      // Close detail if focused item was deleted
      if (focusedItem && idsToDelete.has(focusedItem.id)) {
        handleCloseDetail()
      }

      onDataChanged?.()
      // Reload to get accurate counts
      loadItems()
    } catch (error) {
      console.error('[UnifiedDataPanel] Bulk delete error:', error)
      alert('Failed to delete some items')
      // Reload to restore state
      loadItems()
    } finally {
      setBulkActionInProgress(false)
    }
  }, [
    selectedItems,
    itemLabel,
    modelType,
    focusedItem,
    handleCloseDetail,
    onDataChanged,
    loadItems,
  ])

  // Bulk reclassify selected column items to a new digit
  const handleBulkReclassify = useCallback(
    async (newDigit: number) => {
      const columnItems = selectedItems.filter(isColumnDataItem)
      if (columnItems.length === 0 || newDigit === selectedDigit) return

      setBulkActionInProgress(true)

      // Optimistically remove from current view
      const idsToMove = new Set(columnItems.map((item) => item.id))
      setItems((prev) => prev.filter((item) => !idsToMove.has(item.id)))
      setSelectedIds(new Set())

      try {
        const response = await fetch('/api/vision-training/images', {
          method: 'PATCH',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({
            images: columnItems.map((item) => ({
              digit: item.digit,
              filename: item.filename,
            })),
            newDigit,
          }),
        })

        if (!response.ok) {
          throw new Error('Failed to reclassify images')
        }

        // Close detail if focused item was moved
        if (focusedItem && idsToMove.has(focusedItem.id)) {
          handleCloseDetail()
        }

        onDataChanged?.()
        // Reload to get accurate counts
        loadItems()
      } catch (error) {
        console.error('[UnifiedDataPanel] Bulk reclassify error:', error)
        alert('Failed to reclassify some images')
        // Reload to restore state
        loadItems()
      } finally {
        setBulkActionInProgress(false)
      }
    },
    [selectedItems, selectedDigit, focusedItem, handleCloseDetail, onDataChanged, loadItems]
  )

  // Reclassify a single column item
  const handleReclassify = useCallback(
    async (item: ColumnDataItem, newDigit: number) => {
      setReclassifying(true)
      try {
        const response = await fetch(`/api/vision-training/images/${item.digit}/${item.filename}`, {
          method: 'PATCH',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ newDigit }),
        })
        if (response.ok) {
          // Remove from current view, clear from selection, and close detail
          setItems((prev) => prev.filter((i) => i.id !== item.id))
          setSelectedIds((prev) => {
            const next = new Set(prev)
            next.delete(item.id)
            return next
          })
          handleCloseDetail()
          onDataChanged?.()
          // Reload to get updated counts
          loadItems()
        } else {
          alert('Failed to reclassify image')
        }
      } catch (error) {
        console.error('[UnifiedDataPanel] Reclassify error:', error)
        alert('Failed to reclassify image')
      } finally {
        setReclassifying(false)
      }
    },
    [handleCloseDetail, onDataChanged, loadItems]
  )

  const handleCaptureComplete = useCallback(() => {
    loadItems()
    onDataChanged?.()
  }, [loadItems, onDataChanged])

  const handleStartSync = useCallback(async () => {
    setSyncProgress({ phase: 'connecting', message: 'Connecting...' })
    try {
      const response = await fetch(`/api/vision-training/sync?modelType=${modelType}`, {
        method: 'POST',
      })
      if (response.ok) {
        setSyncProgress({ phase: 'complete', message: 'Sync complete!' })
        loadItems()
        onDataChanged?.()
      } else {
        setSyncProgress({ phase: 'error', message: 'Sync failed' })
      }
    } catch (error) {
      setSyncProgress({
        phase: 'error',
        message: error instanceof Error ? error.message : 'Sync failed',
      })
    }
    setSyncHistoryRefreshTrigger((prev) => prev + 1)
  }, [modelType, loadItems, onDataChanged])

  const handleCancelSync = useCallback(() => {
    setSyncProgress({ phase: 'idle', message: '' })
  }, [])

  /**
   * Handle "Train on Filtered Items" button click.
   * Creates a manifest from the filtered items and navigates to the training page.
   */
  const handleTrainOnFiltered = useCallback(async () => {
    if (filteredItems.length === 0) return

    setCreatingManifest(true)
    try {
      // Build manifest items based on model type
      const manifestItems = filteredItems.map((item) => {
        if (isBoundaryDataItem(item)) {
          return {
            type: 'boundary' as const,
            deviceId: item.deviceId,
            baseName: item.baseName,
          }
        } else if (isColumnDataItem(item)) {
          return {
            type: 'column' as const,
            digit: item.digit,
            filename: item.filename,
          }
        }
        // Should not happen, but TypeScript requires exhaustive check
        throw new Error('Unknown item type')
      })

      // Build filters object for display purposes
      const manifestFilters: Record<string, unknown> = {}
      if (filters.captureType !== 'all') {
        manifestFilters.captureType = filters.captureType
      }
      if (filters.deviceId) {
        manifestFilters.deviceId = filters.deviceId
      }
      if (modelType === 'column-classifier') {
        manifestFilters.digit = selectedDigit
      }

      // Create manifest via API
      const response = await fetch('/api/vision-training/manifests', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          modelType,
          filters: manifestFilters,
          items: manifestItems,
        }),
      })

      if (!response.ok) {
        const errorData = await response.json()
        throw new Error(errorData.error || 'Failed to create manifest')
      }

      const { manifestId } = await response.json()

      // Navigate to training page with manifest parameter
      router.push(`/vision-training/${modelType}/train?manifest=${manifestId}`)
    } catch (error) {
      console.error('[UnifiedDataPanel] Failed to create manifest:', error)
      alert(
        `Failed to create training manifest: ${error instanceof Error ? error.message : 'Unknown error'}`
      )
    } finally {
      setCreatingManifest(false)
    }
  }, [filteredItems, filters, modelType, selectedDigit, router])

  // === Render ===

  return (
    <div
      data-component="unified-data-panel"
      className={css({
        display: 'flex',
        flexDirection: 'column',
        flex: 1,
        minHeight: 0, // Allow shrinking in flex context
        bg: 'gray.900',
      })}
    >
      {/* Header */}
      <DataPanelHeader
        modelType={modelType}
        totalCount={totalCount}
        dataQuality={dataQuality}
        syncStatus={syncStatus}
        syncProgress={syncProgress}
        onStartSync={handleStartSync}
        onCancelSync={handleCancelSync}
        syncHistoryRefreshTrigger={syncHistoryRefreshTrigger}
      />

      {/* Numeral selector (column-classifier only) */}
      {modelType === 'column-classifier' && (
        <div
          data-element="numeral-selector-bar"
          className={css({
            px: { base: 2, lg: 4 },
            py: 3,
            borderBottom: '1px solid',
            borderColor: 'gray.800',
            bg: 'gray.875',
            overflowX: 'auto',
          })}
        >
          <NumeralSelector
            digitCounts={digitCounts}
            selectedDigit={selectedDigit}
            onSelectDigit={setSelectedDigit}
            compact={false}
          />
        </div>
      )}

      {/* Filter bar */}
      <div className={css({ px: { base: 2, lg: 4 }, py: 3 })}>
        <DataPanelFilters
          items={items}
          filters={filters}
          onFiltersChange={setFilters}
          isExpanded={filtersExpanded}
          onToggleExpanded={() => setFiltersExpanded(!filtersExpanded)}
          itemLabel={itemLabel}
        />
      </div>

      {/* Live capture indicator (boundary only) */}
      {modelType === 'boundary-detector' && newSamplesCount > 0 && (
        <div
          data-element="live-capture-indicator"
          className={css({
            display: 'flex',
            alignItems: 'center',
            gap: 2,
            px: 4,
            py: 2,
            mx: 4,
            mb: 2,
            bg: 'green.900/30',
            border: '1px solid',
            borderColor: 'green.700/50',
            borderRadius: 'lg',
          })}
        >
          <span
            className={css({
              width: '10px',
              height: '10px',
              borderRadius: 'full',
              bg: 'green.400',
              animation: 'pulse 1.5s ease-in-out infinite',
            })}
          />
          <span
            className={css({
              color: 'green.300',
              fontWeight: 'medium',
              fontSize: 'sm',
            })}
          >
            Live Capture Active
          </span>
          <span className={css({ color: 'green.400', fontSize: 'sm' })}>
            +{newSamplesCount} new frame{newSamplesCount !== 1 ? 's' : ''} captured
          </span>
        </div>
      )}

      {/* Mobile tab bar */}
      <div
        data-element="mobile-tab-bar"
        className={css({
          display: { base: 'flex', lg: 'none' },
          borderBottom: '1px solid',
          borderColor: 'gray.800',
        })}
      >
        <button
          type="button"
          onClick={() => setMobileTab('browse')}
          className={css({
            flex: 1,
            py: 3,
            bg: 'transparent',
            color: mobileTab === 'browse' ? 'purple.400' : 'gray.500',
            borderBottom: '2px solid',
            borderColor: mobileTab === 'browse' ? 'purple.400' : 'transparent',
            border: 'none',
            cursor: 'pointer',
            fontWeight: 'medium',
            fontSize: 'sm',
          })}
        >
          🖼 Browse ({filteredItems.length})
        </button>
        <button
          type="button"
          onClick={() => setMobileTab('capture')}
          className={css({
            flex: 1,
            py: 3,
            bg: 'transparent',
            color: mobileTab === 'capture' ? 'green.400' : 'gray.500',
            borderBottom: '2px solid',
            borderColor: mobileTab === 'capture' ? 'green.400' : 'transparent',
            border: 'none',
            cursor: 'pointer',
            fontWeight: 'medium',
            fontSize: 'sm',
          })}
        >
          📸 {rightPanelMode === 'detail' ? 'Details' : 'Capture'}
        </button>
      </div>

      {/* Main content - split view */}
      <div
        data-element="main-content"
        className={css({
          flex: 1,
          display: 'flex',
          flexDirection: { base: 'column', lg: 'row' },
          alignItems: 'stretch', // Both panels fill full height
          minHeight: 0,
          overflow: 'hidden',
          gap: 4,
        })}
      >
        {/* Browse panel */}
        <div
          data-element="browse-panel"
          className={css({
            display: {
              base: mobileTab === 'browse' ? 'flex' : 'none',
              lg: 'flex',
            },
            flexDirection: 'column',
            flex: 1,
            minWidth: 0,
            minHeight: 0, // Critical for flex children to shrink below content size
            bg: 'gray.850',
            borderRadius: 'lg',
            overflow: 'hidden',
          })}
        >
          {loading ? (
            <div
              className={css({
                flex: 1,
                display: 'flex',
                alignItems: 'center',
                justifyContent: 'center',
              })}
            >
              <div className={css({ textAlign: 'center' })}>
                <div
                  className={css({
                    fontSize: '2xl',
                    animation: 'spin 1s linear infinite',
                  })}
                >

                </div>
                <div className={css({ color: 'gray.400', mt: 2 })}>Loading {itemLabel}...</div>
              </div>
            </div>
          ) : filteredItems.length === 0 ? (
            <div
              className={css({
                flex: 1,
                display: 'flex',
                alignItems: 'center',
                justifyContent: 'center',
              })}
            >
              <div className={css({ textAlign: 'center', p: 4 })}>
                <div className={css({ fontSize: '3xl', mb: 3 })}>📷</div>
                <div className={css({ color: 'gray.300', mb: 2 })}>
                  {items.length === 0
                    ? `No ${itemLabel} captured yet`
                    : `No ${itemLabel} match filters`}
                </div>
                {items.length > 0 && (
                  <button
                    type="button"
                    onClick={() => setFilters(getDefaultFilters())}
                    className={css({
                      mt: 2,
                      px: 4,
                      py: 2,
                      bg: 'gray.700',
                      color: 'gray.200',
                      border: 'none',
                      borderRadius: 'md',
                      cursor: 'pointer',
                      _hover: { bg: 'gray.600' },
                    })}
                  >
                    Clear Filters
                  </button>
                )}
              </div>
            </div>
          ) : (
            <>
              {/* Selection bar */}
              <div
                data-element="selection-bar"
                className={css({
                  display: 'flex',
                  alignItems: 'center',
                  justifyContent: 'space-between',
                  px: 3,
                  py: 2,
                  borderBottom: '1px solid',
                  borderColor: 'gray.800',
                  bg: 'gray.875',
                  flexShrink: 0,
                })}
              >
                <div
                  data-element="item-count"
                  className={css({ fontSize: 'sm', color: 'gray.400' })}
                >
                  <strong className={css({ color: 'gray.200' })}>{filteredItems.length}</strong>{' '}
                  {itemLabel}
                  {selectedIds.size > 0 && (
                    <span
                      data-element="selection-count"
                      className={css({ color: 'blue.400', ml: 2 })}
                    >
                      ({selectedIds.size} selected)
                    </span>
                  )}
                </div>

                <div data-element="selection-actions" className={css({ display: 'flex', gap: 2 })}>
                  {/* Train on Filtered button - show when we have filtered items */}
                  {filteredItems.length > 0 && (
                    <button
                      type="button"
                      data-action="train-on-filtered"
                      onClick={handleTrainOnFiltered}
                      disabled={creatingManifest}
                      className={css({
                        px: 3,
                        py: 1,
                        fontSize: 'xs',
                        fontWeight: 'medium',
                        color: 'purple.300',
                        bg: 'purple.900/30',
                        border: '1px solid',
                        borderColor: 'purple.700/50',
                        borderRadius: 'md',
                        cursor: creatingManifest ? 'not-allowed' : 'pointer',
                        opacity: creatingManifest ? 0.6 : 1,
                        _hover: creatingManifest
                          ? {}
                          : { bg: 'purple.900/50', borderColor: 'purple.600' },
                        whiteSpace: 'nowrap',
                      })}
                    >
                      {creatingManifest
                        ? '⏳ Creating...'
                        : `🚀 Train on ${filteredItems.length} ${itemLabel}`}
                    </button>
                  )}
                  {selectedIds.size === 0 && (
                    <button
                      type="button"
                      data-action="select-all"
                      onClick={selectAll}
                      className={css({
                        px: 2,
                        py: 1,
                        fontSize: 'xs',
                        color: 'gray.400',
                        bg: 'transparent',
                        border: '1px solid',
                        borderColor: 'gray.700',
                        borderRadius: 'md',
                        cursor: 'pointer',
                        _hover: { borderColor: 'gray.600', color: 'gray.300' },
                      })}
                    >
                      Select All
                    </button>
                  )}
                </div>
              </div>

              {/* Virtualized Grid */}
              <div
                ref={gridScrollContainerRef}
                data-element="grid-scroll-container"
                className={css({
                  flex: 1,
                  overflow: 'auto',
                  minHeight: 0,
                  contain: 'strict',
                })}
              >
                <div
                  data-element="grid"
                  style={{
                    height: `${rowVirtualizer.getTotalSize() + GRID_PADDING * 2}px`,
                    width: '100%',
                    position: 'relative',
                    padding: `${GRID_PADDING}px`,
                  }}
                >
                  {rowVirtualizer.getVirtualItems().map((virtualRow) => {
                    const rowStartIndex = virtualRow.index * itemsPerRow
                    const rowItems = filteredItems.slice(rowStartIndex, rowStartIndex + itemsPerRow)

                    return (
                      <div
                        key={virtualRow.key}
                        data-element="grid-row"
                        data-row-index={virtualRow.index}
                        style={{
                          position: 'absolute',
                          top: 0,
                          left: `${GRID_PADDING}px`,
                          right: `${GRID_PADDING}px`,
                          height: `${itemHeight}px`,
                          transform: `translateY(${virtualRow.start}px)`,
                          display: 'flex',
                          gap: `${ITEM_GAP}px`,
                        }}
                      >
                        {rowItems.map((item, colIndex) => {
                          const itemIndex = rowStartIndex + colIndex
                          return isBoundaryDataItem(item) ? (
                            <div
                              key={item.id}
                              data-element="grid-item"
                              data-item-id={item.id}
                              data-col-index={colIndex}
                              style={{
                                width: `${actualItemWidth}px`,
                                height: '100%',
                                flexShrink: 0,
                              }}
                            >
                              <BoundaryGridItem
                                item={item}
                                isSelected={selectedIds.has(item.id)}
                                isFocused={focusedItem?.id === item.id}
                                onSelect={(shiftKey) => toggleSelect(item.id, itemIndex, shiftKey)}
                                onViewDetails={() => handleViewDetails(item)}
                                onDelete={() => handleDelete(item)}
                              />
                            </div>
                          ) : isColumnDataItem(item) ? (
                            <div
                              key={item.id}
                              data-element="grid-item"
                              data-item-id={item.id}
                              data-col-index={colIndex}
                              style={{
                                width: `${actualItemWidth}px`,
                                height: '100%',
                                flexShrink: 0,
                              }}
                            >
                              <ColumnGridItem
                                item={item}
                                isSelected={selectedIds.has(item.id)}
                                isFocused={focusedItem?.id === item.id}
                                onSelect={(shiftKey) => toggleSelect(item.id, itemIndex, shiftKey)}
                                onViewDetails={() => handleViewDetails(item)}
                                onDelete={() => handleDelete(item)}
                              />
                            </div>
                          ) : null
                        })}
                      </div>
                    )
                  })}
                </div>
              </div>
            </>
          )}
        </div>

        {/* Right panel: Bulk Selection, Detail, or Capture */}
        <div
          data-element="right-panel"
          className={css({
            display: {
              base: mobileTab === 'capture' ? 'flex' : 'none',
              lg: 'flex',
            },
            flexDirection: 'column',
            width: {
              lg: selectedIds.size > 1 || rightPanelMode === 'detail' ? 'auto' : '400px',
            },
            maxWidth: { lg: '50%' },
            flexShrink: 0,
            minHeight: 0,
            height: { lg: '100%' }, // Fill parent height
            overflow: 'hidden', // Don't grow from content - scroll instead
          })}
        >
          {selectedIds.size > 1 ? (
            /* Bulk selection panel */
            <div
              data-element="bulk-selection-panel"
              className={css({
                p: 4,
                bg: 'gray.850',
                borderRadius: 'lg',
                display: 'flex',
                flexDirection: 'column',
                gap: 4,
                flex: 1,
                minHeight: 0,
                overflow: 'auto',
              })}
            >
              {/* Header */}
              <div
                className={css({
                  display: 'flex',
                  alignItems: 'center',
                  justifyContent: 'space-between',
                })}
              >
                <div
                  className={css({
                    display: 'flex',
                    alignItems: 'center',
                    gap: 2,
                  })}
                >
                  <span className={css({ fontSize: 'xl' })}>📦</span>
                  <span
                    className={css({
                      fontSize: 'lg',
                      fontWeight: 'bold',
                      color: 'gray.100',
                    })}
                  >
                    {selectedIds.size} {itemLabel} selected
                  </span>
                </div>
                <button
                  type="button"
                  onClick={clearSelection}
                  className={css({
                    px: 2,
                    py: 1,
                    fontSize: 'sm',
                    color: 'gray.400',
                    bg: 'transparent',
                    border: '1px solid',
                    borderColor: 'gray.700',
                    borderRadius: 'md',
                    cursor: 'pointer',
                    _hover: { borderColor: 'gray.600', color: 'gray.300' },
                  })}
                >
                  Clear Selection
                </button>
              </div>

              {/* Bulk actions */}
              <div
                className={css({
                  display: 'flex',
                  flexDirection: 'column',
                  gap: 3,
                  p: 4,
                  bg: 'gray.900',
                  borderRadius: 'md',
                })}
              >
                <div className={css({ fontSize: 'sm', color: 'gray.400', mb: 1 })}>
                  Bulk Actions
                </div>

                {/* Bulk delete */}
                <button
                  type="button"
                  data-action="bulk-delete"
                  onClick={handleBulkDelete}
                  disabled={bulkActionInProgress}
                  className={css({
                    display: 'flex',
                    alignItems: 'center',
                    justifyContent: 'center',
                    gap: 2,
                    py: 3,
                    px: 4,
                    fontSize: 'sm',
                    fontWeight: 'medium',
                    color: 'red.300',
                    bg: 'red.900/30',
                    border: '1px solid',
                    borderColor: 'red.700/50',
                    borderRadius: 'md',
                    cursor: bulkActionInProgress ? 'not-allowed' : 'pointer',
                    opacity: bulkActionInProgress ? 0.5 : 1,
                    _hover: { bg: 'red.900/50', borderColor: 'red.600' },
                  })}
                >
                  <span>🗑️</span>
                  <span>
                    Delete {selectedIds.size} {itemLabel}
                  </span>
                </button>

                {/* Bulk reclassify (column-classifier only) */}
                {modelType === 'column-classifier' && (
                  <div
                    className={css({
                      display: 'flex',
                      flexDirection: 'column',
                      gap: 2,
                    })}
                  >
                    <div className={css({ fontSize: 'sm', color: 'gray.400' })}>Move to digit:</div>
                    <div
                      className={css({
                        display: 'grid',
                        gridTemplateColumns: 'repeat(5, 1fr)',
                        gap: 2,
                      })}
                    >
                      {[0, 1, 2, 3, 4, 5, 6, 7, 8, 9].map((d) => (
                        <button
                          key={d}
                          type="button"
                          data-action="bulk-reclassify-to"
                          data-target-digit={d}
                          onClick={() => handleBulkReclassify(d)}
                          disabled={d === selectedDigit || bulkActionInProgress}
                          className={css({
                            py: 2,
                            fontSize: 'lg',
                            fontWeight: 'bold',
                            fontFamily: 'mono',
                            color: d === selectedDigit ? 'gray.600' : 'gray.100',
                            bg: d === selectedDigit ? 'gray.800' : 'blue.900/30',
                            border: '1px solid',
                            borderColor: d === selectedDigit ? 'gray.700' : 'blue.700/50',
                            borderRadius: 'md',
                            cursor:
                              d === selectedDigit || bulkActionInProgress
                                ? 'not-allowed'
                                : 'pointer',
                            opacity: bulkActionInProgress ? 0.5 : 1,
                            _hover:
                              d === selectedDigit || bulkActionInProgress
                                ? {}
                                : {
                                    bg: 'blue.600',
                                    borderColor: 'blue.500',
                                    color: 'white',
                                  },
                          })}
                        >
                          {d}
                        </button>
                      ))}
                    </div>
                  </div>
                )}
              </div>

              {/* Selection tip */}
              <div
                className={css({
                  fontSize: 'xs',
                  color: 'gray.500',
                  textAlign: 'center',
                })}
              >
                Tip: Shift+click to select a range of {itemLabel}
              </div>
            </div>
          ) : rightPanelMode === 'detail' && focusedItem ? (
            <DataPanelDetailPanel
              modelType={modelType}
              selectedItem={focusedItem}
              onClose={handleCloseDetail}
              onDelete={handleDelete}
              isDeleting={deleting === focusedItem.id}
              onReclassify={handleReclassify}
              isReclassifying={reclassifying}
            />
          ) : (
            <DataPanelCapturePanel
              modelType={modelType}
              onCaptureComplete={handleCaptureComplete}
              selectedDigit={selectedDigit}
            />
          )}
        </div>
      </div>
    </div>
  )
}