All files / src/components/SearchPanel ResultsTable.tsx

68.7% Statements 573/834
42.62% Branches 26/61
9.67% Functions 3/31
68.7% Lines 573/834

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 11411x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x   1x 1x 1x                           1x               1x 1x 1x                         1x                                                     1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x   1x       1x 1x     1x 1x 1x 1x 1x 1x 1x     1x         1x 1x 1x 1x 1x 1x   1x       1x                                                     1x                     1x 1x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x   4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x   4x 4x 3x           3x 3x 3x 3x 3x 3x 3x 4x   4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x   4x   4x 4x 4x 4x 4x 4x 1x 1x 1x 1x 4x     4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 3x 3x 2x 2x 2x 2x 3x 1x 1x 3x 4x   4x 4x   4x 4x 4x 4x 4x 4x 4x   4x 4x 4x 4x 4x 4x 4x   4x 4x 4x 4x 4x 4x 4x 4x   4x 4x 4x 4x 4x 4x 3x     3x 4x   4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x                             4x 4x           4x 4x   4x 4x 4x                               4x   4x 4x 3x 3x 3x 3x     3x 1x     1x     1x 1x 1x 1x 1x 1x 1x     1x 1x 3x         3x 3x 3x 4x   4x 4x 4x 4x                   4x   4x 4x                               4x 4x     4x 4x 4x 4x 4x 4x 1x 1x 1x 1x 1x 1x 4x   4x 4x 4x 4x 4x 4x 4x   4x 4x 4x 4x 4x 3x 3x   4x   4x 4x 4x 4x                   4x 4x 4x             4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x   4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x                             4x 4x 4x             4x   4x 4x 4x   4x 4x 4x 4x 4x 4x 4x                       4x           4x           4x       4x 4x 4x         4x 4x 4x 4x                                   4x 4x 4x 4x 4x 4x 4x                             4x 4x       4x                         4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x   4x 4x 4x 4x 4x 4x 4x 4x   4x       4x       4x 4x 4x   4x     4x 4x 4x 4x 4x   4x     4x 4x 4x 1x 3x     4x 4x 4x 4x 4x 4x 4x 4x 4x   4x     4x 4x 4x 4x 4x   4x   4x 4x 4x 4x 4x   4x     4x 4x 4x 4x 4x 4x   4x               4x     4x           4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x       4x 4x 4x     4x 4x 4x     4x 4x 4x   4x 4x 4x 4x           4x 4x           4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x               4x   4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x   4x 4x 4x 4x 4x   4x 4x 4x 4x           4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x                 4x                                                                             4x 4x                                                                                               4x 4x 4x               4x 4x 4x 4x 4x           4x 4x   4x 4x 4x 4x 4x 4x                 4x   4x 4x 4x         4x             4x 4x 4x 4x 4x 4x 4x 4x       4x 4x 4x 4x 4x   4x   4x 4x 4x 4x   4x   4x 4x 4x 4x   4x   4x 4x 4x 4x   4x               4x 4x 4x 4x 4x   4x 4x 4x 4x                                                 4x 4x 4x 4x 4x 4x 4x 4x 4x           4x  
import { ChemicalChips } from '@/components/SearchPanel/ChemicalChips';
import { ChemicalInfoDialog } from '@/components/SearchPanel/ChemicalInfoDialog';
import { defaultSettings } from '@/../config.json';
import LoadingBackdrop from '@/components/LoadingBackdrop';
import resultStyles from '@/components/ResultsPanel.module.scss';
import { CACHE, DRAWER_INDEX } from '@/constants/common';
import { emitSearchEvent, SearchEvent } from '@/events/searchEvents';
import { reloadPage } from '@/helpers/dom';
import { i18n } from '@/helpers/i18n';
import { countActiveSearchFilters } from '@/helpers/searchFilters';
import { generatePageSizes } from '@/helpers/utils';
import { HotkeyEvent } from '@/hotkeys';
import { getEmptyHideableColumnIds } from '@/mixins/tanstack';
import { isTabView, openExtensionTab } from '@/utils/displayContext';
import { cstorage } from '@/utils/storage';
import { isInputElement, isValidUserSettings } from '@/utils/typeGuards/common';
import ArrowBackIcon from '@mui/icons-material/ArrowBack';
import ChevronLeftIcon from '@mui/icons-material/ChevronLeft';
import ChevronRightIcon from '@mui/icons-material/ChevronRight';
import FilterListIcon from '@mui/icons-material/FilterList';
import FirstPageIcon from '@mui/icons-material/FirstPage';
import LastPageIcon from '@mui/icons-material/LastPage';
import OpenInNewIcon from '@mui/icons-material/OpenInNew';
import ScienceIcon from '@mui/icons-material/Science';
import SearchOffIcon from '@mui/icons-material/SearchOff';
import SettingsIcon from '@mui/icons-material/Settings';
import ViewColumnIcon from '@mui/icons-material/ViewColumn';
 
import ArrowDropDownIcon from '@/icons/ArrowDropDownIcon';
import ArrowDropUpIcon from '@/icons/ArrowDropUpIcon';
import {
  Box,
  Checkbox,
  FormControl,
  FormControlLabel,
  IconButton,
  Link,
  ListItemText,
  Menu,
  MenuItem,
  TableRow,
  Tooltip,
  Typography,
} from '@mui/material';
import {
  Column,
  ColumnFiltersState,
  flexRender,
  Header,
  Row,
  type TableState,
} from '@tanstack/react-table';
import debounce from 'lodash/debounce';
import isEmpty from 'lodash/isEmpty';
import {
  ComponentType,
  Dispatch,
  Fragment,
  KeyboardEvent,
  ReactElement,
  ReactNode,
  SetStateAction,
  useCallback,
  useEffect,
  useRef,
  useState,
} from 'react';
import {
  BackButton,
  ColoredIconButton,
  ColumnMenuItemContainer,
  ColumnResizer,
  EmptyStateCell,
  ErrorContainer,
  ErrorRetryButton,
  FilterIconButton,
  FilterTableCell,
  GlobalFilterTextField,
  HeaderCellContent,
  NavigationContainer,
  PageSizeContainer,
  PageSizeSelect,
  PaginationContainer,
  ProductDetailPanelCell,
  ResultsHeaderContainer,
  SearchResultsTable,
  SortIndicator,
  StickyHeaderCell,
  StyledTableBody,
  StyledTableCell,
  StyledTableHead,
  SubRowTableRow,
  TruncatedCellText,
} from '../StyledComponents';
import ContextMenu from './ContextMenu';
import { useAppContext } from './hooks/useContext';
import { useSearch } from './hooks/useSearch';
import RangeColumnFilter from './Inputs/RangeColumnFilter';
import SelectColumnFilter from './Inputs/SelectColumnFilter';
import TextColumnFilter from './Inputs/TextColumnFilter';
import { ProductDetailPanel } from './ProductDetailPanel';
import styles from './ResultsTable.module.scss';
import { useAutoColumnSizing } from './useAutoColumnSizing.hook';
import { useContextMenu } from './useContextMenu.hook';
import { useResultsTable } from './useResultsTable.hook';
import { Logger } from '@/utils/Logger';
import { getErrorMessage } from '@/helpers/exceptions';
 
const logger = new Logger('ResultsTable');
 
type FilterVariant = 'text' | 'range' | 'select';
 
/** Narrows an unknown column `filterVariant` to a known {@link FilterVariant}. */
const isFilterVariant = (value: unknown): value is FilterVariant =>
  value === 'text' || value === 'range' || value === 'select';
 
// defaultSettings from config.json is static, but its JSON-inferred type widens
// string literals (e.g. `fontSize: string`), so it isn't structurally a
// UserSettings. Validate it once via the schema guard so it narrows without a
// cast; falls back to an empty object (all UserSettings fields are optional) if
// config.json is ever malformed.
const DEFAULT_USER_SETTINGS: UserSettings = isValidUserSettings(defaultSettings)
  ? defaultSettings
  : {};
 
/**
 * Maps a column's `meta.filterVariant` to the input component that renders
 * inside the header filter row. `text` is the fallback so columns without
 * `meta.filterVariant` still get a filter.
 * @source
 */
const filterComponentMap: Record<FilterVariant, ComponentType<FilterVariantInputProps>> = {
  text: TextColumnFilter,
  range: RangeColumnFilter,
  select: SelectColumnFilter,
};
 
/**
 * Dispatches to the correct filter component based on the column's
 * `meta.filterVariant`. Rendered inside each header cell's filter row.
 * @source
 */
function FilterVariantCell({ header }: { header: Header<Product, unknown> }) {
  const rawVariant = header.column.columnDef.meta?.filterVariant;
  const variant: FilterVariant = isFilterVariant(rawVariant) ? rawVariant : 'text';
  const Component = filterComponentMap[variant];
  if (!Component) return null;
  return <Component column={header.column} />;
}
 
/**
 * Props for {@link ResultsTable}.
 * @example
 * ```tsx
 * const props: ResultsTableProps = {
 *   getRowCanExpand: (row) => (row.original.variants?.length ?? 0) > 0,
 *   columnFilterFns: [filters, setFilters],
 * };
 * ```
 * @source
 */
interface ResultsTableProps {
  /** Predicate deciding whether a row can expand to show variant sub-rows. */
  getRowCanExpand: (row: Row<Product>) => boolean;
  /** Controlled column-filter state tuple `[state, setState]`. */
  columnFilterFns: [ColumnFiltersState, Dispatch<SetStateAction<ColumnFiltersState>>];
}
 
/**
 * Enhanced ResultsTable component using chem-pal styling with local functionality
 *
 * Features:
 * - Modern table styling from chem-pal
 * - Local search functionality and streaming results
 * - Context menu for product rows
 * - Auto column sizing
 * - Pagination and filtering
 * - Drawer system integration
 * @source
 */
export default function ResultsTable({
  getRowCanExpand,
  columnFilterFns,
}: ResultsTableProps): ReactElement {
  const appContext = useAppContext();
  // Count of active advanced-search (drawer) filters — blue-highlights the flask
  // button and is surfaced on hover. 0 when the context isn't ready or all default.
  const advancedFilterCount = appContext
    ? countActiveSearchFilters({
        selectedSuppliers: appContext.selectedSuppliers,
        searchFilters: appContext.searchFilters,
        userSettings: appContext.userSettings,
      })
    : 0;
  // How many columns have an active filter (each entry is one column) —
  // independent of whether the filter row is shown. Drives the filter-toggle
  // icon's blue highlight and its hover count.
  const activeColumnFilterCount = columnFilterFns[0].length;
  const hasActiveColumnFilters = activeColumnFilterCount > 0;
  const [showFilters, setShowFilters] = useState(false);
  const [columnMenuAnchor, setColumnMenuAnchor] = useState<null | HTMLElement>(null);
  const [globalFilter, setGlobalFilter] = useState('');
  const [chemicalInfoTerm, setChemicalInfoTerm] = useState<string | undefined>();
  const globalFilterInputRef = useRef<HTMLInputElement>(null);
  const scrollContainerRef = useRef<HTMLDivElement>(null);
 
  // Bridge hotkeys (fired from App.tsx) into local state/refs.
  useEffect(() => {
    const onFocus = () => {
      const el = globalFilterInputRef.current;
      if (!el) return;
      el.focus();
      el.select();
    };
    const onToggle = () => setShowFilters((v) => !v);
    window.addEventListener(HotkeyEvent.FOCUS_GLOBAL_FILTER, onFocus);
    window.addEventListener(HotkeyEvent.TOGGLE_COLUMN_FILTERS, onToggle);
    return () => {
      window.removeEventListener(HotkeyEvent.FOCUS_GLOBAL_FILTER, onFocus);
      window.removeEventListener(HotkeyEvent.TOGGLE_COLUMN_FILTERS, onToggle);
    };
  }, []);
 
  // Enhanced search hook that maintains streaming behavior
  const {
    searchResults,
    isLoading,
    isAborting,
    error,
    executeSearch,
    handleStopSearch,
    excludeProduct,
    tableText,
    executedQuery,
  } = useSearch();
 
  const setColumnFilters = columnFilterFns[1];
 
  // Runs a real search (home bar, results-panel input, omnibox, history re-run,
  // or drawer retry). Every fresh query clears the table's per-column filters so
  // rows from the previous search don't stay hidden — unlike restoring the panel,
  // which preserves them. Column visibility and the global filter are left as-is.
  const runSearch = useCallback(
    (query: string) => {
      if (!query.trim()) return;
      setColumnFilters([]);
      executeSearch(query);
    },
    [executeSearch, setColumnFilters],
  );
 
  // Watch for pending search queries triggered from HistoryPanel or the drawer.
  // The ref guard dedupes against:
  //   1. StrictMode double-invoke of effects on mount (dev only)
  //   2. The `appContext` dep in the array — context object identity changes on
  //      every context state update, so this effect re-fires whenever anything
  //      in AppContext changes, not just `pendingSearchQuery`.
  //   3. `executeSearch` / `appContext` not being stable references, which
  //      would otherwise cause spurious re-runs.
  // Without the guard, a single submitted query fires `executeSearch` twice
  // (and two sets of supplier HTTP requests).
  const lastHandledPendingQueryRef = useRef<string | null>(null);
  useEffect(() => {
    const pending = appContext?.pendingSearchQuery;
    if (!pending) {
      // Reset so the same query can be submitted again later.
      lastHandledPendingQueryRef.current = null;
      return;
    }
    if (lastHandledPendingQueryRef.current === pending) return;
    lastHandledPendingQueryRef.current = pending;
    runSearch(pending);
    appContext?.setPendingSearchQuery(null);
  }, [appContext?.pendingSearchQuery, runSearch, appContext]);
 
  // Context menu functionality
  const { contextMenu, handleContextMenu, handleCloseContextMenu } = useContextMenu();
 
  const table = useResultsTable({
    showSearchResults: searchResults,
    columnFilterFns,
    globalFilterFns: [globalFilter, setGlobalFilter],
    getRowCanExpand,
    userSettings: appContext?.userSettings ?? DEFAULT_USER_SETTINGS,
  });
 
  // ── Table state persistence ──────────────────────────────────────────
  // Uses the TanStack "fully controlled state" pattern: take over the
  // table's state via `table.setOptions`, persist the slices we care about
  // (sorting, pagination, expanded rows, column visibility) to
  // chrome.storage.session, and restore them on mount.
  const [tableState, setTableState] = useState<TableState>(table.initialState);
  const isStateLoadedRef = useRef(false);
 
  // The rows-per-page the user explicitly asked for, via the Select or the
  // "show all" hotkey. Filtering can clamp the *effective* pageSize below this
  // when fewer rows are available; tracking the intent lets us restore it once
  // the row count grows back (e.g. the user clears a column filter).
  // `Number.POSITIVE_INFINITY` means "all rows". Declared here (above the load
  // effect) so a restored pageSize can hydrate it — otherwise the reconciliation
  // below would immediately reset a persisted non-default row limit to the default.
  const desiredPageSizeRef = useRef(tableState.pagination?.pageSize ?? 10);
 
  // Collapse all variant rows whenever a new search begins. Without this,
  // the persisted `expanded` state from the previous search can leak into
  // the new results when row IDs happen to collide (e.g. both searches
  // include a product at the same index).
  const prevIsLoadingRef = useRef(false);
  useEffect(() => {
    if (isLoading && !prevIsLoadingRef.current) {
      setTableState((prev) => ({ ...prev, expanded: {} }));
    }
    prevIsLoadingRef.current = isLoading;
  }, [isLoading]);
 
  // Once a search settles, auto-hide hideable columns that have no data in any row
  // (across all results and their variants, not just the visible page), and restore
  // any column we auto-hid once it has data again — to the visibility it had before
  // we hid it, so a user's own show/hide choice survives. Only columns we hid are
  // touched, so unrelated manual choices are left intact. Recomputed both when the
  // search finishes and when the asynchronously-loaded price history settles, so the
  // late-arriving trend columns (Trend/Change) are judged on their real data rather
  // than the empty pre-load state. Gated by the `autoHideEmptyColumns` setting
  // (default on); when off, everything we hid is restored so the toggle applies
  // immediately.
  const autoHideEmptyColumns = appContext?.userSettings?.results?.autoHideEmpty ?? true;
  // Maps each auto-hidden column id to the visibility it had before we hid it
  // (`undefined` = no explicit entry, i.e. its default), so restore is exact.
  const autoHiddenColumnsRef = useRef<Map<string, boolean | undefined>>(new Map());
  // Price history loads asynchronously into table meta after a search; depending on
  // it re-runs this effect once it settles (see useResultsTable).
  const priceHistory = table.options.meta?.priceHistory;
  useEffect(() => {
    // Feature disabled: restore anything we auto-hid to its pre-hide visibility.
    if (!autoHideEmptyColumns) {
      if (autoHiddenColumnsRef.current.size === 0) return;
      const hidden = autoHiddenColumnsRef.current;
      setTableState((prev) => {
        const columnVisibility = { ...prev.columnVisibility };
        for (const [id, prior] of hidden) {
          if (prior === undefined) delete columnVisibility[id];
          else columnVisibility[id] = prior;
        }
        return { ...prev, columnVisibility };
      });
      autoHiddenColumnsRef.current = new Map();
      return;
    }
 
    // Only act on a settled result set — not mid-search, and only with results.
    if (isLoading || searchResults.length === 0) return;
 
    const emptyColumnIds = new Set(getEmptyHideableColumnIds(table));
    // `table.setOptions` binds the table's state to `tableState` each render, so
    // `getState()` is the current visibility we compute the next one from.
    const current = table.getState().columnVisibility ?? {};
    const columnVisibility: Record<string, boolean> = { ...current };
    const nextHidden = new Map<string, boolean | undefined>();
 
    // Restore columns we previously auto-hid that now have data to their pre-hide
    // visibility; keep the still-empty ones hidden (remembering their prior value).
    for (const [id, prior] of autoHiddenColumnsRef.current) {
      if (emptyColumnIds.has(id)) {
        nextHidden.set(id, prior);
        continue;
      }
      if (prior === undefined) delete columnVisibility[id];
      else columnVisibility[id] = prior;
    }
    // Hide columns with no data, recording each one's pre-hide visibility once.
    for (const id of emptyColumnIds) {
      if (!nextHidden.has(id)) nextHidden.set(id, current[id]);
      columnVisibility[id] = false;
    }
    autoHiddenColumnsRef.current = nextHidden;
    setTableState((prev) => ({ ...prev, columnVisibility }));
    // `table` is a stable instance from useResultsTable.
  }, [isLoading, searchResults, autoHideEmptyColumns, priceHistory, table]);
 
  // Load persisted state once on mount
  useEffect(() => {
    const load = async () => {
      try {
        const data = await cstorage.session.get([CACHE.TABLE_STATE]);
        const stored = data[CACHE.TABLE_STATE] as
          | (Partial<TableState> & { globalFilter?: string; showFilters?: boolean })
          | undefined;
        if (stored && typeof stored === 'object') {
          if (typeof stored.globalFilter === 'string') {
            setGlobalFilter(stored.globalFilter);
          }
          if (typeof stored.showFilters === 'boolean') {
            setShowFilters(stored.showFilters);
          }
          if (Array.isArray(stored.columnFilters)) {
            columnFilterFns[1](stored.columnFilters);
          }
          // Hydrate the "desired rows-per-page" intent from the restored pageSize
          // so the reconciliation below keeps the persisted row limit instead of
          // resetting it to the default once cached results repopulate the table.
          if (typeof stored.pagination?.pageSize === 'number') {
            desiredPageSizeRef.current = stored.pagination.pageSize;
          }
          setTableState((prev) => ({ ...prev, ...stored }));
        }
      } catch (error) {
        logger.warn(`Failed to load table state from session storage: ${getErrorMessage(error)}`, {
          error,
        });
      }
      isStateLoadedRef.current = true;
    };
    load();
  }, []);
 
  // Override state management — the table reads state from our local
  // `tableState` and pushes every change back through `setTableState`.
  // Column filters and global filter remain externally controlled.
  table.setOptions((prev) => ({
    ...prev,
    state: {
      ...tableState,
      columnFilters: columnFilterFns[0],
      globalFilter,
    },
    onStateChange: setTableState,
  }));
 
  // Debounced save — only persist the slices we care about restoring
 
  const saveTableState = useCallback(
    debounce(async (s: TableState & { showFilters?: boolean }) => {
      try {
        await cstorage.session.set({
          [CACHE.TABLE_STATE]: {
            sorting: s.sorting,
            pagination: s.pagination,
            expanded: s.expanded,
            columnVisibility: s.columnVisibility,
            columnFilters: s.columnFilters,
            globalFilter: s.globalFilter,
            showFilters: s.showFilters,
          },
        });
      } catch (error) {
        logger.warn(`Failed to persist table state: ${getErrorMessage(error)}`, { error });
      }
    }, 300),
    [],
  );
 
  // Persist whenever controlled state changes (skip until initial load
  // completes to avoid overwriting stored state with defaults).
  // globalFilter, columnFilters, and showFilters are managed externally
  // but still persisted alongside table state.
  useEffect(() => {
    if (!isStateLoadedRef.current) return;
    saveTableState({
      ...tableState,
      globalFilter,
      columnFilters: columnFilterFns[0],
      showFilters,
    });
  }, [tableState, globalFilter, columnFilterFns[0], showFilters, saveTableState]);
 
  // Clamp pageSize synchronously so the MUI Select never renders with an
  // out-of-range value (e.g. persisted pageSize=36 when valid options are
  // [10, 20, 40, 74]). Must happen during render, not in a useEffect,
  // because MUI warns before effects run.
  const filteredRowCount = table.getRowModel().rows.filter((row) => row.depth === 0).length;
  const totalRowCount = table.getFilteredRowModel().rows.length;
  const supplierResultsCount = table.getColumn('supplier')?.getFacetedUniqueValues().size ?? 0;
 
  // Emit the filtered row count; the badge controller owns the badge update.
  // Suppress leading zeros (the empty table before results populate on open)
  // so they don't clear a badge App already set to the restored count.
  const hasHadResultsRef = useRef(false);
  useEffect(() => {
    if (totalRowCount > 0) hasHadResultsRef.current = true;
    if (totalRowCount === 0 && !hasHadResultsRef.current) return;
    emitSearchEvent(SearchEvent.RESULTS_COUNT, { count: totalRowCount });
  }, [filteredRowCount, totalRowCount]);
 
  // Bridge the results-table hotkeys (fired from App.tsx) into the table API.
  // `table` is a stable instance, so row counts are read fresh at event time.
  useEffect(() => {
    const onExpandAll = () => {
      // Expand only rows that can actually expand — setting the global
      // `expanded: true` flag would render an empty detail panel for every
      // non-expandable row, since the row render only guards on getIsExpanded().
      const expanded: Record<string, boolean> = {};
      for (const row of table.getRowModel().rows) {
        if (row.getCanExpand()) expanded[row.id] = true;
      }
      table.setExpanded(expanded);
    };
    const onCollapseAll = () => table.setExpanded({});
    const onScrollToTop = () => scrollContainerRef.current?.scrollTo({ top: 0 });
    const onShowAll = () => {
      const rowCount = table.getFilteredRowModel().rows.length;
      if (rowCount > 0) {
        desiredPageSizeRef.current = Number.POSITIVE_INFINITY;
        table.setPageSize(rowCount);
      }
    };
    const onClearColumnFilters = () => setColumnFilters([]);
    window.addEventListener(HotkeyEvent.EXPAND_ALL_ROWS, onExpandAll);
    window.addEventListener(HotkeyEvent.COLLAPSE_ALL_ROWS, onCollapseAll);
    window.addEventListener(HotkeyEvent.SCROLL_RESULTS_TO_TOP, onScrollToTop);
    window.addEventListener(HotkeyEvent.SHOW_ALL_ROWS, onShowAll);
    window.addEventListener(HotkeyEvent.CLEAR_COLUMN_FILTERS, onClearColumnFilters);
    return () => {
      window.removeEventListener(HotkeyEvent.EXPAND_ALL_ROWS, onExpandAll);
      window.removeEventListener(HotkeyEvent.COLLAPSE_ALL_ROWS, onCollapseAll);
      window.removeEventListener(HotkeyEvent.SCROLL_RESULTS_TO_TOP, onScrollToTop);
      window.removeEventListener(HotkeyEvent.SHOW_ALL_ROWS, onShowAll);
      window.removeEventListener(HotkeyEvent.CLEAR_COLUMN_FILTERS, onClearColumnFilters);
    };
  }, [table, setColumnFilters]);
 
  // Reconcile the effective pageSize with what the user actually asked for
  // (`desiredPageSizeRef`) whenever the valid options change. Filtering shrinks
  // the row count, which can clamp the effective size below the user's choice;
  // clearing the filter grows it back. Reconciling against the *intent* rather
  // than the current (possibly-clamped) size means clearing a filter restores
  // the user's original selection — e.g. "All" survives a filter round-trip
  // instead of collapsing to the default 10.
  //
  // Valid sizes come from the *filter-applied total* (totalRowCount), not the
  // page-visible count (filteredRowCount): the latter creates a self-reinforcing
  // collapse where valid sizes shrink to `[page-visible]`, forcing pageSize down,
  // which keeps only that many rows visible, etc. The options Select below uses
  // the total as well. Runs during render, not in an effect, because the MUI
  // Select warns about an out-of-range value before effects run.
  if (totalRowCount > 0) {
    const validSizes = generatePageSizes(totalRowCount, 10, 5);
    const currentPageSize = tableState.pagination?.pageSize ?? 10;
    const desired = desiredPageSizeRef.current;
    const target =
      desired >= totalRowCount
        ? totalRowCount // "all", or more than currently available → show every row
        : validSizes.includes(desired)
          ? desired
          : (validSizes.filter((size) => size <= desired).pop() ?? validSizes[0]);
    if (currentPageSize !== target) {
      table.setPageSize(target);
    }
  }
 
  // Initialize column visibility - this effect is still needed
  useEffect(() => {
    if (appContext && !isEmpty(appContext.userSettings.results?.hidden)) {
      table.getAllLeafColumns().map((column: Column<Product>) => {
        if (appContext.userSettings?.results?.hidden?.includes(column.id)) {
          column.toggleVisibility(false);
        }
      });
    }
  }, [appContext?.userSettings.results?.hidden, table]);
 
  // Auto column sizing is driven by the raw searchResults (not the filtered
  // row model) so that filter input keystrokes don't trigger column remeasuring.
  const { getMeasurementTableProps, autoSizeColumns } = useAutoColumnSizing(table, searchResults);
 
  // A column-resize drag ends with a stray `click` that bubbles to the header's
  // sort toggle (the click's target resolves to the <th>, so stopping propagation
  // on the resizer alone doesn't catch it). Mark a resize in progress on the
  // handle's pointer-down and clear it one frame after pointer-up — after the
  // stray click has already fired and been swallowed by the header handler below.
  const suppressSortAfterResizeRef = useRef(false);
  const markResizeStart = () => {
    suppressSortAfterResizeRef.current = true;
    window.addEventListener(
      'pointerup',
      () =>
        requestAnimationFrame(() => {
          suppressSortAfterResizeRef.current = false;
        }),
      { once: true },
    );
  };
 
  const handleSearch = (query: string) => {
    if (query.trim()) {
      runSearch(query.trim());
    }
  };
 
  const handleKeyPress = (event: KeyboardEvent) => {
    if (event.key === 'Enter' && isInputElement(event.target)) {
      handleSearch(event.target.value);
    }
  };
 
  const toggleFilters = () => {
    setShowFilters(!showFilters);
  };
 
  // Clear the results table's column filters (and the global filter) so hidden
  // results become visible again.
  const clearColumnFilters = () => {
    setColumnFilters([]);
    setGlobalFilter('');
  };
 
  // Reset every drawer search filter to its default and re-run the last query.
  // Re-triggers via the pending-query path so the search reads the freshly
  // cleared filters on the next render (rather than a stale closure).
  const retrySearchWithoutFilters = () => {
    if (!appContext) return;
    appContext.setSelectedSuppliers([]);
    appContext.setSearchFilters({
      ...appContext.searchFilters,
      availability: [],
      country: [],
      shippingType: [],
    });
    appContext.setUserSettings({
      ...appContext.userSettings,
      priceMin: undefined,
      priceMax: undefined,
      search: { ...appContext.userSettings.search, invertSuppliersSelection: false },
    });
    if (executedQuery) appContext.setPendingSearchQuery(executedQuery);
  };
 
  // Content for the empty table body — distinguishes "search returned nothing
  // while drawer filters were active" (offer a filter-free retry) from "results
  // exist but the table's column filters hide them all" (offer to clear those).
  const renderEmptyState = (): ReactNode => {
    if (searchResults.length === 0) {
      if (isLoading) return i18n('results_status_searching');
      if (executedQuery && advancedFilterCount > 0) {
        return (
          <>
            {i18n('results_status_no_results_filtered')}
            <Link
              component="button"
              type="button"
              onClick={retrySearchWithoutFilters}
              sx={{ display: 'block', mt: 1, mx: 'auto', cursor: 'pointer' }}
            >
              {i18n('results_retry_without_filters')}
            </Link>
          </>
        );
      }
      return tableText || i18n('results_status_no_search_query');
    }
    // searchResults exist but none are shown → the column/global filters hid them.
    const columnFiltersActive =
      table.getState().columnFilters.length > 0 || Boolean(table.getState().globalFilter);
    if (columnFiltersActive) {
      return (
        <>
          {i18n('results_status_hidden_by_column_filters', [String(searchResults.length)])}{' '}
          <Link component="button" type="button" onClick={clearColumnFilters}>
            {i18n('results_clear_column_filters')}
          </Link>
        </>
      );
    }
    return i18n('results_status_no_results_found');
  };
 
  return (
    <>
      <LoadingBackdrop
        open={isLoading}
        // Count top-level rows only — `searchResults.length` can double-count
        // when suppliers yield variants as flat products rather than nested.
        // `getFilteredRowModel().rows.length` is the committed parent-row count
        // (sub-rows live on each row's `.subRows`), which is what users see.
        resultCount={totalRowCount}
        supplierResultsCount={supplierResultsCount}
        isAborting={isAborting}
        query={executedQuery}
        onClick={handleStopSearch}
      />
      <div className={resultStyles['results-container']}>
        <div className={resultStyles['results-header']}>
          <div className={resultStyles['header-left']}>
            {appContext?.setPanel && (
              <BackButton
                onClick={() => appContext.setPanel!(0)}
                size="small"
                aria-label={i18n('common_back_to_search')}
              >
                <ArrowBackIcon />
              </BackButton>
            )}
          </div>
          <div className={resultStyles['header-right']}>
            {/* Advanced search: opens the drawer's Search tab (mirrors the home
                page's ScienceIcon). First icon, to the left of the others. Turns
                blue with a filter count on hover when any drawer filter is set. */}
            <Tooltip
              title={
                advancedFilterCount > 0
                  ? i18n('search_active_filters', [String(advancedFilterCount)])
                  : i18n('search_advanced_options')
              }
            >
              <ColoredIconButton
                onClick={() => appContext?.toggleDrawer(DRAWER_INDEX.SEARCH)}
                size="small"
                iconColor={advancedFilterCount > 0 ? '#4e73af' : '#666'}
                aria-label={i18n('search_advanced_options')}
              >
                <ScienceIcon />
              </ColoredIconButton>
            </Tooltip>
            <Tooltip
              title={
                hasActiveColumnFilters
                  ? i18n('results_active_column_filters', [String(activeColumnFilterCount)])
                  : i18n('results_toggle_filters')
              }
            >
              <FilterIconButton
                onClick={toggleFilters}
                size="small"
                // Blue when a column filter is applied, or while the filter row is
                // open (preserving the toggle's pressed-state affordance).
                isActive={hasActiveColumnFilters || showFilters}
                activeColor="#4e73af"
                textColor="#666"
                aria-label={i18n('results_toggle_filters')}
              >
                <FilterListIcon />
              </FilterIconButton>
            </Tooltip>
            <ColoredIconButton
              onClick={(e) => setColumnMenuAnchor(e.currentTarget)}
              size="small"
              iconColor="#666"
              aria-label={i18n('results_column_visibility')}
            >
              <ViewColumnIcon />
            </ColoredIconButton>
            <ColoredIconButton
              onClick={() => appContext?.toggleDrawer(DRAWER_INDEX.SETTINGS)}
              size="small"
              iconColor="#666"
              aria-label={i18n('results_open_options')}
            >
              <SettingsIcon />
            </ColoredIconButton>
            {/* Maximize: open in a full tab. Last icon, popup/side-panel only. */}
            {!isTabView() && (
              <ColoredIconButton
                onClick={() => void openExtensionTab()}
                size="small"
                iconColor="#666"
                aria-label={i18n('common_open_in_tab')}
              >
                <OpenInNewIcon />
              </ColoredIconButton>
            )}
          </div>
        </div>
 
        {/* <div className="results-title">Search Results ({searchResults.length} found)</div> */}
 
        <ResultsHeaderContainer>
          {/* One chip per searched reagent; clicking opens its chemical details. The
              result count lives in the pagination footer below. */}
          {executedQuery ? (
            <ChemicalChips query={executedQuery} onSelect={setChemicalInfoTerm} />
          ) : null}
          {/* Only show the global filter if there are results. Based on
              searchResults (not the filtered row model) so the input doesn't
              vanish once the user's filter query matches zero rows. */}
          {searchResults.length > 0 && (
            <GlobalFilterTextField
              size="small"
              variant="outlined"
              placeholder={i18n('results_filter_placeholder')}
              value={globalFilter}
              onChange={(e) => setGlobalFilter(e.target.value)}
              inputRef={globalFilterInputRef}
              slotProps={{
                input: {
                  onKeyDown: handleKeyPress,
                  'aria-label': i18n('results_filter_aria'),
                },
              }}
            />
          )}
        </ResultsHeaderContainer>
        <ChemicalInfoDialog
          term={chemicalInfoTerm}
          onClose={() => setChemicalInfoTerm(undefined)}
        />
 
        <Box
          ref={scrollContainerRef}
          className={`${resultStyles['results-paper']} ${resultStyles['results-paper-container']}`}
        >
          {/* Hidden measurement table for auto-sizing */}
          <table
            className={resultStyles['hidden-measurement-table']}
            {...getMeasurementTableProps()}
          >
            <thead className="results-table-column-headers">
              <tr>
                {table.getFlatHeaders().map((header) => (
                  <th key={header.id}>
                    {/* Wrap the header in a nowrap span so its own text width is
                        measurable independently of the column width. Rendered
                        via flexRender (not col.id) so function headers like
                        "Price (USD)" are measured correctly and set the column's
                        minimum width. */}
                    <span style={{ whiteSpace: 'nowrap' }}>
                      {flexRender(header.column.columnDef.header, header.getContext())}
                    </span>
                  </th>
                ))}
              </tr>
            </thead>
            <tbody className="results-table-body">
              {table
                .getRowModel()
                .rows.slice(0, 5)
                .map((row) => (
                  <tr key={row.id}>
                    {row.getVisibleCells().map((cell) => (
                      // `nowrap` (no width pin) makes scrollWidth report the
                      // natural single-line content width, so each column fits
                      // its content (clamped by meta.autoSizeMax) instead of a
                      // uniform width that leaves dead space after short values.
                      <td key={cell.id} style={{ whiteSpace: 'nowrap' }}>
                        {typeof cell.column.columnDef.cell === 'function'
                          ? cell.column.columnDef.cell(cell.getContext())
                          : ''}
                      </td>
                    ))}
                  </tr>
                ))}
            </tbody>
          </table>
 
          <SearchResultsTable>
            {/* Table Head */}
            <StyledTableHead>
              {table.getHeaderGroups().map((headerGroup) => (
                <TableRow key={headerGroup.id}>
                  {headerGroup.headers.map((header) => (
                    <StickyHeaderCell
                      key={header.id}
                      canSort={header.column.getCanSort()}
                      cellWidth={header.getSize()}
                      onClick={(event) => {
                        // Swallow the stray click that ends a column resize so it
                        // doesn't toggle the sort (see markResizeStart).
                        if (suppressSortAfterResizeRef.current) return;
                        header.column.getToggleSortingHandler()?.(event);
                      }}
                      style={header.column.columnDef.meta?.style}
                    >
                      {header.isPlaceholder ? null : (
                        <HeaderCellContent>
                          {flexRender(header.column.columnDef.header, header.getContext())}
                          {header.column.getCanSort() && (
                            <SortIndicator>
                              {
                                {
                                  asc: <ArrowDropUpIcon />,
                                  desc: <ArrowDropDownIcon />,
                                }[String(header.column.getIsSorted())]
                              }
                            </SortIndicator>
                          )}
                        </HeaderCellContent>
                      )}
                      {header.column.getCanResize() && (
                        <ColumnResizer
                          isResizing={header.column.getIsResizing()}
                          onMouseDown={(event) => {
                            markResizeStart();
                            header.getResizeHandler()(event);
                          }}
                          onTouchStart={(event) => {
                            markResizeStart();
                            header.getResizeHandler()(event);
                          }}
                          // Stop the drag/click from bubbling to the header's
                          // sort toggle handler.
                          onClick={(event) => event.stopPropagation()}
                          // Double-click any handle to best-fit every column to
                          // its content width.
                          onDoubleClick={(event) => {
                            event.stopPropagation();
                            autoSizeColumns();
                          }}
                          className={`resizer${header.column.getIsResizing() ? ' isResizing' : ''}`}
                        />
                      )}
                    </StickyHeaderCell>
                  ))}
                </TableRow>
              ))}
 
              {/* Filter Row */}
              {showFilters &&
                table.getHeaderGroups().map((headerGroup) => {
                  return (
                    <TableRow key={`${headerGroup.id}-filters`}>
                      {headerGroup.headers.map((header) => {
                        if (header.column.id === 'expander') {
                          return (
                            <FilterTableCell
                              key={`${header.id}-filter`}
                              cellWidth={27.5}
                              sx={{ flexShrink: 0 }}
                            >
                              <Tooltip title={i18n('results_clear_filters')}>
                                <IconButton
                                  size="small"
                                  onClick={() => columnFilterFns[1]([])}
                                  aria-label={i18n('results_clear_filters')}
                                  sx={{ flexShrink: 0 }}
                                >
                                  <SearchOffIcon fontSize="small" sx={{ flexShrink: 0 }} />
                                </IconButton>
                              </Tooltip>
                            </FilterTableCell>
                          );
                        }
                        return (
                          <FilterTableCell key={`${header.id}-filter`} cellWidth={header.getSize()}>
                            {header.column.getCanFilter() ? (
                              <FilterVariantCell header={header} />
                            ) : null}
                          </FilterTableCell>
                        );
                      })}
                    </TableRow>
                  );
                })}
            </StyledTableHead>
 
            {/* Table Body */}
            <StyledTableBody>
              {table.getRowModel().rows.length > 0 ? (
                // Render only top-level rows. Variants still exist as sub-rows in
                // the model (so hierarchy filtering works), but instead of
                // rendering them as their own rows we surface them — plus the
                // product image and detail fields — in an expanded panel below.
                table
                  .getRowModel()
                  .rows.filter((row) => row.depth === 0)
                  .map((row) => (
                    <Fragment key={row.id}>
                      <SubRowTableRow
                        isSubRow={false}
                        onContextMenu={(e) => handleContextMenu(e, row.original)}
                      >
                        {row.getVisibleCells().map((cell) => (
                          <StyledTableCell
                            key={cell.id}
                            className={resultStyles['styled-table-cell']}
                            style={{
                              textAlign: cell.column.columnDef.meta?.style?.textAlign,
                              // Under table-layout: fixed, let long unbreakable
                              // tokens wrap instead of overflowing the column.
                              overflowWrap: 'anywhere',
                            }}
                          >
                            {cell.column.columnDef.meta?.truncate ? (
                              // The fixed-layout cell already has a definite
                              // width, so the block fills it and ellipsizes the
                              // overflow; full text shows in the hover tooltip.
                              <TruncatedCellText title={String(cell.getValue() ?? '')}>
                                {flexRender(cell.column.columnDef.cell, cell.getContext())}
                              </TruncatedCellText>
                            ) : (
                              flexRender(cell.column.columnDef.cell, cell.getContext())
                            )}
                          </StyledTableCell>
                        ))}
                      </SubRowTableRow>
                      {row.getIsExpanded() && (
                        <TableRow>
                          <ProductDetailPanelCell colSpan={row.getVisibleCells().length}>
                            <ProductDetailPanel row={row} table={table} />
                          </ProductDetailPanelCell>
                        </TableRow>
                      )}
                    </Fragment>
                  ))
              ) : (
                <TableRow className={resultStyles['styled-table-row']}>
                  <EmptyStateCell colSpan={table.getAllColumns().length}>
                    {renderEmptyState()}
                  </EmptyStateCell>
                </TableRow>
              )}
            </StyledTableBody>
          </SearchResultsTable>
 
          {/* Enhanced error handling */}
          {error && (
            <ErrorContainer className={resultStyles['error-container']}>
              <p>{i18n('results_error', [error])}</p>
              <ErrorRetryButton onClick={reloadPage} className={resultStyles['error-retry-button']}>
                {i18n('results_retry')}
              </ErrorRetryButton>
            </ErrorContainer>
          )}
 
          {/* Pagination Controls - Only show if more than 1 page */}
          {totalRowCount > 10 && (
            <PaginationContainer>
              {/* Page Size Selector */}
              <PageSizeContainer>
                <Typography variant="body2">{i18n('results_show')}:</Typography>
                <FormControl size="small">
                  <PageSizeSelect
                    value={table.getState().pagination.pageSize}
                    onChange={(e) => {
                      const next = Number(e.target.value);
                      // "All" is the option whose value equals the current total;
                      // record it as an unbounded intent so it survives a filter
                      // round-trip even as the total changes.
                      desiredPageSizeRef.current =
                        next >= totalRowCount ? Number.POSITIVE_INFINITY : next;
                      table.setPageSize(next);
                    }}
                    aria-label={i18n('results_rows_per_page_aria')}
                  >
                    {generatePageSizes(totalRowCount, 10, 5).map((pageSize) => (
                      <MenuItem key={pageSize} value={pageSize}>
                        {pageSize === totalRowCount ? i18n('results_all') : pageSize}
                      </MenuItem>
                    ))}
                  </PageSizeSelect>
                </FormControl>
                <Typography variant="body2">{i18n('results_rows')}</Typography>
              </PageSizeContainer>
 
              {/* Page Info — "Showing N of M" surfaces the post-filter vs
                  pre-filter delta when the user narrows the results with a
                  column / global filter. When no filter is active (filtered
                  === total) it collapses back to the plain total form. */}
              <Typography variant="body2">
                {i18n('results_page_of_total', [
                  String(table.getState().pagination.pageIndex + 1),
                  String(table.getPageCount()),
                ]) + ' '}
                {filteredRowCount === totalRowCount
                  ? i18n('results_total', [String(totalRowCount)])
                  : i18n('results_showing', [String(filteredRowCount), String(totalRowCount)])}
              </Typography>
 
              {/* Navigation Buttons */}
              <NavigationContainer>
                <IconButton
                  onClick={() => table.setPageIndex(0)}
                  disabled={!table.getCanPreviousPage()}
                  size="small"
                >
                  <FirstPageIcon />
                </IconButton>
                <IconButton
                  onClick={() => table.previousPage()}
                  disabled={!table.getCanPreviousPage()}
                  size="small"
                >
                  <ChevronLeftIcon />
                </IconButton>
                <IconButton
                  onClick={() => table.nextPage()}
                  disabled={!table.getCanNextPage()}
                  size="small"
                >
                  <ChevronRightIcon />
                </IconButton>
                <IconButton
                  onClick={() => table.setPageIndex(table.getPageCount() - 1)}
                  disabled={!table.getCanNextPage()}
                  size="small"
                >
                  <LastPageIcon />
                </IconButton>
              </NavigationContainer>
            </PaginationContainer>
          )}
        </Box>
 
        {/* Column Visibility Menu */}
        <Menu
          anchorEl={columnMenuAnchor}
          open={Boolean(columnMenuAnchor)}
          onClose={() => setColumnMenuAnchor(null)}
          className={styles['column-visibility-menu']}
        >
          {table
            .getAllLeafColumns()
            .filter((column) => column.getCanHide())
            .map((column) => {
              // Read the header off the column definition (present for hidden
              // columns too, unlike getFlatHeaders which only covers visible ones).
              // String headers are already localized; the price column's function
              // header falls back to its plain i18n label so it isn't stringified
              // into JS source or dropped to the raw lowercase column id.
              const headerDef = column.columnDef.header;
              const label = typeof headerDef === 'string' ? headerDef : i18n(`column_${column.id}`);
              return (
                <ColumnMenuItemContainer key={column.id}>
                  <FormControlLabel
                    control={
                      <Checkbox
                        checked={column.getIsVisible()}
                        onChange={column.getToggleVisibilityHandler()}
                      />
                    }
                    label={<ListItemText primary={label} />}
                  />
                </ColumnMenuItemContainer>
              );
            })}
        </Menu>
 
        {/* Context Menu */}
        {contextMenu && contextMenu.product && (
          <ContextMenu
            x={contextMenu.x}
            y={contextMenu.y}
            product={contextMenu.product}
            table={table}
            onClose={handleCloseContextMenu}
            onExcludeProduct={excludeProduct}
            executedQuery={executedQuery}
          />
        )}
      </div>
    </>
  );
}