inbox.go

  1package tui
  2
  3import (
  4	"fmt"
  5	"io"
  6	"strings"
  7	"time"
  8
  9	"charm.land/bubbles/v2/key"
 10	"charm.land/bubbles/v2/list"
 11	tea "charm.land/bubbletea/v2"
 12	"charm.land/lipgloss/v2"
 13	"github.com/floatpane/matcha/config"
 14	"github.com/floatpane/matcha/fetcher"
 15	"github.com/floatpane/matcha/theme"
 16)
 17
 18var (
 19	// In bubbles v2, list.DefaultStyles() takes a boolean for hasDarkBackground
 20	paginationStyle = list.DefaultStyles(true).PaginationStyle.PaddingLeft(4)
 21	inboxHelpStyle  = list.DefaultStyles(true).HelpStyle.PaddingLeft(4).PaddingBottom(1)
 22	tabStyle        = lipgloss.NewStyle().Padding(0, 2)
 23	activeTabStyle  = lipgloss.NewStyle().Padding(0, 2).Foreground(lipgloss.Color("42")).Bold(true).Underline(true)
 24	tabBarStyle     = lipgloss.NewStyle().BorderStyle(lipgloss.NormalBorder()).BorderBottom(true).PaddingBottom(1).MarginBottom(1)
 25)
 26
 27var dateStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("243"))
 28var unreadEmailStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("42")).Bold(true)
 29var readEmailStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("240"))
 30
 31type item struct {
 32	title, desc   string
 33	originalIndex int
 34	uid           uint32
 35	accountID     string
 36	accountEmail  string
 37	date          time.Time
 38	isRead        bool
 39}
 40
 41func (i item) Title() string       { return i.title }
 42func (i item) Description() string { return i.desc }
 43func (i item) FilterValue() string { return i.title + " " + i.desc }
 44
 45type itemDelegate struct{}
 46
 47func (d itemDelegate) Height() int                               { return 1 }
 48func (d itemDelegate) Spacing() int                              { return 0 }
 49func (d itemDelegate) Update(msg tea.Msg, m *list.Model) tea.Cmd { return nil }
 50func (d itemDelegate) Render(w io.Writer, m list.Model, index int, listItem list.Item) {
 51	i, ok := listItem.(item)
 52	if !ok {
 53		return
 54	}
 55
 56	prefix := fmt.Sprintf("%d. ", index+1)
 57	sender := parseSenderName(i.desc)
 58	statusStyle := unreadEmailStyle
 59	statusIcon := "\uf0e0"
 60	if i.isRead {
 61		statusStyle = readEmailStyle
 62		statusIcon = "\uf2b6"
 63	}
 64	styledIcon := statusStyle.Render(statusIcon)
 65	styledSender := statusStyle.Render(sender)
 66	separator := " · "
 67
 68	// For "ALL" view, show account indicator instead of number
 69	if i.accountEmail != "" {
 70		prefix = fmt.Sprintf("%d. [%s] ", index+1, truncateEmail(i.accountEmail))
 71	}
 72
 73	// Format and right-align date
 74	dateStr := formatRelativeDate(i.date)
 75	styledDate := dateStyle.Render(dateStr)
 76	if i.isRead {
 77		styledDate = readEmailStyle.Render(dateStr)
 78	} else {
 79		styledDate = statusStyle.Render(dateStr)
 80	}
 81	dateWidth := lipgloss.Width(styledDate)
 82
 83	listWidth := m.Width()
 84	isSelected := index == m.Index()
 85	cursorWidth := 0
 86	if isSelected {
 87		cursorWidth = 2 // "> " prefix
 88	}
 89
 90	// Available width for the whole left side (prefix + sender + separator + subject)
 91	maxLeft := listWidth - dateWidth - 2 - cursorWidth // 2 for spacing
 92	if maxLeft < 10 {
 93		maxLeft = 10
 94	}
 95
 96	prefixWidth := lipgloss.Width(prefix)
 97	iconWidth := lipgloss.Width(styledIcon) + 1
 98	senderWidth := lipgloss.Width(styledSender)
 99	sepWidth := len(separator)
100	subjectBudget := maxLeft - prefixWidth - iconWidth - senderWidth - sepWidth
101
102	subject := i.title
103	if subjectBudget < 4 {
104		subjectBudget = 4
105	}
106	if lipgloss.Width(subject) > subjectBudget {
107		for lipgloss.Width(subject) > subjectBudget-1 && len(subject) > 0 {
108			subject = subject[:len(subject)-1]
109		}
110		subject += "…"
111	}
112	styledSubject := statusStyle.Render(subject)
113
114	str := prefix + styledIcon + " " + styledSender + separator + styledSubject
115
116	// Pad to push date to the right
117	padding := listWidth - lipgloss.Width(str) - dateWidth - cursorWidth
118	if padding < 1 {
119		padding = 1
120	}
121
122	fn := itemStyle.Render
123	if index == m.Index() {
124		fn = func(s ...string) string {
125			return selectedItemStyle.Render("> " + s[0])
126		}
127	}
128
129	fmt.Fprint(w, fn(str+strings.Repeat(" ", padding)+styledDate))
130}
131
132// formatRelativeDate formats a time as relative if within the last week,
133// otherwise as an absolute date.
134func formatRelativeDate(t time.Time) string {
135	if t.IsZero() {
136		return ""
137	}
138	now := time.Now()
139	d := now.Sub(t)
140
141	switch {
142	case d < time.Minute:
143		return "just now"
144	case d < time.Hour:
145		mins := int(d.Minutes())
146		if mins == 1 {
147			return "1 min ago"
148		}
149		return fmt.Sprintf("%d min ago", mins)
150	case d < 24*time.Hour:
151		hours := int(d.Hours())
152		if hours == 1 {
153			return "1 hour ago"
154		}
155		return fmt.Sprintf("%d hours ago", hours)
156	case d < 7*24*time.Hour:
157		days := int(d.Hours() / 24)
158		if days == 1 {
159			return "1 day ago"
160		}
161		return fmt.Sprintf("%d days ago", days)
162	default:
163		if t.Year() == now.Year() {
164			return t.Format("Jan 02")
165		}
166		return t.Format("Jan 02, 2006")
167	}
168}
169
170// parseSenderName extracts the display name from a "Name <email>" string,
171// falling back to the local part of the email address.
172func parseSenderName(from string) string {
173	if idx := strings.Index(from, " <"); idx > 0 {
174		return strings.TrimSpace(from[:idx])
175	}
176	// No display name — use local part of email
177	if idx := strings.Index(from, "@"); idx > 0 {
178		return from[:idx]
179	}
180	return from
181}
182
183// truncateEmail shortens an email for display
184func truncateEmail(email string) string {
185	parts := strings.Split(email, "@")
186	if len(parts) >= 1 && len(parts[0]) > 8 {
187		return parts[0][:8] + "..."
188	}
189	if len(parts) >= 1 {
190		return parts[0]
191	}
192	return email
193}
194
195// AccountTab represents a tab for an account
196type AccountTab struct {
197	ID    string
198	Label string
199	Email string
200}
201
202type Inbox struct {
203	list               list.Model
204	isFetching         bool
205	isRefreshing       bool
206	emailsCount        int
207	accounts           []config.Account
208	emailsByAccount    map[string][]fetcher.Email
209	allEmails          []fetcher.Email
210	tabs               []AccountTab
211	activeTabIndex     int
212	width              int
213	height             int
214	currentAccountID   string // Empty means "ALL"
215	emailCountByAcct   map[string]int
216	mailbox            MailboxKind
217	folderName         string          // Custom folder name override for title
218	noMoreByAccount    map[string]bool // Per-account: true when pagination returns 0 results
219	extraShortHelpKeys []key.Binding
220}
221
222func NewInbox(emails []fetcher.Email, accounts []config.Account) *Inbox {
223	return NewInboxWithMailbox(emails, accounts, MailboxInbox)
224}
225
226func NewSentInbox(emails []fetcher.Email, accounts []config.Account) *Inbox {
227	return NewInboxWithMailbox(emails, accounts, MailboxSent)
228}
229
230func NewTrashInbox(emails []fetcher.Email, accounts []config.Account) *Inbox {
231	return NewInboxWithMailbox(emails, accounts, MailboxTrash)
232}
233
234func NewArchiveInbox(emails []fetcher.Email, accounts []config.Account) *Inbox {
235	return NewInboxWithMailbox(emails, accounts, MailboxArchive)
236}
237
238func NewInboxWithMailbox(emails []fetcher.Email, accounts []config.Account, mailbox MailboxKind) *Inbox {
239	// Build tabs: empty for single account, "ALL" + accounts for multiple
240	var tabs []AccountTab
241	if len(accounts) <= 1 {
242		tabs = []AccountTab{{ID: "", Label: "", Email: ""}}
243	} else {
244		tabs = []AccountTab{{ID: "", Label: "ALL", Email: ""}}
245		for _, acc := range accounts {
246			// Use FetchEmail for display, fall back to Email if not set
247			displayEmail := acc.FetchEmail
248			if displayEmail == "" {
249				displayEmail = acc.Email
250			}
251			tabs = append(tabs, AccountTab{ID: acc.ID, Label: displayEmail, Email: displayEmail})
252		}
253	}
254
255	// Group emails by account
256	emailsByAccount := make(map[string][]fetcher.Email)
257	for _, email := range emails {
258		emailsByAccount[email.AccountID] = append(emailsByAccount[email.AccountID], email)
259	}
260
261	// Track email counts per account
262	emailCountByAcct := make(map[string]int)
263	for accID, accEmails := range emailsByAccount {
264		emailCountByAcct[accID] = len(accEmails)
265	}
266
267	inbox := &Inbox{
268		accounts:         accounts,
269		emailsByAccount:  emailsByAccount,
270		allEmails:        emails,
271		tabs:             tabs,
272		activeTabIndex:   0,
273		currentAccountID: "",
274		emailCountByAcct: emailCountByAcct,
275		mailbox:          mailbox,
276	}
277
278	inbox.updateList()
279	return inbox
280}
281
282// NewInboxSingleAccount creates an inbox for a single account (legacy support)
283func NewInboxSingleAccount(emails []fetcher.Email) *Inbox {
284	return NewInbox(emails, nil)
285}
286
287func (m *Inbox) updateList() {
288	// Capture current index to restore later
289	currentIndex := m.list.Index()
290
291	var displayEmails []fetcher.Email
292	var showAccountLabel bool
293
294	if m.currentAccountID == "" {
295		// "ALL" view - show all emails sorted by date
296		displayEmails = m.allEmails
297		showAccountLabel = !(len(m.accounts) <= 1)
298	} else {
299		// Specific account view
300		displayEmails = m.emailsByAccount[m.currentAccountID]
301		showAccountLabel = false
302	}
303
304	m.emailsCount = len(displayEmails)
305
306	items := make([]list.Item, len(displayEmails))
307	for i, email := range displayEmails {
308		accountEmail := ""
309		if showAccountLabel {
310			// Find the account email for display
311			for _, acc := range m.accounts {
312				if acc.ID == email.AccountID {
313					accountEmail = acc.FetchEmail
314					break
315				}
316			}
317		}
318
319		items[i] = item{
320			title:         email.Subject,
321			desc:          email.From,
322			originalIndex: i,
323			uid:           email.UID,
324			accountID:     email.AccountID,
325			accountEmail:  accountEmail,
326			date:          email.Date,
327			isRead:        email.IsRead,
328		}
329	}
330
331	l := list.New(items, itemDelegate{}, 20, 14)
332	l.Title = m.getTitle()
333	l.SetShowStatusBar(true)
334	l.SetFilteringEnabled(true)
335	l.Styles.Title = lipgloss.NewStyle().Foreground(theme.ActiveTheme.Accent).Bold(true)
336	l.Styles.PaginationStyle = paginationStyle
337	l.Styles.HelpStyle = inboxHelpStyle
338	l.SetStatusBarItemName("email", "emails")
339	l.AdditionalShortHelpKeys = func() []key.Binding {
340		bindings := []key.Binding{
341			key.NewBinding(key.WithKeys("d"), key.WithHelp("\uf014 d", "delete")),
342			key.NewBinding(key.WithKeys("a"), key.WithHelp("\uea98 a", "archive")),
343			key.NewBinding(key.WithKeys("r"), key.WithHelp("\ue348 r", "refresh")),
344		}
345		if len(m.tabs) > 1 {
346			bindings = append(bindings,
347				key.NewBinding(key.WithKeys("left", "h"), key.WithHelp("←/h", "prev tab")),
348				key.NewBinding(key.WithKeys("right", "l"), key.WithHelp("→/l", "next tab")),
349			)
350		}
351		bindings = append(bindings, m.extraShortHelpKeys...)
352		return bindings
353	}
354
355	l.KeyMap.Quit.SetEnabled(false)
356
357	// Disable default help to render it manually at the bottom
358	l.SetShowHelp(false)
359
360	if m.width > 0 {
361		l.SetWidth(m.width)
362	}
363	if m.height > 0 {
364		l.SetHeight(m.height / 2)
365	}
366
367	// Restore index
368	// If index is out of bounds (e.g. list shrank), clamp it.
369	if currentIndex >= len(items) {
370		currentIndex = len(items) - 1
371	}
372	if currentIndex < 0 {
373		currentIndex = 0
374	}
375	l.Select(currentIndex)
376
377	m.list = l
378}
379
380func (m *Inbox) getTitle() string {
381	var title string
382	if m.currentAccountID == "" {
383		title = m.getBaseTitle() + " - All Accounts"
384	} else {
385		title = m.getBaseTitle()
386		for _, acc := range m.accounts {
387			if acc.ID == m.currentAccountID {
388				if acc.Name != "" {
389					title = fmt.Sprintf("%s - %s", m.getBaseTitle(), acc.Name)
390				} else {
391					title = fmt.Sprintf("%s - %s", m.getBaseTitle(), acc.FetchEmail)
392				}
393				break
394			}
395		}
396	}
397	if m.isRefreshing {
398		title += " (refreshing...)"
399	}
400	if m.isFetching {
401		title += " (loading more...)"
402	}
403	return title
404}
405
406func (m *Inbox) getBaseTitle() string {
407	if m.folderName != "" {
408		return m.folderName
409	}
410	switch m.mailbox {
411	case MailboxSent:
412		return "Sent"
413	case MailboxTrash:
414		return "Trash"
415	case MailboxArchive:
416		return "Archive"
417	default:
418		return "Inbox"
419	}
420}
421
422func (m *Inbox) Init() tea.Cmd {
423	return nil
424}
425
426func (m *Inbox) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
427	var cmds []tea.Cmd
428
429	switch msg := msg.(type) {
430	case tea.KeyPressMsg:
431		if m.list.FilterState() == list.Filtering {
432			break
433		}
434		switch keypress := msg.String(); keypress {
435		case "left", "h":
436			if len(m.tabs) > 1 {
437				m.activeTabIndex--
438				if m.activeTabIndex < 0 {
439					m.activeTabIndex = len(m.tabs) - 1
440				}
441				m.currentAccountID = m.tabs[m.activeTabIndex].ID
442				m.updateList()
443				return m, nil
444			}
445		case "right", "l":
446			if len(m.tabs) > 1 {
447				m.activeTabIndex++
448				if m.activeTabIndex >= len(m.tabs) {
449					m.activeTabIndex = 0
450				}
451				m.currentAccountID = m.tabs[m.activeTabIndex].ID
452				m.updateList()
453				return m, nil
454			}
455		case "d":
456			selectedItem, ok := m.list.SelectedItem().(item)
457			if ok {
458				return m, func() tea.Msg {
459					return DeleteEmailMsg{UID: selectedItem.uid, AccountID: selectedItem.accountID, Mailbox: m.mailbox}
460				}
461			}
462		case "a":
463			selectedItem, ok := m.list.SelectedItem().(item)
464			if ok {
465				return m, func() tea.Msg {
466					return ArchiveEmailMsg{UID: selectedItem.uid, AccountID: selectedItem.accountID, Mailbox: m.mailbox}
467				}
468			}
469		case "r":
470			m.isRefreshing = true
471			m.list.Title = m.getTitle()
472			// Copy counts to avoid race conditions if used elsewhere (though here it's just passing data)
473			counts := make(map[string]int)
474			for k, v := range m.emailCountByAcct {
475				counts[k] = v
476			}
477			return m, func() tea.Msg {
478				return RequestRefreshMsg{Mailbox: m.mailbox, Counts: counts}
479			}
480		case "enter":
481			selectedItem, ok := m.list.SelectedItem().(item)
482			if ok {
483				idx := selectedItem.originalIndex
484				uid := selectedItem.uid
485				accountID := selectedItem.accountID
486				return m, func() tea.Msg {
487					return ViewEmailMsg{Index: idx, UID: uid, AccountID: accountID, Mailbox: m.mailbox}
488				}
489			}
490		}
491	case tea.WindowSizeMsg:
492		m.width = msg.Width
493		m.height = msg.Height
494		m.list.SetWidth(msg.Width)
495		m.list.SetHeight(msg.Height / 2)
496		if m.shouldFetchMore() {
497			return m, tea.Batch(m.fetchMoreCmds()...)
498		}
499		return m, nil
500
501	case FetchingMoreEmailsMsg:
502		m.isFetching = true
503		m.list.Title = m.getTitle()
504		return m, nil
505
506	case EmailsAppendedMsg:
507		if msg.Mailbox != m.mailbox {
508			return m, nil
509		}
510		m.isFetching = false
511		m.list.Title = m.getTitle()
512
513		if len(msg.Emails) == 0 {
514			if m.noMoreByAccount == nil {
515				m.noMoreByAccount = make(map[string]bool)
516			}
517			m.noMoreByAccount[msg.AccountID] = true
518			return m, nil
519		}
520
521		// Add emails to the appropriate account
522		for _, email := range msg.Emails {
523			m.emailsByAccount[email.AccountID] = append(m.emailsByAccount[email.AccountID], email)
524			m.allEmails = append(m.allEmails, email)
525		}
526		m.emailCountByAcct[msg.AccountID] = len(m.emailsByAccount[msg.AccountID])
527
528		m.updateList()
529		return m, nil
530
531	case RefreshingEmailsMsg:
532		if msg.Mailbox != m.mailbox {
533			return m, nil
534		}
535		m.isRefreshing = true
536		m.list.Title = m.getTitle()
537		return m, nil
538
539	case EmailsRefreshedMsg:
540		if msg.Mailbox != m.mailbox {
541			return m, nil
542		}
543		// Only clear the refreshing indicator. The actual email data is
544		// merged by the main model (preserving paginated emails) and
545		// pushed to us via SetEmails, so we must not overwrite it here.
546		m.isRefreshing = false
547		m.list.Title = m.getTitle()
548		return m, nil
549	}
550
551	var cmd tea.Cmd
552	m.list, cmd = m.list.Update(msg)
553	cmds = append(cmds, cmd)
554
555	if m.shouldFetchMore() {
556		cmds = append(cmds, m.fetchMoreCmds()...)
557	}
558	return m, tea.Batch(cmds...)
559}
560
561func (m *Inbox) shouldFetchMore() bool {
562	if m.isFetching || m.isRefreshing {
563		return false
564	}
565	if m.allAccountsExhausted() {
566		return false
567	}
568	if len(m.list.Items()) == 0 {
569		return false
570	}
571	if m.list.FilterState() == list.Filtering {
572		return false
573	}
574	// Fetch if we've reached the bottom OR if we don't have enough items to fill the view
575	return m.list.Index() >= len(m.list.Items())-1 || len(m.list.Items()) < m.list.Height()
576}
577
578// allAccountsExhausted returns true if all relevant accounts have no more emails to fetch.
579func (m *Inbox) allAccountsExhausted() bool {
580	if len(m.noMoreByAccount) == 0 {
581		return false
582	}
583	if m.currentAccountID != "" {
584		return m.noMoreByAccount[m.currentAccountID]
585	}
586	// "ALL" view: all accounts must be exhausted
587	for _, acc := range m.accounts {
588		if !m.noMoreByAccount[acc.ID] {
589			return false
590		}
591	}
592	return len(m.accounts) > 0
593}
594
595func (m *Inbox) fetchMoreCmds() []tea.Cmd {
596	var cmds []tea.Cmd
597	limit := uint32(m.list.Height())
598	if limit < 20 {
599		limit = 20
600	}
601
602	if m.currentAccountID == "" {
603		if len(m.accounts) == 0 {
604			return nil
605		}
606		for _, acc := range m.accounts {
607			accountID := acc.ID
608			if m.noMoreByAccount[accountID] {
609				continue
610			}
611			offset := uint32(len(m.emailsByAccount[accountID]))
612			cmds = append(cmds, func(id string, off uint32) tea.Cmd {
613				return func() tea.Msg {
614					return FetchMoreEmailsMsg{Offset: off, AccountID: id, Mailbox: m.mailbox, Limit: limit}
615				}
616			}(accountID, offset))
617		}
618		return cmds
619	}
620
621	if m.noMoreByAccount[m.currentAccountID] {
622		return nil
623	}
624	offset := uint32(len(m.emailsByAccount[m.currentAccountID]))
625	cmds = append(cmds, func(id string, off uint32) tea.Cmd {
626		return func() tea.Msg {
627			return FetchMoreEmailsMsg{Offset: off, AccountID: id, Mailbox: m.mailbox, Limit: limit}
628		}
629	}(m.currentAccountID, offset))
630	return cmds
631}
632
633func (m *Inbox) View() tea.View {
634	var b strings.Builder
635
636	// Render tabs if there are multiple accounts
637	if len(m.tabs) > 1 {
638		var tabViews []string
639		for i, tab := range m.tabs {
640			label := tab.Label
641			if tab.ID == "" {
642				label = "ALL"
643			}
644
645			if i == m.activeTabIndex {
646				tabViews = append(tabViews, activeTabStyle.Render(label))
647			} else {
648				tabViews = append(tabViews, tabStyle.Render(label))
649			}
650		}
651		tabBar := tabBarStyle.Render(lipgloss.JoinHorizontal(lipgloss.Top, tabViews...))
652		b.WriteString(tabBar)
653		b.WriteString("\n")
654	}
655
656	b.WriteString(m.list.View())
657
658	// Ensure we don't start gap calculation on the same line as the list
659	if !strings.HasSuffix(b.String(), "\n") {
660		b.WriteString("\n")
661	}
662
663	helpView := inboxHelpStyle.Render(m.list.Help.View(m.list))
664
665	if m.height > 0 {
666		usedHeight := lipgloss.Height(b.String())
667		helpHeight := lipgloss.Height(helpView)
668
669		gap := m.height - usedHeight - helpHeight
670		if gap > 0 {
671			b.WriteString(strings.Repeat("\n", gap))
672		}
673	} else {
674		b.WriteString("\n")
675	}
676
677	b.WriteString(helpView)
678
679	return tea.NewView(b.String())
680}
681
682// GetCurrentAccountID returns the currently selected account ID
683func (m *Inbox) GetCurrentAccountID() string {
684	return m.currentAccountID
685}
686
687// GetEmailAtIndex returns the email at the given index for the current view
688func (m *Inbox) GetEmailAtIndex(index int) *fetcher.Email {
689	var displayEmails []fetcher.Email
690	if m.currentAccountID == "" {
691		displayEmails = m.allEmails
692	} else {
693		displayEmails = m.emailsByAccount[m.currentAccountID]
694	}
695
696	if index >= 0 && index < len(displayEmails) {
697		return &displayEmails[index]
698	}
699	return nil
700}
701
702func (m *Inbox) GetMailbox() MailboxKind {
703	return m.mailbox
704}
705
706// MarkEmailAsRead marks an email as read by UID and account ID, updating it in all stores.
707func (m *Inbox) MarkEmailAsRead(uid uint32, accountID string) {
708	for i := range m.allEmails {
709		if m.allEmails[i].UID == uid && m.allEmails[i].AccountID == accountID {
710			m.allEmails[i].IsRead = true
711			break
712		}
713	}
714	if emails, ok := m.emailsByAccount[accountID]; ok {
715		for i := range emails {
716			if emails[i].UID == uid {
717				emails[i].IsRead = true
718				break
719			}
720		}
721	}
722	m.updateList()
723}
724
725// RemoveEmail removes an email by UID and account ID
726func (m *Inbox) RemoveEmail(uid uint32, accountID string) {
727	// Remove from account-specific list
728	if emails, ok := m.emailsByAccount[accountID]; ok {
729		var filtered []fetcher.Email
730		for _, e := range emails {
731			if e.UID != uid {
732				filtered = append(filtered, e)
733			}
734		}
735		m.emailsByAccount[accountID] = filtered
736	}
737
738	// Remove from all emails list
739	var filteredAll []fetcher.Email
740	for _, e := range m.allEmails {
741		if !(e.UID == uid && e.AccountID == accountID) {
742			filteredAll = append(filteredAll, e)
743		}
744	}
745	m.allEmails = filteredAll
746
747	m.updateList()
748}
749
750// SetSize sets the width and height of the inbox, then updates the list.
751func (m *Inbox) SetSize(width, height int) {
752	m.width = width
753	m.height = height
754	m.list.SetWidth(width)
755	m.list.SetHeight(height / 2)
756}
757
758// SetFolderName sets a custom folder name for the inbox title.
759func (m *Inbox) SetFolderName(name string) {
760	m.folderName = name
761	m.list.Title = m.getTitle()
762}
763
764// SetEmails updates all emails (used after fetch)
765func (m *Inbox) SetEmails(emails []fetcher.Email, accounts []config.Account) {
766	m.accounts = accounts
767	m.allEmails = emails
768	m.noMoreByAccount = make(map[string]bool)
769
770	// Rebuild tabs: empty for single account, "ALL" + accounts for multiple
771	var tabs []AccountTab
772	if len(accounts) <= 1 {
773		tabs = []AccountTab{{ID: "", Label: "", Email: ""}}
774	} else {
775		tabs = []AccountTab{{ID: "", Label: "ALL", Email: ""}}
776		for _, acc := range accounts {
777			tabs = append(tabs, AccountTab{ID: acc.ID, Label: acc.FetchEmail, Email: acc.Email})
778		}
779	}
780	m.tabs = tabs
781
782	// Re-group emails by account
783	m.emailsByAccount = make(map[string][]fetcher.Email)
784	for _, email := range emails {
785		m.emailsByAccount[email.AccountID] = append(m.emailsByAccount[email.AccountID], email)
786	}
787
788	// Update email counts
789	m.emailCountByAcct = make(map[string]int)
790	for accID, accEmails := range m.emailsByAccount {
791		m.emailCountByAcct[accID] = len(accEmails)
792	}
793
794	m.updateList()
795}