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
package main

import (
	"context"
	"encoding/json"
	"flag"
	"fmt"
	"os"
	"sort"
	"strings"
	"time"

	tea "github.com/charmbracelet/bubbletea"
	"github.com/charmbracelet/lipgloss"
)

// StashInfo represents a git stash entry
type StashInfo struct {
	Ref     string // e.g., "stash@{0}"
	Message string
}

// CommitInfo represents a single commit
type CommitInfo struct {
	Hash    string
	Subject string
	Author  string
	Date    time.Time
	Stashes []StashInfo // stashes based on this commit
}

// BranchInfo represents information about a git branch
type BranchInfo struct {
	Name              string
	CurrentCommit     string
	IsCurrentBranch   bool
	IsRemote          bool // True if this is a remote branch
	LastCommitMessage string
	LastCommitAuthor  string
	LastCommitDate    time.Time
	UpstreamBranch    string
	ParentCandidates  []ParentCandidate
	PrefixShared      []PrefixSharedBranch
	CommitsAhead      int
	CommitsBehind     int
	// Remote tracking information
	RemoteCounterpart        string          // e.g., "origin/feature-branch"
	CommitsMissingFromRemote []string        // commit hashes in local not in remote
	CommitsMissingFromLocal  []string        // commit hashes in remote not in local
	AmendedCommits           []AmendedCommit // commits that appear amended between local and remote
	// Recent commits for detail view
	RecentCommits []CommitInfo
	// Stash count (stashes based on last 10 commits)
	StashCount int
}

// ParentCandidate represents a potential parent branch
type ParentCandidate struct {
	BranchName     string
	Method         string // "upstream", "merge-base", "patch-id-prefix"
	CommonAncestor string
}

// PrefixSharedBranch represents a branch that shares a patch-id prefix
type PrefixSharedBranch struct {
	BranchName         string
	CurrentCommit      string // commit hash this branch points to
	SharedPrefixLength int
	TotalInBranch      int
	TotalInCurrent     int
	Diverged           bool
}

// AmendedCommit represents a commit that appears to be the same logical change
// but with different hash (due to rebase/amend)
type AmendedCommit struct {
	LocalCommit   string  // hash in local branch
	RemoteCommit  string  // hash in remote branch
	LocalMessage  string  // commit message in local
	RemoteMessage string  // commit message in remote
	Similarity    float64 // 0.0-1.0 similarity score from nilsimsa
	LocalPatchId  string  // patch-id of local commit
	RemotePatchId string  // patch-id of remote commit
	// Note: Same patch-id = pure rebase (metadata only)
	//       Different patch-id = actual amendment (code changed)
}

// LoadingState represents the current loading state
type LoadingState int

const (
	LoadingBranches LoadingState = iota
	EnrichingBranches
	LoadingComplete
)

// ViewMode represents the current view mode
type ViewMode int

const (
	ViewModeList ViewMode = iota
	ViewModeDetail
)

// Model is the main Bubble Tea model
type Model struct {
	branches      []BranchInfo
	allBranches   []BranchInfo // Includes remote branches for enrichment
	selectedRow   int
	viewportStart int
	pageSize      int
	windowWidth   int
	windowHeight  int
	loadingState  LoadingState
	err           error
	ctx           context.Context
	cancel        context.CancelFunc
	viewMode      ViewMode
	detailBranch  *BranchInfo
	detailLoading bool
	patchIdCache  map[string][]string
}

// Messages
type branchesLoadedMsg struct {
	branches []BranchInfo
}

type branchesErrorMsg struct {
	err error
}

type showBranchDetailsMsg struct {
	branchName string
}

type branchDetailLoadedMsg struct {
	branch       BranchInfo
	patchIdCache map[string][]string
}

type branchDetailErrorMsg struct {
	err error
}

type checkoutCompleteMsg struct {
	branchName string
}

type checkoutErrorMsg struct {
	err error
}

func main() {
	// Unset CI environment variable to enable interactive mode in Bubble Tea
	// (muesli/termenv checks CI and disables TTY detection if set)
	os.Unsetenv("CI")

	jsonOutput := flag.Bool("json", false, "output branch information as JSON")
	flag.Parse()

	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()

	if *jsonOutput {
		if err := outputJSON(ctx); err != nil {
			fmt.Fprintf(os.Stderr, "Error: %v\n", err)
			os.Exit(1)
		}
		return
	}

	m := Model{
		ctx:          ctx,
		cancel:       cancel,
		viewMode:     ViewModeList,
		patchIdCache: make(map[string][]string),
		pageSize:     20, // Default page size until WindowSizeMsg arrives
	}

	p := tea.NewProgram(m, tea.WithAltScreen())
	if _, err := p.Run(); err != nil {
		fmt.Fprintf(os.Stderr, "Error: %v\n", err)
		os.Exit(1)
	}
}

// outputJSON outputs branch information as JSON
func outputJSON(ctx context.Context) error {
	// Create root timing span
	rootSpan := NewRootSpan("git-branchey")
	ctx = WithRootSpan(ctx, rootSpan)

	branches, err := getBranches(ctx)
	if err != nil {
		return fmt.Errorf("getting branches: %w", err)
	}

	// Separate local and remote branches
	// We only enrich and output local branches, but use remote branches for parent detection
	var localBranches []BranchInfo
	for _, branch := range branches {
		if !branch.IsRemote {
			localBranches = append(localBranches, branch)
		}
	}

	// Enrich local branches with parent information (4-phase approach, including patch-ids for JSON output)
	localBranches = enrichLocalBranchesWithParentInfo(ctx, localBranches, branches, false)

	// Output only local branches (enriched)
	encoder := json.NewEncoder(os.Stdout)
	encoder.SetIndent("", "  ")
	encodeErr := encoder.Encode(localBranches)

	// Print timing statistics
	printNestedTimingStats(rootSpan)

	return encodeErr
}

// Init initializes the model
func (m Model) Init() tea.Cmd {
	return tea.Batch(
		loadBranches(m.ctx),
		tea.EnterAltScreen,
	)
}

// Update handles messages
func (m Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
	switch msg := msg.(type) {
	case tea.KeyMsg:
		switch msg.String() {
		case "ctrl+c", "ctrl+q":
			m.cancel()
			return m, tea.Quit
		case "q":
			// q exits detail view if in detail mode, exits program from list mode
			if m.viewMode == ViewModeDetail {
				m.viewMode = ViewModeList
				m.detailBranch = nil
				m.detailLoading = false
				return m, nil
			}
			// Exit program from list view
			m.cancel()
			return m, tea.Quit
		case "esc":
			// Esc also exits detail view
			if m.viewMode == ViewModeDetail {
				m.viewMode = ViewModeList
				m.detailBranch = nil
				m.detailLoading = false
				return m, nil
			}
		case "c":
			// Checkout selected branch (only in list mode and when loaded)
			if m.viewMode == ViewModeList && m.loadingState == LoadingComplete && len(m.branches) > 0 {
				selectedBranch := m.branches[m.selectedRow]
				// Don't checkout if already on this branch
				if !selectedBranch.IsCurrentBranch {
					return m, checkoutBranch(m.ctx, selectedBranch.Name)
				}
			}
		case "enter":
			// Show detail view for selected branch (only in list mode and when loaded)
			if m.viewMode == ViewModeList && m.loadingState == LoadingComplete && len(m.branches) > 0 {
				selectedBranch := m.branches[m.selectedRow]
				m.viewMode = ViewModeDetail
				m.detailLoading = true
				return m, loadBranchDetails(m.ctx, selectedBranch, m.allBranches, m.patchIdCache)
			}
		case "j", "down":
			if m.selectedRow < len(m.branches)-1 {
				m.selectedRow++
				if m.selectedRow >= m.viewportStart+m.pageSize {
					m.viewportStart = m.selectedRow - m.pageSize + 1
				}
			}
		case "k", "up":
			if m.selectedRow > 0 {
				m.selectedRow--
				if m.selectedRow < m.viewportStart {
					m.viewportStart = m.selectedRow
				}
			}
		case "g":
			m.selectedRow = 0
			m.viewportStart = 0
		case "G":
			m.selectedRow = len(m.branches) - 1
			if m.selectedRow >= m.pageSize {
				m.viewportStart = m.selectedRow - m.pageSize + 1
			} else {
				m.viewportStart = 0
			}
		case "pgup":
			m.selectedRow -= m.pageSize
			if m.selectedRow < 0 {
				m.selectedRow = 0
			}
			m.viewportStart = m.selectedRow
		case "pgdown":
			if len(m.branches) > 0 {
				m.selectedRow += m.pageSize
				if m.selectedRow >= len(m.branches) {
					m.selectedRow = len(m.branches) - 1
				}
				// Adjust viewport to keep selection visible
				if m.selectedRow >= m.viewportStart+m.pageSize {
					m.viewportStart = m.selectedRow - m.pageSize + 1
				}
			}
		}

	case tea.WindowSizeMsg:
		m.windowWidth = msg.Width
		m.windowHeight = msg.Height
		// Reserve space for header (3 lines) and footer (2 lines)
		m.pageSize = max(msg.Height-5, 1)

	case branchesLoadedMsg:
		m.allBranches = msg.branches // Store all branches (including remote)
		// Filter for local branches to display
		var localBranches []BranchInfo
		for _, branch := range msg.branches {
			if !branch.IsRemote {
				localBranches = append(localBranches, branch)
			}
		}
		m.branches = localBranches
		m.loadingState = EnrichingBranches
		return m, enrichBranchesWithParents(m.ctx, msg.branches)

	case branchesEnrichedMsg:
		m.branches = msg.branches
		// Sort branches by most recently updated first
		sort.Slice(m.branches, func(i, j int) bool {
			return m.branches[i].LastCommitDate.After(m.branches[j].LastCommitDate)
		})
		// Ensure selectedRow is within bounds
		if m.selectedRow >= len(m.branches) {
			m.selectedRow = len(m.branches) - 1
		}
		if m.selectedRow < 0 {
			m.selectedRow = 0
		}
		m.loadingState = LoadingComplete
		return m, nil

	case branchesErrorMsg:
		m.err = msg.err
		m.loadingState = LoadingComplete
		return m, nil

	case branchDetailLoadedMsg:
		m.detailBranch = &msg.branch
		m.patchIdCache = msg.patchIdCache
		m.detailLoading = false
		return m, nil

	case branchDetailErrorMsg:
		m.err = msg.err
		m.detailLoading = false
		m.viewMode = ViewModeList // Return to list on error
		return m, nil

	case checkoutCompleteMsg:
		// Reload branches after successful checkout
		return m, loadBranches(m.ctx)

	case checkoutErrorMsg:
		m.err = msg.err
		return m, nil
	}

	return m, nil
}

// View renders the UI
func (m Model) View() string {
	if m.err != nil {
		return fmt.Sprintf("Error: %v\n\nPress q to quit.", m.err)
	}

	if m.loadingState == LoadingBranches {
		return "Loading branches..."
	}

	if m.loadingState == EnrichingBranches {
		return fmt.Sprintf("Loading branches... (found %d, detecting parents...)", len(m.branches))
	}

	if len(m.branches) == 0 {
		return "No branches found.\n\nPress q to quit."
	}

	// Render detail view if in detail mode
	if m.viewMode == ViewModeDetail {
		return m.renderDetailView()
	}

	// Render list view (default)
	return m.renderListView()
}

// renderListView renders the branch list view
func (m Model) renderListView() string {

	// Header
	header := lipgloss.NewStyle().
		Bold(true).
		Foreground(lipgloss.Color("15")).
		Render("Git Branches")

	// Create table with columns
	columns := []TableColumn{
		{
			Name:  "",
			Width: 1,
			Align: lipgloss.Left,
			RenderCell: func(data any) string {
				branch := data.(BranchInfo)
				if branch.IsCurrentBranch {
					return "*"
				}
				return " "
			},
		},
		{
			Name:  "Branch",
			Width: 30,
			Align: lipgloss.Left,
			RenderCell: func(data any) string {
				branch := data.(BranchInfo)
				return branch.Name
			},
		},
		{
			Name:  "Parent",
			Width: 25,
			Align: lipgloss.Left,
			RenderCell: func(data any) string {
				branch := data.(BranchInfo)
				if len(branch.ParentCandidates) == 0 {
					return "-"
				}

				bestParent := branch.ParentCandidates[0]
				parent := bestParent.BranchName

				// Add method indicator
				switch bestParent.Method {
				case "upstream-tracking":
					parent = parent + "⬆?" // upstream tracking (potentially stale)
				case "patch-id-prefix", "patch-id-shared":
					parent = parent + "↻" // rebased
				case "ancestor-walk":
					// No indicator for ancestor-walk (most common natural parent)
				}

				return parent
			},
		},
		{
			Name:  "Ahead/Behind",
			Width: 12,
			Align: lipgloss.Left,
			RenderCell: func(data any) string {
				branch := data.(BranchInfo)
				if branch.CommitsAhead > 0 || branch.CommitsBehind > 0 {
					return fmt.Sprintf("+%d/-%d", branch.CommitsAhead, branch.CommitsBehind)
				}
				return "-"
			},
		},
		{
			Name:  "Stashes",
			Width: 7,
			Align: lipgloss.Left,
			RenderCell: func(data any) string {
				branch := data.(BranchInfo)
				if branch.StashCount > 0 {
					return fmt.Sprintf("%d", branch.StashCount)
				}
				return "-"
			},
		},
		{
			Name:  "Updated",
			Width: 0, // Auto-expand to fill remaining width
			Align: lipgloss.Left,
			RenderCell: func(data any) string {
				branch := data.(BranchInfo)
				return formatRelativeTime(branch.LastCommitDate)
			},
		},
	}

	// Calculate visible range
	start := m.viewportStart
	end := min(start+m.pageSize, len(m.branches))

	// Check scroll position for border indicators
	isAtTop := (m.viewportStart == 0)
	isAtBottom := (end >= len(m.branches))

	// Create border with scroll indicators
	border := lipgloss.RoundedBorder()
	if !isAtTop {
		// Not at top - show continuation indicator
		border.Top = ""
		border.TopLeft = "┊"
		border.TopRight = "┊"
	}
	if !isAtBottom {
		// Not at bottom - show continuation indicator
		border.Bottom = ""
		border.BottomLeft = "┊"
		border.BottomRight = "┊"
	}

	// Account for border in table width calculation
	borderStyle := lipgloss.NewStyle().
		Border(border).
		BorderForeground(lipgloss.Color("240"))

	borderFrameSize := borderStyle.GetHorizontalFrameSize()
	tableWidth := max(m.windowWidth-borderFrameSize, 20)

	table := NewTable(columns, tableWidth)

	// Render table header (color changes based on scroll position)
	headerRow := table.RenderHeader(isAtTop)

	// Render branch rows
	var tableRows []string
	tableRows = append(tableRows, headerRow)

	for i := start; i < end; i++ {
		branch := m.branches[i]
		if i == m.selectedRow {
			tableRows = append(tableRows, table.RenderRowWithBackground(branch, lipgloss.Color("240")))
		} else {
			tableRows = append(tableRows, table.RenderRow(branch))
		}
	}

	// Join table content and add border
	tableContent := lipgloss.JoinVertical(lipgloss.Left, tableRows...)
	borderedTable := borderStyle.Render(tableContent)

	// Footer
	footer := fmt.Sprintf("\nShowing %d-%d of %d branches | j/k/PgUp/PgDown: navigate | g/G: top/bottom | c: checkout | Enter: details | q/Ctrl+C: quit",
		start+1, end, len(m.branches))

	return lipgloss.JoinVertical(lipgloss.Left, header, "", borderedTable, footer)
}

// renderDetailView renders the detailed view for a single branch
func (m Model) renderDetailView() string {
	if m.detailLoading {
		return "Loading branch details..."
	}

	if m.detailBranch == nil {
		return "No branch selected.\n\nPress Esc to return to list."
	}

	branch := *m.detailBranch

	// Title
	title := lipgloss.NewStyle().
		Bold(true).
		Foreground(lipgloss.Color("15")).
		Render(fmt.Sprintf("Branch Details: %s", branch.Name))

	// Build detail sections
	var sections []string

	// Section 1: Basic Info
	basicInfo := lipgloss.NewStyle().
		Border(lipgloss.RoundedBorder()).
		BorderForeground(lipgloss.Color("240")).
		Padding(1, 2).
		Render(fmt.Sprintf(
			"Commit: %s\nLast Update: %s\nAuthor: %s\nMessage: %s",
			branch.CurrentCommit[:12],
			formatRelativeTime(branch.LastCommitDate),
			branch.LastCommitAuthor,
			branch.LastCommitMessage,
		))
	sections = append(sections, lipgloss.NewStyle().Bold(true).Render("Basic Information"))
	sections = append(sections, basicInfo)

	// Section 2: Parent Information
	if len(branch.ParentCandidates) > 0 {
		var parentLines []string
		for i, parent := range branch.ParentCandidates {
			indicator := ""
			if i == 0 {
				indicator = "★ "
			}
			parentLines = append(parentLines, fmt.Sprintf(
				"%s%s (method: %s, common ancestor: %s)",
				indicator,
				parent.BranchName,
				parent.Method,
				parent.CommonAncestor[:12],
			))
		}
		parentInfo := lipgloss.NewStyle().
			Border(lipgloss.RoundedBorder()).
			BorderForeground(lipgloss.Color("240")).
			Padding(1, 2).
			Render(strings.Join(parentLines, "\n"))
		sections = append(sections, "")
		sections = append(sections, lipgloss.NewStyle().Bold(true).Render("Parent Candidates"))
		sections = append(sections, parentInfo)
	}

	// Section 3: Related Branches (PrefixShared)
	if len(branch.PrefixShared) > 0 {
		var relatedLines []string
		for _, related := range branch.PrefixShared {
			var description string

			// Check if they point to the exact same commit
			if branch.CurrentCommit == related.CurrentCommit {
				description = fmt.Sprintf(
					"%s - identical (same commit: %s)",
					related.BranchName,
					related.CurrentCommit[:12],
				)
			} else if !related.Diverged && related.SharedPrefixLength == related.TotalInCurrent && related.SharedPrefixLength == related.TotalInBranch {
				// Same number of commits but different commit IDs - likely rebased
				description = fmt.Sprintf(
					"%s - rebased/amended (same %d changes, different commits)",
					related.BranchName,
					related.SharedPrefixLength,
				)
			} else if !related.Diverged && related.SharedPrefixLength == related.TotalInCurrent {
				// All our commits are in the other branch (we might be behind)
				description = fmt.Sprintf(
					"%s - contains all our commits (%d/%d, +%d in their branch)",
					related.BranchName,
					related.SharedPrefixLength,
					related.TotalInBranch,
					related.TotalInBranch-related.SharedPrefixLength,
				)
			} else if !related.Diverged && related.SharedPrefixLength == related.TotalInBranch {
				// All their commits are in our branch (they might be behind us)
				description = fmt.Sprintf(
					"%s - we contain all their commits (%d/%d, +%d in our branch)",
					related.BranchName,
					related.SharedPrefixLength,
					related.TotalInCurrent,
					related.TotalInCurrent-related.SharedPrefixLength,
				)
			} else if related.Diverged {
				// Diverged - shared prefix but both have unique commits
				description = fmt.Sprintf(
					"%s - diverged (shared: %d, ours: %d, theirs: %d)",
					related.BranchName,
					related.SharedPrefixLength,
					related.TotalInCurrent-related.SharedPrefixLength,
					related.TotalInBranch-related.SharedPrefixLength,
				)
			} else {
				// Fallback
				description = fmt.Sprintf(
					"%s - shared: %d/%d commits",
					related.BranchName,
					related.SharedPrefixLength,
					related.TotalInCurrent,
				)
			}
			relatedLines = append(relatedLines, description)
		}
		relatedInfo := lipgloss.NewStyle().
			Border(lipgloss.RoundedBorder()).
			BorderForeground(lipgloss.Color("240")).
			Padding(1, 2).
			Render(strings.Join(relatedLines, "\n"))
		sections = append(sections, "")
		sections = append(sections, lipgloss.NewStyle().Bold(true).Render("Related Branches (Patch-ID based)"))
		sections = append(sections, relatedInfo)
	} else {
		sections = append(sections, "")
		sections = append(sections, lipgloss.NewStyle().Bold(true).Render("Related Branches"))
		sections = append(sections, lipgloss.NewStyle().Faint(true).Render("No related branches found"))
	}

	// Section 4: Ahead/Behind Commits
	if branch.CommitsAhead > 0 || branch.CommitsBehind > 0 {
		aheadBehind := lipgloss.NewStyle().
			Border(lipgloss.RoundedBorder()).
			BorderForeground(lipgloss.Color("240")).
			Padding(1, 2).
			Render(fmt.Sprintf(
				"Ahead: %d commits\nBehind: %d commits",
				branch.CommitsAhead,
				branch.CommitsBehind,
			))
		sections = append(sections, "")
		sections = append(sections, lipgloss.NewStyle().Bold(true).Render("Ahead/Behind"))
		sections = append(sections, aheadBehind)
	}

	// Section 5: Amended Commits
	if len(branch.AmendedCommits) > 0 {
		var amendedLines []string
		for _, amended := range branch.AmendedCommits {
			patchMatch := "✓ same patch"
			if amended.LocalPatchId != amended.RemotePatchId {
				patchMatch = "✗ different patch (code changed)"
			}
			amendedLines = append(amendedLines, fmt.Sprintf(
				"Local: %s ↔ Remote: %s\nSimilarity: %.0f%% | %s",
				amended.LocalCommit[:8],
				amended.RemoteCommit[:8],
				amended.Similarity*100,
				patchMatch,
			))
		}
		amendedInfo := lipgloss.NewStyle().
			Border(lipgloss.RoundedBorder()).
			BorderForeground(lipgloss.Color("240")).
			Padding(1, 2).
			Render(strings.Join(amendedLines, "\n\n"))
		sections = append(sections, "")
		sections = append(sections, lipgloss.NewStyle().Bold(true).Render("Amended Commits"))
		sections = append(sections, amendedInfo)
	}

	// Section 6: Recent Commits
	if len(branch.RecentCommits) > 0 {
		var commitLines []string
		for _, commit := range branch.RecentCommits {
			commitLines = append(commitLines, fmt.Sprintf(
				"%s %s (%s, %s)",
				commit.Hash[:8],
				commit.Subject,
				commit.Author,
				formatRelativeTime(commit.Date),
			))
			// Show stashes that were based on this commit
			for _, stash := range commit.Stashes {
				commitLines = append(commitLines, fmt.Sprintf(
					"  └─ %s: %s",
					stash.Ref,
					stash.Message,
				))
			}
		}
		commitsInfo := lipgloss.NewStyle().
			Border(lipgloss.RoundedBorder()).
			BorderForeground(lipgloss.Color("240")).
			Padding(1, 2).
			Render(strings.Join(commitLines, "\n"))
		sections = append(sections, "")
		sections = append(sections, lipgloss.NewStyle().Bold(true).Render("Recent Commits"))
		sections = append(sections, commitsInfo)
	}

	// Footer
	footer := "\nPress q/Esc to return to list | Ctrl+C: quit"

	content := lipgloss.JoinVertical(lipgloss.Left, sections...)
	return lipgloss.JoinVertical(lipgloss.Left, title, "", content, footer)
}

// formatRelativeTime formats a time relative to now
func formatRelativeTime(t time.Time) string {
	if t.IsZero() {
		return "unknown"
	}

	duration := time.Since(t)

	switch {
	case duration < time.Minute:
		return "just now"
	case duration < time.Hour:
		mins := int(duration.Minutes())
		return fmt.Sprintf("%dm ago", mins)
	case duration < 24*time.Hour:
		hours := int(duration.Hours())
		return fmt.Sprintf("%dh ago", hours)
	case duration < 7*24*time.Hour:
		days := int(duration.Hours() / 24)
		return fmt.Sprintf("%dd ago", days)
	case duration < 30*24*time.Hour:
		weeks := int(duration.Hours() / 24 / 7)
		return fmt.Sprintf("%dw ago", weeks)
	default:
		months := int(duration.Hours() / 24 / 30)
		return fmt.Sprintf("%dmo ago", months)
	}
}