summaryrefslogtreecommitdiff
path: root/internal/ui/ultra.go
blob: fc28bc550398ad485af2a55d469b2a4f30a8aa3a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
package ui

import (
	"fmt"
	"regexp"
	"strings"
	"time"

	tea "charm.land/bubbletea/v2"
	"charm.land/lipgloss/v2"

	"codeberg.org/snonux/tasksamurai/internal"
	"codeberg.org/snonux/tasksamurai/internal/task"
)

func (m *Model) renderUltraModus() string {
	tasks := m.ultraTaskList()
	width := m.ultraRenderWidth()

	top := m.ultraStatusLine(m.ultraModeStatus(tasks), width)
	bottom := m.ultraStatusLine(m.ultraCursorStatus(tasks), width)
	overlay, overlayHeight := m.ultraOverlay()

	var lines []string
	lines = append(lines, top)

	if len(tasks) == 0 {
		// No tasks available — render a centered placeholder instead of an empty card area.
		lines = append(lines, m.ultraNoTasksMessage(width, m.ultraCardBudget(top, bottom, overlayHeight)))
	} else {
		lines = append(
			lines,
			m.ultraRenderCards(
				tasks,
				width,
				m.ultraVisibleCursor(tasks),
				m.ultraVisibleStart(len(tasks)),
				m.ultraCardBudget(top, bottom, overlayHeight),
			)...,
		)
	}

	lines = append(lines, bottom)
	if overlay != "" {
		lines = append(lines, overlay)
	}
	return strings.Join(lines, "\n")
}

// ultraNoTasksMessage renders a vertically and horizontally centered "No tasks" message
// sized to fill the available card budget height.
func (m *Model) ultraNoTasksMessage(width, budget int) string {
	msg := lipgloss.NewStyle().
		Width(width).
		Align(lipgloss.Center).
		Foreground(lipgloss.Color("240")).
		Render("No tasks")

	// Pad vertically so the message appears centered in the card area.
	msgHeight := lipgloss.Height(msg)
	paddingTop := (budget - msgHeight) / 2
	if paddingTop < 0 {
		paddingTop = 0
	}

	var lines []string
	emptyLine := lipgloss.NewStyle().Width(width).Render("")
	for range paddingTop {
		lines = append(lines, emptyLine)
	}
	lines = append(lines, msg)
	return strings.Join(lines, "\n")
}

func (m Model) buildUltraHelpContent() string {
	return m.buildRenderedHelpContent(m.ultraHelpSections())
}

func (m Model) ultraHelpSections() []helpSection {
	return []helpSection{
		{
			title: "Navigation",
			items: []helpItem{
				{key: "j, k", desc: "move down/up"},
				{key: "pgup, pgdn", desc: "page up/down"},
				{key: "g, G", desc: "go to start/end"},
			},
		},
		{
			title: "Task Management",
			items: []helpItem{
				{key: "Enter, e, E", desc: "edit selected task"},
				{key: "s", desc: "start/stop task"},
				{key: "d", desc: "mark task done"},
				{key: "U", desc: "undo last done"},
				{key: "+", desc: "add new task"},
			},
		},
		{
			title: "Task Fields",
			items: []helpItem{
				{key: "p", desc: "set priority"},
				{key: "w", desc: "set due date"},
				{key: "W", desc: "remove due date"},
				{key: "t", desc: "edit tags"},
				{key: "a, A", desc: "add/replace annotations"},
				{key: "J", desc: "edit project"},
				{key: "R", desc: "edit recurrence"},
				{key: "f", desc: "change filter"},
			},
		},
		{
			title: "Search",
			items: []helpItem{
				{key: "/", desc: "search ultra cards"},
				{key: "n, N", desc: "next/previous match"},
			},
		},
		{
			title: "Appearance",
			items: []helpItem{
				{key: "c, C", desc: "random/reset theme"},
				{key: "x", desc: "toggle disco mode"},
				{key: "B", desc: "toggle blinking"},
			},
		},
		{
			title: "General",
			items: []helpItem{
				{key: "H", desc: "toggle help"},
				{key: "esc", desc: "close help/input or exit ultra mode"},
				{key: "q", desc: "exit ultra mode"},
			},
		},
	}
}

func (m *Model) ultraRenderWidth() int {
	width := m.tbl.Width()
	if width <= 0 {
		return 80
	}
	return width
}

func (m *Model) ultraSearchOverlay() (string, int) {
	if !m.ultraSearching {
		return "", 0
	}

	overlay := lipgloss.NewStyle().
		Foreground(lipgloss.Color("248")).
		PaddingTop(1).
		Render(m.ultraSearchInput.View())
	return overlay, lipgloss.Height(overlay)
}

func (m *Model) ultraCardBudget(top, bottom string, overlayHeight int) int {
	budget := m.windowHeight - lipgloss.Height(top) - lipgloss.Height(bottom) - overlayHeight
	if budget < 0 {
		return 0
	}
	return budget
}

func (m *Model) ultraVisibleStart(total int) int {
	start := m.ultraOffset
	if start < 0 {
		return 0
	}
	if start > total {
		return total
	}
	return start
}

func (m *Model) ultraVisibleCount() int {
	tasks := m.ultraTaskList()
	if len(tasks) == 0 {
		return 0
	}

	width := m.ultraRenderWidth()
	top := m.ultraStatusLine(m.ultraModeStatus(tasks), width)
	bottom := m.ultraStatusLine(m.ultraCursorStatus(tasks), width)
	_, overlayHeight := m.ultraOverlay()

	budget := m.ultraCardBudget(top, bottom, overlayHeight)
	if budget <= 0 {
		return 0
	}

	start := m.ultraVisibleStart(len(tasks))
	selected := m.ultraVisibleCursor(tasks)
	used := 0
	count := 0
	for i := start; i < len(tasks); i++ {
		card := m.renderUltraCard(tasks[i], width, i == selected, m.ultraSearchRegex)
		if card == "" {
			continue
		}

		cardHeight := lipgloss.Height(card)
		if count > 0 {
			if used+1+cardHeight > budget {
				break
			}
			used++
		} else if cardHeight > budget {
			break
		}

		if used+cardHeight > budget {
			break
		}

		used += cardHeight
		count++
	}

	return count
}

func (m *Model) ultraTaskList() []task.Task {
	if m.ultraFiltered == nil {
		return m.tasks
	}

	tasks := make([]task.Task, 0, len(m.ultraFiltered))
	for _, idx := range m.ultraFiltered {
		if idx < 0 || idx >= len(m.tasks) {
			continue
		}
		tasks = append(tasks, m.tasks[idx])
	}
	return tasks
}

func (m *Model) ultraFilteredTaskIDs() []int {
	if m.ultraFiltered == nil {
		return nil
	}

	ids := make([]int, 0, len(m.ultraFiltered))
	for _, idx := range m.ultraFiltered {
		if idx < 0 || idx >= len(m.tasks) {
			continue
		}
		ids = append(ids, m.tasks[idx].ID)
	}
	return ids
}

func (m *Model) rebuildUltraFiltered(ids []int) {
	if m.ultraFiltered == nil {
		return
	}

	indexes := make([]int, 0, len(ids))
	for _, id := range ids {
		if idx := m.taskIndexByID(id); idx >= 0 {
			indexes = append(indexes, idx)
		}
	}
	m.ultraFiltered = indexes
}

func (m *Model) getUltraSelectedTaskID() (int, error) {
	tasks := m.ultraTaskList()
	if len(tasks) == 0 {
		return 0, fmt.Errorf("no ultra tasks available")
	}
	if m.ultraCursor < 0 || m.ultraCursor >= len(tasks) {
		return 0, fmt.Errorf("ultra cursor %d out of range", m.ultraCursor)
	}
	return tasks[m.ultraCursor].ID, nil
}

func (m *Model) ultraTaskIndexByID(id int) int {
	for i, t := range m.ultraTaskList() {
		if t.ID == id {
			return i
		}
	}
	return -1
}

func (m *Model) taskIndexByID(id int) int {
	for i, t := range m.tasks {
		if t.ID == id {
			return i
		}
	}
	return -1
}

func (m *Model) selectTaskByID(id int) bool {
	row := m.taskIndexByID(id)
	if row < 0 {
		return false
	}

	prevRow := m.tbl.Cursor()
	prevCol := m.tbl.ColumnCursor()
	m.tbl.SetCursor(row)

	if m.showUltra {
		if ultraRow := m.ultraTaskIndexByID(id); ultraRow >= 0 {
			m.ultraCursor = ultraRow
		}
		m.ultraEnsureVisible()
	}

	if prevRow != m.tbl.Cursor() || prevCol != m.tbl.ColumnCursor() {
		m.updateSelectionHighlight(prevRow, m.tbl.Cursor(), prevCol, m.tbl.ColumnCursor())
	}
	return true
}

func (m *Model) reconcileUltraSelection() {
	if !m.showUltra {
		return
	}

	if m.ultraFocusedID > 0 {
		if m.ultraTaskIndexByID(m.ultraFocusedID) >= 0 {
			_ = m.selectTaskByID(m.ultraFocusedID)
			m.ultraFocusedID = 0
			m.ultraEnsureVisible()
			return
		}
		m.ultraFocusedID = 0
	}

	m.ultraEnsureVisible()
	m.syncUltraTableSelection()
}

func (m *Model) syncUltraTableSelection() {
	tasks := m.ultraTaskList()
	cursor := m.ultraVisibleCursor(tasks)
	if cursor < 0 {
		return
	}

	row := m.taskIndexByID(tasks[cursor].ID)
	if row < 0 {
		return
	}

	prevRow := m.tbl.Cursor()
	prevCol := m.tbl.ColumnCursor()
	m.tbl.SetCursor(row)
	m.updateSelectionHighlight(prevRow, row, prevCol, m.tbl.ColumnCursor())
}

func (m *Model) ultraOverlay() (string, int) {
	overlay, overlayHeight := m.ultraSearchOverlay()

	inputOverlay := m.ultraInputOverlay()
	if inputOverlay != "" {
		if overlay != "" {
			overlay += "\n" + inputOverlay
			overlayHeight += lipgloss.Height(inputOverlay)
		} else {
			overlay = inputOverlay
			overlayHeight = lipgloss.Height(inputOverlay)
		}
	}

	return overlay, overlayHeight
}

func (m *Model) ultraInputOverlay() string {
	switch {
	case m.annotating:
		return m.annotateInput.View()
	case m.dueEditing:
		return m.dueView(true)
	case m.prioritySelecting:
		return m.priorityView(true)
	case m.descEditing:
		return m.descInput.View()
	case m.tagsEditing:
		return m.tagsInput.View()
	case m.recurEditing:
		return m.recurInput.View()
	case m.projEditing:
		return m.projInput.View()
	case m.filterEditing:
		return m.filterInput.View()
	case m.addingTask:
		return m.addInput.View()
	case m.searching:
		return m.searchInput.View()
	default:
		return ""
	}
}

// ultraVisibleCursor treats ultraCursor as a cursor within the visible ultra task list.
func (m *Model) ultraVisibleCursor(tasks []task.Task) int {
	if len(tasks) == 0 {
		return -1
	}
	if m.ultraCursor < 0 {
		return 0
	}
	if m.ultraCursor >= len(tasks) {
		return len(tasks) - 1
	}
	return m.ultraCursor
}

func (m Model) ultraStatusLine(text string, width int) string {
	return lipgloss.NewStyle().
		Foreground(lipgloss.Color(m.theme.StatusFG)).
		Background(lipgloss.Color(m.theme.StatusBG)).
		Width(width).
		Render(text)
}

func (m *Model) ultraModeStatus(tasks []task.Task) string {
	filter := "all"
	if m.ultraSearching {
		if query := strings.TrimSpace(m.ultraSearchInput.Value()); query != "" {
			filter = query
		} else if m.ultraSearchRegex != nil {
			filter = m.ultraSearchRegex.String()
		} else if m.ultraFiltered != nil {
			filter = "filtered"
		}
	} else if m.ultraSearchRegex != nil {
		filter = m.ultraSearchRegex.String()
	} else if m.ultraFiltered != nil {
		filter = "filtered"
	}
	// Mirror the normal-mode title format so the app name is always visible,
	// with "(ultra)" appended to distinguish the view.
	return fmt.Sprintf("Task Samurai %s (ultra) | filter: %s | %d tasks", internal.Version, filter, len(tasks))
}

func (m *Model) ultraSearchText(t task.Task) string {
	return ultraJoinSections(
		m.ultraHeaderText(t),
		m.ultraMetaText(t),
		ultraOrDash(strings.TrimSpace(t.Description)),
		m.ultraAnnotationsSearchText(t),
	)
}

func (m *Model) ultraFilteredIndexes(re *regexp.Regexp) []int {
	if re == nil {
		return nil
	}

	indexes := make([]int, 0, len(m.tasks))
	for i, t := range m.tasks {
		if re.MatchString(m.ultraSearchText(t)) {
			indexes = append(indexes, i)
		}
	}
	return indexes
}

// handleUltraSearchMode handles keystrokes while the ultra search input is open.
// Results are filtered live on every keystroke; Enter confirms (keeps the
// filter, closes the input); Esc cancels (clears the filter, closes the input).
// The search term is treated as a regular expression.
func (m *Model) handleUltraSearchMode(msg tea.KeyPressMsg) (tea.Model, tea.Cmd) {
	switch msg.String() {
	case "enter":
		// Empty input clears the filter; non-empty confirms and keeps it.
		if strings.TrimSpace(m.ultraSearchInput.Value()) == "" {
			m.ultraSearchRegex = nil
			m.ultraFiltered = nil
			m.ultraCursor = 0
			m.ultraOffset = 0
		}
		m.ultraSearching = false
		m.ultraSearchInput.Blur()
		return m, nil
	case "esc":
		// Cancel: clear the filter and close the search input.
		m.ultraSearching = false
		m.ultraSearchInput.SetValue("")
		m.ultraSearchInput.Blur()
		m.ultraSearchRegex = nil
		m.ultraFiltered = nil
		m.ultraCursor = 0
		m.ultraOffset = 0
		return m, nil
	}

	// Forward the keystroke to the text input widget.
	var cmd tea.Cmd
	m.ultraSearchInput, cmd = m.ultraSearchInput.Update(msg)

	// Recompile and refilter on every change for live results.
	m.ultraApplySearch(m.ultraSearchInput.Value())
	return m, cmd
}

// ultraApplySearch compiles value as a case-insensitive regex and updates the
// filtered task index. The pattern is automatically wrapped with (?i) so plain
// text searches like "foo" match "Foo" and "FOO" without extra effort. Explicit
// flags (e.g. (?-i)) in the pattern override this default. If value is empty
// the filter is cleared. If the regex is invalid (e.g. mid-typing an incomplete
// pattern) the existing filter is left unchanged so the display does not flicker.
func (m *Model) ultraApplySearch(value string) {
	value = strings.TrimSpace(value)
	if value == "" {
		m.ultraSearchRegex = nil
		m.ultraFiltered = nil
		m.ultraCursor = 0
		m.ultraOffset = 0
		return
	}
	// Prepend (?i) for case-insensitive matching unless the user already
	// supplied inline flags (patterns starting with "(?" opt in explicitly).
	pattern := value
	if !strings.HasPrefix(pattern, "(?") {
		pattern = "(?i)" + pattern
	}
	re, err := compileAndCacheRegex(pattern)
	if err != nil {
		// Keep the previous filter while the regex is incomplete.
		return
	}
	m.ultraSearchRegex = re
	m.ultraFiltered = m.ultraFilteredIndexes(re)
	m.ultraCursor = 0
	m.ultraOffset = 0
}

func (m *Model) ultraMoveSearchMatch(delta int) {
	if len(m.ultraFiltered) == 0 {
		return
	}

	m.ultraMoveCursor(delta)
}

func (m *Model) ultraCursorStatus(tasks []task.Task) string {
	cursor := m.ultraVisibleCursor(tasks)
	if cursor < 0 {
		return fmt.Sprintf("0/%d", len(tasks))
	}
	return fmt.Sprintf("%d/%d", cursor+1, len(tasks))
}

func (m *Model) ultraHeaderText(t task.Task) string {
	return strings.Join(
		[]string{
			fmt.Sprintf("#%d", t.ID),
			ultraOrDash(t.Priority),
			ultraOrDash(t.Status),
			fmt.Sprintf("%.1f", t.Urgency),
			ultraTaskAge(t.Entry),
		},
		" | ",
	)
}

func (m *Model) ultraMetaText(t task.Task) string {
	return strings.Join(
		[]string{
			"project: " + ultraOrDash(t.Project),
			"tags: " + ultraOrDash(strings.Join(t.Tags, " ")),
			"due: " + ultraDueValue(m, t.Due),
			"recur: " + ultraOrDash(t.Recur),
			"start: " + ultraOrDash(m.formatTaskDate(t.Start)),
		},
		" | ",
	)
}

func (m *Model) ultraDescriptionLines(t task.Task, width int) []string {
	text := t.Description
	if text == "" {
		text = "-"
	}

	// No leading indent — keep description flush with the card edge for a compact layout.
	return wordWrap(text, ultraBodyWidth(width))
}

func (m *Model) ultraDescriptionText(t task.Task, width int) string {
	return strings.Join(m.ultraDescriptionLines(t, width), "\n")
}

func (m *Model) ultraAnnotationsLines(t task.Task, width int) []string {
	if len(t.Annotations) == 0 {
		return nil
	}

	bodyWidth := ultraBodyWidth(width)
	var lines []string
	for _, ann := range t.Annotations {
		text := fmt.Sprintf("[%s] %s", m.formatTaskDate(ann.Entry), ultraOrDash(strings.TrimSpace(ann.Description)))
		// No indent on continuation lines — keep annotations flush for a compact layout.
		lines = append(lines, wordWrap(text, bodyWidth)...)
	}
	return lines
}

func (m *Model) ultraAnnotationsText(t task.Task, width int) string {
	return strings.Join(m.ultraAnnotationsLines(t, width), "\n")
}

func (m *Model) ultraAnnotationsSearchText(t task.Task) string {
	if len(t.Annotations) == 0 {
		return ""
	}

	lines := make([]string, 0, len(t.Annotations))
	for _, ann := range t.Annotations {
		line := fmt.Sprintf("[%s] %s", m.formatTaskDate(ann.Entry), ultraOrDash(strings.TrimSpace(ann.Description)))
		lines = append(lines, line)
	}
	return strings.Join(lines, "\n")
}

// renderUltraCard assembles the card sections and applies the outer selection style.
// bg is threaded through all inner render calls so that ANSI resets emitted by
// per-field styles do not expose the terminal-default black background inside a
// selected (grey) card.
func (m *Model) renderUltraCard(t task.Task, width int, selected bool, re *regexp.Regexp) string {
	bg := ""
	if selected {
		bg = m.theme.SelectedBG
	}

	// No blank lines between sections — ultraJoinSections passes "" so
	// ultraJoinSectionsWithBlank skips the separator entirely. The outer
	// ultraCardStyle already fills the selected background across all lines,
	// so per-section bg-coloured blank rows are not needed.
	card := ultraJoinSections(
		m.renderUltraHeaderWithRegex(t, width, re, bg),
		m.renderUltraMetaWithRegex(t, width, re, bg),
		m.renderUltraDescriptionWithRegex(t, width, re, bg),
		m.renderUltraAnnotationsWithRegex(t, width, re, bg),
	)
	if card == "" {
		return ""
	}
	blink := m.blinkID != 0 && m.blinkOn && t.ID == m.blinkID
	if blink {
		lines := strings.SplitN(card, "\n", 2)
		lines[0] = "! " + lines[0]
		card = strings.Join(lines, "\n")
	}
	return ultraCardStyle(m.theme, width, selected, blink).Render(card)
}

// renderUltraHeader renders the task's primary state line (no selection bg).
func (m *Model) renderUltraHeader(t task.Task, width int) string {
	return m.renderUltraHeaderWithRegex(t, width, m.ultraSearchRegex, "")
}

// renderUltraMeta renders the task's secondary metadata line (no selection bg).
func (m *Model) renderUltraMeta(t task.Task, width int) string {
	return m.renderUltraMetaWithRegex(t, width, m.ultraSearchRegex, "")
}

// renderUltraDescription renders the wrapped task description body (no selection bg).
func (m *Model) renderUltraDescription(t task.Task, width int) string {
	return m.renderUltraDescriptionWithRegex(t, width, m.ultraSearchRegex, "")
}

// renderUltraAnnotations renders wrapped annotation lines with timestamps (no selection bg).
func (m *Model) renderUltraAnnotations(t task.Task, width int) string {
	return m.renderUltraAnnotationsWithRegex(t, width, m.ultraSearchRegex, "")
}

func (m *Model) renderUltraHeaderWithRegex(t task.Task, width int, re *regexp.Regexp, bg string) string {
	idText := fmt.Sprintf("#%d", t.ID)
	priorityText := ultraOrDash(t.Priority)
	statusText := ultraOrDash(t.Status)
	urgencyText := fmt.Sprintf("%.1f", t.Urgency)
	ageText := ultraTaskAge(t.Entry)
	line := strings.Join([]string{idText, priorityText, statusText, urgencyText, ageText}, " | ")
	if re != nil && re.MatchString(line) && !ultraRegexMatchesAny(re, idText, priorityText, statusText, urgencyText, ageText) {
		return m.renderUltraSearchLine(line, lipgloss.NewStyle().Bold(true).Foreground(lipgloss.Color("253")), re, bg)
	}

	sep := ultraFieldSep(bg)
	id := m.ultraStyledText(re, lipgloss.NewStyle().Bold(true).Foreground(lipgloss.Color("253")), idText, bg)
	// H/M/L badges keep their own coloured background; plain "-" uses the card bg.
	priorityBG := bg
	if t.Priority == "H" || t.Priority == "M" || t.Priority == "L" {
		priorityBG = ""
	}
	priority := m.ultraStyledText(re, ultraPriorityStyle(m.theme, t.Priority), priorityText, priorityBG)
	status := m.ultraStyledText(re, lipgloss.NewStyle().Foreground(lipgloss.Color("246")), statusText, bg)
	urgency := m.ultraStyledText(re, lipgloss.NewStyle().Foreground(lipgloss.Color("214")), urgencyText, bg)
	age := m.ultraStyledText(re, lipgloss.NewStyle().Foreground(lipgloss.Color("240")), ageText, bg)
	return strings.Join([]string{id, priority, status, urgency, age}, sep)
}

func (m *Model) renderUltraMetaWithRegex(t task.Task, width int, re *regexp.Regexp, bg string) string {
	_ = width
	project := ultraOrDash(t.Project)
	tags := ultraOrDash(strings.Join(t.Tags, " "))
	due := ultraDueValue(m, t.Due)
	recur := ultraOrDash(t.Recur)
	start := ultraOrDash(m.formatTaskDate(t.Start))
	line := strings.Join(
		[]string{
			"project: " + project,
			"tags: " + tags,
			"due: " + due,
			"recur: " + recur,
			"start: " + start,
		},
		" | ",
	)
	if re != nil && re.MatchString(line) && !ultraRegexMatchesAny(re, "project:", project, "tags:", tags, "due:", due, "recur:", recur, "start:", start) {
		return m.renderUltraSearchLine(line, lipgloss.NewStyle().Foreground(lipgloss.Color("253")), re, bg)
	}

	sep := ultraFieldSep(bg)
	parts := []string{
		m.ultraKeyValue(re, "project", project, bg),
		m.ultraKeyValue(re, "tags", tags, bg),
		m.ultraKeyValue(re, "due", due, bg),
		m.ultraKeyValue(re, "recur", recur, bg),
		m.ultraKeyValue(re, "start", start, bg),
	}
	return strings.Join(parts, sep)
}

func (m *Model) renderUltraDescriptionWithRegex(t task.Task, width int, re *regexp.Regexp, bg string) string {
	// Brighter foreground ("253") than annotations to give description visual priority.
	style := lipgloss.NewStyle().Foreground(lipgloss.Color("253"))
	if bg != "" {
		style = style.Background(lipgloss.Color(bg))
	}
	var lines []string
	for _, line := range m.ultraDescriptionLines(t, width) {
		if re != nil && re.MatchString(line) {
			line = m.highlightMatches(line, re)
		}
		lines = append(lines, style.Render(line))
	}
	return strings.Join(lines, "\n")
}

func (m *Model) renderUltraAnnotationsWithRegex(t task.Task, width int, re *regexp.Regexp, bg string) string {
	lines := m.ultraAnnotationsLines(t, width)
	if len(lines) == 0 {
		return ""
	}

	// Dimmer than description ("244") to visually subordinate annotations.
	style := lipgloss.NewStyle().Foreground(lipgloss.Color("244")).Italic(true)
	if bg != "" {
		style = style.Background(lipgloss.Color(bg))
	}
	for i, line := range lines {
		if re != nil && re.MatchString(line) {
			line = m.highlightMatches(line, re)
		}
		lines[i] = style.Render(line)
	}
	return strings.Join(lines, "\n")
}

// ultraSeparator returns a full-width dim line used between cards.
func ultraSeparator(width int) string {
	return lipgloss.NewStyle().Foreground(lipgloss.Color("237")).Render(strings.Repeat("─", width))
}

func (m *Model) ultraRenderCards(tasks []task.Task, width, selected, start, cardBudget int) []string {
	if start < 0 {
		start = 0
	}
	if start > len(tasks) {
		start = len(tasks)
	}

	sep := ultraSeparator(width)
	var lines []string
	used := 0
	for i := start; i < len(tasks); i++ {
		card := m.renderUltraCard(tasks[i], width, i == selected, m.ultraSearchRegex)
		if card == "" {
			continue
		}

		cardHeight := lipgloss.Height(card)
		// Account for separator line (1 line) between cards.
		if len(lines) > 0 {
			if used+1+cardHeight > cardBudget {
				break
			}
			lines = append(lines, sep)
			used++
		} else if cardHeight > cardBudget {
			break
		}

		if used+cardHeight > cardBudget {
			break
		}
		lines = append(lines, strings.Split(card, "\n")...)
		used += cardHeight
	}
	return lines
}

// ultraStyledText renders text with style, applying bg as the background so
// ANSI resets emitted by the inner Render call do not expose the terminal
// default (black) inside a selected card.
func (m *Model) ultraStyledText(re *regexp.Regexp, style lipgloss.Style, text, bg string) string {
	if bg != "" {
		style = style.Background(lipgloss.Color(bg))
	}
	if re != nil && re.MatchString(text) {
		text = m.highlightMatches(text, re)
	}
	return style.Render(ultraOrDash(text))
}

// renderUltraSearchLine renders a full-line search match, applying bg when set.
func (m *Model) renderUltraSearchLine(text string, style lipgloss.Style, re *regexp.Regexp, bg string) string {
	if bg != "" {
		style = style.Background(lipgloss.Color(bg))
	}
	if re != nil && re.MatchString(text) {
		text = m.highlightMatches(text, re)
	}
	return style.Render(text)
}

// ultraFieldSep returns the field separator with bg applied so it stays on the
// card background even between styled spans.
func ultraFieldSep(bg string) string {
	sep := " | "
	if bg != "" {
		return lipgloss.NewStyle().Background(lipgloss.Color(bg)).Render(sep)
	}
	return sep
}

func (m *Model) ultraKeyValue(re *regexp.Regexp, label, value, bg string) string {
	labelStyle := lipgloss.NewStyle().Bold(true).Foreground(lipgloss.Color(m.theme.HeaderFG))
	valueStyle := lipgloss.NewStyle().Foreground(lipgloss.Color("252"))
	// The space between label and value must also carry bg; a plain " " would
	// expose the terminal default (black) between the two styled spans.
	space := lipgloss.NewStyle().Background(lipgloss.Color(bg)).Render(" ")
	if bg == "" {
		space = " "
	}
	return m.ultraStyledText(re, labelStyle, label+":", bg) + space + m.ultraStyledText(re, valueStyle, value, bg)
}

func ultraCardStyle(theme Theme, width int, selected, blink bool) lipgloss.Style {
	style := lipgloss.NewStyle().Width(width)
	if selected {
		style = style.Foreground(lipgloss.Color(theme.SelectedFG)).Background(lipgloss.Color(theme.SelectedBG))
	}
	if blink {
		style = style.Bold(true).Reverse(true)
	}
	return style
}

func ultraPriorityStyle(theme Theme, priority string) lipgloss.Style {
	// Width(3) so the badge reads as a pill rather than a single character.
	style := lipgloss.NewStyle().Width(3).Align(lipgloss.Center).Bold(true).Foreground(lipgloss.Color("255"))
	switch priority {
	case "H":
		return style.Background(lipgloss.Color(theme.PrioHighBG))
	case "M":
		return style.Background(lipgloss.Color(theme.PrioMedBG))
	case "L":
		return style.Background(lipgloss.Color(theme.PrioLowBG))
	}
	// No priority — render dimly without a badge background.
	return lipgloss.NewStyle().Foreground(lipgloss.Color("240"))
}

func ultraJoinSections(sections ...string) string {
	return ultraJoinSectionsWithBlank("", sections...)
}

// ultraJoinSectionsWithBlank joins non-empty sections separated by blankLine.
// When blankLine is a styled empty string (e.g. with a background colour),
// the inter-section gap carries that style instead of falling back to the
// terminal default. A blankLine of "" means no separator — sections are joined
// with a plain newline for a compact, gap-free layout.
func ultraJoinSectionsWithBlank(blankLine string, sections ...string) string {
	var parts []string
	for _, sec := range sections {
		if sec == "" {
			continue
		}
		if len(parts) > 0 && blankLine != "" {
			// Only insert the blank line when one was explicitly provided.
			parts = append(parts, blankLine)
		}
		parts = append(parts, sec)
	}
	return strings.Join(parts, "\n")
}

func ultraRegexMatchesAny(re *regexp.Regexp, parts ...string) bool {
	if re == nil {
		return false
	}
	for _, part := range parts {
		if re.MatchString(part) {
			return true
		}
	}
	return false
}

func ultraBodyWidth(width int) int {
	if width <= 2 {
		return 20
	}
	w := width - 2
	if w < 20 {
		return 20
	}
	return w
}

func ultraTaskAge(entry string) string {
	if entry == "" {
		return "-"
	}
	ts, err := time.Parse(task.DateFormat, entry)
	if err != nil {
		return entry
	}
	return fmt.Sprintf("%dd", int(time.Since(ts).Hours()/24))
}

func ultraOrDash(text string) string {
	if strings.TrimSpace(text) == "" {
		return "-"
	}
	return text
}

func ultraDueValue(m *Model, due string) string {
	val := m.formatDue(due, 0)
	return ultraOrDash(val)
}

func (m *Model) ultraEnsureVisible() {
	tasks := m.ultraTaskList()
	if len(tasks) == 0 {
		m.ultraCursor = 0
		m.ultraOffset = 0
		return
	}

	if m.ultraCursor < 0 {
		m.ultraCursor = 0
	}
	if m.ultraCursor >= len(tasks) {
		m.ultraCursor = len(tasks) - 1
	}
	if m.ultraOffset < 0 {
		m.ultraOffset = 0
	}
	if m.ultraOffset >= len(tasks) {
		m.ultraOffset = len(tasks) - 1
	}

	for range tasks {
		visible := m.ultraVisibleCount()
		if visible <= 0 {
			if m.ultraOffset == m.ultraCursor {
				return
			}
			m.ultraOffset = m.ultraCursor
			continue
		}

		start := m.ultraVisibleStart(len(tasks))
		end := start + visible - 1
		if m.ultraCursor < start {
			if m.ultraOffset == m.ultraCursor {
				return
			}
			m.ultraOffset = m.ultraCursor
			continue
		}
		if m.ultraCursor > end {
			next := m.ultraCursor - visible + 1
			if next < 0 {
				next = 0
			}
			if next == m.ultraOffset {
				return
			}
			m.ultraOffset = next
			continue
		}
		return
	}
}

// handleUltraMode handles keyboard input in ultra mode.
func (m *Model) handleUltraMode(msg tea.KeyPressMsg) (tea.Model, tea.Cmd) {
	switch msg.String() {
	case "H":
		return m.handleToggleHelp()
	case "q", "esc":
		return m.handleQuitOrEscape()
	case "u":
		// Toggle back to the traditional table view. Works even when started
		// via --ultra because the table model always exists; it was just never
		// shown. The user can press u again to return to ultra mode.
		m.ultraClearFocusedID()
		m.showUltra = false
		m.ultraStartup = false // no longer forced into ultra-only mode
		m.ultraSearchRegex = nil
		m.ultraFiltered = nil
		m.ultraSearchInput.SetValue("")
		// Sync the table cursor to the task we were on in ultra mode.
		tasks := m.ultraTaskList()
		if m.ultraCursor >= 0 && m.ultraCursor < len(tasks) {
			m.tbl.SetCursor(m.ultraCursor)
		}
		return m, nil
	case "/":
		m.ultraSearching = true
		m.ultraSearchInput.SetValue("")
		m.ultraSearchInput.Focus()
		return m, nil
	case "j", "down":
		m.ultraMoveCursor(1)
	case "k", "up":
		m.ultraMoveCursor(-1)
	case "n":
		m.ultraMoveSearchMatch(1)
	case "N":
		m.ultraMoveSearchMatch(-1)
	case "pgdn", "pgdown", "space":
		m.ultraMoveCursor(m.ultraVisibleCount())
	case "pgup", "b":
		m.ultraMoveCursor(-m.ultraVisibleCount())
	case "g", "home":
		m.ultraGoHome()
	case "G", "end":
		m.ultraGoEnd()
	case "enter", "e", "E":
		return m.handleUltraEditTask()
	case "s":
		return m.handleUltraToggleStart()
	case "d":
		return m.handleUltraMarkDone()
	case "p":
		return m.handleUltraSetPriority()
	case "w":
		return m.handleUltraSetDueDate()
	case "W":
		return m.handleUltraRemoveDueDate()
	case "t":
		return m.handleUltraEditTags()
	case "a":
		return m.handleUltraAnnotate(false)
	case "A":
		return m.handleUltraAnnotate(true)
	case "J":
		return m.handleUltraEditProject()
	case "R":
		return m.handleUltraSetRecurrence()
	case "f":
		return m.handleFilter()
	case "+":
		m.ultraClearFocusedID()
		return m.handleAddTask()
	case "U":
		return m.handleUndo()
	case "c":
		return m.handleRandomTheme()
	case "C":
		return m.handleResetTheme()
	case "x":
		return m.handleToggleDisco()
	case "B":
		return m.handleToggleBlink()
	}
	return m, nil
}

func (m *Model) ultraMoveCursor(delta int) {
	m.ultraFocusedID = 0

	tasks := m.ultraTaskList()
	last := len(tasks) - 1
	if last >= 0 {
		m.ultraCursor += delta
		if m.ultraCursor < 0 {
			m.ultraCursor = 0
		}
		if m.ultraCursor > last {
			m.ultraCursor = last
		}
	}

	m.ultraEnsureVisible()
}

func (m *Model) ultraGoHome() {
	m.ultraFocusedID = 0
	m.ultraCursor = 0
	m.ultraOffset = 0
}

func (m *Model) ultraGoEnd() {
	m.ultraFocusedID = 0

	tasks := m.ultraTaskList()
	if last := len(tasks) - 1; last >= 0 {
		m.ultraCursor = last
	} else {
		m.ultraCursor = 0
	}

	m.ultraEnsureVisible()
}

func (m *Model) ultraClearFocusedID() {
	m.ultraFocusedID = 0
}

func (m *Model) ultraPrepareSelectedTask() (int, bool) {
	id, err := m.getUltraSelectedTaskID()
	if err != nil {
		return 0, false
	}
	if !m.selectTaskByID(id) {
		return 0, false
	}

	m.ultraFocusedID = id
	return id, true
}

func (m *Model) handleUltraEditTask() (tea.Model, tea.Cmd) {
	id, ok := m.ultraPrepareSelectedTask()
	if !ok {
		return m, nil
	}

	m.editID = id
	return m, editCmd(id)
}

func (m *Model) handleUltraToggleStart() (tea.Model, tea.Cmd) {
	if _, ok := m.ultraPrepareSelectedTask(); !ok {
		return m, nil
	}

	return m.handleToggleStart()
}

func (m *Model) handleUltraMarkDone() (tea.Model, tea.Cmd) {
	id, ok := m.ultraPrepareSelectedTask()
	if !ok {
		return m, nil
	}

	return m, m.startBlink(id, true)
}

func (m *Model) handleUltraSetPriority() (tea.Model, tea.Cmd) {
	if _, ok := m.ultraPrepareSelectedTask(); !ok {
		return m, nil
	}

	return m.handleSetPriority()
}

func (m *Model) handleUltraSetDueDate() (tea.Model, tea.Cmd) {
	if _, ok := m.ultraPrepareSelectedTask(); !ok {
		return m, nil
	}

	return m.handleSetDueDate()
}

func (m *Model) handleUltraRemoveDueDate() (tea.Model, tea.Cmd) {
	if _, ok := m.ultraPrepareSelectedTask(); !ok {
		return m, nil
	}

	return m.handleRemoveDueDate()
}

func (m *Model) handleUltraEditTags() (tea.Model, tea.Cmd) {
	if _, ok := m.ultraPrepareSelectedTask(); !ok {
		return m, nil
	}

	return m.handleEditTags()
}

func (m *Model) handleUltraAnnotate(replace bool) (tea.Model, tea.Cmd) {
	if _, ok := m.ultraPrepareSelectedTask(); !ok {
		return m, nil
	}

	return m.handleAnnotate(replace)
}

func (m *Model) handleUltraEditProject() (tea.Model, tea.Cmd) {
	if _, ok := m.ultraPrepareSelectedTask(); !ok {
		return m, nil
	}

	return m.handleEditProject()
}

func (m *Model) handleUltraSetRecurrence() (tea.Model, tea.Cmd) {
	if _, ok := m.ultraPrepareSelectedTask(); !ok {
		return m, nil
	}

	return m.handleSetRecurrence()
}