trackWork 0.15.0

A terminal-based time tracking application for managing work sessions
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
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
use std::collections::HashMap;

use anyhow::Result;
use arboard::Clipboard;
use chrono::{Datelike, Duration, Local, NaiveDate, NaiveDateTime, NaiveTime, Timelike};

use crate::config::Config;
use crate::db::Database;
use crate::integrations::{IntegrationKind, SecretsManager};
use crate::models::{Task, TimeEntry};
use crate::triggers::TriggerEvent;

#[derive(Clone)]
pub struct TaskEditState {
    pub task_id: Option<i64>, // None = creating new
    pub issue_key: String,
    pub name: String,
    pub project: String,
    pub current_field: usize, // 0=issue_key, 1=name, 2=project
}

#[derive(Clone)]
pub enum InputMode {
    Normal,
    Editing {
        field: String,
        entry_id: i64,
        description: String,
        start_time: String,
        end_time: String,
        issue_key: String,
        current_field: usize,
        cursor_pos: usize,
    },
    Creating {
        field: String,
        description: String,
        start_time: String,
        end_time: String,
        issue_key: String,
        current_field: usize,
        cursor_pos: usize,
        suggestions: Vec<(String, String, i64)>, // (issue_key, description, usage_count)
        selected_suggestion: usize,              // 0 = "new", 1+ = index into suggestions
        off_work: bool,                          // create as an off-work entry
    },
    ConfirmDelete {
        entry_id: i64,
    },
    Settings {
        field: String,
        integration: IntegrationKind,
        open_command: String,
        open_worklog_command: String,
        jira_url_setting: String,
        jira_email: String,
        jira_api_token: String,
        date_format: String,
        legacy_time_format: bool,
        hide_eye_candy: bool,
        colors: [String; 6],
        current_field: usize,
        cursor_pos: usize,
        debug_log_scroll_offset: usize,
    },
    WhatsNew,
    Tasks {
        tasks: Vec<Task>,
        selected_index: usize,
        editing: Option<TaskEditState>,
        confirm_delete: bool,
    },
    PassphrasePrompt {
        passphrase: String,
        cursor_pos: usize,
        error_message: Option<String>,
        confirm_delete: bool,
    },
    PassphraseChange {
        old_passphrase: String,
        new_passphrase: String,
        confirm_passphrase: String,
        current_field: usize,
        cursor_pos: usize,
        error_message: Option<String>,
        is_initial_setup: bool,
    },
    OperationsMenu {
        selected_index: usize,
    },
    /// Read-only modal listing extra keyboard shortcuts not shown in the main help bar.
    Hotkeys,
    /// Editing the manual start/end of the per-day "At Work" row.
    EditingDay {
        field: String,
        start_time: String,
        end_time: String,
        current_field: usize,
        cursor_pos: usize,
    },
    /// Full-screen weekly summary view. The displayed Mon–Sun week is derived
    /// from `anchor`. `selected_day` (0..=6) is the highlighted column,
    /// `selected_field` (0=Workday Start, 1=Workday End, 2=Lunch) the row in the
    /// edit panel. `editing` is Some while editing the highlighted field.
    WeekSummary {
        anchor: NaiveDate,
        selected_day: usize,
        selected_field: usize,
        editing: Option<DayEditDraft>,
    },
    /// Triggers sub-settings screen: per-event webhook config. There are 3
    /// events × 3 fields each. `current_field` = event*3 + sub, where sub is
    /// 0=enabled, 1=URL, 2=body.
    Triggers {
        field: String,
        enabled: [bool; 3],
        urls: [String; 3],
        bodies: [String; 3],
        current_field: usize,
        cursor_pos: usize,
    },
}

/// In-progress edit of one of a day's editable fields in the weekly summary.
#[derive(Clone)]
pub struct DayEditDraft {
    pub date: NaiveDate,
    /// 0 = Workday Start, 1 = Workday End, 2 = Lunch.
    pub kind: usize,
    /// "HH:MM" buffer — the workday value, or the lunch start.
    pub start: String,
    /// Lunch end "HH:MM" (unused for kinds 0/1).
    pub end: String,
    /// Lunch only: 0 = editing start, 1 = editing end.
    pub sub_field: usize,
    /// Existing off-work entry to update; None = create a new one.
    pub lunch_entry_id: Option<i64>,
}

pub struct App {
    pub db: Database,
    pub entries: Vec<TimeEntry>,
    pub selected_index: Option<usize>,
    /// When true, the pinned "At Work" row is highlighted instead of an entry.
    pub at_work_selected: bool,
    /// Manual overrides for the current day's "At Work" span (None = auto-derived).
    pub day_start_override: Option<NaiveDateTime>,
    pub day_end_override: Option<NaiveDateTime>,
    pub current_date: NaiveDate,
    pub input_mode: InputMode,
    pub total_duration_minutes: i64,
    pub weekly_stats: Vec<(String, i64)>,
    pub config: Config,
    pub status_message: Option<String>,
    pub debug_log: Vec<String>,
    pub clipboard: Option<Clipboard>,
    pub secrets: SecretsManager,
    pub pending_api_token: Option<String>,
    pub task_names: HashMap<String, String>,
    /// When `q` was first tapped, for the double-tap-to-quit confirmation.
    pub quit_armed_at: Option<std::time::Instant>,
    /// Real RGB of the terminal's 16 ANSI palette colors, queried at startup
    /// via OSC 4. Empty if the terminal didn't answer; shimmer/breathe then
    /// fall back to static color approximations.
    pub term_palette: HashMap<u8, (u8, u8, u8)>,
    /// Local date as of the last `tick()` call. When the wall-clock date moves
    /// past this, we auto-close any timer left running from the previous day.
    pub last_seen_date: NaiveDate,
    /// Background-filled "newer release on crates.io" slot. `Some(v)` only when
    /// `v` is strictly newer than `CARGO_PKG_VERSION`; the top bar nudges from
    /// it. See `update_check.rs`.
    pub available_update: crate::update_check::UpdateSlot,
}

impl App {
    pub fn new(db_path: &str) -> Result<Self> {
        let db = Database::new(db_path)?;
        let current_date = Local::now().date_naive();
        // Close any timer that was left running on a previous day before we
        // read entries — otherwise such a timer would still look "running"
        // and accumulate duration indefinitely.
        let _ = db.auto_end_stale_running(current_date);
        let entries = db.get_entries_for_date(current_date)?;
        let total_duration_minutes = db.get_total_duration_for_date(current_date)?;
        let weekly_stats = db.get_weekly_stats(current_date)?;
        let config = Config::load()?;

        let selected_index = if entries.is_empty() { None } else { Some(0) };
        let secrets = SecretsManager::new();
        let task_names = db.get_task_name_map().unwrap_or_default();
        let (day_start_override, day_end_override) = db.get_day_overrides(current_date).unwrap_or((None, None));

        Ok(App {
            db,
            entries,
            selected_index,
            at_work_selected: false,
            day_start_override,
            day_end_override,
            current_date,
            input_mode: InputMode::Normal,
            total_duration_minutes,
            weekly_stats,
            config,
            status_message: None,
            debug_log: Vec::new(),
            clipboard: None,
            secrets,
            pending_api_token: None,
            task_names,
            quit_armed_at: None,
            term_palette: HashMap::new(),
            last_seen_date: current_date,
            available_update: std::sync::Arc::new(std::sync::Mutex::new(None)),
        })
    }

    /// Window during which a second `q` confirms quit.
    const QUIT_CONFIRM_WINDOW: std::time::Duration = std::time::Duration::from_millis(500);

    /// True while the quit confirmation is active (first `q` tapped, within the window).
    pub fn quit_armed(&self) -> bool {
        self.quit_armed_at
            .map(|t| t.elapsed() < Self::QUIT_CONFIRM_WINDOW)
            .unwrap_or(false)
    }

    /// Handle a `q` press in Normal mode. Returns `true` when the app should quit
    /// (second tap within the window); the first tap just arms the confirmation.
    pub fn handle_quit_key(&mut self) -> bool {
        if self.quit_armed() {
            true
        } else {
            self.quit_armed_at = Some(std::time::Instant::now());
            false
        }
    }

    pub fn refresh_task_names(&mut self) {
        self.task_names = self.db.get_task_name_map().unwrap_or_default();
    }

    /// Called once per event-loop iteration. When the local wall-clock date
    /// changes (midnight crossed while the app was open, or the machine woke
    /// from sleep on a new day), close any timer left running on a previous
    /// day and refresh the visible entries.
    pub fn tick(&mut self) -> Result<()> {
        let today = Local::now().date_naive();
        if today != self.last_seen_date {
            self.db.auto_end_stale_running(today)?;
            self.last_seen_date = today;
            // Reflect the close in the visible list if the user is looking at
            // a date that could have held the stale timer.
            self.refresh_entries()?;
        }
        Ok(())
    }

    pub fn refresh_entries(&mut self) -> Result<()> {
        self.entries = self.db.get_entries_for_date(self.current_date)?;
        self.total_duration_minutes = self.db.get_total_duration_for_date(self.current_date)?;
        self.weekly_stats = self.db.get_weekly_stats(self.current_date)?;
        self.refresh_task_names();
        let (start_ov, end_ov) = self.db.get_day_overrides(self.current_date).unwrap_or((None, None));
        self.day_start_override = start_ov;
        self.day_end_override = end_ov;

        // Adjust selected index if necessary
        if self.entries.is_empty() {
            self.selected_index = None;
        } else if let Some(idx) = self.selected_index {
            if idx >= self.entries.len() {
                self.selected_index = Some(self.entries.len() - 1);
            }
        } else {
            self.selected_index = Some(0);
        }

        // The "At Work" row can't stay selected if it no longer exists.
        if self.at_work_selected && !self.has_day_row() {
            self.at_work_selected = false;
        }

        Ok(())
    }

    /// Effective "At Work" span for the current day: (start, end, is_manual).
    /// Derived from the day's task entries, with manual overrides taking
    /// precedence. Returns None when there's nothing to show.
    pub fn at_work_span(&self) -> Option<(NaiveDateTime, NaiveDateTime, bool)> {
        let now = Local::now().naive_local();
        at_work_span_of(
            &self.entries,
            self.day_start_override,
            self.day_end_override,
            now,
        )
    }

    pub fn has_day_row(&self) -> bool {
        self.at_work_span().is_some()
    }

    pub fn select_next(&mut self) {
        if self.at_work_selected {
            self.at_work_selected = false;
            if !self.entries.is_empty() {
                self.selected_index = Some(0);
            } else {
                self.at_work_selected = true;
            }
            return;
        }
        if self.entries.is_empty() {
            return;
        }
        self.selected_index = Some(match self.selected_index {
            Some(i) => {
                if i >= self.entries.len() - 1 {
                    0
                } else {
                    i + 1
                }
            }
            None => 0,
        });
    }

    pub fn select_previous(&mut self) {
        if self.at_work_selected {
            return; // Already at the top.
        }
        match self.selected_index {
            Some(0) | None => {
                if self.has_day_row() {
                    self.at_work_selected = true;
                } else if !self.entries.is_empty() {
                    self.selected_index = Some(0);
                }
            }
            Some(i) => self.selected_index = Some(i - 1),
        }
    }

    pub fn move_entry_up(&mut self) -> Result<()> {
        if self.at_work_selected {
            return Ok(());
        }
        if let Some(idx) = self.selected_index {
            if idx > 0 {
                self.db.reorder_entries(self.current_date, idx, idx - 1)?;
                self.refresh_entries()?;
                self.selected_index = Some(idx - 1);
            }
        }
        Ok(())
    }

    pub fn move_entry_down(&mut self) -> Result<()> {
        if self.at_work_selected {
            return Ok(());
        }
        if let Some(idx) = self.selected_index {
            if idx < self.entries.len() - 1 {
                self.db.reorder_entries(self.current_date, idx, idx + 1)?;
                self.refresh_entries()?;
                self.selected_index = Some(idx + 1);
            }
        }
        Ok(())
    }

    pub fn next_day(&mut self) -> Result<()> {
        self.current_date = self.current_date.succ_opt().unwrap_or(self.current_date);
        self.refresh_entries()?;
        Ok(())
    }

    pub fn previous_day(&mut self) -> Result<()> {
        self.current_date = self.current_date.pred_opt().unwrap_or(self.current_date);
        self.refresh_entries()?;
        Ok(())
    }

    pub fn start_creating(&mut self) {
        self.start_creating_inner(false);
    }

    /// Start creating a new entry that is pre-marked as off-work (e.g. lunch).
    pub fn start_creating_off_work(&mut self) {
        self.start_creating_inner(true);
    }

    fn start_creating_inner(&mut self, off_work: bool) {
        let now = Local::now().naive_local();
        let suggestions = self
            .db
            .get_previous_tasks_with_issue_keys()
            .unwrap_or_default();

        self.input_mode = InputMode::Creating {
            field: "Description".to_string(),
            description: String::new(),
            start_time: now.format("%H:%M").to_string(),
            end_time: String::new(),
            issue_key: String::new(),
            current_field: 0,
            cursor_pos: 0,
            suggestions,
            selected_suggestion: 0, // Start with "new" selected
            off_work,
        };
    }

    pub fn suggestion_next(&mut self) {
        if let InputMode::Creating {
            suggestions,
            selected_suggestion,
            ..
        } = &mut self.input_mode
        {
            let max_index = suggestions.len(); // 0 = new, 1..=len = suggestions
            *selected_suggestion = (*selected_suggestion + 1) % (max_index + 1);
        }
    }

    pub fn suggestion_previous(&mut self) {
        if let InputMode::Creating {
            suggestions,
            selected_suggestion,
            ..
        } = &mut self.input_mode
        {
            let max_index = suggestions.len();
            *selected_suggestion = if *selected_suggestion == 0 {
                max_index
            } else {
                *selected_suggestion - 1
            };
        }
    }

    pub fn apply_selected_suggestion(&mut self) {
        if let InputMode::Creating {
            suggestions,
            selected_suggestion,
            description,
            issue_key,
            ..
        } = &mut self.input_mode
        {
            if *selected_suggestion > 0 {
                // Apply suggestion (selected_suggestion is 1-indexed for suggestions)
                if let Some((sugg_issue_key, sugg_description, _)) =
                    suggestions.get(*selected_suggestion - 1)
                {
                    *description = sugg_description.clone();
                    *issue_key = sugg_issue_key.clone();
                }
            }
        }
        self.update_field_label();
    }

    pub fn start_editing(&mut self) {
        if let Some(idx) = self.selected_index {
            if let Some(entry) = self.entries.get(idx) {
                let desc_len = entry.description.chars().count();
                self.input_mode = InputMode::Editing {
                    field: "Description".to_string(),
                    entry_id: entry.id,
                    description: entry.description.clone(),
                    start_time: entry.start_time.format("%H:%M").to_string(),
                    end_time: entry
                        .end_time
                        .map(|t| t.format("%H:%M").to_string())
                        .unwrap_or_default(),
                    issue_key: entry.issue_key.clone(),
                    current_field: 0,
                    cursor_pos: desc_len,
                };
                self.update_field_label();
            }
        }
    }

    pub fn cursor_left(&mut self) {
        crate::cursor::cursor_left(&mut self.input_mode);
        self.update_field_label();
    }

    pub fn cursor_right(&mut self) {
        crate::cursor::cursor_right(&mut self.input_mode);
        self.update_field_label();
    }

    pub fn input_char(&mut self, c: char) {
        // Reset suggestion on typing in Creating mode
        if let InputMode::Creating { current_field, selected_suggestion, .. } = &mut self.input_mode {
            if *current_field == 0 || *current_field == 3 {
                *selected_suggestion = 0;
            }
        }

        crate::cursor::insert_char(&mut self.input_mode, c);
        self.update_field_label();
    }

    pub fn delete_char(&mut self) {
        // Reset suggestion on deleting in Creating mode
        if let InputMode::Creating { current_field, selected_suggestion, .. } = &mut self.input_mode {
            if *current_field == 0 || *current_field == 3 {
                *selected_suggestion = 0;
            }
        }

        crate::cursor::delete_char(&mut self.input_mode);
        self.update_field_label();
    }

    pub fn settings_legacy_time_format_field(&self) -> usize {
        if let InputMode::Settings { integration, .. } = &self.input_mode {
            match integration {
                IntegrationKind::CustomCommands => 4,
                IntegrationKind::Jira => 5,
            }
        } else {
            4
        }
    }

    pub fn settings_passphrase_field(&self) -> usize {
        if let InputMode::Settings { integration, .. } = &self.input_mode {
            match integration {
                IntegrationKind::CustomCommands => 5,
                IntegrationKind::Jira => 6,
            }
        } else {
            5
        }
    }

    /// Open the Triggers sub-settings screen, loading current webhook config.
    pub fn open_triggers(&mut self) {
        let t = &self.config.triggers;
        self.input_mode = InputMode::Triggers {
            field: String::new(),
            enabled: [t.day_start.enabled, t.ooo_start.enabled, t.ooo_end.enabled],
            urls: [t.day_start.url.clone(), t.ooo_start.url.clone(), t.ooo_end.url.clone()],
            bodies: [t.day_start.body.clone(), t.ooo_start.body.clone(), t.ooo_end.body.clone()],
            current_field: 0,
            cursor_pos: 0,
        };
        self.update_field_label();
    }

    /// Persist the Triggers screen back into config and return to Settings.
    pub fn save_triggers(&mut self) -> Result<()> {
        if let InputMode::Triggers { enabled, urls, bodies, .. } = &self.input_mode {
            let events = [
                &mut self.config.triggers.day_start,
                &mut self.config.triggers.ooo_start,
                &mut self.config.triggers.ooo_end,
            ];
            // Snapshot the InputMode values first to avoid borrow conflicts.
            let enabled = *enabled;
            let urls = urls.clone();
            let bodies = bodies.clone();
            for (i, ev) in events.into_iter().enumerate() {
                ev.enabled = enabled[i];
                ev.url = urls[i].clone();
                ev.body = bodies[i].clone();
            }
            self.config.save()?;
        }
        self.open_settings();
        Ok(())
    }

    /// Fire a webhook for `event` if it's enabled and has a URL. `description`
    /// fills the `[[description]]` template variable (empty for day start).
    pub fn fire_trigger(&mut self, event: TriggerEvent, description: &str) {
        let cfg = match event {
            TriggerEvent::DayStart => &self.config.triggers.day_start,
            TriggerEvent::OooStart => &self.config.triggers.ooo_start,
            TriggerEvent::OooEnd => &self.config.triggers.ooo_end,
        };
        if !cfg.enabled || cfg.url.trim().is_empty() {
            return;
        }

        let now = Local::now();
        let date = now.format("%Y-%m-%d").to_string();
        let time = now.format("%H:%M").to_string();
        let datetime = now.to_rfc3339();
        let body = Config::substitute_trigger_variables(
            &cfg.body,
            event.label(),
            &date,
            &time,
            &datetime,
            description,
        );
        let url = cfg.url.clone();

        match crate::triggers::send(&url, &body) {
            Ok(status) => self
                .debug_log
                .push(format!("[TRIGGER] {} → HTTP {}", event.label(), status)),
            Err(e) => self
                .debug_log
                .push(format!("[TRIGGER ERROR] {}: {}", event.label(), e)),
        }
        while self.debug_log.len() > 10000 {
            self.debug_log.remove(0);
        }
    }

    /// Fire the day-start webhook the first time the workday begins today.
    /// Persisted per date so it fires at most once per day across restarts.
    fn maybe_fire_day_start(&mut self) {
        if self.current_date != Local::now().date_naive() || !self.has_day_row() {
            return;
        }
        let today = self.current_date.to_string();
        let already = self.db.get_app_setting("trigger_day_start_fired").ok().flatten();
        if already.as_deref() == Some(today.as_str()) {
            return;
        }
        let _ = self.db.set_app_setting("trigger_day_start_fired", &today);
        self.fire_trigger(TriggerEvent::DayStart, "");
    }

    pub fn cycle_integration(&mut self) {
        if let InputMode::Settings { integration, current_field, .. } = &mut self.input_mode {
            if *current_field == 0 {
                *integration = integration.cycle_next();
                // Reset to field 0 since field layout changed
            }
        }
        self.update_field_label();
    }

    pub fn next_field(&mut self) {
        match &mut self.input_mode {
            InputMode::Creating { current_field, .. }
            | InputMode::Editing { current_field, .. } => {
                *current_field = (*current_field + 1) % 4;
            }
            InputMode::EditingDay { current_field, .. } => {
                *current_field = (*current_field + 1) % 2;
            }
            InputMode::Triggers { current_field, .. } => {
                *current_field = (*current_field + 1) % 9;
            }
            InputMode::Settings { current_field, integration, .. } => {
                let count = match integration {
                    IntegrationKind::CustomCommands => 14,
                    IntegrationKind::Jira => 15,
                };
                *current_field = (*current_field + 1) % count;
            }
            InputMode::PassphraseChange { current_field, is_initial_setup, .. } => {
                let count = if *is_initial_setup { 2 } else { 3 };
                *current_field = (*current_field + 1) % count;
            }
            _ => {}
        }
        crate::cursor::reset_cursor_to_end(&mut self.input_mode);
        self.update_field_label();
    }

    pub fn previous_field(&mut self) {
        match &mut self.input_mode {
            InputMode::Triggers { current_field, .. } => {
                *current_field = if *current_field == 0 { 8 } else { *current_field - 1 };
            }
            InputMode::Settings { current_field, integration, .. } => {
                let count = match integration {
                    IntegrationKind::CustomCommands => 14,
                    IntegrationKind::Jira => 15,
                };
                *current_field = if *current_field == 0 {
                    count - 1
                } else {
                    *current_field - 1
                };
            }
            InputMode::PassphraseChange { current_field, is_initial_setup, .. } => {
                let count = if *is_initial_setup { 2 } else { 3 };
                *current_field = if *current_field == 0 {
                    count - 1
                } else {
                    *current_field - 1
                };
            }
            _ => {}
        }
        crate::cursor::reset_cursor_to_end(&mut self.input_mode);
        self.update_field_label();
    }

    pub fn cycle_color(&mut self, forward: bool) {
        if let InputMode::Settings {
            integration,
            colors,
            current_field,
            ..
        } = &mut self.input_mode
        {
            let colors_start = match integration {
                IntegrationKind::CustomCommands => 8,
                IntegrationKind::Jira => 9,
            };
            if *current_field >= colors_start && *current_field < colors_start + 6 {
                let color_idx = *current_field - colors_start;
                let available = Config::available_colors();

                // Find current color index
                if let Some(current_idx) = available.iter().position(|&c| c == colors[color_idx]) {
                    let new_idx = if forward {
                        (current_idx + 1) % available.len()
                    } else {
                        if current_idx == 0 {
                            available.len() - 1
                        } else {
                            current_idx - 1
                        }
                    };
                    colors[color_idx] = available[new_idx].to_string();
                }
            }
        }
        self.update_field_label();
    }

    pub fn insert_variable(&mut self) {
        if let InputMode::Settings {
            integration,
            current_field,
            ..
        } = &self.input_mode
        {
            // Only insert variables for CustomCommands fields 1 and 2
            if *integration != IntegrationKind::CustomCommands {
                return;
            }
            if *current_field != 1 && *current_field != 2 {
                return;
            }

            let variables = Config::available_variables();
            static mut VARIABLE_INDEX: usize = 0;

            let var = unsafe {
                let v = variables[VARIABLE_INDEX % variables.len()];
                VARIABLE_INDEX = (VARIABLE_INDEX + 1) % variables.len();
                v
            };

            crate::cursor::insert_str(&mut self.input_mode, var);
        }
        self.update_field_label();
    }

    /// Cycle-insert a `[[variable]]` into the active Triggers text field.
    pub fn insert_trigger_variable(&mut self) {
        if let InputMode::Triggers { current_field, .. } = &self.input_mode {
            // Only URL (sub 1) and body (sub 2) are text fields.
            if current_field % 3 == 0 {
                return;
            }
            let variables = Config::available_trigger_variables();
            static mut TRIGGER_VARIABLE_INDEX: usize = 0;
            let var = unsafe {
                let v = variables[TRIGGER_VARIABLE_INDEX % variables.len()];
                TRIGGER_VARIABLE_INDEX = (TRIGGER_VARIABLE_INDEX + 1) % variables.len();
                v
            };
            crate::cursor::insert_str(&mut self.input_mode, var);
        }
        self.update_field_label();
    }

    pub fn increment_time(&mut self) {
        match &mut self.input_mode {
            InputMode::Creating {
                start_time,
                end_time,
                current_field,
                ..
            }
            | InputMode::Editing {
                start_time,
                end_time,
                current_field,
                ..
            } => {
                if *current_field == 1 {
                    // Increment start time (down = forward in time)
                    *start_time = adjust_time_string(start_time, 1);
                } else if *current_field == 2 {
                    // Increment end time (down = forward in time)
                    *end_time = adjust_time_string(end_time, 1);
                }
            }
            InputMode::EditingDay { start_time, end_time, current_field, .. } => {
                if *current_field == 0 {
                    *start_time = adjust_time_string(start_time, 1);
                } else if *current_field == 1 {
                    *end_time = adjust_time_string(end_time, 1);
                }
            }
            _ => {}
        }
        self.update_field_label();
    }

    pub fn decrement_time(&mut self) {
        match &mut self.input_mode {
            InputMode::Creating {
                start_time,
                end_time,
                current_field,
                ..
            }
            | InputMode::Editing {
                start_time,
                end_time,
                current_field,
                ..
            } => {
                if *current_field == 1 {
                    // Decrement start time (up = back in time)
                    *start_time = adjust_time_string(start_time, -1);
                } else if *current_field == 2 {
                    // Decrement end time (up = back in time)
                    *end_time = adjust_time_string(end_time, -1);
                }
            }
            InputMode::EditingDay { start_time, end_time, current_field, .. } => {
                if *current_field == 0 {
                    *start_time = adjust_time_string(start_time, -1);
                } else if *current_field == 1 {
                    *end_time = adjust_time_string(end_time, -1);
                }
            }
            _ => {}
        }
        self.update_field_label();
    }

    fn update_field_label(&mut self) {
        let show_cursor = true;
        match &mut self.input_mode {
            InputMode::Creating {
                field,
                current_field,
                cursor_pos,
                description,
                start_time,
                end_time,
                issue_key,
                ..
            } => {
                let cp = *cursor_pos;
                *field = match current_field {
                    0 => format!("Description [{}]", crate::cursor::render_with_cursor(description, cp, show_cursor)),
                    1 => format!("Start Time [{}]", crate::cursor::render_with_cursor(start_time, cp, show_cursor)),
                    2 => format!("End Time [{}]", crate::cursor::render_with_cursor(end_time, cp, show_cursor)),
                    3 => format!("Issue Key [{}]", crate::cursor::render_with_cursor(issue_key, cp, show_cursor)),
                    _ => "Unknown".to_string(),
                };
            }
            InputMode::Editing {
                field,
                current_field,
                cursor_pos,
                description,
                start_time,
                end_time,
                issue_key,
                ..
            } => {
                let cp = *cursor_pos;
                *field = match current_field {
                    0 => format!("Description [{}]", crate::cursor::render_with_cursor(description, cp, show_cursor)),
                    1 => format!("Start Time [{}]", crate::cursor::render_with_cursor(start_time, cp, show_cursor)),
                    2 => format!("End Time [{}]", crate::cursor::render_with_cursor(end_time, cp, show_cursor)),
                    3 => format!("Issue Key [{}]", crate::cursor::render_with_cursor(issue_key, cp, show_cursor)),
                    _ => "Unknown".to_string(),
                };
            }
            InputMode::Settings {
                field,
                integration,
                current_field,
                open_command,
                open_worklog_command,
                jira_url_setting,
                jira_email,
                jira_api_token,
                date_format,
                legacy_time_format,
                hide_eye_candy,
                colors,
                ..
            } => {
                *field = match integration {
                    IntegrationKind::CustomCommands => match current_field {
                        0 => format!("Integration: {}", integration.display_name()),
                        1 => format!("Log Work Command: {}", open_command),
                        2 => format!("Open Issue Command: {}", open_worklog_command),
                        3 => format!("Date Format: {}", date_format),
                        4 => format!("Legacy Time Format: {}", if *legacy_time_format { "Yes" } else { "No" }),
                        5 => "Change Passphrase".to_string(),
                        6 => "Triggers".to_string(),
                        7 => format!("Hide Eye Candy: {}", if *hide_eye_candy { "Yes" } else { "No" }),
                        8..=13 => {
                            let color_idx = *current_field - 8;
                            format!("{}: {}", Config::color_names()[color_idx], colors[color_idx])
                        }
                        _ => "Settings".to_string(),
                    },
                    IntegrationKind::Jira => match current_field {
                        0 => format!("Integration: {}", integration.display_name()),
                        1 => format!("Jira URL: {}", jira_url_setting),
                        2 => format!("Jira Email: {}", jira_email),
                        3 => format!("API Token: {}", "*".repeat(jira_api_token.len().min(20))),
                        4 => format!("Date Format: {}", date_format),
                        5 => format!("Legacy Time Format: {}", if *legacy_time_format { "Yes" } else { "No" }),
                        6 => "Change Passphrase".to_string(),
                        7 => "Triggers".to_string(),
                        8 => format!("Hide Eye Candy: {}", if *hide_eye_candy { "Yes" } else { "No" }),
                        9..=14 => {
                            let color_idx = *current_field - 9;
                            format!("{}: {}", Config::color_names()[color_idx], colors[color_idx])
                        }
                        _ => "Settings".to_string(),
                    },
                };
            }
            InputMode::EditingDay {
                field,
                current_field,
                cursor_pos,
                start_time,
                end_time,
            } => {
                let cp = *cursor_pos;
                *field = match current_field {
                    0 => format!("Start Time [{}]", crate::cursor::render_with_cursor(start_time, cp, show_cursor)),
                    1 => format!("End Time [{}]", crate::cursor::render_with_cursor(end_time, cp, show_cursor)),
                    _ => "Unknown".to_string(),
                };
            }
            InputMode::Triggers {
                field,
                current_field,
                cursor_pos,
                urls,
                bodies,
                ..
            } => {
                let cp = *cursor_pos;
                let event = *current_field / 3;
                let sub = *current_field % 3;
                *field = match sub {
                    1 => format!("URL [{}]", crate::cursor::render_with_cursor(&urls[event], cp, show_cursor)),
                    2 => format!("Body [{}]", crate::cursor::render_with_cursor(&bodies[event], cp, show_cursor)),
                    _ => "Enabled".to_string(),
                };
            }
            InputMode::PassphrasePrompt { .. } => {}
            InputMode::PassphraseChange { .. } => {}
            _ => {}
        }
    }

    pub fn save_entry(&mut self) -> Result<()> {
        match &self.input_mode {
            InputMode::Creating {
                description,
                start_time,
                end_time,
                issue_key,
                off_work,
                ..
            } => {
                let start = self.parse_time(start_time)?;
                let end = if end_time.is_empty() {
                    None
                } else {
                    Some(self.parse_time(end_time)?)
                };

                let ik = issue_key.clone();
                let off_work = *off_work;
                let description = description.clone();
                let new_id = self
                    .db
                    .create_entry(description.clone(), start, end, ik.clone())?;
                if off_work {
                    self.db.toggle_off_work(new_id)?;
                }
                if !ik.is_empty() {
                    let _ = self.db.ensure_task_exists(&ik);
                    if !self.task_names.contains_key(&ik) {
                        self.sync_task_name_from_jira(&ik);
                    }
                }
                self.refresh_entries()?;
                if off_work {
                    // A new off-work entry means going out of office.
                    self.fire_trigger(TriggerEvent::OooStart, &description);
                } else {
                    // A new work entry starts the workday → fire the day-start webhook.
                    self.maybe_fire_day_start();
                }
            }
            InputMode::Editing {
                entry_id,
                description,
                start_time,
                end_time,
                issue_key,
                ..
            } => {
                let start = self.parse_time(start_time)?;
                let end = if end_time.is_empty() {
                    None
                } else {
                    Some(self.parse_time(end_time)?)
                };

                let ik = issue_key.clone();
                self.db.update_entry(
                    *entry_id,
                    description.clone(),
                    start,
                    end,
                    ik.clone(),
                )?;
                if !ik.is_empty() {
                    let _ = self.db.ensure_task_exists(&ik);
                    if !self.task_names.contains_key(&ik) {
                        self.sync_task_name_from_jira(&ik);
                    }
                }
                self.refresh_entries()?;
            }
            InputMode::EditingDay {
                start_time,
                end_time,
                ..
            } => {
                let start = self.parse_time(start_time)?;
                let end = self.parse_time(end_time)?;
                self.db.set_day_overrides(self.current_date, Some(start), Some(end))?;
                self.refresh_entries()?;
            }
            _ => {}
        }

        self.input_mode = InputMode::Normal;
        Ok(())
    }

    pub fn cancel_input(&mut self) {
        self.input_mode = InputMode::Normal;
    }

    pub fn open_settings(&mut self) {
        let jira_api_token = self.secrets.get("jira_api_token")
            .unwrap_or(None)
            .unwrap_or_default();

        self.input_mode = InputMode::Settings {
            field: "Integration".to_string(),
            integration: self.config.integration.clone(),
            open_command: self.config.open_command.clone(),
            open_worklog_command: self.config.open_worklog_command.clone(),
            jira_url_setting: self.config.jira_url_setting.clone().unwrap_or_default(),
            jira_email: self.config.jira_email.clone().unwrap_or_default(),
            jira_api_token,
            date_format: self.config.date_format.clone(),
            legacy_time_format: self.config.legacy_time_format,
            hide_eye_candy: self.config.hide_eye_candy,
            colors: self.config.colors.clone(),
            current_field: 0,
            cursor_pos: 0,
            debug_log_scroll_offset: 0,
        };
        self.update_field_label();
    }

    pub fn save_settings(&mut self) -> Result<()> {
        if let InputMode::Settings {
            integration,
            open_command,
            open_worklog_command,
            jira_url_setting,
            jira_email,
            jira_api_token,
            date_format,
            legacy_time_format,
            hide_eye_candy,
            colors,
            ..
        } = &self.input_mode
        {
            self.config.integration = integration.clone();
            self.config.open_command = open_command.clone();
            self.config.open_worklog_command = open_worklog_command.clone();
            self.config.jira_url_setting = if jira_url_setting.is_empty() {
                None
            } else {
                Some(jira_url_setting.clone())
            };
            self.config.jira_email = if jira_email.is_empty() {
                None
            } else {
                Some(jira_email.clone())
            };
            self.config.date_format = date_format.clone();
            self.config.legacy_time_format = *legacy_time_format;
            self.config.hide_eye_candy = *hide_eye_candy;
            self.config.colors = colors.clone();
            self.config.save()?;

            // Save API token to secrets manager
            if jira_api_token.is_empty() {
                let _ = self.secrets.delete("jira_api_token");
            } else {
                // If encryption is not set up, redirect to passphrase setup first
                if !self.secrets.is_unlocked() && !self.secrets.has_encrypted_file() {
                    self.pending_api_token = Some(jira_api_token.clone());
                    self.input_mode = InputMode::PassphraseChange {
                        old_passphrase: String::new(),
                        new_passphrase: String::new(),
                        confirm_passphrase: String::new(),
                        current_field: 0,
                        cursor_pos: 0,
                        error_message: None,
                        is_initial_setup: true,
                    };
                    return Ok(());
                }
                self.secrets.set("jira_api_token", jira_api_token)?;
            }
        }
        self.input_mode = InputMode::Normal;
        Ok(())
    }

    pub fn confirm_delete(&mut self) {
        if let Some(idx) = self.selected_index {
            if let Some(entry) = self.entries.get(idx) {
                self.input_mode = InputMode::ConfirmDelete { entry_id: entry.id };
            }
        }
    }

    pub fn delete_entry(&mut self, entry_id: i64) -> Result<()> {
        self.db.delete_entry(entry_id)?;
        self.refresh_entries()?;
        self.input_mode = InputMode::Normal;
        Ok(())
    }

    pub fn force_delete_entry(&mut self) -> Result<()> {
        if let Some(idx) = self.selected_index {
            if let Some(entry) = self.entries.get(idx) {
                self.db.delete_entry(entry.id)?;
                self.refresh_entries()?;
            }
        }
        Ok(())
    }

    pub fn stop_or_restart_entry(&mut self) -> Result<()> {
        if let Some(idx) = self.selected_index {
            if let Some(entry) = self.entries.get(idx) {
                if entry.is_running() {
                    // Stop the running entry
                    let now = Local::now().naive_local();
                    let was_off_work = entry.off_work;
                    let description = entry.description.clone();
                    self.db.update_entry(
                        entry.id,
                        entry.description.clone(),
                        entry.start_time,
                        Some(now),
                        entry.issue_key.clone(),
                    )?;
                    self.refresh_entries()?;
                    // Stopping a running off-work entry means coming back in.
                    if was_off_work {
                        self.fire_trigger(TriggerEvent::OooEnd, &description);
                    }
                } else {
                    // Start a new entry with the same description and issue_key, but allow editing
                    let now = Local::now().naive_local();
                    let suggestions = self
                        .db
                        .get_previous_tasks_with_issue_keys()
                        .unwrap_or_default();
                    let desc_len = entry.description.chars().count();
                    self.input_mode = InputMode::Creating {
                        field: "Description".to_string(),
                        description: entry.description.clone(),
                        start_time: now.format("%H:%M").to_string(),
                        end_time: String::new(),
                        issue_key: entry.issue_key.clone(),
                        current_field: 0,
                        cursor_pos: desc_len,
                        suggestions,
                        selected_suggestion: 0,
                        off_work: false,
                    };
                }
            }
        }
        Ok(())
    }

    /// 's' on the At Work row: clock in at the current time, or revert the
    /// start to auto (first task) if a manual start is already set.
    pub fn toggle_at_work_start(&mut self) -> Result<()> {
        let new_start = if self.day_start_override.is_some() {
            None
        } else {
            Some(Local::now().naive_local())
        };
        self.db.set_day_overrides(self.current_date, new_start, self.day_end_override)?;
        self.refresh_entries()?;
        self.maybe_fire_day_start();
        Ok(())
    }

    /// 'e' on the At Work row: edit the start and end times manually.
    pub fn start_editing_day(&mut self) {
        if let Some((start, end, _)) = self.at_work_span() {
            let start_str = start.format("%H:%M").to_string();
            let cursor_pos = start_str.chars().count();
            self.input_mode = InputMode::EditingDay {
                field: String::new(),
                start_time: start_str,
                end_time: end.format("%H:%M").to_string(),
                current_field: 0,
                cursor_pos,
            };
            self.update_field_label();
        }
    }

    /// 'd' on the At Work row: drop manual overrides and revert to auto.
    pub fn reset_day_overrides(&mut self) -> Result<()> {
        self.db.set_day_overrides(self.current_date, None, None)?;
        self.refresh_entries()?;
        Ok(())
    }

    fn parse_time(&self, time_str: &str) -> Result<NaiveDateTime> {
        let time = NaiveTime::parse_from_str(time_str, "%H:%M")
            .or_else(|_| NaiveTime::parse_from_str(time_str, "%H:%M:%S"))?;
        Ok(self.current_date.and_time(time))
    }

    pub fn copy_time_to_clipboard(&mut self) -> Result<()> {
        if let Some(idx) = self.selected_index {
            if let Some(entry) = self.entries.get(idx) {
                if let Some(duration_minutes) = entry.duration_minutes() {
                    let time_str = format!("{}m", duration_minutes);

                    // Create clipboard if it doesn't exist
                    if self.clipboard.is_none() {
                        self.clipboard = Clipboard::new().ok();
                    }

                    // Use persistent clipboard instance
                    if let Some(clip) = &mut self.clipboard {
                        match clip.set_text(time_str.clone()) {
                            Ok(_) => {
                                self.debug_log
                                    .push(format!("[CLIPBOARD] Copied: {}", time_str));
                                while self.debug_log.len() > 10000 {
                                    self.debug_log.remove(0);
                                }
                            }
                            Err(e) => {
                                self.debug_log.push(format!("[CLIPBOARD ERROR] {}", e));
                                while self.debug_log.len() > 10000 {
                                    self.debug_log.remove(0);
                                }
                            }
                        }
                    }
                }
            }
        }
        Ok(())
    }

    /// Undo a logged entry: delete the remote Jira worklog when we recorded its
    /// id, then clear the local logged flag. Falls back to a local-only unmark
    /// for custom integrations or entries that were never pushed.
    fn unlog_entry(&mut self, entry_id: i64, issue_key: &str, worklog_id: &str, is_jira: bool) {
        if is_jira && !worklog_id.is_empty() {
            let jira_url = self.config.jira_url_setting.clone().unwrap_or_default();
            let jira_email = self.config.jira_email.clone().unwrap_or_default();
            let api_token = self.secrets.get("jira_api_token").unwrap_or(None).unwrap_or_default();

            if let Some(output) = crate::integrations::delete_work(
                &self.config.integration,
                &jira_url,
                &jira_email,
                &api_token,
                issue_key,
                worklog_id,
            ) {
                for msg in &output.messages {
                    self.debug_log.push(msg.clone());
                }
                while self.debug_log.len() > 10000 {
                    self.debug_log.remove(0);
                }
                if output.success {
                    let _ = self.db.unmark_logged(entry_id);
                    let _ = self.refresh_entries();
                    self.status_message = Some("Worklog deleted from Jira".to_string());
                } else {
                    self.status_message = Some("Failed to delete worklog (see debug log)".to_string());
                }
            }
        } else {
            // No remote worklog to remove: just clear the local flag.
            let _ = self.db.unmark_logged(entry_id);
            let _ = self.refresh_entries();
            self.status_message = Some("Unmarked as logged".to_string());
        }
    }

    pub fn run_log_command(&mut self) -> Result<()> {
        if let Some(idx) = self.selected_index {
            if let Some(entry) = self.entries.get(idx) {
                // Toggle: if already logged, undo it — deleting the remote Jira
                // worklog when we have its id — instead of logging again.
                if entry.logged {
                    let entry_id = entry.id;
                    let issue_key = entry.issue_key.clone();
                    let worklog_id = entry.worklog_id.clone();
                    let is_jira = !issue_key.is_empty()
                        && self.config.integration != IntegrationKind::CustomCommands;
                    self.unlog_entry(entry_id, &issue_key, &worklog_id, is_jira);
                    return Ok(());
                }
                if !entry.issue_key.is_empty() && self.config.integration != IntegrationKind::CustomCommands {
                    // Use built-in integration
                    let jira_url = self.config.jira_url_setting.clone().unwrap_or_default();
                    let jira_email = self.config.jira_email.clone().unwrap_or_default();
                    let api_token = self.secrets.get("jira_api_token")
                        .unwrap_or(None)
                        .unwrap_or_default();

                    let entry_started = if self.config.legacy_time_format {
                        entry.start_time.and_utc().format("%Y-%m-%dT%H:%M:%S%.3f%z").to_string()
                    } else {
                        entry.start_time.and_utc().to_rfc3339()
                    };

                    let task_duration = entry
                        .duration_minutes()
                        .map(|m| format!("{}m", m))
                        .unwrap_or_default();

                    let entry_id = entry.id;
                    let is_logged = entry.logged;

                    let entry_description = entry.description.clone();

                    if let Some(output) = crate::integrations::log_work(
                        &self.config.integration,
                        &jira_url,
                        &jira_email,
                        &api_token,
                        &entry.issue_key,
                        &task_duration,
                        &entry_started,
                        &entry_description,
                    ) {
                        for msg in &output.messages {
                            self.debug_log.push(msg.clone());
                        }
                        if output.success && !is_logged {
                            let wid = output.worklog_id.clone().unwrap_or_default();
                            if let Err(e) = self.db.mark_logged(entry_id, &wid) {
                                self.debug_log.push(format!("[JIRA] Failed to mark as logged: {}", e));
                            } else {
                                self.debug_log.push("[JIRA] Automatically marked as logged".to_string());
                                let _ = self.refresh_entries();
                            }
                        }
                        while self.debug_log.len() > 10000 {
                            self.debug_log.remove(0);
                        }
                    }
                    return Ok(());
                }

                if !entry.issue_key.is_empty() {
                    // Format time based on legacy_time_format setting
                    let entry_started = if self.config.legacy_time_format {
                        // Legacy format: 2025-11-06T14:25:00.000+0000
                        entry.start_time.and_utc().format("%Y-%m-%dT%H:%M:%S%.3f%z").to_string()
                    } else {
                        // ISO 8601 format: 2025-11-06T14:25:00.000+00:00
                        entry.start_time.and_utc().to_rfc3339()
                    };

                    self.debug_log.push(entry_started.clone());

                    let entry_ended = entry.end_time.map(|t| t.to_string()).unwrap_or_default();
                    let task_duration = entry
                        .duration_minutes()
                        .map(|m| format!("{}m", m))
                        .unwrap_or_default();

                    let command = self.config.substitute_variables(
                        &entry.issue_key,
                        &entry_started,
                        &entry_ended,
                        &task_duration,
                        &entry.description,
                    );

                    // Execute the command using shell for proper argument parsing
                    let mut process = if cfg!(target_os = "windows") {
                        let mut cmd = std::process::Command::new("cmd");
                        cmd.args(&["/C", &command]);
                        cmd
                    } else {
                        let mut cmd = std::process::Command::new("sh");
                        cmd.args(&["-c", &command]);
                        cmd
                    };

                    // Capture output
                    process.stdin(std::process::Stdio::null());
                    process.stdout(std::process::Stdio::piped());
                    process.stderr(std::process::Stdio::piped());

                    let entry_id = entry.id;
                    let is_logged = entry.logged;
                    match process.output() {
                            Ok(output) => {
                                self.debug_log
                                    .push(format!("[LOG WORK] Executed: {}", command));

                                // Log stdout if present
                                if !output.stdout.is_empty() {
                                    if let Ok(stdout_str) = String::from_utf8(output.stdout) {
                                        for line in stdout_str.lines() {
                                            self.debug_log
                                                .push(format!("[LOG WORK STDOUT] {}", line));
                                        }
                                    }
                                }

                                // Log stderr if present
                                if !output.stderr.is_empty() {
                                    if let Ok(stderr_str) = String::from_utf8(output.stderr) {
                                        for line in stderr_str.lines() {
                                            self.debug_log
                                                .push(format!("[LOG WORK STDERR] {}", line));
                                        }
                                    }
                                }

                                // Log exit status
                                self.debug_log
                                    .push(format!("[LOG WORK EXIT CODE] {}", output.status));

                                // Mark task as logged if command succeeded (exit code 0) and not already logged
                                if output.status.success() && !is_logged {
                                    if let Err(e) = self.db.toggle_logged(entry_id) {
                                        self.debug_log.push(format!(
                                            "[LOG WORK] Failed to mark as logged: {}",
                                            e
                                        ));
                                    } else {
                                        self.debug_log.push("[LOG WORK] Automatically marked as logged".to_string());
                                        // Refresh entries to show updated logged status
                                        let _ = self.refresh_entries();
                                    }
                                }

                                // Keep only last 10000 log entries
                                while self.debug_log.len() > 10000 {
                                    self.debug_log.remove(0);
                                }
                        }
                        Err(e) => {
                            self.debug_log
                                .push(format!("[LOG WORK ERROR] Failed: {} - {}", command, e));
                            while self.debug_log.len() > 10000 {
                                self.debug_log.remove(0);
                            }
                        }
                    }
                }
            }
        }
        Ok(())
    }

    /// Fetch a single issue's summary from Jira and store it in the tasks table.
    pub fn sync_task_name_from_jira(&mut self, issue_key: &str) {
        let jira_url = self.config.jira_url_setting.clone().unwrap_or_default();
        let jira_email = self.config.jira_email.clone().unwrap_or_default();
        let api_token = self.secrets.get("jira_api_token")
            .unwrap_or(None)
            .unwrap_or_default();

        if let Some(result) = crate::integrations::fetch_issue_summary(
            &self.config.integration,
            &jira_url,
            &jira_email,
            &api_token,
            issue_key,
        ) {
            match result {
                Ok(name) if !name.is_empty() => {
                    if let Err(e) = self.db.update_task_name(issue_key, &name) {
                        self.debug_log.push(format!("[JIRA] Failed to save task name for {}: {}", issue_key, e));
                    } else {
                        self.task_names.insert(issue_key.to_string(), name.clone());
                        self.debug_log.push(format!("[JIRA] Synced {}: {}", issue_key, name));
                    }
                }
                Ok(_) => {
                    self.debug_log.push(format!("[JIRA] Empty summary for {}", issue_key));
                }
                Err(e) => {
                    self.debug_log.push(e);
                }
            }
        }
    }

    /// Sync task names for all tasks that have an issue_key but no name yet.
    pub fn sync_all_task_names(&mut self) {
        let keys = self.db.get_tasks_with_empty_names().unwrap_or_default();
        if keys.is_empty() {
            self.status_message = Some("All tasks already have names".to_string());
            return;
        }
        let count = keys.len();
        for key in keys {
            self.sync_task_name_from_jira(&key);
        }
        self.refresh_task_names();
        self.status_message = Some(format!("Synced {} task name(s) from Jira", count));
    }

    pub fn run_open_worklog_command(&mut self) -> Result<()> {
        if let Some(idx) = self.selected_index {
            if let Some(entry) = self.entries.get(idx) {
                if !entry.issue_key.is_empty() && self.config.integration != IntegrationKind::CustomCommands {
                    // Use built-in integration
                    let jira_url = self.config.jira_url_setting.clone().unwrap_or_default();

                    if let Some(output) = crate::integrations::open_issue(
                        &self.config.integration,
                        &jira_url,
                        &entry.issue_key,
                    ) {
                        for msg in &output.messages {
                            self.debug_log.push(msg.clone());
                        }
                        while self.debug_log.len() > 10000 {
                            self.debug_log.remove(0);
                        }
                    }
                    return Ok(());
                }

                // Execute worklog command with variable substitution
                if !entry.issue_key.is_empty() {
                    let entry_started = entry.start_time.to_string();
                    let entry_ended = entry.end_time.map(|t| t.to_string()).unwrap_or_default();
                    let task_duration = entry
                        .duration_minutes()
                        .map(|m| format!("{}m", m))
                        .unwrap_or_default();

                    // Use open_worklog_command with variable substitution
                    let command = self
                        .config
                        .open_worklog_command
                        .replace("[[issue_key]]", &entry.issue_key)
                        .replace("[[entry_started]]", &entry_started)
                        .replace("[[entry_ended]]", &entry_ended)
                        .replace("[[task_duration]]", &task_duration)
                        .replace("[[description]]", &entry.description);

                    // Execute the command using shell for proper argument parsing
                    let mut process = if cfg!(target_os = "windows") {
                        let mut cmd = std::process::Command::new("cmd");
                        cmd.args(&["/C", &command]);
                        cmd
                    } else {
                        let mut cmd = std::process::Command::new("sh");
                        cmd.args(&["-c", &command]);
                        cmd
                    };

                    // Capture output
                    process.stdin(std::process::Stdio::null());
                    process.stdout(std::process::Stdio::piped());
                    process.stderr(std::process::Stdio::piped());

                    match process.output() {
                            Ok(output) => {
                                self.debug_log
                                    .push(format!("[OPEN ISSUE] Executed: {}", command));

                                // Log stdout if present
                                if !output.stdout.is_empty() {
                                    if let Ok(stdout_str) = String::from_utf8(output.stdout) {
                                        for line in stdout_str.lines() {
                                            self.debug_log
                                                .push(format!("[OPEN ISSUE STDOUT] {}", line));
                                        }
                                    }
                                }

                                // Log stderr if present
                                if !output.stderr.is_empty() {
                                    if let Ok(stderr_str) = String::from_utf8(output.stderr) {
                                        for line in stderr_str.lines() {
                                            self.debug_log
                                                .push(format!("[OPEN ISSUE STDERR] {}", line));
                                        }
                                    }
                                }

                                // Log exit status
                                self.debug_log.push(format!(
                                    "[OPEN ISSUE OPEN ISSUE EXIT CODE] {}",
                                    output.status
                                ));

                                // Keep only last 10000 log entries
                                while self.debug_log.len() > 10000 {
                                    self.debug_log.remove(0);
                                }
                        }
                        Err(e) => {
                            self.debug_log.push(format!(
                                "[OPEN ISSUE ERROR] Failed: {} - {}",
                                command, e
                            ));
                            while self.debug_log.len() > 10000 {
                                self.debug_log.remove(0);
                            }
                        }
                    }
                }
            }
        }
        Ok(())
    }

    pub fn toggle_logged(&mut self) -> Result<()> {
        if let Some(idx) = self.selected_index {
            if let Some(entry) = self.entries.get(idx) {
                self.db.toggle_logged(entry.id)?;
                self.refresh_entries()?;
            }
        }
        Ok(())
    }

    /// Clear the status message
    pub fn clear_status(&mut self) {
        self.status_message = None;
    }

    /// Check if a new version is available and show What's New modal if needed
    pub fn check_version(&mut self) -> Result<()> {
        let current_version = env!("CARGO_PKG_VERSION");
        let last_seen = self.db.get_last_seen_version()?;

        if last_seen.as_deref() != Some(current_version) {
            self.input_mode = InputMode::WhatsNew;
        }

        Ok(())
    }

    /// Close What's New modal and save the current version
    pub fn close_whats_new(&mut self) -> Result<()> {
        let current_version = env!("CARGO_PKG_VERSION");
        self.db.set_last_seen_version(current_version)?;
        self.input_mode = InputMode::Normal;
        Ok(())
    }

    /// Get the earliest start time from all entries (entries can be out of order)
    pub fn get_earliest_start_time(&self) -> Option<NaiveDateTime> {
        self.entries.iter().map(|e| e.start_time).min()
    }

    /// Get the latest end time from all entries, or current time if any entry is running
    pub fn get_latest_end_time(&self, date: Option<NaiveDate>) -> Option<NaiveDateTime> {
        if self.entries.is_empty() {
            return None;
        }

        // Filter entries by date if provided
        let filtered_entries: Vec<&TimeEntry> = if let Some(filter_date) = date {
            self.entries
                .iter()
                .filter(|e| e.start_time.date() == filter_date)
                .collect()
        } else {
            self.entries.iter().collect()
        };

        if filtered_entries.is_empty() {
            return None;
        }

        // Check if any entry is running
        let has_running = filtered_entries.iter().any(|e| e.is_running());

        if has_running {
            Some(Local::now().naive_local())
        } else {
            // Find the maximum end time
            filtered_entries.iter().filter_map(|e| e.end_time).max()
        }
    }

    /// Scroll the debug log in settings view
    pub fn scroll_debug_log(&mut self, direction: i32) {
        if let InputMode::Settings {
            debug_log_scroll_offset,
            ..
        } = &mut self.input_mode
        {
            if direction > 0 {
                // Scroll down (show older logs)
                *debug_log_scroll_offset =
                    (*debug_log_scroll_offset + 1).min(self.debug_log.len().saturating_sub(1));
            } else {
                // Scroll up (show newer logs)
                *debug_log_scroll_offset = debug_log_scroll_offset.saturating_sub(1);
            }
        }
    }

    /// Toggle legacy time format setting
    pub fn toggle_legacy_time_format(&mut self) {
        if let InputMode::Settings {
            legacy_time_format,
            ..
        } = &mut self.input_mode
        {
            *legacy_time_format = !*legacy_time_format;
        }
        self.update_field_label();
    }

    /// Toggle the "hide eye candy" setting (turns off shimmer/breathe animations).
    pub fn toggle_hide_eye_candy(&mut self) {
        if let InputMode::Settings {
            hide_eye_candy,
            ..
        } = &mut self.input_mode
        {
            *hide_eye_candy = !*hide_eye_candy;
        }
        self.update_field_label();
    }

    // ---- Weekly summary editing ----

    /// Date of the currently highlighted day column.
    pub fn week_selected_date(&self) -> Option<NaiveDate> {
        if let InputMode::WeekSummary { anchor, selected_day, .. } = &self.input_mode {
            let monday =
                *anchor - Duration::days(anchor.weekday().num_days_from_monday() as i64);
            Some(monday + Duration::days(*selected_day as i64))
        } else {
            None
        }
    }

    /// Move the highlighted day; rolls into the adjacent week at the Mon/Sun edge.
    pub fn week_select_day(&mut self, delta: i64) {
        if let InputMode::WeekSummary { anchor, selected_day, .. } = &mut self.input_mode {
            let sd = *selected_day as i64 + delta;
            if sd < 0 {
                *anchor -= Duration::days(7);
                *selected_day = 6;
            } else if sd > 6 {
                *anchor += Duration::days(7);
                *selected_day = 0;
            } else {
                *selected_day = sd as usize;
            }
        }
    }

    /// Page the displayed week by `delta` weeks, keeping the highlighted weekday.
    pub fn week_change_week(&mut self, delta: i64) {
        if let InputMode::WeekSummary { anchor, .. } = &mut self.input_mode {
            *anchor += Duration::days(7 * delta);
        }
    }

    /// Move between the edit-panel fields (Workday Start / End / Lunch).
    pub fn week_move_field(&mut self, delta: i64) {
        if let InputMode::WeekSummary { selected_field, .. } = &mut self.input_mode {
            *selected_field = (((*selected_field as i64 + delta) % 3 + 3) % 3) as usize;
        }
    }

    /// Leave the weekly summary and open the highlighted day in the normal dashboard.
    pub fn week_open_day(&mut self) -> Result<()> {
        let date = match self.week_selected_date() {
            Some(d) => d,
            None => return Ok(()),
        };
        self.current_date = date;
        self.at_work_selected = false;
        self.selected_index = Some(0);
        self.refresh_entries()?;
        self.input_mode = InputMode::Normal;
        Ok(())
    }

    /// Begin editing the highlighted field of the highlighted day.
    pub fn week_begin_edit(&mut self) {
        let date = match self.week_selected_date() {
            Some(d) => d,
            None => return,
        };
        let kind = if let InputMode::WeekSummary { selected_field, .. } = &self.input_mode {
            *selected_field
        } else {
            return;
        };
        let now = Local::now().naive_local();
        let entries = self.db.get_entries_for_date(date).unwrap_or_default();
        let (s_ov, e_ov) = self.db.get_day_overrides(date).unwrap_or((None, None));

        let draft = if kind == 2 {
            // Lunch: edit the first off-work entry, or create one defaulting to the gap.
            if let Some(e) = entries.iter().find(|e| e.off_work) {
                let end = e.end_time.unwrap_or(now);
                DayEditDraft {
                    date,
                    kind: 2,
                    start: e.start_time.format("%H:%M").to_string(),
                    end: end.format("%H:%M").to_string(),
                    sub_field: 0,
                    lunch_entry_id: Some(e.id),
                }
            } else {
                let (start, end) = suggest_lunch_gap(&entries);
                DayEditDraft { date, kind: 2, start, end, sub_field: 0, lunch_entry_id: None }
            }
        } else {
            let (start, end) = at_work_span_of(&entries, s_ov, e_ov, now)
                .map(|(s, e, _)| (s.format("%H:%M").to_string(), e.format("%H:%M").to_string()))
                .unwrap_or_else(|| ("09:00".to_string(), "17:00".to_string()));
            DayEditDraft { date, kind, start, end, sub_field: 0, lunch_entry_id: None }
        };

        if let InputMode::WeekSummary { editing, .. } = &mut self.input_mode {
            *editing = Some(draft);
        }
    }

    /// Nudge the active time buffer by `delta` minutes (↑/↓ while editing).
    pub fn week_edit_adjust(&mut self, delta: i32) {
        if let InputMode::WeekSummary { editing: Some(d), .. } = &mut self.input_mode {
            let buf = day_edit_active_buf(d);
            *buf = adjust_time_string(buf, delta);
        }
    }

    pub fn week_edit_input(&mut self, c: char) {
        if !(c.is_ascii_digit() || c == ':') {
            return;
        }
        if let InputMode::WeekSummary { editing: Some(d), .. } = &mut self.input_mode {
            let buf = day_edit_active_buf(d);
            if buf.chars().count() < 5 {
                buf.push(c);
            }
        }
    }

    pub fn week_edit_backspace(&mut self) {
        if let InputMode::WeekSummary { editing: Some(d), .. } = &mut self.input_mode {
            day_edit_active_buf(d).pop();
        }
    }

    /// Tab between lunch start/end (no-op for workday fields).
    pub fn week_edit_tab(&mut self) {
        if let InputMode::WeekSummary { editing: Some(d), .. } = &mut self.input_mode {
            if d.kind == 2 {
                d.sub_field = (d.sub_field + 1) % 2;
            }
        }
    }

    pub fn week_edit_cancel(&mut self) {
        if let InputMode::WeekSummary { editing, .. } = &mut self.input_mode {
            *editing = None;
        }
    }

    /// Persist the in-progress edit: workday bounds as day overrides, lunch as an
    /// off-work entry (created or updated).
    pub fn week_edit_save(&mut self) -> Result<()> {
        let draft = match &self.input_mode {
            InputMode::WeekSummary { editing: Some(d), .. } => d.clone(),
            _ => return Ok(()),
        };
        let parse = |s: &str| NaiveTime::parse_from_str(s, "%H:%M");

        if draft.kind == 2 {
            if let (Ok(st), Ok(en)) = (parse(&draft.start), parse(&draft.end)) {
                let start_dt = draft.date.and_time(st);
                let end_dt = draft.date.and_time(en);
                if let Some(id) = draft.lunch_entry_id {
                    self.db
                        .update_entry(id, "Lunch".to_string(), start_dt, Some(end_dt), String::new())?;
                } else {
                    let id =
                        self.db
                            .create_entry("Lunch".to_string(), start_dt, Some(end_dt), String::new())?;
                    // New entries default to off_work = 0; flip it on.
                    self.db.toggle_off_work(id)?;
                }
            }
        } else {
            let (cur_s, cur_e) = self.db.get_day_overrides(draft.date).unwrap_or((None, None));
            let (mut new_s, mut new_e) = (cur_s, cur_e);
            if draft.kind == 0 {
                if let Ok(t) = parse(&draft.start) {
                    new_s = Some(draft.date.and_time(t));
                }
            } else if let Ok(t) = parse(&draft.end) {
                new_e = Some(draft.date.and_time(t));
            }
            self.db.set_day_overrides(draft.date, new_s, new_e)?;
        }

        if let InputMode::WeekSummary { editing, .. } = &mut self.input_mode {
            *editing = None;
        }
        if draft.date == self.current_date {
            self.refresh_entries()?;
        }
        Ok(())
    }
}

/// Effective "At Work" span for an arbitrary day's entries: (start, end, is_manual).
/// Manual overrides take precedence over the auto-derived first-start/last-end.
/// `now` is used as the end for running entries (and when clocked in with no ended task).
pub fn at_work_span_of(
    entries: &[TimeEntry],
    start_override: Option<NaiveDateTime>,
    end_override: Option<NaiveDateTime>,
    now: NaiveDateTime,
) -> Option<(NaiveDateTime, NaiveDateTime, bool)> {
    let auto_start = entries.iter().map(|e| e.start_time).min();
    let auto_end = entries.iter().map(|e| e.end_time.unwrap_or(now)).max();

    let start = start_override.or(auto_start);
    let end = end_override.or(auto_end);
    let manual = start_override.is_some() || end_override.is_some();

    match (start, end) {
        (Some(s), Some(e)) => Some((s, e.max(s), manual)),
        // Clocked in manually but no task has ended yet: span runs to now.
        (Some(s), None) => Some((s, now.max(s), manual)),
        _ => None,
    }
}

/// The time buffer currently being edited in a `DayEditDraft`.
fn day_edit_active_buf(d: &mut DayEditDraft) -> &mut String {
    match d.kind {
        1 => &mut d.end,                       // Workday End
        2 if d.sub_field == 1 => &mut d.end,   // Lunch end
        _ => &mut d.start,                     // Workday Start, or Lunch start
    }
}

/// Suggest a lunch slot = the largest positive gap between a day's tasks
/// (ignoring off-work entries and running entries). Falls back to 11:30–12:00.
fn suggest_lunch_gap(entries: &[TimeEntry]) -> (String, String) {
    let mut work: Vec<(NaiveDateTime, NaiveDateTime)> = entries
        .iter()
        .filter(|e| !e.off_work)
        .filter_map(|e| e.end_time.map(|end| (e.start_time, end)))
        .collect();
    work.sort_by_key(|(s, _)| *s);

    let mut best: Option<(NaiveDateTime, NaiveDateTime, i64)> = None;
    for w in work.windows(2) {
        let (prev_end, next_start) = (w[0].1, w[1].0);
        let gap = next_start.signed_duration_since(prev_end).num_minutes();
        if gap > 0 && best.is_none_or(|(_, _, b)| gap > b) {
            best = Some((prev_end, next_start, gap));
        }
    }

    match best {
        Some((s, e, _)) => (s.format("%H:%M").to_string(), e.format("%H:%M").to_string()),
        None => ("11:30".to_string(), "12:00".to_string()),
    }
}

fn adjust_time_string(time_str: &str, minutes: i32) -> String {
    // Parse the time string
    if let Ok(time) = NaiveTime::parse_from_str(time_str, "%H:%M") {
        // Add/subtract minutes
        let total_minutes = time.hour() as i32 * 60 + time.minute() as i32 + minutes;

        // Handle wrapping (0-1439 minutes in a day)
        let wrapped_minutes = ((total_minutes % 1440) + 1440) % 1440;

        let new_hour = (wrapped_minutes / 60) as u32;
        let new_minute = (wrapped_minutes % 60) as u32;

        format!("{:02}:{:02}", new_hour, new_minute)
    } else {
        // If parsing fails, return original or default
        time_str.to_string()
    }
}