File size: 65,091 Bytes
70e1ff0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b97e847
 
 
 
70e1ff0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b97e847
 
 
 
 
70e1ff0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b97e847
70e1ff0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b97e847
70e1ff0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b97e847
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
70e1ff0
 
 
b97e847
 
 
70e1ff0
 
b97e847
 
 
 
 
 
70e1ff0
 
 
 
b97e847
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
70e1ff0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b97e847
 
 
 
 
 
 
 
 
 
 
 
 
70e1ff0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b97e847
 
 
 
 
70e1ff0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b97e847
 
 
 
 
 
70e1ff0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b97e847
 
 
 
 
70e1ff0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b97e847
70e1ff0
 
b97e847
70e1ff0
 
 
 
 
 
 
 
b97e847
 
 
 
 
70e1ff0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b97e847
70e1ff0
 
 
 
 
 
b97e847
 
 
 
 
 
70e1ff0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
// Application State (will be populated from IndexedDB)
const state = {
    apiKey: "",
    systemPrompt: "You are a helpful assistant.",
    temperature: 1.0,
    maxTokens: 4096,
    topP: 1.0,
    frequencyPenalty: 0.0,
    presencePenalty: 0.0,
    selectedModel: "openai/gpt-oss-120b",
    reasoningEffort: "medium",
    autoShowReasoning: false,
    contextLimit: 100,
    theme: "light",
    // NOTE: state.messages is the in-memory context sent to API (trimmed to contextLimit)
    // Full conversation history is persisted in IndexedDB via conversationManager
    messages: [],
    isStreaming: false,
    abortController: null,
    lastUsage: null,
    totalCost: 0,
    isInitialLoad: true // Track if this is the first conversation load
};

// Model pricing (USD per 1M tokens) - OpenRouter prices
const MODEL_PRICING = {
    "openai/gpt-oss-20b": { input: 1.5, output: 6.0 },
    "openai/gpt-oss-120b": { input: 3.0, output: 12.0 }
};

// Calculate cost from usage
function calculateCost(usage, model) {
    const pricing = MODEL_PRICING[model];
    if (!pricing || !usage) return 0;

    const inputCost = ((usage.prompt_tokens || 0) / 1000000) * pricing.input;
    const outputCost = ((usage.completion_tokens || 0) / 1000000) * pricing.output;
    return inputCost + outputCost;
}

// DOM Elements
const elements = {
    sidebar: document.getElementById("sidebar"),
    sidebarOverlay: document.getElementById("sidebarOverlay"),
    settingsBtn: document.getElementById("settingsBtn"),
    toggleSidebar: document.getElementById("toggleSidebar"),
    newChatBtn: document.getElementById("newChatBtn"),
    settingsModal: document.getElementById("settingsModal"),
    closeModal: document.getElementById("closeModal"),
    saveSettings: document.getElementById("saveSettings"),
    clearSettings: document.getElementById("clearSettings"),
    themeToggle: document.getElementById("themeToggle"),
    themeText: document.getElementById("themeText"),
    chatMessages: document.getElementById("chatMessages"),
    messageInput: document.getElementById("messageInput"),
    sendBtn: document.getElementById("sendBtn"),
    modelCards: document.querySelectorAll(".model-card"),
    reasoningSection: document.getElementById("reasoningSection"),
    // Settings form elements
    apiKeyInput: document.getElementById("apiKey"),
    systemPromptInput: document.getElementById("systemPrompt"),
    temperatureInput: document.getElementById("temperature"),
    tempValue: document.getElementById("tempValue"),
    maxTokensInput: document.getElementById("maxTokens"),
    topPInput: document.getElementById("topP"),
    topPValue: document.getElementById("topPValue"),
    frequencyPenaltyInput: document.getElementById("frequencyPenalty"),
    freqValue: document.getElementById("freqValue"),
    presencePenaltyInput: document.getElementById("presencePenalty"),
    presValue: document.getElementById("presValue"),
    autoShowReasoningInput: document.getElementById("autoShowReasoning"),
    contextLimitInput: document.getElementById("contextLimit"),
    messageCounter: document.getElementById("messageCounter"),
    // New UI elements
    scrollToBottomBtn: document.getElementById("scrollToBottomBtn"),
    focusModeBtn: document.getElementById("focusModeBtn")
};

// NOTE: escapeHtml is defined in utils.js - use that global function

// Helper function to manage context window
function trimContextWindow() {
    // Keep only the last N messages (contextLimit = N pairs of user/assistant)
    const maxMessages = state.contextLimit * 2; // user + assistant pairs
    if (state.messages.length > maxMessages) {
        state.messages = state.messages.slice(-maxMessages);
    }
    updateMessageCounter();
}

// Update message counter display
function updateMessageCounter() {
    const messagePairs = Math.floor(state.messages.length / 2);
    const maxPairs = state.contextLimit;
    elements.messageCounter.textContent = `Messages: ${messagePairs} / ${maxPairs} pairs`;
}

// ========================================
// Conversation Management Functions
// ========================================

// Start a new conversation
async function startNewConversation() {
    try {
        // Reset session cost when starting new conversation
        state.totalCost = 0;
        state.lastUsage = null;
        updateTokenCounter();

        // Create and load new conversation (callback handles UI update)
        const convId = await conversationManager.createConversation("New Chat", state.selectedModel);
        await conversationManager.loadConversation(convId);
        showNotification("New conversation started", "success");
        return convId;
    } catch (error) {
        showNotification("Failed to create new conversation", "error");
        console.error(error);
    }
}

// Import a conversation from JSON file
async function importConversation() {
    try {
        const data = await showImportFilePicker();
        if (!data) return; // User cancelled or invalid file

        const convId = await conversationManager.importConversation(data);
        await conversationManager.loadConversation(convId);
        await conversationsUI.refresh();
        showNotification(`Imported "${data.conversation.title}"`, "success");
    } catch (error) {
        showNotification("Failed to import conversation: " + error.message, "error");
        console.error(error);
    }
}

// Load a conversation into the UI (called by onConversationChange callback)
function loadConversationIntoUI(conversation, messages) {
    // Reset session cost when switching conversations
    state.totalCost = 0;
    state.lastUsage = null;
    updateTokenCounter(false);

    // Clear and load messages
    elements.chatMessages.innerHTML = "";

    if (messages.length === 0) {
        elements.chatMessages.innerHTML = getWelcomeHTML();
        state.messages = [];
    } else {
        // Apply context limit: keep only the last N message pairs
        const maxMessages = state.contextLimit * 2;
        const trimmedMessages = messages.length > maxMessages ? messages.slice(-maxMessages) : messages;

        trimmedMessages.forEach(msg => {
            addMessage(msg.role, msg.content, msg.reasoning, msg.timestamp, msg.id);
        });
        state.messages = trimmedMessages.map(msg => ({
            role: msg.role,
            content: msg.content
        }));
    }

    // Update model if conversation uses different model
    if (conversation.model !== state.selectedModel) {
        selectModel(conversation.model);
    }

    updateMessageCounter();

    // Refresh conversation list to update active state (single call)
    conversationsUI.refresh();

    // Show notification when switching conversations (but not on initial load)
    if (!state.isInitialLoad && messages.length > 0) {
        const msgCount = Math.floor(messages.length / 2);
        showNotification(`Loaded "${conversation.title}" (${msgCount} messages)`, "info");
    }

    // Mark that initial load is complete
    state.isInitialLoad = false;
}

// Save current message to database
async function saveMessageToDB(role, content, reasoning = null) {
    if (!conversationManager.currentConversationId) {
        await startNewConversation();
    }

    try {
        await conversationManager.addMessage(conversationManager.currentConversationId, role, content, reasoning);

        // Auto-name conversation based on first user message
        const messages = await conversationManager.getMessages(conversationManager.currentConversationId);
        if (messages.length === 1 && role === "user") {
            await conversationManager.autoNameConversation(conversationManager.currentConversationId, content);
            await conversationsUI.refresh();
        }
    } catch (error) {
        console.error("Failed to save message:", error);
        showNotification("Warning: Message not saved to database", "warning");
        throw error; // Propagate error so caller knows save failed
    }
}

// Initialize App
async function init() {
    await loadSettingsFromDB();
    setupEventListeners();
    applyTheme();
    updateModelSelection();
    updateReasoningSection();
    checkApiKey();
    restoreFocusMode(); // Restore focus mode preference
    conversationsUI.init();
    await initializeConversations();
}

// Load settings from IndexedDB into state
async function loadSettingsFromDB() {
    const settings = await settingsManager.getAll();
    Object.assign(state, settings);
    loadSettingsToUI();
}

// Load settings from state to UI
function loadSettingsToUI() {
    elements.apiKeyInput.value = state.apiKey;
    elements.systemPromptInput.value = state.systemPrompt;
    elements.temperatureInput.value = state.temperature;
    elements.tempValue.textContent = state.temperature.toFixed(1);
    elements.maxTokensInput.value = state.maxTokens;
    elements.topPInput.value = state.topP;
    elements.topPValue.textContent = state.topP.toFixed(2);
    elements.frequencyPenaltyInput.value = state.frequencyPenalty;
    elements.freqValue.textContent = state.frequencyPenalty.toFixed(1);
    elements.presencePenaltyInput.value = state.presencePenalty;
    elements.presValue.textContent = state.presencePenalty.toFixed(1);
    elements.autoShowReasoningInput.checked = state.autoShowReasoning;
    elements.contextLimitInput.value = state.contextLimit;

    // Set reasoning effort
    const reasoningRadio = document.querySelector(`input[name="reasoning"][value="${state.reasoningEffort}"]`);
    if (reasoningRadio) reasoningRadio.checked = true;
}

// Initialize conversation system
async function initializeConversations() {
    // Set up callback: loadConversation() always triggers this
    conversationManager.onConversationChange = (conversation, messages) => {
        loadConversationIntoUI(conversation, messages);
    };

    // Load most recent conversation or create first one
    const allConversations = await conversationManager.getAllConversations();

    if (allConversations.length === 0) {
        await startNewConversation();
    } else {
        conversationManager.currentConversationId = allConversations[0].id;
        await conversationManager.loadConversation(allConversations[0].id);
    }
}

// Setup Event Listeners
function setupEventListeners() {
    // New Chat button
    elements.newChatBtn.addEventListener("click", async () => {
        await startNewConversation();
    });

    // Import Chat button
    document.getElementById("importConversationBtn").addEventListener("click", async () => {
        await importConversation();
    });

    // Settings modal
    elements.settingsBtn.addEventListener("click", openSettings);
    elements.closeModal.addEventListener("click", closeSettings);
    elements.saveSettings.addEventListener("click", saveSettings);
    elements.clearSettings.addEventListener("click", clearSettings);

    // Edit message modal
    document.getElementById("closeEditModal").addEventListener("click", closeEditModal);
    document.getElementById("cancelEditMessage").addEventListener("click", closeEditModal);
    document.getElementById("confirmEditMessage").addEventListener("click", confirmEditMessage);

    // Close edit modal on backdrop click
    document.getElementById("editMessageModal").addEventListener("click", e => {
        if (e.target.id === "editMessageModal") {
            closeEditModal();
        }
    });

    // Handle Ctrl+Enter in edit modal textarea
    document.getElementById("editMessageText").addEventListener("keydown", e => {
        if (e.key === "Enter" && (e.ctrlKey || e.metaKey)) {
            e.preventDefault();
            confirmEditMessage();
        }
        if (e.key === "Escape") {
            closeEditModal();
        }
    });

    // Click outside modal to close
    elements.settingsModal.addEventListener("click", e => {
        if (e.target === elements.settingsModal || e.target.classList.contains("modal-backdrop")) {
            closeSettings();
        }
    });

    // Theme toggle
    elements.themeToggle.addEventListener("click", toggleTheme);

    // Sidebar toggle (mobile)
    elements.toggleSidebar.addEventListener("click", e => {
        e.stopPropagation(); // Prevent click from bubbling
        const isOpen = elements.sidebar.classList.toggle("open");
        elements.sidebarOverlay.classList.toggle("active", isOpen);

        // Prevent body scroll when sidebar is open on mobile
        if (isOpen) {
            document.body.style.overflow = "hidden";
        } else {
            document.body.style.overflow = "";
        }
    });

    // Close sidebar when clicking on overlay
    elements.sidebarOverlay.addEventListener("click", () => {
        elements.sidebar.classList.remove("open");
        elements.sidebarOverlay.classList.remove("active");
        document.body.style.overflow = "";
    });

    // Close sidebar when clicking outside (mobile) - backup method
    document.addEventListener("click", e => {
        const sidebar = elements.sidebar;
        const toggleBtn = elements.toggleSidebar;

        // Check if sidebar is open and click is outside sidebar and toggle button
        if (sidebar.classList.contains("open") && !sidebar.contains(e.target) && !toggleBtn.contains(e.target)) {
            sidebar.classList.remove("open");
            elements.sidebarOverlay.classList.remove("active");
            document.body.style.overflow = "";
        }
    });

    // Prevent clicks inside sidebar from closing it
    elements.sidebar.addEventListener("click", e => {
        e.stopPropagation();
    });

    // Close sidebar with Escape key
    document.addEventListener("keydown", e => {
        if (e.key === "Escape" && elements.sidebar.classList.contains("open")) {
            elements.sidebar.classList.remove("open");
            elements.sidebarOverlay.classList.remove("active");
            document.body.style.overflow = "";
        }
    });

    // Model selection
    elements.modelCards.forEach(card => {
        card.addEventListener("click", () => {
            selectModel(card.dataset.model);
        });
    });

    // Reasoning effort
    document.querySelectorAll('input[name="reasoning"]').forEach(radio => {
        radio.addEventListener("change", async e => {
            state.reasoningEffort = e.target.value;
            await settingsManager.set("reasoningEffort", state.reasoningEffort);
        });
    });

    // Collapsible sidebar sections
    document.querySelectorAll(".section-toggle").forEach(toggle => {
        toggle.addEventListener("click", () => {
            const targetId = toggle.dataset.target;
            const content = document.getElementById(targetId);
            if (content) {
                toggle.classList.toggle("collapsed");
                content.classList.toggle("hidden");
            }
        });
    });

    // Range inputs
    elements.temperatureInput.addEventListener("input", e => {
        elements.tempValue.textContent = parseFloat(e.target.value).toFixed(1);
    });

    elements.topPInput.addEventListener("input", e => {
        elements.topPValue.textContent = parseFloat(e.target.value).toFixed(2);
    });

    elements.frequencyPenaltyInput.addEventListener("input", e => {
        elements.freqValue.textContent = parseFloat(e.target.value).toFixed(1);
    });

    elements.presencePenaltyInput.addEventListener("input", e => {
        elements.presValue.textContent = parseFloat(e.target.value).toFixed(1);
    });

    // System Prompt Library buttons
    document.querySelectorAll(".prompt-btn").forEach(btn => {
        btn.addEventListener("click", () => {
            const promptKey = btn.dataset.prompt;
            if (SYSTEM_PROMPTS[promptKey]) {
                elements.systemPromptInput.value = SYSTEM_PROMPTS[promptKey];
                showNotification(`Loaded "${btn.textContent}" prompt`, "success");
            }
        });
    });

    // Message input
    elements.messageInput.addEventListener("input", handleInputChange);
    elements.messageInput.addEventListener("keydown", e => {
        if (e.key === "Enter" && !e.shiftKey) {
            e.preventDefault();
            if (state.isStreaming) {
                stopStreaming();
            } else {
                sendMessage();
            }
        }
    });

    // Send button - initial setup
    updateSendButton();

    // Reset cost button
    const resetCostBtn = document.getElementById("resetCostBtn");
    if (resetCostBtn) {
        resetCostBtn.addEventListener("click", () => {
            state.totalCost = 0;
            state.lastUsage = null;
            updateTokenCounter();
            showNotification("Session cost reset", "success");
        });
    }

    // Keyboard shortcuts
    document.addEventListener("keydown", e => {
        // Ctrl/Cmd + K: New conversation
        if ((e.ctrlKey || e.metaKey) && e.key === "k") {
            e.preventDefault();
            startNewConversation();
        }
        // Ctrl/Cmd + Enter: Send message (when focused on input)
        if ((e.ctrlKey || e.metaKey) && e.key === "Enter" && document.activeElement === elements.messageInput) {
            e.preventDefault();
            if (!state.isStreaming) {
                sendMessage();
            }
        }
        // Ctrl/Cmd + B: Toggle focus mode
        if ((e.ctrlKey || e.metaKey) && e.key === "b") {
            e.preventDefault();
            toggleFocusMode();
        }
    });

    // Focus mode button
    if (elements.focusModeBtn) {
        elements.focusModeBtn.addEventListener("click", toggleFocusMode);
    }

    // Scroll to bottom button
    if (elements.scrollToBottomBtn) {
        elements.scrollToBottomBtn.addEventListener("click", scrollToBottom);
    }

    // Show/hide scroll-to-bottom button based on scroll position
    elements.chatMessages.addEventListener("scroll", handleChatScroll);

    // Warn user before closing tab if streaming is in progress
    window.addEventListener("beforeunload", e => {
        if (state.isStreaming) {
            e.preventDefault();
            e.returnValue = "A response is currently being generated. Are you sure you want to leave?";
            return e.returnValue;
        }
    });
}

// Debounce helper for performance
let resizeTimeout = null;

// Handle input change
function handleInputChange() {
    // Debounced auto-resize textarea
    if (resizeTimeout) clearTimeout(resizeTimeout);
    resizeTimeout = setTimeout(() => {
        elements.messageInput.style.height = "auto";
        elements.messageInput.style.height = elements.messageInput.scrollHeight + "px";
    }, 16); // ~60fps

    updateSendButton();
}

// ========================================
// Scroll to Bottom & Focus Mode
// ========================================

// Scroll to bottom of chat
function scrollToBottom() {
    elements.chatMessages.scrollTo({
        top: elements.chatMessages.scrollHeight,
        behavior: "smooth"
    });
}

// Handle chat scroll - show/hide scroll-to-bottom button
let scrollTimeout = null;
function handleChatScroll() {
    if (scrollTimeout) clearTimeout(scrollTimeout);
    scrollTimeout = setTimeout(() => {
        const { scrollTop, scrollHeight, clientHeight } = elements.chatMessages;
        const distanceFromBottom = scrollHeight - scrollTop - clientHeight;

        // Show button if user has scrolled up more than 200px from bottom
        if (elements.scrollToBottomBtn) {
            if (distanceFromBottom > 200) {
                elements.scrollToBottomBtn.classList.remove("hidden");
            } else {
                elements.scrollToBottomBtn.classList.add("hidden");
            }
        }
    }, 100);
}

// Toggle focus mode (hide/show sidebar on desktop)
function toggleFocusMode() {
    document.body.classList.toggle("focus-mode");
    const isFocusMode = document.body.classList.contains("focus-mode");

    // Save preference
    localStorage.setItem("focusMode", isFocusMode ? "true" : "false");

    // Show notification
    showNotification(isFocusMode ? "Focus mode enabled (Ctrl+B to exit)" : "Focus mode disabled", "info");
}

// Restore focus mode on load
function restoreFocusMode() {
    const savedFocusMode = localStorage.getItem("focusMode");
    if (savedFocusMode === "true") {
        document.body.classList.add("focus-mode");
    }
}

// Check API key
function checkApiKey() {
    if (!state.apiKey) {
        showNotification("Please configure your OpenRouter API key in settings", "warning");
    }
}

// Theme management
const THEMES = ["light", "dark", "midnight"];
const THEME_LABELS = {
    light: "Dark Mode",
    dark: "Midnight",
    midnight: "Light Mode"
};
const THEME_ICONS = {
    light: "moon", // Shows moon (click to go dark)
    dark: "sparkle", // Shows sparkle (click to go midnight)
    midnight: "sun" // Shows sun (click to go light)
};

function applyTheme() {
    document.documentElement.setAttribute("data-theme", state.theme);
    elements.themeText.textContent = THEME_LABELS[state.theme] || "Dark Mode";

    // Update icon visibility
    const btn = elements.themeToggle;
    btn.classList.remove("theme-light", "theme-dark", "theme-midnight");
    btn.classList.add(`theme-${state.theme}`);
}

async function toggleTheme() {
    const currentIndex = THEMES.indexOf(state.theme);
    const nextIndex = (currentIndex + 1) % THEMES.length;
    state.theme = THEMES[nextIndex];
    await settingsManager.set("theme", state.theme);
    applyTheme();
}

// Model selection
async function selectModel(modelId) {
    state.selectedModel = modelId;
    await settingsManager.set("selectedModel", modelId);
    updateModelSelection();
    updateReasoningSection();

    // Update current conversation's model in database
    if (conversationManager.currentConversationId) {
        conversationManager
            .updateConversationModel(conversationManager.currentConversationId, modelId)
            .catch(err => console.error("Failed to update conversation model:", err));
    }
}

function updateModelSelection() {
    elements.modelCards.forEach(card => {
        card.classList.toggle("active", card.dataset.model === state.selectedModel);
    });
}

function updateReasoningSection() {
    // Show reasoning section for GPT-OSS models (they support reasoning effort)
    const isGPTOSSModel = state.selectedModel.includes("gpt-oss");
    elements.reasoningSection.style.display = isGPTOSSModel ? "block" : "none";
}

// Settings modal
function openSettings() {
    elements.settingsModal.classList.remove("hidden");
    loadSettingsToUI();
}

function closeSettings() {
    elements.settingsModal.classList.add("hidden");
}

async function saveSettings() {
    state.apiKey = elements.apiKeyInput.value.trim();
    state.systemPrompt = elements.systemPromptInput.value.trim();
    state.temperature = parseFloat(elements.temperatureInput.value);
    state.maxTokens = parseInt(elements.maxTokensInput.value);
    state.topP = parseFloat(elements.topPInput.value);
    state.frequencyPenalty = parseFloat(elements.frequencyPenaltyInput.value);
    state.presencePenalty = parseFloat(elements.presencePenaltyInput.value);
    state.autoShowReasoning = elements.autoShowReasoningInput.checked;
    state.contextLimit = parseInt(elements.contextLimitInput.value);

    // Save to IndexedDB
    await settingsManager.saveAll({
        apiKey: state.apiKey,
        systemPrompt: state.systemPrompt,
        temperature: state.temperature,
        maxTokens: state.maxTokens,
        topP: state.topP,
        frequencyPenalty: state.frequencyPenalty,
        presencePenalty: state.presencePenalty,
        autoShowReasoning: state.autoShowReasoning,
        contextLimit: state.contextLimit
    });

    // Trim context if needed
    trimContextWindow();

    closeSettings();
    showNotification("Settings saved successfully", "success");
}

async function clearSettings() {
    if (confirm("Are you sure you want to reset all settings to defaults? (Conversations will be preserved)")) {
        // Reset settings in IndexedDB
        await settingsManager.resetAll();

        // Reset state to defaults
        Object.assign(state, DEFAULT_SETTINGS);

        loadSettingsToUI();
        applyTheme();
        updateModelSelection();
        updateReasoningSection();
        showNotification("Settings reset to defaults", "info");
    }
}

// Chat functions

// Chat functions
function getWelcomeHTML() {
    return `

        <div class="welcome-message">

            <img src="assets/images/open-models-gpt-oss-16x9.jpg" alt="GPT-OSS" class="welcome-image">

            <h2 class="welcome-title">⚡ Kai's GPT-OSS</h2>

            <p class="welcome-text">Chat with OpenAI's powerful models via OpenRouter API</p>

        </div>

    `;
}

function clearChat() {
    state.messages = [];
    elements.chatMessages.innerHTML = getWelcomeHTML();
}

function addMessage(role, content, reasoning = null, timestamp = null, messageId = null) {
    // Remove welcome message if exists
    const welcomeMsg = elements.chatMessages.querySelector(".welcome-message");
    if (welcomeMsg) {
        welcomeMsg.remove();
    }

    const messageDiv = document.createElement("div");
    messageDiv.className = `message ${role}`;
    if (messageId) messageDiv.dataset.messageId = messageId;

    const avatar = document.createElement("div");
    avatar.className = "message-avatar";
    avatar.textContent = role === "user" ? "U" : "AI";

    const contentDiv = document.createElement("div");
    contentDiv.className = "message-content";

    const textDiv = document.createElement("div");
    textDiv.className = "message-text";

    // Use marked.js for assistant messages, plain text for user
    if (role === "assistant" && typeof marked !== "undefined") {
        textDiv.innerHTML = marked.parse(content);
        wrapTablesForScroll(textDiv);
    } else {
        textDiv.textContent = content;
    }

    contentDiv.appendChild(textDiv);

    // Add reasoning section if available (for assistant messages)
    if (role === "assistant" && reasoning) {
        const reasoningToggle = document.createElement("button");
        reasoningToggle.className = "reasoning-toggle";
        reasoningToggle.innerHTML = `

            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">

                <polyline points="6 9 12 15 18 9"></polyline>

            </svg>

            <span>Show reasoning</span>

        `;

        const reasoningSection = document.createElement("div");
        reasoningSection.className = "reasoning-content";
        reasoningSection.innerHTML = `

            <div class="reasoning-header">

                <div class="reasoning-label">

                    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">

                        <circle cx="12" cy="12" r="10"></circle>

                        <path d="M9.09 9a3 3 0 0 1 5.83 1c0 2-3 3-3 3"></path>

                        <line x1="12" y1="17" x2="12.01" y2="17"></line>

                    </svg>

                    Reasoning Process

                </div>

                <button class="copy-reasoning-btn" title="Copy reasoning">

                    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">

                        <rect x="9" y="9" width="13" height="13" rx="2" ry="2"></rect>

                        <path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"></path>

                    </svg>

                    Copy

                </button>

            </div>

            <div class="reasoning-text">${escapeHtml(reasoning)}</div>

        `;

        // Copy reasoning button handler
        reasoningSection.querySelector(".copy-reasoning-btn").addEventListener("click", async () => {
            try {
                await navigator.clipboard.writeText(reasoning);
                showNotification("Reasoning copied", "success");
            } catch (err) {
                showNotification("Failed to copy", "error");
            }
        });

        // Toggle reasoning visibility
        reasoningToggle.addEventListener("click", () => {
            const isVisible = reasoningSection.classList.toggle("visible");
            reasoningToggle.classList.toggle("expanded");
            reasoningToggle.querySelector("span").textContent = isVisible ? "Hide reasoning" : "Show reasoning";
        });

        // Auto-show reasoning if option is enabled
        if (state.autoShowReasoning) {
            reasoningSection.classList.add("visible");
            reasoningToggle.classList.add("expanded");
            reasoningToggle.querySelector("span").textContent = "Hide reasoning";
        }

        // Insert reasoning BEFORE the message text (at the top)
        contentDiv.insertBefore(reasoningSection, textDiv);
        contentDiv.insertBefore(reasoningToggle, reasoningSection);
    }

    // Add message footer with timestamp and actions
    const footerDiv = document.createElement("div");
    footerDiv.className = "message-footer";

    const msgTime = timestamp ? new Date(timestamp) : new Date();
    const timeStr = msgTime.toLocaleString("en-US", {
        month: "short",
        day: "numeric",
        hour: "2-digit",
        minute: "2-digit"
    });

    // Different actions for user vs assistant messages
    const userActions = `

        <button class="msg-action-btn" data-action="edit" title="Edit">

            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">

                <path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"></path>

                <path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"></path>

            </svg>

        </button>

    `;

    const assistantActions = `

        <button class="msg-action-btn" data-action="regenerate" title="Regenerate">

            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">

                <polyline points="23 4 23 10 17 10"></polyline>

                <path d="M20.49 15a9 9 0 1 1-2.12-9.36L23 10"></path>

            </svg>

        </button>

    `;

    footerDiv.innerHTML = `

        <span class="message-time">${timeStr}</span>

        <div class="message-actions">

            ${role === "user" ? userActions : assistantActions}

            <button class="msg-action-btn" data-action="copy" title="Copy">

                <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">

                    <rect x="9" y="9" width="13" height="13" rx="2" ry="2"></rect>

                    <path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"></path>

                </svg>

            </button>

            <button class="msg-action-btn msg-action-delete" data-action="delete" title="Delete">

                <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">

                    <polyline points="3 6 5 6 21 6"></polyline>

                    <path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"></path>

                </svg>

            </button>

        </div>

    `;

    // Copy action
    footerDiv.querySelector('[data-action="copy"]').addEventListener("click", () => {
        navigator.clipboard
            .writeText(content)
            .then(() => {
                showNotification("Message copied", "success");
            })
            .catch(() => {
                showNotification("Failed to copy", "error");
            });
    });

    // Delete action
    footerDiv.querySelector('[data-action="delete"]').addEventListener("click", async () => {
        await deleteMessage(messageDiv, content, role);
    });

    // Edit action (user messages only)
    const editBtn = footerDiv.querySelector('[data-action="edit"]');
    if (editBtn) {
        editBtn.addEventListener("click", () => {
            editUserMessage(messageDiv, content);
        });
    }

    // Regenerate action (assistant messages only)
    const regenBtn = footerDiv.querySelector('[data-action="regenerate"]');
    if (regenBtn) {
        regenBtn.addEventListener("click", async () => {
            await regenerateResponse(messageDiv);
        });
    }

    contentDiv.appendChild(footerDiv);

    messageDiv.appendChild(avatar);
    messageDiv.appendChild(contentDiv);

    elements.chatMessages.appendChild(messageDiv);
    elements.chatMessages.scrollTop = elements.chatMessages.scrollHeight;

    return messageDiv;
}

// Delete a message from UI, state, and database
async function deleteMessage(messageDiv, content, role) {
    // Get the index of this message in the DOM to find correct state index
    const allMessages = Array.from(elements.chatMessages.querySelectorAll(".message"));
    const domIndex = allMessages.indexOf(messageDiv);

    // Find and remove from state.messages using index (more reliable than content matching)
    if (domIndex !== -1 && domIndex < state.messages.length) {
        state.messages.splice(domIndex, 1);
    } else {
        // Fallback to content matching if index fails
        const msgIndex = state.messages.findIndex(m => m.role === role && m.content === content);
        if (msgIndex !== -1) {
            state.messages.splice(msgIndex, 1);
        }
    }

    // Remove from database if we have a messageId
    const messageId = messageDiv.dataset.messageId;
    if (messageId) {
        try {
            await db.messages.delete(parseInt(messageId));
        } catch (error) {
            console.error("Failed to delete message from DB:", error);
        }
    }

    // Animate and remove from UI
    messageDiv.style.transition = "opacity 0.2s, transform 0.2s";
    messageDiv.style.opacity = "0";
    messageDiv.style.transform = "translateX(-20px)";
    setTimeout(() => {
        messageDiv.remove();
        updateTokenCounter();

        // Show welcome if no messages left
        if (elements.chatMessages.children.length === 0) {
            elements.chatMessages.innerHTML = getWelcomeHTML();
        }
    }, 200);

    showNotification("Message deleted", "success");
}

// State for edit modal
let editMessageState = {
    messageDiv: null,
    originalContent: ""
};

// Show edit message modal
function showEditModal(messageDiv, originalContent) {
    editMessageState.messageDiv = messageDiv;
    editMessageState.originalContent = originalContent;

    const modal = document.getElementById("editMessageModal");
    const textarea = document.getElementById("editMessageText");

    textarea.value = originalContent;
    modal.classList.remove("hidden");

    // Focus and select text
    setTimeout(() => {
        textarea.focus();
        textarea.setSelectionRange(textarea.value.length, textarea.value.length);
    }, 100);
}

// Close edit message modal
function closeEditModal() {
    const modal = document.getElementById("editMessageModal");
    modal.classList.add("hidden");
    editMessageState.messageDiv = null;
    editMessageState.originalContent = "";
}

// Confirm edit and regenerate
function confirmEditMessage() {
    try {
        const textarea = document.getElementById("editMessageText");
        const newContent = textarea.value.trim();

        if (!newContent || newContent === editMessageState.originalContent) {
            closeEditModal();
            return;
        }

        const messageDiv = editMessageState.messageDiv;
        const originalContent = editMessageState.originalContent;

        closeEditModal();

        // Find message index in state
        const msgIndex = state.messages.findIndex(m => m.role === "user" && m.content === originalContent);
        if (msgIndex === -1) return;

        // Remove this message and all following messages from state
        state.messages = state.messages.slice(0, msgIndex);

        // Remove this message and all following messages from UI
        let current = messageDiv;
        while (current) {
            const next = current.nextElementSibling;
            current.remove();
            current = next;
        }

        // Delete from database (this message and all after it)
        const messageId = messageDiv.dataset.messageId;
        if (messageId && conversationManager.currentConversationId) {
            db.messages
                .where("conversationId")
                .equals(conversationManager.currentConversationId)
                .and(m => m.id >= parseInt(messageId))
                .delete()
                .catch(e => console.error("Failed to delete messages from DB:", e));
        }

        // Set the new message in input and send
        elements.messageInput.value = newContent;
        sendMessage();
    } catch (error) {
        console.error("Error in confirmEditMessage:", error);
        showNotification("Failed to edit message", "error");
        closeEditModal();
    }
}

// Edit user message and regenerate response
function editUserMessage(messageDiv, originalContent) {
    if (state.isStreaming) {
        showNotification("Cannot edit while generating", "warning");
        return;
    }

    showEditModal(messageDiv, originalContent);
}

// Regenerate the last assistant response
async function regenerateResponse(messageDiv) {
    if (state.isStreaming) {
        showNotification("Cannot regenerate while generating", "warning");
        return;
    }

    // Find the content of this assistant message
    const textDiv = messageDiv.querySelector(".message-text");
    if (!textDiv) return;

    // Find message index in state
    const msgIndex = state.messages.findLastIndex(m => m.role === "assistant");
    if (msgIndex === -1) return;

    // Remove assistant message from state
    state.messages = state.messages.slice(0, msgIndex);

    // Remove from UI
    messageDiv.style.transition = "opacity 0.2s, transform 0.2s";
    messageDiv.style.opacity = "0";
    messageDiv.style.transform = "translateX(-20px)";

    await new Promise(resolve => setTimeout(resolve, 200));
    messageDiv.remove();

    // Delete from database
    const messageId = messageDiv.dataset.messageId;
    if (messageId) {
        try {
            await db.messages.delete(parseInt(messageId));
        } catch (error) {
            console.error("Failed to delete message from DB:", error);
        }
    }

    // Regenerate: create new streaming message and call API
    const { messageDiv: newMsgDiv, textDiv: newTextDiv, contentDiv } = createStreamingMessage();
    state.isStreaming = true;
    updateSendButton();

    let fullContent = "";
    let reasoning = null;

    try {
        await callOpenRouterStreaming(state.messages, chunk => {
            if (chunk.content) {
                fullContent += chunk.content;
                updateStreamingMessage(newTextDiv, fullContent);
            }
            if (chunk.reasoning) reasoning = chunk.reasoning;
            if (chunk.usage) {
                state.lastUsage = chunk.usage;
                updateTokenCounter();
            }
        });

        if (fullContent) {
            finalizeStreamingMessage(
                newMsgDiv,
                newTextDiv,
                contentDiv,
                fullContent,
                reasoning,
                new Date().toISOString()
            );
            state.messages.push({ role: "assistant", content: fullContent });

            // Add cost for this regenerated response
            if (state.lastUsage) {
                updateTokenCounter(true);
            }

            try {
                await saveMessageToDB("assistant", fullContent, reasoning);
            } catch (error) {}

            trimContextWindow();
        }
    } catch (error) {
        if (error.name === "AbortError") {
            if (fullContent) {
                finalizeStreamingMessage(
                    newMsgDiv,
                    newTextDiv,
                    contentDiv,
                    fullContent + "\n\n*[Generation stopped]*",
                    reasoning,
                    new Date().toISOString()
                );
                state.messages.push({ role: "assistant", content: fullContent });
            } else {
                newMsgDiv.remove();
            }
        } else {
            newMsgDiv.remove();
            showNotification(error.message || "Failed to regenerate", "error");
        }
    } finally {
        state.isStreaming = false;
        state.abortController = null;
        updateSendButton();
    }
}
function addLoadingMessage() {
    const messageDiv = document.createElement("div");
    messageDiv.className = "message assistant loading";
    messageDiv.id = "loading-message";

    const avatar = document.createElement("div");
    avatar.className = "message-avatar";
    avatar.textContent = "AI";

    const contentDiv = document.createElement("div");
    contentDiv.className = "message-content";

    const loadingDiv = document.createElement("div");
    loadingDiv.className = "message-loading";
    loadingDiv.innerHTML =
        '<div class="loading-dot"></div><div class="loading-dot"></div><div class="loading-dot"></div>';

    contentDiv.appendChild(loadingDiv);
    messageDiv.appendChild(avatar);
    messageDiv.appendChild(contentDiv);

    elements.chatMessages.appendChild(messageDiv);
    elements.chatMessages.scrollTop = elements.chatMessages.scrollHeight;

    return messageDiv;
}

function removeLoadingMessage() {
    const loadingMsg = document.getElementById("loading-message");
    if (loadingMsg) {
        loadingMsg.remove();
    }
}

// Create streaming message element
function createStreamingMessage() {
    const welcomeMsg = elements.chatMessages.querySelector(".welcome-message");
    if (welcomeMsg) welcomeMsg.remove();

    const messageDiv = document.createElement("div");
    messageDiv.className = "message assistant streaming";
    messageDiv.id = "streaming-message";

    const avatar = document.createElement("div");
    avatar.className = "message-avatar";
    avatar.textContent = "AI";

    const contentDiv = document.createElement("div");
    contentDiv.className = "message-content";

    const textDiv = document.createElement("div");
    textDiv.className = "message-text";
    textDiv.innerHTML = '<span class="streaming-cursor"></span>';

    contentDiv.appendChild(textDiv);
    messageDiv.appendChild(avatar);
    messageDiv.appendChild(contentDiv);

    elements.chatMessages.appendChild(messageDiv);
    elements.chatMessages.scrollTop = elements.chatMessages.scrollHeight;

    return { messageDiv, textDiv, contentDiv };
}

// Update streaming message content
function updateStreamingMessage(textDiv, content) {
    if (typeof marked !== "undefined") {
        textDiv.innerHTML = marked.parse(content) + '<span class="streaming-cursor"></span>';
    } else {
        textDiv.textContent = content;
    }
    elements.chatMessages.scrollTop = elements.chatMessages.scrollHeight;
}

// Finalize streaming message (convert to normal message)
function finalizeStreamingMessage(messageDiv, textDiv, contentDiv, content, reasoning, timestamp) {
    messageDiv.classList.remove("streaming");
    messageDiv.id = "";

    // Remove cursor
    const cursor = textDiv.querySelector(".streaming-cursor");
    if (cursor) cursor.remove();

    // Re-render with marked
    if (typeof marked !== "undefined") {
        textDiv.innerHTML = marked.parse(content);
        wrapTablesForScroll(textDiv);
    }

    // Add reasoning if available
    if (reasoning) {
        const reasoningToggle = document.createElement("button");
        reasoningToggle.className = "reasoning-toggle";
        reasoningToggle.innerHTML = `

            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">

                <polyline points="6 9 12 15 18 9"></polyline>

            </svg>

            <span>Show reasoning</span>

        `;

        const reasoningSection = document.createElement("div");
        reasoningSection.className = "reasoning-content";
        reasoningSection.innerHTML = `

            <div class="reasoning-header">

                <div class="reasoning-label">

                    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">

                        <circle cx="12" cy="12" r="10"></circle>

                        <path d="M9.09 9a3 3 0 0 1 5.83 1c0 2-3 3-3 3"></path>

                        <line x1="12" y1="17" x2="12.01" y2="17"></line>

                    </svg>

                    Reasoning Process

                </div>

                <button class="copy-reasoning-btn" title="Copy reasoning">

                    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">

                        <rect x="9" y="9" width="13" height="13" rx="2" ry="2"></rect>

                        <path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"></path>

                    </svg>

                    Copy

                </button>

            </div>

            <div class="reasoning-text">${escapeHtml(reasoning)}</div>

        `;

        // Copy reasoning button handler
        reasoningSection.querySelector(".copy-reasoning-btn").addEventListener("click", async () => {
            try {
                await navigator.clipboard.writeText(reasoning);
                showNotification("Reasoning copied", "success");
            } catch (err) {
                showNotification("Failed to copy", "error");
            }
        });

        reasoningToggle.addEventListener("click", () => {
            const isVisible = reasoningSection.classList.toggle("visible");
            reasoningToggle.classList.toggle("expanded");
            reasoningToggle.querySelector("span").textContent = isVisible ? "Hide reasoning" : "Show reasoning";
        });

        if (state.autoShowReasoning) {
            reasoningSection.classList.add("visible");
            reasoningToggle.classList.add("expanded");
            reasoningToggle.querySelector("span").textContent = "Hide reasoning";
        }

        contentDiv.insertBefore(reasoningSection, textDiv);
        contentDiv.insertBefore(reasoningToggle, reasoningSection);
    }

    // Add footer
    const footerDiv = document.createElement("div");
    footerDiv.className = "message-footer";
    const msgTime = timestamp ? new Date(timestamp) : new Date();
    const timeStr = msgTime.toLocaleString("en-US", {
        month: "short",
        day: "numeric",
        hour: "2-digit",
        minute: "2-digit"
    });

    footerDiv.innerHTML = `

        <span class="message-time">${timeStr}</span>

        <div class="message-actions">

            <button class="msg-action-btn" data-action="regenerate" title="Regenerate">

                <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">

                    <polyline points="23 4 23 10 17 10"></polyline>

                    <path d="M20.49 15a9 9 0 1 1-2.12-9.36L23 10"></path>

                </svg>

            </button>

            <button class="msg-action-btn" data-action="copy" title="Copy">

                <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">

                    <rect x="9" y="9" width="13" height="13" rx="2" ry="2"></rect>

                    <path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"></path>

                </svg>

            </button>

            <button class="msg-action-btn msg-action-delete" data-action="delete" title="Delete">

                <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">

                    <polyline points="3 6 5 6 21 6"></polyline>

                    <path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"></path>

                </svg>

            </button>

        </div>

    `;

    // Regenerate button handler
    footerDiv.querySelector('[data-action="regenerate"]').addEventListener("click", async () => {
        await regenerateResponse(messageDiv);
    });

    footerDiv.querySelector('[data-action="copy"]').addEventListener("click", () => {
        navigator.clipboard
            .writeText(content)
            .then(() => {
                showNotification("Message copied", "success");
            })
            .catch(() => {
                showNotification("Failed to copy", "error");
            });
    });

    footerDiv.querySelector('[data-action="delete"]').addEventListener("click", async () => {
        await deleteMessage(messageDiv, content, "assistant");
    });

    contentDiv.appendChild(footerDiv);
}

// Stop streaming
function stopStreaming() {
    if (state.abortController) {
        state.abortController.abort();
        state.abortController = null;
    }
}

async function sendMessage() {
    const message = elements.messageInput.value.trim();
    if (!message || state.isStreaming) return;

    if (!state.apiKey) {
        showNotification("Please configure your API key first", "error");
        openSettings();
        return;
    }

    // Add user message
    addMessage("user", message);
    state.messages.push({ role: "user", content: message });
    updateMessageCounter();

    // Save user message to database
    try {
        await saveMessageToDB("user", message);
    } catch (error) {
        // Continue anyway - message is in UI and state
        console.warn("User message not saved to DB, but continuing...");
    }

    // Clear input
    elements.messageInput.value = "";
    elements.messageInput.style.height = "auto";
    handleInputChange();

    // Create streaming message
    const { messageDiv, textDiv, contentDiv } = createStreamingMessage();
    state.isStreaming = true;
    updateSendButton();

    let fullContent = "";
    let reasoning = null;

    try {
        await callOpenRouterStreaming(state.messages, chunk => {
            // Handle content chunks
            if (chunk.content) {
                fullContent += chunk.content;
                updateStreamingMessage(textDiv, fullContent);
            }
            // Handle reasoning
            if (chunk.reasoning) {
                reasoning = chunk.reasoning;
            }
            // Handle usage stats (display only, don't add cost yet)
            if (chunk.usage) {
                state.lastUsage = chunk.usage;
                updateTokenCounter(false);
            }
        });

        // Finalize message
        if (fullContent) {
            finalizeStreamingMessage(messageDiv, textDiv, contentDiv, fullContent, reasoning, new Date().toISOString());
            state.messages.push({ role: "assistant", content: fullContent });

            // Now add the cost for this complete response
            if (state.lastUsage) {
                updateTokenCounter(true);
            }

            // Save to database
            try {
                await saveMessageToDB("assistant", fullContent, reasoning);
            } catch (error) {
                console.warn("Assistant message not saved to DB");
            }

            trimContextWindow();
        }
    } catch (error) {
        if (error.name === "AbortError") {
            // User cancelled - keep partial content if any
            if (fullContent) {
                finalizeStreamingMessage(
                    messageDiv,
                    textDiv,
                    contentDiv,
                    fullContent + "\n\n*[Generation stopped]*",
                    reasoning,
                    new Date().toISOString()
                );
                state.messages.push({ role: "assistant", content: fullContent });
                try {
                    await saveMessageToDB("assistant", fullContent, reasoning);
                } catch (e) {}
            } else {
                messageDiv.remove();
            }
            showNotification("Generation stopped", "info");
        } else {
            messageDiv.remove();
            showNotification(error.message || "Failed to get response", "error");
            console.error("Error:", error);
        }
    } finally {
        state.isStreaming = false;
        state.abortController = null;
        updateSendButton();
    }
}

// Update send button state (send vs stop)
function updateSendButton() {
    const hasText = elements.messageInput.value.trim().length > 0;

    if (state.isStreaming) {
        elements.sendBtn.innerHTML = `

            <svg width="20" height="20" viewBox="0 0 24 24" fill="currentColor">

                <rect x="6" y="6" width="12" height="12" rx="2"></rect>

            </svg>

        `;
        elements.sendBtn.disabled = false;
        elements.sendBtn.classList.add("stop-btn");
        elements.sendBtn.onclick = stopStreaming;
    } else {
        elements.sendBtn.innerHTML = `

            <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">

                <line x1="22" y1="2" x2="11" y2="13"></line>

                <polygon points="22 2 15 22 11 13 2 9 22 2"></polygon>

            </svg>

        `;
        elements.sendBtn.disabled = !hasText;
        elements.sendBtn.classList.remove("stop-btn");
        elements.sendBtn.onclick = sendMessage;
    }
}

// Update token counter display
function updateTokenCounter(addCost = false) {
    const sessionCostEl = document.getElementById("sessionCostDisplay");
    const tokenUsageEl = document.getElementById("tokenUsageDisplay");

    if (state.lastUsage) {
        const input = state.lastUsage.prompt_tokens || 0;
        const output = state.lastUsage.completion_tokens || 0;

        // Only add cost when explicitly requested (after a complete response)
        if (addCost) {
            const lastCost = calculateCost(state.lastUsage, state.selectedModel);
            state.totalCost += lastCost;
        }

        const costStr =
            state.totalCost < 0.01 ? `${(state.totalCost * 100).toFixed(2)}¢` : `$${state.totalCost.toFixed(4)}`;

        // Update sidebar cost display
        if (sessionCostEl) {
            sessionCostEl.textContent =
                state.totalCost < 0.01 ? `${(state.totalCost * 100).toFixed(2)}¢` : `$${state.totalCost.toFixed(4)}`;
        }
        if (tokenUsageEl) {
            tokenUsageEl.textContent = `Last: ${input} in → ${output} out`;
        }

        // Update message counter with compact cost badge
        elements.messageCounter.innerHTML = `

            <span style="display: flex; align-items: center; gap: 6px;">

                <span>📊 ${input}${output}</span>

                <span class="cost-badge">${costStr}</span>

            </span>

        `;
    } else {
        const messagePairs = Math.floor(state.messages.length / 2);
        elements.messageCounter.textContent = `Messages: ${messagePairs} / ${state.contextLimit} pairs`;
    }
}

async function callOpenRouterStreaming(messages, onChunk, retryCount = 0) {
    const MAX_RETRIES = 2;
    const apiUrl = "https://openrouter.ai/api/v1/chat/completions";

    // Prepare messages with system prompt
    const requestMessages = [{ role: "system", content: state.systemPrompt }, ...messages];

    const requestBody = {
        model: state.selectedModel,
        messages: requestMessages,
        temperature: state.temperature,
        max_tokens: state.maxTokens,
        top_p: state.topP,
        frequency_penalty: state.frequencyPenalty,
        presence_penalty: state.presencePenalty,
        stream: true
    };

    // Add reasoning config for GPT-OSS models
    if (state.selectedModel.includes("gpt-oss")) {
        requestBody.reasoning = {
            effort: state.reasoningEffort
        };
    }

    state.abortController = new AbortController();

    let response;
    try {
        response = await fetch(apiUrl, {
            method: "POST",
            headers: {
                "Content-Type": "application/json",
                Authorization: `Bearer ${state.apiKey}`,
                "HTTP-Referer": window.location.origin,
                "X-Title": "GPT-OSS Demo"
            },
            body: JSON.stringify(requestBody),
            signal: state.abortController.signal
        });
    } catch (error) {
        // Network error (offline, DNS failure, CORS, etc.)
        if (error.name === "AbortError") throw error;

        if (retryCount < MAX_RETRIES) {
            showNotification(`Connection failed. Retrying... (${retryCount + 1}/${MAX_RETRIES})`, "warning");
            await new Promise(r => setTimeout(r, 1000 * (retryCount + 1))); // Exponential backoff
            return callOpenRouterStreaming(messages, onChunk, retryCount + 1);
        }

        // Final failure
        if (!navigator.onLine) {
            throw new Error("You are offline. Please check your internet connection.");
        }
        throw new Error("Network error. Please check your connection and try again.");
    }

    if (!response.ok) {
        let errorMessage = `HTTP error! status: ${response.status}`;
        try {
            const error = await response.json();
            errorMessage = error.error?.message || errorMessage;

            // Provide helpful messages for common errors
            if (response.status === 401) {
                errorMessage = "Invalid API key. Please check your settings.";
            } else if (response.status === 429) {
                errorMessage = "Rate limit exceeded. Please wait a moment and try again.";
            } else if (response.status === 503) {
                errorMessage = "Service temporarily unavailable. Please try again later.";
            }
        } catch (e) {
            // Failed to parse error response
        }
        throw new Error(errorMessage);
    }

    const reader = response.body.getReader();
    const decoder = new TextDecoder();
    let buffer = "";
    let reasoning = null;

    while (true) {
        const { done, value } = await reader.read();
        if (done) break;

        buffer += decoder.decode(value, { stream: true });
        const lines = buffer.split("\n");
        buffer = lines.pop() || "";

        for (const line of lines) {
            if (line.startsWith("data: ")) {
                const data = line.slice(6);
                if (data === "[DONE]") {
                    if (reasoning) onChunk({ reasoning });
                    return;
                }

                try {
                    const parsed = JSON.parse(data);
                    const delta = parsed.choices?.[0]?.delta;

                    if (delta?.content) {
                        onChunk({ content: delta.content });
                    }

                    // Handle reasoning from delta - prefer reasoning_details over reasoning
                    // to avoid duplication (some models send both)
                    if (delta?.reasoning_details) {
                        const texts = delta.reasoning_details
                            .filter(r => r.type === "reasoning.text" || r.type === "reasoning.summary")
                            .map(r => r.text || r.summary)
                            .filter(Boolean);
                        if (texts.length) {
                            reasoning = (reasoning || "") + texts.join("\n");
                        }
                    } else if (delta?.reasoning) {
                        // Fallback to reasoning only if reasoning_details is not present
                        reasoning = (reasoning || "") + delta.reasoning;
                    }

                    // Usage stats (usually in final chunk)
                    if (parsed.usage) {
                        onChunk({ usage: parsed.usage });
                    }
                } catch (e) {
                    // Skip invalid JSON
                }
            }
        }
    }

    if (reasoning) onChunk({ reasoning });
}

// Notification system
function showNotification(message, type = "info") {
    // Remove existing notifications
    const existing = document.querySelector(".notification");
    if (existing) existing.remove();

    const notification = document.createElement("div");
    notification.className = `notification notification-${type}`;
    notification.style.cssText = `

        position: fixed;

        top: 20px;

        right: 20px;

        padding: 16px 20px;

        background-color: ${

            type === "error"

                ? "var(--color-danger)"

                : type === "success"

                  ? "var(--color-success)"

                  : type === "warning"

                    ? "#ff9e6c"

                    : "var(--color-primary)"

        };

        color: white;

        border-radius: 8px;

        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);

        z-index: 10000;

        animation: slideInRight 0.3s ease;

        max-width: 400px;

        font-size: 14px;

        font-weight: 500;

    `;
    notification.textContent = message;

    document.body.appendChild(notification);

    setTimeout(() => {
        notification.style.animation = "slideOutRight 0.3s ease";
        setTimeout(() => notification.remove(), 300);
    }, 3000);
}

// Add CSS for notifications
const style = document.createElement("style");
style.textContent = `

    @keyframes slideInRight {

        from {

            opacity: 0;

            transform: translateX(100px);

        }

        to {

            opacity: 1;

            transform: translateX(0);

        }

    }



    @keyframes slideOutRight {

        from {

            opacity: 1;

            transform: translateX(0);

        }

        to {

            opacity: 0;

            transform: translateX(100px);

        }

    }

`;
document.head.appendChild(style);

// ========================================
// About Modal — Made with 💙 by Kai ⚡
// ========================================

function setupAboutModal() {
    const aboutModal = document.getElementById("aboutModal");
    const closeAboutModal = document.getElementById("closeAboutModal");
    const btnAbout = document.getElementById("btn-about");

    if (!aboutModal) return;

    function openAboutModal() {
        aboutModal.classList.remove("hidden");
        document.body.style.overflow = "hidden";
    }

    function closeAboutModalFn() {
        aboutModal.classList.add("hidden");
        document.body.style.overflow = "";
    }

    // Event listeners
    if (btnAbout)
        btnAbout.addEventListener("click", e => {
            e.preventDefault();
            openAboutModal();
        });
    if (closeAboutModal) closeAboutModal.addEventListener("click", closeAboutModalFn);

    // Close on overlay click
    aboutModal.addEventListener("click", e => {
        if (e.target === aboutModal) closeAboutModalFn();
    });

    // Close on Escape key
    document.addEventListener("keydown", e => {
        if (e.key === "Escape" && !aboutModal.classList.contains("hidden")) {
            closeAboutModalFn();
        }
    });
}

// Initialize app when DOM is ready
if (document.readyState === "loading") {
    document.addEventListener("DOMContentLoaded", () => {
        init();
        setupAboutModal();
    });
} else {
    init();
    setupAboutModal();
}