All files / src/web/pages NewsletterDetail.tsx

74.6% Statements 470/630
75.65% Branches 87/115
23.8% Functions 5/21
74.6% Lines 470/630

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 8291x 1x 1x 1x 1x 1x 1x 1x   1x 1x 1x 1x 1x 1x 1x 1x 1x 1x     38x 38x 38x 38x   38x 24x 24x 24x 24x 24x   24x                                                             24x 38x   38x 24x 24x 24x   24x 24x           24x   24x 24x   24x               24x   24x   24x 24x 24x   24x 24x 24x   24x 24x 48x 48x 24x 24x 24x 38x   38x 38x   1x 68x 68x 68x 68x 68x 68x     68x 30x 30x 26x 25x 25x   68x   68x     68x 68x 68x   68x 68x 68x   68x 68x 68x   68x 68x 68x   68x 68x 68x   68x 68x 68x   68x 68x   68x     68x 68x       68x 68x   68x 68x       68x 68x   68x 68x       68x 68x   68x 68x       68x 68x   68x 68x       68x 68x     68x 68x           68x 68x     68x 68x     68x 68x     68x 68x 3x 3x 3x 3x     3x 68x 68x   68x 68x 68x 68x 68x 68x 68x 68x 68x 68x 68x 68x 68x 68x       68x 68x   68x     68x 68x 68x 68x 68x 68x 68x 68x 68x 68x 68x 68x 68x 68x     68x   30x 2x 2x   30x 2x 2x 26x 68x   68x 68x     68x   68x     68x 30x 30x 30x 68x     68x 30x 24x 24x 68x     68x 30x 20x         20x 68x     68x     68x     68x   44x 11x 11x     44x 7x 7x   26x   26x         26x 26x   26x 26x 26x 26x 26x 26x 26x 26x 26x 26x                     26x   26x 26x 26x   26x 68x     68x   44x 40x 40x     40x         4x   4x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x                       2x     4x 4x 68x     68x 30x 30x 30x 68x     68x 68x 67x 67x 67x 67x 67x 67x 67x 67x 68x 68x 68x 68x 68x 68x 68x 68x 68x 68x   68x   68x   30x     30x     30x       30x 68x       68x 68x     68x 68x 68x 68x 68x 68x 68x 68x   68x 1x 1x   68x 5x 5x 5x 5x 5x 5x 5x   5x   68x         61x 61x 61x   61x   61x   61x 61x 61x 61x 61x 61x   61x 68x   68x 68x 68x 68x 68x 8x   68x 68x 68x 68x 68x 68x 68x 68x   68x   68x 68x 68x 68x 68x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x                   3x 68x                                     68x 68x     68x 68x 61x 61x 61x 61x 61x 61x   68x 68x 68x     68x 61x 61x 61x 61x 61x 61x 61x 61x 61x       68x 68x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x   14x   68x 61x   68x     68x 68x 68x   68x 68x     68x 61x 61x 61x 61x 61x 61x 61x 61x 61x   68x   68x 68x 68x 68x 68x 68x 68x 68x 68x 68x 244x 244x 244x 244x   244x 244x 244x 68x 68x 68x 68x 68x 68x   68x   68x     68x 68x 68x 68x 68x 68x 68x 68x 68x 68x 38x 38x 38x 38x 68x 68x 68x 68x         68x   68x   38x 68x   68x 24x               68x   68x           68x                                             68x 68x 68x 68x 68x 68x 68x 68x 68x   68x 68x                                                                                     68x     68x     68x   68x   1x  
import LoadingScreen from '@common/components/common/LoadingScreen';
import { useAuth } from '@common/contexts/AuthContext';
import { useNewsletterDetail } from '@common/hooks/useNewsletterDetail';
import { useNewsletterSourceGroups } from '@common/hooks/useNewsletterSourceGroups';
import { useSharedNewsletterActions } from '@common/hooks/useSharedNewsletterActions';
import { useSimpleNewsletterNavigation } from '@common/hooks/useSimpleNewsletterNavigation';
import { useTags } from '@common/hooks/useTags';
import { newsletterService } from '@common/services';
import type { NewsletterSourceGroup, NewsletterWithRelations, Tag } from '@common/types';
import { useLogger } from '@common/utils/logger/useLogger';
import { useMutation } from '@tanstack/react-query';
import BackButton from '@web/components/BackButton';
import TagSelector from '@web/components/TagSelector';
import { formatReadTime } from '@common/utils/newsletterUtils';
import { parseFilterUrlParams, urlParamsToNewsletterFilter } from '@web/utils/filterUrlUtils';
import { memo, useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { useLocation, useNavigate, useParams, useSearchParams } from 'react-router-dom';
import NavigationArrows from '../../components/NewsletterDetail/NavigationArrows';
import NewsletterDetailActions from '../../components/NewsletterDetail/NewsletterDetailActions';
 
// Lightweight Shadow DOM renderer to isolate newsletter HTML styles from app theme/layout
function ShadowHtml({ html }: { html: string }) {
  const hostRef = useRef<HTMLDivElement | null>(null);
  const shadowRef = useRef<ShadowRoot | null>(null);
  const darkStyleRef = useRef<HTMLStyleElement | null>(null);
 
  const setTheme = useCallback((mode: 'light' | 'dark') => {
    if (!shadowRef.current) return;
    if (!darkStyleRef.current) {
      darkStyleRef.current = document.createElement('style');
      shadowRef.current.appendChild(darkStyleRef.current);
    }
    // Base light styles are handled by the first style tag. Here we set overrides for dark.
    darkStyleRef.current.textContent = mode === 'dark' ? `
      .nh-content { color: #f1f5f9; background: transparent; }
      /* Force-override common inline white backgrounds from email HTML */
      .nh-content, .nh-content * { background-color: transparent !important; }
      .nh-content h1, .nh-content h2, .nh-content h3, .nh-content h4, .nh-content h5, .nh-content h6 { color: #ffffff !important; font-weight: 600 !important; }
      /* Many newsletters ship inline color:#000000; force readable text in dark mode. */
      .nh-content p,
      .nh-content li,
      .nh-content span,
      .nh-content div,
      .nh-content td,
      .nh-content th,
      .nh-content tr,
      .nh-content ul,
      .nh-content ol {
        color: #f1f5f9 !important;
      }
      .nh-content a { color: #3b82f6 !important; text-decoration: underline !important; font-weight: 500 !important; }
      .nh-content a:hover { color: #60a5fa !important; }
      .nh-content strong { color: #ffffff !important; font-weight: 700 !important; }
      .nh-content b { color: #ffffff !important; font-weight: 700 !important; }
      .nh-content blockquote { color: #e2e8f0; border-left: 4px solid #475569; background: rgba(51,65,85,0.4); }
      /* Re-apply explicit dark backgrounds for code/pre after global transparent override */
      .nh-content code { background: rgba(100,116,139,0.5); color: #ffffff; padding: 0.1rem 0.3rem; border-radius: 0.25rem; }
      .nh-content pre { background: rgba(30,41,59,0.9); color: #f8fafc; padding: 0.75rem; border-radius: 0.5rem; overflow: auto; }
      .nh-content table { color: #f1f5f9; }
      .nh-content th { background: rgba(30,41,59,0.9); color: #ffffff; font-weight: 600; }
      .nh-content td, .nh-content th { border-color: #475569; }
      .nh-content hr { border-color: #475569; }
      .nh-content img { background: transparent; }
      .nh-content em, .nh-content i { color: #e2e8f0; }
    ` : '';
  }, []);
 
  useEffect(() => {
    if (!hostRef.current) return;
    if (!shadowRef.current) {
      shadowRef.current = hostRef.current.attachShadow({ mode: 'open' });
      // Base styles to keep host transparent and inherit fonts/colors
      const style = document.createElement('style');
      style.textContent = `
        :host { all: initial; contain: content; }
        .nh-content { font-family: inherit; color: inherit; line-height: 1.6; background: transparent; }
        .nh-content img { max-width: 100%; height: auto; }
        .nh-content a { color: #2563EB; text-decoration: underline; }
      `;
      shadowRef.current.appendChild(style);
      // Initialize theme based on current document state
      const isDark = document.documentElement.classList.contains('dark');
      setTheme(isDark ? 'dark' : 'light');
      // Listen for theme changes
      const handler = (e: Event) => {
        try {
          const detail = (e as CustomEvent).detail as { mode?: 'light' | 'dark' };
          if (detail && detail.mode) setTheme(detail.mode);
        } catch {
          // no-op
        }
      };
      window.addEventListener('nh-theme-change', handler as EventListener);
      // Cleanup on unmount
      hostRef.current.addEventListener('DOMNodeRemovedFromDocument', () => {
        window.removeEventListener('nh-theme-change', handler as EventListener);
      });
    }
    if (shadowRef.current) {
      // Wrap html inside a container to apply base styles
      const wrapper = document.createElement('div');
      wrapper.className = 'nh-content';
      wrapper.innerHTML = html;
      // Clear previous content except the first two style elements (base + dark)
      const nodes = Array.from(shadowRef.current.childNodes);
      nodes.forEach((n, idx) => {
        if (idx <= 1 && n.nodeName.toLowerCase() === 'style') return;
        shadowRef.current?.removeChild(n);
      });
      shadowRef.current.appendChild(wrapper);
    }
  }, [html, setTheme]);
 
  return <div ref={hostRef} />;
}
 
const NewsletterDetail = memo(() => {
  const [tagSelectorKey, setTagSelectorKey] = useState(0);
  const { id } = useParams<{ id: string }>();
  const log = useLogger();
  const location = useLocation();
  const [searchParams] = useSearchParams();
  const navigate = useNavigate();
 
  // Check if we came from the reading queue using multiple indicators
  const isFromReadingQueue = useMemo(() => {
    return (
      location.state?.fromReadingQueue === true ||
      location.state?.from === '/reading-queue' ||
      (typeof location.state?.from === 'string' && location.state.from.includes('reading-queue')) ||
      (typeof document.referrer === 'string' && document.referrer.includes('reading-queue'))
    );
  }, [location.state]);
 
  useTags();
 
  // Create mutations directly using useMutation
  const markAsReadMutation = useMutation({
    mutationFn: (id: string) => newsletterService.markAsRead(id),
  });
 
  const markAsUnreadMutation = useMutation({
    mutationFn: (id: string) => newsletterService.markAsUnread(id),
  });
 
  const toggleLikeMutation = useMutation({
    mutationFn: (id: string) => newsletterService.toggleLike(id),
  });
 
  const toggleArchiveMutation = useMutation({
    mutationFn: (id: string) => newsletterService.toggleArchive(id),
  });
 
  const deleteNewsletterMutation = useMutation({
    mutationFn: (id: string) => newsletterService.deleteNewsletter(id),
  });
 
  const addToQueueMutation = useMutation({
    mutationFn: (id: string) => newsletterService.addToReadingQueue(id),
  });
 
  const updateTagsMutation = useMutation({
    mutationFn: ({ id, tagIds }: { id: string; tagIds: string[] }) =>
      newsletterService.updateTags(id, tagIds),
  });
 
  // Create wrapper functions to convert NewsletterOperationResult to boolean
  const markAsRead = useCallback(
    async (id: string) => {
      const result = await markAsReadMutation.mutateAsync(id);
      return result.success;
    },
    [markAsReadMutation]
  );
 
  const markAsUnread = useCallback(
    async (id: string) => {
      const result = await markAsUnreadMutation.mutateAsync(id);
      return result.success;
    },
    [markAsUnreadMutation]
  );
 
  const toggleLike = useCallback(
    async (id: string) => {
      const result = await toggleLikeMutation.mutateAsync(id);
      return result.success;
    },
    [toggleLikeMutation]
  );
 
  const toggleArchive = useCallback(
    async (id: string) => {
      const result = await toggleArchiveMutation.mutateAsync(id);
      return result.success;
    },
    [toggleArchiveMutation]
  );
 
  const deleteNewsletter = useCallback(
    async (id: string) => {
      const result = await deleteNewsletterMutation.mutateAsync(id);
      return result.success;
    },
    [deleteNewsletterMutation]
  );
 
  // Create a toggleInQueue function that combines addToQueue and removeFromQueue
  const toggleInQueue = useCallback(
    async (id: string) => {
      // This is a simplified version - in practice you'd need to check if the newsletter is in queue
      // For now, we'll just use addToQueue as a fallback
      const result = await addToQueueMutation.mutateAsync(id);
      return result.success;
    },
    [addToQueueMutation]
  );
 
  // Create a wrapper for updateNewsletterTags to match the expected signature for useSharedNewsletterActions
  const updateNewsletterTagsForActions = useCallback(
    async (id: string, tagIds: string[]) => {
      await updateTagsMutation.mutateAsync({ id, tagIds });
    },
    [updateTagsMutation]
  );
 
  // Create a wrapper for updateNewsletterTags that returns boolean for TagSelector
  const updateNewsletterTagsForSelector = useCallback(
    async (id: string, tagIds: string[]) => {
      try {
        await updateTagsMutation.mutateAsync({ id, tagIds });
        return true;
      } catch (_error) {
        return false;
      }
    },
    [updateTagsMutation]
  );
 
  const { handleMarkAsRead, handleToggleArchive } = useSharedNewsletterActions(
    {
      markAsRead,
      markAsUnread,
      toggleLike,
      toggleArchive,
      deleteNewsletter,
      toggleInQueue,
      updateNewsletterTags: updateNewsletterTagsForActions,
    },
    {
      showToasts: false,
      optimisticUpdates: false,
      onSuccess: () => {
        // Don't refetch here - let React Query handle cache updates
        // This prevents cascading refetches
      },
    }
  );
 
  const { user } = useAuth();
 
  // Use the optimized newsletter detail hook
  const {
    newsletter,
    isLoading: loading,
    isError,
    error: fetchError,
    refetch,
    prefetchRelated,
  } = useNewsletterDetail(id || '', {
    enabled: !!id && !!user?.id,
    staleTime: 5 * 60 * 1000, // 5 minutes
    refetchOnWindowFocus: false,
    prefetchTags: true,
    prefetchSource: true,
  });
 
  // Get source ID from location state or newsletter data
  const sourceId = useMemo(() => {
    // First try to get from location state (most reliable)
    if (location.state?.sourceId) {
      return location.state.sourceId;
    }
    // Fallback to newsletter source ID if coming from newsletter sources
    if (isFromReadingQueue && newsletter?.source?.id) {
      return newsletter.source.id;
    }
    return undefined;
  }, [location.state?.sourceId, isFromReadingQueue, newsletter?.source?.id]);
 
  const [hasAutoMarkedAsRead, setHasAutoMarkedAsRead] = useState(false);
  const [hasAutoArchived, setHasAutoArchived] = useState(false);
 
  // Track mount status for cleanup
  const isMounted = useRef(true);
  // Track if mark as read is in progress to prevent duplicates
  const markAsReadInProgress = useRef(false);
 
  // Cleanup on unmount
  useEffect(() => {
    return () => {
      isMounted.current = false;
    };
  }, []);
 
  // Prefetch related data when newsletter loads
  useEffect(() => {
    if (newsletter && !loading) {
      prefetchRelated();
    }
  }, [newsletter, loading, prefetchRelated]);
 
  // Memoize the transformed tags to prevent unnecessary re-renders
  const tagsForUI = useMemo((): Tag[] => {
    if (!newsletter?.tags) return [];
    return (newsletter.tags as unknown[]).map((t: unknown) => {
      if (typeof t === 'object' && t !== null && 'name' in t && 'color' in t) return t as Tag;
      if (typeof t === 'object' && t !== null && 'tag' in t && (t as { tag: Tag }).tag)
        return (t as { tag: Tag }).tag as Tag;
      return t as Tag;
    });
  }, [newsletter?.tags]);
 
  // Handle newsletter updates from the actions component
  const handleNewsletterUpdate = useCallback((_updatedNewsletter: NewsletterWithRelations) => {
    // Don't refetch here - React Query will update from cache
    // This prevents infinite loops of refetching
  }, []);
 
  // Auto-mark newsletter as read when it loads (instantaneous)
  useEffect(() => {
    // Only run when we have a new newsletter that hasn't been marked as read
    if (!newsletter || newsletter.is_read || loading || fetchError) {
      return;
    }
 
    // Only run once per newsletter ID
    if (hasAutoMarkedAsRead) {
      return;
    }
 
    const markAsRead = async () => {
      // Check if already in progress
      if (markAsReadInProgress.current) {
        return;
      }
 
      // Set both flags before making the call to prevent duplicate calls
      setHasAutoMarkedAsRead(true);
      markAsReadInProgress.current = true;
 
      try {
        await handleMarkAsRead(newsletter.id);
        log.debug('Auto-marked newsletter as read on detail view', {
          action: 'auto_mark_read_detail',
          metadata: {
            newsletterId: newsletter.id,
            title: newsletter.title,
          },
        });
      } catch (error) {
        // Reset flag on error so it can be retried
        setHasAutoMarkedAsRead(false);
        log.error(
          'Failed to auto-mark newsletter as read in detail view',
          {
            action: 'auto_mark_read_detail_error',
            metadata: { newsletterId: newsletter.id },
          },
          error instanceof Error ? error : new Error(String(error))
        );
      } finally {
        // Always reset the in-progress flag
        markAsReadInProgress.current = false;
      }
    };
 
    markAsRead();
  }, [newsletter, loading, fetchError, hasAutoMarkedAsRead, handleMarkAsRead, log]);
 
  // Auto-archive newsletter after it's been read and viewed for a short time
  useEffect(() => {
    // Skip if conditions aren't met
    if (!newsletter || !newsletter.is_read || newsletter.is_archived || loading || fetchError) {
      return;
    }
 
    // Skip if already processed
    if (hasAutoArchived) {
      return;
    }
 
    // Set flag immediately to prevent multiple timers
    setHasAutoArchived(true);
 
    const archiveNewsletter = async () => {
      try {
        await handleToggleArchive(newsletter); // newsletter is from outer scope
        log.debug('Auto-archived newsletter after reading', {
          action: 'auto_archive_detail',
          metadata: {
            newsletterId: newsletter.id, // newsletter is from outer scope
            title: newsletter.title, // newsletter is from outer scope
          },
        });
      } catch (error) {
        // Reset flag on error so it can be retried
        setHasAutoArchived(false);
        log.error(
          'Failed to auto-archive newsletter in detail view',
          {
            action: 'auto_archive_detail_error',
            metadata: { newsletterId: newsletter.id }, // newsletter is from outer scope
          },
          error instanceof Error ? error : new Error(String(error))
        );
      }
    };
 
    // Archive after 3 seconds of viewing a read newsletter
    const timeoutId = setTimeout(archiveNewsletter, 3000);
    return () => clearTimeout(timeoutId);
  }, [newsletter, loading, fetchError, hasAutoArchived, handleToggleArchive, log]);
 
  // Reset auto-mark and auto-archive state when newsletter ID changes
  useEffect(() => {
    setHasAutoMarkedAsRead(false);
    setHasAutoArchived(false);
    markAsReadInProgress.current = false;
  }, [id]);
 
  // Memoize mutations object to prevent unnecessary re-renders and infinite loops
  const mutations = useMemo(
    () => ({
      markAsRead,
      markAsUnread,
      toggleLike,
      toggleArchive,
      deleteNewsletter,
      toggleInQueue,
      updateNewsletterTags: updateNewsletterTagsForActions,
    }),
    [
      markAsRead,
      markAsUnread,
      toggleLike,
      toggleArchive,
      deleteNewsletter,
      toggleInQueue,
      updateNewsletterTagsForActions,
    ]
  );
 
  const { groups = [] } = useNewsletterSourceGroups();
  // Get navigation filter from location state or URL params
  const navigationFilter = useMemo(() => {
    // Parse URL parameters using centralized utility
    const urlParams = parseFilterUrlParams(searchParams);
 
    // Convert to newsletter filter format
    const filter = urlParamsToNewsletterFilter(urlParams);
 
    // Also check location state for backward compatibility
    if (location.state?.tagIds?.length > 0 && !filter.tagIds) {
      filter.tagIds = location.state.tagIds;
    }
 
    return filter;
  }, [searchParams, location.state]);
 
  // Freeze the original filter state when component mounts (before auto-archive)
  // Use a ref to avoid re-initializing with changing memoized value
  const navigationFilterRef = useRef(navigationFilter);
  const [originalNavigationFilter] = useState(navigationFilterRef.current);
 
  // Setup navigation
  const navigation = useSimpleNewsletterNavigation(id || '', {
    isReadingQueue: isFromReadingQueue,
    filter: {
      ...originalNavigationFilter, // Keep frozen filter for core state
      groupIds: navigationFilter.groupIds, // But respect current group filtering
    },
    sourceId: sourceId,
  });
 
  if (loading) {
    return <LoadingScreen />;
  }
 
  if (isError) {
    return (
      <div key={`error-${id}`} className="max-w-6xl w-full mx-auto px-4 py-8">
        <BackButton className="mb-4" />
        <div className="bg-red-100 text-red-700 px-4 py-3 rounded-md mb-6">
          {fetchError?.message || 'Failed to load newsletter. Please try again.'}
        </div>
      </div>
    );
  }
 
  if (!newsletter) {
    return <LoadingScreen />;
  }
 
  // Add key to force remount when ID changes
  return (
    <div data-testid="newsletter-detail">
      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
        {/* Back Button */}
        <BackButton className="mb-4" />
 
        <div className="flex flex-col lg:flex-row gap-8">
          {/* Main content */}
          <div className="flex-1">
            <div className="bg-white dark:bg-neutral-900 rounded-xl shadow-sm p-6 mb-6 border border-slate-200/60 dark:border-neutral-800">
              <div className="mb-6">
                <h1
                  data-testid="newsletter-detail-title"
                  className="text-2xl font-bold text-gray-900 dark:text-slate-100 mb-4"
                >
                  {newsletter?.title}
                </h1>
                {/* Newsletter Source and Group */}
                <div className="mb-2">
                  <div data-testid="newsletter-source" className="text-sm text-gray-600 dark:text-slate-400">
                    <span className="font-medium">Source:</span>{' '}
                    {newsletter?.source?.name || 'Unknown'}
                    {newsletter?.source?.from && (
                      <span className="ml-2 text-gray-400 dark:text-slate-500">({newsletter.source.from})</span>
                    )}
                  </div>
                  <div data-testid="newsletter-source-group" className="text-sm text-gray-600 dark:text-slate-400 mt-1">
                    <span className="font-medium">Source Groups:</span>{' '}
                    <SourceGroupDropdown newsletter={newsletter} groups={groups} onGroupChange={refetch} />
                    <span className="ml-2 text-xs text-gray-400 dark:text-slate-500">(up to 10)</span>
                  </div>
                </div>
              </div>
              {/* Tags and Action Buttons Row */}
              <div className="flex items-center justify-between mb-4">
                {/* Tags Section */}
                <div className="flex-1">
                  <TagSelector
                    key={tagSelectorKey}
                    selectedTags={tagsForUI}
                    onTagsChange={async (newTags: Tag[]) => {
                      if (!id) return;
                      try {
                        const ok = await updateNewsletterTagsForSelector(
                          id,
                          newTags.map((t) => t.id)
                        );
                        if (ok) {
                          await refetch();
                          setTagSelectorKey((k) => k + 1);
                        }
                      } catch (error) {
                        log.error(
                          'Failed to update tags',
                          {
                            action: 'update_tags',
                            metadata: { newsletterId: id },
                          },
                          error instanceof Error ? error : new Error(String(error))
                        );
                      }
                    }}
                    onTagDeleted={async () => {
                      if (!id) return;
                      try {
                        const ok = await updateNewsletterTagsForSelector(id, []);
                        if (ok) {
                          await refetch();
                          setTagSelectorKey((k) => k + 1);
                        }
                      } catch (error) {
                        log.error(
                          'Failed to delete tag',
                          {
                            action: 'delete_tag',
                            metadata: { newsletterId: id },
                          },
                          error instanceof Error ? error : new Error(String(error))
                        );
                      }
                    }}
                  />
                </div>
 
                {/* Action Buttons */}
                <div className="ml-4">
                  {newsletter && (
                    <NewsletterDetailActions
                      newsletter={newsletter}
                      onNewsletterUpdate={handleNewsletterUpdate}
                      isFromReadingQueue={isFromReadingQueue}
                      mutations={mutations}
                    />
                  )}
                </div>
              </div>
            </div>
 
            {/* Top Navigation Arrows */}
            {newsletter && (
              <div className="mb-4">
                <NavigationArrows
                  onPrevious={navigation.navigateToPrevious}
                  onNext={navigation.navigateToNext}
                  hasPrevious={navigation.hasPrevious}
                  hasNext={navigation.hasNext}
                  isLoading={navigation.isLoading}
                />
              </div>
            )}
 
            {/* Newsletter Content */}
            <div className="mb-6 rounded-xl p-4 bg-white dark:bg-neutral-950 border border-slate-200/60 dark:border-neutral-900">
              {newsletter?.received_at && (
                <div className="text-sm text-gray-500 dark:text-slate-400 mb-6">
                  <div>
                    {new Date(newsletter.received_at).toLocaleDateString('en-US', {
                      year: 'numeric',
                      month: 'long',
                      day: 'numeric',
                      hour: '2-digit',
                      minute: '2-digit',
                    })}
                  </div>
                  {(newsletter.word_count > 0 || newsletter.estimated_read_time > 0) && (
                    <div className="mt-1 text-gray-400 dark:text-slate-500">
                      {formatReadTime(newsletter.estimated_read_time, newsletter.word_count)} read •{' '}
                      {newsletter.word_count.toLocaleString()} words
                    </div>
                  )}
                </div>
              )}
              {newsletter?.content && (
                <ShadowHtml html={newsletter.content} />
              )}
            </div>
 
            {/* Context & Insights - Moved below newsletter content */}
            <div className="bg-white dark:bg-neutral-900 rounded-xl shadow-sm p-6 mb-6 border border-slate-200/60 dark:border-neutral-800">
              <h3 className="font-medium text-gray-900 dark:text-slate-100 mb-4">Context & Insights</h3>
              <div className="text-sm text-gray-600 dark:text-slate-400">
                {/* Intentionally left empty as per requirements */}
              </div>
            </div>
 
            {/* Bottom Navigation Arrows */}
            {newsletter && (
              <div className="mt-6">
                <NavigationArrows
                  onPrevious={navigation.navigateToPrevious}
                  onNext={navigation.navigateToNext}
                  hasPrevious={navigation.hasPrevious}
                  hasNext={navigation.hasNext}
                  isLoading={navigation.isLoading}
                />
              </div>
            )}
          </div>
          {/* Sidebar */}
          <div className="lg:w-80 flex-shrink-0">
            <div className="bg-white dark:bg-neutral-900 rounded-xl shadow-sm p-6 border border-slate-200/60 dark:border-neutral-800">
              <h3 className="font-medium text-gray-900 dark:text-slate-100 mb-4">Related Topics</h3>
              <div className="flex flex-wrap gap-2">
                {[
                  { id: '1', name: 'Tech News', count: 5 },
                  { id: '2', name: 'AI', count: 8 },
                  { id: '3', name: 'Product', count: 3 },
                  { id: '4', name: 'Industry', count: 6 },
                ].map((topic) => (
                  <button
                    key={topic.id}
                    onClick={() => navigate(`/inbox?topic=${topic.name.toLowerCase()}`)}
                    className="px-3 py-1.5 text-sm bg-gray-100 dark:bg-neutral-800 hover:bg-gray-200 dark:hover:bg-neutral-700 text-gray-700 dark:text-slate-200 rounded-full flex items-center gap-1.5"
                  >
                    <span>{topic.name}</span>
                    <span className="text-xs text-gray-500 dark:text-slate-400">{topic.count}</span>
                  </button>
                ))}
              </div>
            </div>
          </div>
        </div>
      </div>
      {/* ScrollToTop is now mounted globally in Layout */}
    </div>
  );
});
 
// Inline Source Group Dropdown component
function SourceGroupDropdown({ newsletter, groups, onGroupChange }: { newsletter: NewsletterWithRelations, groups: NewsletterSourceGroup[], onGroupChange?: () => void }) {
  const [showDropdown, setShowDropdown] = useState(false);
  const [groupLoading] = useState(false);
  const [groupError, setGroupError] = useState<string | null>(null);
  const [groupUpdating, setGroupUpdating] = useState(false);
  const [selectedGroupIds, setSelectedGroupIds] = useState<string[]>([]);
  const dropdownRef = useRef<HTMLDivElement>(null);
  const { addSourcesToGroup, removeSourcesFromGroup } = useNewsletterSourceGroups();
  const sourceId = newsletter.source?.id;
  const currentGroupIds: string[] = useMemo(() => {
    if (!sourceId) return [];
    return groups
      .filter((g) => Array.isArray(g.sources) && g.sources.some((s: { id: string }) => s.id === sourceId))
      .map((g) => g.id);
  }, [groups, sourceId]);
  const currentGroupNames = useMemo(() => {
    const idsToDisplay = showDropdown ? currentGroupIds : (selectedGroupIds.length ? selectedGroupIds : currentGroupIds);
    if (!idsToDisplay.length) return 'None';
    const names = groups
      .filter((g) => idsToDisplay.includes(g.id))
      .map((g) => g.name);
    return names.join(', ');
  }, [groups, currentGroupIds, selectedGroupIds, showDropdown]);
 
  useEffect(() => {
    // Sync local selection when the computed current groups change or dropdown opens
    setSelectedGroupIds(currentGroupIds);
  }, [currentGroupIds]);
 
  useEffect(() => {
    if (!showDropdown) return;
    function handleClickOutside(event: MouseEvent) {
      if (dropdownRef.current && !dropdownRef.current.contains(event.target as Node)) {
        setShowDropdown(false);
      }
    }
    document.addEventListener('mousedown', handleClickOutside);
    return () => document.removeEventListener('mousedown', handleClickOutside);
  }, [showDropdown]);
 
  const toggleSelection = (groupId: string) => {
    setSelectedGroupIds((prev) =>
      prev.includes(groupId) ? prev.filter((id) => id !== groupId) : [...prev, groupId]
    );
  };
 
  const handleSave = async () => {
    if (!sourceId) return;
    setGroupUpdating(true);
    setGroupError(null);
    try {
      const toAdd = selectedGroupIds.filter((id) => !currentGroupIds.includes(id));
      const toRemove = currentGroupIds.filter((id) => !selectedGroupIds.includes(id));
 
      // Perform additions and removals
      await Promise.all([
        ...toAdd.map((gid) => addSourcesToGroup.mutateAsync({ groupId: gid, sourceIds: [sourceId] })),
        ...toRemove.map((gid) => removeSourcesFromGroup.mutateAsync({ groupId: gid, sourceIds: [sourceId] })),
      ]);
 
      setShowDropdown(false);
      if (onGroupChange) onGroupChange();
    } catch (_err) {
      setGroupError('Failed to update groups');
    } finally {
      setGroupUpdating(false);
    }
  };
 
  return (
    <span ref={dropdownRef} style={{ display: 'inline-block', minWidth: 120 }}>
      {!showDropdown ? (
        <button
          type="button"
          className="font-medium text-blue-700 dark:text-blue-400 hover:underline focus:outline-none px-1 rounded"
          onClick={() => setShowDropdown(true)}
          disabled={groupLoading || groupUpdating || !groups.length}
          aria-label="Edit source group"
        >
          {currentGroupNames}
        </button>
      ) : (
        <div className="border rounded px-3 py-2 bg-white dark:bg-neutral-900 shadow-sm text-sm border-gray-200 dark:border-neutral-700" style={{ minWidth: 220 }}>
          <div className="max-h-48 overflow-auto pr-1">
            {groups.map((group) => (
              <button
                key={group.id}
                type="button"
                className={`w-full flex items-center justify-between py-1 text-left hover:bg-neutral-50 dark:hover:bg-neutral-800 rounded px-1 ${selectedGroupIds.includes(group.id) ? 'text-blue-700 dark:text-blue-400 font-medium' : 'text-gray-700 dark:text-slate-200'}`}
                onClick={() => toggleSelection(group.id)}
                disabled={groupLoading || groupUpdating}
              >
                <span>{group.name}</span>
                <span className={`ml-2 text-xs ${selectedGroupIds.includes(group.id) ? 'opacity-100' : 'opacity-0'}`}>✓</span>
              </button>
            ))}
            {groups.length === 0 && (
              <div className="text-neutral-500 dark:text-slate-400">No groups</div>
            )}
          </div>
          <div className="flex justify-end gap-2 pt-2">
            <button
              type="button"
              className="px-2 py-1 text-neutral-600 dark:text-slate-300 hover:bg-neutral-100 dark:hover:bg-neutral-800 rounded"
              onClick={() => {
                setSelectedGroupIds(currentGroupIds);
                setShowDropdown(false);
              }}
              disabled={groupUpdating}
            >
              Cancel
            </button>
            <button
              type="button"
              className="px-2 py-1 bg-blue-600 text-white rounded disabled:opacity-50 hover:bg-blue-700 dark:hover:bg-blue-800"
              onClick={handleSave}
              disabled={groupUpdating}
            >
              Save
            </button>
          </div>
        </div>
      )}
      {(groupLoading || groupUpdating) && (
        <span className="ml-2 text-xs text-gray-400 dark:text-slate-400">Updating...</span>
      )}
      {groupError && (
        <span className="ml-2 text-xs text-red-500 dark:text-red-400">{groupError}</span>
      )}
    </span>
  );
}
 
export default NewsletterDetail;