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
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
package main

import (
	"bytes"
	"database/sql"
	"encoding/json"
	"fmt"
	"log"
	"os"
	"strings"
	"time"

	tea "github.com/charmbracelet/bubbletea"
	"github.com/charmbracelet/lipgloss"
	_ "modernc.org/sqlite"
)

var logBuffer bytes.Buffer

// tickMsg is sent every minute to update the display
type tickMsg time.Time

// TimeEntry represents a single time tracking entry
type TimeEntry struct {
	ID            int64
	ClientID      int64
	StartTime     int64          // Unix timestamp
	EndTime       sql.NullInt64  // Unix timestamp, NULL = in progress
	Comment       string         // Optional comment/description
	InvoiceID     sql.NullInt64  // Invoice ID if invoiced
	InvoiceNumber sql.NullString // Invoice number if invoiced
	Index         int            // Display index (1-based position in client's entry list)
}

// Milestone represents a marker in the timeline showing project phases
type Milestone struct {
	ID        int64
	ClientID  int64
	Name      string
	Timestamp int64 // Unix timestamp
}

// DisplayItem represents either a time entry or milestone for unified rendering
type DisplayItem struct {
	ItemType        string // "entry" or "milestone"
	Entry           *TimeEntry
	Milestone       *Milestone
	SortTimestamp   int64   // For sorting: entry.StartTime or milestone.Timestamp
	DisplayIndex    int     // 1-based display position
	CumulativeHours float64 // Hours accumulated up to this point
}

// Client represents a client with their time entries and milestones
type Client struct {
	ID           int64
	Name         string
	Shortcode    string // Invoice prefix (e.g., "NP" for NewPipe)
	DisplayItems []DisplayItem
	TargetHours  float64
	Archived     bool
	ArchivedAt   sql.NullInt64 // Unix timestamp of when archived/unarchived
}

// filterEntries extracts only TimeEntry items from DisplayItems
func filterEntries(items []DisplayItem) []TimeEntry {
	var entries []TimeEntry
	for _, item := range items {
		if item.ItemType == "entry" && item.Entry != nil {
			entries = append(entries, *item.Entry)
		}
	}
	return entries
}

// InputMode represents the current input mode of the TUI
type InputMode int

const (
	InputModeNormal                  InputMode = iota // Normal navigation mode
	InputModeCreatingClient                           // Creating a new client (entering name)
	InputModeCreatingClientShortcode                  // Creating a new client (entering shortcode)
	InputModeCreatingMilestone                        // Creating a new milestone (entering name)
	InputModeEditingMilestone                         // Editing an existing milestone (entering name)
	InputModeInvoicePreview                           // Previewing invoice creation
	InputModeMessage                                  // Showing a message dialog
	// Note: InputModeEditingComment and InputModeBlockedEdit are handled by TimestampTableModel component
)

// ClientScrollPosition stores scroll state for a specific client
type ClientScrollPosition struct {
	selectedRow   int // Currently selected row (0-based)
	viewportStart int // First visible row in viewport
}

// ScrollStateEntry represents the saved scroll state for a single client
type ScrollStateEntry struct {
	ClientID       int64 `json:"client_id"`
	CursorPosition int   `json:"cursor_position"` // Absolute cursor position (selectedRow) - source of truth
	ViewportOffset int   `json:"viewport_offset"` // Relative: how many rows before cursor the viewport starts
}

// Model is the bubbletea model for the timetracking TUI
type Model struct {
	// Core data
	clients        []Client
	selectedClient int     // Index of currently selected client
	db             *sql.DB // Database connection

	// Navigation state
	selectedRow int // Currently selected row (0-based)
	pageSize    int // Number of visible rows (note: viewport is managed by timestampTable)

	// Per-client scroll positions (keyed by client ID)
	clientScrollPositions map[int64]ClientScrollPosition

	// Timestamp table component
	timestampTable TimestampTableModel

	// Input state
	inputMode          InputMode // Current input mode
	inputBuffer        string    // Text buffer for input mode (used for client creation, milestone creation)
	cursorPos          int       // Cursor position in input buffer (0 = start)
	pendingClientName  string    // Temporary storage for client name while prompting for shortcode
	editingMilestoneID int64     // ID of milestone being edited (for edit mode)
	milestoneTimestamp int64     // Timestamp for new milestone being created
	// Note: Comment editing state (editingEntryID, originalComment, blockedEditMessage) is now in TimestampTableModel

	// View state
	archivedView   *ArchivedViewModel   // nil when in normal mode, non-nil when viewing archived clients
	invoicePreview *InvoicePreviewModel // nil when in normal mode, non-nil when previewing invoice

	// Message dialog state
	messageText string // Text to display in message dialog

	// Terminal dimensions
	windowWidth  int
	windowHeight int
}

// NewModel creates a new Model with clients loaded from the database
func NewModel(db *sql.DB) (Model, error) {
	clients, err := LoadClients(db)
	if err != nil {
		return Model{}, fmt.Errorf("failed to load clients: %w", err)
	}

	// Initialize scroll positions map
	scrollPositions := make(map[int64]ClientScrollPosition)

	// Try to load saved scroll positions from database (JSON format)
	scrollStateJSON, err := LoadUIState(db, "scroll_state")
	if err == nil && scrollStateJSON != "" {
		var scrollStates []ScrollStateEntry
		if err := json.Unmarshal([]byte(scrollStateJSON), &scrollStates); err == nil {
			// Load saved positions into map
			for _, state := range scrollStates {
				cursorPosition := state.CursorPosition
				viewportOffset := state.ViewportOffset

				// Find the client to check bounds
				for _, client := range clients {
					if client.ID == state.ClientID {
						// Clamp cursor to valid range [0, len(items)-1]
						cursorPosition = clampIndex(cursorPosition, len(client.DisplayItems))

						// Calculate viewportStart from cursor and relative offset
						// viewportStart = cursor - offset (offset = how many rows before cursor)
						viewportStart := cursorPosition - viewportOffset

						// Clamp viewportStart to be non-negative (viewport can't start before list)
						viewportStart = clampMin(viewportStart, 0)

						scrollPositions[client.ID] = ClientScrollPosition{
							selectedRow:   cursorPosition,
							viewportStart: viewportStart,
						}
						break
					}
				}
			}
		}
	}

	// For any clients without saved positions, default to end of list
	for _, client := range clients {
		if _, exists := scrollPositions[client.ID]; !exists {
			if len(client.DisplayItems) > 0 {
				scrollPositions[client.ID] = ClientScrollPosition{
					selectedRow:   len(client.DisplayItems) - 1,
					viewportStart: 0, // Will be adjusted by viewport logic
				}
			} else {
				scrollPositions[client.ID] = ClientScrollPosition{
					selectedRow:   0,
					viewportStart: 0,
				}
			}
		}
	}

	// Try to load saved selected client ID
	selectedClientIndex := 0
	savedClientIDStr, err := LoadUIState(db, "selected_client_id")
	if err == nil && savedClientIDStr != "" {
		var savedClientID int64
		if _, err := fmt.Sscanf(savedClientIDStr, "%d", &savedClientID); err == nil {
			// Find the client with this ID
			for i, client := range clients {
				if client.ID == savedClientID {
					selectedClientIndex = i
					break
				}
			}
		}
	}

	// Set initial position based on selected client's scroll position
	var initialRow, initialViewport int
	if len(clients) > 0 && selectedClientIndex < len(clients) {
		selectedClient := clients[selectedClientIndex]
		initialPos := scrollPositions[selectedClient.ID]
		initialRow = initialPos.selectedRow
		initialViewport = initialPos.viewportStart
	}

	// Create border style for timestamp table (will be updated with window size)
	borderStyle := lipgloss.NewStyle().
		Border(lipgloss.RoundedBorder()).
		BorderForeground(ColorTableBorder)

	// Create timestamp table with default dimensions (will be updated on first WindowSizeMsg)
	timestampTable := NewTimestampTableModel(80, borderStyle)
	// Set initial selected row and viewport from loaded state
	var initialItemCount int
	if len(clients) > 0 {
		initialItemCount = len(clients[selectedClientIndex].DisplayItems)
	}
	timestampTable.SetSelectedRow(initialRow, initialItemCount)
	timestampTable.SetViewportStart(initialViewport)
	// Note: pageSize will be set on first WindowSizeMsg

	model := Model{
		clients:               clients,
		selectedClient:        selectedClientIndex,
		selectedRow:           initialRow,
		clientScrollPositions: scrollPositions,
		timestampTable:        timestampTable,
		db:                    db,
	}

	return model, nil
}

// Init initializes the model (bubbletea interface)
func (m Model) Init() tea.Cmd {
	// Start the periodic tick to update calculated values every minute
	return tea.Tick(time.Minute, func(t time.Time) tea.Msg {
		return tickMsg(t)
	})
}

// calculateRestartableEntryID returns the ID of the entry that can be restarted with 't',
// or -1 if there is no restartable entry.
// An entry is restartable if it's the most recent completed entry and ended < 15min ago.
// Only returns a valid ID if no entry is currently running.
func calculateRestartableEntryID(entries []TimeEntry) int64 {
	// Check if there's a running entry
	hasRunningEntry := false
	for _, entry := range entries {
		if !entry.EndTime.Valid {
			hasRunningEntry = true
			break
		}
	}

	// Only show restartable entry if nothing is running
	if hasRunningEntry {
		return -1
	}

	// Find the most recent completed entry
	restartableEntry := findMostRecentCompletedEntry(entries)
	if restartableEntry != nil {
		return restartableEntry.ID
	}

	return -1
}

// renderInputTextWithCursor renders input text with a cursor at the specified position.
// The cursor is shown as a highlighted character (if on a char) or a block at the end.
func renderInputTextWithCursor(buffer string, cursorPos int) string {
	if cursorPos < len(buffer) {
		// Cursor is on a character - highlight it with background
		before := buffer[:cursorPos]
		cursorChar := string(buffer[cursorPos])
		after := buffer[cursorPos+1:]
		cursorStyle := lipgloss.NewStyle().Background(ColorCursorBackground).Foreground(ColorCursorForeground)
		return before + cursorStyle.Render(cursorChar) + after
	}
	// Cursor is at end - show a block cursor
	cursorStyle := lipgloss.NewStyle().Background(ColorCursorBackground)
	return buffer + cursorStyle.Render(" ")
}

// renderTabs renders the client tab bar at the top of the view.
func (m Model) renderTabs() string {
	var tabs strings.Builder
	for i, client := range m.clients {
		tabStyle := lipgloss.NewStyle().Padding(0, 1).Foreground(ColorTextDim)
		if i == m.selectedClient {
			// Highlight selected client
			tabStyle = tabStyle.Background(ColorSelectionBackground).Foreground(ColorDialogForeground).Bold(true)
		}
		tabs.WriteString(tabStyle.Render(client.Name))
		if i < len(m.clients)-1 {
			tabSep := lipgloss.NewStyle().Foreground(ColorTextDim).Render(" | ")
			tabs.WriteString(tabSep)
		}
	}
	return tabs.String() + "\n"
}

// createCustomBorder creates a custom border based on the current input mode.
// For input modes, the bottom border shows the input prompt with cursor.
func (m Model) createCustomBorder() lipgloss.Border {
	customBorder := lipgloss.RoundedBorder()
	if m.inputMode == InputModeCreatingClient {
		// Show input prompt in bottom border with cursor at correct position
		text := renderInputTextWithCursor(m.inputBuffer, m.cursorPos)
		customBorder.Bottom = "─────New client name: " + text + "─────"
	} else if m.inputMode == InputModeCreatingClientShortcode {
		// Show shortcode prompt in bottom border
		text := renderInputTextWithCursor(m.inputBuffer, m.cursorPos)
		customBorder.Bottom = fmt.Sprintf("─────Shortcode for '%s': %s─────", m.pendingClientName, text)
	} else if m.inputMode == InputModeCreatingMilestone {
		// Show milestone creation prompt in bottom border
		text := renderInputTextWithCursor(m.inputBuffer, m.cursorPos)
		customBorder.Bottom = "─────New milestone: " + text + "─────"
	} else if m.inputMode == InputModeEditingMilestone {
		// Show milestone editing prompt in bottom border
		text := renderInputTextWithCursor(m.inputBuffer, m.cursorPos)
		customBorder.Bottom = "─────Edit milestone: " + text + "─────"
	} else {
		customBorder.Bottom = "─"
	}
	return customBorder
}

// renderSummaryFooter renders the hours summary footer for the given client.
// Shows total hours, uninvoiced hours, target hours, and the difference.
func renderSummaryFooter(client Client) string {
	entries := filterEntries(client.DisplayItems)
	totalHours := calculateTotalHours(entries)
	uninvoicedHours := calculateUninvoicedHours(entries)
	diff := totalHours - client.TargetHours
	diffSign := ""
	diffColor := ColorAgeNewest // Green for positive
	if diff > 0 {
		diffSign = "+"
	} else if diff < 0 {
		diffColor = ColorError // Red for negative
	}

	summaryStyle := lipgloss.NewStyle().
		Bold(true).
		Foreground(ColorAgeNewest)

	targetStyle := lipgloss.NewStyle().
		Foreground(ColorTextDim)

	diffStyle := lipgloss.NewStyle().
		Bold(true).
		Foreground(diffColor)

	uninvoicedStyle := lipgloss.NewStyle().
		Bold(true).
		Foreground(ColorRestartable) // Orange color for uninvoiced

	var footer string
	footer += "\n"
	footer += summaryStyle.Render(fmt.Sprintf("SUMM: %.1fh", totalHours)) + " "
	footer += uninvoicedStyle.Render(fmt.Sprintf("(Uninvoiced: %.1fh)", uninvoicedHours)) + "\n"
	footer += targetStyle.Render(fmt.Sprintf("Target: %.0fh", client.TargetHours)) + "\n"
	footer += diffStyle.Render(fmt.Sprintf("Diff: %s%.1fh", diffSign, diff)) + "\n"
	return footer
}

// renderMessageDialog renders a centered message dialog overlay.
func (m Model) renderMessageDialog() string {
	dialogStyle := lipgloss.NewStyle().
		Border(lipgloss.RoundedBorder()).
		BorderForeground(ColorRestartable). // Orange border for info
		Padding(1, 2).
		Background(ColorDialogBackground).
		Foreground(ColorDialogForeground)

	messageStyle := lipgloss.NewStyle().
		Foreground(ColorDialogForeground)

	instructionStyle := lipgloss.NewStyle().
		Foreground(ColorTextDim).
		Italic(true)

	dialogContent := messageStyle.Render(m.messageText) + "\n\n"
	dialogContent += instructionStyle.Render("[Press any key to continue]")

	dialog := dialogStyle.Render(dialogContent)

	// Create overlay by positioning dialog in center
	return lipgloss.Place(
		m.windowWidth,
		m.windowHeight,
		lipgloss.Center,
		lipgloss.Center,
		dialog,
		lipgloss.WithWhitespaceChars(" "),
		lipgloss.WithWhitespaceForeground(ColorOverlayBackground),
	)
}

// saveCurrentScrollPosition saves the current client's scroll position to the map
func (m *Model) saveCurrentScrollPosition() {
	if len(m.clients) > 0 && m.selectedClient < len(m.clients) {
		currentClient := m.clients[m.selectedClient]
		m.clientScrollPositions[currentClient.ID] = ClientScrollPosition{
			selectedRow:   m.selectedRow,
			viewportStart: m.timestampTable.GetViewportStart(),
		}
	}
}

// saveUIStateToDB persists the current UI state to the database.
// This saves the selected client ID and all scroll positions as JSON.
func (m *Model) saveUIStateToDB() {
	if m.db == nil {
		return
	}

	// Save current scroll position to map first
	m.saveCurrentScrollPosition()

	// Save selected client ID
	if len(m.clients) > 0 && m.selectedClient < len(m.clients) {
		currentClient := m.clients[m.selectedClient]
		clientIDStr := fmt.Sprintf("%d", currentClient.ID)
		if err := SaveUIState(m.db, "selected_client_id", clientIDStr); err != nil {
			log.Printf("Failed to save selected client: %v", err)
		}
	}

	// Save scroll state for all clients as JSON array
	var scrollStates []ScrollStateEntry
	for clientID, pos := range m.clientScrollPositions {
		// Calculate relative viewport offset (how many rows before cursor the viewport starts)
		viewportOffset := pos.selectedRow - pos.viewportStart
		scrollStates = append(scrollStates, ScrollStateEntry{
			ClientID:       clientID,
			CursorPosition: pos.selectedRow, // Absolute cursor position
			ViewportOffset: viewportOffset,  // Relative offset
		})
	}

	if len(scrollStates) > 0 {
		jsonData, err := json.Marshal(scrollStates)
		if err != nil {
			log.Printf("Failed to marshal scroll state: %v", err)
			return
		}
		if err := SaveUIState(m.db, "scroll_state", string(jsonData)); err != nil {
			log.Printf("Failed to save scroll state: %v", err)
		}
	}
}

// adjustViewportToSelection adjusts the viewport to keep the selected row visible.
// Delegates to the timestampTable component which manages the viewport.
func (m *Model) adjustViewportToSelection() {
	m.timestampTable.adjustViewportToSelection()
}

// switchToClient switches to the next or previous client with wrap-around.
// If forward is true, moves to the next client; if false, moves to the previous.
// Saves current client's scroll position and restores target client's position.
func (m *Model) switchToClient(forward bool) {
	if len(m.clients) == 0 {
		return
	}

	// Save current client's scroll position (to memory and DB)
	m.saveCurrentScrollPosition()

	// Switch to next/previous client
	if forward {
		m.selectedClient = (m.selectedClient + 1) % len(m.clients)
	} else {
		m.selectedClient = (m.selectedClient - 1 + len(m.clients)) % len(m.clients)
	}

	// Restore target client's scroll position
	targetClient := m.clients[m.selectedClient]
	if pos, exists := m.clientScrollPositions[targetClient.ID]; exists {
		m.selectedRow = pos.selectedRow
		m.timestampTable.SetViewportStart(pos.viewportStart)

		// Bounds check in case client's items changed
		m.selectedRow = clampIndex(m.selectedRow, len(targetClient.DisplayItems))
	} else {
		// No saved position - default to end
		if len(targetClient.DisplayItems) > 0 {
			m.selectedRow = len(targetClient.DisplayItems) - 1
		} else {
			m.selectedRow = 0
		}
		m.timestampTable.SetViewportStart(0)
	}

	// Sync the timestamp table with new position
	m.syncTimestampTableToCurrentClient()

	// Save UI state to database
	m.saveUIStateToDB()
}

// reloadClients reloads all clients from the database.
// Returns an error if the reload fails.
func (m *Model) reloadClients() error {
	newClients, err := LoadClients(m.db)
	if err != nil {
		return fmt.Errorf("failed to reload clients: %w", err)
	}
	m.clients = newClients
	return nil
}

// preserveSelection ensures the current selection remains valid after data changes.
// Adjusts selectedClient and selectedRow if they're out of bounds.
// Call this after reloading clients when you want to keep the user's current position.
func (m *Model) preserveSelection() {
	// Bounds check for selected client
	m.selectedClient = clampIndex(m.selectedClient, len(m.clients))

	// Bounds check for selected row within current client
	if len(m.clients) > 0 && m.selectedClient < len(m.clients) {
		currentClient := m.clients[m.selectedClient]
		m.selectedRow = clampIndex(m.selectedRow, len(currentClient.DisplayItems))
	}

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

// scrollToLastEntry moves the selection to the last item in the current client's list.
// This is useful after adding a new entry or milestone to automatically show it to the user.
// Call this after reloading clients when a new item was added.
func (m *Model) scrollToLastEntry() {
	if len(m.clients) == 0 || m.selectedClient >= len(m.clients) {
		return
	}

	currentClient := m.clients[m.selectedClient]
	if len(currentClient.DisplayItems) > 0 {
		m.selectedRow = len(currentClient.DisplayItems) - 1
	} else {
		m.selectedRow = 0
	}

	// Adjust viewport to ensure the last entry is visible
	m.adjustViewportToSelection()
}

// syncTimestampTableToCurrentClient updates the timestamp table component's selected row and viewport.
// Call this after data changes that might have affected the entry count.
func (m *Model) syncTimestampTableToCurrentClient() {
	if len(m.clients) == 0 || m.selectedClient >= len(m.clients) {
		return
	}

	currentClient := m.clients[m.selectedClient]
	m.timestampTable.SetSelectedRow(m.selectedRow, len(currentClient.DisplayItems))
	// Note: viewport is already managed by timestampTable, no need to set it here
}

// handleInputModeKeys handles keyboard input when in client creation mode
func (m Model) handleInputModeKeys(msg tea.KeyMsg) (tea.Model, tea.Cmd) {
	switch msg.Type {
	case tea.KeyEscape, tea.KeyCtrlC:
		// Cancel input mode
		m.inputMode = InputModeNormal
		m.inputBuffer = ""
		m.cursorPos = 0
		return m, nil

	case tea.KeyEnter:
		// Move to shortcode input
		if m.inputBuffer == "" {
			// Empty name, just cancel
			m.inputMode = InputModeNormal
			return m, nil
		}

		// Save the name and move to shortcode input
		m.pendingClientName = m.inputBuffer
		m.inputMode = InputModeCreatingClientShortcode
		m.inputBuffer = ""
		m.cursorPos = 0
		log.Printf("Client name entered: %s, now prompting for shortcode", m.pendingClientName)
		return m, nil

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

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

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

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

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

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

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

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

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

// handleCreatingClientShortcodeKeys handles keyboard input when entering client shortcode
func (m Model) handleCreatingClientShortcodeKeys(msg tea.KeyMsg) (tea.Model, tea.Cmd) {
	switch msg.Type {
	case tea.KeyEscape, tea.KeyCtrlC:
		// Cancel client creation
		m.inputMode = InputModeNormal
		m.inputBuffer = ""
		m.cursorPos = 0
		m.pendingClientName = ""
		return m, nil

	case tea.KeyEnter:
		// Create client with name and shortcode
		if m.inputBuffer == "" {
			// Empty shortcode, just cancel
			m.inputMode = InputModeNormal
			m.pendingClientName = ""
			return m, nil
		}

		// Convert shortcode to uppercase
		shortcode := m.inputBuffer
		// Already uppercase from input handling below

		if err := CreateClient(m.db, m.pendingClientName, shortcode); err != nil {
			log.Printf("Error creating client: %v", err)
			// Stay in input mode to let user try again
			return m, nil
		}

		// Reload clients from database
		newClients, err := LoadClients(m.db)
		if err != nil {
			log.Printf("Error reloading clients: %v", err)
			m.inputMode = InputModeNormal
			m.inputBuffer = ""
			m.cursorPos = 0
			m.pendingClientName = ""
			return m, nil
		}

		m.clients = newClients
		// Switch to the newly created client
		for i, client := range m.clients {
			if client.Name == m.pendingClientName {
				m.selectedClient = i
				m.selectedRow = 0
				m.timestampTable.SetViewportStart(0)
				break
			}
		}

		m.syncTimestampTableToCurrentClient()

		m.inputMode = InputModeNormal
		m.inputBuffer = ""
		m.cursorPos = 0
		log.Printf("Created client: %s with shortcode %s", m.pendingClientName, shortcode)
		m.pendingClientName = ""
		return m, nil

	case tea.KeyBackspace:
		if m.cursorPos > 0 {
			m.inputBuffer = m.inputBuffer[:m.cursorPos-1] + m.inputBuffer[m.cursorPos:]
			m.cursorPos = saturatingDec(m.cursorPos, 0)
		}
		return m, nil

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

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

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

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

	default:
		// 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+") {
			return m, nil
		}

		// Handle any other key input - convert to uppercase for shortcodes
		input := msg.String()
		if len(input) == 1 && input[0] >= 'a' && input[0] <= 'z' {
			input = string(input[0] - 32) // Convert to uppercase
		}

		// Insert at cursor position
		m.inputBuffer = m.inputBuffer[:m.cursorPos] + input + m.inputBuffer[m.cursorPos:]
		m.cursorPos += len(input)
		return m, nil
	}
}

// handleMessageKeys handles keyboard input when showing a message dialog
func (m Model) handleMessageKeys(msg tea.KeyMsg) (tea.Model, tea.Cmd) {
	// Any key dismisses the message dialog
	m.inputMode = InputModeNormal
	m.messageText = ""
	return m, nil
}

// handleCreatingMilestoneKeys handles keyboard input when creating a new milestone
func (m Model) handleCreatingMilestoneKeys(msg tea.KeyMsg) (tea.Model, tea.Cmd) {
	switch msg.Type {
	case tea.KeyEscape, tea.KeyCtrlC:
		// Cancel milestone creation
		m.inputMode = InputModeNormal
		m.inputBuffer = ""
		m.cursorPos = 0
		m.milestoneTimestamp = 0
		return m, nil

	case tea.KeyEnter:
		// Create milestone
		if m.inputBuffer == "" {
			// Empty name, just cancel
			m.inputMode = InputModeNormal
			m.milestoneTimestamp = 0
			return m, nil
		}

		currentClient := m.clients[m.selectedClient]
		if err := CreateMilestone(m.db, currentClient.ID, m.inputBuffer, m.milestoneTimestamp); err != nil {
			log.Printf("Error creating milestone: %v", err)
			m.inputMode = InputModeNormal
			m.inputBuffer = ""
			m.cursorPos = 0
			m.milestoneTimestamp = 0
			return m, nil
		}

		log.Printf("Created milestone '%s' at timestamp %d", m.inputBuffer, m.milestoneTimestamp)

		// Reload clients from database
		if err := m.reloadClients(); err != nil {
			log.Printf("Error reloading clients: %v", err)
		}

		// Preserve selection (or try to select the new milestone)
		m.preserveSelection()
		m.syncTimestampTableToCurrentClient()

		m.inputMode = InputModeNormal
		m.inputBuffer = ""
		m.cursorPos = 0
		m.milestoneTimestamp = 0
		return m, nil

	case tea.KeyBackspace:
		if m.cursorPos > 0 {
			m.inputBuffer = m.inputBuffer[:m.cursorPos-1] + m.inputBuffer[m.cursorPos:]
			m.cursorPos = saturatingDec(m.cursorPos, 0)
		}
		return m, nil

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

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

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

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

	default:
		// 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+") {
			return m, nil
		}

		// Handle any other key input
		m.inputBuffer = m.inputBuffer[:m.cursorPos] + msg.String() + m.inputBuffer[m.cursorPos:]
		m.cursorPos += len(msg.String())
		return m, nil
	}
}

// handleEditingMilestoneKeys handles keyboard input when editing an existing milestone
func (m Model) handleEditingMilestoneKeys(msg tea.KeyMsg) (tea.Model, tea.Cmd) {
	switch msg.Type {
	case tea.KeyEscape, tea.KeyCtrlC:
		// Cancel milestone editing
		m.inputMode = InputModeNormal
		m.inputBuffer = ""
		m.cursorPos = 0
		m.editingMilestoneID = 0
		return m, nil

	case tea.KeyEnter:
		// Update milestone
		if m.inputBuffer == "" {
			// Empty name, just cancel
			m.inputMode = InputModeNormal
			m.editingMilestoneID = 0
			return m, nil
		}

		if err := UpdateMilestone(m.db, m.editingMilestoneID, m.inputBuffer); err != nil {
			log.Printf("Error updating milestone: %v", err)
			m.inputMode = InputModeNormal
			m.inputBuffer = ""
			m.cursorPos = 0
			m.editingMilestoneID = 0
			return m, nil
		}

		log.Printf("Updated milestone %d to '%s'", m.editingMilestoneID, m.inputBuffer)

		// Reload clients from database
		if err := m.reloadClients(); err != nil {
			log.Printf("Error reloading clients: %v", err)
		}

		// Preserve selection
		m.preserveSelection()
		m.syncTimestampTableToCurrentClient()

		m.inputMode = InputModeNormal
		m.inputBuffer = ""
		m.cursorPos = 0
		m.editingMilestoneID = 0
		return m, nil

	case tea.KeyBackspace:
		if m.cursorPos > 0 {
			m.inputBuffer = m.inputBuffer[:m.cursorPos-1] + m.inputBuffer[m.cursorPos:]
			m.cursorPos = saturatingDec(m.cursorPos, 0)
		}
		return m, nil

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

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

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

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

	default:
		// 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+") {
			return m, nil
		}

		// Handle any other key input
		m.inputBuffer = m.inputBuffer[:m.cursorPos] + msg.String() + m.inputBuffer[m.cursorPos:]
		m.cursorPos += len(msg.String())
		return m, nil
	}
}

// handleInvoicePreviewUpdate handles updates when in invoice preview mode
func (m Model) handleInvoicePreviewUpdate(msg tea.Msg) (tea.Model, tea.Cmd) {
	// Delegate to invoice preview component
	updatedPreview, cmd, action := m.invoicePreview.Update(msg)
	m.invoicePreview = updatedPreview

	switch action {
	case InvoiceActionCancel:
		// User cancelled, exit preview mode
		m.inputMode = InputModeNormal
		m.invoicePreview = nil
		return m, cmd

	case InvoiceActionConfirm:
		// Invoice was created successfully, reload and exit
		if err := m.reloadClients(); err != nil {
			log.Printf("Error reloading clients: %v", err)
		}
		m.preserveSelection()
		m.inputMode = InputModeNormal
		m.invoicePreview = nil
		return m, cmd
	}

	return m, cmd
}

// Note: handleEditCommentKeys() and handleBlockedEditKeys() have been moved to TimestampTableModel component

// handleWindowSizeMsg handles terminal window resize events
func (m Model) handleWindowSizeMsg(msg tea.WindowSizeMsg) Model {
	m.windowWidth = msg.Width
	m.windowHeight = msg.Height
	// Reserve space for tabs (1 line), border (2 lines), header (1 line), blank separator (1 line), and footer summary (3 lines)
	m.pageSize = clampMin(msg.Height-9, 1)

	// Update timestamp table component with new dimensions
	m.timestampTable.SetWindowWidth(m.windowWidth)
	m.timestampTable.SetPageSize(m.pageSize)

	// Adjust viewport to ensure cursor is visible within current window size
	// This respects the loaded viewport offset and only adjusts if necessary
	m.adjustViewportToSelection()

	return m
}

// handleDeleteEntry handles a deletion request from the timestamp table component
func (m Model) handleDeleteEntry(msg DeleteEntryMsg, currentClient Client) (Model, tea.Cmd) {
	if err := DeleteEntry(m.db, msg.EntryID); err != nil {
		// Check if error is due to invoice protection
		if strings.Contains(err.Error(), "invoiced") {
			m.inputMode = InputModeMessage
			m.messageText = "Cannot delete invoiced entry. Invoiced entries are immutable to preserve billing integrity."
			log.Printf("Blocked deletion of invoiced entry %d", msg.EntryID)
			return m, nil
		}
		log.Printf("Error deleting entry: %v", err)
		return m, nil
	}

	log.Printf("Deleted entry %d for client %s", msg.EntryID, currentClient.Name)

	// Reload all clients from database
	if err := m.reloadClients(); err != nil {
		log.Printf("Error reloading clients: %v", err)
		return m, nil
	}

	// Preserve selection (deleting doesn't add entries)
	m.preserveSelection()

	// Sync to component
	m.syncTimestampTableToCurrentClient()

	return m, nil
}

// handleDeleteMilestone handles a deletion request for a milestone from the timestamp table component
func (m Model) handleDeleteMilestone(msg DeleteMilestoneMsg) (Model, tea.Cmd) {
	if err := DeleteMilestone(m.db, msg.MilestoneID); err != nil {
		log.Printf("Error deleting milestone: %v", err)
		return m, nil
	}

	log.Printf("Deleted milestone %d", msg.MilestoneID)

	// Reload all clients from database
	if err := m.reloadClients(); err != nil {
		log.Printf("Error reloading clients: %v", err)
		return m, nil
	}

	// Preserve selection (deleting doesn't add items)
	m.preserveSelection()

	// Sync to component
	m.syncTimestampTableToCurrentClient()

	return m, nil
}

// handleMoveMilestoneUp handles moving a milestone up (adopting previous item's timestamp)
func (m Model) handleMoveMilestoneUp(msg MoveMilestoneUpMsg) (Model, tea.Cmd) {
	currentClient := m.clients[m.selectedClient]

	// Find the milestone in the display items
	milestoneIndex := -1
	for i, item := range currentClient.DisplayItems {
		if item.ItemType == "milestone" && item.Milestone != nil && item.Milestone.ID == msg.MilestoneID {
			milestoneIndex = i
			break
		}
	}

	if milestoneIndex <= 0 {
		// Can't move up (already first item or not found)
		return m, nil
	}

	// Get previous item's timestamp
	previousItem := currentClient.DisplayItems[milestoneIndex-1]
	var newTimestamp int64
	if previousItem.ItemType == "entry" && previousItem.Entry != nil {
		newTimestamp = previousItem.Entry.StartTime
	} else if previousItem.ItemType == "milestone" && previousItem.Milestone != nil {
		newTimestamp = previousItem.Milestone.Timestamp
	}

	// When moving up to an entry's timestamp, the milestone will naturally sort before it
	// (milestones come before entries at the same timestamp by design)
	// So we don't need any offset here

	// Update milestone timestamp
	if err := UpdateMilestoneTimestamp(m.db, msg.MilestoneID, newTimestamp); err != nil {
		log.Printf("Error moving milestone up: %v", err)
		return m, nil
	}

	log.Printf("Moved milestone %d up to timestamp %d", msg.MilestoneID, newTimestamp)

	// Reload clients from database
	if err := m.reloadClients(); err != nil {
		log.Printf("Error reloading clients: %v", err)
		return m, nil
	}

	// Try to keep selection on the moved milestone
	// Find it in the new list
	for i, item := range m.clients[m.selectedClient].DisplayItems {
		if item.ItemType == "milestone" && item.Milestone != nil && item.Milestone.ID == msg.MilestoneID {
			m.selectedRow = i
			break
		}
	}

	m.adjustViewportToSelection()
	m.syncTimestampTableToCurrentClient()

	return m, nil
}

// handleMoveMilestoneDown handles moving a milestone down (adopting next item's timestamp)
func (m Model) handleMoveMilestoneDown(msg MoveMilestoneDownMsg) (Model, tea.Cmd) {
	currentClient := m.clients[m.selectedClient]

	// Find the milestone in the display items
	milestoneIndex := -1
	for i, item := range currentClient.DisplayItems {
		if item.ItemType == "milestone" && item.Milestone != nil && item.Milestone.ID == msg.MilestoneID {
			milestoneIndex = i
			break
		}
	}

	if milestoneIndex < 0 || milestoneIndex >= len(currentClient.DisplayItems)-1 {
		// Can't move down (already last item or not found)
		return m, nil
	}

	// Get next item's timestamp
	nextItem := currentClient.DisplayItems[milestoneIndex+1]
	var targetTimestamp int64
	if nextItem.ItemType == "entry" && nextItem.Entry != nil {
		targetTimestamp = nextItem.Entry.StartTime
	} else if nextItem.ItemType == "milestone" && nextItem.Milestone != nil {
		targetTimestamp = nextItem.Milestone.Timestamp
	}

	// Find the last item with the same timestamp, so we move after all items at that timestamp
	var newTimestamp int64 = targetTimestamp
	foundDifferent := false
	for i := milestoneIndex + 2; i < len(currentClient.DisplayItems); i++ {
		item := currentClient.DisplayItems[i]
		var itemTimestamp int64
		if item.ItemType == "entry" && item.Entry != nil {
			itemTimestamp = item.Entry.StartTime
		} else if item.ItemType == "milestone" && item.Milestone != nil {
			itemTimestamp = item.Milestone.Timestamp
		}

		if itemTimestamp == targetTimestamp {
			// Still same timestamp, keep going
			continue
		} else {
			// Found different timestamp, use it
			newTimestamp = itemTimestamp
			foundDifferent = true
			break
		}
	}

	// If we didn't find a different timestamp (moving to last position),
	// add 1 second to the target timestamp to ensure it sorts after
	if !foundDifferent {
		newTimestamp = targetTimestamp + 1
	}

	// Update milestone timestamp
	if err := UpdateMilestoneTimestamp(m.db, msg.MilestoneID, newTimestamp); err != nil {
		log.Printf("Error moving milestone down: %v", err)
		return m, nil
	}

	log.Printf("Moved milestone %d down to timestamp %d", msg.MilestoneID, newTimestamp)

	// Reload clients from database
	if err := m.reloadClients(); err != nil {
		log.Printf("Error reloading clients: %v", err)
		return m, nil
	}

	// Try to keep selection on the moved milestone
	// Find it in the new list
	for i, item := range m.clients[m.selectedClient].DisplayItems {
		if item.ItemType == "milestone" && item.Milestone != nil && item.Milestone.ID == msg.MilestoneID {
			m.selectedRow = i
			break
		}
	}

	m.adjustViewportToSelection()
	m.syncTimestampTableToCurrentClient()

	return m, nil
}

// handleUpdateComment handles a comment update request from the timestamp table component
func (m Model) handleUpdateComment(msg UpdateCommentMsg) (Model, tea.Cmd) {
	if err := UpdateEntryComment(m.db, msg.EntryID, msg.Comment); err != nil {
		log.Printf("Error updating comment: %v", err)
		return m, nil
	}

	log.Printf("Updated comment for entry %d", msg.EntryID)

	// Reload all clients from database
	if err := m.reloadClients(); err != nil {
		log.Printf("Error reloading clients: %v", err)
		return m, nil
	}

	// Preserve selection (editing doesn't add entries)
	m.preserveSelection()

	// Sync to component
	m.syncTimestampTableToCurrentClient()

	return m, nil
}

// handleAdjustStartTime handles a start time adjustment request from the timestamp table component
func (m Model) handleAdjustStartTime(msg AdjustStartTimeMsg) (Model, tea.Cmd) {
	if err := UpdateEntryStartTime(m.db, msg.EntryID, msg.MinutesDelta); err != nil {
		// Show error message to user
		m.inputMode = InputModeMessage
		m.messageText = fmt.Sprintf("Cannot adjust start time: %s", err.Error())
		log.Printf("Error adjusting start time for entry %d: %v", msg.EntryID, err)
		return m, nil
	}

	log.Printf("Adjusted start time for entry %d by %d minutes", msg.EntryID, msg.MinutesDelta)

	// Reload all clients from database
	if err := m.reloadClients(); err != nil {
		log.Printf("Error reloading clients: %v", err)
		return m, nil
	}

	// Preserve selection (adjustment doesn't add entries)
	m.preserveSelection()

	// Sync to component
	m.syncTimestampTableToCurrentClient()

	return m, nil
}

// handleAdjustEndTime handles an end time adjustment request from the timestamp table component
func (m Model) handleAdjustEndTime(msg AdjustEndTimeMsg) (Model, tea.Cmd) {
	if err := UpdateEntryEndTime(m.db, msg.EntryID, msg.MinutesDelta); err != nil {
		// Show error message to user
		m.inputMode = InputModeMessage
		m.messageText = fmt.Sprintf("Cannot adjust end time: %s", err.Error())
		log.Printf("Error adjusting end time for entry %d: %v", msg.EntryID, err)
		return m, nil
	}

	log.Printf("Adjusted end time for entry %d by %d minutes", msg.EntryID, msg.MinutesDelta)

	// Reload all clients from database
	if err := m.reloadClients(); err != nil {
		log.Printf("Error reloading clients: %v", err)
		return m, nil
	}

	// Preserve selection (adjustment doesn't add entries)
	m.preserveSelection()

	// Sync to component
	m.syncTimestampTableToCurrentClient()

	return m, nil
}

// handleTableKeys handles table navigation and editing keys by delegating to timestamp table component
func (m Model) handleTableKeys(msg tea.KeyMsg, currentClient Client) (Model, tea.Cmd) {
	// Delegate to timestamp table component
	updatedTable, cmd, customMsg := m.timestampTable.Update(msg, currentClient.DisplayItems)
	m.timestampTable = updatedTable

	// Sync selectedRow from component to parent
	m.selectedRow = m.timestampTable.GetSelectedRow()

	// Handle custom messages from component
	if customMsg != nil {
		switch msg := customMsg.(type) {
		case DeleteEntryMsg:
			return m.handleDeleteEntry(msg, currentClient)

		case DeleteMilestoneMsg:
			return m.handleDeleteMilestone(msg)

		case UpdateCommentMsg:
			return m.handleUpdateComment(msg)

		case AdjustStartTimeMsg:
			return m.handleAdjustStartTime(msg)

		case AdjustEndTimeMsg:
			return m.handleAdjustEndTime(msg)

		case MoveMilestoneUpMsg:
			return m.handleMoveMilestoneUp(msg)

		case MoveMilestoneDownMsg:
			return m.handleMoveMilestoneDown(msg)
		}
	}

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

	// Save current scroll position after navigation
	m.saveCurrentScrollPosition()

	return m, cmd
}

// handleArchiveClient handles the 'ctrl+a' key to archive the current client
func (m Model) handleArchiveClient() (Model, tea.Cmd) {
	currentClient := m.clients[m.selectedClient]
	clientID := currentClient.ID

	if err := ArchiveClient(m.db, clientID); err != nil {
		log.Printf("Error archiving client: %v", err)
		return m, nil
	}
	log.Printf("Archived client: %s", currentClient.Name)

	// Reload active clients from database
	newClients, err := LoadClients(m.db)
	if err != nil {
		log.Printf("Error reloading clients: %v", err)
		return m, nil
	}
	m.clients = newClients

	// After archiving, switch to first client if available
	if len(m.clients) > 0 {
		m.selectedClient = 0
		m.selectedRow = 0
		m.timestampTable.SetViewportStart(0)
		m.syncTimestampTableToCurrentClient()
	}

	return m, nil
}

// handleInvoiceKey handles the 'i' key to enter invoice preview mode
func (m Model) handleInvoiceKey() (Model, tea.Cmd) {
	currentClient := m.clients[m.selectedClient]

	// Get uninvoiced entries (filter out milestones)
	entries := filterEntries(currentClient.DisplayItems)
	uninvoicedEntries := []TimeEntry{}
	for _, entry := range entries {
		if !entry.InvoiceID.Valid && entry.EndTime.Valid {
			uninvoicedEntries = append(uninvoicedEntries, entry)
		}
	}

	if len(uninvoicedEntries) == 0 {
		// Show message dialog instead of silent log
		m.inputMode = InputModeMessage
		m.messageText = fmt.Sprintf("No uninvoiced entries for client '%s'", currentClient.Name)
		log.Printf("No uninvoiced entries for client %s", currentClient.Name)
		return m, nil
	}

	// Check if client has a shortcode
	if currentClient.Shortcode == "" {
		m.inputMode = InputModeMessage
		m.messageText = fmt.Sprintf("Client '%s' must have a shortcode before creating invoices", currentClient.Name)
		log.Printf("Client %s missing shortcode", currentClient.Name)
		return m, nil
	}

	// Generate invoice number with client shortcode
	invoiceNumber, err := GenerateInvoiceNumber(m.db, currentClient.Shortcode)
	if err != nil {
		log.Printf("Error generating invoice number: %v", err)
		return m, nil
	}

	// Calculate total hours
	var totalHours float64
	for _, entry := range uninvoicedEntries {
		if entry.EndTime.Valid {
			durationSeconds := entry.EndTime.Int64 - entry.StartTime
			totalHours += float64(durationSeconds) / 3600.0
		}
	}

	// Create invoice preview component
	m.invoicePreview = NewInvoicePreviewModel(
		m.db,
		currentClient.ID,
		currentClient.Name,
		uninvoicedEntries,
		invoiceNumber,
		totalHours,
		m.windowWidth,
		m.windowHeight,
	)
	m.inputMode = InputModeInvoicePreview

	log.Printf("Previewing invoice %s with %d entries (%.2f hours)", invoiceNumber, len(uninvoicedEntries), totalHours)
	return m, nil
}

// handleMilestoneKey handles the 'm' key to create or edit a milestone
func (m Model) handleMilestoneKey() (Model, tea.Cmd) {
	currentClient := m.clients[m.selectedClient]

	if len(currentClient.DisplayItems) == 0 {
		// No items - create milestone at current time
		m.inputMode = InputModeCreatingMilestone
		m.inputBuffer = ""
		m.cursorPos = 0
		m.milestoneTimestamp = time.Now().Unix()
		log.Printf("Creating milestone at current time")
		return m, nil
	}

	// Get selected item
	selectedItem := currentClient.DisplayItems[m.selectedRow]

	if selectedItem.ItemType == "milestone" && selectedItem.Milestone != nil {
		// Edit existing milestone
		m.inputMode = InputModeEditingMilestone
		m.editingMilestoneID = selectedItem.Milestone.ID
		m.inputBuffer = selectedItem.Milestone.Name
		m.cursorPos = len(selectedItem.Milestone.Name)
		log.Printf("Editing milestone %d", selectedItem.Milestone.ID)
		return m, nil
	} else if selectedItem.ItemType == "entry" && selectedItem.Entry != nil {
		// Create new milestone at entry's start time
		m.inputMode = InputModeCreatingMilestone
		m.inputBuffer = ""
		m.cursorPos = 0
		m.milestoneTimestamp = selectedItem.Entry.StartTime
		log.Printf("Creating milestone at entry start time %d", selectedItem.Entry.StartTime)
		return m, nil
	}

	return m, nil
}

// handleForceNewEntry handles the 'ctrl+t' key to force start a new entry
func (m Model) handleForceNewEntry() (Model, tea.Cmd) {
	currentClient := m.clients[m.selectedClient]
	clientID := currentClient.ID

	// Check if there's a running entry
	runningEntry, err := GetRunningEntry(m.db, clientID)
	if err != nil {
		log.Printf("Error checking running entry: %v", err)
		return m, nil
	}

	if runningEntry != nil {
		// Already running - do nothing (no-op)
		log.Printf("Cannot force-start new entry: entry %d is already running", runningEntry.ID)
		return m, nil
	}

	// Start the new entry
	if err := StartNewEntry(m.db, clientID); err != nil {
		log.Printf("Error starting new entry: %v", err)
		return m, nil
	}
	log.Printf("Force-started new entry for client %s", currentClient.Name)

	// Reload all clients from database
	if err := m.reloadClients(); err != nil {
		log.Printf("Error reloading clients: %v", err)
		return m, nil
	}

	// Scroll to the newly added entry
	m.scrollToLastEntry()

	m.syncTimestampTableToCurrentClient()

	return m, nil
}

// handleToggleTracking handles the 't' key to toggle time tracking (start/stop/restart)
func (m Model) handleToggleTracking() (Model, tea.Cmd) {
	currentClient := m.clients[m.selectedClient]
	clientID := currentClient.ID

	// Check if there's a running entry
	runningEntry, err := GetRunningEntry(m.db, clientID)
	if err != nil {
		log.Printf("Error checking running entry: %v", err)
		return m, nil
	}

	addedNewEntry := false // Track whether we added a new entry

	if runningEntry != nil {
		// Stop the running entry
		if err := StopEntry(m.db, runningEntry.ID); err != nil {
			log.Printf("Error stopping entry: %v", err)
			return m, nil
		}
		log.Printf("Stopped entry %d for client %s", runningEntry.ID, currentClient.Name)
	} else {
		// No running entry - check if we should restart the last one
		lastEntry, err := GetLastCompletedEntry(m.db, clientID)
		if err != nil {
			log.Printf("Error checking last entry: %v", err)
			return m, nil
		}

		if lastEntry != nil && lastEntry.EndTime.Valid {
			// Check if ended less than 15 minutes ago
			minutesSinceEnd := (time.Now().Unix() - lastEntry.EndTime.Int64) / 60
			if minutesSinceEnd < 15 {
				// Restart the last entry
				if err := RestartEntry(m.db, lastEntry.ID); err != nil {
					// Check if error is due to invoice protection
					if strings.Contains(err.Error(), "invoiced") {
						m.inputMode = InputModeMessage
						m.messageText = "Cannot restart invoiced entry. Use Ctrl+T to start a new entry instead."
						log.Printf("Blocked restart of invoiced entry %d", lastEntry.ID)
						return m, nil
					}
					log.Printf("Error restarting entry: %v", err)
					return m, nil
				}
				log.Printf("Restarted entry %d for client %s", lastEntry.ID, currentClient.Name)
				addedNewEntry = true
			} else {
				// Start a new entry
				if err := StartNewEntry(m.db, clientID); err != nil {
					log.Printf("Error starting new entry: %v", err)
					return m, nil
				}
				log.Printf("Started new entry for client %s", currentClient.Name)
				addedNewEntry = true
			}
		} else {
			// No previous entries, start a new one
			if err := StartNewEntry(m.db, clientID); err != nil {
				log.Printf("Error starting new entry: %v", err)
				return m, nil
			}
			log.Printf("Started new entry for client %s", currentClient.Name)
			addedNewEntry = true
		}
	}

	// Reload all clients from database
	if err := m.reloadClients(); err != nil {
		log.Printf("Error reloading clients: %v", err)
		return m, nil
	}

	// If we added a new entry, scroll to it; otherwise preserve selection
	if addedNewEntry {
		m.scrollToLastEntry()
	} else {
		m.preserveSelection()
	}

	m.syncTimestampTableToCurrentClient()

	return m, nil
}

// handleArchivedViewUpdate handles updates when in archived view mode
func (m Model) handleArchivedViewUpdate(msg tea.Msg) (tea.Model, tea.Cmd) {
	// Delegate to archived view component
	updatedView, cmd, shouldExit := m.archivedView.Update(msg)
	m.archivedView = updatedView

	// If archived view signals exit, reload active clients and reset view
	if shouldExit {
		m.archivedView = nil
		activeClients, err := LoadClients(m.db)
		if err != nil {
			log.Printf("Error loading active clients: %v", err)
			return m, nil
		}
		m.clients = activeClients
		// Reset selection to first client
		if len(m.clients) > 0 {
			m.selectedClient = 0
			m.selectedRow = 0
			m.timestampTable.SetViewportStart(0)
			m.syncTimestampTableToCurrentClient()
		}
	}

	return m, cmd
}

// Update handles messages and updates the model (bubbletea interface)
func (m Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
	// Early delegation to archived view if active
	if m.archivedView != nil {
		return m.handleArchivedViewUpdate(msg)
	}

	switch msg := msg.(type) {
	case tickMsg:
		// Periodic tick to update calculated values (durations, totals, etc.)
		// Simply returning triggers a re-render, and schedule the next tick
		return m, tea.Tick(time.Minute, func(t time.Time) tea.Msg {
			return tickMsg(t)
		})

	case tea.WindowSizeMsg:
		return m.handleWindowSizeMsg(msg), nil

	case tea.FocusMsg:
		// Terminal gained focus - reload data to pick up any external changes
		log.Printf("Terminal gained focus - reloading data")
		if err := m.reloadClients(); err != nil {
			log.Printf("Error reloading clients on focus: %v", err)
			return m, nil
		}
		m.preserveSelection()
		m.syncTimestampTableToCurrentClient()
		return m, nil

	case tea.BlurMsg:
		// Terminal lost focus - could use this to save state, pause timers, etc.
		log.Printf("Terminal lost focus")
		return m, nil

	case tea.KeyMsg:

		// Handle input mode separately
		if m.inputMode == InputModeCreatingClient {
			return m.handleInputModeKeys(msg)
		}

		// Handle client shortcode input mode
		if m.inputMode == InputModeCreatingClientShortcode {
			return m.handleCreatingClientShortcodeKeys(msg)
		}

		// Handle milestone creation mode
		if m.inputMode == InputModeCreatingMilestone {
			return m.handleCreatingMilestoneKeys(msg)
		}

		// Handle milestone editing mode
		if m.inputMode == InputModeEditingMilestone {
			return m.handleEditingMilestoneKeys(msg)
		}

		// Note: InputModeEditingComment and InputModeBlockedEdit are handled by TimestampTableModel component

		// Handle invoice preview mode
		if m.inputMode == InputModeInvoicePreview {
			return m.handleInvoicePreviewUpdate(msg)
		}

		// Handle message mode
		if m.inputMode == InputModeMessage {
			return m.handleMessageKeys(msg)
		}

		// Handle cases that don't require a current client
		keyStr := msg.String()

		// Handle global commands first (don't need current client)
		if keyStr == "q" || keyStr == "ctrl+c" {
			// Save UI state before quitting
			m.saveUIStateToDB()
			return m, tea.Quit
		}

		if keyStr == "ctrl+n" {
			// Enter client creation mode
			m.inputMode = InputModeCreatingClient
			m.inputBuffer = ""
			m.cursorPos = 0
			return m, nil
		}

		if keyStr == "ctrl+u" {
			// Enter archived view
			archivedView, err := NewArchivedViewModel(m.db, m.windowWidth, m.windowHeight)
			if err != nil {
				log.Printf("Error creating archived view: %v", err)
				return m, nil
			}
			m.archivedView = archivedView
			return m, nil
		}

		// Check if we have any clients before proceeding
		if len(m.clients) == 0 {
			return m, nil
		}

		// Now we can safely access the current client
		currentClient := m.clients[m.selectedClient]

		// Delegate table navigation and editing keys to timestamp table component
		tableKeys := map[string]bool{
			"up": true, "down": true, "k": true, "j": true,
			"pgup": true, "pgdown": true, "home": true, "end": true,
			"g": true, "G": true, "e": true, "ctrl+d": true,
			"ctrl+left": true, "ctrl+right": true,
			"ctrl+shift+left": true, "ctrl+shift+right": true,
		}

		if tableKeys[keyStr] {
			return m.handleTableKeys(msg, currentClient)
		}

		// Handle commands that require a current client
		switch keyStr {
		case "ctrl+a":
			return m.handleArchiveClient()

		case "t":
			return m.handleToggleTracking()

		case "ctrl+t":
			return m.handleForceNewEntry()

		case "tab":
			// Switch to next client (with wrap-around)
			m.switchToClient(true)
			m.syncTimestampTableToCurrentClient()

		case "shift+tab":
			// Switch to previous client (with wrap-around)
			m.switchToClient(false)
			m.syncTimestampTableToCurrentClient()

		case "i":
			return m.handleInvoiceKey()

		case "m":
			return m.handleMilestoneKey()
		}
	}

	return m, nil
}

// View renders the UI (bubbletea interface)
func (m Model) View() string {
	if m.windowWidth == 0 {
		return "Loading..."
	}

	// Early delegation to archived view if active
	if m.archivedView != nil {
		return m.archivedView.View()
	}

	// Check if we have any clients
	if len(m.clients) == 0 {
		return "No clients found. Press Ctrl+N to create a new client."
	}

	currentClient := m.clients[m.selectedClient]

	// Render tabs
	tabs := m.renderTabs()

	var output string

	// Create custom border with input prompt in bottom if in input mode
	customBorder := m.createCustomBorder()

	// Define border style for the table
	borderStyle := lipgloss.NewStyle().
		Border(customBorder).
		BorderForeground(ColorTableBorder)

	// Render table using timestamp table component
	// Calculate restartable entry ID directly from current entries
	entries := filterEntries(currentClient.DisplayItems)
	restartableEntryID := calculateRestartableEntryID(entries)
	output += m.timestampTable.View(currentClient.DisplayItems, restartableEntryID)

	// Render summary footer
	output += renderSummaryFooter(currentClient)

	// Apply border to entire view
	finalView := borderStyle.Render(output)

	// If in message mode, overlay the message dialog
	if m.inputMode == InputModeMessage {
		return m.renderMessageDialog()
	}

	// If in invoice preview mode, overlay the preview dialog
	if m.inputMode == InputModeInvoicePreview && m.invoicePreview != nil {
		return m.invoicePreview.View()
	}

	return tabs + finalView
}

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

	// Set up standard logger to buffer output and dump to stderr on exit
	log.SetOutput(&logBuffer)
	defer func() {
		if logBuffer.Len() > 0 {
			fmt.Fprintf(os.Stderr, "%s", logBuffer.String())
		}
	}()

	// Parse command line arguments
	// Default database path: ~/.local/share/timetrack/timetrack.db (XDG data dir)
	// Legacy fallback: If ~/kot/work/timetracking.db exists, use it (author's personal location)
	homeDir, err := os.UserHomeDir()
	if err != nil {
		log.Panicf("Failed to get user home directory: %v", err)
	}

	authorDbPath := homeDir + "/kot/work/timetracking.db"
	xdgDbPath := homeDir + "/.local/share/timetrack/timetrack.db"

	var dbPath string
	// Check if author's personal path exists (legacy reason)
	if _, err := os.Stat(authorDbPath); err == nil {
		dbPath = authorDbPath
	} else {
		// Use XDG path (will be created if needed)
		dbPath = xdgDbPath

		// Ensure directory exists
		xdgDbDir := homeDir + "/.local/share/timetrack"
		if err := os.MkdirAll(xdgDbDir, 0755); err != nil {
			log.Panicf("Failed to create data directory: %v", err)
		}
	}

	// Check for migrate command
	if len(os.Args) >= 2 && os.Args[1] == "migrate" {
		if len(os.Args) != 3 {
			printUsage()
			os.Exit(1)
		}

		dbPath = os.Args[2]

		fmt.Printf("Running migrations on database: %s\n\n", dbPath)

		// Initialize database (which runs migrations)
		db, err := InitDB(dbPath)
		if err != nil {
			log.Panicf("Failed to initialize database: %v", err)
		}
		defer db.Close()

		fmt.Println("\n✓ All migrations completed successfully")
		return
	}

	// Check for create-invoice command
	if len(os.Args) >= 2 && os.Args[1] == "create-invoice" {
		if len(os.Args) != 4 {
			fmt.Fprintf(os.Stderr, "Usage: timetrack create-invoice <database> <client-name>\n")
			os.Exit(1)
		}

		dbPath = os.Args[2]
		clientName := os.Args[3]

		// Initialize database
		db, err := InitDB(dbPath)
		if err != nil {
			log.Panicf("Failed to initialize database: %v", err)
		}
		defer db.Close()

		// Create invoice
		if err := createInvoiceCLI(db, clientName); err != nil {
			log.Panicf("%v", err)
		}

		return
	}

	// Check for import-client command
	if len(os.Args) >= 2 && os.Args[1] == "import-client" {
		if len(os.Args) != 5 && len(os.Args) != 6 {
			printUsage()
			os.Exit(1)
		}

		dbPath = os.Args[2]
		clientName := os.Args[3]
		jsonPath := os.Args[4]

		// Optional shortcode parameter
		shortcode := ""
		if len(os.Args) == 6 {
			shortcode = os.Args[5]
		}

		// Initialize database
		db, err := InitDB(dbPath)
		if err != nil {
			log.Panicf("Failed to initialize database: %v", err)
		}
		defer db.Close()

		// Import client
		if err := importClient(db, clientName, jsonPath, shortcode); err != nil {
			log.Panicf("Failed to import client: %v", err)
		}

		return
	}

	// Check for --repl flag
	replMode := false
	filteredArgs := os.Args[1:]
	for i, arg := range filteredArgs {
		if arg == "--repl" {
			replMode = true
			filteredArgs = append(filteredArgs[:i], filteredArgs[i+1:]...)
			break
		}
	}

	// TUI mode (default)
	if len(filteredArgs) > 0 {
		dbPath = filteredArgs[0]
	}

	// Initialize database
	db, err := InitDB(dbPath)
	if err != nil {
		log.Panicf("Failed to initialize database: %v", err)
	}
	defer db.Close()

	// Repl mode
	if replMode {
		if err := RunRepl(db); err != nil {
			log.Panicf("Failed to run repl: %v", err)
		}
		return
	}

	// Create model with database
	model, err := NewModel(db)
	if err != nil {
		log.Panicf("Failed to create model: %v", err)
	}

	// Start bubbletea program with focus reporting enabled
	p := tea.NewProgram(model, tea.WithAltScreen(), tea.WithReportFocus())
	if _, err := p.Run(); err != nil {
		log.Panicf("Failed to run TUI: %v", err)
	}
}