All files / src App.tsx

91.79% Statements 347/378
83.79% Branches 331/395
91.26% Functions 94/103
93.54% Lines 319/341

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                                                                              816x 816x     816x   816x 120x   119x 1x       816x 120x 1x 1x   120x 120x       816x 816x 816x 816x     816x   816x 816x 816x 816x 816x 816x 816x 816x 816x 816x             816x 246x         816x     816x 258x         816x 244x           816x 244x         816x 244x             816x 816x 241x   120x 117x 111x 241x 111x 111x 2x 2x   109x                 816x   816x 816x 816x 816x 816x 816x     816x 816x                 816x             816x 240x           816x 816x   123x               816x       816x                 816x     816x 123x         816x 131x         816x 816x 125x     816x 125x     816x 125x                           816x                               816x 155x         816x 154x         816x 121x 1x                 816x   1x 1x 1x 1x 1x 1x 1x                         816x   42x                             33x     816x 816x 122x       816x 816x 238x 117x 117x       117x       816x 365x 1x 1x 1x 1x 1x 1x 1x   365x 365x                       816x   13x 13x 13x   13x   13x           816x 176x 13x     816x 1x 1x 1x       816x 1x 1x 1x         816x           2x 2x 2x 2x 2x 1x 1x           816x 3x 3x 3x   2x   2x 1x           816x   3x 3x 3x 3x   3x 3x 3x 3x 3x 2x 3x     3x 3x   1x                 816x         816x     816x                       816x   3x 3x 3x 3x 3x 3x 3x 3x         816x   3x 3x   2x 2x   2x 2x   2x   2x 2x 2x   1x                 1x   3x 3x 3x         816x         816x   19x     19x             816x 13x     816x   4x         816x   1x         816x   1x         816x                   4x 4x   4x 4x   4x         4x       4x                       3x 3x 3x 3x           816x                             816x     816x 5x 4x 4x 4x       816x 2x 2x 2x 2x       816x 816x           1x 1x       14x 6x 4x 2x   2x 2x 1x 1x         13x     5x 4x       3x 1x       2x 1x       12x 12x     7x 5x       3x 2x       2x 2x       3x 3x       2x 1x       3x 2x                                                   816x       816x 248x 4x       8x 4x 4x 4x 4x 2x 2x 2x         4x   4x 4x 4x         816x 240x             576x 3x   1x             573x 6x   1x             567x 4x                           563x 122x                       441x                               1x                                         2x 2x   4x                                             2x                                                                 1x 1x     6x 6x                                                                             26x                               26x                                                                               2x 2x 1x 1x       1x 1x 1x 1x     1x 1x 1x 1x                                                       1x       1x 1x               1x                
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { api, type ContainerState, type Message, type SearchResult } from "./api";
import { ComposeModal, type ComposeMode } from "./components/ComposeModal";
import { ConfirmDialog } from "./components/ConfirmDialog";
import { DemoBanner } from "./components/DemoBanner";
import { MessageDetail } from "./components/MessageDetail";
import { MessageList } from "./components/MessageList";
import { OutboundConnectorSetupModal } from "./components/OutboundConnectorSetupModal";
import { SearchPanel } from "./components/SearchPanel";
import { Settings } from "./components/Settings";
import { SetupScreen } from "./components/SetupScreen";
import { ShortcutsHelp } from "./components/ShortcutsHelp";
import {
	ALL_MAIL_LABEL_ID,
	INBOX_LABEL_ID,
	Sidebar,
	UNIFIED_ALL_MAIL_LABEL_ID,
	UNIFIED_INBOX_LABEL_ID,
	UNIFIED_UNREAD_LABEL_ID,
	UNREAD_LABEL_ID,
} from "./components/Sidebar";
import { ToastContainer, toast } from "./components/Toast";
import { UnlockScreen } from "./components/UnlockScreen";
import { Welcome } from "./components/Welcome";
import { buildThreadingHeaders } from "./compose-utils";
import {
	useAsync,
	useBulkSelection,
	useDarkMode,
	useDesktopNotifications,
	useHistoryNavigation,
	useKeyboardShortcuts,
	useMessageActions,
	useMessagePagination,
	useSyncPoller,
} from "./hooks";
import { isFlagged, parseFlags } from "./utils";
 
export function App() {
	const [dark, toggleDark] = useDarkMode();
	const { notifyNewMail } = useDesktopNotifications();
 
	// Container lock state — checked before any data fetching
	const [containerState, setContainerState] = useState<ContainerState | "loading">("loading");
 
	useEffect(() => {
		api
			.status()
			.then(({ state }) => setContainerState(state))
			.catch(() => setContainerState("unlocked")); // server error — let data routes surface it
	}, []);
 
	// Listen for 423 responses — container restarted and is now locked (or in setup)
	useEffect(() => {
		const handler = (e: Event) => {
			const state = (e as CustomEvent<{ state: string }>).detail?.state;
			setContainerState(state === "setup" ? "setup" : "locked");
		};
		window.addEventListener("stork-container-locked", handler);
		return () => window.removeEventListener("stork-container-locked", handler);
	}, []);
 
	// Data state
	const [selectedIdentityId, setSelectedIdentityId] = useState<number | null>(null);
	const [selectedLabelId, setSelectedLabelId] = useState<number | null>(null);
	const [selectedMessageId, setSelectedMessageId] = useState<number | null>(null);
	const [filterLabelIds, setFilterLabelIds] = useState<number[]>([]);
 
	// UI state
	const [composeMode, setComposeMode] = useState<ComposeMode | null>(null);
	// Compose mode queued while the outbound-connector setup wizard is open
	const [pendingComposeMode, setPendingComposeMode] = useState<ComposeMode | null>(null);
	const [showSearch, setShowSearch] = useState(false);
	const [initialSearchQuery, setInitialSearchQuery] = useState("");
	const [openedFromSearch, setOpenedFromSearch] = useState(false);
	const [searchResults, setSearchResults] = useState<SearchResult[]>([]);
	const [activeSearchQuery, setActiveSearchQuery] = useState("");
	const [showShortcuts, setShowShortcuts] = useState(false);
	const [showSettings, setShowSettings] = useState(false);
	const [messageListIndex, setMessageListIndex] = useState(0);
	const [sidebarOpen, setSidebarOpen] = useState(false);
 
	// Fetch identities — only when container is unlocked
	const {
		data: identities,
		error: identitiesError,
		refetch: refetchIdentities,
	} = useAsync(
		() => (containerState === "unlocked" ? api.identities.list() : Promise.resolve(null)),
		[containerState],
	);
 
	// Auto-select first identity
	const effectiveIdentityId = selectedIdentityId ?? identities?.[0]?.id ?? null;
 
	// Labels are global — not per-identity
	const { data: labels, refetch: refetchLabels } = useAsync(
		() => (containerState === "unlocked" ? api.labels.list() : Promise.resolve(null)),
		[containerState],
	);
 
	// Fetch all folders (needed for move-to-folder in MessageDetail)
	const { data: folders } = useAsync(
		() => (containerState === "unlocked" ? api.folders.listAll() : Promise.resolve([])),
		[containerState],
	);
 
	// Fetch inbound connectors (needed for per-connector labels in unified inbox view,
	// and to determine first-run state)
	const { data: inboundConnectors, refetch: refetchInboundConnectors } = useAsync(
		() => (containerState === "unlocked" ? api.connectors.inbound.list() : Promise.resolve([])),
		[containerState],
	);
 
	// Fetch outbound connectors — needed to detect zero-connector state for the compose upsell
	const { data: outboundConnectors, refetch: refetchOutboundConnectors } = useAsync(
		() => (containerState === "unlocked" ? api.connectors.outbound.list() : Promise.resolve([])),
		[containerState],
	);
 
	// Resolve the default view. In multi-identity mode the primary navigation is
	// unified (cross-identity), so default to UNIFIED_INBOX. In single-identity mode
	// honour the per-identity default_view setting.
	const effectiveIdentity = identities?.find((a) => a.id === effectiveIdentityId) ?? null;
	const defaultLabelId = useMemo(() => {
		if (!labels || labels.length === 0) return INBOX_LABEL_ID;
		// Multi-identity: unified inbox is the default starting point
		if ((identities?.length ?? 0) > 1 && !selectedIdentityId) return UNIFIED_INBOX_LABEL_ID;
		if (!effectiveIdentity) return INBOX_LABEL_ID;
		const dv = effectiveIdentity.default_view ?? "inbox";
		Iif (dv === "unread") return UNREAD_LABEL_ID;
		Iif (dv === "all") return ALL_MAIL_LABEL_ID;
		if (dv.startsWith("label:")) {
			const id = Number.parseInt(dv.slice(6), 10);
			return Number.isNaN(id) ? INBOX_LABEL_ID : id;
		}
		return INBOX_LABEL_ID; // 'inbox' or unknown
	}, [effectiveIdentity, labels, identities?.length, selectedIdentityId]);
 
	// Auto-select default view (uses per-identity setting, falls back to Inbox).
	// Guard on identities !== null to avoid a double-fetch: if labels resolve before
	// identities, effectiveLabelId would become non-null with effectiveIdentityId=null,
	// then when identities load effectiveIdentityId changes → getFetchFn changes → second
	// message fetch with the same args. Waiting for identities ensures one fetch.
	const effectiveLabelId =
		selectedLabelId ?? (labels && labels.length > 0 && identities !== null ? defaultLabelId : null);
 
	const isAllMail = effectiveLabelId === ALL_MAIL_LABEL_ID;
	const isUnread = effectiveLabelId === UNREAD_LABEL_ID;
	const isInbox = effectiveLabelId === INBOX_LABEL_ID;
	const isUnifiedInbox = effectiveLabelId === UNIFIED_INBOX_LABEL_ID;
	const isUnifiedAllMail = effectiveLabelId === UNIFIED_ALL_MAIL_LABEL_ID;
	const isUnifiedUnread = effectiveLabelId === UNIFIED_UNREAD_LABEL_ID;
 
	// Find the real inbox label for the promoted Inbox view
	const inboxLabel = labels?.find((l) => l.name.toLowerCase() === "inbox") ?? null;
	const inboxLabelId = inboxLabel?.id ?? null;
 
	// Suggested intersection filters: labels that commonly co-occur with messages in the current view.
	// For real labels (positive ID) and the promoted Inbox view: fetch from the related-labels API.
	// For virtual views (All Mail, Unread, unified variants): derive from labels by message count.
	// When multiple filter labels are active, use the intersection-aware endpoint so that every
	// suggestion is guaranteed to appear in at least one message in the current result set —
	// this makes it impossible to follow a chip and land on zero results.
	const suggestForLabelId =
		filterLabelIds.length > 0
			? null // handled separately below via filterRelated
			: isInbox || isUnifiedInbox
				? inboxLabelId
				: effectiveLabelId && effectiveLabelId > 0
					? effectiveLabelId
					: null;
	const { data: relatedLabelsFromApi } = useAsync(
		() => (suggestForLabelId ? api.labels.related(suggestForLabelId, 5) : Promise.resolve(null)),
		[suggestForLabelId],
	);
 
	// When filter labels are active, fetch suggestions from the intersection-aware endpoint so that
	// the suggested chips are the union of labels from messages in the current filtered result set.
	const filterRelatedKey = filterLabelIds.join(",");
	const { data: filterRelatedLabels } = useAsync(
		() =>
			filterLabelIds.length > 0
				? api.labels.filterRelated(filterLabelIds, 5)
				: Promise.resolve(null),
		[filterRelatedKey],
	);
 
	// For virtual "all" views, suggest top labels by message count (all non-system labels)
	const isVirtualAllView =
		filterLabelIds.length === 0 &&
		!suggestForLabelId &&
		(isAllMail || isUnread || isUnifiedAllMail || isUnifiedUnread);
	const virtualViewSuggestions =
		isVirtualAllView && labels
			? labels
					.filter((l) => l.message_count > 0 && !filterLabelIds.includes(l.id))
					.sort((a, b) => b.message_count - a.message_count)
					.slice(0, 5)
					.map((l) => ({ id: l.id, name: l.name, color: l.color, icon: l.icon, source: l.source }))
			: null;
 
	// filterRelated results are already scoped to the intersection — no need to re-filter by active IDs
	const relatedLabels = filterRelatedLabels ?? relatedLabelsFromApi ?? virtualViewSuggestions;
 
	// Fetch "All Mail" count for the sidebar badge (global across all inbound connectors)
	const { data: allMailCount, refetch: refetchAllMailCount } = useAsync(
		() => api.inbox.allMessages.count(),
		[],
	);
 
	// Fetch "Unread" count for the sidebar badge (global across all inbound connectors)
	const { data: unreadCount, refetch: refetchUnreadCount } = useAsync(
		() => api.inbox.unreadMessages.count(),
		[],
	);
 
	// Fetch unified inbox count for the "All Inboxes" sidebar badge (only with multiple identities)
	const hasMultipleIdentities = (identities?.length ?? 0) > 1;
	const { data: unifiedInboxCount, refetch: refetchUnifiedInboxCount } = useAsync(
		() => (hasMultipleIdentities ? api.inbox.unified.count() : Promise.resolve(null)),
		[hasMultipleIdentities],
	);
	const { data: unifiedAllMailCount, refetch: refetchUnifiedAllMailCount } = useAsync(
		() => (hasMultipleIdentities ? api.inbox.allMessages.count() : Promise.resolve(null)),
		[hasMultipleIdentities],
	);
	const { data: unifiedUnreadCount, refetch: refetchUnifiedUnreadCount } = useAsync(
		() => (hasMultipleIdentities ? api.inbox.unreadMessages.count() : Promise.resolve(null)),
		[hasMultipleIdentities],
	);
 
	// Message list fetching + pagination (extracted to hook)
	const {
		allMessages,
		setAllMessages,
		messagesLoading,
		messagesError,
		refetchMessages,
		hasMore,
		loadingMore,
		handleLoadMore,
	} = useMessagePagination({
		effectiveLabelId: isInbox ? inboxLabelId : effectiveLabelId,
		isAllMail,
		isUnread,
		isUnifiedInbox,
		isUnifiedAllMail,
		isUnifiedUnread,
		filterLabelIds,
	});
 
	// Fetch selected message detail
	const {
		data: selectedMessage,
		loading: messageLoading,
		error: messageError,
		refetch: refetchMessage,
	} = useAsync(
		() => (selectedMessageId ? api.messages.get(selectedMessageId) : Promise.resolve(null)),
		[selectedMessageId],
	);
 
	// Fetch thread for selected message
	const { data: thread, error: threadError } = useAsync(
		() => (selectedMessageId ? api.messages.getThread(selectedMessageId) : Promise.resolve([])),
		[selectedMessageId],
	);
 
	// Show toast when thread fails to load
	useEffect(() => {
		if (threadError) {
			toast("Failed to load thread", "error");
		}
	}, [threadError]);
 
	// Poll sync status — auto-refresh labels & messages when sync completes
	const {
		syncing,
		lastError: syncError,
		syncStatus,
	} = useSyncPoller(
		useCallback(() => {
			refetchLabels();
			refetchMessages();
			refetchAllMailCount();
			refetchUnreadCount();
			refetchUnifiedInboxCount();
			refetchUnifiedAllMailCount();
			refetchUnifiedUnreadCount();
		}, [
			refetchLabels,
			refetchMessages,
			refetchAllMailCount,
			refetchUnreadCount,
			refetchUnifiedInboxCount,
			refetchUnifiedAllMailCount,
			refetchUnifiedUnreadCount,
		]),
	);
 
	const currentLabelName =
		filterLabelIds.length > 1
			? filterLabelIds
					.map((id) => labels?.find((l) => l.id === id)?.name)
					.filter(Boolean)
					.join(" + ")
			: isUnifiedInbox
				? "All Inboxes"
				: isUnifiedAllMail
					? "All Mail"
					: isUnifiedUnread
						? "Unread"
						: isAllMail
							? "All Mail"
							: isUnread
								? "Unread"
								: isInbox
									? "Inbox"
									: (labels?.find((l) => l.id === effectiveLabelId)?.name ?? "Inbox");
 
	// Update document title with total unread count
	const totalUnread = labels?.reduce((sum, l) => sum + (l.unread_count || 0), 0) ?? 0;
	useEffect(() => {
		document.title = totalUnread > 0 ? `(${totalUnread}) Stork Mail` : "Stork Mail";
	}, [totalUnread]);
 
	// Fire desktop notification when new mail arrives (unread count increases after sync)
	const prevTotalUnreadRef = useRef<number | null>(null);
	useEffect(() => {
		if (labels === null) return;
		const prev = prevTotalUnreadRef.current;
		Iif (prev !== null && totalUnread > prev) {
			const diff = totalUnread - prev;
			notifyNewMail(diff, inboxLabel?.name ?? "Inbox");
		}
		prevTotalUnreadRef.current = totalUnread;
	}, [totalUnread, labels, inboxLabel?.name, notifyNewMail]);
 
	// Auto-refresh when window regains focus
	useEffect(() => {
		const handler = () => {
			refetchMessages();
			refetchLabels();
			refetchAllMailCount();
			refetchUnreadCount();
			refetchUnifiedInboxCount();
			refetchUnifiedAllMailCount();
			refetchUnifiedUnreadCount();
		};
		window.addEventListener("focus", handler);
		return () => window.removeEventListener("focus", handler);
	}, [
		refetchMessages,
		refetchLabels,
		refetchAllMailCount,
		refetchUnreadCount,
		refetchUnifiedInboxCount,
		refetchUnifiedAllMailCount,
		refetchUnifiedUnreadCount,
	]);
 
	// Message selection
	const handleSelectMessage = useCallback(
		(id: number) => {
			setSelectedMessageId(id);
			const idx = allMessages.findIndex((m) => m.id === id);
			setMessageListIndex(idx >= 0 ? idx : 0);
			// Close sidebar on mobile when selecting a message
			setSidebarOpen(false);
			// Clear search origin when selecting from message list
			setOpenedFromSearch(false);
		},
		[allMessages],
	);
 
	// Search result prev/next navigation
	const searchResultIndex = useMemo(() => {
		if (!openedFromSearch || !selectedMessageId) return -1;
		return searchResults.findIndex((r) => r.id === selectedMessageId);
	}, [openedFromSearch, selectedMessageId, searchResults]);
 
	const handleSearchPrev = useCallback(() => {
		const prev = searchResults[searchResultIndex - 1];
		Eif (searchResultIndex > 0 && prev) {
			setSelectedMessageId(prev.id);
		}
	}, [searchResultIndex, searchResults]);
 
	const handleSearchNext = useCallback(() => {
		const next = searchResults[searchResultIndex + 1];
		Eif (searchResultIndex >= 0 && searchResultIndex < searchResults.length - 1 && next) {
			setSelectedMessageId(next.id);
		}
	}, [searchResultIndex, searchResults]);
 
	// Browser back/forward navigation
	useHistoryNavigation({
		identityId: effectiveIdentityId,
		labelId: effectiveLabelId,
		messageId: selectedMessageId,
		searchActive: openedFromSearch,
		onNavigate: useCallback((state) => {
			Eif (state.identityId !== null) setSelectedIdentityId(state.identityId);
			setSelectedLabelId(state.labelId);
			setSelectedMessageId(state.messageId);
			setMessageListIndex(0);
			if (state.searchActive) {
				setShowSearch(true);
				setOpenedFromSearch(false);
			}
		}, []),
	});
 
	// Manual sync trigger
	const handleSyncNow = useCallback(async () => {
		Iif (!effectiveIdentityId) return;
		try {
			await api.sync.trigger(effectiveIdentityId);
		} catch (err) {
			const message = err instanceof Error ? err.message : "Unknown error";
			// "already syncing" is expected — sync poller will show progress
			if (!message.includes("already syncing")) {
				toast(`Sync failed: ${message}`, "error");
			}
		}
	}, [effectiveIdentityId]);
 
	// Inline star toggle from message list — uses parseFlags for consistent flag manipulation
	const handleToggleStar = useCallback(
		async (messageId: number) => {
			const msg = allMessages.find((m) => m.id === messageId);
			Iif (!msg) return;
			const flagged = isFlagged(msg.flags);
			const flagsUpdate = flagged ? { remove: ["\\Flagged"] } : { add: ["\\Flagged"] };
			// Optimistic update using parseFlags (same pattern as useMessageActions)
			setAllMessages((prev) =>
				prev.map((m) => {
					Iif (m.id !== messageId) return m;
					const flagSet = parseFlags(m.flags);
					if (flagged) flagSet.delete("\\Flagged");
					else flagSet.add("\\Flagged");
					return { ...m, flags: [...flagSet].join(",") };
				}),
			);
			try {
				await api.messages.updateFlags(messageId, flagsUpdate);
			} catch {
				refetchMessages();
			}
		},
		[allMessages, setAllMessages, refetchMessages],
	);
 
	// Archive = remove the current label. Works from any real label view (Inbox or custom label).
	// Not available from virtual views: All Mail, Unread, Unified.
	const archiveLabelId =
		isInbox && inboxLabelId
			? inboxLabelId
			: effectiveLabelId && effectiveLabelId > 0
				? effectiveLabelId
				: null;
	const archiveDisabled = !archiveLabelId;
 
	// Bulk selection (state + action handlers extracted to hook)
	const bulk = useBulkSelection({
		messages: allMessages,
		selectedMessageId,
		setSelectedMessageId,
		refetchMessages,
		refetchLabels,
		effectiveLabelId: archiveLabelId,
		isAllMail: archiveDisabled,
		refetchAllMailCount,
		refetchUnreadCount,
	});
 
	const handleSelectLabel = useCallback(
		(id: number) => {
			setSelectedLabelId(id);
			setFilterLabelIds([]);
			setSelectedMessageId(null);
			setMessageListIndex(0);
			setSidebarOpen(false);
			setShowSearch(false);
			setOpenedFromSearch(false);
			bulk.clear();
		},
		[bulk],
	);
 
	const handleToggleFilterLabel = useCallback(
		(id: number) => {
			setFilterLabelIds((prev) => {
				if (prev.length === 0) {
					// Starting a multi-label filter: include the currently selected label + the new one
					const currentIds: number[] = [];
					Iif (effectiveLabelId && effectiveLabelId > 0) {
						currentIds.push(effectiveLabelId);
					E} else if (isInbox && inboxLabelId) {
						currentIds.push(inboxLabelId);
					}
					Eif (!currentIds.includes(id)) currentIds.push(id);
					// Need at least 2 labels for multi-filter to be meaningful
					Iif (currentIds.length < 2) return [id];
					setSelectedLabelId(null);
					return currentIds;
				}
				Iif (prev.includes(id)) {
					const next = prev.filter((x) => x !== id);
					// If only one label left, switch to single-label view
					if (next.length <= 1) {
						if (next[0]) setSelectedLabelId(next[0]);
						return [];
					}
					return next;
				}
				return [...prev, id];
			});
			setSelectedMessageId(null);
			setMessageListIndex(0);
			bulk.clear();
		},
		[effectiveLabelId, isInbox, inboxLabelId, bulk],
	);
 
	const handleClearFilter = useCallback(() => {
		setFilterLabelIds([]);
	}, []);
 
	// Dispatch compose: if no outbound connectors exist, queue the mode and show the setup wizard
	const openOrQueueCompose = useCallback(
		(mode: ComposeMode) => {
			Iif ((outboundConnectors?.length ?? 0) === 0) {
				setPendingComposeMode(mode);
			} else {
				setComposeMode(mode);
			}
		},
		[outboundConnectors],
	);
 
	// Compose handlers
	const handleCompose = useCallback(() => {
		openOrQueueCompose({ type: "new" });
	}, [openOrQueueCompose]);
 
	const handleReply = useCallback(
		(msg: Message) => {
			openOrQueueCompose({ type: "reply", original: msg });
		},
		[openOrQueueCompose],
	);
 
	const handleReplyAll = useCallback(
		(msg: Message) => {
			openOrQueueCompose({ type: "reply-all", original: msg });
		},
		[openOrQueueCompose],
	);
 
	const handleForward = useCallback(
		(msg: Message) => {
			openOrQueueCompose({ type: "forward", original: msg });
		},
		[openOrQueueCompose],
	);
 
	const handleSend = useCallback(
		async (data: {
			identityId?: number;
			to: string;
			cc: string;
			bcc: string;
			subject: string;
			body: string;
			htmlBody?: string;
		}) => {
			const sendIdentityId = data.identityId ?? selectedIdentityId;
			Iif (!sendIdentityId) throw new Error("No email identity selected");
 
			const parseAddresses = (raw: string): string[] =>
				raw
					.split(",")
					.map((s) => s.trim())
					.filter(Boolean);
 
			// Build threading headers for replies/forwards
			const { inReplyTo, references } =
				composeMode && composeMode.type !== "new"
					? buildThreadingHeaders(composeMode.original)
					: { inReplyTo: undefined, references: undefined };
 
			await api.send({
				identity_id: sendIdentityId,
				to: parseAddresses(data.to),
				cc: data.cc ? parseAddresses(data.cc) : undefined,
				bcc: data.bcc ? parseAddresses(data.bcc) : undefined,
				subject: data.subject,
				text_body: data.body,
				html_body: data.htmlBody,
				in_reply_to: inReplyTo,
				references,
			});
 
			setComposeMode(null);
			toast("Message sent", "success");
			refetchMessages();
			refetchLabels();
		},
		[selectedIdentityId, composeMode, refetchMessages, refetchLabels],
	);
 
	// Per-message keyboard action handlers (star, mark read/unread, archive, delete)
	const msgActions = useMessageActions({
		messages: allMessages,
		messageListIndex,
		selectedMessageId,
		setSelectedMessageId,
		setAllMessages,
		labels: labels ?? null,
		folders: folders ?? null,
		effectiveLabelId: archiveLabelId,
		isAllMail: archiveDisabled,
		refetchMessages,
		refetchLabels,
		refetchAllMailCount,
		refetchUnreadCount,
	});
	const { focusedMessage } = msgActions;
 
	// Keyboard shortcuts
	const navigateDown = useCallback(() => {
		if (allMessages.length > 0 && messageListIndex < allMessages.length - 1) {
			const newIdx = messageListIndex + 1;
			setMessageListIndex(newIdx);
			setSelectedMessageId(allMessages[newIdx]?.id ?? 0);
		}
	}, [allMessages, messageListIndex]);
 
	const navigateUp = useCallback(() => {
		Eif (allMessages.length > 0 && messageListIndex > 0) {
			const newIdx = messageListIndex - 1;
			setMessageListIndex(newIdx);
			setSelectedMessageId(allMessages[newIdx]?.id ?? 0);
		}
	}, [allMessages, messageListIndex]);
 
	const shortcuts = useMemo(
		() => ({
			j: navigateDown,
			k: navigateUp,
			ArrowDown: navigateDown,
			ArrowUp: navigateUp,
			Enter: () => {
				Eif (allMessages[messageListIndex]) {
					setSelectedMessageId(allMessages[messageListIndex].id);
				}
			},
			Escape: () => {
				if (showSearch) setShowSearch(false);
				else if (showShortcuts) setShowShortcuts(false);
				else if (showSettings) setShowSettings(false);
				else if (composeMode) setComposeMode(nullE);
				else if (selectedMessageId) {
					setSelectedMessageId(null);
					if (openedFromSearch) {
						setShowSearch(true);
						setOpenedFromSearch(false);
					}
				}
			},
			c: () => {
				if (!composeMode && !showSearch) handleCompose();
			},
			r: () => {
				if (selectedMessage && !composeMode && !showSearch) {
					handleReply(selectedMessage);
				}
			},
			a: () => {
				if (selectedMessage && !composeMode && !showSearch) {
					handleReplyAll(selectedMessage);
				}
			},
			f: () => {
				if (selectedMessage && !composeMode && !showSearch) {
					handleForward(selectedMessage);
				}
			},
			"/": (e: KeyboardEvent) => {
				e.preventDefault();
				Eif (!showSearch) setShowSearch(true);
			},
			"?": () => {
				if (!showShortcuts && !showSearch && !composeMode) {
					setShowShortcuts(true);
				}
			},
			s: () => {
				if (focusedMessage && !composeMode && !showSearch) {
					msgActions.star();
				}
			},
			u: () => {
				Eif (focusedMessage && !composeMode && !showSearch) {
					msgActions.toggleRead();
				}
			},
			d: () => {
				Eif (focusedMessage && !composeMode && !showSearch) {
					msgActions.setPendingDelete(focusedMessage.id);
				}
			},
			e: () => {
				if (focusedMessage && !composeMode && !showSearch) {
					msgActions.archive();
				}
			},
			x: () => {
				if (focusedMessage && !composeMode && !showSearch) {
					bulk.toggle(focusedMessage.id);
				}
			},
		}),
		[
			navigateDown,
			navigateUp,
			allMessages,
			messageListIndex,
			focusedMessage,
			selectedMessage,
			composeMode,
			showSearch,
			showShortcuts,
			showSettings,
			selectedMessageId,
			openedFromSearch,
			handleCompose,
			handleReply,
			handleReplyAll,
			handleForward,
			msgActions,
			bulk,
		],
	);
 
	useKeyboardShortcuts(shortcuts);
 
	// Auto-recover when server comes back after a connection failure.
	// Polls /api/status and updates containerState so the correct screen renders.
	useEffect(() => {
		if (!identitiesError) return;
		let active = true;
		// Sequential scheduling: wait for each probe to complete before
		// scheduling the next, so slow responses don't stack up.
		async function probe() {
			if (!active) return;
			try {
				const { state } = await api.status();
				Iif (!active) return;
				if (state !== containerState) {
					setContainerState(state);
				E} else if (state === "unlocked") {
					refetchIdentities();
				}
			} catch {
				// Still unreachable — keep polling
			}
			Eif (active) setTimeout(probe, 3000);
		}
		probe();
		return () => {
			active = false;
		};
	}, [identitiesError, containerState, refetchIdentities]);
 
	// Container state gates — render before any data UI
	if (containerState === "loading") {
		return (
			<div className="h-screen flex items-center justify-center bg-gray-50 dark:bg-gray-950">
				<div className="w-6 h-6 border-2 border-stork-600 border-t-transparent rounded-full animate-spin" />
			</div>
		);
	}
 
	if (containerState === "setup") {
		return (
			<SetupScreen
				onUnlocked={() => setContainerState("unlocked")}
				dark={dark}
				onToggleDark={toggleDark}
			/>
		);
	}
 
	if (containerState === "locked") {
		return (
			<UnlockScreen
				onUnlocked={() => setContainerState("unlocked")}
				dark={dark}
				onToggleDark={toggleDark}
			/>
		);
	}
 
	if (identitiesError) {
		return (
			<div className="h-screen flex items-center justify-center bg-gray-50 dark:bg-gray-950">
				<div className="text-center space-y-3">
					<div className="w-8 h-8 mx-auto border-2 border-stork-600 border-t-transparent rounded-full animate-spin" />
					<p className="text-gray-600 dark:text-gray-400">Reconnecting to server…</p>
					<p className="text-sm text-gray-400">{identitiesError}</p>
				</div>
			</div>
		);
	}
 
	// First-run: show welcome screen when no inbound connectors exist yet.
	// Checking connectors (not identities) means users who configure a connector
	// manually via Settings won't see the welcome screen again.
	if (Array.isArray(inboundConnectors) && inboundConnectors.length === 0) {
		return (
			<Welcome
				onSetupComplete={() => {
					refetchIdentities();
					refetchInboundConnectors();
				}}
				dark={dark}
				onToggleDark={toggleDark}
			/>
		);
	}
 
	return (
		<div className="h-screen flex flex-col overflow-hidden">
			<DemoBanner />
			<div className="flex-1 flex min-h-0 overflow-hidden">
				{/* Skip to content link — visible on Tab for keyboard users */}
				<a
					href="#message-list"
					className="sr-only focus:not-sr-only focus:absolute focus:z-50 focus:top-2 focus:left-2 focus:px-4 focus:py-2 focus:bg-stork-600 focus:text-white focus:rounded-md focus:text-sm"
				>
					Skip to messages
				</a>
				{/* Mobile sidebar overlay */}
				{sidebarOpen && (
					<button
						type="button"
						className="fixed inset-0 z-30 bg-black/30 md:hidden"
						onClick={() => setSidebarOpen(false)}
						aria-label="Close sidebar"
					/>
				)}
 
				{/* Sidebar */}
				<div
					className={`fixed inset-y-0 left-0 z-40 md:relative md:z-0 transform transition-transform duration-200 ease-in-out ${
						sidebarOpen ? "translate-x-0" : "-translate-x-full md:translate-x-0"
					}`}
				>
					<Sidebar
						identities={identities ?? []}
						labels={labels ?? []}
						selectedLabelId={effectiveLabelId}
						filterLabelIds={filterLabelIds}
						onSelectLabel={handleSelectLabel}
						onToggleFilterLabel={handleToggleFilterLabel}
						onClearFilter={handleClearFilter}
						onCompose={handleCompose}
						onSearch={(query) => {
							setInitialSearchQuery(query);
							setShowSearch(true);
						}}
						onSettings={() => setShowSettings(true)}
						onSyncNow={handleSyncNow}
						dark={dark}
						onToggleDark={toggleDark}
						syncing={syncing}
						syncError={syncError}
						syncStatus={syncStatus}
						onLabelsChanged={refetchLabels}
						allMailCount={allMailCount}
						unreadCount={unreadCount}
						inboxLabel={inboxLabel}
						unifiedInboxCount={unifiedInboxCount}
						unifiedAllMailCount={unifiedAllMailCount}
						unifiedUnreadCount={unifiedUnreadCount}
					/>
				</div>
 
				{/* Main content area — split into message list + detail */}
				<div className="flex-1 flex min-w-0">
					{/* Mobile header with hamburger */}
					<div className="md:hidden absolute top-0 left-0 z-20 p-2">
						<button
							type="button"
							onClick={() => setSidebarOpen(true)}
							className="p-2 text-gray-500 hover:text-gray-700 dark:text-gray-400 dark:hover:text-gray-200 rounded-md hover:bg-gray-100 dark:hover:bg-gray-800"
							aria-label="Open sidebar"
						>
							<svg
								className="w-5 h-5"
								fill="none"
								stroke="currentColor"
								viewBox="0 0 24 24"
								role="img"
								aria-label="Menu"
							>
								<title>Menu</title>
								<path
									strokeLinecap="round"
									strokeLinejoin="round"
									strokeWidth={2}
									d="M4 6h16M4 12h16M4 18h16"
								/>
							</svg>
						</button>
					</div>
 
					{/* Message list panel — hidden on mobile when viewing a message (unless search is active) */}
					<div
						id="message-list"
						className={`w-full md:w-80 xl:w-96 flex-shrink-0 border-r border-gray-200 dark:border-gray-800 flex flex-col min-h-0 ${
							selectedMessageId !== null && !showSearch ? "hidden md:flex" : "flex"
						}`}
					>
						{showSearch ? (
							<SearchPanel
								onClose={() => {
									setShowSearch(false);
									setInitialSearchQuery("");
								}}
								onSelectMessage={(id) => {
									setSelectedMessageId(id);
									setOpenedFromSearch(true);
								}}
								inboundConnectorId={null}
								onResultsChange={setSearchResults}
								onQueryChange={setActiveSearchQuery}
								initialQuery={initialSearchQuery}
							/>
						) : (
							<MessageList
								messages={allMessages}
								selectedId={selectedMessageId}
								focusedId={focusedMessage?.id ?? null}
								onSelect={handleSelectMessage}
								loading={messagesLoading}
								error={messagesError}
								folderName={currentLabelName}
								onRefresh={refetchMessages}
								hasMore={hasMore}
								onLoadMore={handleLoadMore}
								loadingMore={loadingMore}
								onToggleStar={handleToggleStar}
								inboundConnectors={
									isUnifiedInbox || isUnifiedAllMail || isUnifiedUnread || filterLabelIds.length > 1
										? (inboundConnectors ?? undefined)
										: undefined
								}
								totalCount={
									isUnifiedInbox
										? unifiedInboxCount?.total
										: isUnifiedAllMail
											? unifiedAllMailCount?.total
											: isUnifiedUnread
												? unifiedUnreadCount?.total
												: isAllMail
													? allMailCount?.total
													: isUnread
														? unreadCount?.total
														: isInbox
															? inboxLabel?.message_count
															: labels?.find((l) => l.id === effectiveLabelId)?.message_count
								}
								selectedIds={bulk.selectedIds}
								onToggleSelect={bulk.toggle}
								onSelectAll={bulk.selectAll}
								onClearSelection={bulk.clear}
								onBulkDelete={bulk.bulkDelete}
								onBulkMarkRead={bulk.markRead}
								onBulkMarkUnread={bulk.markUnread}
								onBulkMove={bulk.move}
								onBulkArchive={!archiveDisabled ? bulk.archive : undefined}
								onArchiveMessage={!archiveDisabled ? (id) => msgActions.archive(id) : undefined}
								archiveMessageLabel={
									isInbox
										? "Archive"
										: effectiveLabelId && effectiveLabelId > 0
											? `Remove from ${labels?.find((l) => l.id === effectiveLabelId)?.name ?? "label"}`
											: undefined
								}
								folders={folders ?? []}
								suggestedLabels={relatedLabels ?? undefined}
								onAddFilterLabel={handleToggleFilterLabel}
								filterLabelIds={filterLabelIds}
								allLabels={labels ?? undefined}
								onRemoveFilterLabel={handleToggleFilterLabel}
								onClearFilter={handleClearFilter}
							/>
						)}
					</div>
 
					{/* Message detail / thread view — hidden on mobile when no message selected */}
					<div
						className={`flex-1 min-w-0 ${selectedMessageId === null ? "hidden md:flex" : "flex"}`}
					>
						<MessageDetail
							message={selectedMessage ?? null}
							thread={thread ?? []}
							loading={messageLoading && selectedMessageId !== null}
							error={messageError}
							dark={dark}
							onReply={handleReply}
							onReplyAll={handleReplyAll}
							onForward={handleForward}
							openedFromSearch={openedFromSearch}
							searchPosition={
								searchResultIndex >= 0
									? { current: searchResultIndex + 1, total: searchResults.length }
									: undefined
							}
							onSearchPrev={searchResultIndex > 0 ? handleSearchPrev : undefined}
							onSearchNext={
								searchResultIndex >= 0 && searchResultIndex < searchResults.length - 1
									? handleSearchNext
									: undefined
							}
							onBack={() => {
								setSelectedMessageId(null);
								if (openedFromSearch) {
									setShowSearch(true);
									setOpenedFromSearch(false);
								}
							}}
							onMessageChanged={() => {
								refetchMessage();
								refetchMessages();
								refetchLabels();
								refetchUnreadCount();
							}}
							onMessageDeleted={() => {
								setSelectedMessageId(null);
								refetchMessages();
								refetchLabels();
								refetchUnreadCount();
							}}
							folders={folders ?? []}
							identityId={effectiveIdentityId}
							onLabelsChanged={refetchLabels}
							searchQuery={openedFromSearch ? activeSearchQuery : undefined}
						/>
					</div>
				</div>
 
				{/* Modals */}
				{pendingComposeMode && (
					<OutboundConnectorSetupModal
						onDone={() => {
							const mode = pendingComposeMode;
							setPendingComposeMode(null);
							refetchOutboundConnectors();
							refetchIdentities();
							setComposeMode(mode);
						}}
						onCancel={() => setPendingComposeMode(null)}
					/>
				)}
				{composeMode && (
					<ComposeModal
						mode={composeMode}
						identities={identities ?? []}
						selectedIdentityId={effectiveIdentityId}
						onClose={() => setComposeMode(null)}
						onSend={handleSend}
					/>
				)}
				{showShortcuts && <ShortcutsHelp onClose={() => setShowShortcuts(false)} />}
				{showSettings && <Settings onClose={() => setShowSettings(false)} />}
				{msgActions.pendingDelete !== null && (
					<ConfirmDialog
						title="Delete message"
						message="This will permanently delete this message. This action cannot be undone."
						confirmLabel="Delete"
						variant="danger"
						onConfirm={msgActions.confirmDelete}
						onCancel={() => msgActions.setPendingDelete(null)}
					/>
				)}
				<ToastContainer />
			</div>
		</div>
	);
}