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

import (
	"fmt"
	"log"
	"strings"

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

// EditMode represents the current editing state of the timestamp table
type EditMode int

const (
	EditModeNormal         EditMode = iota // Normal navigation mode
	EditModeEditingComment                 // Editing a comment
	EditModeBlockedEdit                    // Showing error when edit is blocked
)

// TimestampTableModel manages the timestamp table view with navigation and editing
// Note: Does NOT store entries - they are passed to View() and Update() as needed
type TimestampTableModel struct {
	// Navigation state
	selectedRow   int // Currently selected row (0-based)
	viewportStart int // First visible row in viewport
	pageSize      int // Number of visible rows

	// Edit state
	editMode           EditMode // Current edit mode
	editingEntryID     int64    // ID of entry being edited
	inputBuffer        string   // Text buffer for editing
	cursorPos          int      // Cursor position in input buffer
	originalComment    string   // Original comment before editing
	blockedEditMessage string   // Error message when edit is blocked

	// Display configuration
	windowWidth int // Terminal width

	// Border style from parent (for table frame size calculation)
	borderStyle lipgloss.Style
}

// Custom messages for communicating actions to parent
type DeleteEntryMsg struct {
	EntryID int64
}

type UpdateCommentMsg struct {
	EntryID int64
	Comment string
}

type AdjustStartTimeMsg struct {
	EntryID      int64
	MinutesDelta int
}

type AdjustEndTimeMsg struct {
	EntryID      int64
	MinutesDelta int
}

type DeleteMilestoneMsg struct {
	MilestoneID int64
}

type MoveMilestoneUpMsg struct {
	MilestoneID int64
}

type MoveMilestoneDownMsg struct {
	MilestoneID int64
}

// NewTimestampTableModel creates a new timestamp table model
// Note: pageSize should be set by parent via SetPageSize() after creation
// Note: entries are passed to View() and Update() methods, not stored
func NewTimestampTableModel(windowWidth int, borderStyle lipgloss.Style) TimestampTableModel {
	return TimestampTableModel{
		selectedRow:   0,
		viewportStart: 0,
		pageSize:      1, // Will be set by parent via SetPageSize()
		editMode:      EditModeNormal,
		windowWidth:   windowWidth,
		borderStyle:   borderStyle,
	}
}

// SetPageSize updates the page size and adjusts viewport accordingly
// Note: Call preserveSelection() after this if entries count has changed
func (t *TimestampTableModel) SetPageSize(pageSize int) {
	t.pageSize = clampMin(pageSize, 1)
}

// SetWindowWidth updates the window width for table rendering
func (t *TimestampTableModel) SetWindowWidth(width int) {
	t.windowWidth = width
}

// SetViewportStart sets the viewport start position directly (for restoring saved state)
func (t *TimestampTableModel) SetViewportStart(viewportStart int) {
	t.viewportStart = clampMin(viewportStart, 0)
}

// GetSelectedItem returns the currently selected display item, or nil if no items
func (t TimestampTableModel) GetSelectedItem(items []DisplayItem) *DisplayItem {
	if len(items) == 0 || t.selectedRow >= len(items) {
		return nil
	}
	return &items[t.selectedRow]
}

// GetSelectedRow returns the currently selected row index
func (t TimestampTableModel) GetSelectedRow() int {
	return t.selectedRow
}

// GetViewportStart returns the viewport start position
func (t TimestampTableModel) GetViewportStart() int {
	return t.viewportStart
}

// SetSelectedRow sets the selected row and adjusts viewport
func (t *TimestampTableModel) SetSelectedRow(row int, entryCount int) {
	t.selectedRow = clampIndex(row, entryCount)
	t.adjustViewportToSelection()
}

// ScrollToLastEntry moves the selection to the last entry
func (t *TimestampTableModel) ScrollToLastEntry(entryCount int) {
	if entryCount > 0 {
		t.selectedRow = entryCount - 1
	} else {
		t.selectedRow = 0
	}
	t.adjustViewportToSelection()
}

// adjustViewportToSelection adjusts the viewport to keep the selected row visible
// Note: Does not need entry count - works purely on selectedRow and pageSize
func (t *TimestampTableModel) adjustViewportToSelection() {
	// Keep selection within viewport bounds
	if t.selectedRow < t.viewportStart {
		t.viewportStart = t.selectedRow
	}
	if t.selectedRow >= t.viewportStart+t.pageSize {
		t.viewportStart = t.selectedRow - t.pageSize + 1
	}

	// Ensure viewportStart is non-negative
	t.viewportStart = clampMin(t.viewportStart, 0)
}

// PreserveSelection ensures the current selection remains valid after data changes
// Call this after the entry count changes to clamp selectedRow to valid range
func (t *TimestampTableModel) PreserveSelection(entryCount int) {
	// Bounds check for selected row
	t.selectedRow = clampIndex(t.selectedRow, entryCount)

	// Adjust viewport to ensure selection is visible
	t.adjustViewportToSelection()
}

// Update handles messages and updates the timestamp table model
// Returns (updatedModel, cmd, customMsg)
// customMsg is sent to parent for actions that require database operations
// items parameter is needed for navigation bounds checking and edit operations
func (t TimestampTableModel) Update(msg tea.Msg, items []DisplayItem) (TimestampTableModel, tea.Cmd, tea.Msg) {
	switch msg := msg.(type) {
	case tea.KeyMsg:
		// Handle edit modes
		if t.editMode == EditModeEditingComment {
			return t.handleEditCommentKeys(msg)
		}

		if t.editMode == EditModeBlockedEdit {
			return t.handleBlockedEditKeys(msg, items)
		}

		// Handle normal mode navigation and actions
		return t.handleNormalModeKeys(msg, items)
	}

	return t, nil, nil
}

// handleNormalModeKeys handles keyboard input in normal mode
func (t TimestampTableModel) handleNormalModeKeys(msg tea.KeyMsg, items []DisplayItem) (TimestampTableModel, tea.Cmd, tea.Msg) {
	if len(items) == 0 {
		return t, nil, nil
	}

	keyStr := msg.String()

	switch keyStr {
	case "up", "k":
		t.selectedRow = saturatingDec(t.selectedRow, 0)

	case "down", "j":
		t.selectedRow = saturatingInc(t.selectedRow, len(items)-1)

	case "pgup":
		t.selectedRow = saturatingSub(t.selectedRow, t.pageSize, 0)

	case "pgdown":
		t.selectedRow = saturatingAdd(t.selectedRow, t.pageSize, len(items)-1)

	case "home", "g":
		t.selectedRow = 0

	case "end", "G":
		t.selectedRow = len(items) - 1

	case "e":
		// Enter comment edit mode for the selected entry (only works for entries, not milestones)
		selectedItem := items[t.selectedRow]

		// Only allow editing comments on entries
		if selectedItem.ItemType != "entry" || selectedItem.Entry == nil {
			// Silently ignore for milestones
			return t, nil, nil
		}

		selectedEntry := selectedItem.Entry

		// Check if entry is invoiced
		if selectedEntry.InvoiceID.Valid {
			// Show inline error in comment field
			t.editMode = EditModeBlockedEdit
			t.editingEntryID = selectedEntry.ID
			if selectedEntry.InvoiceNumber.Valid {
				t.blockedEditMessage = fmt.Sprintf("Cannot edit: Entry is invoiced (%s)", selectedEntry.InvoiceNumber.String)
			} else {
				t.blockedEditMessage = "Cannot edit: Entry is invoiced"
			}
			log.Printf("Blocked editing of invoiced entry %d", selectedEntry.ID)
			return t, nil, nil
		}

		t.editMode = EditModeEditingComment
		t.editingEntryID = selectedEntry.ID
		t.originalComment = selectedEntry.Comment
		t.inputBuffer = selectedEntry.Comment
		t.cursorPos = len(selectedEntry.Comment) // Start cursor at end
		log.Printf("Editing comment for entry %d", selectedEntry.ID)
		return t, nil, nil

	case "ctrl+d":
		// Delete the selected item (entry or milestone)
		selectedItem := items[t.selectedRow]
		if selectedItem.ItemType == "entry" && selectedItem.Entry != nil {
			// Send delete entry message to parent
			return t, nil, DeleteEntryMsg{EntryID: selectedItem.Entry.ID}
		} else if selectedItem.ItemType == "milestone" && selectedItem.Milestone != nil {
			// Send delete milestone message to parent
			return t, nil, DeleteMilestoneMsg{MilestoneID: selectedItem.Milestone.ID}
		}

	case "ctrl+left":
		selectedItem := items[t.selectedRow]
		// For entries: adjust end time backward (-15 minutes)
		if selectedItem.ItemType == "entry" && selectedItem.Entry != nil {
			return t, nil, AdjustEndTimeMsg{EntryID: selectedItem.Entry.ID, MinutesDelta: -15}
		}
		// For milestones: move up
		if selectedItem.ItemType == "milestone" && selectedItem.Milestone != nil {
			return t, nil, MoveMilestoneUpMsg{MilestoneID: selectedItem.Milestone.ID}
		}

	case "ctrl+right":
		selectedItem := items[t.selectedRow]
		// For entries: adjust end time forward (+15 minutes)
		if selectedItem.ItemType == "entry" && selectedItem.Entry != nil {
			return t, nil, AdjustEndTimeMsg{EntryID: selectedItem.Entry.ID, MinutesDelta: +15}
		}
		// For milestones: move down
		if selectedItem.ItemType == "milestone" && selectedItem.Milestone != nil {
			return t, nil, MoveMilestoneDownMsg{MilestoneID: selectedItem.Milestone.ID}
		}

	case "ctrl+shift+left":
		// Adjust start time backward (-15 minutes) - only for entries
		selectedItem := items[t.selectedRow]
		if selectedItem.ItemType == "entry" && selectedItem.Entry != nil {
			return t, nil, AdjustStartTimeMsg{EntryID: selectedItem.Entry.ID, MinutesDelta: -15}
		}

	case "ctrl+shift+right":
		// Adjust start time forward (+15 minutes) - only for entries
		selectedItem := items[t.selectedRow]
		if selectedItem.ItemType == "entry" && selectedItem.Entry != nil {
			return t, nil, AdjustStartTimeMsg{EntryID: selectedItem.Entry.ID, MinutesDelta: +15}
		}

	}

	// Adjust viewport to keep selection visible
	t.adjustViewportToSelection()

	return t, nil, nil
}

// handleEditCommentKeys handles keyboard input when editing a comment
func (t TimestampTableModel) handleEditCommentKeys(msg tea.KeyMsg) (TimestampTableModel, tea.Cmd, tea.Msg) {
	switch msg.Type {
	case tea.KeyEscape, tea.KeyCtrlC:
		// Cancel edit mode and restore original comment
		t.editMode = EditModeNormal
		t.inputBuffer = ""
		t.cursorPos = 0
		t.editingEntryID = 0
		t.originalComment = ""
		return t, nil, nil

	case tea.KeyEnter:
		// Save comment - send message to parent
		updateMsg := UpdateCommentMsg{
			EntryID: t.editingEntryID,
			Comment: t.inputBuffer,
		}

		// Exit edit mode
		t.editMode = EditModeNormal
		t.inputBuffer = ""
		t.cursorPos = 0
		t.editingEntryID = 0
		t.originalComment = ""

		return t, nil, updateMsg

	case tea.KeyBackspace:
		// Remove character before cursor
		if t.cursorPos > 0 {
			t.inputBuffer = t.inputBuffer[:t.cursorPos-1] + t.inputBuffer[t.cursorPos:]
			t.cursorPos = saturatingDec(t.cursorPos, 0)
		}
		return t, nil, nil

	case tea.KeyLeft:
		t.cursorPos = saturatingDec(t.cursorPos, 0)
		return t, nil, nil

	case tea.KeyRight:
		t.cursorPos = saturatingInc(t.cursorPos, len(t.inputBuffer))
		return t, nil, nil

	case tea.KeyHome, tea.KeyCtrlA:
		t.cursorPos = 0
		return t, nil, nil

	case tea.KeyEnd, tea.KeyCtrlE:
		t.cursorPos = len(t.inputBuffer)
		return t, nil, nil

	case tea.KeyCtrlLeft:
		// Jump to previous word boundary
		if t.cursorPos > 0 {
			// Skip spaces
			for t.cursorPos > 0 && t.inputBuffer[t.cursorPos-1] == ' ' {
				t.cursorPos = saturatingDec(t.cursorPos, 0)
			}
			// Skip word characters
			for t.cursorPos > 0 && t.inputBuffer[t.cursorPos-1] != ' ' {
				t.cursorPos = saturatingDec(t.cursorPos, 0)
			}
		}
		return t, nil, nil

	case tea.KeyCtrlRight:
		// Jump to next word boundary
		if t.cursorPos < len(t.inputBuffer) {
			// Skip word characters
			for t.cursorPos < len(t.inputBuffer) && t.inputBuffer[t.cursorPos] != ' ' {
				t.cursorPos = saturatingInc(t.cursorPos, len(t.inputBuffer))
			}
			// Skip spaces
			for t.cursorPos < len(t.inputBuffer) && t.inputBuffer[t.cursorPos] == ' ' {
				t.cursorPos = saturatingInc(t.cursorPos, len(t.inputBuffer))
			}
		}
		return t, nil, nil

	default:
		// Check for ctrl+backspace or ctrl+w (delete word)
		if msg.String() == "ctrl+backspace" || msg.String() == "ctrl+h" || msg.String() == "ctrl+w" {
			if t.cursorPos > 0 {
				// Find start of word
				newPos := t.cursorPos
				// Skip spaces
				for newPos > 0 && t.inputBuffer[newPos-1] == ' ' {
					newPos--
				}
				// Skip word characters
				for newPos > 0 && t.inputBuffer[newPos-1] != ' ' {
					newPos--
				}
				// Delete from newPos to cursor
				t.inputBuffer = t.inputBuffer[:newPos] + t.inputBuffer[t.cursorPos:]
				t.cursorPos = newPos
			}
			return t, nil, nil
		}

		// Don't insert keys that have modifiers (ctrl, alt, etc.)
		keyStr := msg.String()
		if msg.Alt || len(keyStr) > 1 && (keyStr[:5] == "ctrl+" || keyStr[:4] == "alt+") {
			// Ignore keys with modifiers
			return t, nil, nil
		}

		// Handle any other key input (including spaces, letters, numbers, etc.)
		// Insert at cursor position
		t.inputBuffer = t.inputBuffer[:t.cursorPos] + msg.String() + t.inputBuffer[t.cursorPos:]
		t.cursorPos += len(msg.String())
		return t, nil, nil
	}
}

// handleBlockedEditKeys handles keyboard input when showing blocked edit error
func (t TimestampTableModel) handleBlockedEditKeys(msg tea.KeyMsg, items []DisplayItem) (TimestampTableModel, tea.Cmd, tea.Msg) {
	keyStr := msg.String()

	// Only allow safe movement keys to dismiss the error
	movementKeys := map[string]bool{
		"up":     true,
		"down":   true,
		"k":      true,
		"j":      true,
		"pgup":   true,
		"pgdown": true,
		"home":   true,
		"end":    true,
		"g":      true,
		"G":      true,
		"esc":    true,
	}

	if movementKeys[keyStr] {
		// Dismiss the error
		t.editMode = EditModeNormal
		t.editingEntryID = 0
		t.blockedEditMessage = ""

		// Re-process the key in normal mode
		return t.handleNormalModeKeys(msg, items)
	}

	// Block all other keys - just stay in blocked edit mode
	return t, nil, nil
}

// View renders the timestamp table
// items parameter contains the data to display - component doesn't store it
// restartableEntryID is the ID of the entry that can be restarted (for highlighting), -1 if none
func (t TimestampTableModel) View(items []DisplayItem, restartableEntryID int64) string {
	if len(items) == 0 {
		return ""
	}

	// Check if there's a running entry
	hasRunningEntry := false
	for _, item := range items {
		if item.ItemType == "entry" && item.Entry != nil && !item.Entry.EndTime.Valid {
			hasRunningEntry = true
			break
		}
	}

	// Find the restartable entry for highlighting
	var restartableEntry *TimeEntry
	if !hasRunningEntry && restartableEntryID != -1 {
		for _, item := range items {
			if item.ItemType == "entry" && item.Entry != nil && item.Entry.ID == restartableEntryID {
				restartableEntry = item.Entry
				break
			}
		}
	}

	// Helper function to determine if an item is selected and needs background
	isItemSelected := func(item DisplayItem) bool {
		if len(items) == 0 || t.selectedRow >= len(items) {
			return false
		}
		selectedItem := items[t.selectedRow]

		// For entries, check if we're editing this entry
		if item.ItemType == "entry" && item.Entry != nil {
			isEditingThisEntry := t.editMode == EditModeEditingComment && item.Entry.ID == t.editingEntryID
			if selectedItem.ItemType == "entry" && selectedItem.Entry != nil {
				return item.Entry.ID == selectedItem.Entry.ID && !isEditingThisEntry
			}
		}

		// For milestones
		if item.ItemType == "milestone" && item.Milestone != nil {
			if selectedItem.ItemType == "milestone" && selectedItem.Milestone != nil {
				return item.Milestone.ID == selectedItem.Milestone.ID
			}
		}

		return false
	}

	// Define table columns
	columns := []TableColumn{
		{
			Name:  "#",
			Width: 5,
			Align: lipgloss.Right,
			RenderCell: func(data any, width int) string {
				item := data.(DisplayItem)
				color := ColorTextDim

				// For entries: check if invoiced or restartable
				if item.ItemType == "entry" && item.Entry != nil {
					if item.Entry.InvoiceID.Valid {
						color = ColorTextDim
					} else if restartableEntry != nil && item.Entry.ID == restartableEntry.ID {
						color = ColorRestartable
					}
				}
				// For milestones: use milestone-specific color
				if item.ItemType == "milestone" {
					color = ColorRestartable // Orange color for milestones
				}

				indexStyle := lipgloss.NewStyle().Foreground(color).Align(lipgloss.Right)

				// Apply selection background if item is selected
				bgStyle := lipgloss.NewStyle()
				if isItemSelected(item) {
					bgStyle = lipgloss.NewStyle().Background(ColorSelectionBackground)
				}

				return renderCell(indexStyle.Render(fmt.Sprintf("%4d", item.DisplayIndex)), width, bgStyle)
			},
		},
		{
			Name:  "Date",
			Width: 12,
			Align: lipgloss.Left,
			RenderCell: func(data any, width int) string {
				item := data.(DisplayItem)
				color := ColorAgeNewer
				var content string

				// Get content based on item type
				if item.ItemType == "entry" && item.Entry != nil {
					content = timestampToDate(item.Entry.StartTime)
					if item.Entry.InvoiceID.Valid {
						color = ColorTextDim
					} else if restartableEntry != nil && item.Entry.ID == restartableEntry.ID {
						color = ColorRestartable
					}
				} else if item.ItemType == "milestone" && item.Milestone != nil {
					content = "🏁"
					color = ColorRestartable // Orange for milestones
				}

				dateStyle := lipgloss.NewStyle().Foreground(color)

				// Apply selection background if item is selected
				bgStyle := lipgloss.NewStyle()
				if isItemSelected(item) {
					bgStyle = lipgloss.NewStyle().Background(ColorSelectionBackground)
				}

				return renderCell(dateStyle.Render(content), width, bgStyle)
			},
		},
		{
			Name:  "Start",
			Width: 7,
			Align: lipgloss.Right,
			RenderCell: func(data any, width int) string {
				item := data.(DisplayItem)
				color := ColorAgeMid
				var content string

				if item.ItemType == "entry" && item.Entry != nil {
					// For entries: show start time
					if item.Entry.InvoiceID.Valid {
						color = ColorTextDim
					} else if restartableEntry != nil && item.Entry.ID == restartableEntry.ID {
						color = ColorRestartable
					}
					content = timestampToTime(item.Entry.StartTime)
				} else if item.ItemType == "milestone" {
					// For milestones: show cumulative hours in format X.Xh
					color = ColorRestartable // Orange for milestones
					content = fmt.Sprintf("%.1fh", item.CumulativeHours)
				}

				timeStyle := lipgloss.NewStyle().Foreground(color).Align(lipgloss.Right)

				// Apply selection background if item is selected
				bgStyle := lipgloss.NewStyle()
				if isItemSelected(item) {
					bgStyle = lipgloss.NewStyle().Background(ColorSelectionBackground)
				}

				return renderCell(timeStyle.Render(content), width, bgStyle)
			},
		},
		{
			Name:  "End",
			Width: 7,
			Align: lipgloss.Right,
			RenderCell: func(data any, width int) string {
				item := data.(DisplayItem)
				color := ColorAgeMid
				var content string

				if item.ItemType == "entry" && item.Entry != nil {
					// For entries: show end time
					if item.Entry.InvoiceID.Valid {
						color = ColorTextDim
					} else if restartableEntry != nil && item.Entry.ID == restartableEntry.ID {
						color = ColorRestartable
					}
					content = formatEndTime(item.Entry.StartTime, item.Entry.EndTime)
				} else if item.ItemType == "milestone" {
					// For milestones: show separator
					color = ColorTextDim
					content = "────"
				}

				timeStyle := lipgloss.NewStyle().Foreground(color).Align(lipgloss.Right)

				// Apply selection background if item is selected
				bgStyle := lipgloss.NewStyle()
				if isItemSelected(item) {
					bgStyle = lipgloss.NewStyle().Background(ColorSelectionBackground)
				}

				return renderCell(timeStyle.Render(content), width, bgStyle)
			},
		},
		{
			Name:  "Duration",
			Width: 10,
			Align: lipgloss.Right,
			RenderCell: func(data any, width int) string {
				item := data.(DisplayItem)
				color := ColorAgeNewest
				bold := true
				var content string

				if item.ItemType == "entry" && item.Entry != nil {
					// For entries: show duration
					if item.Entry.InvoiceID.Valid {
						color = ColorTextDim
						bold = false
					} else if restartableEntry != nil && item.Entry.ID == restartableEntry.ID {
						color = ColorRestartable
					}
					content = formatDuration(item.Entry.StartTime, item.Entry.EndTime)
				} else if item.ItemType == "milestone" {
					// For milestones: show separator
					color = ColorTextDim
					bold = false
					content = "────"
				}

				durStyle := lipgloss.NewStyle().Foreground(color).Bold(bold).Align(lipgloss.Right)

				// Apply selection background if item is selected
				bgStyle := lipgloss.NewStyle()
				if isItemSelected(item) {
					bgStyle = lipgloss.NewStyle().Background(ColorSelectionBackground)
				}

				return renderCell(durStyle.Render(content), width, bgStyle)
			},
		},
		{
			Name:  "Comment",
			Width: 20, // This will be expanded to fill remaining space (last column)
			Align: lipgloss.Left,
			RenderCell: func(data any, width int) string {
				item := data.(DisplayItem)

				// Check if we're showing a blocked edit error for this entry
				if item.ItemType == "entry" && item.Entry != nil && t.editMode == EditModeBlockedEdit && item.Entry.ID == t.editingEntryID {
					// Show error message in red with full background across the cell
					content := t.blockedEditMessage
					content = truncateContent(content, width)
					errorStyle := lipgloss.NewStyle().Foreground(ColorError).Bold(true)
					bgStyle := lipgloss.NewStyle().Background(ColorSelectionBackground)
					return renderCell(errorStyle.Render(content), width, bgStyle)
				}

				// Check if we're editing this entry's comment
				if item.ItemType == "entry" && item.Entry != nil && t.editMode == EditModeEditingComment && item.Entry.ID == t.editingEntryID {
					// Show input buffer with cursor at correct position
					var content string
					if t.cursorPos < len(t.inputBuffer) {
						// Cursor is on a character - highlight it with background
						before := t.inputBuffer[:t.cursorPos]
						cursorChar := string(t.inputBuffer[t.cursorPos])
						after := t.inputBuffer[t.cursorPos+1:]
						cursorStyle := lipgloss.NewStyle().Background(ColorCursorBackground).Foreground(ColorCursorForeground)
						content = before + cursorStyle.Render(cursorChar) + after
					} else {
						// Cursor is at end - show a block cursor
						cursorStyle := lipgloss.NewStyle().Background(ColorCursorBackground)
						content = t.inputBuffer + cursorStyle.Render(" ")
					}
					content = truncateContent(content, width)
					// Apply selection background to the entire Comment column when editing
					commentStyle := lipgloss.NewStyle().Foreground(ColorAgeNewest).Background(ColorSelectionBackground)
					return renderCell(commentStyle.Render(content), width, lipgloss.NewStyle())
				}

				// Normal rendering
				var content string
				commentStyle := lipgloss.NewStyle().Foreground(ColorTextDim)

				if item.ItemType == "entry" && item.Entry != nil {
					// For entries: show comment
					content = item.Entry.Comment

					// If invoiced, prepend invoice number
					if item.Entry.InvoiceID.Valid && item.Entry.InvoiceNumber.Valid {
						invoiceTag := fmt.Sprintf("[INV: %s] ", item.Entry.InvoiceNumber.String)
						if content == "" {
							content = invoiceTag
						} else {
							content = invoiceTag + content
						}
					}
				} else if item.ItemType == "milestone" && item.Milestone != nil {
					// For milestones: show just the name (🏁 is in Date column)
					content = item.Milestone.Name
					commentStyle = commentStyle.Foreground(ColorRestartable).Bold(true)
				}

				if content == "" {
					content = "" // Empty string for no comment
				}
				content = truncateContent(content, width)

				// Apply selection background if item is selected
				bgStyle := lipgloss.NewStyle()
				if isItemSelected(item) {
					bgStyle = lipgloss.NewStyle().Background(ColorSelectionBackground)
				}

				return renderCell(commentStyle.Render(content), width, bgStyle)
			},
		},
	}

	// Create table
	table := NewTable(columns, t.windowWidth, t.borderStyle)

	var output strings.Builder

	// Render header
	header := table.RenderHeader()
	output.WriteString(header + "\n")

	// Render visible rows
	visibleEnd := min(t.viewportStart+t.pageSize, len(items))

	selectionBgColor := ColorSelectionBackground

	for i := t.viewportStart; i < visibleEnd; i++ {
		item := items[i]
		var row string
		// Don't apply full row background if we're editing this entry's comment
		// (the Comment column will handle its own background in that case)
		// But DO apply it for blocked edit - we want the whole row selected
		isEditingThisItem := false
		if item.ItemType == "entry" && item.Entry != nil {
			isEditingThisItem = t.editMode == EditModeEditingComment && item.Entry.ID == t.editingEntryID
		}
		if i == t.selectedRow && !isEditingThisItem {
			row = table.RenderRowWithBackground(item, selectionBgColor)
		} else {
			row = table.RenderRow(item)
		}
		output.WriteString(row + "\n")
	}

	// Add empty lines if viewport isn't full
	for i := visibleEnd; i < t.viewportStart+t.pageSize; i++ {
		output.WriteString("\n")
	}

	return output.String()
}