File size: 53,647 Bytes
d02cadc
98cd950
 
 
 
d02cadc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
98cd950
 
 
 
 
 
 
 
 
 
 
 
 
 
790eee5
 
 
 
98cd950
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
790eee5
 
 
 
 
 
 
98cd950
 
 
d02cadc
 
 
98cd950
 
 
 
 
 
 
 
 
 
 
 
790eee5
 
 
 
 
98cd950
 
 
 
 
 
 
 
 
790eee5
 
98cd950
 
 
 
 
 
 
 
 
 
790eee5
 
 
 
 
 
 
98cd950
 
 
 
 
 
 
 
790eee5
 
 
 
 
98cd950
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
790eee5
 
98cd950
 
 
 
 
 
 
 
 
790eee5
 
98cd950
 
 
 
 
 
 
 
 
 
 
 
 
 
d02cadc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
98cd950
 
 
 
 
 
 
 
 
6c7859a
98cd950
 
 
6c7859a
 
98cd950
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6c7859a
 
 
 
 
 
98cd950
 
6c7859a
 
 
98cd950
 
 
 
 
 
 
790eee5
 
 
 
 
 
98cd950
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
790eee5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
98cd950
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c248ea4
 
 
 
 
98cd950
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d02cadc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6c7859a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
790eee5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
98cd950
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
790eee5
 
 
98cd950
 
790eee5
98cd950
790eee5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
98cd950
790eee5
 
98cd950
790eee5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
98cd950
790eee5
 
 
 
 
 
98cd950
 
 
790eee5
98cd950
790eee5
 
98cd950
 
790eee5
98cd950
 
790eee5
 
 
 
 
 
 
 
 
 
 
 
 
98cd950
 
 
 
 
 
 
 
 
 
 
 
d02cadc
98cd950
 
 
 
 
 
 
 
 
 
 
 
d02cadc
98cd950
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
790eee5
98cd950
 
 
 
790eee5
 
 
 
 
 
 
98cd950
790eee5
 
 
98cd950
790eee5
98cd950
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
790eee5
98cd950
790eee5
 
98cd950
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
790eee5
 
 
98cd950
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
790eee5
 
98cd950
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
790eee5
98cd950
790eee5
 
98cd950
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6c7859a
98cd950
6c7859a
98cd950
 
 
6c7859a
98cd950
 
 
 
 
 
6c7859a
98cd950
 
 
6c7859a
98cd950
 
 
6c7859a
98cd950
 
 
6c7859a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
98cd950
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
790eee5
 
 
 
 
 
98cd950
 
 
 
 
 
 
 
 
 
 
 
 
 
 
790eee5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c248ea4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
98cd950
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d02cadc
98cd950
 
d02cadc
98cd950
 
790eee5
 
 
 
 
 
 
98cd950
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
ο»Ώ/* ============================================

   IVY'S RSS HUB β€” Main Application

   Orchestrates the RSS feed aggregator

   ============================================ */

/**

 * Shared Utilities β€” Used by both App and Sidebar

 * Avoids code duplication across modules

 */
window.IvyUtils = {
    /**

     * Escape HTML to prevent XSS

     */
    escapeHtml(text) {
        if (!text) return "";
        const div = document.createElement("div");
        div.textContent = text;
        return div.innerHTML;
    },

    /**

     * Escape text for use in HTML attributes

     */
    escapeAttr(text) {
        if (!text) return "";
        return text
            .replace(/&/g, "&")
            .replace(/"/g, """)
            .replace(/'/g, "'")
            .replace(/</g, "&lt;")
            .replace(/>/g, "&gt;");
    },

    /**

     * Truncate text with ellipsis

     */
    truncate(text, maxLength) {
        if (!text || text.length <= maxLength) return text;
        return text.substring(0, maxLength) + "...";
    }
};

/**

 * RSSHub Application

 */
class RSSHubApp {
    constructor() {
        // Initialize parser
        this.parser = new RSSParser();

        // State
        this.feeds = [];
        this.feedResults = [];
        this.currentCategory = "all";
        this.currentLang = "all"; // Language filter: "all", "en", "fr"
        this.settings = this.loadSettings();
        this.isRefreshing = false; // Prevent double-refresh race conditions
        this.autoRefreshTimer = null; // Auto-refresh interval timer
        this.nextRefreshTime = null; // Timestamp of next auto-refresh
        this.countdownTimer = null; // Countdown display timer

        // DOM Elements
        this.elements = {
            feedsContainer: document.getElementById("feeds-container"),
            statusText: document.getElementById("status-text"),
            statusTime: document.getElementById("status-time"),
            btnRefresh: document.getElementById("btn-refresh"),
            btnTheme: document.getElementById("btn-theme"),
            btnSettings: document.getElementById("btn-settings"),
            btnAbout: document.getElementById("btn-about"),
            modalAbout: document.getElementById("modal-about"),
            modalSettings: document.getElementById("modal-settings"),
            modalCloseAbout: document.getElementById("modal-close-about"),
            modalCloseSettings: document.getElementById("modal-close-settings"),
            sourcesList: document.getElementById("sources-list"),
            navButtons: document.querySelectorAll(".nav-btn"),
            langButtons: document.querySelectorAll(".lang-btn"),
            sidebar: document.getElementById("sidebar")
        };

        // Initialize theme
        this.initTheme();

        // Initialize
        this.init();
    }

    /**

     * Initialize theme from localStorage or system preference

     */
    initTheme() {
        const savedTheme = localStorage.getItem("ivy-rss-hub-theme");

        if (savedTheme) {
            // User has a saved preference
            document.documentElement.setAttribute("data-theme", savedTheme);
            this.updateThemeIcon(savedTheme);
        } else {
            // Use system preference (CSS handles it, but we update the icon)
            const prefersDark = window.matchMedia("(prefers-color-scheme: dark)").matches;
            this.updateThemeIcon(prefersDark ? "dark" : "light");
        }

        // Listen for system theme changes
        window.matchMedia("(prefers-color-scheme: dark)").addEventListener("change", e => {
            if (!localStorage.getItem("ivy-rss-hub-theme")) {
                this.updateThemeIcon(e.matches ? "dark" : "light");
            }
        });
    }

    /**

     * Toggle between light and dark theme

     */
    toggleTheme() {
        const currentTheme = document.documentElement.getAttribute("data-theme");
        const prefersDark = window.matchMedia("(prefers-color-scheme: dark)").matches;

        // Determine current effective theme
        let effectiveTheme;
        if (currentTheme) {
            effectiveTheme = currentTheme;
        } else {
            effectiveTheme = prefersDark ? "dark" : "light";
        }

        // Toggle
        const newTheme = effectiveTheme === "dark" ? "light" : "dark";
        document.documentElement.setAttribute("data-theme", newTheme);
        localStorage.setItem("ivy-rss-hub-theme", newTheme);
        this.updateThemeIcon(newTheme);

        this.showToast(`${newTheme === "dark" ? "πŸŒ™ Dark" : "β˜€οΈ Light"} theme activated`, "info");
    }

    /**

     * Update theme toggle button icon

     */
    updateThemeIcon(theme) {
        if (this.elements.btnTheme) {
            this.elements.btnTheme.textContent = theme === "dark" ? "πŸŒ™" : "β˜€οΈ";
            this.elements.btnTheme.title = `Switch to ${theme === "dark" ? "light" : "dark"} theme`;
        }
    }

    /**

     * Initialize the application

     */
    init() {
        // Load feeds from settings or defaults
        this.feeds = this.settings.feeds || [...window.FeedsConfig.DEFAULT_FEEDS];

        // Save if migration occurred
        if (this._needsMigrationSave) {
            console.log("[Migration] Saving migrated feed configuration");
            this.saveSettings();
            this._needsMigrationSave = false;
        }

        // Setup event listeners
        this.setupEventListeners();

        // Setup scroll propagation for nested scrollable containers
        this.setupScrollPropagation();

        // Render settings
        this.renderSourcesList();

        // Initialize sidebar
        this.sidebar = new SidebarManager(this);
        window.sidebar = this.sidebar; // Expose for event handlers

        // Initialize settings UI from saved values
        this.initSettingsUI();

        // Initial fetch
        this.refreshFeeds();

        // Start auto-refresh if enabled
        if (this.settings.autoRefresh) {
            this.startAutoRefresh();
        }
    }

    /**

     * Initialize settings UI elements from saved settings

     */
    initSettingsUI() {
        const groupBySourceCheckbox = document.getElementById("opt-group-by-source");
        const showDescriptionsCheckbox = document.getElementById("opt-show-descriptions");
        const maxItemsInput = document.getElementById("opt-max-items");
        const autoRefreshCheckbox = document.getElementById("opt-auto-refresh");
        const refreshIntervalSelect = document.getElementById("opt-refresh-interval");

        if (groupBySourceCheckbox) {
            groupBySourceCheckbox.checked = this.settings.groupBySource !== false;
        }
        if (showDescriptionsCheckbox) {
            showDescriptionsCheckbox.checked = this.settings.showDescriptions !== false;
        }
        if (maxItemsInput) {
            maxItemsInput.value = this.settings.maxItems || 10;
        }
        if (autoRefreshCheckbox) {
            autoRefreshCheckbox.checked = this.settings.autoRefresh === true;
        }
        if (refreshIntervalSelect) {
            refreshIntervalSelect.value = this.settings.refreshInterval || 10;
        }
        this.updateAutoRefreshStatus();
    }

    /**

     * Setup event listeners

     */
    setupEventListeners() {
        // Refresh button - normal click uses cache, shift+click forces refresh
        this.elements.btnRefresh.addEventListener("click", async e => {
            // Prevent double-click while already loading
            if (this.isRefreshing) {
                return;
            }

            if (e.shiftKey) {
                // Force refresh - clear all cache including IndexedDB
                await this.parser.clearAllCache();
                this.showToast("Cache cleared! Refreshing...", "info");
                console.log("πŸ”„ Force refresh - cache cleared");
            }
            // Normal refresh uses cache if available
            this.refreshFeeds();
        });

        // Add tooltip hint
        this.elements.btnRefresh.title = "Refresh feeds (Shift+Click to force refresh)";

        // Theme toggle
        this.elements.btnTheme?.addEventListener("click", () => {
            this.toggleTheme();
        });

        // About modal
        this.elements.btnAbout.addEventListener("click", () => {
            this.elements.modalAbout.classList.add("active");
            // Focus the close button for accessibility
            setTimeout(() => this.elements.modalCloseAbout.focus(), 100);
        });
        this.elements.modalCloseAbout.addEventListener("click", () => {
            this.elements.modalAbout.classList.remove("active");
        });

        // Settings modal
        this.elements.btnSettings.addEventListener("click", () => {
            this.renderSourcesList();
            this.elements.modalSettings.classList.add("active");
            // Focus the close button for accessibility
            setTimeout(() => this.elements.modalCloseSettings.focus(), 100);
        });
        this.elements.modalCloseSettings.addEventListener("click", () => {
            this.elements.modalSettings.classList.remove("active");
        });

        // Close modals on overlay click
        [this.elements.modalAbout, this.elements.modalSettings].forEach(modal => {
            modal.addEventListener("click", e => {
                if (e.target === modal) {
                    modal.classList.remove("active");
                }
            });
        });

        // Focus trap for modals (accessibility)
        document.addEventListener("keydown", e => {
            if (e.key !== "Tab") return;

            // Check if a modal is open
            const activeModal = document.querySelector(".modal-overlay.active .modal");
            if (!activeModal) return;

            // Get all focusable elements in the modal
            const focusableElements = activeModal.querySelectorAll(
                'button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])'
            );
            const firstElement = focusableElements[0];
            const lastElement = focusableElements[focusableElements.length - 1];

            // Trap focus within modal
            if (e.shiftKey && document.activeElement === firstElement) {
                e.preventDefault();
                lastElement.focus();
            } else if (!e.shiftKey && document.activeElement === lastElement) {
                e.preventDefault();
                firstElement.focus();
            }
        });

        // Keyboard shortcuts
        document.addEventListener("keydown", e => {
            // Don't trigger shortcuts when typing in inputs
            if (e.target.tagName === "INPUT" || e.target.tagName === "TEXTAREA") {
                // Escape to blur inputs
                if (e.key === "Escape") e.target.blur();
                return;
            }

            // Escape to close modals and sidebar
            if (e.key === "Escape") {
                this.elements.modalAbout.classList.remove("active");
                this.elements.modalSettings.classList.remove("active");
                // Also close mobile sidebar
                this.elements.sidebar?.classList.remove("open");
            }

            // R to refresh (Shift+R for force refresh)
            if (e.key === "r" || e.key === "R") {
                e.preventDefault();
                if (e.shiftKey) {
                    this.parser.clearAllCache().then(() => {
                        this.showToast("Cache cleared! Refreshing...", "info");
                        this.refreshFeeds();
                    });
                } else {
                    this.refreshFeeds();
                }
            }

            // / to focus search
            if (e.key === "/") {
                e.preventDefault();
                const searchInput = document.getElementById("search-input");
                if (searchInput) {
                    searchInput.focus();
                    // Open sidebar on mobile
                    if (window.innerWidth <= 1100) {
                        this.elements.sidebar?.classList.add("open");
                    }
                }
            }

            // S to toggle sidebar on desktop
            if (e.key === "s" && !e.ctrlKey && !e.metaKey) {
                const sidebar = document.getElementById("sidebar");
                if (sidebar) sidebar.classList.toggle("hidden-desktop");
            }

            // T to toggle theme
            if (e.key === "t" && !e.ctrlKey && !e.metaKey) {
                this.toggleTheme();
            }

            // Home or ArrowUp (when not in input) to scroll to top
            if (e.key === "Home" || (e.key === "ArrowUp" && e.ctrlKey)) {
                e.preventDefault();
                this.scrollToTop();
            }
        });

        // Back to top button
        this.setupBackToTop();

        // Category navigation
        this.elements.navButtons.forEach(btn => {
            btn.addEventListener("click", () => {
                this.setCategory(btn.dataset.category);
            });
        });

        // Add custom feed (use AbortController pattern to prevent duplicate listeners)
        const addFeedBtn = document.getElementById("btn-add-feed");
        if (addFeedBtn && !addFeedBtn.dataset.listenerAttached) {
            addFeedBtn.addEventListener("click", () => this.addCustomFeed());
            addFeedBtn.dataset.listenerAttached = "true";
        }

        // Settings options
        document.getElementById("opt-group-by-source")?.addEventListener("change", e => {
            this.settings.groupBySource = e.target.checked;
            this.saveSettings();
            this.renderFeeds();
        });

        document.getElementById("opt-show-descriptions")?.addEventListener("change", e => {
            this.settings.showDescriptions = e.target.checked;
            this.saveSettings();
            this.renderFeeds();
        });

        document.getElementById("opt-max-items")?.addEventListener("change", e => {
            this.settings.maxItems = parseInt(e.target.value) || 20;
            this.saveSettings();
            this.renderFeeds();
        });

        // Auto-refresh settings
        document.getElementById("opt-auto-refresh")?.addEventListener("change", e => {
            this.settings.autoRefresh = e.target.checked;
            this.saveSettings();
            if (e.target.checked) {
                this.startAutoRefresh();
                this.showToast("Auto-refresh enabled! ⏰", "success");
            } else {
                this.stopAutoRefresh();
                this.showToast("Auto-refresh disabled", "info");
            }
        });

        document.getElementById("opt-refresh-interval")?.addEventListener("change", e => {
            this.settings.refreshInterval = parseInt(e.target.value) || 10;
            this.saveSettings();
            // Restart timer with new interval if auto-refresh is enabled
            if (this.settings.autoRefresh) {
                this.startAutoRefresh();
                this.showToast(`Refresh interval set to ${e.target.value} minutes`, "success");
            }
        });

        // Enable/Disable all feeds buttons
        document.getElementById("btn-enable-all")?.addEventListener("click", () => {
            this.feeds.forEach(f => (f.enabled = true));
            this.saveSettings();
            this.renderSourcesList();
            this.showToast("All feeds enabled!", "success");
        });

        document.getElementById("btn-disable-all")?.addEventListener("click", () => {
            this.feeds.forEach(f => (f.enabled = false));
            this.saveSettings();
            this.renderSourcesList();
            this.showToast("All feeds disabled", "info");
        });

        // Language filter buttons
        this.elements.langButtons.forEach(btn => {
            btn.addEventListener("click", () => {
                this.setLanguage(btn.dataset.lang);
            });
        });

        // Reset all data button
        document.getElementById("btn-reset-all")?.addEventListener("click", () => {
            this.resetAllData();
        });
    }

    /**

     * Set active category filter

     */
    setCategory(category) {
        this.currentCategory = category;

        // Update nav buttons
        this.elements.navButtons.forEach(btn => {
            btn.classList.toggle("active", btn.dataset.category === category);
        });

        // Re-render feeds
        this.renderFeeds();
    }

    /**

     * Setup scroll propagation for nested scrollable containers

     * Fixes the issue where scroll gets "trapped" inside .source-articles

     * when reaching the top or bottom of the container

     */
    setupScrollPropagation() {
        // Use event delegation on the feeds container
        this.elements.feedsContainer.addEventListener(
            "wheel",
            e => {
                const target = e.target.closest(".source-articles");
                if (!target) return;

                const { scrollTop, scrollHeight, clientHeight } = target;
                const isAtTop = scrollTop <= 0;
                const isAtBottom = scrollTop + clientHeight >= scrollHeight - 1;

                // If scrolling up and at top, or scrolling down and at bottom,
                // let the event propagate to the parent
                if ((e.deltaY < 0 && isAtTop) || (e.deltaY > 0 && isAtBottom)) {
                    // Don't prevent default - let parent scroll
                    return;
                }

                // Otherwise, prevent the event from reaching the parent
                // This keeps scroll inside the container when not at bounds
                if (scrollHeight > clientHeight) {
                    e.stopPropagation();
                }
            },
            { passive: true }
        );
    }

    /**

     * Setup Back to Top button behavior

     */
    setupBackToTop() {
        const backToTopBtn = document.getElementById("back-to-top");
        if (!backToTopBtn) return;

        // Show/hide button based on scroll position
        let ticking = false;
        window.addEventListener(
            "scroll",
            () => {
                if (!ticking) {
                    requestAnimationFrame(() => {
                        const scrollY = window.scrollY || document.documentElement.scrollTop;
                        // Show button after scrolling 400px
                        if (scrollY > 400) {
                            backToTopBtn.classList.add("visible");
                        } else {
                            backToTopBtn.classList.remove("visible");
                        }
                        ticking = false;
                    });
                    ticking = true;
                }
            },
            { passive: true }
        );

        // Click handler
        backToTopBtn.addEventListener("click", () => {
            this.scrollToTop();
        });
    }

    /**

     * Smooth scroll to top of page

     */
    scrollToTop() {
        window.scrollTo({
            top: 0,
            behavior: "smooth"
        });
    }

    /* ============================================

       AUTO-REFRESH SYSTEM

       ============================================ */

    /**

     * Start auto-refresh timer

     */
    startAutoRefresh() {
        // Clear any existing timer
        this.stopAutoRefresh();

        const intervalMinutes = this.settings.refreshInterval || 10;
        const intervalMs = intervalMinutes * 60 * 1000;

        // Set next refresh time
        this.nextRefreshTime = Date.now() + intervalMs;

        // Start main refresh timer
        this.autoRefreshTimer = setInterval(() => {
            console.log("[RSS] Auto-refresh triggered");
            this.refreshFeeds();
            // Reset next refresh time
            this.nextRefreshTime = Date.now() + intervalMs;
        }, intervalMs);

        // Start countdown display timer (update every 10 seconds)
        this.countdownTimer = setInterval(() => {
            this.updateAutoRefreshStatus();
        }, 10000);

        // Update status immediately
        this.updateAutoRefreshStatus();

        console.log(`[RSS] Auto-refresh started: every ${intervalMinutes} minutes`);
    }

    /**

     * Stop auto-refresh timer

     */
    stopAutoRefresh() {
        if (this.autoRefreshTimer) {
            clearInterval(this.autoRefreshTimer);
            this.autoRefreshTimer = null;
        }
        if (this.countdownTimer) {
            clearInterval(this.countdownTimer);
            this.countdownTimer = null;
        }
        this.nextRefreshTime = null;
        this.updateAutoRefreshStatus();
    }

    /**

     * Update auto-refresh status display

     */
    updateAutoRefreshStatus() {
        const statusEl = document.getElementById("auto-refresh-status");
        if (!statusEl) return;

        if (!this.settings.autoRefresh || !this.nextRefreshTime) {
            statusEl.textContent = "Auto-refresh is disabled";
            statusEl.style.color = "";
            return;
        }

        const remaining = this.nextRefreshTime - Date.now();
        if (remaining <= 0) {
            statusEl.textContent = "Refreshing now...";
            statusEl.style.color = "var(--ivy-green)";
            return;
        }

        const minutes = Math.floor(remaining / 60000);
        const seconds = Math.floor((remaining % 60000) / 1000);

        if (minutes > 0) {
            statusEl.textContent = `⏰ Next refresh in ${minutes}m ${seconds}s`;
        } else {
            statusEl.textContent = `⏰ Next refresh in ${seconds}s`;
        }
        statusEl.style.color = "var(--ivy-green)";
    }

    /**

     * Set active language filter

     */
    setLanguage(lang) {
        this.currentLang = lang;

        // Update lang buttons
        this.elements.langButtons.forEach(btn => {
            btn.classList.toggle("active", btn.dataset.lang === lang);
        });

        // Re-render feeds
        this.renderFeeds();
    }

    /**

     * Refresh all feeds

     */
    async refreshFeeds() {
        // Prevent concurrent refresh calls
        if (this.isRefreshing) {
            console.debug("[RSS] Refresh already in progress, skipping");
            return;
        }
        this.isRefreshing = true;

        try {
            // Show loading state
            this.elements.btnRefresh.classList.add("spinning");
            this.elements.btnRefresh.setAttribute("aria-busy", "true");
            this.setStatus("Loading feeds...", "");
            this.renderLoading();

            // Get enabled feeds
            const enabledFeeds = this.feeds.filter(f => f.enabled);

            if (enabledFeeds.length === 0) {
                this.setStatus("No feeds enabled", "");
                this.renderEmpty("No feeds enabled. Go to Settings to enable some feeds.");
                return;
            }

            // Use progressive loading with callback
            this.feedResults = [];

            await this.parser.fetchAllFeedsProgressive(enabledFeeds, (results, loaded, total) => {
                // Update results
                this.feedResults = results;

                // Calculate stats
                const successful = results.filter(r => r.status === "success").length;
                const fromCache = results.filter(r => r.fromCache).length;
                const maxItems = this.settings.maxItems || 10;

                // Count DISPLAYED articles (limited by maxItems per source)
                const displayedArticles = results
                    .filter(r => r.feed)
                    .reduce((sum, r) => sum + Math.min(r.feed.items.length, maxItems), 0);

                // Update status with progress
                const cacheInfo = fromCache > 0 ? ` (${fromCache} cached)` : "";
                this.setStatus(
                    `${successful}/${loaded} sources loaded${cacheInfo} β€’ ~${displayedArticles} articles`,
                    loaded < total ? `Loading ${loaded}/${total}...` : `Last updated: ${this.formatTime(new Date())}`
                );

                // Render feeds progressively
                this.renderFeeds();
            });

            // Final update
            const successful = this.feedResults.filter(r => r.status === "success").length;
            const total = this.feedResults.length;
            const fromCache = this.feedResults.filter(r => r.fromCache).length;
            const maxItems = this.settings.maxItems || 10;
            const displayedArticles = this.feedResults
                .filter(r => r.feed)
                .reduce((sum, r) => sum + Math.min(r.feed.items.length, maxItems), 0);

            const cacheInfo = fromCache > 0 ? ` (${fromCache} ⚑)` : "";
            this.setStatus(
                `${successful}/${total} sources${cacheInfo} β€’ ${displayedArticles} articles`,
                `Last updated: ${this.formatTime(new Date())}`
            );

            // Render feeds
            this.renderFeeds();

            // Update sidebar with article data
            if (this.sidebar) {
                this.sidebar.updateWithArticles(this.feedResults);
            }
        } catch (error) {
            console.error("[RSS] Error during refresh:", error);
            this.setStatus("Error loading feeds", "");
            this.showToast("Failed to load some feeds. Please try again.", "error");
        } finally {
            // Always cleanup - stop spinner and reset flag
            this.elements.btnRefresh.classList.remove("spinning");
            this.elements.btnRefresh.setAttribute("aria-busy", "false");
            this.isRefreshing = false;
        }
    }

    /**

     * Render loading state

     */
    renderLoading() {
        const enabledCount = this.feeds.filter(f => f.enabled).length;
        this.elements.feedsContainer.innerHTML = `

            <div class="loading-state">

                <div class="loading-spinner"></div>

                <p>Fetching ${enabledCount} feeds...</p>

                <p class="hint">First load may take a moment. Shift+R to force refresh.</p>

            </div>

        `;
    }

    /**

     * Render empty state

     */
    renderEmpty(message) {
        this.elements.feedsContainer.innerHTML = `

            <div class="empty-state">

                <div class="empty-icon">πŸ“­</div>

                <p>${message}</p>

                <p class="hint">Try changing filters or enabling more sources in Settings.</p>

            </div>

        `;
    }

    /**

     * Render feeds to DOM

     */
    renderFeeds() {
        // Filter by category
        let filteredResults = this.feedResults;
        if (this.currentCategory !== "all") {
            filteredResults = this.feedResults.filter(r => r.category === this.currentCategory);
        }

        // Filter by language
        if (this.currentLang !== "all") {
            filteredResults = filteredResults.filter(r => r.lang === this.currentLang);
        }

        // Filter to only successful feeds
        const successfulFeeds = filteredResults.filter(r => r.status === "success" && r.feed);

        if (successfulFeeds.length === 0) {
            const langLabel = this.currentLang === "en" ? "English" : this.currentLang === "fr" ? "French" : "";
            this.renderEmpty(`No articles found for this filter.${langLabel ? ` (${langLabel} only)` : ""}`);
            return;
        }

        // Group by source (default: true)
        if (this.settings.groupBySource !== false) {
            this.renderGroupedBySource(successfulFeeds);
        } else {
            this.renderMergedList(successfulFeeds);
        }

        // Show failed feeds if any (collapsed by default)
        const failedFeeds = filteredResults.filter(r => r.status === "error");
        if (failedFeeds.length > 0) {
            this.renderFailedFeeds(failedFeeds);
        }
    }

    /**

     * Render a section showing failed feeds

     */
    renderFailedFeeds(failedFeeds) {
        const html = `

            <section class="source-section error collapsed" data-source="failed-feeds">

                <header class="source-header" onclick="app.toggleSource('failed-feeds')" role="button" tabindex="0" aria-expanded="false">

                    <div class="source-title">

                        <span class="source-icon">⚠️</span>

                        <span class="source-name">Failed to load (${failedFeeds.length})</span>

                    </div>

                    <div class="source-meta">

                        <span class="source-count" style="background: #ef4444;">${failedFeeds.length}</span>

                        <span class="source-toggle">β–Ό</span>

                    </div>

                </header>

                <ul class="source-articles">

                    ${failedFeeds

                        .map(

                            feed => `

                        <div class="article-item-wrapper">

                            <div class="article-item" style="cursor: default;">

                                <div class="article-title">${this.escapeHtml(feed.name)}</div>

                                <div class="article-meta">

                                    <span style="color: #ef4444;">❌ ${this.escapeHtml(feed.error || "Unknown error")}</span>

                                </div>

                            </div>

                        </div>

                    `

                        )

                        .join("")}

                </ul>

            </section>

        `;

        this.elements.feedsContainer.insertAdjacentHTML("beforeend", html);
    }

    /**

     * Render feeds grouped by source (optimized with innerHTML batching)

     */
    renderGroupedBySource(feedResults) {
        const maxItems = this.settings.maxItems || 10;

        // Build all HTML at once for better performance (single DOM reflow)
        const htmlParts = feedResults.map((result, index) => {
            const items = result.feed.items.slice(0, maxItems);
            const categoryInfo = window.FeedsConfig.CATEGORIES[result.category] || {};
            const isFavorite = this.sidebar?.isSourceFavorite(result.id);
            const favoriteClass = isFavorite ? "saved" : "";
            const colorIndex = this.getSourceColorIndex(result.id);

            // Determine status class based on result
            const statusClass = result.fromCache ? "cached" : "fresh";
            const statusIcon = result.fromCache ? "⚑" : "";

            return `

                <section class="source-section" data-source="${result.id}" data-color-index="${colorIndex}" role="region" aria-label="${this.escapeHtml(result.name)} feed">

                    <header class="source-header" role="button" tabindex="0" aria-expanded="true" onclick="app.toggleSource('${result.id}')" onkeydown="if(event.key==='Enter'||event.key===' '){event.preventDefault();app.toggleSource('${result.id}')}">

                        <button class="source-favorite ${favoriteClass}"

                                onclick="event.stopPropagation(); app.toggleSourceFavorite('${result.id}', '${this.escapeHtml(result.name)}', '${result.icon}')"

                                onkeydown="event.stopPropagation()"

                                aria-label="${isFavorite ? "Remove from favorites" : "Add to favorites"}"

                                title="${isFavorite ? "Remove from favorites" : "Add to favorites"}">

                            ${isFavorite ? "β˜…" : "β˜†"}

                        </button>

                        <div class="source-title">

                            <span class="source-icon" aria-hidden="true">${result.icon}</span>

                            <span class="source-name">${result.name}</span>

                        </div>

                        <div class="source-meta">

                            <span class="source-count" aria-label="${items.length} articles">${items.length}</span>

                            <span class="source-status ${statusClass}" title="${result.fromCache ? "Loaded from cache" : "Fresh from source"}">

                                ${statusIcon} ${this.formatTimeAgo(result.lastFetched)}

                            </span>

                            <span class="source-toggle" aria-hidden="true">β–Ό</span>

                        </div>

                    </header>

                    <ul class="source-articles">

                        ${items.map(item => this.renderArticleItem(item)).join("")}

                    </ul>

                </section>

            `;
        });

        // Single DOM update for better performance
        this.elements.feedsContainer.innerHTML = htmlParts.join("");
    }

    /**

     * Toggle favorite state for a source

     */
    toggleSourceFavorite(sourceId, sourceName, sourceIcon) {
        if (!this.sidebar) return;
        const wasAdded = this.sidebar.toggleFavoriteSource(sourceId, sourceName, sourceIcon);
        this.showToast(
            wasAdded ? `${sourceName} added to favorites! ⭐` : `${sourceName} removed from favorites`,
            wasAdded ? "success" : "info"
        );
        this.renderFeeds();
    }

    /**

     * Render all articles in a merged list sorted by date

     */
    renderMergedList(feedResults) {
        const maxItems = this.settings.maxItems || 10;

        // Collect all articles with source info
        const allArticles = feedResults.flatMap(result =>
            result.feed.items.map(item => ({
                ...item,
                sourceName: result.name,
                sourceIcon: result.icon,
                sourceId: result.id
            }))
        );

        // Sort by date (newest first)
        allArticles.sort((a, b) => {
            const dateA = a.pubDate || new Date(0);
            const dateB = b.pubDate || new Date(0);
            return dateB - dateA;
        });

        // Limit total
        const limitedArticles = allArticles.slice(0, maxItems * feedResults.length);

        const html = `

            <section class="source-section">

                <header class="source-header">

                    <div class="source-title">

                        <span class="source-icon">πŸ“°</span>

                        <span class="source-name">All Articles</span>

                    </div>

                    <div class="source-meta">

                        <span class="source-count">${limitedArticles.length}</span>

                    </div>

                </header>

                <ul class="source-articles">

                    ${limitedArticles.map(item => this.renderArticleItem(item, true)).join("")}

                </ul>

            </section>

        `;

        this.elements.feedsContainer.innerHTML = html;
    }

    /**

     * Render a single article item

     */
    renderArticleItem(item, showSource = false) {
        const dateStr = item.pubDate ? this.formatTimeAgo(item.pubDate) : "";
        const fullDate = item.pubDate ? this.formatFullDate(item.pubDate) : "";
        const sourceStr =
            showSource && item.sourceName
                ? `<span class="article-source">${item.sourceIcon} ${item.sourceName}</span>`
                : "";

        // Check if article is recent (less than 2 hours old)
        const isRecent = item.pubDate && Date.now() - item.pubDate.getTime() < 2 * 60 * 60 * 1000;
        const recentClass = isRecent ? "recent" : "";

        // Show description preview if available and enabled in settings
        const showDescriptions = this.settings.showDescriptions !== false;
        const descriptionStr =
            showDescriptions && item.description
                ? `<div class="article-description">${this.escapeHtml(item.description.substring(0, 120))}${item.description.length > 120 ? "..." : ""}</div>`
                : "";

        const isBookmarked = this.sidebar?.isBookmarked(item.link);
        const bookmarkClass = isBookmarked ? "saved" : "";
        // Use data attributes to avoid XSS and JSON parsing issues in onclick
        const safeTitle = this.escapeAttr(item.title);
        const safeLink = this.escapeAttr(item.link);
        const safeSource = this.escapeAttr(item.sourceName || "Unknown");

        return `

            <div class="article-item-wrapper ${recentClass}">

                <a class="article-item" href="${this.escapeHtml(item.link)}" target="_blank" rel="noopener">

                    <div class="article-title">${isRecent ? '<span class="new-badge">NEW</span>' : ""}${this.escapeHtml(item.title)}</div>

                    ${descriptionStr}

                    <div class="article-meta">

                        ${sourceStr}

                        ${dateStr ? `<span class="article-date" title="${fullDate}">πŸ• ${dateStr}</span>` : ""}

                    </div>

                </a>

                <button class="article-bookmark ${bookmarkClass}"

                        data-title="${safeTitle}"

                        data-link="${safeLink}"

                        data-source="${safeSource}"

                        onclick="app.toggleBookmarkFromElement(this)"

                        aria-label="${isBookmarked ? "Remove bookmark" : "Add bookmark"}"

                        title="${isBookmarked ? "Remove bookmark" : "Add bookmark"}">

                    ${isBookmarked ? "β˜…" : "β˜†"}

                </button>

            </div>

        `;
    }

    /**

     * Toggle bookmark for an article (from data attributes)

     */
    toggleBookmarkFromElement(element) {
        if (!this.sidebar) return;

        const articleData = {
            title: element.dataset.title,
            link: element.dataset.link,
            sourceName: element.dataset.source
        };

        if (this.sidebar.isBookmarked(articleData.link)) {
            this.sidebar.removeBookmark(articleData.link);
            this.showToast("Bookmark removed", "info");
        } else {
            this.sidebar.addBookmark(articleData);
            this.showToast("Bookmark added! ⭐", "success");
        }

        // Re-render to update bookmark states
        this.renderFeeds();
    }

    /**

     * Show toast notification

     */
    showToast(message, type = "info") {
        // Remove existing toast if any
        const existing = document.querySelector(".toast-notification");
        if (existing) existing.remove();

        const toast = document.createElement("div");
        toast.className = `toast-notification toast-${type}`;
        toast.setAttribute("role", "status");
        toast.setAttribute("aria-live", "polite");
        toast.innerHTML = `<span>${message}</span>`;
        document.body.appendChild(toast);

        // Trigger animation
        requestAnimationFrame(() => toast.classList.add("show"));

        // Auto-dismiss
        setTimeout(() => {
            toast.classList.remove("show");
            setTimeout(() => toast.remove(), 300);
        }, 2500);
    }

    /**

     * Toggle source section collapse

     */
    toggleSource(sourceId) {
        const section = document.querySelector(`.source-section[data-source="${sourceId}"]`);
        if (section) {
            section.classList.toggle("collapsed");
            // Update aria-expanded
            const header = section.querySelector(".source-header");
            if (header) {
                const isCollapsed = section.classList.contains("collapsed");
                header.setAttribute("aria-expanded", !isCollapsed);
            }
        }
    }

    /**

     * Render sources list in settings

     */
    renderSourcesList() {
        const html = this.feeds
            .map(feed => {
                const categoryInfo = window.FeedsConfig.CATEGORIES[feed.category] || {};
                const langFlag = feed.lang === "fr" ? "πŸ‡«πŸ‡·" : feed.lang === "en" ? "πŸ‡¬πŸ‡§" : "🌍";
                const deleteBtn = feed.custom
                    ? `<button class="source-delete-btn" onclick="event.stopPropagation(); app.deleteCustomFeed('${feed.id}')" title="Delete custom feed">πŸ—‘οΈ</button>`
                    : "";
                return `

                <div class="source-toggle-item" data-feed-id="${feed.id}">

                    <input type="checkbox"

                           id="feed-${feed.id}"

                           ${feed.enabled ? "checked" : ""}

                           onchange="app.toggleFeedEnabled('${feed.id}', this.checked)"

                           aria-label="Enable ${this.escapeHtml(feed.name)}">

                    <div class="source-toggle-info">

                        <div class="source-toggle-name">${feed.icon} ${this.escapeHtml(feed.name)} ${feed.custom ? "<span class='custom-badge'>Custom</span>" : ""}</div>

                        <div class="source-toggle-url">${this.escapeHtml(feed.url)}</div>

                    </div>

                    <span class="source-toggle-lang" title="${feed.lang === "fr" ? "French" : "English"}">${langFlag}</span>

                    <span class="source-toggle-category">${categoryInfo.icon || ""} ${categoryInfo.name || feed.category}</span>

                    ${deleteBtn}

                </div>

            `;
            })
            .join("");

        this.elements.sourcesList.innerHTML = html;
    }

    /**

     * Delete a custom feed

     */
    deleteCustomFeed(feedId) {
        const feed = this.feeds.find(f => f.id === feedId);
        if (!feed || !feed.custom) {
            this.showToast("Cannot delete built-in feeds", "error");
            return;
        }

        if (!confirm(`Delete "${feed.name}"?`)) return;

        this.feeds = this.feeds.filter(f => f.id !== feedId);
        this.saveSettings();
        this.renderSourcesList();
        this.showToast(`"${feed.name}" deleted`, "info");
        this.refreshFeeds();
    }

    /**

     * Toggle feed enabled state

     */
    toggleFeedEnabled(feedId, enabled) {
        const feed = this.feeds.find(f => f.id === feedId);
        if (feed) {
            feed.enabled = enabled;
            this.saveSettings();
            this.showToast(`${feed.name} ${enabled ? "enabled" : "disabled"}`, enabled ? "success" : "info");
        }
    }

    /**

     * Add custom feed with validation

     */
    async addCustomFeed() {
        const nameInput = document.getElementById("custom-feed-name");
        const urlInput = document.getElementById("custom-feed-url");
        const categorySelect = document.getElementById("custom-feed-category");
        const addBtn = document.getElementById("btn-add-feed");

        const name = nameInput.value.trim();
        const url = urlInput.value.trim();
        const category = categorySelect.value;

        if (!name || !url) {
            this.showToast("Please enter both name and URL", "error");
            return;
        }

        // Validate URL format
        try {
            new URL(url);
        } catch {
            this.showToast("Please enter a valid URL", "error");
            return;
        }

        // Show loading state
        const originalText = addBtn.textContent;
        addBtn.textContent = "Testing...";
        addBtn.disabled = true;

        // Test if the URL is actually a valid RSS feed
        try {
            const result = await this.parser.fetchFeed({ url, name, id: "test" });
            if (result.status !== "success") {
                throw new Error(result.error || "Invalid RSS feed");
            }
        } catch (e) {
            addBtn.textContent = originalText;
            addBtn.disabled = false;
            this.showToast(`Invalid feed: ${e.message}`, "error");
            return;
        }

        // Restore button
        addBtn.textContent = originalText;
        addBtn.disabled = false;

        // Generate unique ID
        const id = "custom_" + Date.now();

        // Detect language from category or default to 'en'
        const langSelect = document.getElementById("custom-feed-lang");
        const lang = langSelect ? langSelect.value : "en";

        // Add to feeds
        this.feeds.push({
            id,
            name,
            url,
            icon: "πŸ“‘",
            category,
            lang,
            enabled: true,
            custom: true
        });

        // Save and refresh
        this.saveSettings();
        this.renderSourcesList();
        this.showToast(`Feed "${name}" added! πŸŽ‰`, "success");

        // Clear inputs
        nameInput.value = "";
        urlInput.value = "";

        // Refresh feeds
        this.refreshFeeds();
    }

    /**

     * Load settings from localStorage

     */
    loadSettings() {
        try {
            const saved = localStorage.getItem("ivy-rss-hub-settings");
            if (saved) {
                const parsed = JSON.parse(saved);
                // Ensure groupBySource defaults to true if not set
                if (parsed.groupBySource === undefined) {
                    parsed.groupBySource = true;
                }
                // Ensure showDescriptions defaults to true if not set
                if (parsed.showDescriptions === undefined) {
                    parsed.showDescriptions = true;
                }

                // Run migrations for existing users
                if (parsed.feeds) {
                    parsed.feeds = this.migrateFeeds(parsed.feeds);
                }

                return parsed;
            }
        } catch (e) {
            console.warn("Failed to load settings:", e);
        }

        // Defaults
        return {
            groupBySource: true,
            showDescriptions: true,
            maxItems: 10,
            feeds: null // Will use defaults
        };
    }

    /**

     * Migrate old feed configurations to new ones

     * This handles breaking changes like the arXiv RSS -> API migration

     */
    migrateFeeds(feeds) {
        // Migration v1: Replace old arXiv RSS feeds with new API feed
        // Old feeds: arxiv-ai, arxiv-ml, arxiv-cl, arxiv-cv, arxiv-ne, arxiv-combined
        // New feed: arxiv-ai-api
        const oldArxivIds = ["arxiv-ai", "arxiv-ml", "arxiv-cl", "arxiv-cv", "arxiv-ne", "arxiv-combined"];
        const newArxivId = "arxiv-ai-api";

        const hasOldArxiv = feeds.some(f => oldArxivIds.includes(f.id));
        const hasNewArxiv = feeds.some(f => f.id === newArxivId);

        if (hasOldArxiv && !hasNewArxiv) {
            console.log("[Migration] Replacing old arXiv RSS feeds with new API feed");

            // Check if any old arXiv feed was enabled
            const wasEnabled = feeds.some(f => oldArxivIds.includes(f.id) && f.enabled);

            // Remove old arXiv feeds
            feeds = feeds.filter(f => !oldArxivIds.includes(f.id));

            // Add new combined API feed at the beginning of AI category
            const newArxivFeed = {
                id: "arxiv-ai-api",
                name: "arXiv β€” AI & ML (Recent)",
                url: "https://export.arxiv.org/api/query?search_query=cat:cs.AI+OR+cat:cs.LG+OR+cat:cs.CL+OR+cat:cs.CV+OR+cat:cs.NE&max_results=100&sortBy=submittedDate&sortOrder=descending",
                icon: "πŸŽ“",
                category: "ai",
                lang: "en",
                enabled: wasEnabled,
                isAtom: true
            };

            // Insert at the beginning
            feeds.unshift(newArxivFeed);

            // Mark that we need to save after init
            this._needsMigrationSave = true;
        }

        return feeds;
    }

    /**

     * Reset all data (localStorage + IndexedDB)

     */
    async resetAllData() {
        if (
            !confirm(
                "Are you sure you want to reset ALL data?\n\nThis will delete:\nβ€’ All settings\nβ€’ Custom feeds\nβ€’ Bookmarks\nβ€’ Cached data\n\nThis action cannot be undone."
            )
        ) {
            return;
        }

        try {
            // Clear localStorage entries for this app
            localStorage.removeItem("ivy-rss-hub-settings");
            localStorage.removeItem("ivy-rss-hub-theme");
            localStorage.removeItem("ivy-rss-hub-bookmarks");
            localStorage.removeItem("ivy-rss-hub-favorites");
            localStorage.removeItem("ivy-rss-hub-sidebar");

            // Clear IndexedDB (Dexie cache)
            if (this.parser && this.parser.db) {
                await this.parser.db.delete();
                console.log("πŸ—‘οΈ IndexedDB cleared");
            }

            this.showToast("All data cleared! Reloading...", "success");

            // Reload page after a short delay
            setTimeout(() => {
                window.location.reload();
            }, 1000);
        } catch (e) {
            console.error("Reset failed:", e);
            this.showToast("Reset failed: " + e.message, "error");
        }
    }

    /**

     * Save settings to localStorage with quota handling

     */
    saveSettings() {
        try {
            this.settings.feeds = this.feeds;
            const data = JSON.stringify(this.settings);

            // Check approximate size (rough estimate)
            const sizeKB = new Blob([data]).size / 1024;
            if (sizeKB > 4500) {
                // Approaching 5MB limit - warn user
                console.warn(`Settings size: ${sizeKB.toFixed(1)}KB - approaching limit`);
                this.showToast("Storage nearly full. Consider removing some feeds.", "error");
            }

            localStorage.setItem("ivy-rss-hub-settings", data);
        } catch (e) {
            if (e.name === "QuotaExceededError") {
                this.showToast("Storage full! Please delete some feeds.", "error");
            }
            console.warn("Failed to save settings:", e);
        }
    }

    /**

     * Set status bar text

     */
    setStatus(text, time) {
        this.elements.statusText.textContent = text;
        this.elements.statusTime.textContent = time;
    }

    /**

     * Format time to readable string

     */
    formatTime(date) {
        return date.toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" });
    }

    /**

     * Format full date and time for tooltips

     */
    formatFullDate(date) {
        if (!date) return "";

        return date.toLocaleString("fr-FR", {
            weekday: "short",
            day: "numeric",
            month: "short",
            year: "numeric",
            hour: "2-digit",
            minute: "2-digit"
        });
    }

    /**

     * Format time ago string

     */
    formatTimeAgo(date) {
        if (!date) return "";

        const now = new Date();
        const diffMs = now - date;
        const diffMins = Math.floor(diffMs / 60000);
        const diffHours = Math.floor(diffMins / 60);
        const diffDays = Math.floor(diffHours / 24);

        if (diffMins < 1) return "just now";
        if (diffMins < 60) return `${diffMins}m ago`;
        if (diffHours < 24) return `${diffHours}h ago`;
        if (diffDays < 7) return `${diffDays}d ago`;

        return date.toLocaleDateString();
    }

    /**

     * Escape HTML to prevent XSS (delegates to shared utility)

     */
    escapeHtml(text) {
        return window.IvyUtils.escapeHtml(text);
    }

    /**

     * Escape text for use in HTML attributes (delegates to shared utility)

     */
    escapeAttr(text) {
        return window.IvyUtils.escapeAttr(text);
    }

    /**

     * Get a consistent color index (0-11) based on source ID

     * Uses simple hash for consistent colors per source

     */
    getSourceColorIndex(sourceId) {
        let hash = 0;
        for (let i = 0; i < sourceId.length; i++) {
            hash = (hash << 5) - hash + sourceId.charCodeAt(i);
            hash = hash & hash; // Convert to 32-bit integer
        }
        return Math.abs(hash) % 12; // 12 color variations
    }
}

// Initialize app when DOM is ready
let app;
document.addEventListener("DOMContentLoaded", () => {
    app = new RSSHubApp();
    window.app = app; // Expose for event handlers
});