File size: 65,290 Bytes
e7afd1c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import streamlit as st
import json, datetime
import pandas as pd
import numpy as np
import base64
from io import BytesIO
from PIL import Image, ImageDraw, ImageFont
import random
import plotly.express as px
import plotly.graph_objects as go

from db import get_db

# -------------------- Database Connection --------------------
db = get_db()


# Collections for Phase 3
coping_plans_col = db["coping_plans"]
resources_col = db["resources"]
mood_board_col = db["mood_boards"]
gratitude_jar_col = db["gratitude_jar"]
worry_box_col = db["worry_box"]
sessions_col = db["sessions"]  # For assessment data

# -------------------- ๐ŸŽฏ PERSONALIZED COPING PLANS --------------------
def coping_plans_page(username):
    st.title("๐ŸŽฏ Your Personalized Coping Plan")
    st.markdown("Custom strategies based on your mental health profile")
    
    tab1, tab2, tab3 = st.tabs(["๐Ÿ“‹ My Plan", "๐Ÿ”„ Generate New Plan", "๐Ÿ“š All Plans"])
    
    with tab1:
        display_current_plan(username)
    
    with tab2:
        generate_coping_plan(username)
    
    with tab3:
        view_all_plans(username)

def generate_coping_plan(username):
    st.subheader("๐Ÿ”„ Generate Personalized Coping Plan")
    
    # Get user's recent assessment data
    recent_sessions = list(sessions_col.find(
        {"username": username}
    ).sort("timestamp", -1).limit(10))
    
    if not recent_sessions:
        st.info("๐Ÿ’ก Chat with the bot first to generate a personalized plan based on your emotions!")
        return
    
    # Analyze user's patterns
    emotions = [s.get('emotion', 'neutral') for s in recent_sessions]
    most_common_emotion = max(set(emotions), key=emotions.count)
    
    st.markdown(f"### Based on your recent patterns:")
    st.info(f"**Most Common Emotion:** {most_common_emotion.title()}")
    
    # Select focus areas
    st.markdown("### Select your focus areas:")
    
    focus_areas = st.multiselect(
        "What would you like to work on?",
        ["Anxiety Management", "Stress Relief", "Mood Enhancement", 
         "Sleep Quality", "Social Connection", "Self-Esteem", 
         "Anger Management", "Grief Processing"],
        default=["Anxiety Management", "Stress Relief"]
    )
    
    intensity = st.select_slider(
        "How intense should the interventions be?",
        options=["Gentle", "Moderate", "Intensive"],
        value="Moderate"
    )
    
    if st.button("๐ŸŽฏ Generate My Coping Plan", use_container_width=True):
        plan = create_personalized_plan(username, most_common_emotion, focus_areas, intensity)
        
        coping_plans_col.insert_one({
            "username": username,
            "emotion_pattern": most_common_emotion,
            "focus_areas": focus_areas,
            "intensity": intensity,
            "plan": plan,
            "created_at": datetime.datetime.utcnow(),
            "active": True
        })
        
        st.success("โœ… Your personalized coping plan has been generated!")
        st.rerun()

def create_personalized_plan(username, emotion, focus_areas, intensity):
    """Generate a personalized coping plan based on user data"""
    
    # Breathing exercises based on emotion
    breathing_exercises = {
        "anxiety": {
            "name": "4-7-8 Calming Breath",
            "steps": [
                "Inhale through nose for 4 seconds",
                "Hold breath for 7 seconds",
                "Exhale through mouth for 8 seconds",
                "Repeat 4 times"
            ],
            "benefit": "Activates parasympathetic nervous system, reduces anxiety"
        },
        "anger": {
            "name": "Box Breathing",
            "steps": [
                "Inhale for 4 seconds",
                "Hold for 4 seconds",
                "Exhale for 4 seconds",
                "Hold for 4 seconds",
                "Repeat 5 times"
            ],
            "benefit": "Regulates emotions and reduces anger intensity"
        },
        "sadness": {
            "name": "Energizing Breath",
            "steps": [
                "Quick inhale through nose (1 second)",
                "Quick exhale through nose (1 second)",
                "Repeat rapidly 10 times",
                "Rest and breathe normally"
            ],
            "benefit": "Increases energy and lifts mood"
        },
        "default": {
            "name": "Calm Breathing",
            "steps": [
                "Inhale slowly for 3 seconds",
                "Exhale slowly for 6 seconds",
                "Repeat 5 times"
            ],
            "benefit": "General relaxation and stress reduction"
        }
    }
    
    # Activity suggestions based on focus areas
    activities = {
        "Anxiety Management": [
            "๐Ÿšถ Take a 10-minute mindful walk",
            "๐Ÿ“ Write down 3 things you can control right now",
            "๐ŸŽง Listen to calming music for 15 minutes",
            "๐Ÿง˜ Progressive muscle relaxation (5 minutes)"
        ],
        "Stress Relief": [
            "๐Ÿ› Take a warm bath or shower",
            "๐Ÿ“š Read for pleasure (20 minutes)",
            "๐ŸŽจ Engage in creative activity",
            "โ˜• Practice mindful tea/coffee drinking"
        ],
        "Mood Enhancement": [
            "๐ŸŒž Get 15 minutes of sunlight",
            "๐Ÿค Connect with a friend or family member",
            "๐ŸŽต Listen to uplifting music and dance",
            "๐Ÿ˜Š Watch a comedy show or funny videos"
        ],
        "Sleep Quality": [
            "๐Ÿ“ฑ No screens 1 hour before bed",
            "๐Ÿ“– Read a physical book before sleep",
            "๐ŸŒ™ Keep bedroom cool and dark",
            "๐Ÿง˜ Do gentle stretching before bed"
        ],
        "Social Connection": [
            "๐Ÿ“ž Call or text a friend you haven't spoken to recently",
            "๐Ÿ‘ฅ Join an online community of your interest",
            "๐Ÿค Plan a social activity for this week",
            "๐Ÿ’ฌ Share something positive with someone today"
        ],
        "Self-Esteem": [
            "๐Ÿชž Write 5 things you like about yourself",
            "๐Ÿ† Acknowledge one achievement from today",
            "๐Ÿ’ช Do something you're good at",
            "๐ŸŽฏ Set and complete one small goal today"
        ],
        "Anger Management": [
            "๐Ÿšถ Take a break and walk away from the situation",
            "โœ๏ธ Write an angry letter (don't send it)",
            "๐ŸฅŠ Physical exercise to release tension",
            "๐ŸงŠ Hold ice cubes to ground yourself"
        ],
        "Grief Processing": [
            "๐Ÿ“ Journal about your memories",
            "๐Ÿ•ฏ๏ธ Create a small memorial or ritual",
            "๐Ÿค— Allow yourself to cry if needed",
            "๐Ÿ’ฌ Talk to someone who understands your loss"
        ]
    }
    
    # Get appropriate breathing exercise
    breath_exercise = breathing_exercises.get(emotion.lower(), breathing_exercises["default"])
    
    # Select activities based on focus areas
    selected_activities = []
    for area in focus_areas:
        if area in activities:
            selected_activities.extend(activities[area][:2])  # Take top 2 from each area
    
    # Daily schedule based on intensity
    schedules = {
        "Gentle": {
            "morning": "5 minutes breathing exercise",
            "afternoon": "One coping activity from your list",
            "evening": "Gratitude reflection (3 things)"
        },
        "Moderate": {
            "morning": "10 minutes breathing + mood check-in",
            "afternoon": "Two coping activities",
            "evening": "Breathing exercise + gratitude journal"
        },
        "Intensive": {
            "morning": "15 minutes breathing + meditation",
            "midday": "Mood check-in + one activity",
            "afternoon": "Two coping activities",
            "evening": "Breathing + gratitude + worry box review"
        }
    }
    
    plan = {
        "breathing_exercise": breath_exercise,
        "activities": selected_activities,
        "daily_schedule": schedules[intensity],
        "emergency_contacts": [
            {"name": "AASRA", "number": "91-22-27546669"},
            {"name": "Vandrevala Foundation", "number": "1860-2662-345"}
        ],
        "grounding_technique": {
            "name": "5-4-3-2-1 Grounding",
            "steps": [
                "5 things you can see",
                "4 things you can touch",
                "3 things you can hear",
                "2 things you can smell",
                "1 thing you can taste"
            ]
        }
    }
    
    return plan

def display_current_plan(username):
    """Display the user's active coping plan"""
    
    plan_doc = coping_plans_col.find_one({
        "username": username,
        "active": True
    }, sort=[("created_at", -1)])
    
    if not plan_doc:
        st.info("๐Ÿ“‹ No active coping plan. Generate one in the 'Generate New Plan' tab!")
        return
    
    plan = plan_doc['plan']
    
    # Display plan header
    st.markdown(f"### Your Active Plan")
    st.caption(f"Created: {plan_doc['created_at'].strftime('%B %d, %Y')}")
    st.markdown(f"**Focus Areas:** {', '.join(plan_doc['focus_areas'])}")
    st.markdown(f"**Intensity:** {plan_doc['intensity']}")
    
    st.markdown("---")
    
    # Breathing Exercise Section
    with st.expander("๐ŸŒฌ๏ธ Your Breathing Exercise", expanded=True):
        breath = plan['breathing_exercise']
        st.markdown(f"### {breath['name']}")
        st.info(f"**Benefit:** {breath['benefit']}")
        
        st.markdown("**Steps:**")
        for i, step in enumerate(breath['steps'], 1):
            st.markdown(f"{i}. {step}")
        
        if st.button("โœ… I completed this exercise", key="breath_complete"):
            st.success("Great job! Keep up the good work! ๐ŸŒŸ")
    
    # Daily Schedule
    with st.expander("๐Ÿ“… Daily Schedule", expanded=True):
        schedule = plan['daily_schedule']
        
        col1, col2, col3 = st.columns(3)
        
        with col1:
            st.markdown("#### ๐ŸŒ… Morning")
            st.info(schedule.get('morning', 'N/A'))
        
        with col2:
            st.markdown("#### โ˜€๏ธ Afternoon")
            st.info(schedule.get('afternoon', schedule.get('midday', 'N/A')))
        
        with col3:
            st.markdown("#### ๐ŸŒ™ Evening")
            st.info(schedule.get('evening', 'N/A'))
    
    # Activities
    with st.expander("๐ŸŽฏ Recommended Activities", expanded=True):
        st.markdown("Choose activities that resonate with you:")
        
        activities = plan.get('activities', [])
        for activity in activities:
            col1, col2 = st.columns([4, 1])
            with col1:
                st.markdown(f"โ€ข {activity}")
            with col2:
                if st.button("โœ“", key=f"activity_{hash(activity)}"):
                    st.success("Done! โœจ")
    
    # Grounding Technique
    with st.expander("๐Ÿง˜ Emergency Grounding Technique"):
        grounding = plan['grounding_technique']
        st.markdown(f"### {grounding['name']}")
        st.markdown("Use this when feeling overwhelmed:")
        
        for step in grounding['steps']:
            st.markdown(f"โ€ข {step}")
    
    # Emergency Contacts
    with st.expander("๐Ÿ†˜ Emergency Contacts"):
        st.markdown("### Crisis Helplines")
        for contact in plan['emergency_contacts']:
            st.markdown(f"**{contact['name']}:** {contact['number']}")

def view_all_plans(username):
    """View all historical coping plans"""
    
    plans = list(coping_plans_col.find(
        {"username": username}
    ).sort("created_at", -1))
    
    if not plans:
        st.info("๐Ÿ“š No plans yet. Generate your first one!")
        return
    
    st.subheader("๐Ÿ“š Your Coping Plans History")
    
    for plan_doc in plans:
        with st.expander(
            f"Plan from {plan_doc['created_at'].strftime('%B %d, %Y')} - "
            f"{plan_doc['intensity']} Intensity"
        ):
            st.markdown(f"**Focus Areas:** {', '.join(plan_doc['focus_areas'])}")
            st.markdown(f"**Based on emotion pattern:** {plan_doc['emotion_pattern'].title()}")
            
            if st.button("๐Ÿ”„ Activate This Plan", key=f"activate_{plan_doc['_id']}"):
                # Deactivate all plans
                coping_plans_col.update_many(
                    {"username": username},
                    {"$set": {"active": False}}
                )
                # Activate selected plan
                coping_plans_col.update_one(
                    {"_id": plan_doc["_id"]},
                    {"$set": {"active": True}}
                )
                st.success("โœ… Plan activated!")
                st.rerun()

# -------------------- ๐Ÿ“š RESOURCE LIBRARY --------------------
def resource_library_page(username):
    st.title("๐Ÿ“š Resource Library")
    st.markdown("Access guided sessions, tutorials, and worksheets")
    
    tab1, tab2, tab3, tab4 = st.tabs(["๐ŸŽฅ Videos", "๐ŸŽง Audio", "๐Ÿ“„ Worksheets", "๐Ÿ“– Articles"])
    
    with tab1:
        video_resources(username)
    
    with tab2:
        audio_resources(username)
    
    with tab3:
        worksheet_resources(username)
    
    with tab4:
        article_resources(username)

def video_resources(username):
    st.subheader("๐ŸŽฅ Video Tutorials")
    
    videos = [
        {
            "title": "5-Minute Breathing Exercise",
            "duration": "5:00",
            "category": "Breathing",
            "description": "Quick breathing technique to calm anxiety",
            "url": "https://www.youtube.com/watch?v=tybOi4hjZFQ"
        },
        {
            "title": "Guided Meditation for Beginners",
            "duration": "10:00",
            "category": "Meditation",
            "description": "Perfect for those new to meditation",
            "url": "https://www.youtube.com/watch?v=inpok4MKVLM"
        },
        {
            "title": "Progressive Muscle Relaxation",
            "duration": "15:00",
            "category": "Relaxation",
            "description": "Release physical tension systematically",
            "url": "https://www.youtube.com/watch?v=ihO02wUzgkc"
        },
        {
            "title": "Mindful Walking Tutorial",
            "duration": "8:00",
            "category": "Mindfulness",
            "description": "Turn your walk into a meditation",
            "url": "https://www.youtube.com/watch?v=6p_yaNFSYao"
        },
        {
            "title": "Body Scan Meditation",
            "duration": "20:00",
            "category": "Meditation",
            "description": "Deep relaxation through body awareness",
            "url": "https://www.youtube.com/watch?v=ihO02wUzgkc"
        }
    ]
    
    for video in videos:
        with st.container():
            col1, col2 = st.columns([3, 1])
            
            with col1:
                st.markdown(f"### {video['title']}")
                st.caption(f"โฑ๏ธ {video['duration']} โ€ข ๐Ÿท๏ธ {video['category']}")
                st.markdown(video['description'])
            
            with col2:
                if st.button("โ–ถ๏ธ Watch", key=f"video_{video['title']}"):
                    st.markdown(f"[Open Video]({video['url']})")
                    
                    # Log resource access
                    resources_col.insert_one({
                        "username": username,
                        "type": "video",
                        "title": video['title'],
                        "timestamp": datetime.datetime.utcnow()
                    })
            
            st.markdown("---")

def audio_resources(username):
    st.subheader("๐ŸŽง Audio Guided Sessions")
    
    audio_sessions = [
        {
            "title": "Sleep Meditation",
            "duration": "30:00",
            "category": "Sleep",
            "description": "Gentle guidance to help you fall asleep",
            "url": "https://www.youtube.com/watch?v=aEqlQvczMJQ",
            "embed_id": "aEqlQvczMJQ"
        },
        {
            "title": "Anxiety Relief Session",
            "duration": "15:00",
            "category": "Anxiety",
            "description": "Calm your anxious thoughts",
            "url": "https://www.youtube.com/watch?v=O-6f5wQXSu8",
            "embed_id": "O-6f5wQXSu8"
        },
        {
            "title": "Morning Motivation",
            "duration": "10:00",
            "category": "Motivation",
            "description": "Start your day with positivity",
            "url": "https://www.youtube.com/watch?v=ZsTKyYOuK84",
            "embed_id": "ZsTKyYOuK84"
        },
        {
            "title": "Stress Release",
            "duration": "20:00",
            "category": "Stress",
            "description": "Let go of daily stress and tension",
            "url": "https://www.youtube.com/watch?v=inpok4MKVLM",
            "embed_id": "inpok4MKVLM"
        },
        {
            "title": "Self-Compassion Practice",
            "duration": "12:00",
            "category": "Self-Care",
            "description": "Cultivate kindness toward yourself",
            "url": "https://www.youtube.com/watch?v=11U0h0DPu7k",
            "embed_id": "11U0h0DPu7k"
        }
    ]
    
    for audio in audio_sessions:
        with st.expander(f"๐ŸŽง {audio['title']} ({audio['duration']})"):
            st.caption(f"๐Ÿท๏ธ {audio['category']}")
            st.markdown(audio['description'])
            
            # Embed YouTube video
            st.markdown(
                f"""

                <iframe width="100%" height="200" 

                src="https://www.youtube.com/embed/{audio['embed_id']}" 

                frameborder="0" 

                allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" 

                allowfullscreen>

                </iframe>

                """,
                unsafe_allow_html=True
            )
            
            # Log when user opens the expander
            if st.button("โœ… Mark as Listened", key=f"audio_{audio['title']}"):
                resources_col.insert_one({
                    "username": username,
                    "type": "audio",
                    "title": audio['title'],
                    "timestamp": datetime.datetime.utcnow()
                })
                st.success("๐ŸŽ‰ Great job! Session logged.")
            
            st.markdown("---")

def worksheet_resources(username):
    st.subheader("๐Ÿ“„ CBT Worksheets โ€“ Guided Exercises โœจ")

    worksheets = [
        {
            "title": "Thought Record",
            "category": "CBT",
            "description": "Identify negative thoughts and replace them with balanced ones.",
            "content": """

### ๐Ÿ“ How to use the Thought Record Worksheet

1. **Notice a Negative Thought** ๐Ÿ’ญ  

   - Recall a recent thought that caused stress, worry, or discomfort.  

   - Write it down in clear words.



2. **Identify the Cognitive Distortion** ๐Ÿ”  

   - Ask yourself: Is this thought all-or-nothing? Overgeneralized? Catastrophizing?  

   - Labeling the distortion helps you see it clearly.



3. **Examine the Evidence** ๐Ÿ“Š  

   - Look for facts that support this thought.  

   - Look for facts that contradict it.  

   - Balance your perspective by considering both sides.



4. **Create a Balanced Thought** ๐ŸŒˆ  

   - Reframe the situation realistically and kindly.  

   - Example: โ€œI struggled in the meeting, but I also shared some good ideas. I am learning and improving.โ€



5. **Reflect on the Outcome** ๐ŸŒŸ  

   - How do you feel after reframing the thought?  

   - Notice changes in mood, tension, or perspective.



๐Ÿ’ก Tip: Practice this daily for 5โ€“10 minutes. Over time, your mind naturally starts noticing distortions and reframing automatically. โœจ

"""
        },
        {
            "title": "Behavioral Activation",
            "category": "Depression",
            "description": "Plan small positive activities to improve mood.",
            "content": """

### ๐Ÿ“ How to use the Behavioral Activation Worksheet

1. **List Activities You Enjoy or Value** ๐ŸŽจ๐Ÿƒโ€โ™‚๏ธ  

   - Write down small activities that bring you joy or purpose, even if itโ€™s simple (e.g., walking, listening to music, calling a friend).



2. **Schedule Your Activities** ๐Ÿ“…  

   - Pick 1โ€“3 activities per day.  

   - Write down the time and place so it becomes a concrete plan.



3. **Notice Your Mood Before and After** ๐ŸŒž  

   - Rate your mood from 1โ€“10 before the activity.  

   - Rate your mood after completing it.  

   - Observe how small positive steps influence your overall mood.



4. **Start Small** ๐Ÿพ  

   - Begin with achievable tasks.  

   - Small wins create momentum and motivation.



5. **Reflect and Adjust** ๐Ÿ”„  

   - Celebrate completed activities.  

   - Adjust your plan based on what worked and what didnโ€™t.



๐Ÿ’ก Tip: Even on low-energy days, doing one small activity can shift your perspective and create a positive ripple effect. ๐ŸŽ‰

"""
        },
        {
            "title": "Anxiety Trigger Log",
            "category": "Anxiety",
            "description": "Track what triggers anxiety and how you respond.",
            "content": """

### ๐Ÿ“ How to use the Anxiety Trigger Log

1. **Identify Triggers** โš ๏ธ  

   - Note situations, people, thoughts, or environments that provoke anxiety.  

   - Be specific about the context.



2. **Describe Your Response** ๐Ÿง ๐Ÿ’“  

   - Record your emotional, physical, and behavioral reactions.  

   - Examples: racing heart, shallow breathing, avoidance, rumination.



3. **Rate Anxiety Level** ๐Ÿ“Š  

   - Use a scale of 1โ€“10 to indicate how strong the anxiety felt.  

   - Helps monitor patterns over time.



4. **Identify Coping Strategies** ๐ŸŒฟ  

   - Note what helped calm you or what could help next time.  

   - Examples: deep breathing, mindfulness, grounding techniques, calling a friend.



5. **Reflect and Learn** ๐Ÿ“  

   - Review patterns weekly.  

   - Notice repeated triggers, effective coping strategies, and progress.



๐Ÿ’ก Tip: Logging triggers does not make anxiety worse; it gives you insight and control. Knowledge is power! ๐Ÿ’ช

"""
        },
        {
            "title": "Gratitude Worksheet",
            "category": "Positive",
            "description": "Write down things you are grateful for to shift perspective.",
            "content": """

### ๐Ÿ“ How to use the Gratitude Worksheet

1. **List Three Things Daily** ๐ŸŒธ  

   - Write down at least three things you are grateful for today.  

   - Examples: sunny morning, supportive friend, completed task.



2. **Be Specific** โœจ  

   - Avoid generalities like โ€œIโ€™m grateful for life.โ€  

   - Detail makes the gratitude practice more powerful.



3. **Notice the Why** ๐Ÿ’–  

   - Reflect why you are grateful for each item.  

   - Example: โ€œIโ€™m grateful for my friend calling me because it made me feel supported and connected.โ€



4. **Include People and Moments** ๐Ÿ‘จโ€๐Ÿ‘ฉโ€๐Ÿ‘งโ€๐Ÿ‘ฆ  

   - Recognize othersโ€™ impact on your life.  

   - Small gestures often bring the most meaning.



5. **Reflect on the Impact** ๐ŸŒŸ  

   - After a week, review your entries.  

   - Notice changes in mood, perspective, and stress levels.



๐Ÿ’ก Tip: Gratitude rewires your brain to notice positive experiences. Itโ€™s a simple yet powerful tool for lasting happiness! ๐Ÿ˜„

"""
        },
        {
            "title": "Sleep Hygiene Checklist",
            "category": "Sleep",
            "description": "Improve your sleep routine using evidence-based habits.",
            "content": """

### ๐Ÿ“ How to use the Sleep Hygiene Checklist

1. **Set a Consistent Schedule** โฐ  

   - Go to bed and wake up at the same time every day.  

   - Your body thrives on routine.



2. **Create a Sleep-Friendly Environment** ๐ŸŒ™  

   - Keep your bedroom dark, quiet, and cool.  

   - Use blackout curtains or eye masks.  

   - Remove electronic distractions.



3. **Wind Down Before Bed** ๐Ÿ›€  

   - Avoid screens 60 minutes before sleep.  

   - Practice gentle stretching, deep breathing, or light reading.



4. **Limit Stimulants** โ˜•  

   - Avoid caffeine, nicotine, and heavy meals close to bedtime.



5. **Track Sleep Patterns** ๐Ÿ“Š  

   - Note bedtime, wake time, and sleep quality.  

   - Identify habits that help or hinder rest.



6. **Practice Relaxation Techniques** ๐ŸŒฟ  

   - Meditation, progressive muscle relaxation, or guided audio can calm your mind.



7. **Daytime Habits Matter** ๐ŸŒž  

   - Regular physical activity improves sleep.  

   - Exposure to sunlight helps regulate your circadian rhythm.



๐Ÿ’ก Tip: Good sleep is foundational for mental, emotional, and physical health. Prioritize it, and your mind and body will thank you! ๐Ÿ˜ดโœจ

"""
        }
    ]

    for ws in worksheets:
        with st.expander(f"๐Ÿ“„ {ws['title']}"):
            st.caption(f"๐Ÿท๏ธ {ws['category']}")
            st.markdown(ws['description'])
            st.markdown(ws.get('content', '๐Ÿ“Œ No detailed guide yet.'))

            if st.button("๐Ÿ“ Mark as Completed", key=f"ws_{ws['title']}"):
                resources_col.insert_one({
                    "username": username,
                    "type": "worksheet",
                    "title": ws['title'],
                    "timestamp": datetime.datetime.utcnow()
                })
                st.success("๐ŸŽ‰ Worksheet completed and logged!")



def article_resources(username):
    st.subheader("๐Ÿ“– Helpful Articles")
    
    articles = [
        {
            "title": "Understanding Anxiety: A Complete Guide",
            "read_time": "10 min",
            "category": "Education",
            "summary": "Learn about anxiety disorders, symptoms, and evidence-based treatments.",
            "content": """Anxiety is not a weakness. It is not a flaw in your character. It is not a sign that you are broken.

Anxiety is a signal โ€” a deeply human response from your nervous system trying to protect you.



Long ago, anxiety kept humans alive. It prepared the body to react to danger, to run, to fight, or to freeze.

But in the modern world, where threats are psychological, social, and emotional, that same system can become overactive.



When anxiety becomes constant, it stops being protection and starts becoming a burden.



You may feel it as:

A racing mind that never seems to rest.

A tightness in your chest that makes breathing feel shallow.

A constant sense that something is wrong, even when nothing is.

A fear of the future that loops endlessly in your thoughts.



This can be exhausting.

It can be isolating.

It can make you feel like you are fighting an invisible battle every single day.



But here is the truth:

You are not alone.

You are not weak.

And you are not beyond help.



Anxiety is one of the most common mental health experiences in the world.

Millions of people live with it, learn to manage it, and go on to live meaningful, peaceful lives.



Understanding anxiety is the first step toward reducing its power over you.



Anxiety is driven by your nervous system โ€” especially a part called the amygdala.

The amygdala scans your environment for danger.

When it senses a threat, it sends a signal that releases stress hormones like adrenaline and cortisol.



Your heart beats faster.

Your breathing becomes shallow.

Your muscles tense.

Your thoughts become focused on survival.



This is known as the โ€œfight or flightโ€ response.



In short bursts, this system is helpful.

But when it is activated too often or for too long, it creates chronic anxiety.



Your body begins to live as if danger is always present.

Your mind becomes hyper-alert.

Your emotions become harder to regulate.



This is why anxiety is not just โ€œin your head.โ€

It is in your body.

It is in your nervous system.

It is in your biology.



And because it is biological, it is treatable.



There are many forms of anxiety:

Generalized Anxiety Disorder โ€” constant worry about many areas of life.

Social Anxiety โ€” fear of judgment, embarrassment, or rejection.

Panic Disorder โ€” sudden waves of intense fear and physical symptoms.

Health Anxiety โ€” constant worry about illness or bodily sensations.

Phobias โ€” intense fear of specific situations or objects.



Each type feels different.

But all of them share one core feature:

Your brain is trying to protect you from perceived danger.



The problem is not that your brain is broken.

The problem is that your brain is trying too hard.



Anxiety often grows when we avoid what we fear.

Avoidance gives short-term relief, but it teaches the brain that the threat was real.

So the fear grows stronger.



This is why anxiety can slowly shrink your world.

You stop doing things you once enjoyed.

You cancel plans.

You avoid people, places, or situations.



Your life becomes smaller, not because you want it to โ€” but because anxiety is steering your choices.



The good news is that this pattern can be reversed.



Your brain is plastic โ€” it changes with experience.

Every time you face a fear gently and safely, your brain learns:

โ€œI survived this.โ€

โ€œI can handle this.โ€

โ€œThis is not as dangerous as I thought.โ€



This is how healing happens.



There are powerful, evidence-based tools that help reduce anxiety:



Cognitive Behavioral Therapy helps you identify anxious thought patterns and replace them with more balanced ones.

Mindfulness teaches you to observe your thoughts instead of being trapped inside them.

Breathing exercises calm the nervous system and signal safety to the body.

Physical movement helps burn off excess stress hormones.

Healthy sleep restores emotional regulation.

Connection with others reminds your brain that you are safe and supported.



Sometimes medication is helpful โ€” not as a failure, but as a support while you heal.



And perhaps the most important part of healing anxiety is changing how you relate to it.



Instead of fighting anxiety, you learn to understand it.

Instead of fearing fear, you learn to tolerate it.

Instead of judging yourself, you learn to show compassion.



You learn to say:

โ€œThis is uncomfortable, but I am safe.โ€

โ€œThis feeling will rise, and this feeling will fall.โ€

โ€œI do not have to control everything to be okay.โ€



With time, patience, and practice, anxiety loses its grip.

It does not vanish overnight.

But it softens.

It quiets.

It becomes manageable.



And you become stronger โ€” not because anxiety disappears, but because you learn you can live well even when it appears.



Your life is bigger than your fear.

Your future is not defined by your anxiety.

Your nervous system can learn peace again.



And step by step, breath by breath, moment by moment โ€”

You are moving toward that peace.



You are not broken.

You are human.

And you are healing.

"""

        },
        {
            "title": "10 Science-Backed Ways to Reduce Stress",
            "read_time": "7 min",
            "category": "Tips",
            "summary": "Practical, research-supported strategies for stress management.",
            "content": """Stress is not a sign that you are failing.

Stress is a sign that you are human.



Your body was designed to respond to challenge with energy, focus, and alertness.

But when stress becomes constant, your nervous system never gets the message that it is safe to rest.



Your mind becomes tired.

Your body becomes tense.

Your emotions become harder to regulate.

Your joy becomes quieter.



Stress slowly drains you โ€” not because you are weak, but because your system was never meant to run at full speed all the time.



The good news is this:

Your body also has a built-in system for calm.

You can activate it intentionally.



Here are 10 science-backed ways to reduce stress and restore balance.



1. Slow, deep breathing.

When you slow your breath, you directly signal safety to your nervous system.

Long exhalations activate the parasympathetic nervous system โ€” the part responsible for rest and recovery.

Even five slow breaths can reduce cortisol and heart rate.



2. Move your body gently and regularly.

Exercise is one of the most effective stress regulators.

It releases endorphins, improves sleep, and burns off excess adrenaline.

This does not mean intense workouts only โ€” walking, stretching, yoga, or dancing all count.



3. Spend time in nature.

Research shows that being in green spaces lowers stress hormones, reduces rumination, and improves mood.

Even looking at trees through a window has a calming effect on the brain.



4. Practice mindfulness.

Mindfulness trains your brain to stay in the present moment instead of looping through worries about the future.

It reduces activity in the brainโ€™s fear center and strengthens emotional regulation.



5. Improve sleep quality.

Sleep is when your nervous system resets.

Poor sleep increases emotional reactivity and stress sensitivity.

Creating a consistent sleep routine can dramatically improve stress levels.



6. Limit caffeine and stimulants.

Caffeine activates the same system involved in anxiety and stress.

Reducing intake can significantly lower baseline tension in the body.



7. Connect with others.

Human connection is a powerful stress buffer.

Feeling seen, heard, and supported reduces cortisol and increases oxytocin โ€” the hormone of safety and bonding.



8. Write your thoughts down.

Journaling reduces mental load by moving thoughts from your mind onto paper.

This creates clarity and reduces rumination.



9. Practice self-compassion.

Harsh self-criticism keeps the stress response activated.

Speaking to yourself with kindness tells your brain that you are safe, even when things are imperfect.



10. Accept what you cannot control.

Stress often comes from trying to control what is uncertain.

Letting go is not giving up โ€” it is choosing peace over constant struggle.



Stress does not mean something is wrong with you.

It means your system is asking for care.



You are not meant to be calm all the time.

But you are meant to feel safe in your own body.



By practicing these tools gently and consistently, you teach your nervous system that the world is not always an emergency.

You give your mind permission to rest.

You give your body permission to soften.



And from that softness, clarity grows.

Energy returns.

Joy becomes easier to access.



Stress is not your enemy.

It is a message.



And you are learning how to listen โ€” and how to respond with care.

"""

        },
        {
            "title": "The Power of Mindfulness",
            "read_time": "8 min",
            "category": "Mindfulness",
            "summary": "How mindfulness can transform your mental health.",
            "content": """Mindfulness is not about stopping your thoughts.

It is not about becoming calm all the time.

It is not about emptying your mind or being โ€œperfectly present.โ€



Mindfulness is about learning how to be with your experience โ€” exactly as it is โ€” without judgment.



It is the practice of noticing what is happening inside you and around you with kindness and curiosity.



Your thoughts.

Your emotions.

Your bodily sensations.

Your breath.

Your environment.



Without pushing them away.

Without clinging to them.

Without criticizing yourself for having them.



And this simple shift changes everything.



Because most suffering does not come from pain itself.

It comes from our resistance to pain.

Our fear of it.

Our stories about it.

Our desire to escape it.



Mindfulness gently teaches you:

โ€œYou do not need to fight your experience to be okay.โ€



From a scientific perspective, mindfulness reshapes the brain.



Studies show that regular mindfulness practice:

Reduces activity in the amygdala (the brainโ€™s fear center).

Strengthens the prefrontal cortex (responsible for emotional regulation).

Improves attention and focus.

Reduces rumination and worry.

Increases emotional resilience.



In simple words:

It helps your brain become calmer, clearer, and kinder.



But beyond science, mindfulness changes how life feels.



It turns automatic reactions into conscious responses.

It creates space between a feeling and an action.

It gives you the freedom to choose how you show up.



Instead of being pulled by every thought, you learn to observe them.

Instead of being overwhelmed by every emotion, you learn to hold them.

Instead of being lost in the past or anxious about the future, you return to now.



And in this moment โ€” this breath, this body, this awareness โ€” you find stability.



Mindfulness begins with the breath.

Not because breathing is magical, but because it is always here.



You may not always feel calm.

You may not always feel happy.

But you can always feel your breath.



And every time you notice it, you anchor yourself in the present.



Over time, this changes your relationship with your inner world.



You stop fearing your thoughts.

You stop running from your emotions.

You stop judging yourself for being human.



You learn that thoughts are just thoughts.

Emotions are just emotions.

Sensations rise and fall like waves.



You are the ocean, not the waves.



This is what gives mindfulness its power.



It does not remove pain from life.

But it removes the extra suffering we create around pain.



It does not promise happiness.

But it creates peace even when happiness is absent.



It does not change your external circumstances.

But it changes how you experience them.



And that changes everything.



Mindfulness teaches you to meet yourself with compassion.

To treat your inner experience with the same kindness you would offer a dear friend.

To stop being your own harshest critic.

To become your own safe place.



This is not weakness.

This is strength.



Because only a strong mind can be gentle.

Only a brave heart can stay present with discomfort.

Only a wise soul can choose awareness over avoidance.



Every moment of mindfulness is a moment of freedom.

Freedom from automatic reactions.

Freedom from old patterns.

Freedom from unnecessary suffering.



And with practice, that freedom grows.



You do not have to be perfect.

You do not have to meditate for hours.

You do not have to do this โ€œright.โ€



You only have to begin.



One breath.

One moment.

One act of awareness at a time.



And slowly, gently, quietly โ€”

Your relationship with yourself changes.

Your relationship with your mind changes.

Your relationship with your life changes.



That is the power of mindfulness.

"""

        },
        {
            "title": "Cognitive Distortions and How to Combat Them",
            "read_time": "12 min",
            "category": "CBT",
            "summary": "Identify and challenge unhelpful thinking patterns.",
            "content": """Our minds are powerful, but they can also play tricks on us.  

Cognitive distortions are biased ways of thinking that cause us to see reality inaccurately.  

They fuel anxiety, depression, stress, and self-doubt โ€” often without us even noticing.



Some common distortions include:



1. **All-or-Nothing Thinking**  

   Seeing things in black or white, with no middle ground.  

   โ€œIf I fail this task, Iโ€™m a complete failure.โ€



2. **Overgeneralization**  

   Taking one event and assuming it defines everything.  

   โ€œI didnโ€™t do well today, so Iโ€™ll never succeed.โ€



3. **Mental Filtering**  

   Focusing solely on negative details, ignoring positives.  

   โ€œI made a mistake in the presentation, so the whole talk was awful.โ€



4. **Disqualifying the Positive**  

   Dismissing your achievements or compliments.  

   โ€œThey said I did a good job, but they were just being polite.โ€



5. **Jumping to Conclusions**  

   Making assumptions without evidence:  

   - Mind reading: โ€œThey think Iโ€™m incompetent.โ€  

   - Fortune telling: โ€œThis will end badly.โ€



6. **Catastrophizing**  

   Exaggerating the negative outcome.  

   โ€œIf I make a small mistake, it will ruin everything.โ€



7. **Emotional Reasoning**  

   Believing feelings reflect facts.  

   โ€œI feel guilty, so I must have done something wrong.โ€



8. **Should Statements**  

   Setting unrealistic expectations for yourself or others.  

   โ€œI should always be productive. I must never fail.โ€



9. **Labeling**  

   Attaching a negative label to yourself or others.  

   โ€œIโ€™m useless.โ€ โ€œTheyโ€™re a bad person.โ€



10. **Personalization**  

    Taking responsibility for events beyond your control.  

    โ€œItโ€™s my fault that the team missed the deadline.โ€



---



### How to Combat Cognitive Distortions



**1. Awareness is Key**  

Start noticing when your thoughts become distorted. Awareness is the first step toward change.



**2. Challenge the Thought**  

Ask yourself:  

- What is the evidence for this thought?  

- Is there another way to view this situation?  

- Would I say this to a friend?



**3. Reframe Positively**  

Replace distortions with balanced, realistic thoughts.  

- Instead of: โ€œI always fail,โ€ try: โ€œSometimes I struggle, but I also succeed.โ€



**4. Record and Reflect**  

Maintain a thought diary. Write down your negative thoughts, the distortion, and a rational counter-thought.



**5. Practice Self-Compassion**  

Mistakes do not define you. Treat yourself with the kindness you would show a friend.



**6. Use Mindfulness**  

Observe your thoughts without judgment. Let them pass rather than reacting automatically.



**7. Seek Evidence**  

Challenge assumptions by looking for proof. Facts often contradict distorted thoughts.



**8. Gradual Exposure**  

Face situations you fear instead of avoiding them. This weakens distorted thinking over time.



**9. Cognitive Behavioral Exercises**  

- Thought records  

- Behavioral experiments  

- Challenging core beliefs  



**10. Professional Support**  

CBT therapists can guide you in identifying distortions and building healthier thinking patterns.



---



### Why This Matters



Cognitive distortions shape your reality.  

They influence your emotions, behaviors, and decisions.  

By recognizing and challenging them, you:



- Reduce anxiety and stress  

- Improve mood and self-esteem  

- Make clearer, rational decisions  

- Build resilience and emotional intelligence  



Your mind is not your enemy.  

It is a tool. And like any tool, it works best when sharpened and guided.  



Transforming your thoughts transforms your life.

"""

        },
        {
            "title": "Building Healthy Sleep Habits",
            "read_time": "6 min",
            "category": "Sleep",
            "summary": "Create a sleep routine that works for you.",
            "content": """Sleep is not just a break from lifeโ€”itโ€™s a critical pillar of mental, emotional, and physical health.  

Yet in todayโ€™s fast-paced world, many struggle to get restorative rest.  

Building healthy sleep habits can transform your energy, mood, and overall wellbeing.



---



### Why Sleep Matters



- **Brain Function:** Sleep enhances memory, learning, and decision-making.  

- **Emotional Health:** Proper rest reduces irritability, anxiety, and depression.  

- **Physical Health:** Supports immune function, metabolism, and heart health.  

- **Energy & Focus:** Restorative sleep fuels productivity and creativity.



---



### Common Sleep Challenges



- Trouble falling asleep  

- Waking up frequently at night  

- Feeling tired despite adequate hours  

- Insomnia caused by stress or overthinking  



---



### Science-Backed Ways to Improve Sleep



1. **Set a Consistent Sleep Schedule**  

   Go to bed and wake up at the same time every dayโ€”even on weekends.  

   Your body thrives on routine.



2. **Create a Sleep-Inducing Environment**  

   - Keep your bedroom dark, cool, and quiet  

   - Use blackout curtains or eye masks  

   - Remove electronic distractions



3. **Limit Screen Time Before Bed**  

   The blue light from phones, tablets, and TVs interferes with melatonin production.  

   Aim for at least 60 minutes of screen-free time before sleep.



4. **Wind Down with a Nighttime Routine**  

   - Gentle stretching or yoga  

   - Deep breathing exercises  

   - Journaling or gratitude reflections  

   - Reading a physical book  



5. **Mind Your Diet and Beverages**  

   - Avoid caffeine and nicotine in the evening  

   - Limit heavy meals before bedtime  

   - Consider herbal teas like chamomile or lavender



6. **Stay Active During the Day**  

   Regular physical activity improves sleep quality, but avoid intense exercise right before bed.



7. **Manage Stress and Anxiety**  

   Mindfulness, meditation, and cognitive-behavioral strategies help calm racing thoughts at night.



8. **Use the Bed for Sleep Only**  

   Avoid working, scrolling, or watching TV in bed.  

   This strengthens the mental association between bed and sleep.



9. **Expose Yourself to Natural Light**  

   Morning sunlight helps regulate your circadian rhythm, signaling your body when to wake and sleep.



10. **Limit Naps**  

    Short naps (20โ€“30 minutes) are fine, but long or late-day naps can interfere with nighttime sleep.



---



### Tips for a Powerful Sleep Routine



- Stick to a fixed โ€œwind-downโ€ ritual every night  

- Track sleep patterns in a journal or app  

- Listen to relaxing audio like guided meditations or nature sounds  

- Practice gratitude or visualization to calm the mind  



---



### Transform Your Life, One Night at a Time



Healthy sleep is the foundation of a thriving mind and body.  

Small changesโ€”like dimming lights, setting a bedtime, or practicing mindfulnessโ€”create big results over time.  



By committing to consistent sleep habits, you unlock:



- Better emotional resilience  

- Clearer thinking and focus  

- Stronger immunity  

- A more balanced, joyful life  



Sleep well, live well, thrive.

"""

        }
    ]
    
    for article in articles:
        with st.expander(f"๐Ÿ“– {article['title']} ({article['read_time']} read)"):
            st.caption(f"๐Ÿท๏ธ {article['category']}")
            st.markdown(article['summary'])
            
            if st.button("๐Ÿ“š Read Full Article", key=f"article_{article['title']}"):
                #st.info("๐Ÿ“– Full article would open here!")
                st.markdown(article.get('content', 'Full content not available.'))
                
                resources_col.insert_one({
                    "username": username,
                    "type": "article",
                    "title": article['title'],
                    "timestamp": datetime.datetime.utcnow()
                })

# -------------------- ๐ŸŽฎ INTERACTIVE TOOLS --------------------
def interactive_tools_page(username):
    st.title("๐ŸŽฎ Interactive Wellness Tools")
    st.markdown("Creative tools to support your mental health journey")
    
    tab1, tab2, tab3 = st.tabs(["๐ŸŽจ Mood Board", "๐Ÿ™ Gratitude Jar", "๐Ÿ“ฆ Worry Box"])
    
    with tab1:
        mood_board_tool(username)
    
    with tab2:
        gratitude_jar_tool(username)
    
    with tab3:
        worry_box_tool(username)

def mood_board_tool(username):
    st.subheader("๐ŸŽจ Mood Board Creator")
    st.markdown("Express your emotions visually through colors, words, and symbols")
    
    col1, col2 = st.columns([2, 1])
    
    with col1:
        # Current mood
        current_mood = st.select_slider(
            "How are you feeling right now?",
            options=["๐Ÿ˜ข Very Sad", "๐Ÿ˜” Down", "๐Ÿ˜ Neutral", "๐Ÿ™‚ Good", "๐Ÿ˜Š Great"],
            value="๐Ÿ˜ Neutral"
        )
        
        # Color selection
        mood_color = st.color_picker("Pick a color that represents your mood:", "#FF6B6B")
        
        # Words/phrases
        mood_words = st.text_area(
            "Add words or phrases that describe your feelings:",
            placeholder="peaceful, hopeful, anxious, calm..."
        )
        
        # Emoji selection
        selected_emojis = st.multiselect(
            "Add emojis to your board:",
            ["๐Ÿ˜Š", "๐Ÿ˜ข", "๐Ÿ˜ ", "๐Ÿ˜ฐ", "๐ŸŒŸ", "๐Ÿ’ช", "๐ŸŒˆ", "โ˜€๏ธ", "๐ŸŒ™", "๐Ÿ’š", "๐Ÿฆ‹", "๐ŸŒธ"]
        )
        
        if st.button("๐Ÿ’พ Save Mood Board", use_container_width=True):
            mood_board = {
                "username": username,
                "mood": current_mood,
                "color": mood_color,
                "words": mood_words,
                "emojis": selected_emojis,
                "timestamp": datetime.datetime.utcnow()
            }
            
            mood_board_col.insert_one(mood_board)
            st.success("โœ… Mood board saved! Check your gallery below.")
            st.rerun()
    
    with col2:
        st.markdown("### ๐Ÿ’ก Tips")
        st.info("""

        **Mood boarding helps:**

        - Express complex emotions

        - Track emotional patterns

        - Increase self-awareness

        - Process feelings creatively

        """)
    
    # Gallery of past mood boards
    st.markdown("---")
    st.markdown("### ๐Ÿ–ผ๏ธ Your Mood Board Gallery")
    
    past_boards = list(mood_board_col.find(
        {"username": username}
    ).sort("timestamp", -1).limit(12))
    
    if past_boards:
        cols = st.columns(3)
        
        for idx, board in enumerate(past_boards):
            with cols[idx % 3]:
                st.markdown(
                    f"""

                    <div style='background-color: {board['color']}; 

                                padding: 20px; border-radius: 10px; 

                                text-align: center; min-height: 150px;'>

                        <div style='font-size: 2rem;'>{board['mood'].split()[0]}</div>

                        <div style='margin: 10px 0;'>{' '.join(board.get('emojis', []))}</div>

                        <div style='font-size: 0.8rem; color: #333;'>

                            {board['timestamp'].strftime('%b %d')}

                        </div>

                    </div>

                    """,
                    unsafe_allow_html=True
                )
                
                with st.expander("View details"):
                    st.markdown(f"**Mood:** {board['mood']}")
                    if board.get('words'):
                        st.markdown(f"**Words:** {board['words']}")
    else:
        st.info("๐ŸŽจ Create your first mood board above!")

def gratitude_jar_tool(username):
    st.subheader("๐Ÿ™ Gratitude Jar")
    st.markdown("Fill your virtual jar with things you're grateful for")
    
    col1, col2 = st.columns([2, 1])
    
    with col1:
        # Add gratitude
        gratitude_text = st.text_area(
            "What are you grateful for today?",
            placeholder="I'm grateful for...",
            height=100
        )
        
        category = st.selectbox(
            "Category:",
            ["๐Ÿค People", "๐ŸŒŸ Experience", "๐Ÿ’ช Personal Growth", 
             "๐Ÿ  Home & Comfort", "๐ŸŒ Nature", "๐Ÿ’ผ Work", "๐Ÿ’š Health", "๐ŸŽจ Creativity"]
        )
        
        if st.button("๐Ÿ™ Add to Jar", use_container_width=True):
            if gratitude_text:
                gratitude_jar_col.insert_one({
                    "username": username,
                    "text": gratitude_text,
                    "category": category,
                    "timestamp": datetime.datetime.utcnow()
                })
                st.success("โœ… Added to your gratitude jar!")
                st.balloons()
                st.rerun()
            else:
                st.warning("โš ๏ธ Please write something you're grateful for")
    
    with col2:
        # Jar visualization
        jar_count = gratitude_jar_col.count_documents({"username": username})
        
        st.markdown("### ๐Ÿบ Your Jar")
        st.markdown(
            f"""

            <div style='text-align: center; padding: 30px; 

                        background: linear-gradient(180deg, rgba(255,215,0,0.3) 0%, rgba(255,165,0,0.5) 100%);

                        border-radius: 20px; border: 3px solid #FFD700;'>

                <div style='font-size: 4rem;'>๐Ÿบ</div>

                <div style='font-size: 2rem; font-weight: bold; color: #FF8C00;'>{jar_count}</div>

                <div style='color: #666;'>gratitude notes</div>

            </div>

            """,
            unsafe_allow_html=True
        )
    
    # View gratitudes
    st.markdown("---")
    st.markdown("### ๐Ÿ“– Your Gratitude Collection")
    
    # Filter by category
    filter_category = st.selectbox(
        "Filter by category:",
        ["All"] + ["๐Ÿค People", "๐ŸŒŸ Experience", "๐Ÿ’ช Personal Growth", 
                   "๐Ÿ  Home & Comfort", "๐ŸŒ Nature", "๐Ÿ’ผ Work", "๐Ÿ’š Health", "๐ŸŽจ Creativity"],
        key="gratitude_filter"
    )
    
    # Get gratitudes
    query = {"username": username}
    if filter_category != "All":
        query["category"] = filter_category
    
    gratitudes = list(gratitude_jar_col.find(query).sort("timestamp", -1).limit(20))
    
    if gratitudes:
        for gratitude in gratitudes:
            with st.container():
                col1, col2 = st.columns([5, 1])
                
                with col1:
                    st.markdown(f"**{gratitude['category']}** โ€ข {gratitude['timestamp'].strftime('%b %d, %Y')}")
                    st.markdown(f"_{gratitude['text']}_")
                
                with col2:
                    if st.button("๐Ÿ—‘๏ธ", key=f"del_grat_{gratitude['_id']}"):
                        gratitude_jar_col.delete_one({"_id": gratitude["_id"]})
                        st.rerun()
                
                st.markdown("---")
    else:
        st.info("๐Ÿ™ Start adding gratitude notes to fill your jar!")

def worry_box_tool(username):
    st.subheader("๐Ÿ“ฆ Worry Box")
    st.markdown("Write down your worries and store them away - revisit them later with perspective")
    
    col1, col2 = st.columns([2, 1])
    
    with col1:
        # Add worry
        worry_text = st.text_area(
            "What's worrying you?",
            placeholder="Write your worry here...",
            height=120
        )
        
        worry_intensity = st.select_slider(
            "How intense is this worry?",
            options=["๐Ÿ˜Œ Mild", "๐Ÿ˜Ÿ Moderate", "๐Ÿ˜ฐ Severe", "๐Ÿ˜ฑ Overwhelming"],
            value="๐Ÿ˜Ÿ Moderate"
        )
        
        can_control = st.radio(
            "Can you control this?",
            ["โœ… Yes, I can take action", "โŒ No, it's out of my control"],
            horizontal=True
        )
        
        if st.button("๐Ÿ“ฆ Put in Worry Box", use_container_width=True):
            if worry_text:
                worry_box_col.insert_one({
                    "username": username,
                    "text": worry_text,
                    "intensity": worry_intensity,
                    "controllable": can_control,
                    "status": "active",
                    "created_at": datetime.datetime.utcnow(),
                    "resolved_at": None
                })
                st.success("โœ… Worry stored in your box. You can come back to it later.")
                st.rerun()
            else:
                st.warning("โš ๏ธ Please write your worry first")
    
    with col2:
        st.markdown("### ๐Ÿ’ก How it Works")
        st.info("""

        1. **Write** your worry down

        2. **Store** it in the box

        3. **Let go** for now

        4. **Revisit** later with fresh perspective

        5. **Resolve** or release it

        """)
        
        # Box visualization
        active_worries = worry_box_col.count_documents({
            "username": username,
            "status": "active"
        })
        
        st.markdown(
            f"""

            <div style='text-align: center; padding: 30px; 

                        background: linear-gradient(180deg, rgba(156,136,255,0.2) 0%, rgba(99,102,241,0.3) 100%);

                        border-radius: 15px; border: 3px solid #6366F1;'>

                <div style='font-size: 4rem;'>๐Ÿ“ฆ</div>

                <div style='font-size: 2rem; font-weight: bold; color: #4F46E5;'>{active_worries}</div>

                <div style='color: #666;'>active worries</div>

            </div>

            """,
            unsafe_allow_html=True
        )
    
    # View worries
    st.markdown("---")
    
    tab1, tab2, tab3 = st.tabs(["๐Ÿ“ฆ Active Worries", "โœ… Resolved", "๐Ÿ“Š Worry Insights"])
    
    with tab1:
        display_active_worries(username)
    
    with tab2:
        display_resolved_worries(username)
    
    with tab3:
        worry_insights(username)

def display_active_worries(username):
    st.markdown("### ๐Ÿ“ฆ Your Active Worries")
    
    worries = list(worry_box_col.find({
        "username": username,
        "status": "active"
    }).sort("created_at", -1))
    
    if not worries:
        st.success("๐ŸŽ‰ Your worry box is empty! That's great!")
        return
    
    for worry in worries:
        with st.expander(
            f"{worry['intensity'].split()[0]} โ€ข "
            f"{worry['created_at'].strftime('%b %d, %Y')} โ€ข "
            f"{worry['controllable'].split()[0]}"
        ):
            st.markdown(f"**Worry:** {worry['text']}")
            st.markdown(f"**Intensity:** {worry['intensity']}")
            st.markdown(f"**Can Control:** {worry['controllable']}")
            st.caption(f"Added {worry['created_at'].strftime('%B %d, %Y at %I:%M %p')}")
            
            # Action buttons
            col1, col2, col3 = st.columns(3)
            
            with col1:
                if st.button("โœ… Mark Resolved", key=f"resolve_{worry['_id']}"):
                    worry_box_col.update_one(
                        {"_id": worry["_id"]},
                        {
                            "$set": {
                                "status": "resolved",
                                "resolved_at": datetime.datetime.utcnow()
                            }
                        }
                    )
                    st.success("Worry resolved! ๐ŸŽ‰")
                    st.rerun()
            
            with col2:
                if st.button("๐Ÿ—‘๏ธ Delete", key=f"delete_{worry['_id']}"):
                    worry_box_col.delete_one({"_id": worry["_id"]})
                    st.rerun()
            
            with col3:
                # Suggest coping strategy
                if worry['controllable'].startswith("โœ…"):
                    st.info("๐Ÿ’ก Create an action plan!")
                else:
                    st.info("๐Ÿ’ก Practice acceptance")

def display_resolved_worries(username):
    st.markdown("### โœ… Resolved Worries")
    
    resolved = list(worry_box_col.find({
        "username": username,
        "status": "resolved"
    }).sort("resolved_at", -1).limit(20))
    
    if not resolved:
        st.info("No resolved worries yet. Keep working through your active worries!")
        return
    
    for worry in resolved:
        with st.expander(f"โœ… {worry['created_at'].strftime('%b %d')} โ†’ {worry['resolved_at'].strftime('%b %d')}"):
            st.markdown(f"**Worry:** {worry['text']}")
            
            days_to_resolve = (worry['resolved_at'] - worry['created_at']).days
            st.caption(f"Resolved in {days_to_resolve} day(s)")

def worry_insights(username):
    st.markdown("### ๐Ÿ“Š Worry Patterns & Insights")
    
    all_worries = list(worry_box_col.find({"username": username}))
    
    if not all_worries:
        st.info("Start using the worry box to see insights!")
        return
    
    df = pd.DataFrame(all_worries)
    
    # Metrics
    col1, col2, col3, col4 = st.columns(4)
    
    with col1:
        total = len(all_worries)
        st.metric("Total Worries", total)
    
    with col2:
        active = len([w for w in all_worries if w['status'] == 'active'])
        st.metric("Active", active)
    
    with col3:
        resolved = len([w for w in all_worries if w['status'] == 'resolved'])
        st.metric("Resolved", resolved)
    
    with col4:
        if resolved > 0:
            resolution_rate = (resolved / total) * 100
            st.metric("Resolution Rate", f"{resolution_rate:.0f}%")
    
    # Intensity distribution
    st.markdown("---")
    st.markdown("#### Worry Intensity Distribution")
    
    intensity_counts = df['intensity'].value_counts()
    
    fig_intensity = px.pie(
        values=intensity_counts.values,
        names=intensity_counts.index,
        title="Distribution of Worry Intensity"
    )
    st.plotly_chart(fig_intensity, use_container_width=True)
    
    # Controllable vs Uncontrollable
    st.markdown("#### Controllable vs Uncontrollable Worries")
    
    controllable_counts = df['controllable'].value_counts()
    
    col1, col2 = st.columns(2)
    
    with col1:
        can_control = sum([1 for w in all_worries if w['controllable'].startswith('โœ…')])
        cannot_control = sum([1 for w in all_worries if w['controllable'].startswith('โŒ')])
        
        st.metric("Can Control", can_control, help="Worries you can take action on")
        st.metric("Cannot Control", cannot_control, help="Worries outside your control")
    
    with col2:
        st.info("""

        **๐Ÿ’ก Insight:**

        

        Focus energy on controllable worries. 

        For uncontrollable ones, practice 

        acceptance and letting go.

        """)

# -------------------- MAIN PHASE 3 ROUTER --------------------
def phase3_main(username, page):
    """

    Main router for Phase 3 features

    

    Args:

        username: Current logged-in user

        page: Which page to display

    """
    
    if page == "๐ŸŽฏ Coping Plans":
        coping_plans_page(username)
    
    elif page == "๐Ÿ“š Resource Library":
        resource_library_page(username)
    
    elif page == "๐ŸŽฎ Interactive Tools":
        interactive_tools_page(username)

# -------------------- INTEGRATION INSTRUCTIONS --------------------
"""

HOW TO INTEGRATE PHASE 3 WITH YOUR MAIN APP:



1. Save this file as: phase3_interventions.py



2. Import in your final.py (at the top):

   

   import phase3_interventions as phase3



3. Add Phase 3 pages to sidebar navigation (in chat_page function):

   

   page = st.radio("๐Ÿ“ Navigate", [

       "๐Ÿ’ฌ Chat", 

       " virtual_chat",

       "๐Ÿ“Š Analytics", 

       "โ„น๏ธ Resources",

       "๐Ÿ—“๏ธ Mood Journal",

       "๐ŸŽฏ Goals",

       "๐Ÿ“š Exercises",

       "๐Ÿ† Achievements",

       "๐Ÿ”” Reminders",

       "๐ŸŽฏ Coping Plans",      # NEW - Phase 3

       "๐Ÿ“š Resource Library",  # NEW - Phase 3

       "๐ŸŽฎ Interactive Tools"  # NEW - Phase 3

   ])



4. Update routing in chat_page function:

   

   # Phase 3 routing

   if page in ["๐ŸŽฏ Coping Plans", "๐Ÿ“š Resource Library", "๐ŸŽฎ Interactive Tools"]:

       phase3.phase3_main(st.session_state.username, page)

   # Phase 2 routing

   elif page in ["๐Ÿ—“๏ธ Mood Journal", "๐ŸŽฏ Goals", "๐Ÿ“š Exercises", 

                 "๐Ÿ† Achievements", "๐Ÿ”” Reminders"]:

       phase2.phase2_main(st.session_state.username, page)

   # Original pages

   elif page == "๐Ÿ’ฌ Chat":

       chat_interface()

   elif page == "๐Ÿ“Š Analytics":

       analytics_page()

   else:

       resources_page()



PHASE 3 FEATURES INCLUDED:

โœ… Personalized Coping Plans (based on user data)

โœ… Custom Breathing Exercises

โœ… Daily Schedule Generator

โœ… Video Tutorial Library

โœ… Audio Guided Sessions

โœ… CBT Worksheets

โœ… Educational Articles

โœ… Mood Board Creator (visual expression)

โœ… Gratitude Jar (positivity building)

โœ… Worry Box (worry management)

โœ… Comprehensive insights and analytics



All features use your existing MongoDB database!

"""