Profpatsch/users/Profpatsch/timetrack/repl.go
   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
package main

import (
	"database/sql"
	"fmt"
	"strings"
	"time"
	"unicode/utf8"

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

// --- Sfttime ---

const sftEpochUnix = 49020 // unix timestamp of sft epoch (1970-01-01 13:37:00 UTC)

// formatSfttime formats the sub-day part of the current sfttime as ".F3C" (4 hex digits)
func formatSfttime(t time.Time) string {
	unix := t.Unix()
	frac := (unix - sftEpochUnix) % 86400
	if frac < 0 {
		frac += 86400
	}
	// 4 hex digits: frac/86400 * 16^4 = frac*65536/86400
	fracHex := (frac * 65536) / 86400
	return fmt.Sprintf(".%04X", fracHex)
}

// --- Styles ---

var (
	styleVerb        = lipgloss.NewStyle().Foreground(ColorTextDim)
	styleShortcode   = lipgloss.NewStyle().Bold(true).Foreground(lipgloss.Color("15"))
	styleDuration    = lipgloss.NewStyle().Foreground(ColorAgeNewest)
	styleUninvoiced  = lipgloss.NewStyle().Foreground(ColorRestartable)
	styleMilestone   = lipgloss.NewStyle().Foreground(ColorAgeMid)
	styleRunning     = lipgloss.NewStyle().Foreground(ColorAgeNewest).Bold(true)
	styleIdle        = lipgloss.NewStyle().Foreground(ColorTextDim)
	styleActions     = lipgloss.NewStyle().Foreground(ColorTextDim)
	stylePrompt      = lipgloss.NewStyle().Foreground(lipgloss.Color("15"))
	styleFuzzyPrompt = lipgloss.NewStyle().Foreground(ColorTextDim)
	styleClientRow   = lipgloss.NewStyle().Foreground(ColorTextDim)
)

// --- Shared helpers ---

// fuzzyMatch returns true if all runes of pattern appear in s in order (case-insensitive)
func fuzzyMatch(s, pattern string) bool {
	s = strings.ToLower(s)
	pattern = strings.ToLower(pattern)
	pi := 0
	for _, r := range s {
		if pi >= utf8.RuneCountInString(pattern) {
			break
		}
		pr, size := utf8.DecodeRuneInString(pattern[pi:])
		if r == pr {
			pi += size
		}
	}
	return pi >= utf8.RuneCountInString(pattern)
}

// formatRunningDuration formats elapsed time as "1h23m" or "45m"
func formatRunningDuration(startTime int64) string {
	elapsed := time.Now().Unix() - startTime
	hours := elapsed / 3600
	minutes := (elapsed % 3600) / 60
	if hours > 0 {
		return fmt.Sprintf("%dh%02dm", hours, minutes)
	}
	return fmt.Sprintf("%dm", minutes)
}

// formatIdleAgo formats how long ago a timestamp was, e.g. "23m ago", "1y5d3h ago"
func formatIdleAgo(ts int64) string {
	elapsed := time.Now().Unix() - ts
	if elapsed < 0 {
		elapsed = 0
	}
	minutes := (elapsed % 3600) / 60
	hours := (elapsed % 86400) / 3600
	days := (elapsed % (365 * 86400)) / 86400
	years := elapsed / (365 * 86400)

	var parts []string
	if years > 0 {
		parts = append(parts, fmt.Sprintf("%dy", years))
	}
	if days > 0 {
		parts = append(parts, fmt.Sprintf("%dd", days))
	}
	if hours > 0 {
		parts = append(parts, fmt.Sprintf("%dh", hours))
	}
	if minutes > 0 || len(parts) == 0 {
		parts = append(parts, fmt.Sprintf("%dm", minutes))
	}
	return strings.Join(parts, "") + " ago"
}

// formatHours formats hours as "3.2h"
func formatHours(h float64) string {
	return fmt.Sprintf("%.1fh", h)
}

// currentMilestoneName returns the name of the most recent milestone for a client, or ""
func currentMilestoneName(client *Client) string {
	if client == nil {
		return ""
	}
	for i := len(client.DisplayItems) - 1; i >= 0; i-- {
		item := client.DisplayItems[i]
		if item.ItemType == "milestone" && item.Milestone != nil {
			return item.Milestone.Name
		}
	}
	return ""
}

// buildClientStatusLine builds the info line for a client (no actions line)
func buildClientInfoLine(client *Client, running *TimeEntry, restartable *TimeEntry) string {
	entries := filterEntries(client.DisplayItems)
	uninvoicedHours := calculateUninvoicedHours(entries)
	milestoneName := currentMilestoneName(client)

	var parts []string
	parts = append(parts, styleIdle.Render(formatSfttime(time.Now())))
	parts = append(parts, styleShortcode.Render(client.Shortcode))

	if running != nil {
		dur := formatRunningDuration(running.StartTime)
		parts = append(parts, styleRunning.Render("RUNNING "+dur))
	} else if restartable != nil {
		ago := formatIdleAgo(restartable.EndTime.Int64)
		parts = append(parts, styleIdle.Render("idle "+ago))
	} else {
		parts = append(parts, styleIdle.Render("idle"))
	}

	parts = append(parts, styleUninvoiced.Render("uninvoiced: "+formatHours(uninvoicedHours)))

	if milestoneName != "" {
		parts = append(parts, styleMilestone.Render("milestone: "+milestoneName))
	}

	return strings.Join(parts, "  |  ")
}

// renderClientRow renders a single client row for the picker, highlighted if selected
func renderClientRow(c Client, selected bool) string {
	entries := filterEntries(c.DisplayItems)
	uninvoiced := calculateUninvoicedHours(entries)
	var lastActivity string
	for i := len(c.DisplayItems) - 1; i >= 0; i-- {
		item := c.DisplayItems[i]
		if item.ItemType == "entry" && item.Entry != nil {
			lastActivity = formatIdleAgo(item.Entry.StartTime)
			break
		}
	}
	text := fmt.Sprintf("  %-6s  %-20s  %-12s  %s uninvoiced",
		c.Shortcode, c.Name, lastActivity, formatHours(uninvoiced))
	if selected {
		return lipgloss.NewStyle().Background(ColorSelectionBackground).Render(text)
	}
	return styleClientRow.Render(text)
}

// actionLine builds a colored action output line
func actionLine(verb, shortcode, duration, uninvoiced string) string {
	parts := []string{styleVerb.Render(verb)}
	if shortcode != "" {
		parts = append(parts, styleShortcode.Render(shortcode))
	}
	if duration != "" {
		parts = append(parts, styleDuration.Render(duration))
	}
	if uninvoiced != "" {
		parts = append(parts, styleUninvoiced.Render("(uninvoiced: "+uninvoiced+")"))
	}
	return strings.Join(parts, " ")
}

// newProgram creates a bubbletea program without alt-screen
func newProgram(m tea.Model) *tea.Program {
	return tea.NewProgram(m)
}

// ============================================================
// Session 1: Picker
// ============================================================

// PickerResult is returned when the picker session ends
type PickerResult struct {
	Client *Client // nil = quit
}

// pickerQuitMsg triggers the actual quit after the final render
type pickerQuitMsg struct{}

type pickerModel struct {
	db          *sql.DB
	clients     []Client
	fuzzyInput  string
	cursorIndex int
	result      *PickerResult // non-nil = session over
	quitting    bool
	excludeID   int64  // client ID to exclude (0 = none)
	label       string // header label
}

func newPickerModel(db *sql.DB, clients []Client, excludeID int64, label string) pickerModel {
	return pickerModel{
		db:        db,
		clients:   clients,
		excludeID: excludeID,
		label:     label,
	}
}

func (m pickerModel) filtered() []Client {
	var result []Client
	for _, c := range m.clients {
		if m.excludeID != 0 && c.ID == m.excludeID {
			continue
		}
		if m.fuzzyInput == "" || fuzzyMatch(c.Name, m.fuzzyInput) || fuzzyMatch(c.Shortcode, m.fuzzyInput) {
			result = append(result, c)
		}
	}
	return result
}

func (m pickerModel) clampCursor() pickerModel {
	f := m.filtered()
	if len(f) == 0 {
		m.cursorIndex = 0
	} else {
		m.cursorIndex = clampRange(m.cursorIndex, 0, len(f)-1)
	}
	return m
}

func (m pickerModel) Init() tea.Cmd { return nil }

func pickerQuitCmd() tea.Msg { return pickerQuitMsg{} }

func (m pickerModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
	switch msg := msg.(type) {
	case pickerQuitMsg:
		return m, tea.Quit

	case tea.KeyMsg:
		switch msg.String() {
		case "ctrl+l":
			return m, tea.ClearScreen

		case "ctrl+q", "ctrl+c":
			m.result = &PickerResult{Client: nil}
			return m, tea.Quit

		case "esc":
			m.result = &PickerResult{Client: nil}
			return m, tea.Quit

		case "ctrl+a":
			if m.excludeID != 0 {
				f := m.filtered()
				if len(f) == 0 {
					return m, nil
				}
				m = m.clampCursor()
				selected := f[m.cursorIndex]
				if err := ArchiveClient(m.db, selected.ID); err != nil {
					return m, nil
				}
				clients, err := LoadClients(m.db)
				if err != nil {
					return m, nil
				}
				m.clients = clients
				m = m.clampCursor()
			}
			return m, nil

		case "ctrl+u":
			if m.excludeID != 0 {
				// Open archived clients picker as a sub-session
				if err := runArchivedPickerSession(m.db); err != nil {
					return m, nil
				}
				// Reload active clients after returning (unarchives may have happened)
				clients, err := LoadClients(m.db)
				if err != nil {
					return m, nil
				}
				m.clients = clients
				m = m.clampCursor()
			}
			return m, nil
		}

		switch msg.Type {
		case tea.KeyUp:
			m.cursorIndex = saturatingDec(m.cursorIndex, 0)
			m = m.clampCursor()

		case tea.KeyDown:
			f := m.filtered()
			m.cursorIndex = saturatingInc(m.cursorIndex, len(f)-1)
			m = m.clampCursor()

		case tea.KeyEnter:
			f := m.filtered()
			if len(f) == 0 {
				return m, nil
			}
			m = m.clampCursor()
			selected := f[m.cursorIndex]
			for i := range m.clients {
				if m.clients[i].ID == selected.ID {
					m.result = &PickerResult{Client: &m.clients[i]}
					break
				}
			}
			m.quitting = true
			return m, pickerQuitCmd

		case tea.KeyBackspace:
			if len(m.fuzzyInput) > 0 {
				runes := []rune(m.fuzzyInput)
				m.fuzzyInput = string(runes[:len(runes)-1])
				m = m.clampCursor()
			}

		case tea.KeyRunes:
			m.fuzzyInput += msg.String()
			m = m.clampCursor()
		}
	}
	return m, nil
}

func (m pickerModel) View() string {
	if m.quitting && m.result != nil && m.result.Client != nil {
		return styleShortcode.Render(m.result.Client.Shortcode)
	}

	var lines []string
	lines = append(lines, stylePrompt.Render(m.label))
	for i, c := range m.filtered() {
		lines = append(lines, renderClientRow(c, i == m.cursorIndex))
	}
	lines = append(lines, styleFuzzyPrompt.Render("> ")+m.fuzzyInput)
	if m.excludeID != 0 {
		lines = append(lines, styleActions.Render("Enter=select  Ctrl+A=archive  Ctrl+U=archived  ESC=back  Ctrl+Q=quit"))
	}
	return strings.Join(lines, "\n")
}

// runPickerSession runs the picker and returns the selected client (nil = quit/back)
func runPickerSession(db *sql.DB, clients []Client, excludeID int64, label string) (*Client, error) {
	m := newPickerModel(db, clients, excludeID, label)
	p := newProgram(m)
	final, err := p.Run()
	if err != nil {
		return nil, err
	}
	result := final.(pickerModel).result
	if result == nil {
		return nil, nil
	}
	return result.Client, nil
}

// ============================================================
// Session 1b: Archived clients picker
// ============================================================

type archivedPickerModel struct {
	db          *sql.DB
	clients     []Client
	cursorIndex int
	fuzzyInput  string
	quitting    bool
}

func (m archivedPickerModel) Init() tea.Cmd { return nil }

func (m archivedPickerModel) filtered() []Client {
	if m.fuzzyInput == "" {
		return m.clients
	}
	var result []Client
	for _, c := range m.clients {
		if fuzzyMatch(c.Name, m.fuzzyInput) || fuzzyMatch(c.Shortcode, m.fuzzyInput) {
			result = append(result, c)
		}
	}
	return result
}

func (m archivedPickerModel) clampCursor() archivedPickerModel {
	f := m.filtered()
	if len(f) == 0 {
		m.cursorIndex = 0
	} else {
		m.cursorIndex = clampRange(m.cursorIndex, 0, len(f)-1)
	}
	return m
}

// archivedPickerQuitMsg triggers quit after final render
type archivedPickerQuitMsg struct{}

func archivedPickerQuitCmd() tea.Msg { return archivedPickerQuitMsg{} }

func (m archivedPickerModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
	switch msg := msg.(type) {
	case archivedPickerQuitMsg:
		return m, tea.Quit

	case tea.KeyMsg:
		switch msg.String() {
		case "ctrl+l":
			return m, tea.ClearScreen
		case "ctrl+q", "ctrl+c", "esc", "ctrl+u":
			m.quitting = true
			return m, archivedPickerQuitCmd
		case "ctrl+a":
			// Unarchive highlighted client
			f := m.filtered()
			if len(f) == 0 {
				return m, nil
			}
			m = m.clampCursor()
			selected := f[m.cursorIndex]
			if err := ArchiveClient(m.db, selected.ID); err != nil {
				return m, nil
			}
			clients, err := LoadArchivedClients(m.db)
			if err != nil {
				return m, nil
			}
			m.clients = clients
			m = m.clampCursor()
			return m, nil
		}

		switch msg.Type {
		case tea.KeyUp:
			m.cursorIndex = saturatingDec(m.cursorIndex, 0)
			m = m.clampCursor()
		case tea.KeyDown:
			f := m.filtered()
			m.cursorIndex = saturatingInc(m.cursorIndex, len(f)-1)
			m = m.clampCursor()
		case tea.KeyBackspace:
			if len(m.fuzzyInput) > 0 {
				runes := []rune(m.fuzzyInput)
				m.fuzzyInput = string(runes[:len(runes)-1])
				m = m.clampCursor()
			}
		case tea.KeyRunes:
			m.fuzzyInput += msg.String()
			m = m.clampCursor()
		}
	}
	return m, nil
}

func (m archivedPickerModel) View() string {
	if m.quitting {
		return stylePrompt.Render("Archived clients")
	}

	var lines []string
	lines = append(lines, stylePrompt.Render("Archived clients:"))
	f := m.filtered()
	if len(f) == 0 {
		lines = append(lines, styleClientRow.Render("  (none)"))
	} else {
		for i, c := range f {
			lines = append(lines, renderClientRow(c, i == m.cursorIndex))
		}
	}
	lines = append(lines, styleFuzzyPrompt.Render("> ")+m.fuzzyInput)
	lines = append(lines, styleActions.Render("Ctrl+A=unarchive  ESC=back  Ctrl+Q=quit"))
	return strings.Join(lines, "\n")
}

// runArchivedPickerSession shows the archived clients list
func runArchivedPickerSession(db *sql.DB) error {
	clients, err := LoadArchivedClients(db)
	if err != nil {
		return err
	}
	m := archivedPickerModel{db: db, clients: clients}
	p := newProgram(m)
	_, err = p.Run()
	return err
}

// ============================================================
// Session 2: Main (status + actions)
// ============================================================

// MainResult is returned when the main session ends
type MainResultKind int

const (
	MainQuit         MainResultKind = iota // Ctrl+Q
	MainAction                             // action taken, print frozenStatus + actionLine
	MainSwitchClient                       // open picker
)

type MainResult struct {
	Kind         MainResultKind
	Client       *Client // current client (may be updated after action)
	FrozenStatus string  // status line to print before action line
	ActionLine   string  // action output line
}

// mainTickMsg is sent every minute to refresh the running timer
type mainTickMsg time.Time

// mainQuitMsg triggers the actual quit after the final render
type mainQuitMsg struct{}

type mainModel struct {
	db       *sql.DB
	client   Client
	result   *MainResult
	quitting bool // when true, View() renders frozenStatus+actionLine then we quit

	// text input sub-phase
	textInput       bool
	textInputBuffer string
	textInputCursor int

	// invoice confirm sub-phase
	invoiceConfirm    bool
	invoiceNumber     string
	invoiceEntryIDs   []int64
	invoiceTotalHours float64
	invoiceEntryCount int
	invoiceDateRange  string
}

func newMainModel(db *sql.DB, client Client) mainModel {
	return mainModel{db: db, client: client}
}

func (m mainModel) Init() tea.Cmd {
	return tea.Tick(time.Minute, func(t time.Time) tea.Msg {
		return mainTickMsg(t)
	})
}

func (m mainModel) runningEntry() *TimeEntry {
	entry, err := GetRunningEntry(m.db, m.client.ID)
	if err != nil {
		return nil
	}
	return entry
}

func (m mainModel) restartableEntry() *TimeEntry {
	entries := filterEntries(m.client.DisplayItems)
	return findMostRecentCompletedEntry(entries)
}

func (m *mainModel) reload() error {
	clients, err := LoadClients(m.db)
	if err != nil {
		return err
	}
	for i := range clients {
		if clients[i].ID == m.client.ID {
			m.client = clients[i]
			return nil
		}
	}
	return nil
}

func (m mainModel) statusLine() string {
	running := m.runningEntry()
	restartable := m.restartableEntry()
	return buildClientInfoLine(&m.client, running, restartable)
}

func (m mainModel) actionsLine() string {
	running := m.runningEntry()
	var actions []string
	if running != nil {
		actions = append(actions, "t=stop")
	} else {
		if m.restartableEntry() != nil {
			actions = append(actions, "t=restart", "T=new")
		} else {
			actions = append(actions, "t=start")
		}
	}
	actions = append(actions, "c=client", "m=milestone")
	entries := filterEntries(m.client.DisplayItems)
	if calculateUninvoicedHours(entries) > 0 {
		actions = append(actions, "i=invoice")
	}
	actions = append(actions, "Ctrl+Q=quit")
	return styleActions.Render(strings.Join(actions, "  "))
}

// quitCmd triggers the final-render-then-quit sequence
func quitCmd() tea.Msg { return mainQuitMsg{} }

func (m mainModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
	switch msg := msg.(type) {
	case mainQuitMsg:
		// Final render has happened, now actually quit
		return m, tea.Quit

	case mainTickMsg:
		return m, tea.Tick(time.Minute, func(t time.Time) tea.Msg {
			return mainTickMsg(t)
		})

	case tea.KeyMsg:
		if msg.String() == "ctrl+l" {
			return m, tea.ClearScreen
		}

		if m.textInput {
			return m.updateTextInput(msg)
		}
		return m.updateNormal(msg)
	}
	return m, nil
}

func (m mainModel) updateNormal(msg tea.KeyMsg) (tea.Model, tea.Cmd) {
	// Invoice confirm sub-phase
	if m.invoiceConfirm {
		switch msg.String() {
		case "ctrl+q", "ctrl+c":
			m.result = &MainResult{Kind: MainQuit, Client: &m.client}
			return m, tea.Quit
		case "esc":
			m.invoiceConfirm = false
			return m, nil
		case "enter", " ":
			return m.commitInvoice()
		}
		return m, nil
	}

	switch msg.String() {
	case "ctrl+q", "ctrl+c":
		m.result = &MainResult{Kind: MainQuit, Client: &m.client}
		return m, tea.Quit // no final render needed for quit

	case "t":
		return m.handleToggle()

	case "T":
		return m.handleForceStart()

	case "c":
		frozen := m.statusLine()
		m.result = &MainResult{
			Kind:         MainSwitchClient,
			Client:       &m.client,
			FrozenStatus: frozen,
			ActionLine:   styleActions.Render("c=client"),
		}
		m.quitting = true
		return m, quitCmd

	case "m":
		m.textInput = true
		m.textInputBuffer = ""
		m.textInputCursor = 0
		return m, nil

	case "i":
		return m.handleInvoice()
	}
	return m, nil
}

func (m mainModel) updateTextInput(msg tea.KeyMsg) (tea.Model, tea.Cmd) {
	switch msg.Type {
	case tea.KeyCtrlQ, tea.KeyCtrlC:
		m.result = &MainResult{Kind: MainQuit, Client: &m.client}
		return m, tea.Quit // no final render needed for quit

	case tea.KeyEscape:
		m.textInput = false
		m.textInputBuffer = ""
		m.textInputCursor = 0
		return m, nil

	case tea.KeyEnter:
		if m.textInputBuffer == "" {
			m.textInput = false
			return m, nil
		}
		return m.commitMilestone()

	case tea.KeyBackspace:
		if m.textInputCursor > 0 {
			runes := []rune(m.textInputBuffer)
			runes = append(runes[:m.textInputCursor-1], runes[m.textInputCursor:]...)
			m.textInputBuffer = string(runes)
			m.textInputCursor--
		}

	case tea.KeyLeft:
		if m.textInputCursor > 0 {
			m.textInputCursor--
		}

	case tea.KeyRight:
		if m.textInputCursor < utf8.RuneCountInString(m.textInputBuffer) {
			m.textInputCursor++
		}

	case tea.KeyRunes:
		runes := []rune(m.textInputBuffer)
		newRunes := []rune(msg.String())
		runes = append(runes[:m.textInputCursor], append(newRunes, runes[m.textInputCursor:]...)...)
		m.textInputBuffer = string(runes)
		m.textInputCursor += len(newRunes)
	}
	return m, nil
}

func (m mainModel) commitMilestone() (tea.Model, tea.Cmd) {
	frozen := m.statusLine()
	ts := time.Now().Unix()
	if running := m.runningEntry(); running != nil {
		ts = running.StartTime
	}
	name := m.textInputBuffer
	var actionStr string
	if err := CreateMilestone(m.db, m.client.ID, name, ts); err != nil {
		actionStr = styleVerb.Render("error: " + err.Error())
	} else {
		actionStr = styleVerb.Render("milestone ") + styleMilestone.Render(`"`+name+`"`)
		_ = m.reload()
	}
	m.result = &MainResult{
		Kind:         MainAction,
		Client:       &m.client,
		FrozenStatus: frozen,
		ActionLine:   actionStr,
	}
	m.quitting = true
	return m, quitCmd
}

func (m mainModel) setActionResult(frozen, line string) (tea.Model, tea.Cmd) {
	m.result = &MainResult{Kind: MainAction, Client: &m.client, FrozenStatus: frozen, ActionLine: line}
	m.quitting = true
	return m, quitCmd
}

func (m mainModel) handleToggle() (tea.Model, tea.Cmd) {
	frozen := m.statusLine()
	running := m.runningEntry()

	if running != nil {
		if err := StopEntry(m.db, running.ID); err != nil {
			return m.setActionResult(frozen, styleVerb.Render("error: "+err.Error()))
		}
		_ = m.reload()
		entries := filterEntries(m.client.DisplayItems)
		uninvoicedHours := calculateUninvoicedHours(entries)
		dur := formatRunningDuration(running.StartTime)
		return m.setActionResult(frozen, actionLine("stop", m.client.Shortcode, "+"+dur, formatHours(uninvoicedHours)))
	}

	restartable := m.restartableEntry()
	if restartable != nil {
		if err := RestartEntry(m.db, restartable.ID); err != nil {
			return m.setActionResult(frozen, styleVerb.Render("error: "+err.Error()))
		}
		_ = m.reload()
		return m.setActionResult(frozen, actionLine("restart", m.client.Shortcode, "", ""))
	}

	if err := StartNewEntry(m.db, m.client.ID); err != nil {
		return m.setActionResult(frozen, styleVerb.Render("error: "+err.Error()))
	}
	_ = m.reload()
	return m.setActionResult(frozen, actionLine("start", m.client.Shortcode, "", ""))
}

func (m mainModel) handleForceStart() (tea.Model, tea.Cmd) {
	if m.runningEntry() != nil {
		return m, nil
	}
	frozen := m.statusLine()
	if err := StartNewEntry(m.db, m.client.ID); err != nil {
		return m.setActionResult(frozen, styleVerb.Render("error: "+err.Error()))
	}
	_ = m.reload()
	return m.setActionResult(frozen, actionLine("start", m.client.Shortcode, "", ""))
}

func (m mainModel) handleInvoice() (tea.Model, tea.Cmd) {
	if m.client.Shortcode == "" {
		frozen := m.statusLine()
		return m.setActionResult(frozen, styleVerb.Render("error: client has no shortcode"))
	}

	entries := filterEntries(m.client.DisplayItems)
	var uninvoicedIDs []int64
	var totalHours float64
	var minDate, maxDate string
	for _, e := range entries {
		if !e.InvoiceID.Valid && e.EndTime.Valid {
			uninvoicedIDs = append(uninvoicedIDs, e.ID)
			totalHours += float64(e.EndTime.Int64-e.StartTime) / 3600.0
			d := timestampToDate(e.StartTime)
			if minDate == "" || d < minDate {
				minDate = d
			}
			if maxDate == "" || d > maxDate {
				maxDate = d
			}
		}
	}
	if len(uninvoicedIDs) == 0 {
		frozen := m.statusLine()
		return m.setActionResult(frozen, styleVerb.Render("no uninvoiced entries"))
	}

	invoiceNumber, err := GenerateInvoiceNumber(m.db, m.client.Shortcode)
	if err != nil {
		frozen := m.statusLine()
		return m.setActionResult(frozen, styleVerb.Render("error: "+err.Error()))
	}

	dateRange := minDate
	if maxDate != minDate {
		dateRange = minDate + " to " + maxDate
	}

	m.invoiceConfirm = true
	m.invoiceNumber = invoiceNumber
	m.invoiceEntryIDs = uninvoicedIDs
	m.invoiceTotalHours = totalHours
	m.invoiceEntryCount = len(uninvoicedIDs)
	m.invoiceDateRange = dateRange
	return m, nil
}

func (m mainModel) commitInvoice() (tea.Model, tea.Cmd) {
	frozen := m.statusLine()
	invoice, err := CreateInvoice(m.db, m.client.ID, m.invoiceEntryIDs, nil, "")
	if err != nil {
		return m.setActionResult(frozen, styleVerb.Render("error: "+err.Error()))
	}
	_ = m.reload()
	line := styleVerb.Render("invoice") + " " +
		styleShortcode.Render(m.client.Shortcode) + " " +
		styleMilestone.Render(invoice.InvoiceNumber) + " " +
		styleDuration.Render(fmt.Sprintf("(%.1fh, %d entries)", m.invoiceTotalHours, m.invoiceEntryCount))
	return m.setActionResult(frozen, line)
}

func (m mainModel) View() string {
	// When quitting, render the frozen status + action line as the final frame
	if m.quitting && m.result != nil {
		return m.result.FrozenStatus + "\n" + m.result.ActionLine
	}

	var lines []string
	lines = append(lines, m.statusLine())

	if m.invoiceConfirm {
		summary := styleMilestone.Render(m.invoiceNumber) + "  " +
			styleDuration.Render(fmt.Sprintf("%.1fh", m.invoiceTotalHours)) + "  " +
			styleVerb.Render(fmt.Sprintf("%d entries", m.invoiceEntryCount)) + "  " +
			styleVerb.Render(m.invoiceDateRange) + "   " +
			styleActions.Render("Enter=confirm  ESC=cancel")
		lines = append(lines, summary)
		return strings.Join(lines, "\n")
	}

	if m.textInput {
		// render text input prompt instead of actions
		runes := []rune(m.textInputBuffer)
		var rendered string
		if m.textInputCursor < len(runes) {
			cursorStyle := lipgloss.NewStyle().Background(ColorCursorBackground).Foreground(ColorCursorForeground)
			rendered = string(runes[:m.textInputCursor]) + cursorStyle.Render(string(runes[m.textInputCursor])) + string(runes[m.textInputCursor+1:])
		} else {
			cursorStyle := lipgloss.NewStyle().Background(ColorCursorBackground)
			rendered = string(runes) + cursorStyle.Render(" ")
		}
		lines = append(lines, stylePrompt.Render("milestone name: ")+rendered)
		lines = append(lines, styleActions.Render("Enter=confirm  ESC=cancel  Ctrl+Q=quit"))
	} else {
		lines = append(lines, m.actionsLine())
	}

	return strings.Join(lines, "\n")
}

// runMainSession runs one main session and returns the result
func runMainSession(db *sql.DB, client Client) (*MainResult, error) {
	m := newMainModel(db, client)
	p := newProgram(m)
	final, err := p.Run()
	if err != nil {
		return nil, err
	}
	result := final.(mainModel).result
	if result == nil {
		// program was killed externally
		return &MainResult{Kind: MainQuit, Client: &client}, nil
	}
	return result, nil
}

// ============================================================
// Session 3: Create client
// ============================================================

type createClientResult struct {
	client *Client // nil = quit
}

type createClientPhase int

const (
	createClientPhaseName createClientPhase = iota
	createClientPhaseShortcode
)

type createClientModel struct {
	db          *sql.DB
	phase       createClientPhase
	name        string
	inputBuffer string
	inputCursor int
	result      *createClientResult
}

func (m createClientModel) Init() tea.Cmd { return nil }

func (m createClientModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
	msg2, ok := msg.(tea.KeyMsg)
	if !ok {
		return m, nil
	}

	if msg2.String() == "ctrl+q" || msg2.String() == "ctrl+c" {
		m.result = &createClientResult{client: nil}
		return m, tea.Quit
	}

	switch msg2.Type {
	case tea.KeyEnter:
		if m.inputBuffer == "" {
			return m, nil
		}
		if m.phase == createClientPhaseName {
			m.name = m.inputBuffer
			m.inputBuffer = ""
			m.inputCursor = 0
			m.phase = createClientPhaseShortcode
			return m, nil
		}
		// create the client
		shortcode := strings.ToUpper(m.inputBuffer)
		if err := CreateClient(m.db, m.name, shortcode); err != nil {
			// just reset and try again
			m.inputBuffer = ""
			m.inputCursor = 0
			return m, nil
		}
		// load the new client
		clients, err := LoadClients(m.db)
		if err != nil {
			m.result = &createClientResult{client: nil}
			return m, tea.Quit
		}
		for i := range clients {
			if clients[i].Name == m.name {
				m.result = &createClientResult{client: &clients[i]}
				break
			}
		}
		return m, tea.Quit

	case tea.KeyBackspace:
		if m.inputCursor > 0 {
			runes := []rune(m.inputBuffer)
			runes = append(runes[:m.inputCursor-1], runes[m.inputCursor:]...)
			m.inputBuffer = string(runes)
			m.inputCursor--
		}

	case tea.KeyLeft:
		if m.inputCursor > 0 {
			m.inputCursor--
		}

	case tea.KeyRight:
		if m.inputCursor < utf8.RuneCountInString(m.inputBuffer) {
			m.inputCursor++
		}

	case tea.KeyRunes:
		input := msg2.String()
		if m.phase == createClientPhaseShortcode {
			input = strings.ToUpper(input)
		}
		runes := []rune(m.inputBuffer)
		newRunes := []rune(input)
		runes = append(runes[:m.inputCursor], append(newRunes, runes[m.inputCursor:]...)...)
		m.inputBuffer = string(runes)
		m.inputCursor += len(newRunes)
	}

	return m, nil
}

func (m createClientModel) View() string {
	runes := []rune(m.inputBuffer)
	var rendered string
	if m.inputCursor < len(runes) {
		cursorStyle := lipgloss.NewStyle().Background(ColorCursorBackground).Foreground(ColorCursorForeground)
		rendered = string(runes[:m.inputCursor]) + cursorStyle.Render(string(runes[m.inputCursor])) + string(runes[m.inputCursor+1:])
	} else {
		cursorStyle := lipgloss.NewStyle().Background(ColorCursorBackground)
		rendered = string(runes) + cursorStyle.Render(" ")
	}

	var prompt string
	if m.phase == createClientPhaseName {
		prompt = "client name"
	} else {
		prompt = fmt.Sprintf("shortcode for '%s'", m.name)
	}
	return stylePrompt.Render(prompt+": ") + rendered
}

// runCreateClientSession runs the create-client flow and returns the new client (nil = quit)
func runCreateClientSession(db *sql.DB) (*Client, error) {
	m := createClientModel{db: db}
	p := newProgram(m)
	final, err := p.Run()
	if err != nil {
		return nil, err
	}
	result := final.(createClientModel).result
	if result == nil {
		return nil, nil
	}
	return result.client, nil
}

// ============================================================
// Outer loop
// ============================================================

// RunRepl is the main entry point for the repl mode
func RunRepl(db *sql.DB) error {
	clients, err := LoadClients(db)
	if err != nil {
		return fmt.Errorf("failed to load clients: %w", err)
	}

	// No clients: prompt to create one
	if len(clients) == 0 {
		client, err := runCreateClientSession(db)
		if err != nil {
			return err
		}
		if client == nil {
			return nil // quit
		}
		clients = []Client{*client}
	}

	// Start with most recent client (DB already orders by last activity)
	current := clients[0]

	for {
		result, err := runMainSession(db, current)
		if err != nil {
			return err
		}

		switch result.Kind {
		case MainQuit:
			return nil

		case MainAction:
			current = *result.Client

		case MainSwitchClient:
			// reload clients for picker
			clients, err = LoadClients(db)
			if err != nil {
				return err
			}

			picked, err := runPickerSession(db, clients, current.ID, "Switch client:")
			if err != nil {
				return err
			}
			if picked != nil {
				current = *picked
			}
			// whether picked or ESC'd, start a new main session
		}
	}
}