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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
import gradio as gr
import datetime
import json
import os
import calendar
from pathlib import Path
import plotly.graph_objects as go
import plotly.express as px
import numpy as np

# Create data directory if it doesn't exist
DATA_DIR = Path("daily_data")
try:
    DATA_DIR.mkdir(parents=True, exist_ok=True)
except Exception as e:
    print(f"Error creating data directory: {e}")

JOURNAL_QUESTIONS = [
    "What made you happiest today, and why?",
    "What was the biggest challenge you faced today, and how did you approach it?",
    "What's one thing you learned or realized today?",
    "What are you grateful for today?",
    "What emotion did you feel the most today? What triggered it?",
    "What's one moment or interaction that stood out to you?",
    "What progress did you make toward your goals today?",
    "Did you notice any recurring habits or patterns in your day?",
    "How did you support or connect with someone today?",
    "What could you have done differently to improve your day?",
    "What's one thing you want to prioritize or focus on tomorrow?",
    "If today were a chapter in your life story, what would its title be?"
]

def get_date_key():
    """Get current date in YYYY-MM-DD format"""
    return datetime.datetime.now().strftime("%Y-%m-%d")

def save_daily_data(data, date_key=None):
    """Save daily data to JSON file"""
    if date_key is None:
        date_key = get_date_key()
    
    # Ensure data is a dictionary
    if not isinstance(data, dict):
        data = create_empty_daily_data()
    
    # Convert DataFrame to list for JSON serialization
    if "focus" in data:
        if "priorities" in data["focus"]:
            priorities = data["focus"]["priorities"]
            if hasattr(priorities, '__array__') or hasattr(priorities, 'values'):
                data["focus"]["priorities"] = priorities.values.tolist() if hasattr(priorities, 'values') else priorities.tolist()
        if "later" in data["focus"]:
            later = data["focus"]["later"]
            if hasattr(later, '__array__') or hasattr(later, 'values'):
                data["focus"]["later"] = later.values.tolist() if hasattr(later, 'values') else later.tolist()
    
    # Deep merge required fields with existing data
    required_fields = {
        "tracking_metrics": {
            "productivity": 0,
            "energy": 0,
            "mood": 0,
            "sleep_quality": 0,
            "exercise_intensity": 0
        },
        "habits": {},
        "focus": {
            "priorities": [],
            "later": [],
            "priority_reward": "",
            "later_reward": ""
        },
        "meals": {
            "breakfast": "",
            "lunch": "",
            "dinner": "",
            "snacks": ""
        },
        "last_updated": datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    }
    
    for key, default_value in required_fields.items():
        if key not in data:
            data[key] = default_value
        elif isinstance(default_value, dict):
            for subkey, subvalue in default_value.items():
                if subkey not in data[key]:
                    data[key][subkey] = subvalue
    
    file_path = DATA_DIR / f"{date_key}.json"
    
    try:
        # Ensure the directory exists again (in case it was deleted)
        DATA_DIR.mkdir(parents=True, exist_ok=True)
        
        # Write directly to the file first
        with open(file_path, 'w') as f:
            json.dump(data, f, indent=2, sort_keys=True)
            
    except Exception as e:
        print(f"Error saving data: {e}")
        try:
            # Fallback: try to save in the current directory
            with open(f"{date_key}.json", 'w') as f:
                json.dump(data, f, indent=2, sort_keys=True)
            print(f"Saved data to current directory as fallback")
        except Exception as e2:
            print(f"Final save attempt failed: {e2}")

def clean_daily_data_file(date_key):
    """Clean up corrupted JSON file and restore it with valid data"""
    file_path = DATA_DIR / f"{date_key}.json"
    try:
        if file_path.exists():
            with open(file_path, 'r') as f:
                content = f.read().strip()
            
            try:
                # Try to parse the content directly first
                data = json.loads(content)
                return validate_data_structure(data)
            except json.JSONDecodeError:
                # If that fails, try to clean the content
                content = content.rstrip(', \t\n\r')
                last_brace = content.rfind('}')
                if last_brace != -1:
                    content = content[:last_brace + 1]
                    try:
                        data = json.loads(content)
                        data = validate_data_structure(data)
                        # Save the cleaned data
                        save_daily_data(data, date_key)
                        return data
                    except:
                        pass
        
        # If all cleaning attempts fail, create new data
        print(f"Creating new data for {date_key}")
        data = create_empty_daily_data()
        save_daily_data(data, date_key)
        return data
        
    except Exception as e:
        print(f"Error cleaning data file {date_key}: {e}")
        return create_empty_daily_data()

def load_daily_data(date_key=None):
    """Load daily data from JSON file"""
    if date_key is None:
        date_key = get_date_key()
    
    file_path = DATA_DIR / f"{date_key}.json"
    try:
        if file_path.exists():
            try:
                # Try to load and clean the file
                data = clean_json_file(file_path)
                
                # Validate and update the data structure
                data = validate_data_structure(data)
                save_daily_data(data, date_key)
                return data
            except Exception as e:
                print(f"Error loading data: {e}")
                return create_empty_daily_data()
        else:
            # Only create new file if it's today's date
            if date_key == get_date_key():
                data = create_empty_daily_data()
                save_daily_data(data, date_key)
                return data
            else:
                return create_empty_daily_data()
    except Exception as e:
        print(f"Error loading data: {e}")
        return create_empty_daily_data()

def validate_data_structure(data):
    """Validate and update data structure if needed"""
    if not isinstance(data, dict):
        return create_empty_daily_data()
    
    # Create a new data structure with all required fields
    valid_data = create_empty_daily_data()
    
    # Copy existing data while ensuring all required fields exist
    for key, default_value in valid_data.items():
        if key in data:
            if isinstance(default_value, dict):
                valid_data[key] = {**default_value, **data[key]}
            else:
                valid_data[key] = data[key]
    
    return valid_data

def create_empty_daily_data():
    """Create empty data structure for a new day"""
    # Load current habits list
    current_habits = load_habits()
    
    data = {
        "habits": {habit: [False] * 7 for habit in current_habits},
        "focus": {
            "priorities": [
                ["", ""],  # Empty task and status
                ["", ""],
                ["", ""],
                ["", ""],
                ["", ""]
            ],
            "later": [
                ["", ""],  # Empty task and status
                ["", ""],
                ["", ""],
                ["", ""],
                ["", ""]
            ],
            "priority_reward": "",
            "later_reward": ""
        },
        "meals": {
            "breakfast": "",
            "lunch": "",
            "dinner": "",
            "snacks": ""
        },
        "last_updated": datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
        "tracking_metrics": {
            "productivity": 0,
            "energy": 0,
            "mood": 0,
            "sleep_quality": 0,
            "exercise_intensity": 0
        }
    }
    
    # Add journal section with empty entries
    data["journal"] = {
        question: "" for question in JOURNAL_QUESTIONS
    }
    
    return data

def get_week_dates():
    """Get dates for current week"""
    today = datetime.date.today()
    monday = today - datetime.timedelta(days=today.weekday())
    return [(monday + datetime.timedelta(days=i)).strftime("%Y-%m-%d") for i in range(7)]

def get_month_dates():
    """Get dates for current month"""
    today = datetime.date.today()
    _, num_days = calendar.monthrange(today.year, today.month)
    return [(datetime.date(today.year, today.month, day)).strftime("%Y-%m-%d") 
            for day in range(1, num_days + 1)]

def load_week_data():
    """Load data for the current week"""
    week_data = {}
    week_dates = get_week_dates()
    
    for date in week_dates:
        file_path = DATA_DIR / f"{date}.json"
        if file_path.exists():
            try:
                data = load_daily_data(date)
                week_data[date] = data
            except Exception as e:
                print(f"Error loading week data for {date}: {e}")
                week_data[date] = create_empty_daily_data()
        else:
            # Don't create a file, just return empty data structure
            week_data[date] = {
                "tracking_metrics": {
                    "productivity": 0,
                    "energy": 0,
                    "mood": 0,
                    "sleep_quality": 0,
                    "exercise_intensity": 0
                }
            }
    return week_data

def load_month_data():
    """Load data for the current month"""
    month_data = {}
    month_dates = get_month_dates()
    
    for date in month_dates:
        file_path = DATA_DIR / f"{date}.json"
        if file_path.exists():
            try:
                data = load_daily_data(date)
                month_data[date] = data
            except Exception as e:
                print(f"Error loading month data for {date}: {e}")
                month_data[date] = create_empty_daily_data()
        else:
            # Don't create a file, just return empty data structure
            month_data[date] = {
                "tracking_metrics": {
                    "productivity": 0,
                    "energy": 0,
                    "mood": 0,
                    "sleep_quality": 0,
                    "exercise_intensity": 0
                }
            }
    return month_data

def calculate_success_rate(data_dict, metric):
    """Calculate success rate for a given metric"""
    if not data_dict:
        return 0
    total = 0
    count = 0
    for date, data in data_dict.items():
        # Ensure tracking_metrics exists for each data point
        if "tracking_metrics" not in data:
            data["tracking_metrics"] = {
                "productivity": 0,
                "energy": 0,
                "mood": 0,
                "sleep_quality": 0,
                "exercise_intensity": 0
            }
        if metric in data.get("tracking_metrics", {}):
            total += data["tracking_metrics"][metric]
            count += 1
    return round((total / count) if count > 0 else 0, 2)

# Replace the hardcoded HABITS list with a function to load habits
def get_default_habits():
    """Get the default habits list if no custom list exists"""
    return [
        # Morning Routine (Essential)
        "Morning Exercise/Yoga",
        "Meditation (20min)",

        
        # After Work Activities
        "Evening Stretch (20min)",
        "Active Learning (20min)",
        "Journal",

        
        # Flexible Throughout Day
        "Reading (20min)",
        "Take a photo",
        "Future Planning"
    ]

def load_habits():
    """Load the current habits list from the configuration"""
    config_path = Path("habits_config.json")
    if config_path.exists():
        try:
            with open(config_path, 'r') as f:
                data = json.load(f)
                if "habits" in data and isinstance(data["habits"], list):
                    return data["habits"]
                else:
                    # If the file exists but is invalid, create a new one with defaults
                    default_habits = get_default_habits()
                    save_habits(default_habits)
                    return default_habits
        except Exception as e:
            print(f"Error loading habits: {e}")
            # If there's an error reading the file, create a new one with defaults
            default_habits = get_default_habits()
            save_habits(default_habits)
            return default_habits
    else:
        # If the file doesn't exist, create it with defaults
        default_habits = get_default_habits()
        save_habits(default_habits)
        return default_habits

def save_habits(habits_list):
    """Save the current habits list to configuration"""
    config_path = Path("habits_config.json")
    try:
        # Ensure the list is unique and sorted
        habits_list = sorted(list(set(habits_list)))
        
        # Save to config file
        with open(config_path, 'w') as f:
            json.dump({"habits": habits_list}, f, indent=2)
        
        # Also update the current day's data to match
        current_data = load_daily_data()
        new_habits = {habit: [False] * 7 for habit in habits_list}
        
        # Preserve existing habit states
        for habit, states in current_data["habits"].items():
            if habit in new_habits:
                new_habits[habit] = states
        
        current_data["habits"] = new_habits
        save_daily_data(current_data)
        
    except Exception as e:
        print(f"Error saving habits: {e}")

# Remove redundant constants
DEFAULT_SELF_CARE_ITEMS = [
 "Yoga (AM)", "Vitamins", "Outside",
    "Stretch (PM)", "Reading", "Learning", "Journal",
    "Tapping", "Meditate", "Brain Train"
]

def parse_time(time_str):
    """Parse time string in either 12-hour or 24-hour format"""
    try:
        # Try 24-hour format first
        return datetime.datetime.strptime(time_str, "%H:%M").strftime("%H:%M")
    except ValueError:
        try:
            # Try 12-hour format with AM/PM
            return datetime.datetime.strptime(time_str.strip().upper(), "%I:%M %p").strftime("%H:%M")
        except ValueError:
            try:
                # Try 12-hour format without space before AM/PM
                return datetime.datetime.strptime(time_str.strip().upper(), "%I:%M%p").strftime("%H:%M")
            except ValueError:
                return "00:00"  # Default if parsing fails

def calculate_age_stats(birth_date_str, birth_time_str="00:00"):
    """Calculate age-related statistics with precise birth date and time"""
    try:
        # Parse birth date and time
        try:
            birth_time = parse_time(birth_time_str)
        except ValueError:
            return {"Error": "Invalid time format. Please use either HH:MM (24-hour) or HH:MM AM/PM (12-hour)"}
        
        birth_datetime = datetime.datetime.strptime(f"{birth_date_str} {birth_time}", "%Y-%m-%d %H:%M")
        now = datetime.datetime.now()
        
        # Calculate time differences
        time_lived = now - birth_datetime
        age_days = time_lived.days
        age_hours = time_lived.total_seconds() / 3600
        age_minutes = time_lived.total_seconds() / 60
        age_weeks = age_days / 7
        age_months = age_days / 30.44
        age_years = age_days / 365.25
        
        # Calculate time until milestones
        days_until_90 = (datetime.datetime(birth_datetime.year + 90, birth_datetime.month, birth_datetime.day) - now).days
        weeks_until_90 = days_until_90 / 7
        months_until_90 = days_until_90 / 30.44
        years_until_90 = days_until_90 / 365.25
        
        # Calculate percentages and milestones
        percent_lived = (age_years / 90) * 100
        percent_of_year = (now.timetuple().tm_yday / 365.25) * 100
        percent_of_month = (now.day / calendar.monthrange(now.year, now.month)[1]) * 100
        percent_of_week = ((now.weekday() + 1) / 7) * 100
        percent_of_day = ((now.hour * 3600 + now.minute * 60 + now.second) / 86400) * 100
        
        # Calculate next birthday
        next_birthday = datetime.datetime(now.year, birth_datetime.month, birth_datetime.day)
        if next_birthday < now:
            next_birthday = datetime.datetime(now.year + 1, birth_datetime.month, birth_datetime.day)
        days_to_birthday = (next_birthday - now).days
        
        return {
            "Current Age": {
                "Years": f"{age_years:.2f}",
                "Months": f"{age_months:.1f}",
                "Weeks": f"{age_weeks:.1f}",
                "Days": str(age_days),
                "Hours": f"{age_hours:,.0f}",
                "Minutes": f"{age_minutes:,.0f}"
            },
            "Time Until 90": {
                "Years": f"{years_until_90:.1f}",
                "Months": f"{months_until_90:.1f}",
                "Weeks": f"{weeks_until_90:.1f}",
                "Days": str(days_until_90)
            },
            "Life Progress": {
                "Life Percentage": f"{percent_lived:.1f}%",
                "Current Year": f"{percent_of_year:.1f}%",
                "Current Month": f"{percent_of_month:.1f}%",
                "Current Week": f"{percent_of_week:.1f}%",
                "Current Day": f"{percent_of_day:.1f}%"
            },
            "Milestones": {
                "Days to Next Birthday": str(days_to_birthday),
                "Weeks Lived": f"{age_weeks:,.0f}",
                "Days Lived": f"{age_days:,d}",
                "Hours Lived": f"{age_hours:,.0f}",
                "10,000 Days": f"{10000 - (age_days % 10000)} days until next 10k milestone",
                "Life Seasons": f"You are in season {int(age_years/20) + 1} of your life"
            }
        }
    except ValueError as e:
        return {"Error": f"Invalid date or time format. Please use YYYY-MM-DD for date and HH:MM (24-hour) or HH:MM AM/PM (12-hour) for time."}

def update_progress(checkboxes):
    """Calculate progress percentage"""
    completed = sum(1 for x in checkboxes if x)
    total = len(checkboxes)
    return f"{(completed/total)*100:.1f}%" if total > 0 else "0%"

def check_and_refresh_day(current_data):
    """Check if we need to start a new day"""
    # Ensure tracking_metrics exists
    if "tracking_metrics" not in current_data:
        current_data["tracking_metrics"] = {
            "productivity": 0,
            "energy": 0,
            "mood": 0,
            "sleep_quality": 0,
            "exercise_intensity": 0
        }
    
    last_updated = datetime.datetime.strptime(current_data["last_updated"], "%Y-%m-%d %H:%M:%S")
    current_time = datetime.datetime.now()
    
    # If it's a new day (past midnight)
    if last_updated.date() < current_time.date():
        # Save current data with previous date
        previous_date = last_updated.strftime("%Y-%m-%d")
        save_daily_data(current_data, previous_date)
        
        # Create new empty data for today
        current_data = create_empty_daily_data()
        save_daily_data(current_data)
    
    # Always return the current data
    return current_data

def update_data(data_key, value):
    """Update specific data in the daily record"""
    current_data = load_daily_data()
    current_data = check_and_refresh_day(current_data)
    
    # Convert value to list only if it's a DataFrame or numpy array and not a dict
    if not isinstance(value, dict) and (hasattr(value, '__array__') or hasattr(value, 'values')):
        value = value.values.tolist() if hasattr(value, 'values') else value.tolist()
    
    # Update the specified data
    keys = data_key.split('.')
    target = current_data
    
    # Special handling for habits which are stored as lists
    if keys[0] == "habits" and len(keys) == 3:
        habit_name = keys[1]
        day_index = int(keys[2])  # Convert string index to integer
        if habit_name in target["habits"]:
            target["habits"][habit_name][day_index] = value
    else:
        # Normal dictionary path traversal
        for key in keys[:-1]:
            target = target[key]
        target[keys[-1]] = value
    
    current_data["last_updated"] = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    save_daily_data(current_data)
    return current_data

def update_activity(new_name, old_name):
    """Update a self-care activity name and maintain its status"""
    if not new_name.strip() or new_name == old_name:
        return gr.update()
    
    try:
        current_data = load_daily_data()
        
        # Ensure proper data structure
        if "self_care" not in current_data or not isinstance(current_data["self_care"], dict):
            current_data["self_care"] = {
                "items": DEFAULT_SELF_CARE_ITEMS.copy(),
                "status": {item: "Not Done" for item in DEFAULT_SELF_CARE_ITEMS}
            }
        if "items" not in current_data["self_care"]:
            current_data["self_care"]["items"] = list(current_data["self_care"].keys())
            current_data["self_care"]["status"] = current_data["self_care"].copy()
        
        # Update activity in items list
        if old_name in current_data["self_care"]["items"]:
            idx = current_data["self_care"]["items"].index(old_name)
            current_data["self_care"]["items"][idx] = new_name.strip()
            
            # Update status
            if "status" in current_data["self_care"]:
                if old_name in current_data["self_care"]["status"]:
                    current_data["self_care"]["status"][new_name.strip()] = current_data["self_care"]["status"].pop(old_name)
        
        save_daily_data(current_data)
        return gr.update()
    except Exception as e:
        print(f"Error updating activity: {e}")
        return gr.update()

def create_life_visualizations(stats):
    figures = {}
    
    # 1. Life Progress Donut Chart
    progress_data = {k: float(v.strip('%')) for k, v in stats["Life Progress"].items()}
    fig_progress = go.Figure(data=[go.Pie(
        labels=list(progress_data.keys()),
        values=list(progress_data.values()),
        hole=.3,
        marker_colors=px.colors.qualitative.Set3
    )])
    fig_progress.update_layout(title="Life Progress Metrics")
    figures["progress"] = fig_progress
    
    # 2. Time Remaining Bar Chart
    time_until = {k: float(v) for k, v in stats["Time Until 90"].items()}
    fig_remaining = go.Figure(data=[go.Bar(
        x=list(time_until.keys()),
        y=list(time_until.values()),
        marker_color='lightblue'
    )])
    fig_remaining.update_layout(title="Time Until 90")
    figures["remaining"] = fig_remaining
    
    # 3. Life Timeline
    current_year = float(stats["Current Age"]["Years"])
    fig_timeline = go.Figure()
    
    # Add seasons
    seasons = [
        {"name": "Learning & Discovery", "start": 0, "end": 20, "color": "lightgreen"},
        {"name": "Creation & Building", "start": 20, "end": 40, "color": "lightblue"},
        {"name": "Mastery & Leadership", "start": 40, "end": 60, "color": "lightyellow"},
        {"name": "Wisdom & Guidance", "start": 60, "end": 80, "color": "lightpink"},
        {"name": "Legacy & Reflection", "start": 80, "end": 90, "color": "lavender"}
    ]
    
    for season in seasons:
        fig_timeline.add_shape(
            type="rect",
            x0=season["start"],
            x1=season["end"],
            y0=0,
            y1=1,
            fillcolor=season["color"],
            opacity=0.3,
            layer="below",
            line_width=0,
        )
    
    # Add current age marker
    fig_timeline.add_trace(go.Scatter(
        x=[current_year, current_year],
        y=[0, 1],
        mode="lines",
        line=dict(color="red", width=2),
        name="Current Age"
    ))
    
    fig_timeline.update_layout(
        title="Life Seasons Timeline",
        xaxis_title="Age",
        yaxis_showticklabels=False,
        showlegend=True
    )
    figures["timeline"] = fig_timeline
    
    return figures

def update_metrics(prod, en, m, slp, ex, selected_date=None):
    """Update tracking metrics and return updated weekly grid"""
    if selected_date is None:
        selected_date = get_date_key()
    
    # Load data for the selected date
    current_data = load_daily_data(selected_date)
    
    # Update the metrics
    current_data["tracking_metrics"] = {
        "productivity": prod,
        "energy": en,
        "mood": m,
        "sleep_quality": slp,
        "exercise_intensity": ex
    }
    
    # Save the updated data
    save_daily_data(current_data, selected_date)
    
    # Reload week data to get updated grid
    week_data = load_week_data()
    
    # Create updated weekly grid values
    week_dates = get_week_dates()
    grid_values = [
        ["Productivity"] + [week_data[date]["tracking_metrics"]["productivity"] for date in week_dates],
        ["Energy"] + [week_data[date]["tracking_metrics"]["energy"] for date in week_dates],
        ["Mood"] + [week_data[date]["tracking_metrics"]["mood"] for date in week_dates],
        ["Sleep"] + [week_data[date]["tracking_metrics"]["sleep_quality"] for date in week_dates],
        ["Exercise"] + [week_data[date]["tracking_metrics"]["exercise_intensity"] for date in week_dates]
    ]
    
    # Calculate monthly averages
    month_data = load_month_data()
    avg_prod = calculate_success_rate(month_data, "productivity")
    avg_energy = calculate_success_rate(month_data, "energy")
    avg_mood = calculate_success_rate(month_data, "mood")
    avg_sleep = calculate_success_rate(month_data, "sleep_quality")
    avg_exercise = calculate_success_rate(month_data, "exercise_intensity")
    
    return [
        grid_values,  # Weekly grid values
        f"Average Productivity: {avg_prod}/5",
        f"Average Energy: {avg_energy}/5",
        f"Average Mood: {avg_mood}/5",
        f"Average Sleep: {avg_sleep}/5",
        f"Average Exercise: {avg_exercise}/5"
    ]

def update_journal_entry(question, answer):
    """Update a specific journal entry"""
    current_data = load_daily_data()
    
    # Ensure journal section exists
    if "journal" not in current_data:
        current_data["journal"] = {q: "" for q in JOURNAL_QUESTIONS}
    
    # Update the specific question's answer
    current_data["journal"][question] = answer
    
    # Save the updated data
    save_daily_data(current_data)
    return current_data

# Add this function to format the stats display
def create_stats_display(stats):
    # Current Age Section
    current_age = f"""
    ### 🎂 Current Age
    - **Years:** {stats["Current Age"]["Years"]} years
    - **Months:** {stats["Current Age"]["Months"]} months
    - **Weeks:** {stats["Current Age"]["Weeks"]} weeks
    - **Days:** {stats["Current Age"]["Days"]} days
    
    ⏰ You've been alive for:
    - **{stats["Current Age"]["Hours"]}** hours
    - **{stats["Current Age"]["Minutes"]}** minutes
    """
    
    # Time Until 90 Section
    time_remaining = f"""
    ### ⏳ Time Until 90
    - **Years:** {stats["Time Until 90"]["Years"]} years
    - **Months:** {stats["Time Until 90"]["Months"]} months
    - **Weeks:** {stats["Time Until 90"]["Weeks"]} weeks
    - **Days:** {stats["Time Until 90"]["Days"]} days
    """
    
    # Progress Section
    progress = f"""
    ### 📊 Life Progress
    - **Life Journey:** {stats["Life Progress"]["Life Percentage"]} complete
    - **This Year:** {stats["Life Progress"]["Current Year"]} complete
    - **This Month:** {stats["Life Progress"]["Current Month"]} complete
    - **This Week:** {stats["Life Progress"]["Current Week"]} complete
    - **Today:** {stats["Life Progress"]["Current Day"]} complete
    """
    
    # Milestones Section
    milestones = f"""
    ### 🏆 Key Milestones
    - **Next Birthday:** {stats["Milestones"]["Days to Next Birthday"]} days away
    - **Weeks Journey:** {stats["Milestones"]["Weeks Lived"]} weeks lived
    - **Days Journey:** {stats["Milestones"]["Days Lived"]} days experienced
    - **Hours Journey:** {stats["Milestones"]["Hours Lived"]} hours lived
    - **10k Milestone:** {stats["Milestones"]["10,000 Days"]}
    - **Life Season:** {stats["Milestones"]["Life Seasons"]}
    """
    
    return current_age, time_remaining, progress, milestones

# Add this function to format daily data for display
def format_daily_summary(date, data):
    """Format daily data into a summary row for the history table"""
    try:
        metrics = data.get("tracking_metrics", {})
        habits_completed = sum(1 for habit in data.get("habits", {}).values() 
                             for done in habit if done)
        total_habits = len(data.get("habits", {})) * 7
        habits_percent = f"{(habits_completed/total_habits)*100:.1f}%" if total_habits > 0 else "0%"
        
        journal_entries = sum(1 for entry in data.get("journal", {}).values() if entry.strip())
        
        # Format date for display
        display_date = datetime.datetime.strptime(date, "%Y-%m-%d").strftime("%Y-%m-%d (%a)")
        
        return [
            display_date,
            metrics.get("productivity", 0),
            metrics.get("energy", 0),
            metrics.get("mood", 0),
            metrics.get("sleep_quality", 0),
            metrics.get("exercise_intensity", 0),
            habits_percent,
            journal_entries
        ]
    except Exception as e:
        print(f"Error formatting data for {date}: {e}")
        return [date, 0, 0, 0, 0, 0, "0%", 0]

# Add this function to load history data
def load_history_data():
    """Load all available daily data files"""
    history_data = []
    
    # Get all JSON files in the data directory
    json_files = sorted(DATA_DIR.glob("*.json"), reverse=True)  # Sort newest first
    
    for file_path in json_files:
        date = file_path.stem  # Get date from filename
        try:
            with open(file_path, 'r') as f:
                data = json.load(f)
                # Format the data for display
                history_data.append(format_daily_summary(date, data))
        except Exception as e:
            print(f"Error loading {file_path}: {e}")
    
    return history_data

def save_user_config(birth_date, birth_time):
    """Save user configuration data"""
    try:
        # Validate date format
        datetime.datetime.strptime(birth_date, "%Y-%m-%d")
        
        # Convert time to 24-hour format
        formatted_time = parse_time(birth_time)
        
        config = {
            "birth_date": birth_date,
            "birth_time": formatted_time
        }
        
        config_path = Path("user_config.json")
        with open(config_path, "w") as f:
            json.dump(config, f, indent=2)
        
        return True
    except Exception as e:
        print(f"Error saving config: {e}")
        return False

def load_user_config():
    """Load user configuration data"""
    config_path = Path("user_config.json")
    default_config = {
        "birth_date": "",  # Your birth date
        "birth_time": ""        # Your birth time in 24-hour format
    }
    
    if config_path.exists():
        try:
            with open(config_path, "r") as f:
                config = json.load(f)
                # Validate loaded data
                datetime.datetime.strptime(config["birth_date"], "%Y-%m-%d")
                parse_time(config["birth_time"])
                return config
        except Exception as e:
            print(f"Error loading config: {e}")
    
    return default_config

def add_new_habit(habit_name, duration, category):
    """Add a new habit to the tracking system"""
    try:
        if not habit_name.strip():
            return "⚠️ Please enter a habit name", None, None, None
        
        # Format the habit name with duration if provided
        formatted_habit = habit_name.strip()
        if duration:
            formatted_habit = f"{formatted_habit} ({duration})"
        
        # Add category prefix for sorting
        if category == "Morning":
            formatted_habit = f"Morning {formatted_habit}"
        elif category == "Evening":
            formatted_habit = f"Evening {formatted_habit}"
        
        # Load current habits
        current_habits = load_habits()
        
        # Check if habit already exists
        if formatted_habit in current_habits:
            return "⚠️ This habit already exists", None, None, None
        
        # Add new habit to list
        current_habits.append(formatted_habit)
        
        # Save updated habits list
        save_habits(current_habits)
        
        # Return success message and clear inputs
        return "✅ Habit added successfully!", "", "", ""
        
    except Exception as e:
        print(f"Error adding habit: {e}")
        return f"❌ Error adding habit: {str(e)}", None, None, None

def create_habit_section():
    """Create the habit tracking section with better layout"""
    # Load current habits
    current_habits = load_habits()
    
    # Group habits by time of day
    morning_habits = [h for h in current_habits if any(x in h.lower() for x in ["wake", "morning", "meditation", "brain", "walk"])]
    evening_habits = [h for h in current_habits if any(x in h.lower() for x in ["evening", "massage", "learning", "journal", "guitar"])]
    flexible_habits = [h for h in current_habits if h not in morning_habits + evening_habits]
    
    with gr.Column(scale=1):
        gr.Markdown("### 📅 Daily Habits & Tasks")
        
        # Create summary text component first
        with gr.Row():
            gr.Markdown("### 📊 Weekly Summary")
            summary_text = gr.Markdown()
            refresh_btn = gr.Button("🔄 Refresh")
        
        # Add status message component
        status_message = gr.Markdown(visible=False)
        
        # Connect refresh button to update summary
        refresh_btn.click(
            fn=update_summary,
            outputs=summary_text
        )
        
        # Add column headers once at the top
        with gr.Row(equal_height=True, variant="compact"):
            with gr.Column(scale=6):
                gr.Markdown("Task")
            with gr.Column(scale=7):
                with gr.Row(equal_height=True, variant="compact"):
                    days = ["M", "T", "W", "Th", "F", "S", "Su"]
                    for day in days:
                        with gr.Column(scale=1, min_width=35):
                            gr.Markdown(day)
            with gr.Column(scale=3):
                gr.Markdown("Progress")
        
        # Morning Section
        with gr.Group():
            gr.Markdown("#### 🌅 Morning Routine")
            create_habit_group(morning_habits, summary_text)
        
        gr.Markdown("---")
        
        # Evening Section
        with gr.Group():
            gr.Markdown("#### 🌙 Evening Activities")
            create_habit_group(evening_habits, summary_text)
            
        gr.Markdown("---")
        
        # Flexible Section
        with gr.Group():
            gr.Markdown("#### ⭐ Flexible Activities")
            create_habit_group(flexible_habits, summary_text)
        
        gr.Markdown("---")
        
        # Add new habit section
        with gr.Row(equal_height=True):
            new_habit = gr.Textbox(
                label="New Habit/Task",
                placeholder="Enter a new habit or task to track",
                scale=3,
                min_width=200
            )
            category = gr.Dropdown(
                choices=["Morning", "Evening", "Flexible"],
                label="Category",
                value="Flexible",
                scale=2,
                min_width=100
            )
            duration = gr.Dropdown(
                choices=["", "15min", "20min", "30min", "45min", "60min"],
                label="Duration",
                scale=2,
                min_width=100
            )
            add_btn = gr.Button("Add Habit", scale=1, min_width=100)
        
        # Add status message component
        status_message = gr.Markdown(visible=False)
        
        def add_and_refresh(habit_name, category, duration):
            message, _, _, _ = add_new_habit(habit_name, duration, category)
            
            # Reload habits and recreate sections
            current_habits = load_habits()
            morning_habits = [h for h in current_habits if any(x in h.lower() for x in ["wake", "morning", "meditation", "brain", "walk"])]
            evening_habits = [h for h in current_habits if any(x in h.lower() for x in ["evening", "massage", "learning", "journal", "guitar"])]
            flexible_habits = [h for h in current_habits if h not in morning_habits + evening_habits]
            
            # Update summary
            summary = update_summary()
            
            # Create updated habit groups
            create_habit_group(morning_habits, summary_text)
            create_habit_group(evening_habits, summary_text)
            create_habit_group(flexible_habits, summary_text)
            
            return [
                message,                    # Status message
                "",                        # Clear habit input
                category,                  # Keep category selection
                "",                        # Clear duration input
                gr.update(visible=True),   # Show status message
                gr.update(value=summary)   # Update summary text
            ]
        
        # Connect the add button event
        add_btn.click(
            fn=add_and_refresh,
            inputs=[new_habit, category, duration],
            outputs=[
                status_message,
                new_habit,
                category,
                duration,
                status_message,
                summary_text
            ]
        )
        
        # Create a refresh button that will be clicked programmatically
        refresh_habits_btn = gr.Button("Refresh", visible=False)
        
        def add_and_refresh(habit_name, duration):
            message, _, _ = add_new_habit(habit_name, duration)
            return [
                message,                    # Status message
                "",                        # Clear habit input
                "",                        # Clear duration input
                gr.update(visible=True),    # Show status message
                True                        # Trigger refresh button
            ]
        
        # Connect the add button event
        add_btn.click(
            fn=add_and_refresh,
            inputs=[new_habit, duration],
            outputs=[
                status_message,
                new_habit,
                duration,
                status_message,
                refresh_habits_btn
            ]
        )
        
        # Connect refresh button to reload habits
        def reload_habits():
            current_habits = load_habits()
            morning_habits = [h for h in current_habits if any(x in h.lower() for x in ["wake", "morning", "meditation", "brain", "walk"])]
            evening_habits = [h for h in current_habits if any(x in h.lower() for x in ["evening", "massage", "learning", "journal", "guitar"])]
            flexible_habits = [h for h in current_habits if h not in morning_habits + evening_habits]
            
            return [
                gr.update(value=update_summary()),  # Update summary
                gr.update(visible=False)            # Hide status message
            ]
        
        refresh_habits_btn.click(
            fn=reload_habits,
            outputs=[
                summary_text,
                status_message
            ]
        )

def create_habit_group(habits, summary_text):
    """Create a group of habit tracking rows with better scaling"""
    for habit in habits:
        with gr.Row(equal_height=True, variant="compact") as row:
            # Task name and duration (left side)
            with gr.Column(scale=6, min_width=300):
                name_edit = gr.Textbox(
                    value=habit,
                    label="Task Name",
                    interactive=True,
                    container=False,
                )
                
                # Duration slider (optional, shown inline)
                duration_edit = None
                if any(x in habit.lower() for x in ["min", "hour"]):
                    duration_edit = gr.Slider(
                        minimum=5,
                        maximum=60,
                        value=int(''.join(filter(str.isdigit, habit))) if any(c.isdigit() for c in habit) else 20,
                        step=5,
                        label="Duration",
                        container=False,
                        scale=1
                    )
            
            # Checkboxes container (middle)
            with gr.Column(scale=7, min_width=350):
                with gr.Row(equal_height=True, variant="compact"):
                    days = ["M", "T", "W", "Th", "F", "S", "Su"]
                    checkboxes = []
                    for day in days:
                        with gr.Column(scale=1, min_width=30):
                            checkbox = gr.Checkbox(
                                label=day,
                                container=False,
                                scale=1,
                                min_width=25,
                                show_label=False
                            )
                            gr.Markdown(day, container=False)
                            checkboxes.append(checkbox)
            
            # Progress and actions (right side)
            with gr.Column(scale=3, min_width=150):
                with gr.Row(equal_height=True, variant="compact"):
                    progress = gr.Textbox(
                        value="0%",
                        label="Progress",
                        interactive=False,
                        container=False,
                        scale=2
                    )
                    edit_btn = gr.Button("✏️", scale=1, min_width=30)
                    delete_btn = gr.Button("🗑️", scale=1, min_width=30)
            
            # Connect edit button handler
            def edit_habit(name, duration=None):
                if duration is not None:
                    result = update_habit_name(habit, name, duration)
                    gr.Info(f"Updated: {name}")
                    return result
                result = update_habit_name(habit, name)
                gr.Info(f"Updated: {name}")
                return result
            
            edit_btn.click(
                fn=edit_habit,
                inputs=[name_edit] + ([duration_edit] if duration_edit else []),
                outputs=[name_edit]
            )
            
            # Connect delete button handler
            def delete_habit_fn(habit_name=habit):
                """Delete a habit and update the UI"""
                try:
                    # 1. Delete from habits_config.json first
                    config_path = Path("habits_config.json")
                    if config_path.exists():
                        with open(config_path, 'r') as f:
                            config_data = json.load(f)
                        if "habits" in config_data:
                            if habit_name in config_data["habits"]:
                                config_data["habits"].remove(habit_name)
                                with open(config_path, 'w') as f:
                                    json.dump(config_data, f, indent=2)
                                print(f"Removed {habit_name} from habits_config.json")

                    # 2. Update current daily data
                    current_data = load_daily_data()
                    if "habits" in current_data and habit_name in current_data["habits"]:
                        del current_data["habits"][habit_name]
                        save_daily_data(current_data)
                        print(f"Removed {habit_name} from current daily data")

                    # 3. Clean up historical data
                    json_files = list(DATA_DIR.glob("*.json"))
                    for file_path in json_files:
                        try:
                            with open(file_path, 'r') as f:
                                day_data = json.load(f)
                            if "habits" in day_data and habit_name in day_data["habits"]:
                                del day_data["habits"][habit_name]
                                with open(file_path, 'w') as f:
                                    json.dump(day_data, f, indent=2)
                                print(f"Removed {habit_name} from {file_path}")
                        except Exception as e:
                            print(f"Error updating file {file_path}: {e}")

                    # Show success notification
                    gr.Info(f"Deleted: {habit_name}")
                    
                    # Force reload habits from config
                    load_habits()  # Reload habits to ensure sync
                    
                    # Hide the row in UI
                    return gr.update(visible=False)
                
                except Exception as e:
                    print(f"Error deleting habit: {e}")
                    gr.Warning(f"Failed to delete {habit_name}")
                    return gr.update()
            
            # Connect delete button with proper output
            delete_btn.click(
                fn=delete_habit_fn,
                outputs=row
            )
            
            # Update progress when checkboxes change
            def make_progress_handler(current_habit):
                """Create a closure for the progress handler to capture the habit name"""
                def update_progress_display(*checkbox_values):
                    """Update progress display for a habit"""
                    completed = sum(1 for x in checkbox_values if x)
                    total = len(checkbox_values)
                    percentage = f"{(completed/total)*100:.1f}%" if total > 0 else "0%"
                    
                    # Update the data
                    current_data = load_daily_data()
                    if current_habit in current_data["habits"]:
                        current_data["habits"][current_habit] = list(checkbox_values)
                        save_daily_data(current_data)
                    
                    return percentage
                return update_progress_display
            
            # Connect checkbox handlers using closure
            progress_handler = make_progress_handler(habit)
            for checkbox in checkboxes:
                checkbox.change(
                    fn=progress_handler,
                    inputs=checkboxes,
                    outputs=progress
                )

def update_habit_name(old_name, new_name, duration=None):
    """Update habit name and optionally duration"""
    if not new_name.strip():
        return gr.update()
    
    try:
        # Format new name
        new_full_name = new_name.strip()
        if duration is not None:
            new_full_name = f"{new_full_name} ({int(duration)}min)"
        
        # Update habits configuration
        current_habits = load_habits()
        if old_name in current_habits:
            current_habits.remove(old_name)
            current_habits.append(new_full_name)
            save_habits(current_habits)
        
        # Update all daily files
        update_all_daily_files(habit_to_rename=old_name, new_name=new_full_name)
        
        # Return update for the textbox
        return gr.update(value=new_full_name)
    except Exception as e:
        print(f"Error updating habit name: {e}")
        gr.Warning(f"Failed to update {old_name}")
        return gr.update()

def update_summary():
    """Update the weekly summary text"""
    current_data = load_daily_data()
    total_habits = len(current_data["habits"])
    total_completed = sum(
        sum(1 for x in habit_data if x)
        for habit_data in current_data["habits"].values()
    )
    total_possible = total_habits * 7
    completion_rate = (total_completed / total_possible * 100) if total_possible > 0 else 0
    
    return f"""
    - Total Habits: {total_habits}
    - Completed Tasks: {total_completed}/{total_possible}
    - Overall Completion Rate: {completion_rate:.1f}%
    """

def auto_refresh():
    """Auto refresh function to check and refresh day data"""
    try:
        current_data = load_daily_data()
        current_data = check_and_refresh_day(current_data)
        save_daily_data(current_data)
        # Don't return anything
    except Exception as e:
        print(f"Error in auto refresh: {e}")

def update_all_daily_files(habit_to_remove=None, habit_to_rename=None, new_name=None):
    """Update all daily data files when habits are modified"""
    try:
        # Get all JSON files in the data directory
        json_files = list(DATA_DIR.glob("*.json"))
        
        for file_path in json_files:
            try:
                # Load the file
                with open(file_path, 'r') as f:
                    data = json.load(f)
                
                modified = False
                
                # Handle habit removal
                if habit_to_remove and habit_to_remove in data.get("habits", {}):
                    del data["habits"][habit_to_remove]
                    modified = True
                
                # Handle habit renaming
                if habit_to_rename and new_name and habit_to_rename in data.get("habits", {}):
                    data["habits"][new_name] = data["habits"].pop(habit_to_rename)
                    modified = True
                
                # Save if modified
                if modified:
                    with open(file_path, 'w') as f:
                        json.dump(data, f, indent=2, sort_keys=True)
                        
            except Exception as e:
                print(f"Error updating file {file_path}: {e}")
                continue
    except Exception as e:
        print(f"Error updating daily files: {e}")

def get_available_dates():
    """Get list of dates with existing data files"""
    try:
        json_files = sorted(DATA_DIR.glob("*.json"), reverse=True)  # Most recent first
        dates = [file.stem for file in json_files]  # Get dates from filenames
        return dates
    except Exception as e:
        print(f"Error getting available dates: {e}")
        return [get_date_key()]  # Return today's date as fallback

def refresh_dates():
    """Refresh the available dates in the dropdown"""
    dates = get_available_dates()
    return gr.update(choices=dates)

def load_selected_date_metrics(date):
    """Load metrics for the selected date"""
    data = load_daily_data(date)
    metrics = data.get("tracking_metrics", {
        "productivity": 0,
        "energy": 0,
        "mood": 0,
        "sleep_quality": 0,
        "exercise_intensity": 0
    })
    
    return [
        metrics["productivity"],
        metrics["energy"],
        metrics["mood"],
        metrics["sleep_quality"],
        metrics["exercise_intensity"]
    ]

def load_day_details(evt: gr.SelectData):
    """Load detailed view of a specific day"""
    try:
        # Get clicked date (remove the day of week if present)
        date = evt.value[0].split(" (")[0] if isinstance(evt.value, list) else evt.value
        
        data = load_daily_data(date)
        
        # Ensure required data structures exist with defaults
        if "focus" not in data:
            data["focus"] = {
                "priorities": [],
                "later": [],
                "priority_reward": "",
                "later_reward": ""
            }
        
        if "meals" not in data:
            data["meals"] = {
                "breakfast": "",
                "lunch": "",
                "dinner": "",
                "snacks": ""
            }
        
        # Ensure focus lists exist and are properly formatted
        if not isinstance(data["focus"].get("priorities", []), list):
            data["focus"]["priorities"] = []
        if not isinstance(data["focus"].get("later", []), list):
            data["focus"]["later"] = []
        
        # Format metrics data
        metrics_data = [
            ["Productivity", data.get("tracking_metrics", {}).get("productivity", 0)],
            ["Energy", data.get("tracking_metrics", {}).get("energy", 0)],
            ["Mood", data.get("tracking_metrics", {}).get("mood", 0)],
            ["Sleep Quality", data.get("tracking_metrics", {}).get("sleep_quality", 0)],
            ["Exercise Intensity", data.get("tracking_metrics", {}).get("exercise_intensity", 0)]
        ]
        
        # Format habits data with proper validation
        habits_data = []
        habits_dict = data.get("habits", {})
        
        # Load current habits configuration to ensure we show all configured habits
        current_habits = load_habits()
        
        # Create a row for each habit, using stored data if available or default values if not
        for habit in current_habits:
            status = habits_dict.get(habit, [False] * 7)
            # Ensure status is a list of 7 boolean values
            if not isinstance(status, list) or len(status) != 7:
                status = [False] * 7
            row = [habit]
            row.extend(["✓" if done else "×" for done in status])
            habits_data.append(row)
        
        # Sort habits by category (morning, evening, flexible)
        def get_habit_category(habit):
            if any(x in habit.lower() for x in ["wake", "morning", "meditation", "brain", "walk"]):
                return 0  # Morning
            elif any(x in habit.lower() for x in ["evening", "massage", "learning", "journal", "guitar"]):
                return 1  # Evening
            return 2  # Flexible
        
        habits_data.sort(key=lambda x: get_habit_category(x[0]))

        # Format journal data with validation
        journal_data = []
        for q, a in data.get("journal", {}).items():
            if isinstance(a, str):
                if a.strip():
                    journal_data.append([q, a])
        
        # Format focus and meals data with proper validation
        priorities_text = "\n".join([
            f"- {task[0]}: {task[1]}" if isinstance(task, list) and len(task) >= 2 else "- No task"
            for task in data["focus"]["priorities"]
            if isinstance(task, list) and len(task) >= 2 and task[0]
        ]) or "No priorities set"
        
        later_text = "\n".join([
            f"- {task[0]}: {task[1]}" if isinstance(task, list) and len(task) >= 2 else "- No task"
            for task in data["focus"]["later"]
            if isinstance(task, list) and len(task) >= 2 and task[0]
        ]) or "No tasks set"
        
        focus_meals = f"""### 🎯 Focus Tasks

**Must Do Today:**
{priorities_text}

**For Later:**
{later_text}

### 🍽️ Meals
- **Breakfast:** {data["meals"].get("breakfast", "") or "Not recorded"}
- **Lunch:** {data["meals"].get("lunch", "") or "Not recorded"}
- **Dinner:** {data["meals"].get("dinner", "") or "Not recorded"}
- **Snacks:** {data["meals"].get("snacks", "") or "Not recorded"}
"""
        
        return [
            date,  # Selected date
            metrics_data,  # Metrics view
            habits_data,  # Habits view
            journal_data,  # Journal view
            focus_meals  # Focus and meals view
        ]
    except Exception as e:
        print(f"Error loading details for date {date if 'date' in locals() else 'unknown'}: {str(e)}")
        # Return a graceful fallback with empty/default values
        return [
            evt.value,
            [["No metrics data available", 0]],
            [["No habits data available", "×", "×", "×", "×", "×", "×", "×"]],
            [["No journal entries available", ""]],
            """### 🎯 Focus Tasks\n\n**Must Do Today:**\nNo data available\n\n**For Later:**\nNo data available\n\n### 🍽️ Meals\nNo meal data available"""
        ]

def manual_save():
    """Manually save all current data"""
    try:
        current_data = load_daily_data()
        save_daily_data(current_data)
        return "✅ Data saved successfully!"
    except Exception as e:
        print(f"Error saving data: {e}")
        return "❌ Error saving data"

def clean_json_file(file_path):
    """Clean up potentially corrupted JSON file"""
    try:
        with open(file_path, 'r') as f:
            content = f.read().strip()
            
        # Try to find the last valid JSON structure
        try:
            # First try to parse as-is
            data = json.loads(content)
            return data
        except json.JSONDecodeError:
            # If that fails, try to clean up the content
            # Find the last closing brace
            last_brace = content.rfind('}')
            if last_brace != -1:
                content = content[:last_brace + 1]
                try:
                    data = json.loads(content)
                    # Save the cleaned data back to file
                    with open(file_path, 'w') as f:
                        json.dump(data, f, indent=2)
                    return data
                except json.JSONDecodeError:
                    pass
            
            # If all cleanup attempts fail, create new data
            data = create_empty_daily_data()
            with open(file_path, 'w') as f:
                json.dump(data, f, indent=2)
            return data
            
    except Exception as e:
        print(f"Error cleaning JSON file {file_path}: {e}")
        return create_empty_daily_data()

with gr.Blocks() as demo:
    # Load initial data
    current_data = load_daily_data()
    current_data = check_and_refresh_day(current_data)

    
    # Centered, smaller logo
    with gr.Row():
        with gr.Column(scale=2):
            pass  # Empty column for spacing
        with gr.Column(scale=1):
            gr.Image("./logo.png", show_label=False, container=False, width=250, show_download_button=False, )
        with gr.Column(scale=2):
            pass  # Empty column for spacing
    
    with gr.Row():
        date_text = gr.Textbox(
            value=datetime.datetime.now().strftime("%A, %B %d"),
            label="Date",
            interactive=False
        )
        date_picker = gr.Dropdown(
            choices=get_available_dates(),
            value=get_date_key(),
            label="Select Date",
            interactive=True
        )
        today_btn = gr.Button("Return to Today")
        refresh_dates_btn = gr.Button("🔄 Refresh Dates")
        save_btn = gr.Button("💾 Save Data", variant="primary")
        save_status = gr.Markdown(visible=True)
    
    # Connect save button event
    save_btn.click(
        fn=manual_save,
        outputs=save_status
    ).then(
        lambda: gr.update(visible=True),
        None,
        save_status
    )

    # Create state for all components that need updating
    with gr.Tabs():
        # Must Do Daily Tab
        with gr.TabItem("Must Do Daily"):
            create_habit_section()

        # Today's Focus Tab
        with gr.TabItem("Today's Focus"):
            with gr.Column():
                gr.Markdown("### Today's Focus")
                with gr.Row():
                    # Left column for priorities
                    with gr.Column(scale=2):
                        gr.Markdown("#### Must Do Today")
                        priorities = gr.Dataframe(
                            headers=["Task", "Status"],
                            datatype=["str", "str"],
                            value=current_data["focus"]["priorities"],
                            row_count=5,  # Fixed number of rows
                            col_count=(2, "fixed"),  # Fixed number of columns
                            interactive=True
                        )
                        priority_reward = gr.Textbox(
                            label="Reward for Completion",
                            value=current_data["focus"]["priority_reward"],
                            placeholder="Enter reward for completing priorities",
                            lines=2
                        )
                    
                    # Right column for later tasks
                    with gr.Column(scale=2):
                        gr.Markdown("#### For Later")
                        later = gr.Dataframe(
                            headers=["Task", "Status"],
                            datatype=["str", "str"],
                            value=current_data["focus"]["later"],
                            row_count=5,  # Fixed number of rows
                            col_count=(2, "fixed"),  # Fixed number of columns
                            interactive=True
                        )
                        later_reward = gr.Textbox(
                            label="Reward for Completion",
                            value=current_data["focus"]["later_reward"],
                            placeholder="Enter reward for completing later tasks",
                            lines=2
                        )
                
                # Event handlers
                priorities.change(
                    lambda x: update_data("focus.priorities", x),
                    inputs=[priorities]
                )
                priority_reward.change(
                    lambda x: update_data("focus.priority_reward", x),
                    inputs=[priority_reward]
                )
                later.change(
                    lambda x: update_data("focus.later", x),
                    inputs=[later]
                )
                later_reward.change(
                    lambda x: update_data("focus.later_reward", x),
                    inputs=[later_reward]
                )

        # Meals Tab
        with gr.TabItem("Meals"):
            with gr.Column():
                meal_inputs = {}
                for meal in ["breakfast", "lunch", "dinner", "snacks"]:
                    meal_inputs[meal] = gr.Textbox(
                        label=meal.capitalize(),
                        value=current_data["meals"][meal],
                        placeholder=f"What did you have for {meal}?"
                    )
                    meal_inputs[meal].change(
                        lambda x, m=meal: update_data(f"meals.{m}", x),
                        inputs=[meal_inputs[meal]]
                    )
        
        # Life Overview Tab
        with gr.TabItem("Life Overview"):
            with gr.Column():
                gr.Markdown("""
                ### 🌟 Your Life Journey Calculator
                
                Time is our most precious resource - not because it's limited, but because it's an opportunity for endless possibilities. 
                Let's explore your unique journey through time and discover the incredible potential that lies ahead.
                """)
                
                # Load saved config
                user_config = load_user_config()
                
                with gr.Row():
                    birth_date = gr.Textbox(
                        label="Your Birth Date (YYYY-MM-DD)",
                        value=user_config["birth_date"],
                        placeholder="YYYY-MM-DD"
                    )
                    birth_time = gr.Textbox(
                        label="Your Birth Time",
                        value=user_config["birth_time"],
                        placeholder="HH:MM (24-hour) or HH:MM AM/PM"
                    )
                    calculate_btn = gr.Button("✨ Calculate Your Life Journey", variant="primary")
                
                # Add status message
                status_msg = gr.Markdown()
                
                with gr.Tabs():
                    with gr.TabItem("Life Stats"):
                        with gr.Row():
                            current_age_md = gr.Markdown()
                            time_remaining_md = gr.Markdown()
                        with gr.Row():
                            progress_md = gr.Markdown()
                            milestones_md = gr.Markdown()
                            
                    with gr.TabItem("Visualizations"):
                        with gr.Row():
                            progress_plot = gr.Plot(label="Life Progress")
                            remaining_plot = gr.Plot(label="Time Until 90")
                        timeline_plot = gr.Plot(label="Life Seasons Timeline")

                # Update the calculate button click handler
                def update_stats_and_plots(birth_date_str, birth_time_str):
                    try:
                        # Save the values
                        if save_user_config(birth_date_str, birth_time_str):
                            stats = calculate_age_stats(birth_date_str, birth_time_str)
                            if "Error" in stats:
                                return [
                                    f"⚠️ {stats['Error']}", "", "", "", None, None, None
                                ]
                            
                            figures = create_life_visualizations(stats)
                            current_age, time_remaining, progress, milestones = create_stats_display(stats)
                            return [
                                current_age,
                                time_remaining,
                                progress,
                                milestones,
                                figures["progress"],
                                figures["remaining"],
                                figures["timeline"]
                            ]
                        else:
                            return ["⚠️ Failed to save configuration", "", "", "", None, None, None]
                    except Exception as e:
                        return [f"⚠️ Error: {str(e)}", "", "", "", None, None, None]
            
            calculate_btn.click(
                    fn=update_stats_and_plots,
                inputs=[birth_date, birth_time],
                    outputs=[
                        current_age_md,
                        time_remaining_md,
                        progress_md,
                        milestones_md,
                        progress_plot,
                        remaining_plot,
                        timeline_plot
                    ]
            )

        # Progress Tracking Tab
        with gr.TabItem("Progress Tracking"):
            with gr.Column():
                gr.Markdown("### Daily Metrics")
                with gr.Row():
                    # Load data for the selected date
                    selected_data = load_daily_data(date_picker.value)
                    
                    if "tracking_metrics" not in selected_data:
                        selected_data["tracking_metrics"] = {
                            "productivity": 0,
                            "energy": 0,
                            "mood": 0,
                            "sleep_quality": 0,
                            "exercise_intensity": 0
                        }
                    
                    productivity = gr.Slider(minimum=0, maximum=5, value=selected_data["tracking_metrics"]["productivity"], label="Productivity", step=1)
                    energy = gr.Slider(minimum=0, maximum=5, value=selected_data["tracking_metrics"]["energy"], label="Energy Level", step=1)
                    mood = gr.Slider(minimum=0, maximum=5, value=selected_data["tracking_metrics"]["mood"], label="Mood", step=1)
                    sleep = gr.Slider(minimum=0, maximum=5, value=selected_data["tracking_metrics"]["sleep_quality"], label="Sleep Quality", step=1)
                    exercise = gr.Slider(minimum=0, maximum=5, value=selected_data["tracking_metrics"]["exercise_intensity"], label="Exercise Intensity", step=1)

                gr.Markdown("### Weekly Overview")
                week_data = load_week_data()
                week_dates = get_week_dates()
                weekly_grid = gr.DataFrame(
                    headers=["Metric"] + [datetime.datetime.strptime(date, "%Y-%m-%d").strftime("%a %d") for date in week_dates],
                    value=[
                        ["Productivity"] + [week_data[date]["tracking_metrics"]["productivity"] for date in week_dates],
                        ["Energy"] + [week_data[date]["tracking_metrics"]["energy"] for date in week_dates],
                        ["Mood"] + [week_data[date]["tracking_metrics"]["mood"] for date in week_dates],
                        ["Sleep"] + [week_data[date]["tracking_metrics"]["sleep_quality"] for date in week_dates],
                        ["Exercise"] + [week_data[date]["tracking_metrics"]["exercise_intensity"] for date in week_dates]
                    ],
                    interactive=False
                )

                gr.Markdown("### Monthly Stats")
                month_data = load_month_data()
                with gr.Row():
                    prod_label = gr.Label(f"Average Productivity: {calculate_success_rate(month_data, 'productivity')}/10")
                    energy_label = gr.Label(f"Average Energy: {calculate_success_rate(month_data, 'energy')}/10")
                    mood_label = gr.Label(f"Average Mood: {calculate_success_rate(month_data, 'mood')}/10")
                    sleep_label = gr.Label(f"Average Sleep: {calculate_success_rate(month_data, 'sleep_quality')}/10")
                    exercise_label = gr.Label(f"Average Exercise: {calculate_success_rate(month_data, 'exercise_intensity')}/10")

                # Update tracking metrics and connect to UI elements
                for slider in [productivity, energy, mood, sleep, exercise]:
                    slider.change(
                        fn=update_metrics,
                        inputs=[productivity, energy, mood, sleep, exercise, date_picker],
                        outputs=[
                            weekly_grid,
                            prod_label,
                            energy_label,
                            mood_label,
                            sleep_label,
                            exercise_label
                        ]
                    )

        # Journaling Tab
        with gr.TabItem("Daily Journal"):
            with gr.Column():
                gr.Markdown("""
                ### 📝 Daily Reflection Journal
                
                Take a moment to reflect on your day. These questions will help you process your experiences,
                learn from them, and plan for tomorrow. Your responses are saved automatically.
                """)
                
                # Create journal entries
                journal_inputs = {}
                current_journal = current_data.get("journal", {})
                
                for question in JOURNAL_QUESTIONS:
                    with gr.Group():
                        gr.Markdown(f"#### {question}")
                        journal_inputs[question] = gr.TextArea(
                            value=current_journal.get(question, ""),
                            placeholder="Write your thoughts here...",
                            lines=3,
                            label=""
                        )
                        
                        # Add change handler for each text area
                        journal_inputs[question].change(
                            fn=update_journal_entry,
                            inputs=[
                                gr.State(question),
                                journal_inputs[question]
                            ]
                        )
                
                # Add export button
                def export_journal():
                    current_data = load_daily_data()
                    if "journal" in current_data:
                        date = get_date_key()
                        export_text = f"Journal Entry for {date}\n\n"
                        
                        for question in JOURNAL_QUESTIONS:
                            answer = current_data["journal"].get(question, "")
                            if answer:  # Only include questions with answers
                                export_text += f"Q: {question}\n"
                                export_text += f"A: {answer}\n\n"
                        
                        return export_text
                    return "No journal entries found for today."
                
                with gr.Row():
                    export_btn = gr.Button("Export Journal Entry")
                    export_text = gr.TextArea(
                        label="Exported Journal",
                        interactive=False,
                        visible=False
                    )
                
                export_btn.click(
                    fn=export_journal,
                    outputs=export_text,
                    show_progress=True
                ).then(
                    lambda: gr.update(visible=True),
                    None,
                    [export_text]
                )

        # History Tab
        with gr.TabItem("History"):
            with gr.Column():
                gr.Markdown("### 📚 History Viewer")
                
                # Create the history table
                history_headers = [
                    "Date",
                    "Productivity",
                    "Energy",
                    "Mood",
                    "Sleep",
                    "Exercise",
                    "Habits",
                    "Journal"
                ]
                
                with gr.Row():
                    history_table = gr.DataFrame(
                        headers=history_headers,
                        datatype=["str", "number", "number", "number", "number", "number", "str", "number"],
                        value=load_history_data(),
                        interactive=False
                    )
                
                # Create detail view sections
                with gr.Row():
                    selected_date = gr.Textbox(label="Selected Date", interactive=False)
                    refresh_btn = gr.Button("🔄 Refresh History")
                
                with gr.Tabs() as detail_tabs:
                    with gr.TabItem("Metrics"):
                        metrics_view = gr.DataFrame(
                            headers=["Metric", "Value"],
                            datatype=["str", "number"],
                            interactive=False
                        )
                    
                    with gr.TabItem("Habits"):
                        gr.Markdown("### Daily Habits Tracking")
                        habits_view = gr.DataFrame(
                            headers=["Habit", "M", "T", "W", "Th", "F", "S", "Su"],
                            datatype=["str", "str", "str", "str", "str", "str", "str", "str"],
                            interactive=False,
                            value=[[habit] + ["×"] * 7 for habit in load_habits()]  # Initialize with default values
                        )
                    
                    with gr.TabItem("Journal"):
                        journal_view = gr.DataFrame(
                            headers=["Question", "Response"],
                            datatype=["str", "str"],
                            interactive=False
                        )
                    
                    with gr.TabItem("Focus & Meals"):
                        focus_meals_md = gr.Markdown()
                
                # Connect event handlers
                history_table.select(
                    fn=load_day_details,
                    outputs=[
                        selected_date,
                        metrics_view,
                        habits_view,
                        journal_view,
                        focus_meals_md
                    ]
                )
                
                refresh_btn.click(
                    fn=load_history_data,
                    outputs=[history_table]
                )

        # Documentation Tab
        with gr.TabItem("Documentation"):
            with gr.Column():
                gr.Markdown("""
                # Potential Made Simple System Documentation

                ## Overview
                Welcome to your Life Tracking System, inspired by Rob Dyrdek's "Rhythm of Existence" philosophy. This comprehensive app helps you monitor and optimize various aspects of your life, creating a harmonious balance between work, health, personal life, and sleep.

                ## Philosophy
                The "Rhythm of Existence" philosophy, pioneered by entrepreneur Rob Dyrdek, emphasizes the importance of creating intentional, balanced routines that maximize both productivity and life satisfaction. Key principles include:

                - **Intentional Living**: Every day is an opportunity to make progress towards your goals
                - **Balance**: Maintaining equilibrium between work, health, relationships, and personal growth
                - **Consistency**: Building sustainable habits that compound over time
                - **Measurement**: What gets measured gets improved
                - **Reflection**: Regular review and adjustment of life patterns

                ## Features

                ### 1. Must Do Daily
                - Track daily habits and routines
                - Organize tasks into morning, evening, and flexible time slots
                - Monitor weekly progress and completion rates
                - Set custom durations for time-based activities

                ### 2. Today's Focus
                - Prioritize tasks with "Must Do Today" and "For Later" lists
                - Set rewards for completing priority tasks
                - Track task status and progress
                - Maintain clarity on daily objectives

                ### 3. Meals
                - Log daily meals and snacks
                - Monitor eating patterns
                - Track nutritional consistency

                ### 4. Life Overview
                - Calculate and visualize your life journey
                - Track progress through different life seasons
                - Set and monitor life milestones
                - Understand time allocation and remaining potential

                ### 5. Progress Tracking
                - Monitor daily metrics:
                  - Productivity (0-5)
                  - Energy Level (0-5)
                  - Mood (0-5)
                  - Sleep Quality (0-5)
                  - Exercise Intensity (0-5)
                - View weekly and monthly trends
                - Track success rates and improvements

                ### 6. Daily Journal
                - Reflect on daily experiences
                - Answer guided questions for deeper insight
                - Export journal entries for review
                - Build self-awareness through consistent reflection

                ### 7. History
                - Review past data and trends
                - Analyze patterns in habits and metrics
                - Track long-term progress
                - Learn from historical patterns

                ## Best Practices

                1. **Morning Routine**
                   - Start with mindfulness and exercise
                   - Review daily priorities
                   - Set intentions for the day

                2. **Throughout the Day**
                   - Update task status regularly
                   - Log meals as they happen
                   - Track metrics while they're fresh

                3. **Evening Routine**
                   - Complete journal entries
                   - Review task completion
                   - Plan for tomorrow

                4. **Weekly Review**
                   - Analyze progress trends
                   - Adjust habits as needed
                   - Set new goals and rewards

                ## Tips for Success

                1. **Start Small**
                   - Begin with a few key habits
                   - Gradually add more as you build consistency
                   - Focus on progress, not perfection

                2. **Be Consistent**
                   - Log data daily
                   - Complete journal entries regularly
                   - Track metrics consistently

                3. **Review and Adjust**
                   - Use the History tab to spot patterns
                   - Adjust goals based on progress
                   - Celebrate improvements

                4. **Stay Motivated**
                   - Set meaningful rewards
                   - Track progress visually
                   - Share achievements with others

                ## Technical Notes

                - Data is saved automatically
                - Manual save option available
                - Export functionality for journal entries
                - Daily refresh at midnight
                - Ability to view and edit past dates

                ## Support and Feedback

                This is a free tool designed to help you optimize your life and create your own perfect rhythm of existence. As you use the app, remember that the goal is progress, not perfection. Every small improvement compounds over time to create significant life changes.

                For support or to share feedback, please visit the project's repository or contact the development team.

                Happy tracking! 🌟
                """)

    # Date selection handlers
    def load_selected_date(date):
        try:
            # Validate date format
            datetime.datetime.strptime(date, "%Y-%m-%d")
            data = load_daily_data(date)
            
            # Update display date
            display_date = datetime.datetime.strptime(date, "%Y-%m-%d").strftime("%A, %B %d")
            
            # Update journal entries if they exist
            journal_updates = []
            for question in JOURNAL_QUESTIONS:
                journal_updates.append(data.get("journal", {}).get(question, ""))
            
            return [display_date] + journal_updates
        except ValueError:
            return [date_text.value] + ["" for _ in JOURNAL_QUESTIONS]

    def return_to_today():
        today = get_date_key()
        date_picker.value = today
        return [today, datetime.datetime.now().strftime("%A, %B %d")]

    # Connect date selection events
    date_picker.change(
        fn=load_selected_date,
        inputs=[date_picker],
        outputs=[date_text] + list(journal_inputs.values())
    )

    today_btn.click(
        fn=return_to_today,
        outputs=[date_picker, date_text]
    )

    # Auto-refresh every minute
    def auto_refresh():
        """Auto refresh function to check and refresh day data"""
        try:
            current_data = load_daily_data()
            current_data = check_and_refresh_day(current_data)
            save_daily_data(current_data)
        except Exception as e:
            print(f"Error in auto refresh: {e}")

    demo.load(fn=auto_refresh)  # No outputs needed
    demo.queue()

    # Connect the date selection events
    date_picker.change(
        fn=load_selected_date_metrics,
        inputs=[date_picker],
        outputs=[productivity, energy, mood, sleep, exercise]
    )

    refresh_dates_btn.click(
        fn=refresh_dates,
        outputs=[date_picker]
    )

demo.launch()