All files / src/web/pages Inbox.tsx

65.56% Statements 594/906
64.94% Branches 63/97
53.33% Functions 8/15
65.56% Lines 594/906

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 11241x 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 2x 2x         2x   2x 2x     2x 2x   2x 2x 2x 2x 2x 2x   2x     1x     1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x   1x 1x 1x 1x     1x 81x 81x 81x 81x     81x 81x 30x 30x 30x 30x 81x 81x     81x 81x 81x 81x 81x 81x 81x 81x 81x 81x 81x 81x 81x 81x 81x 81x 81x 81x 81x 81x 81x 81x 81x 81x 81x 81x 81x 81x 81x 81x 81x 81x 81x 81x 81x 81x 81x 81x     81x     81x 8x 8x 81x     81x 81x 1x 1x 1x 81x 81x   81x 81x       81x 81x     81x 81x 1x   1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 81x 81x     81x 81x                         81x 81x         81x     81x   81x 81x 81x     81x                     81x 81x     81x     81x 30x 30x 30x 30x 30x   30x 30x             30x 81x     81x 81x 81x 81x 81x 81x 81x 81x 81x 81x         81x 81x 81x 81x 81x 81x 81x     81x 30x   30x             30x 30x                                                               81x     81x 81x 30x 30x 30x 30x 30x 30x 30x 30x 81x 81x 81x 81x 81x 81x 81x 81x 81x 81x   81x 81x 81x 81x 81x     81x     81x 81x 81x 81x     81x     81x 81x 81x 81x 81x 81x 81x 81x 81x 81x 81x 81x 81x 81x     81x 81x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 81x 81x 81x 81x 81x 81x 81x 81x 81x 81x 81x 81x 81x 81x 81x     81x 81x 81x 81x 81x 81x   81x 81x 81x     81x 81x     81x     81x     81x 30x 30x 30x 81x     81x 4x 4x 81x   81x 12x 12x 12x   12x 12x 12x 12x   12x 12x 12x 12x 12x 81x   81x 1x   1x 1x 1x 1x 1x 81x   81x       81x   81x       81x     81x 1x   1x 1x   1x 1x 1x 1x 1x 1x 81x   81x 1x   1x 1x   1x 1x 1x 1x 1x 1x 81x   81x 3x   3x 3x   3x 3x 2x 2x 3x 3x 81x   81x                       81x   81x                                       81x     81x 81x                                                                                                                                                                                                                                                                           81x 81x 81x 81x 81x 81x 81x 81x 81x 81x 81x 81x   81x 81x                                   81x 81x     81x 81x                         81x 81x     81x   81x     81x             81x   81x 81x 4x   4x 4x 3x 4x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 4x 4x 4x 81x 81x   81x 81x 3x   3x 3x 2x 3x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 3x 3x 3x 81x 81x   81x 81x 2x   2x 2x   2x 2x 2x 2x 2x                     2x 2x 2x 81x 81x   81x 81x 1x   1x 1x 1x 1x                     1x 1x 1x 81x 81x   81x 81x                                       81x 81x   81x 81x                   81x 81x     81x 30x 30x 30x 30x 30x 81x   81x 30x     81x           81x 30x 30x 30x                   81x     81x     81x 30x 30x       30x 81x     81x 1x 1x     81x 1x 1x   79x   79x 79x   79x 79x 79x 79x 79x   79x 79x 79x 79x 79x 79x 79x 79x 79x 79x 79x 79x 79x 79x 79x 79x 79x 79x 79x 79x 79x 79x 79x 79x     79x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x       81x 81x 81x 81x 81x     81x 81x 81x 81x       81x 81x     81x 81x   81x         79x 2x   77x 77x 77x 77x 77x 77x 77x 77x 77x   77x 77x 77x 77x   77x 12x 12x 77x 77x 3x 3x 3x 77x 2x 2x 2x 77x 1x 1x 77x         77x 77x 77x 77x     77x 77x   77x     77x 77x   77x 77x 77x   77x 77x 77x 77x 77x   81x   81x   81x   1x   1x  
import { Mail } from 'lucide-react';
import React, { memo, useCallback, useEffect, useMemo, useState } from 'react';
import { useNavigate } from 'react-router-dom';
 
import BulkSelectionActions from '@web/components/BulkSelectionActions';
import { TimeRange } from '@web/components/TimeFilter';
 
import LoadingScreen from '@common/components/common/LoadingScreen';
import { InboxFilterType, InfiniteNewsletterList } from '@web/components/InfiniteScroll';
 
import { useInfiniteNewsletters } from '@common/hooks/infiniteScroll';
import { useErrorHandling } from '@common/hooks/useErrorHandling';
import { useInboxFilters } from '@common/hooks/useInboxFilters';
import { useBulkLoadingStates } from '@common/hooks/useLoadingStates';
import { useNewsletters } from '@common/hooks/useNewsletters';
import { useNewsletterSourceGroups } from '@common/hooks/useNewsletterSourceGroups';
import { useReadingQueue } from '@common/hooks/useReadingQueue';
import { useSharedNewsletterActions } from '@common/hooks/useSharedNewsletterActions';
import { useGroupCounts } from '@web/hooks/useGroupCounts';
import { parseFilterUrlParams, syncFilterUrl } from '@web/utils/filterUrlUtils';
 
import { useAuth } from '@common/contexts';
import { useToast } from '@common/contexts/ToastContext';
import { useLogger } from '@common/utils/logger/useLogger';
 
import { SelectedFiltersDisplay } from '@web/components/SelectedFiltersDisplay';
import SelectedTagsDisplay from '@web/components/SelectedTagsDisplay';
 
import type { NewsletterWithRelations, Tag } from '@common/types';
import { getCacheManager } from '@common/utils/cacheUtils';
import { DependencyValidator, ValidationRules } from '../../common/utils/dependencyValidation.ts';
import { InboxFilters } from '../components/InboxFilters.tsx';
 
declare global {
  interface Window {
    __inboxGroupFilterInitRun?: boolean;
  }
}
 
// Separate component for empty state
const EmptyState: React.FC<{
  filter: string;
  sourceFilter: string | null;
}> = memo(({ filter, sourceFilter }) => {
  const getEmptyMessage = () => {
    if (filter === 'unread') return 'No unread newsletters';
    if (filter === 'liked') return 'No liked newsletters';
    if (filter === 'archived') return 'No archived newsletters';
    if (sourceFilter) return 'No newsletters found for this source';
    return 'No newsletters found';
  };
 
  const getEmptyDescription = () => {
    if (sourceFilter) {
      return 'Try selecting a different source or adjusting your filters.';
    }
    return 'Try adjusting your filters or check back later.';
  };
 
  return (
    <div className="flex flex-col items-center justify-center py-16 text-neutral-500">
      <Mail className="mx-auto h-14 w-14 mb-4 text-blue-300" />
      <h2 className="text-xl font-semibold mb-2">{getEmptyMessage()}</h2>
      <p className="text-base text-neutral-400">{getEmptyDescription()}</p>
    </div>
  );
});
 
// Separate component for error state
const ErrorState: React.FC<{
  error: Error | null;
  onRetry: () => void;
}> = memo(({ error, onRetry }) => (
  <div className="flex flex-col items-center justify-center h-screen bg-neutral-50 p-4">
    <div className="text-center">
      <Mail className="mx-auto h-16 w-16 text-red-500 mb-4" />
      <h2 className="text-2xl font-semibold text-neutral-800 mb-2">Error Loading Newsletters</h2>
      <p className="text-neutral-600 mb-6">
        {error?.message || 'Something went wrong. Please try again later.'}
      </p>
      <button
        onClick={onRetry}
        className="px-6 py-2 bg-primary-600 text-white rounded-md hover:bg-primary-700 transition-colors"
      >
        Try Again
      </button>
    </div>
  </div>
));
 
// Main Inbox component - now focused primarily on rendering
const Inbox: React.FC = () => {
  const navigate = useNavigate();
  const { user } = useAuth();
  const { showError } = useToast();
  const log = useLogger();
 
  // Create dependency validator for this component
  const dependencyValidator = useMemo(
    () =>
      new DependencyValidator({
        errorPrefix: 'Inbox component dependency validation failed',
        rules: [ValidationRules.noDependencies('groupFilterInitialization')],
      }),
    []
  );
 
  // Filter management using our new context and hooks
  const {
    filter,
    setFilter,
    sourceFilter,
    setSourceFilter,
    timeRange,
    _tagIds,
    debouncedTagIds,
    _pendingTagUpdates,
    visibleTags,
    setVisibleTags,
    allTags,
    groupFilters,
    sortBy,
    sortOrder,
    _newsletterFilter,
    _hasActiveFilters,
    _isFilterActive,
    useLocalTagFiltering,
    newsletterSources,
    isLoadingSources,
    setTimeRange,
    _setTagIds,
    _setPendingTagUpdates,
    _toggleTag,
    _addTag,
    removeTag,
    resetFilters,
    _updateTagDebounced,
    handleTagClick,
    setGroupFilters,
    _toggleGroup,
    _addGroup,
    _removeGroup,
    _clearGroups,
    setSortBy,
    setSortOrder,
  } = useInboxFilters();
 
  // Group filters state (multi-select)
  const { groups: newsletterGroups = [], isLoading: isLoadingGroups } = useNewsletterSourceGroups();
 
  // Helper function to preserve URL parameters after actions
  const preserveFilterParams = useCallback(() => {
    const currentParams = parseFilterUrlParams(new URLSearchParams(window.location.search));
    syncFilterUrl(currentParams, filter, sourceFilter, groupFilters, debouncedTagIds, timeRange);
  }, [filter, sourceFilter, groupFilters, timeRange, debouncedTagIds]);
 
  // When group(s) are selected, clear source filter; when source is selected, clear group filters
  const handleSourceFilterChange = useCallback(
    (sourceId: string | null) => {
      setGroupFilters([]);
      setSourceFilter(sourceId);
    },
    [setGroupFilters, setSourceFilter] // Added setSourceFilter as required by linter
  );
 
  const handleGroupFiltersChange = useCallback(
    (groupIds: string[]) => {
      setSourceFilter(null);
      setGroupFilters(groupIds);
    },
    [setGroupFilters, setSourceFilter] // Added setSourceFilter as required by linter
  );
 
  // Handle filter changes while preserving group filters in URL
  const handleFilterChange = useCallback(
    (newFilter: string) => {
      setFilter(newFilter as InboxFilterType); // Type assertion to handle string to InboxFilterType conversion
      // Sync URL parameters with current state including group filters
      const currentParams = parseFilterUrlParams(new URLSearchParams(window.location.search));
      syncFilterUrl(
        currentParams,
        newFilter,
        sourceFilter,
        groupFilters,
        debouncedTagIds,
        timeRange
      );
    },
    [sourceFilter, groupFilters, debouncedTagIds, timeRange, setFilter] // Added setFilter back as dependency
  );
 
  // Handle time range changes while preserving group filters in URL
  const handleTimeRangeChange = useCallback(
    (newTimeRange: string) => {
      setTimeRange(newTimeRange as TimeRange); // Type assertion to handle string to TimeRange conversion
      // Sync URL parameters with current state including group filters
      const currentParams = parseFilterUrlParams(new URLSearchParams(window.location.search));
      syncFilterUrl(
        currentParams,
        filter,
        sourceFilter,
        groupFilters,
        debouncedTagIds,
        newTimeRange
      );
    },
    [filter, sourceFilter, groupFilters, debouncedTagIds, setTimeRange]
  );
 
  // True while we have an active group filter but groups haven't finished loading yet.
  // During this window we must NOT fire the newsletter query – it would run without
  // any sourceIds restriction and then get stuck showing the unfiltered result.
  const isWaitingForGroups = groupFilters.length > 0 && isLoadingGroups;
 
  // Compute source IDs for the selected groups (union)
  const selectedGroupSourceIds = useMemo(() => {
    // Return undefined if no groups are selected
    if (!groupFilters || groupFilters.length === 0) {
      return undefined;
    }
 
    // Wait for groups to load before converting
    if (isLoadingGroups || newsletterGroups.length === 0) {
      return undefined;
    }
 
    const idSet = new Set<string>();
    groupFilters.forEach((gid) => {
      const g = newsletterGroups.find((x) => x.id === gid);
      g?.sources?.forEach((s) => idSet.add(s.id));
    });
 
    const sourceIds = Array.from(idSet);
    return sourceIds.length > 0 ? sourceIds : undefined;
  }, [groupFilters, newsletterGroups, isLoadingGroups]);
 
  // Newsletter filter from context
  const { newsletterFilter: contextNewsletterFilter } = useInboxFilters();
 
  // Stabilize the newsletter filter to prevent unnecessary re-renders
  const stableNewsletterFilter = useMemo(() => {
    let filterObj = {
      ...contextNewsletterFilter,
      tagIds: contextNewsletterFilter.tagIds ? [...contextNewsletterFilter.tagIds] : undefined,
      sourceIds: contextNewsletterFilter.sourceIds
        ? [...contextNewsletterFilter.sourceIds]
        : undefined,
    };
    if (groupFilters.length > 0 && selectedGroupSourceIds) {
      filterObj = {
        ...filterObj,
        sourceIds: selectedGroupSourceIds,
      };
    }
 
    return filterObj;
  }, [contextNewsletterFilter, groupFilters, selectedGroupSourceIds]);
 
  // Newsletter data with infinite scroll
  const {
    newsletters: rawNewsletters,
    isLoading: isLoadingNewsletters,
    isLoadingMore,
    error: errorNewsletters,
    hasNextPage,
    fetchNextPage,
    refetch: refetchNewsletters,
    totalCount,
  } = useInfiniteNewsletters(stableNewsletterFilter, {
    // Do not start fetching newsletters while we are still waiting for the group
    // data that determines which sourceIds to filter by.  Without this guard the
    // hook would fire an unfiltered query, cache the wrong result, and then never
    // automatically re-fetch once the correct group-scoped filter is ready.
    enabled: !isWaitingForGroups,
    _refetchOnWindowFocus: false,
    _refetchOnMount: useLocalTagFiltering && debouncedTagIds.length > 0, // Force refetch when tags are selected
    _staleTime: 0,
    pageSize: 25,
    debug: process.env.NODE_ENV === 'development',
  });
 
  // Apply client-side tag filtering when useLocalTagFiltering is enabled
  const newsletters = useMemo(() => {
    if (!useLocalTagFiltering || !debouncedTagIds.length) {
      // Debug: No client-side filtering needed
      if (process.env.NODE_ENV === 'development' && debouncedTagIds.length > 0) {
        console.log('[Inbox] Skipping client-side filtering:', {
          useLocalTagFiltering,
          tagCount: debouncedTagIds.length,
          rawCount: rawNewsletters.length,
        });
      }
      return rawNewsletters;
    }
 
    const filtered = rawNewsletters.filter((newsletter) => {
      const newsletterTagIds = newsletter.tags?.map((tag) => tag.id) || [];
      return debouncedTagIds.every((requiredTagId) => newsletterTagIds.includes(requiredTagId));
    });
 
    // Debug: Log client-side filtering results
    if (process.env.NODE_ENV === 'development') {
      console.log('[Inbox] Client-side tag filtering applied:', {
        filter,
        requiredTags: debouncedTagIds,
        rawCount: rawNewsletters.length,
        filteredCount: filtered.length,
        sampleRawNewsletter: rawNewsletters[0]
          ? {
            id: rawNewsletters[0].id,
            title: rawNewsletters[0].title?.substring(0, 50),
            tags: rawNewsletters[0].tags?.map((t) => ({ id: t.id, name: t.name })),
          }
          : null,
        sampleFiltered: filtered[0]
          ? {
            id: filtered[0].id,
            title: filtered[0].title?.substring(0, 50),
            tags: filtered[0].tags?.map((t) => ({ id: t.id, name: t.name })),
          }
          : null,
      });
    }
 
    return filtered;
  }, [rawNewsletters, useLocalTagFiltering, debouncedTagIds, filter]);
 
  // Prepare group dropdown data with correct counts based on current filter (server-aligned)
  const groupCountsBaseFilter = useMemo(
    () => ({
      search: contextNewsletterFilter.search,
      isRead: contextNewsletterFilter.isRead,
      isArchived: contextNewsletterFilter.isArchived,
      isLiked: contextNewsletterFilter.isLiked,
      tagIds: contextNewsletterFilter.tagIds,
      dateFrom: contextNewsletterFilter.dateFrom,
      dateTo: contextNewsletterFilter.dateTo,
    }),
    [
      contextNewsletterFilter.search,
      contextNewsletterFilter.isRead,
      contextNewsletterFilter.isArchived,
      contextNewsletterFilter.isLiked,
      contextNewsletterFilter.tagIds,
      contextNewsletterFilter.dateFrom,
      contextNewsletterFilter.dateTo,
    ]
  );
 
  const groupCounts = useGroupCounts(newsletterGroups, groupCountsBaseFilter);
  const groupsForDropdown = useMemo(
    () => newsletterGroups.map((g) => ({ id: g.id, name: g.name, count: groupCounts[g.id] ?? 0 })),
    [newsletterGroups, groupCounts]
  );
 
  // Reading queue
  const { readingQueue = [], removeFromQueue } = useReadingQueue() || {};
 
  // Error handling
  const { handleError } = useErrorHandling({
    enableToasts: true,
    enableLogging: true,
  });
 
  // Loading states for bulk operations
  const bulkLoadingStates = useBulkLoadingStates();
 
  // Get newsletter mutations from useNewsletters hook (new onMutate handlers)
  const {
    markAsRead,
    markAsUnread,
    toggleLike,
    toggleArchive,
    deleteNewsletter,
    toggleInQueue,
    bulkMarkAsRead,
    bulkMarkAsUnread,
    bulkArchive,
    bulkUnarchive,
    bulkDeleteNewsletters,
    updateNewsletterTags,
  } = useNewsletters();
 
  // Memoize mutations object to prevent unnecessary re-renders
  const mutations = useMemo(
    () => ({
      markAsRead,
      markAsUnread,
      toggleLike,
      toggleArchive,
      deleteNewsletter,
      toggleInQueue,
      bulkMarkAsRead,
      bulkMarkAsUnread,
      bulkArchive,
      bulkUnarchive,
      bulkDeleteNewsletters,
      updateNewsletterTags,
    }),
    [
      markAsRead,
      markAsUnread,
      toggleLike,
      toggleArchive,
      deleteNewsletter,
      toggleInQueue,
      bulkMarkAsRead,
      bulkMarkAsUnread,
      bulkArchive,
      bulkUnarchive,
      bulkDeleteNewsletters,
      updateNewsletterTags,
    ]
  );
 
  // Shared newsletter actions with our enhanced version
  const newsletterActions = useSharedNewsletterActions(mutations, {
    showToasts: true,
    optimisticUpdates: true,
    enableErrorHandling: true,
    enableLoadingStates: true,
    onSuccess: useCallback(() => {
      // Trigger any additional success handling
    }, []),
    onError: handleError,
  });
 
  // Selection state (local to component since it's UI-only)
  const [selectedIds, setSelectedIds] = useState<Set<string>>(new Set());
  const [isSelecting, setIsSelecting] = useState(false);
 
  // Tag error handling state
  const [tagUpdateError, setTagUpdateError] = useState<string | null>(null);
 
  // Action progress state to prevent refetching during actions
  const [_isActionInProgress, setIsActionInProgress] = useState(false);
 
  // Get selected tag objects for display
  const selectedTags = useMemo(() => {
    return debouncedTagIds
      .map((tagId) => allTags.find((tag) => tag.id === tagId))
      .filter((tag): tag is NonNullable<typeof tag> => tag !== undefined);
  }, [allTags, debouncedTagIds]);
 
  // Selection handlers
  const clearSelection = useCallback(() => {
    setSelectedIds(new Set());
    setIsSelecting(false);
  }, []);
 
  const toggleSelect = useCallback((id: string) => {
    setSelectedIds((prev) => {
      const newSet = new Set(prev);
      if (newSet.has(id)) {
        newSet.delete(id);
      } else {
        newSet.add(id);
      }
      if (newSet.size === 0) {
        setIsSelecting(false);
      } else {
        setIsSelecting(true);
      }
      return newSet;
    });
  }, []);
 
  const toggleSelectAll = useCallback(() => {
    if (selectedIds.size === newsletters.length) {
      clearSelection();
    } else {
      const allIds = new Set(newsletters.map((n) => n.id));
      setSelectedIds(allIds);
      setIsSelecting(true);
    }
  }, [newsletters, selectedIds.size, clearSelection]);
 
  const selectRead = useCallback(() => {
    const readIds = newsletters.filter((n) => n.is_read).map((n) => n.id);
    setSelectedIds(new Set(readIds));
    setIsSelecting(readIds.length > 0);
  }, [newsletters]);
 
  const selectUnread = useCallback(() => {
    const unreadIds = newsletters.filter((n) => !n.is_read).map((n) => n.id);
    setSelectedIds(new Set(unreadIds));
    setIsSelecting(unreadIds.length > 0);
  }, [newsletters]);
 
  // Memoized bulk action handlers with optimistic updates
  const handleBulkMarkAsRead = useCallback(async () => {
    if (selectedIds.size === 0) return;
 
    const ids = Array.from(selectedIds);
    setIsActionInProgress(true);
 
    try {
      await newsletterActions.handleBulkMarkAsRead(ids);
      clearSelection();
    } finally {
      setIsActionInProgress(false);
    }
  }, [selectedIds, newsletterActions, clearSelection]);
 
  const handleBulkMarkAsUnread = useCallback(async () => {
    if (selectedIds.size === 0) return;
 
    const ids = Array.from(selectedIds);
    setIsActionInProgress(true);
 
    try {
      await newsletterActions.handleBulkMarkAsUnread(ids);
      clearSelection();
    } finally {
      setIsActionInProgress(false);
    }
  }, [selectedIds, newsletterActions, clearSelection]);
 
  const handleBulkArchive = useCallback(async () => {
    if (selectedIds.size === 0) return;
 
    const ids = Array.from(selectedIds);
    setIsActionInProgress(true);
 
    try {
      await newsletterActions.handleBulkArchive(ids);
      clearSelection();
    } finally {
      setIsActionInProgress(false);
    }
  }, [selectedIds, newsletterActions, clearSelection]);
 
  const handleBulkUnarchive = useCallback(async () => {
    if (selectedIds.size === 0) return;
 
    const ids = Array.from(selectedIds);
    setIsActionInProgress(true);
 
    try {
      await newsletterActions.handleBulkUnarchive(ids);
      clearSelection();
    } finally {
      setIsActionInProgress(false);
    }
  }, [selectedIds, newsletterActions, clearSelection]);
 
  const handleBulkDelete = useCallback(async () => {
    if (selectedIds.size === 0) return;
 
    if (
      !window.confirm(
        `Are you sure you want to permanently delete ${selectedIds.size} newsletter(s)? This action cannot be undone.`
      )
    ) {
      return;
    }
 
    const ids = Array.from(selectedIds);
    setIsActionInProgress(true);
 
    try {
      await newsletterActions.handleBulkDelete(ids);
      clearSelection();
    } finally {
      setIsActionInProgress(false);
    }
  }, [selectedIds, newsletterActions, clearSelection]);
 
  // Individual newsletter handlers with optimistic updates
  const handleNewsletterClick = useCallback(
    async (newsletter: NewsletterWithRelations) => {
      setIsActionInProgress(true);
 
      // Navigate immediately to avoid async issues
      // Build URL with query parameters to preserve filter context
      const params = new URLSearchParams();
 
      // Set separate read/unread and archived/unarchived parameters
      if (filter === 'unread') {
        params.set('isRead', 'false');
        params.set('isArchived', 'false');
      } else if (filter === 'read') {
        params.set('isRead', 'true');
        params.set('isArchived', 'false');
      } else if (filter === 'archived') {
        params.set('isArchived', 'true');
      } else if (filter === 'liked') {
        params.set('filter', 'liked'); // Keep filter parameter for liked
      }
 
      // Also keep the original filter parameter for backward compatibility
      if (filter && filter !== 'unread') {
        params.set('filter', filter);
      } else if (filter === 'unread') {
        // Explicitly set unread filter in URL for navigation
        params.set('filter', 'unread');
      }
 
      if (sourceFilter) {
        params.set('source', sourceFilter);
      }
      // Multi-group param support
      if (groupFilters && groupFilters.length > 0) {
        params.set('groups', groupFilters.join(','));
      }
      if (timeRange && timeRange !== 'all') {
        params.set('time', timeRange);
      }
      if (debouncedTagIds && debouncedTagIds.length > 0) {
        params.set('tags', debouncedTagIds.join(','));
      }
 
      const queryString = params.toString();
      const targetPath = `/newsletters/${newsletter.id}${queryString ? `?${queryString}` : ''}`;
 
      log.debug('Navigating to newsletter detail immediately', {
        action: 'navigate_to_detail',
        metadata: {
          newsletterId: newsletter.id,
          targetPath,
          currentPath: window.location.pathname,
          queryString,
        },
      });
 
      navigate(targetPath, {
        state: {
          from: '/inbox',
          fromInbox: true,
          currentFilter: filter,
          sourceFilter: sourceFilter,
          timeRange: timeRange,
          tagIds: debouncedTagIds,
        },
      });
 
      // Perform actions after navigation (they will continue in background)
      try {
        // Perform optimistic updates simultaneously for better UX
        const actions = [];
 
        // Mark as read if unread (optimistic)
        if (!newsletter.is_read) {
          actions.push(newsletterActions.handleMarkAsRead(newsletter.id));
        }
 
        // Archive the newsletter when opened from the inbox (optimistic)
        // But only if we're not in a filtered view that would hide it
        const shouldArchive =
          !newsletter.is_archived &&
          // Don't auto-archive if we're viewing archived newsletters
          filter !== 'archived' &&
          // Don't auto-archive if we're on a filter that would hide this newsletter
          // when it gets archived (like 'unread' for read newsletters, 'liked' for unliked newsletters)
          !(filter === 'unread' && newsletter.is_read) &&
          !(filter === 'liked' && !newsletter.is_liked);
 
        if (shouldArchive) {
          actions.push(newsletterActions.handleToggleArchive(newsletter));
        }
 
        // Execute actions in parallel for better performance
        if (actions.length > 0) {
          try {
            await Promise.allSettled(actions);
            log.debug('Newsletter actions completed successfully', {
              action: 'newsletter_actions_completed',
              metadata: {
                newsletterId: newsletter.id,
                actionsCount: actions.length,
                shouldArchive,
              },
            });
          } catch (actionError) {
            log.error(
              'Some newsletter actions failed during click',
              {
                action: 'newsletter_click_actions',
                metadata: {
                  newsletterId: newsletter.id,
                  actionsCount: actions.length,
                  shouldArchive,
                },
              },
              actionError instanceof Error ? actionError : new Error(String(actionError))
            );
          }
        }
 
        // Preserve filter parameters after navigation
        preserveFilterParams();
      } catch (error) {
        log.error(
          'Unexpected error in newsletter click handler',
          {
            action: 'newsletter_click',
            metadata: { newsletterId: newsletter.id },
          },
          error instanceof Error ? error : new Error(String(error))
        );
      } finally {
        setTimeout(() => setIsActionInProgress(false), 100);
      }
    },
    [
      navigate,
      newsletterActions,
      preserveFilterParams,
      log,
      filter,
      sourceFilter,
      groupFilters,
      timeRange,
      debouncedTagIds,
    ]
  );
 
  const handleRemoveFromQueue = useCallback(
    async (e: React.MouseEvent, newsletterId: string) => {
      e.stopPropagation();
      try {
        const queueItem = readingQueue.find((item) => item.newsletter_id === newsletterId);
        if (queueItem) {
          await removeFromQueue(queueItem.id);
          await refetchNewsletters();
        } else {
          showError('Failed to find item in queue');
        }
      } catch (error) {
        handleError(error, {
          category: 'business',
          severity: 'medium',
          context: { action: 'removeFromQueue', newsletterId },
        });
      }
    },
    [readingQueue, removeFromQueue, refetchNewsletters, showError, handleError]
  );
 
  // Tag visibility toggle handler
  const toggleTagVisibility = useCallback(
    async (id: string, e: React.MouseEvent) => {
      e.stopPropagation();
      setVisibleTags((prev: Set<string>) => {
        const newVisibleTags = new Set(prev);
        if (newVisibleTags.has(id)) {
          newVisibleTags.delete(id);
        } else {
          newVisibleTags.clear();
          newVisibleTags.add(id);
        }
        return newVisibleTags;
      });
    },
    [setVisibleTags]
  );
 
  // Tag error handling
  const handleDismissTagError = useCallback(() => {
    setTagUpdateError(null);
  }, []);
 
  // Newsletter prefetching on hover
  const handleNewsletterMouseEnter = useCallback((newsletter: NewsletterWithRelations) => {
    // Only prefetch if the newsletter is unread (more likely to be opened)
    // or if it's not archived (archived newsletters are less likely to be opened)
    if (!newsletter.is_read || !newsletter.is_archived) {
      // Prefetch newsletter details for better performance
      // This could be implemented with a prefetch hook if available
    }
  }, []);
 
  const handleToggleLikeWrapper = useCallback(
    async (newsletter: NewsletterWithRelations) => {
      setIsActionInProgress(true);
 
      try {
        await newsletterActions.handleToggleLike(newsletter);
        preserveFilterParams();
      } catch (error) {
        log.error(
          'Failed to toggle like status',
          {
            action: 'toggle_like',
            metadata: { newsletterId: newsletter.id, filter },
          },
          error instanceof Error ? error : new Error(String(error))
        );
        throw error;
      } finally {
        setTimeout(() => setIsActionInProgress(false), 100);
      }
    },
    [newsletterActions, filter, preserveFilterParams, log]
  );
 
  const handleToggleArchiveWrapper = useCallback(
    async (newsletter: NewsletterWithRelations) => {
      setIsActionInProgress(true);
 
      try {
        await newsletterActions.handleToggleArchive(newsletter);
        preserveFilterParams();
      } catch (error) {
        log.error(
          'Failed to toggle archive status',
          {
            action: 'toggle_archive',
            metadata: { newsletterId: newsletter.id, filter },
          },
          error instanceof Error ? error : new Error(String(error))
        );
        throw error;
      } finally {
        setTimeout(() => setIsActionInProgress(false), 100);
      }
    },
    [newsletterActions, preserveFilterParams, filter, log]
  );
 
  const handleToggleReadWrapper = useCallback(
    async (newsletter: NewsletterWithRelations) => {
      setIsActionInProgress(true);
 
      try {
        if (newsletter.is_read) {
          await newsletterActions.handleMarkAsUnread(newsletter.id);
        } else {
          await newsletterActions.handleMarkAsRead(newsletter.id);
        }
        preserveFilterParams();
      } catch (error) {
        log.error(
          'Failed to toggle read status',
          {
            action: 'toggle_read',
            metadata: { newsletterId: newsletter.id, filter },
          },
          error instanceof Error ? error : new Error(String(error))
        );
        throw error;
      } finally {
        setTimeout(() => setIsActionInProgress(false), 100);
      }
    },
    [newsletterActions, preserveFilterParams, filter, log]
  );
 
  const handleDeleteNewsletterWrapper = useCallback(
    async (newsletterId: string) => {
      setIsActionInProgress(true);
 
      try {
        await newsletterActions.handleDeleteNewsletter(newsletterId);
        preserveFilterParams();
      } catch (error) {
        log.error(
          'Failed to delete newsletter',
          {
            action: 'delete_newsletter',
            metadata: { newsletterId, filter },
          },
          error instanceof Error ? error : new Error(String(error))
        );
        throw error;
      } finally {
        setTimeout(() => setIsActionInProgress(false), 100);
      }
    },
    [newsletterActions, preserveFilterParams, filter, log]
  );
 
  const handleToggleQueueWrapper = useCallback(
    async (newsletter: NewsletterWithRelations, isInQueue: boolean) => {
      setIsActionInProgress(true);
 
      try {
        await newsletterActions.handleToggleInQueue(newsletter, isInQueue);
        preserveFilterParams();
      } catch (error) {
        log.error(
          'Failed to toggle queue status',
          {
            action: 'toggle_queue',
            metadata: { newsletterId: newsletter.id, filter },
          },
          error instanceof Error ? error : new Error(String(error))
        );
        throw error;
      } finally {
        setTimeout(() => setIsActionInProgress(false), 100);
      }
    },
    [newsletterActions, preserveFilterParams, filter, log]
  );
 
  const handleUpdateTagsWrapper = useCallback(
    async (newsletterId: string, tagIds: string[]) => {
      try {
        setTagUpdateError(null);
        await newsletterActions.handleUpdateTags(newsletterId, tagIds);
      } catch (error) {
        const errorMessage = error instanceof Error ? error.message : 'Failed to update tags';
        setTagUpdateError(errorMessage);
        throw error;
      }
    },
    [newsletterActions]
  );
 
  // Cache warming effects
  const cacheManager = useMemo(() => {
    try {
      return getCacheManager();
    } catch {
      return null;
    }
  }, []);
 
  useEffect(() => {
    if (cacheManager && user?.id) {
      cacheManager.warmCache(user.id, 'high');
    }
  }, [cacheManager, user?.id]);
 
  // Initialize group filters from URL on mount
  // IMPORTANT: This useEffect MUST have empty dependencies [] to prevent infinite loops.
  // DO NOT add setGroupFilters or setSourceFilter to the dependencies array.
 
  useEffect(() => {
    const params = new URLSearchParams((window as typeof globalThis).location.search);
    const groupsParam = params.get('groups');
    if (groupsParam) {
      const ids = groupsParam
        .split(',')
        .map((s) => s.trim())
        .filter(Boolean);
      if (ids.length > 0) {
        setGroupFilters(ids);
        setSourceFilter(null);
      }
    }
  }, []); // Intentionally empty - run only once on mount to prevent infinite loops
 
  // Validate that this useEffect has empty dependencies to prevent infinite loops
  dependencyValidator.validate('groupFilterInitialization', []);
 
  // Create sources with counts for the filter dropdown
  const sourcesWithCounts = useMemo(() => {
    return newsletterSources.map(
      (source: NewsletterSource): NewsletterSourceWithCount => ({
        ...source,
        count: source.newsletter_count || 0,
      })
    );
  }, [newsletterSources]);
 
  // Loading state
  if (isLoadingNewsletters && newsletters.length === 0) {
    return <LoadingScreen />;
  }
 
  // Error state
  if (errorNewsletters) {
    return <ErrorState error={errorNewsletters} onRetry={refetchNewsletters} />;
  }
 
  const showArchived = filter === 'archived';
 
  return (
    <div className="px-0 sm:px-6 py-6">
      {/* Header */}
      <div className="flex flex-col space-y-4 mb-6">
        <div className="flex flex-col w-full">
          <div className="flex justify-between items-center w-full">
            <h1 className="text-3xl font-bold text-neutral-800 dark:text-slate-100">Inbox</h1>
          </div>
          {/* Filters below title */}
          <div className="mt-2 w-full">
            <InboxFilters
              filter={filter}
              sourceFilter={sourceFilter}
              groupFilters={groupFilters}
              timeRange={timeRange}
              sortBy={sortBy}
              sortOrder={sortOrder}
              newsletterSources={sourcesWithCounts}
              newsletterGroups={groupsForDropdown}
              onFilterChange={handleFilterChange}
              onSourceFilterChange={handleSourceFilterChange}
              onGroupFiltersChange={handleGroupFiltersChange}
              onTimeRangeChange={handleTimeRangeChange}
              onSortByChange={setSortBy}
              onSortOrderChange={setSortOrder}
              isLoadingSources={isLoadingSources}
              isLoadingGroups={isLoadingGroups}
              showFilterCounts={true}
              onSelectClick={() => setIsSelecting(true)}
            />
          </div>
        </div>
      </div>
 
      {/* Bulk Selection Actions */}
      {isSelecting && (
        <div className="mt-2">
          <BulkSelectionActions
            selectedCount={selectedIds.size}
            totalCount={newsletters.length}
            showArchived={showArchived}
            isBulkActionLoading={bulkLoadingStates.isBulkActionInProgress}
            onSelectAll={toggleSelectAll}
            onSelectRead={selectRead}
            onSelectUnread={selectUnread}
            onMarkAsRead={handleBulkMarkAsRead}
            onMarkAsUnread={handleBulkMarkAsUnread}
            onArchive={handleBulkArchive}
            onUnarchive={handleBulkUnarchive}
            onDelete={handleBulkDelete}
            onCancel={clearSelection}
          />
        </div>
      )}
 
      {/* Selected Tags Display */}
      <SelectedTagsDisplay
        selectedTags={selectedTags}
        onRemoveTag={removeTag}
        onClearAll={resetFilters}
      />
 
      {/* Selected Groups Display */}
      <SelectedFiltersDisplay
        selectedGroups={groupFilters}
        groups={groupsForDropdown}
        onClearGroup={(gid) => {
          const newGroups = groupFilters.filter((id) => id !== gid);
          handleGroupFiltersChange(newGroups);
        }}
        onClearAll={() => handleGroupFiltersChange([])}
      />
 
      {/* Newsletter List with Infinite Scroll */}
      <div
        className={`${selectedTags.length > 0 ? 'pt-2' : 'pt-6'} pb-6 overflow-auto sm:px-6 px-0`}
      >
        {isLoadingNewsletters && rawNewsletters.length === 0 ? (
          <div className="flex flex-col items-center justify-center py-16 text-neutral-500">
            <div className="animate-spin rounded-full h-12 w-12 border-t-2 border-b-2 border-blue-500 mb-4"></div>
            <p className="text-base text-neutral-400">Loading newsletters...</p>
          </div>
        ) : newsletters.length === 0 && !isLoadingNewsletters ? (
          <EmptyState filter={filter} sourceFilter={sourceFilter} />
        ) : (
          <InfiniteNewsletterList
            newsletters={newsletters}
            isLoading={isLoadingNewsletters}
            isLoadingMore={isLoadingMore}
            hasNextPage={hasNextPage}
            totalCount={totalCount}
            error={errorNewsletters}
            onLoadMore={fetchNextPage}
            onRetry={refetchNewsletters}
            // Newsletter row props
            selectedIds={selectedIds}
            isSelecting={isSelecting}
            readingQueue={readingQueue}
            visibleTags={visibleTags}
            // Newsletter row actions
            onToggleSelect={async (id: string) => {
              toggleSelect(id);
            }}
            onToggleLike={handleToggleLikeWrapper}
            onToggleArchive={async (id: string) => {
              const newsletter = newsletters.find((n) => n.id === id);
              if (newsletter) await handleToggleArchiveWrapper(newsletter);
            }}
            onToggleRead={async (id: string) => {
              const newsletter = newsletters.find((n) => n.id === id);
              if (newsletter) await handleToggleReadWrapper(newsletter);
            }}
            onTrash={async (id: string) => {
              await handleDeleteNewsletterWrapper(id);
            }}
            onToggleQueue={async (newsletterId: string) => {
              const newsletter = newsletters.find((n) => n.id === newsletterId);
              const isInQueue = readingQueue.some((item) => item.newsletter_id === newsletterId);
              if (newsletter) await handleToggleQueueWrapper(newsletter, isInQueue);
            }}
            onUpdateTags={handleUpdateTagsWrapper}
            onToggleTagVisibility={toggleTagVisibility}
            onTagClick={async (tag: Tag, _e: React.MouseEvent) => handleTagClick(tag.id)}
            onRemoveFromQueue={async (_e: React.MouseEvent, newsletterId: string) =>
              await handleRemoveFromQueue(_e, newsletterId)
            }
            onNewsletterClick={handleNewsletterClick}
            onMouseEnter={handleNewsletterMouseEnter}
            // Loading states
            isDeletingNewsletter={(id: string) =>
              newsletterActions.isNewsletterLoading('deleteNewsletter', id)
            }
            isUpdatingTags={(id: string) => newsletterActions.isNewsletterLoading('updateTags', id)}
            loadingStates={{}}
            // Error states
            errorTogglingLike={null}
            tagUpdateError={tagUpdateError}
            onDismissTagError={handleDismissTagError}
            // Display options
            showTags={true}
            showCheckbox={isSelecting}
            activeGroupIds={groupFilters}
            allGroups={newsletterGroups.map((g) => ({ ...g, color: g.color || '#3B82F6' }))}
          />
        )}
      </div>
      {/* ScrollToTop is now mounted globally in Layout */}
    </div>
  );
};
 
Inbox.displayName = 'Inbox';
 
export default Inbox;