composer.go

   1package tui
   2
   3import (
   4	"fmt"
   5	"os"
   6	"path/filepath"
   7	"strings"
   8
   9	"charm.land/bubbles/v2/textarea"
  10	"charm.land/bubbles/v2/textinput"
  11	tea "charm.land/bubbletea/v2"
  12	"charm.land/lipgloss/v2"
  13	"github.com/floatpane/matcha/config"
  14	"github.com/google/uuid"
  15)
  16
  17var (
  18	suggestionStyle         = lipgloss.NewStyle().Foreground(lipgloss.Color("245"))
  19	selectedSuggestionStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("42")).Bold(true)
  20	suggestionBoxStyle      = lipgloss.NewStyle().Border(lipgloss.RoundedBorder()).BorderForeground(lipgloss.Color("245")).Padding(0, 1)
  21)
  22
  23// Styles for the UI
  24var (
  25	focusedStyle        = lipgloss.NewStyle().Foreground(lipgloss.Color("42"))
  26	blurredStyle        = lipgloss.NewStyle().Foreground(lipgloss.Color("245"))
  27	noStyle             = lipgloss.NewStyle()
  28	helpStyle           = lipgloss.NewStyle().Foreground(lipgloss.Color("245"))
  29	emailRecipientStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("42")).Bold(true)
  30	attachmentStyle     = lipgloss.NewStyle().PaddingLeft(4).Foreground(lipgloss.Color("245"))
  31	fromSelectorStyle   = lipgloss.NewStyle().Foreground(lipgloss.Color("42"))
  32	smimeToggleStyle    = lipgloss.NewStyle().PaddingLeft(4).Foreground(lipgloss.Color("245"))
  33)
  34
  35const (
  36	focusFrom = iota
  37	focusTo
  38	focusCc
  39	focusBcc
  40	focusSubject
  41	focusBody
  42	focusSignature
  43	focusAttachment
  44	focusEncryptSMIME
  45	focusSend
  46)
  47
  48// Composer model holds the state of the email composition UI.
  49type Composer struct {
  50	focusIndex       int
  51	toInput          textinput.Model
  52	ccInput          textinput.Model
  53	bccInput         textinput.Model
  54	subjectInput     textinput.Model
  55	bodyInput        textarea.Model
  56	signatureInput   textarea.Model
  57	attachmentPaths  []string
  58	attachmentNames  map[string]string
  59	attachmentCursor int
  60	encryptSMIME     bool
  61	width            int
  62	height           int
  63	confirmingExit   bool
  64	hideTips         bool
  65
  66	// Multi-account support
  67	accounts           []config.Account
  68	selectedAccountIdx int
  69	showAccountPicker  bool
  70	fromInput          textinput.Model // editable From when account is catch-all
  71
  72	// Contact suggestions
  73	suggestions        []config.Contact
  74	selectedSuggestion int
  75	showSuggestions    bool
  76	lastToValue        string
  77
  78	// Draft persistence
  79	draftID string
  80
  81	// Reply context
  82	inReplyTo  string
  83	references []string
  84
  85	// Hidden quoted text (appended to body when sending, but not shown in editor)
  86	quotedText string
  87
  88	// Plugin status text shown in the help bar
  89	pluginStatus      string
  90	pluginKeyBindings []PluginKeyBinding
  91
  92	// Plugin prompt overlay
  93	showPluginPrompt        bool
  94	pluginPromptInput       textinput.Model
  95	pluginPromptPlaceholder string
  96}
  97
  98// NewComposer initializes a new composer model.
  99func NewComposer(from, to, subject, body string, hideTips bool) *Composer {
 100	m := &Composer{
 101		draftID:         uuid.New().String(),
 102		hideTips:        hideTips,
 103		attachmentNames: make(map[string]string),
 104	}
 105
 106	tiStyles := ThemedTextInputStyles()
 107	taStyles := ThemedTextAreaStyles()
 108
 109	m.toInput = textinput.New()
 110	m.toInput.Placeholder = t("composer.to_placeholder")
 111	m.toInput.SetValue(to)
 112	m.toInput.Prompt = "> "
 113	m.toInput.CharLimit = 256
 114	m.toInput.SetStyles(tiStyles)
 115
 116	m.ccInput = textinput.New()
 117	m.ccInput.Placeholder = t("composer.cc_placeholder")
 118	m.ccInput.Prompt = "> "
 119	m.ccInput.CharLimit = 256
 120	m.ccInput.SetStyles(tiStyles)
 121
 122	m.bccInput = textinput.New()
 123	m.bccInput.Placeholder = t("composer.bcc_placeholder")
 124	m.bccInput.Prompt = "> "
 125	m.bccInput.CharLimit = 256
 126	m.bccInput.SetStyles(tiStyles)
 127
 128	m.subjectInput = textinput.New()
 129	m.subjectInput.Placeholder = t("composer.subject_placeholder")
 130	m.subjectInput.SetValue(subject)
 131	m.subjectInput.Prompt = "> "
 132	m.subjectInput.CharLimit = 256
 133	m.subjectInput.SetStyles(tiStyles)
 134
 135	m.bodyInput = textarea.New()
 136	m.bodyInput.Placeholder = t("composer.body_placeholder")
 137	m.bodyInput.SetValue(body)
 138	m.bodyInput.Prompt = "> "
 139	m.bodyInput.SetHeight(10)
 140	m.bodyInput.SetStyles(taStyles)
 141
 142	m.signatureInput = textarea.New()
 143	m.signatureInput.Placeholder = t("composer.signature_placeholder")
 144	m.signatureInput.Prompt = "> "
 145	m.signatureInput.SetHeight(3)
 146	m.signatureInput.SetStyles(taStyles)
 147	m.updateSignature()
 148
 149	m.fromInput = textinput.New()
 150	m.fromInput.Placeholder = t("composer.from_placeholder")
 151	m.fromInput.Prompt = "> "
 152	m.fromInput.CharLimit = 256
 153	m.fromInput.SetStyles(tiStyles)
 154
 155	// Start focus on To field (From is selectable but not a text input)
 156	m.focusIndex = focusTo
 157	m.toInput.Focus()
 158
 159	return m
 160}
 161
 162// updateSignature updates the signature input based on the current selected account.
 163func (m *Composer) updateSignature() {
 164	if len(m.accounts) > 0 && m.selectedAccountIdx < len(m.accounts) {
 165		acc := &m.accounts[m.selectedAccountIdx]
 166		if sig, err := config.LoadSignatureForAccount(acc); err == nil && sig != "" {
 167			m.signatureInput.SetValue(sig)
 168		} else if sig, err := config.LoadSignature(); err == nil && sig != "" {
 169			m.signatureInput.SetValue(sig)
 170		} else {
 171			m.signatureInput.SetValue("")
 172		}
 173		// Seed the editable From address for catch-all accounts.
 174		m.fromInput.SetValue(acc.FormatFromHeader())
 175		return
 176	}
 177
 178	if sig, err := config.LoadSignature(); err == nil && sig != "" {
 179		m.signatureInput.SetValue(sig)
 180	} else {
 181		m.signatureInput.SetValue("")
 182	}
 183}
 184
 185// NewComposerWithAccounts initializes a composer with multiple account support.
 186func NewComposerWithAccounts(accounts []config.Account, selectedAccountID string, to, subject, body string, hideTips bool) *Composer {
 187	m := NewComposer("", to, subject, body, hideTips)
 188	m.accounts = accounts
 189
 190	// Find the selected account index
 191	for i, acc := range accounts {
 192		if acc.ID == selectedAccountID {
 193			m.selectedAccountIdx = i
 194			break
 195		}
 196	}
 197	m.updateSignature()
 198
 199	return m
 200}
 201
 202// ResetConfirmation ensures a restored draft isnt stuck in the exit prompt.
 203func (m *Composer) ResetConfirmation() {
 204	m.confirmingExit = false
 205}
 206
 207// SetFromOverride pre-fills the editable From field (used for catch-all replies).
 208func (m *Composer) SetFromOverride(addr string) {
 209	m.fromInput.SetValue(addr)
 210}
 211
 212func (m *Composer) Init() tea.Cmd {
 213	return textinput.Blink
 214}
 215
 216func (m *Composer) getFromAddress() string {
 217	if len(m.accounts) > 0 && m.selectedAccountIdx < len(m.accounts) {
 218		return m.accounts[m.selectedAccountIdx].FormatFromHeader()
 219	}
 220	return ""
 221}
 222
 223func (m *Composer) isCatchAllAccount() bool {
 224	if len(m.accounts) > 0 && m.selectedAccountIdx < len(m.accounts) {
 225		return m.accounts[m.selectedAccountIdx].CatchAll
 226	}
 227	return false
 228}
 229
 230func (m *Composer) getSelectedAccount() *config.Account {
 231	if len(m.accounts) > 0 && m.selectedAccountIdx < len(m.accounts) {
 232		return &m.accounts[m.selectedAccountIdx]
 233	}
 234	return nil
 235}
 236
 237func formatAttachmentName(path string) string {
 238	name := filepath.Base(path)
 239	info, err := os.Stat(path)
 240	if err != nil || info.IsDir() {
 241		return name
 242	}
 243	return fmt.Sprintf("%s (%s)", name, tfs(info.Size()))
 244}
 245
 246func (m *Composer) attachmentDisplayName(path string) string {
 247	if name, ok := m.attachmentNames[path]; ok {
 248		return name
 249	}
 250	return filepath.Base(path)
 251}
 252
 253func (m *Composer) clampAttachmentCursor() {
 254	if len(m.attachmentPaths) == 0 {
 255		m.attachmentCursor = 0
 256		return
 257	}
 258	if m.attachmentCursor < 0 {
 259		m.attachmentCursor = 0
 260	}
 261	if m.attachmentCursor >= len(m.attachmentPaths) {
 262		m.attachmentCursor = len(m.attachmentPaths) - 1
 263	}
 264}
 265
 266func (m *Composer) removeSelectedAttachment() {
 267	if len(m.attachmentPaths) == 0 {
 268		return
 269	}
 270
 271	m.clampAttachmentCursor()
 272	idx := m.attachmentCursor
 273	delete(m.attachmentNames, m.attachmentPaths[idx])
 274	m.attachmentPaths = append(m.attachmentPaths[:idx], m.attachmentPaths[idx+1:]...)
 275	m.clampAttachmentCursor()
 276}
 277
 278func (m *Composer) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
 279	var cmds []tea.Cmd
 280	var cmd tea.Cmd
 281
 282	switch msg := msg.(type) {
 283	case tea.WindowSizeMsg:
 284		m.width = msg.Width
 285		m.height = msg.Height
 286		inputWidth := msg.Width - 6
 287		m.toInput.SetWidth(inputWidth)
 288		m.ccInput.SetWidth(inputWidth)
 289		m.bccInput.SetWidth(inputWidth)
 290		m.subjectInput.SetWidth(inputWidth)
 291		m.bodyInput.SetWidth(inputWidth)
 292		m.signatureInput.SetWidth(inputWidth)
 293		if msg.Height > 0 {
 294			// Fixed rows: title, from, to, cc, bcc, subject, sig label,
 295			// attachment, smime, button, blank, tip, help = 13
 296			const fixedRows = 13
 297			available := msg.Height - fixedRows
 298			if available < 6 {
 299				available = 6
 300			}
 301			bodyHeight := (available * 55) / 100
 302			sigHeight := (available * 15) / 100
 303			if bodyHeight < 3 {
 304				bodyHeight = 3
 305			}
 306			if sigHeight < 2 {
 307				sigHeight = 2
 308			}
 309			m.bodyInput.SetHeight(bodyHeight)
 310			m.signatureInput.SetHeight(sigHeight)
 311		}
 312
 313	case FileSelectedMsg:
 314		// Avoid duplicates and add all selected paths
 315		for _, newPath := range msg.Paths {
 316			exists := false
 317			for _, p := range m.attachmentPaths {
 318				if p == newPath {
 319					exists = true
 320					break
 321				}
 322			}
 323			if !exists {
 324				m.attachmentPaths = append(m.attachmentPaths, newPath)
 325				m.attachmentNames[newPath] = formatAttachmentName(newPath)
 326			}
 327		}
 328		m.clampAttachmentCursor()
 329		return m, nil
 330
 331	case tea.KeyPressMsg:
 332		// Handle contact suggestions mode
 333		if m.showSuggestions && len(m.suggestions) > 0 {
 334			switch msg.String() {
 335			case "up", "ctrl+p":
 336				if m.selectedSuggestion > 0 {
 337					m.selectedSuggestion--
 338				}
 339				return m, nil
 340			case "down", "ctrl+n":
 341				if m.selectedSuggestion < len(m.suggestions)-1 {
 342					m.selectedSuggestion++
 343				}
 344				return m, nil
 345			case "tab", "enter":
 346				// Select the suggestion
 347				selected := m.suggestions[m.selectedSuggestion]
 348
 349				var newEmail string
 350				if strings.Contains(selected.Email, ",") {
 351					// It's a mailing list: insert just the addresses to maintain valid email formatting
 352					newEmail = selected.Email
 353				} else if selected.Name != "" && selected.Name != selected.Email {
 354					newEmail = fmt.Sprintf("%s <%s>", selected.Name, selected.Email)
 355				} else {
 356					newEmail = selected.Email
 357				}
 358
 359				parts := strings.Split(m.toInput.Value(), ",")
 360				if len(parts) > 0 {
 361					if len(parts) == 1 {
 362						parts[0] = newEmail
 363					} else {
 364						parts[len(parts)-1] = " " + newEmail
 365					}
 366				} else {
 367					parts = []string{newEmail}
 368				}
 369
 370				finalValue := strings.Join(parts, ",")
 371				if !strings.HasSuffix(finalValue, ", ") {
 372					finalValue += ", "
 373				}
 374
 375				m.toInput.SetValue(finalValue)
 376				m.toInput.SetCursor(len(finalValue))
 377				m.lastToValue = m.toInput.Value()
 378				m.showSuggestions = false
 379				m.suggestions = nil
 380				return m, nil
 381			case "esc":
 382				m.showSuggestions = false
 383				m.suggestions = nil
 384				return m, nil
 385			}
 386			// For prev-field key, close suggestions and let it fall through to normal handling
 387			if msg.String() == config.Keybinds.Composer.PrevField {
 388				m.showSuggestions = false
 389				m.suggestions = nil
 390			}
 391		}
 392
 393		// Handle plugin prompt overlay
 394		if m.showPluginPrompt {
 395			switch msg.String() {
 396			case "enter":
 397				value := m.pluginPromptInput.Value()
 398				m.showPluginPrompt = false
 399				return m, func() tea.Msg { return PluginPromptSubmitMsg{Value: value} }
 400			case "esc":
 401				m.showPluginPrompt = false
 402				return m, func() tea.Msg { return PluginPromptCancelMsg{} }
 403			default:
 404				m.pluginPromptInput, cmd = m.pluginPromptInput.Update(msg)
 405				return m, cmd
 406			}
 407		}
 408
 409		// Handle account picker mode
 410		if m.showAccountPicker {
 411			switch msg.String() {
 412			case "up", "k":
 413				if m.selectedAccountIdx > 0 {
 414					m.selectedAccountIdx--
 415					m.updateSignature()
 416				}
 417			case "down", "j":
 418				if m.selectedAccountIdx < len(m.accounts)-1 {
 419					m.selectedAccountIdx++
 420					m.updateSignature()
 421				}
 422			case "enter":
 423				m.showAccountPicker = false
 424			case "esc":
 425				m.showAccountPicker = false
 426			}
 427			return m, nil
 428		}
 429
 430		if m.confirmingExit {
 431			switch msg.String() {
 432			case "y", "Y":
 433				return m, func() tea.Msg { return DiscardDraftMsg{ComposerState: m} }
 434			case "n", "N", "esc":
 435				m.confirmingExit = false
 436				return m, nil
 437			default:
 438				return m, nil
 439			}
 440		}
 441
 442		kb := config.Keybinds
 443		attachmentPathSize := len(m.attachmentPaths)
 444		if m.focusIndex == focusAttachment && attachmentPathSize > 0 {
 445			switch msg.String() {
 446			case "up", kb.Global.NavUp:
 447				m.attachmentCursor = (m.attachmentCursor - 1 + attachmentPathSize) % attachmentPathSize
 448				return m, nil
 449			case "down", kb.Global.NavDown:
 450				m.attachmentCursor = (m.attachmentCursor + 1) % attachmentPathSize
 451				return m, nil
 452			}
 453		}
 454
 455		switch msg.String() {
 456		case kb.Global.Quit:
 457			return m, tea.Quit
 458		case kb.Composer.ExternalEditor:
 459			return m, func() tea.Msg { return OpenEditorMsg{} }
 460		case kb.Global.Cancel:
 461			m.confirmingExit = true
 462			return m, nil
 463
 464		case kb.Composer.NextField, kb.Composer.PrevField:
 465			if msg.String() == kb.Composer.PrevField {
 466				m.focusIndex--
 467			} else {
 468				m.focusIndex++
 469			}
 470
 471			maxFocus := focusSend
 472			minFocus := focusFrom
 473			// Skip From field if only one non-catch-all account (nothing to switch or edit)
 474			if len(m.accounts) <= 1 && !m.isCatchAllAccount() {
 475				minFocus = focusTo
 476			}
 477
 478			if m.focusIndex > maxFocus {
 479				m.focusIndex = minFocus
 480			} else if m.focusIndex < minFocus {
 481				m.focusIndex = maxFocus
 482			}
 483
 484			m.fromInput.Blur()
 485			m.toInput.Blur()
 486			m.ccInput.Blur()
 487			m.bccInput.Blur()
 488			m.subjectInput.Blur()
 489			m.bodyInput.Blur()
 490			m.signatureInput.Blur()
 491
 492			switch m.focusIndex {
 493			case focusFrom:
 494				if m.isCatchAllAccount() {
 495					cmds = append(cmds, m.fromInput.Focus())
 496				}
 497			case focusTo:
 498				cmds = append(cmds, m.toInput.Focus())
 499			case focusCc:
 500				cmds = append(cmds, m.ccInput.Focus())
 501			case focusBcc:
 502				cmds = append(cmds, m.bccInput.Focus())
 503			case focusSubject:
 504				cmds = append(cmds, m.subjectInput.Focus())
 505			case focusBody:
 506				cmds = append(cmds, m.bodyInput.Focus())
 507			case focusSignature:
 508				cmds = append(cmds, m.signatureInput.Focus())
 509			}
 510			return m, tea.Batch(cmds...)
 511
 512		case kb.Composer.Delete:
 513			if m.focusIndex == focusAttachment && len(m.attachmentPaths) > 0 {
 514				m.removeSelectedAttachment()
 515				return m, nil
 516			}
 517
 518		case "enter", " ":
 519			switch m.focusIndex {
 520			case focusFrom:
 521				if msg.String() == "enter" && len(m.accounts) > 1 {
 522					m.showAccountPicker = true
 523					return m, nil
 524				}
 525				if m.isCatchAllAccount() && msg.String() == " " {
 526					break
 527				}
 528				return m, nil
 529			case focusAttachment:
 530				if msg.String() == "enter" {
 531					return m, func() tea.Msg { return GoToFilePickerMsg{} }
 532				}
 533			case focusEncryptSMIME:
 534				if msg.String() == "enter" || msg.String() == " " {
 535					m.encryptSMIME = !m.encryptSMIME
 536				}
 537				return m, nil
 538
 539			case focusSend:
 540				if msg.String() == "enter" {
 541					acc := m.getSelectedAccount()
 542					accountID := ""
 543					if acc != nil {
 544						accountID = acc.ID
 545					}
 546					fromOverride := ""
 547					if m.isCatchAllAccount() {
 548						fromOverride = m.fromInput.Value()
 549					}
 550					return m, func() tea.Msg {
 551						return SendEmailMsg{
 552							To:              m.toInput.Value(),
 553							Cc:              m.ccInput.Value(),
 554							Bcc:             m.bccInput.Value(),
 555							Subject:         m.subjectInput.Value(),
 556							Body:            m.bodyInput.Value(),
 557							AttachmentPaths: m.attachmentPaths,
 558							AccountID:       accountID,
 559							FromOverride:    fromOverride,
 560							QuotedText:      m.quotedText,
 561							InReplyTo:       m.inReplyTo,
 562							References:      m.references,
 563							Signature:       m.signatureInput.Value(),
 564							SignSMIME:       acc != nil && acc.SMIMESignByDefault,
 565							EncryptSMIME:    m.encryptSMIME,
 566							SignPGP:         acc != nil && acc.PGPSignByDefault,
 567						}
 568					}
 569				}
 570			}
 571		}
 572	}
 573
 574	switch m.focusIndex {
 575	case focusFrom:
 576		if m.isCatchAllAccount() {
 577			m.fromInput, cmd = m.fromInput.Update(msg)
 578			cmds = append(cmds, cmd)
 579		}
 580	case focusTo:
 581		m.toInput, cmd = m.toInput.Update(msg)
 582		cmds = append(cmds, cmd)
 583
 584		// Check if To field value changed and update suggestions
 585		currentValue := m.toInput.Value()
 586		if currentValue != m.lastToValue {
 587			m.lastToValue = currentValue
 588
 589			// Extract the last comma-separated part for searching
 590			parts := strings.Split(currentValue, ",")
 591			lastPart := strings.TrimSpace(parts[len(parts)-1])
 592
 593			if len(lastPart) >= 2 {
 594				m.suggestions = config.SearchContactsForAccount(lastPart, m.GetSelectedAccountID())
 595				m.showSuggestions = len(m.suggestions) > 0
 596				m.selectedSuggestion = 0
 597			} else {
 598				m.showSuggestions = false
 599				m.suggestions = nil
 600			}
 601		}
 602	case focusCc:
 603		m.ccInput, cmd = m.ccInput.Update(msg)
 604		cmds = append(cmds, cmd)
 605	case focusBcc:
 606		m.bccInput, cmd = m.bccInput.Update(msg)
 607		cmds = append(cmds, cmd)
 608	case focusSubject:
 609		m.subjectInput, cmd = m.subjectInput.Update(msg)
 610		cmds = append(cmds, cmd)
 611	case focusBody:
 612		m.bodyInput, cmd = m.bodyInput.Update(msg)
 613		cmds = append(cmds, cmd)
 614	case focusSignature:
 615		m.signatureInput, cmd = m.signatureInput.Update(msg)
 616		cmds = append(cmds, cmd)
 617	}
 618
 619	return m, tea.Batch(cmds...)
 620}
 621
 622func (m *Composer) View() tea.View {
 623	var composerView strings.Builder
 624	var button string
 625	ck := config.Keybinds.Composer
 626
 627	if m.focusIndex == focusSend {
 628		button = focusedStyle.Copy().Render("[ " + t("composer.send") + " ]")
 629	} else {
 630		button = blurredStyle.Copy().Render("[ " + t("composer.send") + " ]")
 631	}
 632
 633	// From field with account selector
 634	fromAddr := m.getFromAddress()
 635	var fromField string
 636	if m.isCatchAllAccount() {
 637		fromAddrView := m.fromInput.View()
 638		if len(m.accounts) > 1 {
 639			if m.focusIndex == focusFrom {
 640				fromField = focusedStyle.Render(fmt.Sprintf("> %s ", t("composer.from"))) + fromAddrView + " " + blurredStyle.Render("["+t("composer.enter_to_switch")+"]")
 641			} else {
 642				fromField = blurredStyle.Render(fmt.Sprintf("  %s ", t("composer.from"))) + fromAddrView + " " + blurredStyle.Render("["+t("composer.switchable")+"]")
 643			}
 644		} else {
 645			fromField = "  " + t("composer.from") + " " + fromAddrView
 646		}
 647	} else if len(m.accounts) > 1 {
 648		if m.focusIndex == focusFrom {
 649			fromField = focusedStyle.Render(fmt.Sprintf("> %s %s [%s]", t("composer.from"), fromAddr, t("composer.enter_to_switch")))
 650		} else {
 651			fromField = blurredStyle.Render(fmt.Sprintf("  %s %s [%s]", t("composer.from"), fromAddr, t("composer.switchable")))
 652		}
 653	} else if fromAddr != "" {
 654		fromField = "  " + t("composer.from") + " " + emailRecipientStyle.Render(fromAddr)
 655	} else {
 656		fromField = blurredStyle.Render(fmt.Sprintf("  %s (%s)", t("composer.from"), t("composer.no_account")))
 657	}
 658
 659	var attachmentField string
 660	if len(m.attachmentPaths) == 0 {
 661		attachmentText := fmt.Sprintf("%s (%s)", t("composer.attachments_none"), t("composer.enter_to_add"))
 662		if m.focusIndex == focusAttachment {
 663			attachmentField = focusedStyle.Render(fmt.Sprintf("> %s %s", t("composer.attachments"), attachmentText))
 664		} else {
 665			attachmentField = blurredStyle.Render(fmt.Sprintf("  %s %s", t("composer.attachments"), attachmentText))
 666		}
 667	} else {
 668		var b strings.Builder
 669		headerPrefix := "  "
 670		headerStyle := blurredStyle
 671		if m.focusIndex == focusAttachment {
 672			headerPrefix = "> "
 673			headerStyle = focusedStyle
 674		}
 675		b.WriteString(headerStyle.Render(fmt.Sprintf("%s%s (%d):", headerPrefix, t("composer.attachments"), len(m.attachmentPaths))))
 676		for i, p := range m.attachmentPaths {
 677			cursor := "    "
 678			style := blurredStyle
 679			if m.focusIndex == focusAttachment && i == m.attachmentCursor {
 680				cursor = "  > "
 681				style = focusedStyle
 682			}
 683			b.WriteString("\n")
 684			b.WriteString(style.Render(fmt.Sprintf("%s%s", cursor, m.attachmentDisplayName(p))))
 685		}
 686		attachmentField = b.String()
 687	}
 688
 689	encToggle := "[ ]"
 690	if m.encryptSMIME {
 691		encToggle = "[x]"
 692	}
 693	encField := blurredStyle.Render(fmt.Sprintf("  %s %s", t("composer.encrypt_smime"), encToggle))
 694	if m.focusIndex == focusEncryptSMIME {
 695		encField = focusedStyle.Render(fmt.Sprintf("> %s %s", t("composer.encrypt_smime"), encToggle))
 696	}
 697
 698	// Build To field with suggestions
 699	toFieldView := m.toInput.View()
 700	if m.showSuggestions && len(m.suggestions) > 0 {
 701		var suggestionsBuilder strings.Builder
 702		for i, s := range m.suggestions {
 703			display := s.Email
 704			if s.Name != "" && s.Name != s.Email {
 705				display = fmt.Sprintf("%s <%s>", s.Name, s.Email)
 706			}
 707			if i == m.selectedSuggestion {
 708				suggestionsBuilder.WriteString(selectedSuggestionStyle.Render("> "+display) + "\n")
 709			} else {
 710				suggestionsBuilder.WriteString(suggestionStyle.Render("  "+display) + "\n")
 711			}
 712		}
 713		toFieldView = toFieldView + "\n" + suggestionBoxStyle.Render(strings.TrimSuffix(suggestionsBuilder.String(), "\n"))
 714	}
 715
 716	// Signature field label
 717	var signatureLabel string
 718	if m.focusIndex == focusSignature {
 719		signatureLabel = focusedStyle.Render(t("composer.signature") + ":")
 720	} else {
 721		signatureLabel = blurredStyle.Render(t("composer.signature") + ":")
 722	}
 723
 724	tip := ""
 725	switch m.focusIndex {
 726	case focusFrom:
 727		tip = "Select the account to send from."
 728	case focusTo:
 729		tip = "Enter recipient email addresses."
 730	case focusCc:
 731		tip = "Carbon copy recipients."
 732	case focusBcc:
 733		tip = "Blind carbon copy recipients."
 734	case focusSubject:
 735		tip = "The subject line of your email."
 736	case focusBody:
 737		tip = "The main content of your email. Markdown and HTML are supported."
 738	case focusSignature:
 739		tip = "Your email signature. This will be appended to the end of the email."
 740	case focusAttachment:
 741		tip = fmt.Sprintf("Enter: add file • up/down: select attachment • %s: remove selected", ck.Delete)
 742	case focusEncryptSMIME:
 743		tip = "Press Space or Enter to toggle S/MIME encryption on or off."
 744	case focusSend:
 745		tip = "Press Enter to send the email."
 746	}
 747
 748	composerViewElements := []string{
 749		t("composer.title"),
 750		fromField,
 751		toFieldView,
 752		m.ccInput.View(),
 753		m.bccInput.View(),
 754		m.subjectInput.View(),
 755		m.bodyInput.View(),
 756		signatureLabel,
 757		m.signatureInput.View(),
 758		attachmentStyle.Render(attachmentField),
 759	}
 760	if len(m.attachmentPaths) > 0 {
 761		composerViewElements = append(composerViewElements, "")
 762	}
 763	composerViewElements = append(composerViewElements,
 764		smimeToggleStyle.Render(encField),
 765		button,
 766		"",
 767	)
 768
 769	if !m.hideTips && tip != "" {
 770		composerViewElements = append(composerViewElements, TipStyle.Render("Tip: "+tip))
 771	}
 772
 773	mainContent := lipgloss.JoinVertical(lipgloss.Left, composerViewElements...)
 774	helpText := t("composer.help")
 775	for _, pk := range m.pluginKeyBindings {
 776		helpText += " • " + pk.Key + ": " + pk.Description
 777	}
 778	if m.pluginStatus != "" {
 779		helpText += " • " + m.pluginStatus
 780	}
 781	helpView := helpStyle.Render(helpText)
 782
 783	if m.height > 0 {
 784		currentHeight := lipgloss.Height(mainContent) + lipgloss.Height(helpView)
 785		gap := m.height - currentHeight
 786		if gap >= 0 {
 787			mainContent += strings.Repeat("\n", gap+1)
 788		} else {
 789			mainContent += "\n"
 790		}
 791	} else {
 792		mainContent += "\n\n"
 793	}
 794
 795	composerView.WriteString(mainContent)
 796	composerView.WriteString(helpView)
 797
 798	// Plugin prompt overlay
 799	if m.showPluginPrompt {
 800		dialog := DialogBoxStyle.Render(
 801			lipgloss.JoinVertical(lipgloss.Left,
 802				m.pluginPromptPlaceholder,
 803				"",
 804				m.pluginPromptInput.View(),
 805				"",
 806				HelpStyle.Render("enter: submit • esc: cancel"),
 807			),
 808		)
 809		return tea.NewView(lipgloss.Place(m.width, m.height, lipgloss.Center, lipgloss.Center, dialog))
 810	}
 811
 812	// Account picker overlay
 813	if m.showAccountPicker {
 814		var accountList strings.Builder
 815		accountList.WriteString("Select Account:\n\n")
 816		for i, acc := range m.accounts {
 817			display := acc.GetSendAsEmail()
 818			if acc.Name != "" {
 819				display = fmt.Sprintf("%s (%s)", acc.Name, acc.GetSendAsEmail())
 820			}
 821			if i == m.selectedAccountIdx {
 822				accountList.WriteString(selectedItemStyle.Render(fmt.Sprintf("> %s", display)))
 823			} else {
 824				accountList.WriteString(itemStyle.Render(fmt.Sprintf("  %s", display)))
 825			}
 826			accountList.WriteString("\n")
 827		}
 828		accountList.WriteString("\n")
 829		accountList.WriteString(HelpStyle.Render("↑/↓: navigate • enter: select • esc: cancel"))
 830
 831		dialog := DialogBoxStyle.Render(accountList.String())
 832		return tea.NewView(lipgloss.Place(m.width, m.height, lipgloss.Center, lipgloss.Center, dialog))
 833	}
 834
 835	if m.confirmingExit {
 836		dialog := DialogBoxStyle.Render(
 837			lipgloss.JoinVertical(lipgloss.Center,
 838				t("composer.exit_confirm"),
 839				HelpStyle.Render("\n(y/n)"),
 840			),
 841		)
 842		return tea.NewView(lipgloss.Place(m.width, m.height, lipgloss.Center, lipgloss.Center, dialog))
 843	}
 844
 845	return tea.NewView(composerView.String())
 846}
 847
 848// SetAccounts sets the available accounts for sending.
 849func (m *Composer) SetAccounts(accounts []config.Account) {
 850	m.accounts = accounts
 851	if m.selectedAccountIdx >= len(accounts) {
 852		m.selectedAccountIdx = 0
 853	}
 854	m.updateSignature()
 855}
 856
 857// SetSelectedAccount sets the selected account by ID.
 858func (m *Composer) SetSelectedAccount(accountID string) {
 859	for i, acc := range m.accounts {
 860		if acc.ID == accountID {
 861			m.selectedAccountIdx = i
 862			m.updateSignature()
 863			return
 864		}
 865	}
 866}
 867
 868// GetSelectedAccountID returns the ID of the currently selected account.
 869func (m *Composer) GetSelectedAccountID() string {
 870	if len(m.accounts) > 0 && m.selectedAccountIdx < len(m.accounts) {
 871		return m.accounts[m.selectedAccountIdx].ID
 872	}
 873	return ""
 874}
 875
 876// GetDraftID returns the draft ID for this composer.
 877func (m *Composer) GetDraftID() string {
 878	return m.draftID
 879}
 880
 881// SetDraftID sets the draft ID (for loading existing drafts).
 882func (m *Composer) SetDraftID(id string) {
 883	m.draftID = id
 884}
 885
 886// GetTo returns the current To field value.
 887func (m *Composer) GetTo() string {
 888	return m.toInput.Value()
 889}
 890
 891// SetTo updates the To field with new content.
 892func (m *Composer) SetTo(to string) {
 893	m.toInput.SetValue(to)
 894}
 895
 896// GetCc returns the current Cc field value.
 897func (m *Composer) GetCc() string {
 898	return m.ccInput.Value()
 899}
 900
 901// SetCc updates the Cc field with new content.
 902func (m *Composer) SetCc(cc string) {
 903	m.ccInput.SetValue(cc)
 904}
 905
 906// GetBcc returns the current Bcc field value.
 907func (m *Composer) GetBcc() string {
 908	return m.bccInput.Value()
 909}
 910
 911// SetBcc updates the Bcc field with new content.
 912func (m *Composer) SetBcc(bcc string) {
 913	m.bccInput.SetValue(bcc)
 914}
 915
 916// GetSubject returns the current Subject field value.
 917func (m *Composer) GetSubject() string {
 918	return m.subjectInput.Value()
 919}
 920
 921// SetSubject updates the Subject field with new content.
 922func (m *Composer) SetSubject(subject string) {
 923	m.subjectInput.SetValue(subject)
 924}
 925
 926// GetBody returns the current Body field value.
 927func (m *Composer) GetBody() string {
 928	return m.bodyInput.Value()
 929}
 930
 931// SetBody updates the Body field with new content.
 932func (m *Composer) SetBody(body string) {
 933	m.bodyInput.SetValue(body)
 934}
 935
 936// GetAttachmentPaths returns the current attachment paths.
 937func (m *Composer) GetAttachmentPaths() []string {
 938	return m.attachmentPaths
 939}
 940
 941// GetSignature returns the current signature value.
 942func (m *Composer) GetSignature() string {
 943	return m.signatureInput.Value()
 944}
 945
 946// SetReplyContext sets the reply context for the draft.
 947func (m *Composer) SetReplyContext(inReplyTo string, references []string) {
 948	m.inReplyTo = inReplyTo
 949	m.references = references
 950}
 951
 952// SetQuotedText sets the hidden quoted text that will be appended when sending.
 953func (m *Composer) SetQuotedText(text string) {
 954	m.quotedText = text
 955}
 956
 957// GetQuotedText returns the hidden quoted text.
 958func (m *Composer) GetQuotedText() string {
 959	return m.quotedText
 960}
 961
 962// GetInReplyTo returns the In-Reply-To header value.
 963func (m *Composer) GetInReplyTo() string {
 964	return m.inReplyTo
 965}
 966
 967// GetReferences returns the References header values.
 968func (m *Composer) GetReferences() []string {
 969	return m.references
 970}
 971
 972// SetPluginStatus sets a persistent status string from plugins, shown in the help bar.
 973func (m *Composer) SetPluginStatus(status string) {
 974	m.pluginStatus = status
 975}
 976
 977// SetPluginKeyBindings sets the plugin-registered key bindings for display in the help bar.
 978func (m *Composer) SetPluginKeyBindings(bindings []PluginKeyBinding) {
 979	m.pluginKeyBindings = bindings
 980}
 981
 982// ShowPluginPrompt activates the plugin prompt overlay with the given placeholder text.
 983func (m *Composer) ShowPluginPrompt(placeholder string) {
 984	m.pluginPromptPlaceholder = placeholder
 985	m.pluginPromptInput = textinput.New()
 986	m.pluginPromptInput.Placeholder = placeholder
 987	m.pluginPromptInput.Prompt = "> "
 988	m.pluginPromptInput.CharLimit = 256
 989	m.pluginPromptInput.Focus()
 990	m.showPluginPrompt = true
 991}
 992
 993// HidePluginPrompt deactivates the plugin prompt overlay.
 994func (m *Composer) HidePluginPrompt() {
 995	m.showPluginPrompt = false
 996}
 997
 998// ToDraft converts the composer state to a Draft for saving.
 999func (m *Composer) ToDraft() config.Draft {
1000	return config.Draft{
1001		ID:              m.draftID,
1002		To:              m.toInput.Value(),
1003		Cc:              m.ccInput.Value(),
1004		Bcc:             m.bccInput.Value(),
1005		Subject:         m.subjectInput.Value(),
1006		Body:            m.bodyInput.Value(),
1007		AttachmentPaths: m.attachmentPaths,
1008		AccountID:       m.GetSelectedAccountID(),
1009		FromOverride:    m.fromInput.Value(),
1010		InReplyTo:       m.inReplyTo,
1011		References:      m.references,
1012		QuotedText:      m.quotedText,
1013	}
1014}
1015
1016// NewComposerFromDraft creates a composer from an existing draft.
1017func NewComposerFromDraft(draft config.Draft, accounts []config.Account, hideTips bool) *Composer {
1018	m := NewComposerWithAccounts(accounts, draft.AccountID, draft.To, draft.Subject, draft.Body, hideTips)
1019	m.ccInput.SetValue(draft.Cc)
1020	m.bccInput.SetValue(draft.Bcc)
1021	m.draftID = draft.ID
1022	m.attachmentPaths = draft.AttachmentPaths
1023	m.attachmentNames = make(map[string]string, len(m.attachmentPaths))
1024	for _, path := range m.attachmentPaths {
1025		m.attachmentNames[path] = formatAttachmentName(path)
1026	}
1027	m.clampAttachmentCursor()
1028	if m.isCatchAllAccount() && draft.FromOverride != "" {
1029		m.fromInput.SetValue(draft.FromOverride)
1030	}
1031	m.inReplyTo = draft.InReplyTo
1032	m.references = draft.References
1033	m.quotedText = draft.QuotedText
1034	return m
1035}