Jake Vanderwerf
2025-09-30 2cb91676044ecd0abd9c45b4835abb8b0d042312
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
/**
 * Refactor statuses:
 * 1) queued                 - local queue
 * 1) localProcessing         - any local processing that can be done in the browser
 * 2) uploading             - sending to server
 * 3) pending; x in line     - sent to server, waiting
 * 4) processing             - server actively working on it
 * 5) completed             - with optional refresh
 */
class QueueManagerBackup {
    constructor() {
        // localStorage.clear();
        //Core components
        this.a11y = window.jvbA11y;
        this.errors = window.jvbError;
        this.cache = window.jvbCache;
 
        //Config
        this.STORAGE_KEY = 'jvb_queue';
        this.API = `${jvbSettings.api}queue`;
        this.maxRetries = 3;
 
        //Initialize State
        this.queue = new Map();
        this.hasChanges = false;
        this.processing = false;
        this.lastPollTime = null;
 
        //Status Tracking
        this.statuses = [
            'queued',           // Local, waiting to be sent
            'localProcessing',  // Being processed client-side
            'uploading',        // Being sent to server
            'pending',          // On server, waiting to be processed
            'processing',       // Server is actively processing
            'completed',        // Successfully completed
            'failed',           // Failed, can be retried
            'failed_permanent'  // Failed too many times
        ];
 
        //Initialize UI
        this.loadTemplates();
        this.initUI();
 
        // Operation type handlers
        this.processors = {
            'handle_vote': this.processVote.bind(this),
            'invite_artist': this.processArtistInvite.bind(this),
            'new_news': this.processNewNews.bind(this),
            'new_response': this.processNewResponse.bind(this),
            'bio_update': this.processBioUpdate.bind(this),
            'favourite_toggle': this.processFavourite.bind(this),
            'favourite_notes': this.processFavouriteNotes.bind(this),
            'favourite_list_create': this.processFavouriteListCreate.bind(this),
            'favourite_list_add': this.processFavouriteListAddItems.bind(this),
            'favourite_list_remove': this.processFavouriteListRemoveItems.bind(this),
            'favourite_list_delete': this.processFavouriteListDelete.bind(this),
            'favourite_list_share': this.processFavouriteListShare.bind(this),
            'favourite_list_unshare': this.processFavouriteListUnshare.bind(this),
            'user_settings': this.processSettingsUpdate.bind(this),
            'image_upload': this.processFileUpload.bind(this),
            'content_create': this.processContentCreation.bind(this),
            'batch_creation': this.processBatchCreation.bind(this),
            'content_update': this.processContentUpdate.bind(this),
        };
 
        // Cache types that need to be cleared after operations
        this.cacheTypesToClear = {
            'handle_vote': ['karma'],
            'new_news': ['news'],
            'new_response': ['responses', 'news'],
            'bio_update': ['artist'],
            'favourite_toggle': ['favourites', 'favouritesManager'],
            'favourite_notes': ['favouritesManager'],
            'favourite_list_create': ['list-item', 'favourite-lists'],
            'favourite_list_add': ['list-item', 'favourite-lists'],
            'favourite_list_remove': ['list-item', 'favourite-lists'],
            'favourite_list_delete': ['list-item', 'favourite-lists'],
            'favourite_list_share': ['list-item', 'favourite-lists'],
            'favourite_list_unshare': ['list-item', 'favourite-lists'],
        };
 
        // Human-readable operation names
        this.operationNames = {
            'handle_vote': 'Adding your voice',
            'new_news': 'New News',
            'invite_artist': 'Sending Invites...',
            'new_response': 'Sending in your response',
            'image_upload': 'Image Upload',
            'content_update': 'Content Update',
            'content_create': 'New Content',
            'user_settings': 'Settings Update',
            'favourite_toggle': 'Favourite Update',
            'bio_update': 'Profile Update',
            'batch_creation': 'Batch Content Creation',
            'favourite_notes': 'Favourite Notes',
            'favourite_list_create': 'List Creation',
            'favourite_list_add': 'List Update',
            'favourite_list_remove': 'List Update',
            'favourite_list_delete': 'List Deletion',
            'favourite_list_share': 'List Sharing',
            'favourite_list_unshare': 'List Share Removal'
        };
 
        // Status messages for UI
        this.statusMessages = {
            'queued': 'Waiting to send to server...',
            'localProcessing': 'Processing locally...',
            'uploading': 'Sending to server...',
            'pending': 'In line for processing...',
            'processing': 'Server is working on it...',
            'completed': 'All done!',
            'failed': 'There was an error',
            'failed_permanent': 'Failed permanently'
        };
 
        // Skip if not logged in
        if (!jvbSettings.currentUser) {
            return;
        }
 
        // Load queue from localStorage
        this.loadQueue();
 
        // Set up polling configuration
        this.pollingConfig = {
            enabled: true,
            interval: 10000,
            minInterval: 5000,
            maxInterval: 60000,
            countdown: true,
            backoffFactor: 1.5, // Increase interval by this factor when no changes
            consecutiveNoChanges: 0, // Track consecutive polls with no changes
            maxNoChangesCount: 8, // Cap on increasing interval
            lastETag: null,
            lastUserActivity: Date.now(),
            inactiveThreshold: 5 * 60 * 1000
        };
 
        // Track user activity
        this.setupActivityTracking();
 
        // Set up event listeners
        this.initEventListeners();
 
        // Initial fetch of server operations
        this.fetchOperations(true).then(() => {
            this.startPolling();
        });
 
        // Process queue periodically if there are changes
        setInterval(() => {
            if (this.hasChanges) {
                this.processQueue();
            }
        }, 3000);
    }
 
    /**
     * Track user activity to adjust polling
     */
    setupActivityTracking() {
        const events = ['mousedown', 'mousemove', 'keypress', 'scroll', 'touchstart'];
 
        events.forEach(event => {
            document.addEventListener(event, () => {
                this.pollingConfig.lastUserActivity = Date.now();
            }, { passive: true });
        });
    }
 
    /**
     * Initialize UI elements
     */
    initUI() {
        if (!jvbSettings.currentUser) return;
 
        // Main panel elements
        this.panel = document.querySelector('#queue-status-panel');
        if (!this.panel) return;
 
        this.panelList = this.panel.querySelector('.queue-list');
        this.togglePanel = this.panel.querySelector('.queue-status-toggle');
        this.countdown = this.panel.querySelector('.refresh-countdown');
        this.refreshButton = this.panel.querySelector('.manual-refresh');
        this.popup = this.panel.querySelector('.popup');
 
        // Filter buttons
        this.filterButtonsContainer = this.panel.querySelector('.queue-filters');
        this.filterButtons = this.panel.querySelectorAll('.queue-filters .filter');
 
        // Status-specific filter buttons
        this.statusButtons = {};
        this.statuses.forEach(status => {
            this.statusButtons[status] = this.panel.querySelector(`.filter[data-filter="${status}"]`);
        });
 
        // Action buttons
        this.retryButton = this.panel.querySelector('.retry-failed');
        this.clearButton = this.panel.querySelector('.dismiss-completed');
 
        // Initialize status panel
        this.initStatusPanel();
    }
 
 
 
 
    /**
     * Load HTML templates
     */
    loadTemplates() {
        this.templates = new Map();
 
        // Default templates
        this.templates.set('replyButton', this.createReplyButtonTemplate());
        this.templates.set('commentsButton', this.createCommentsButtonTemplate());
        this.templates.set('voteButton', this.createVoteButtonsTemplate());
 
        // Load templates from DOM
        document.querySelectorAll('template').forEach(template => {
            const classes = Array.from(template.classList);
            if (classes.length > 0) {
                const item = template.content.cloneNode(true).firstElementChild;
                classes.forEach(key => {
                    if (!this.templates.has(key)) {
                        this.templates.set(key, item);
                    }
                });
            }
        });
    }
 
    /**
     * Create reply button template
     */
    createReplyButtonTemplate() {
        const button = document.createElement('button');
        button.type = 'button';
        button.className = 'reply';
        button.dataset.action = 'make-response';
        button.innerHTML = jvbSettings.icons.reply + '<span>Reply</span>';
        return button;
    }
 
    /**
     * Create comments button template
     */
    createCommentsButtonTemplate() {
        const button = document.createElement('a');
        button.className = 'button';
        button.innerHTML = jvbSettings.icons.response + '{ <span class="count"></span> }';
        return button;
    }
 
    /**
     * Create vote buttons template
     */
    createVoteButtonsTemplate() {
        const vote = document.createElement('div');
        vote.className = 'vote';
        vote.innerHTML = `
            <button type="button" class="up" onClick="handleVote(this)"
                data-vote="up">${jvbSettings.icons.upvoted + jvbSettings.icons.upvote}
                <span>{ <span class="count">0</span> }</span>
            </button>
            <button type="button" class="down" onClick="handleVote(this)"
                data-vote="down">${jvbSettings.icons.downvoted + jvbSettings.icons.downvote}
                <span>{ <span class="count">0</span> }</span>
            </button>
        `;
        return vote;
    }
 
    /**
     * Initialize status panel
     */
    initStatusPanel() {
        if (!this.panel) return;
 
        // Toggle panel visibility
        if (this.togglePanel) {
            this.togglePanel.addEventListener('click', () => {
                this.panel.classList.toggle('expanded');
                this.togglePanel.title = this.panel.classList.contains('expanded')
                    ? 'Hide Queue' : 'Show Queue';
 
                const message = this.panel.classList.contains('expanded')
                    ? 'Opened Queue Panel' : 'Closed Queue Panel';
                this.a11y.announce(message);
 
                this.maybeAddEmptyState();
            });
        }
 
        // Close panel when clicking outside
        document.addEventListener('click', (e) => {
            if (this.panel.classList.contains('expanded') &&
                !this.panel.contains(e.target) &&
                e.target !== this.togglePanel) {
                this.panel.classList.remove('expanded');
            }
        });
 
        // Handle Escape key
        document.addEventListener('keydown', (e) => {
            if (e.key === 'Escape' && this.panel.classList.contains('expanded')) {
                this.panel.classList.remove('expanded');
            }
        });
 
        // Retry failed operations
        if (this.retryButton) {
            this.retryButton.addEventListener('click', () => this.retryFailedOperations());
        }
 
        // Clear completed operations
        if (this.clearButton) {
            this.clearButton.addEventListener('click', () => this.clearCompletedOperations());
        }
 
        // Filter buttons
        if (this.filterButtons) {
            this.filterButtons.forEach(button => {
                button.addEventListener('click', () => {
                    this.filterButtons.forEach(btn => btn.classList.remove('active'));
                    button.classList.add('active');
 
                    const filter = button.dataset.filter || 'all';
                    this.fetchOperations(true, {status: filter});
                });
            });
        }
 
        // Refresh button
        if (this.refreshButton) {
            this.refreshButton.addEventListener('click', () => {
                this.refreshButton.classList.add('refreshing');
                this.fetchOperations(true, {force: true}).finally(() => {
                    this.refreshButton.classList.remove('refreshing');
                });
            });
        }
 
        // Item-specific actions
        this.panelList.addEventListener('click', (e) => {
            // Retry operation
            if (e.target.classList.contains('retry-operation')) {
                const operationItem = e.target.closest('.queue-item');
                if (operationItem) {
                    this.retryOperation(operationItem.dataset.id);
                }
            }
 
            // Dismiss operation
            else if (e.target.classList.contains('dismiss-operation')) {
                const operationItem = e.target.closest('.queue-item');
                if (operationItem) {
                    this.dismissOperations([operationItem.dataset.id]);
                }
            }
        });
 
        // Initialize empty state
        this.maybeAddEmptyState();
    }
 
    /**
     * Set up event listeners
     */
    initEventListeners() {
        // Network status change
        window.addEventListener('online', () => {
            this.updateNetworkIndicator();
            if (this.hasChanges) {
                this.processQueue();
            }
        });
 
        window.addEventListener('offline', () => {
            this.updateNetworkIndicator();
            this.updateStatusPanel('offline');
        });
 
        // Before unload warning for unsaved changes
        window.addEventListener('beforeunload', (e) => {
            const hasPendingLocalChanges = [...this.queue.values()].some(item =>
                ['queued', 'localProcessing', 'uploading'].includes(item.status)
            );
 
            if (hasPendingLocalChanges) {
                e.preventDefault();
                return e.returnValue = 'You have unsaved changes that haven\'t been sent to the server. Are you sure you want to leave?';
            }
        });
    }
 
    /**
     * Maybe add empty state message
     */
    maybeAddEmptyState() {
        if (this.panelList.children.length === 0) {
            this.panelList.innerHTML = '<div class="no-operations">Everything up to date</div>';
            this.a11y.announce('Nothing queued.');
        } else if (this.panelList.children.length > 1 && this.panelList.querySelector('.no-operations')) {
            this.panelList.querySelector('.no-operations').remove();
        }
    }
 
    /**
     * Add an operation to the queue
     *
     * @param {Object} operation Operation data
     * @returns {string} Operation ID
     */
    async addToQueue(operation) {
        // Try to merge with similar operations
        const mergedOperation = this.mergeOperations(operation);
        operation = mergedOperation || operation;
 
        // Generate unique ID
        const id = this.generateId();
 
        // Create queue item
        const item = {
            id: id,
            type: operation.type,
            data: operation.data,
            user: jvbSettings.currentUser,
            started_at: Date.now(),
            status: 'queued',
            retries: 0,
            dependencies: operation.dependencies || [],
            onUpdate: operation.onUpdate??false
        };
 
        // Add to queue
        this.queue.set(id, item);
        this.saveQueue();
 
        // Update UI
        this.updateStatusPanel('pending');
        this.addPopup(this.getPopupMessage(item));
        this.hasChanges = true;
 
        return item.id;
    }
 
    /**
     * Generate a unique operation ID
     *
     * @returns {string} Unique ID
     */
    generateId() {
        // Create a timestamp-based prefix
        const timestamp = new Date().getTime().toString(36);
 
        // Add random component
        const randomPart = Math.random().toString(36).substring(2, 8);
 
        // Add counter to ensure uniqueness within same millisecond
        this.idCounter = (this.idCounter || 0) + 1;
        const counter = this.idCounter.toString(36);
 
        return `u${jvbSettings.currentUser}-${timestamp}-${randomPart}-${counter}`;
    }
 
    /**
     * Load queue from localStorage
     */
    loadQueue() {
        try {
            const storedData = localStorage.getItem(this.STORAGE_KEY);
            if (!storedData) return;
 
            const queueData = JSON.parse(storedData);
            if (!queueData || !Array.isArray(queueData)) return;
 
            this.queue = new Map();
            queueData.forEach(item => {
                if (item && item.id) {
                    this.queue.set(item.id, item);
                }
            });
 
            // Update UI for loaded items
            [...this.queue.values()].forEach(item => {
                this.updatePanelItem(item);
            });
 
            // Set hasChanges if there are queued items
            this.hasChanges = [...this.queue.values()].some(item =>
                ['queued', 'localProcessing', 'uploading'].includes(item.status)
            );
        } catch (error) {
            console.error('Error loading queue:', error);
            this.queue = new Map();
        }
    }
 
 
    /**
     * Save queue to localStorage
     */
    saveQueue() {
        try {
            // Filter items for storage
            const queueToSave = [...this.queue.values()].filter(item => {
                // Keep local items
                if (['queued', 'localProcessing', 'uploading'].includes(item.status)) {
                    return true;
                }
 
                // Keep completed items for a short while
                if (item.status === 'completed' && item.completed_at) {
                    const hourAgo = Date.now() - (60 * 60 * 1000);
                    return new Date(item.completed_at).getTime() > hourAgo;
                }
 
                // Keep failed items that might be retried
                return (item.status === 'failed' || item.status === 'failed_permanent') &&
                    item.retries < this.maxRetries;
            });
 
            // Serialize and store
            localStorage.setItem(this.STORAGE_KEY, JSON.stringify(queueToSave));
 
            // Also save stats for quick access
            localStorage.setItem(
                this.STORAGE_KEY + '_stats',
                JSON.stringify(this.getQueueStats())
            );
        } catch (error) {
            console.error('Error saving queue:', error);
            // If we hit storage limits, clean up
            this.emergencyQueueCleanup();
        }
    }
 
    /**
     * Emergency cleanup when storage is full
     */
    emergencyQueueCleanup() {
        console.warn('Emergency queue cleanup triggered');
 
        // Keep only essential pending items
        const tempQueue = this.queue;
        this.queue = new Map();
 
        for (const [key, item] of tempQueue.entries()) {
            if (item && item.status === 'pending') {
                this.queue.set(key, item);
            }
        }
 
        // Save the reduced queue
        try {
            localStorage.setItem(this.STORAGE_KEY, JSON.stringify([...this.queue.values()]));
            localStorage.removeItem(this.STORAGE_KEY + '_stats');
        } catch (error) {
            console.error('Failed even after cleanup:', error);
            // Last resort - clear everything
            localStorage.removeItem(this.STORAGE_KEY);
            localStorage.removeItem(this.STORAGE_KEY + '_stats');
        }
    }
 
    /**
     * Fetch operations from the server
     *
     * @param {boolean} initial Whether this is the initial fetch
     * @param {Object} options Filter options
     * @returns {Promise<Object>} Server response
     */
    async fetchOperations(initial = false, options = {}) {
        this.processing = true;
 
        // Start loading indicator
        if (this.refreshButton) {
            this.refreshButton.classList.add('refreshing');
        }
 
        try {
            // Build query parameters
            const params = new URLSearchParams();
 
            if (options.status) {
                params.append('status', options.status);
            }
 
            if (options.ids) {
                params.append('ids', Array.isArray(options.ids) ? options.ids.join(',') : options.ids);
            }
 
            if (options.limit) {
                params.append('limit', options.limit);
            }
 
            const url = `${this.API}?${params.toString()}`;
 
            // Set up fetch options
            const fetchOptions = {
                method: 'GET',
                headers: {
                    'X-WP-Nonce': jvbSettings.nonce
                }
            };
 
            // Add ETag support
            if (!initial && !options.force && this.pollingConfig.lastETag) {
                fetchOptions.headers['If-None-Match'] = this.pollingConfig.lastETag;
            }
 
            // Add If-Modified-Since as backup
            if (!initial && !options.force && this.lastPollTime) {
                fetchOptions.headers['If-Modified-Since'] = new Date(this.lastPollTime).toUTCString();
            }
 
            // Execute fetch
            const response = await fetch(url, fetchOptions);
 
            // If 304 Not Modified, nothing has changed
            if (response.status === 304) {
                this.pollingConfig.consecutiveNoChanges++;
                return { operations: [], cached: true };
            }
 
            // Store ETag for next request
            const etag = response.headers.get('ETag');
            if (etag) {
                this.pollingConfig.lastETag = etag;
            }
 
            // Reset consecutive no changes counter
            this.pollingConfig.consecutiveNoChanges = 0;
 
            // Update last poll time
            this.lastPollTime = new Date().toISOString();
 
            // Parse response
            const data = await response.json();
 
            // Process server operations
            if (data.operations && Array.isArray(data.operations)) {
                for (const op of data.operations) {
                    // Convert to expected format
                    const operation = {
                        id: op.id,
                        type: op.type,
                        data: op.data || {},
                        user: op.user_id,
                        status: op.status,
                        retries: op.retries || 0,
                        started_at: op.started_at,
                        created_at: op.created_at,
                        completed_at: op.completed_at,
                        estimated_completion: op.estimated_completion,
                        queue_position: op.queue_position,
                        error_message: op.error_message
                    };
 
                    // Update or add to local queue
                    this.updateItem(op.id, operation);
                }
            }
 
            // Update UI
            this.maybeAddEmptyState();
            this.updateStatusPanel();
            this.updateFilterCounts();
 
            return data;
        } catch (error) {
            console.error('Failed to fetch operations:', error);
 
            return { operations: [], error: true };
        } finally {
            // End loading indicator
            if (this.refreshButton) {
                this.refreshButton.classList.remove('refreshing');
            }
            this.processing = false;
        }
    }
 
    /**
     * Update a queue item
     *
     * @param {string} id Item ID
     * @param {Object} newData New data to merge
     * @returns {boolean} Success
     */
    updateItem(id, newData) {
        // If item doesn't exist yet, create it
        if (!this.queue.has(id)) {
            this.queue.set(id, {
                id,
                ...newData
            });
            this.saveQueue();
            this.updatePanelItem(this.queue.get(id));
            return true;
        }
 
        // Get existing item
        const item = this.queue.get(id);
        const oldStatus = item.status;
 
        // Merge updates
        const updated = {
            ...item,
            ...newData
        };
 
        // Start polling if server-side processing is happening
        if (['pending', 'processing'].includes(updated.status) &&
            oldStatus !== updated.status) {
            this.startPolling();
        }
 
        // Update queue
        this.queue.set(id, updated);
        this.saveQueue();
 
        // Update UI
        this.updatePanelItem(updated, oldStatus);
 
        // Handle status transitions
        if (oldStatus !== updated.status) {
            this.handleStatusChange(updated, oldStatus);
        }
 
        return true;
    }
 
    /**
     * Handle status change for an item
     *
     * @param {Object} item Item that changed
     * @param {string} oldStatus Previous status
     */
    handleStatusChange(item, oldStatus) {
        // Clear caches when operation completes
        if (item.status === 'completed' && oldStatus !== 'completed') {
            const cacheTypes = this.cacheTypesToClear[item.type];
            if (cacheTypes && cacheTypes.length > 0) {
                cacheTypes.forEach(cacheType => {
                    this.cache.clearByContent(cacheType);
                });
            }
 
            // Show completion notification
            this.addPopup(`${this.getOperationTitle(item)} completed`);
        }
        // Log failures
        else if (item.status === 'failed' && oldStatus !== 'failed') {
            this.errors.logErrorToServer('operation_failed', item.error_message || 'Operation failed', {
                operation_id: item.id,
                type: item.type,
                content_type: item.data.content,
                retries: item.retries
            });
 
            // Show failure notification
            this.addPopup(`Error: ${item.error_message || 'Unknown error'}`);
        }
    }
 
    /**
     * Update panel item in the UI
     *
     * @param {Object} item Item to update
     * @param {string} oldStatus Previous status
     */
    updatePanelItem(item, oldStatus = null) {
        // Find existing panel item or create new one
        let panelItem = this.panelList.querySelector(`.queue-item[data-id="${item.id}"]`);
        if (!panelItem) {
            panelItem = this.createPanelItem(item);
            return;
        }
 
        // Update status classes
        if (oldStatus) {
            panelItem.classList.remove(oldStatus);
        } else {
            this.statuses.forEach(status => panelItem.classList.remove(status));
        }
        panelItem.classList.add(item.status);
 
        // Update status text
        const statusElement = panelItem.querySelector('.queue-item-status');
        if (statusElement) {
            if (oldStatus) {
                statusElement.classList.remove(oldStatus);
            } else {
                this.statuses.forEach(status => statusElement.classList.remove(status));
            }
            statusElement.classList.add(item.status);
            statusElement.textContent = this.getStatusLabel(item.status);
        }
 
        // Update details
        const details = panelItem.querySelector('.queue-item-details');
        if (details) {
            const detailsText = details.querySelector('.details');
            if (detailsText) {
                detailsText.textContent = this.getItemMessage(item);
            }
 
            // Update completion time if available
            const completed = details.querySelector('.completed');
            if (completed && item.completed_at) {
                completed.textContent = `| Finished: ${window.formatTimeAgo(item.completed_at)}`;
            }
        }
 
        // Update progress bar
        const progressBar = panelItem.querySelector('.progress-bar .progress-fill');
        if (progressBar) {
            progressBar.style.width = `${this.calculateProgressPercentage(item)}%`;
        }
 
        // Update action buttons for completed/failed items
        if (['completed', 'failed', 'failed_permanent'].includes(item.status)) {
            const actionsContainer = panelItem.querySelector('.queue-item-actions');
            if (actionsContainer) {
                actionsContainer.innerHTML = this.renderActionButtons(item);
            }
        }
    }
 
    /**
     * Create a new panel item
     *
     * @param {Object} item Item to create
     * @returns {HTMLElement} Created panel item
     */
    createPanelItem(item) {
        const panelItem = document.createElement('div');
        panelItem.className = `queue-item ${item.status}`;
        panelItem.dataset.id = item.id;
        panelItem.dataset.type = item.type;
 
        // Format timestamps
        const timestamp = item.created_at ? new Date(item.created_at).getTime() : item.started_at;
        const timeDisplay = timestamp ? window.formatTimeAgo(new Date(timestamp)) : '';
 
        // Calculate progress
        const progressPercent = this.calculateProgressPercentage(item);
 
        // Get operation type display name
        let typeName = this.operationNames[item.type] || item.type;
        if (typeName && typeName.includes('Content') && item.data && item.data.content) {
            typeName = typeName.replace('Content', window.uppercaseFirst(item.data.content));
        }
 
        // Build HTML
        panelItem.innerHTML = `
            <div class="queue-item-header">
                <span class="queue-item-type">${typeName}</span>
                <span class="queue-item-status ${item.status}">
                    ${this.getStatusLabel(item.status)}
                </span>
                ${['completed', 'failed', 'failed_permanent'].includes(item.status) ?
            '<button class="queue-item-dismiss dismiss-operation" title="Dismiss">&times;</button>' : ''}
            </div>
 
            <div class="queue-item-progress">
                <div class="progress-bar">
                    <div class="progress-fill" style="width: ${progressPercent}%"></div>
                </div>
                <div class="progress-details">
                    ${item.progress ?
            `${item.progress.current || 0} of ${item.progress.total || '?'}` : ''}
                </div>
            </div>
 
            <div class="queue-item-details">
                <div class="details">${this.getItemMessage(item)}</div>
                <div class="time">
                    ${jvbSettings.icons.clock}
                    <span class="started">Started: ${timeDisplay}</span>
                    <span class="completed"></span>
                </div>
            </div>
 
            <div class="queue-item-actions">
                ${this.renderActionButtons(item)}
            </div>
        `;
 
        // Add to panel
        this.panelList.insertBefore(panelItem, this.panelList.firstChild);
 
        return panelItem;
    }
 
    /**
     * Get status label for display
     *
     * @param {string} status Operation status
     * @returns {string} Human-readable status
     */
    getStatusLabel(status) {
        switch (status) {
            case 'queued':
                return 'Received';
            case 'localProcessing':
                return 'Processing Data';
            case 'uploading':
                return 'Sending to Server';
            case 'pending':
                return 'Sent to Server';
            case 'processing':
                return 'Server processing';
            case 'completed':
                return 'Completed';
            case 'failed':
                return 'Failed';
            case 'failed_permanent':
                return 'Failed';
            default:
                return status;
        }
    }
 
    /**
     * Get detailed message for an item
     *
     * @param {Object} item Queue item
     * @returns {string} Detailed message
     */
    getItemMessage(item) {
        // Start with default message
        let message = this.statusMessages[item.status] || '';
 
        // Add position info if available
        if (item.queue_position) {
            if (item.queue_position === 0) {
                message += ' You are next in line.';
            } else {
                message += ` You are #${item.queue_position} in line.`;
            }
        }
 
        // Add estimated completion time if available
        if (item.estimated_completion) {
            message += `\nShould be done ${window.formatTimeSoon(item.estimated_completion)}`;
        }
 
        // Add error if failed
        if ((item.status === 'failed' || item.status === 'failed_permanent') && item.error_message) {
            message += `\nError: ${item.error_message}`;
        }
 
        return item.message || message;
    }
 
    /**
     * Render action buttons for an item
     *
     * @param {Object} item Queue item
     * @returns {string} HTML for action buttons
     */
    renderActionButtons(item) {
        if (item.status === 'failed' || item.status === 'failed_permanent') {
            return `
                <button class="retry-operation" ${item.retries >= this.maxRetries ? 'disabled' : ''}>
                    Retry
                </button>
                <button class="dismiss-operation">
                    Dismiss
                </button>
            `;
        }
 
        if (item.status === 'completed') {
            // Add refresh button for content updates
            let refresh = ['batch_creation', 'content_update'].includes(item.type)
                ? '<button class="refresh-content">Refresh</button>'
                : '';
 
            return `
                ${refresh}
                <button class="dismiss-operation">
                    Dismiss
                </button>
            `;
        }
 
        return '';
    }
 
    /**
     * Calculate progress percentage
     *
     * @param {Object} operation Operation
     * @returns {number} Progress percentage (0-100)
     */
    calculateProgressPercentage(operation) {
        switch (operation.status) {
            case 'queued':
            case 'failed':
            case 'failed_permanent':
                return 0;
 
            case 'localProcessing':
                // Use progress data if available
                if (operation.progress && operation.progress.current && operation.progress.total) {
                    return 5 + (35 * (operation.progress.current / operation.progress.total));
                }
                return 5;
 
            case 'uploading':
                return 40;
 
            case 'pending':
                return 65;
 
            case 'processing':
                if (operation.data && operation.data.progress) {
                    return 75 + (25 * (operation.data.progress.percentage / 100));
                }
                return 85;
 
            case 'completed':
                return 100;
 
            default:
                return 0;
        }
    }
 
    /**
     * Get operation title
     *
     * @param {Object} item Operation item
     * @returns {string} Human-readable title
     */
    getOperationTitle(item) {
        let message = this.operationNames[item.type] || item.type;
 
        if (message.includes('Content') && item.data && item.data.content) {
            return message.replace('Content', window.uppercaseFirst(item.data.content));
        }
 
        return message;
    }
 
    /**
     * Get popup message for an operation
     *
     * @param {Object} item Operation item
     * @returns {string} Message for popup
     */
    getPopupMessage(item) {
        switch (item.type) {
            case 'handle_vote':
                return 'Adding your voice...';
            case 'new_response':
                return 'Adding your voice...';
            case 'new_news':
                return 'Creating new news...';
            case 'image_upload':
                return 'Uploading image...';
            case 'user_settings':
                return 'Updating settings...';
            case 'content_update':
                return `Updating ${item.data.content}...`;
            case 'content_create':
                return `Creating new ${item.data.content}...`;
            case 'favourite_toggle':
                return 'Updating Favourites...';
            case 'invite_artist':
                return 'Inviting artists...';
            case 'bio_update':
                return 'Updating bio...';
            case 'batch_creation':
                return `Sending ${item.data.content} batch to server...`;
            case 'favourite_notes':
                return 'Processing note...';
            case 'favourite_list_create':
                return 'Processing new list...';
            case 'favourite_list_add':
                return 'Processing list changes...';
            case 'favourite_list_remove':
                return 'Processing list changes...';
            case 'favourite_list_delete':
                return 'Processing deletion...';
            case 'favourite_list_share':
                return 'Processing list sharing...';
            case 'favourite_list_unshare':
                return 'Processing un-share...';
            default:
                return `Processing ${item.type}...`;
        }
    }
 
    /**
     * Show popup message
     *
     * @param {string} message Message to show
     * @param {number} delay Time in ms to show popup
     */
    addPopup(message, delay = 2000) {
        if (!this.popup) return;
 
        this.a11y.announce(message);
        this.popup.innerHTML = message;
        this.popup.classList.add('showing');
 
        setTimeout(() => {
            this.popup.classList.remove('showing');
            setTimeout(() => {
                // Clear popup content after fadeout
                while (this.popup.firstChild) {
                    this.popup.removeChild(this.popup.firstChild);
                }
            }, 50);
        }, delay);
    }
 
 
    /**
     * Update network indicator
     */
    updateNetworkIndicator() {
        // Update UI based on online status
        if (this.panel) {
            this.panel.classList.toggle('offline', !navigator.onLine);
        }
    }
 
    /**
     * Update status panel
     *
     * @param {string} status Special status to display
     */
    updateStatusPanel(status) {
        if (!this.panel) return;
 
        // Get pending count for badge
        const pendingCount = [...this.queue.values()].filter(item =>
            ['queued', 'localProcessing', 'uploading'].includes(item.status)
        ).length;
 
        // Update indicator status
        this.panel.classList.remove('offline', 'pending', 'synced', 'image_processing');
 
        if (!navigator.onLine) {
            this.panel.classList.add('offline');
            this.addPopup('Looks like we\'re offline...');
        } else if (status === 'pending' || pendingCount > 0) {
            this.panel.classList.add('pending');
        } else if (status === 'image_processing') {
            this.panel.classList.add('image_processing');
            this.addPopup('Processing images...');
        } else if (status === 'synced' || pendingCount === 0) {
            this.panel.classList.add('synced');
        }
 
        // Update queue stats
        this.updateQueueStats();
    }
 
    /**
     * Update queue statistics
     */
    updateQueueStats() {
        // Calculate stats
        const stats = this.getQueueStats();
 
        // Update filter buttons with counts
        Object.entries(stats).forEach(([status, count]) => {
            const button = this.statusButtons[status];
            if (button) {
                button.dataset.count = count;
 
                // Update count badge
                if (count > 0) {
                    let badge = button.querySelector('.count-badge');
                    if (!badge) {
                        badge = document.createElement('span');
                        badge.className = 'count-badge';
                        button.appendChild(badge);
                    }
                    badge.textContent = count;
                } else {
                    const badge = button.querySelector('.count-badge');
                    if (badge) {
                        badge.remove();
                    }
                }
            }
        });
 
        // Update the status indicator badge
        const badgeCount = stats.queued + stats.localProcessing + stats.uploading;
        const statusIndicator = this.panel.querySelector('.queue-status-indicator');
        const statusCount = this.panel.querySelector('.queue-status-count');
 
        if (statusIndicator) {
            statusIndicator.classList.toggle('active', badgeCount > 0);
        }
 
        if (statusCount) {
            statusCount.textContent = badgeCount > 0 ? badgeCount : '';
        }
 
        // Update action buttons
        if (this.retryButton) {
            this.retryButton.disabled = stats.failed === 0;
        }
 
        if (this.clearButton) {
            this.clearButton.disabled = stats.completed === 0;
        }
    }
 
    /**
     * Get queue statistics
     *
     * @returns {Object} Queue statistics by status
     */
    getQueueStats() {
        const stats = {};
 
        // Initialize all statuses to 0
        this.statuses.forEach(status => {
            stats[status] = 0;
        });
 
        // Count items by status
        for (const item of this.queue.values()) {
            if (stats[item.status] !== undefined) {
                stats[item.status]++;
            }
        }
 
        return stats;
    }
 
 
    /**
     * Update filter counts
     */
    updateFilterCounts() {
        const stats = this.getQueueStats();
 
        if (this.filterButtons) {
            this.filterButtons.forEach(button => {
                const filter = button.dataset.filter;
                if (!filter || filter === 'all') return;
 
                const count = stats[filter] || 0;
                button.dataset.count = count;
 
                // Update badge
                let badge = button.querySelector('.count-badge');
                if (count > 0) {
                    if (!badge) {
                        badge = document.createElement('span');
                        badge.className = 'count-badge';
                        button.appendChild(badge);
                    }
                    badge.textContent = count;
                } else if (badge) {
                    badge.remove();
                }
            });
        }
    }
 
    /**
     * Process the queue
     *
     * @returns {Promise<void>}
     */
    async processQueue() {
        if (!this.hasChanges) return;
 
        // Check if we're online
        if (!navigator.onLine) {
            this.updateStatusPanel('offline');
            return;
        }
 
        try {
            // Find items that are ready to process
            const pendingItems = [...this.queue.values()].filter(item =>
                item.status === 'queued' &&
                (!item.retryAfter || item.retryAfter <= Date.now())
            );
 
            if (pendingItems.length === 0) {
                this.hasChanges = false;
                return;
            }
 
            // Only process a batch at a time
            const batchSize = 5;
            const itemsToProcess = pendingItems.slice(0, batchSize);
 
            // Update UI
            this.updateStatusPanel('pending');
 
            // Process each item
            for (const item of itemsToProcess) {
                try {
                    this.a11y.announce(`Now processing ${this.getOperationTitle(item)} locally.`);
 
                    await this.processItem(item);
 
                    this.a11y.announce('Finished sending to server.');
                } catch (error) {
                    // Log error
                    this.errors.log(error, {
                        component: 'QueueManager',
                        action: 'processQueue',
                        type: item.type,
                        operation_id: item.id
                    });
 
                    // Update item status
                    this.updateItem(item.id, {
                        status: (item.retries >= this.maxRetries - 1) ? 'failed_permanent' : 'failed',
                        error_message: error.message || 'Unknown error',
                        retries: (item.retries || 0) + 1,
                        retryAfter: (item.retries < this.maxRetries - 1) ?
                            Date.now() + (5000 * Math.pow(2, item.retries || 0)) : undefined
                    });
 
                    // Notify user
                    this.addPopup(`Error processing ${this.getOperationTitle(item)}: ${error.message || 'Unknown error'}`);
                }
            }
 
            // Update UI
            this.updateStatusPanel();
 
            // Check if there are more items to process
            const remainingPending = [...this.queue.values()].filter(item =>
                ['queued', 'localProcessing'].includes(item.status)
            ).length;
 
            if (remainingPending > 0) {
                // Schedule another processing round
                setTimeout(() => {
                    this.hasChanges = true;
                    this.processQueue();
                }, 1000);
            } else {
                this.hasChanges = false;
                this.updateStatusPanel('synced');
            }
        } catch (error) {
            console.error('Error in queue processing:', error);
            this.addPopup('Whoops! Something went wrong');
        }
    }
 
    /**
     * Process a single queue item
     *
     * @param {Object} item Queue item to process
     * @returns {Promise<void>}
     */
    async processItem(item) {
        this.updateItem(item.id, {status: 'localProcessing'});
 
        try {
            // Find the processor for this operation type
            const processor = this.processors[item.type];
            if (!processor) {
                throw new Error(`Unknown operation type: ${item.type}`);
            }
 
            // Process the item
            this.a11y.announce(`Processing ${this.getOperationTitle(item)} locally.`);
            const result = await processor(item);
 
            // Store result and update status
            this.updateItem(item.id, {
                result: result,
                status: 'pending'
            });
 
            this.a11y.announce(`${this.getOperationTitle(item)} sent to server for processing.`);
 
            // Start polling for status updates
            this.startPolling();
        } catch (error) {
            this.handleProcessError(item, error);
            throw error;
        }
    }
 
    /**
     * Handle processing error
     *
     * @param {Object} item Item that failed
     * @param {Error} error The error
     */
    handleProcessError(item, error) {
        console.error(`Error processing ${item.type}:`, error);
 
        const errorContext = {
            operation_id: item.id,
            type: item.type,
            content_type: item.data.content,
            attempt: (item.retries || 0) + 1
        };
 
        // Use ErrorHandler
        this.errors.log(error, {
            component: 'QueueManager',
            action: item.type,
            ...errorContext
        });
 
        // Update item
        this.updateItem(item.id, {
            status: (item.retries >= this.maxRetries - 1) ? 'failed_permanent' : 'failed',
            error_message: error.message || 'Unknown error',
            retries: (item.retries || 0) + 1,
            retryAfter: (item.retries < this.maxRetries - 1) ?
                Date.now() + (5000 * Math.pow(2, item.retries || 0)) : undefined
        });
 
        // Notify user
        this.addPopup(`Error processing ${this.getOperationTitle(item)}: ${error.message || 'Unknown error'}`);
    }
 
    /**
     * Make API request for an operation
     *
     * @param {Object} item Operation item
     * @param {string} endpoint API endpoint
     * @param {string} method HTTP method
     * @param {Object|FormData} data Request data
     * @param {Object} additionalHeaders Additional headers
     * @param {string} title Operation title for messages
     * @returns {Promise<Object>} Response data
     */
    async makeRequest(item, endpoint, method, data, additionalHeaders = {}, title) {
        this.updateItem(item.id, {status: 'uploading'});
 
 
        const isFormData = data instanceof FormData;
        const headers = {
            'X-WP-Nonce': jvbSettings.nonce,
            ...additionalHeaders
        };
 
        if (!isFormData && method !== 'GET') {
            headers['Content-Type'] = 'application/json';
        }
 
        console.log('Sending Data: ',data);
 
        try {
            const response = await fetch(`${jvbSettings.api}${endpoint}`, {
                method,
                headers,
                body: isFormData ? data : JSON.stringify(data)
            });
 
 
 
            if (!response.ok) {
                const errorData = await response.json().catch(() => ({}));
                throw new Error(errorData.message || `Request failed with s[tatus ${response.status}`);
            }
 
            return await response.json();
        } catch (error) {
            this.handleProcessError(item, error);
            throw error;
        }
    }
 
    /**
     * Start polling for operation status updates
     */
    startPolling() {
        this.stopPolling();
 
        const interval = this.getPollingInterval();
 
        // Log polling strategy (remove in production)
        console.log(`Polling in ${interval}ms (no-changes: ${this.pollingConfig.consecutiveNoChanges})`);
 
        if (this.pollingConfig.countdown && this.countdown) {
            this.startCountdown(interval / 1000);
        }
 
        this.pollingTimer = setTimeout(() => {
            this.fetchOperations(false).then((result) => {
                // Only continue polling if we have pending operations or recent activity
                const shouldContinue = this.hasServerPendingOperations() ||
                    (Date.now() - this.pollingConfig.lastUserActivity) < this.pollingConfig.inactiveThreshold;
 
                if (shouldContinue) {
                    this.startPolling();
                } else {
                    console.log('Stopping polling: no pending operations and user inactive');
                    this.stopPolling();
                    this.updateStatusPanel('synced');
                }
            });
        }, interval);
    }
 
    /**
     * Stop polling
     */
    stopPolling() {
        if (this.pollingTimer) {
            clearTimeout(this.pollingTimer);
            this.pollingTimer = null;
        }
 
        if (this.countdownTimer) {
            clearInterval(this.countdownTimer);
            this.countdownTimer = null;
        }
 
        // Remove refreshing state
        if (this.refreshButton) {
            this.refreshButton.classList.remove('refreshing');
        }
    }
 
    /**
     * Get adaptive polling interval
     *
     * @returns {number} Polling interval in milliseconds
     */
    getPollingInterval() {
        const now = Date.now();
        const timeSinceActivity = now - this.pollingConfig.lastUserActivity;
        const isUserActive = timeSinceActivity < this.pollingConfig.inactiveThreshold;
 
        // Base interval
        let interval = this.pollingConfig.interval;
 
        // Increase interval based on consecutive no-changes
        const noChangesCount = Math.min(
            this.pollingConfig.consecutiveNoChanges,
            this.pollingConfig.maxNoChangesCount
        );
 
        interval *= Math.pow(this.pollingConfig.backoffFactor, noChangesCount);
 
        // If user is inactive, poll less frequently
        if (!isUserActive) {
            interval *= 3; // Poll 3x less when user is inactive
        }
 
        // If we have pending operations, poll more frequently
        const hasPendingOps = this.hasServerPendingOperations();
        if (hasPendingOps && isUserActive) {
            interval = Math.max(interval * 0.5, this.pollingConfig.minInterval);
        }
 
        // Clamp between min and max
        return Math.min(
            Math.max(interval, this.pollingConfig.minInterval),
            this.pollingConfig.maxInterval
        );
    }
 
    /**
     * Start countdown timer
     *
     * @param {number} seconds Seconds to count down
     */
    startCountdown(seconds) {
        // Clear existing countdown
        if (this.countdownTimer) {
            clearInterval(this.countdownTimer);
        }
 
        if (!this.countdown) return;
 
        // Set initial value
        let remainingSeconds = Math.round(seconds);
        this.countdown.textContent = remainingSeconds;
        this.countdown.classList.add('counting');
 
        // Start countdown
        this.countdownTimer = setInterval(() => {
            remainingSeconds--;
 
            if (remainingSeconds <= 0) {
                clearInterval(this.countdownTimer);
                this.countdownTimer = null;
                this.countdown.textContent = '';
                this.countdown.classList.remove('counting');
                return;
            }
 
            this.countdown.textContent = remainingSeconds;
        }, 1000);
    }
 
 
    /**
     * Check if there are pending operations on the server
     *
     * @returns {boolean} Whether there are pending server operations
     */
    hasServerPendingOperations() {
        return [...this.queue.values()].some(item =>
            item.status === 'pending' ||
            item.status === 'processing'
        );
    }
 
    /**
     * Retry a failed operation
     *
     * @param {string} operationId ID of operation to retry
     */
    retryOperation(operationId) {
        const operation = this.queue.get(operationId);
 
        if (operation && (operation.status === 'failed' || operation.status === 'failed_permanent')) {
            // Send request to server
            fetch(`${this.API}`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-WP-Nonce': jvbSettings.nonce
                },
                body: JSON.stringify({
                    ids: operationId,
                    action: 'retry'
                })
            }).then(response => {
                if (!response.ok) {
                    throw new Error('Failed to retry operation');
                }
                return response.json();
            }).then(data => {
                if (data.success) {
                    // Update local status
                    this.updateItem(operationId, {
                        status: 'pending',
                        error_message: null
                    });
 
                    // Start polling for status updates
                    this.startPolling();
 
                    // Show notification
                    this.addPopup('Operation queued for retry');
                }
            }).catch(error => {
                console.error('Error retrying operation:', error);
                this.addPopup('Failed to retry operation');
            });
        }
    }
 
    /**
     * Retry all failed operations
     */
    retryFailedOperations() {
        // Find failed operations
        const failedIds = [...this.queue.values()]
            .filter(item =>
                (item.status === 'failed' || item.status === 'failed_permanent') &&
                item.retries < this.maxRetries
            )
            .map(item => item.id);
 
        if (failedIds.length === 0) return;
 
        // Confirm with user
        if (confirm(`Retry ${failedIds.length} failed operations?`)) {
            // Send request to server
            fetch(`${this.API}`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-WP-Nonce': jvbSettings.nonce
                },
                body: JSON.stringify({
                    ids: failedIds.join(','),
                    action: 'retry'
                })
            }).then(response => {
                if (!response.ok) {
                    throw new Error('Failed to retry operations');
                }
                return response.json();
            }).then(data => {
                if (data.success) {
                    // Update local status for each operation
                    failedIds.forEach(id => {
                        this.updateItem(id, {
                            status: 'pending',
                            error_message: null
                        });
                    });
 
                    // Start polling for status updates
                    this.startPolling();
 
                    // Show notification
                    this.addPopup(`Retrying ${failedIds.length} operations...`);
                }
            }).catch(error => {
                console.error('Error retrying operations:', error);
                this.addPopup('Failed to retry operations');
            });
        }
    }
 
    /**
     * Clear completed operations
     */
    clearCompletedOperations() {
        // Find completed operations
        const completedIds = [...this.queue.values()]
            .filter(item => item.status === 'completed')
            .map(item => item.id);
 
        if (completedIds.length === 0) return;
 
        // Dismiss operations
        this.dismissOperations(completedIds);
    }
 
    /**
     * Dismiss operations
     *
     * @param {string[]} operationIds IDs of operations to dismiss
     */
    dismissOperations(operationIds) {
        if (!operationIds.length) return;
 
        // Send request to server
        fetch(`${this.API}`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-WP-Nonce': jvbSettings.nonce
            },
            body: JSON.stringify({
                ids: operationIds.join(','),
                action: 'dismiss'
            })
        }).then(response => {
            if (!response.ok) {
                throw new Error('Failed to dismiss operations');
            }
            return response.json();
        }).then(data => {
            if (data.success) {
                // Remove from local queue
                operationIds.forEach(id => {
                    // Remove from UI with animation
                    const item = this.panelList.querySelector(`.queue-item[data-id="${id}"]`);
                    if (item) {
                        item.style.opacity = '0';
                        item.style.transition = 'opacity 0.3s ease-out';
                        setTimeout(() => {
                            item.remove();
                            this.maybeAddEmptyState();
                        }, 300);
                    }
 
                    // Remove from queue
                    this.queue.delete(id);
                });
 
                // Save updated queue
                this.saveQueue();
 
                // Update UI
                this.updateQueueStats();
                this.updateFilterCounts();
 
                // Notify user
                this.a11y.announce('Removed completed tasks');
            }
        }).catch(error => {
            console.error('Error dismissing operations:', error);
            this.addPopup('Failed to dismiss operations');
        });
    }
 
    //INDIVIDUAL PROCESSORS
    /**
     * Process vote operation
     *
     * @param {Object} item Queue item
     * @returns {Promise<Object>} Operation result
     */
    async processVote(item) {
        item.data.id = item.id;
        return await this.makeRequest(
            item,
            'vote',
            'POST',
            item.data,
            {},
            'Adding Your Voice'
        );
    }
 
    /**
     * Process artist invite operation
     *
     * @param {Object} item Queue item
     * @returns {Promise<Object>} Operation result
     */
    async processArtistInvite(item) {
        const data = {
            user: jvbSettings.currentUser,
            invites: item.data,
            id: item.id
        };
 
        return await this.makeRequest(
            item,
            'invitations',
            'POST',
            data,
            { 'action_nonce': jvbSettings.dash },
            'Inviting Artist'
        );
    }
 
    /**
     * Process new news operation
     *
     * @param {Object} item Queue item
     * @returns {Promise<Object>} Operation result
     */
    async processNewNews(item) {
        const formData = new FormData();
 
        // Append all data from item
        for (const [key, value] of Object.entries(item.data)) {
            formData.append(key, value);
        }
 
        formData.append('id', item.id);
 
        return await this.makeRequest(
            item,
            'news',
            'POST',
            formData,
            { 'action_nonce': jvbSettings.dash },
            'Adding News Post'
        );
    }
 
    /**
     * Process new response operation
     *
     * @param {Object} item Queue item
     * @returns {Promise<Object>} Operation result
     */
    async processNewResponse(item) {
        item.data.id = item.id;
        return await this.makeRequest(
            item,
            'response',
            'POST',
            item.data,
            {},
            'Adding your response'
        );
    }
 
    /**
     * Process settings update operation
     *
     * @param {Object} item Queue item
     * @returns {Promise<Object>} Operation result
     */
    async processSettingsUpdate(item) {
        const formData = new FormData();
 
        // Append all data fields
        for (const [key, value] of Object.entries(item.data)) {
            formData.append(key, value);
        }
 
        formData.append('id', item.id);
 
        return await this.makeRequest(
            item,
            'settings',
            'POST',
            formData,
            { 'action_nonce': jvbSettings.dash },
            'Updating Settings'
        );
    }
 
    /**
     * Process bio update operation
     *
     * @param {Object} item Queue item
     * @returns {Promise<Object>} Operation result
     */
    async processBioUpdate(item) {
 
 
        item.data.id = item.id;
        console.log(item);
        console.log(item.data);
 
        return await this.makeRequest(
            item,
            'bio',
            'POST',
            item.data,
            { 'action_nonce': jvbSettings.dash },
            'Updating Bio'
        );
    }
 
    /**
     * Process content update operation
     *
     * @param {Object} item Queue item
     * @returns {Promise<Object>} Operation result
     */
    async processContentUpdate(item) {
        const apiData = {
            id: item.id,
            user: item.user,
            posts: item.data.posts || {},
            content: item.data.content
        };
 
        return await this.makeRequest(
            item,
            'set',
            'POST',
            apiData,
            { 'action_nonce': jvbSettings.dash },
            'Updating Content'
        );
    }
 
    /**
     * Process content creation operation
     *
     * @param {Object} item Queue item
     * @returns {Promise<Object>} Operation result
     */
    async processContentCreation(item) {
        const apiData = {
            id: item.id,
            content: item.data.content,
            ...item.data
        };
 
        return await this.makeRequest(
            item,
            'create',
            'POST',
            apiData,
            { 'action_nonce': jvbSettings.dash },
            `Creating ${item.data.content === 'artwork' ? 'Artwork' : window.uppercaseFirst(item.data.content)+'s'}`
        );
    }
 
    /**
     * Process batch creation operation
     *
     * @param {Object} item Queue item
     * @returns {Promise<Object>} Operation result
     */
    async processBatchCreation(item) {
        const formData = new FormData();
 
        // Add common data
        formData.append('content', item.data.content);
        formData.append('user', item.data.user);
        formData.append('mode', item.data.mode);
        formData.append('id', item.id);
 
        // Process each batch
        item.data.files.forEach((batch, batchIndex) => {
            if (!batch.files || !Array.isArray(batch.files)) {
                console.error('Invalid batch structure:', batch);
                return;
            }
 
            // Add files for this batch - batch.files contains objects with {file: File, metadata: {}}
            batch.files.forEach((fileObj, fileIndex) => {
                // Extract the actual File object
                const file = fileObj.file || fileObj.processedFile || fileObj;
 
                if (file instanceof File) {
                    formData.append(`files[${batchIndex}][${fileIndex}]`, file);
                } else {
                    console.error('Invalid file object:', fileObj);
                }
            });
 
            // Add metadata for this batch - combine individual file metadata
            const batchMetadata = {
                type: batch.type,
                metadata: batch.metadata || {},
                files_metadata: batch.files.map(fileObj => fileObj.metadata || {})
            };
 
            formData.append(`files_data[${batchIndex}]`, JSON.stringify(batchMetadata));
        });
 
        return await this.makeRequest(
            item,
            'create/batch',
            'POST',
            formData,
            { 'action_nonce': jvbSettings.dash },
            `Creating ${item.data.content === 'artwork' ? 'Artwork' : window.uppercaseFirst(item.data.content)+'s'}`
        );
    }
 
    /**
     * Process file upload operation
     *
     * @param {Object} item Queue item
     * @returns {Promise<Object>} Operation result
     */
    async processFileUpload(item) {
        const formData = new FormData();
 
        // Add common fields
        formData.append('content', item.data.content);
        formData.append('user', item.data.user);
        formData.append('id', item.id);
        formData.append('mode', item.data.mode);
 
        // Add optional fields
        if (item.data.postId) {
            formData.append('post_id', item.data.postId);
        }
 
        if (item.data.termId) {
            formData.append('term_id', item.data.termId);
        }
 
        if (item.data.fieldName) {
            formData.append('field_name', item.data.fieldName);
        }
 
        console.log('Processing files for upload:', item.data.files);
 
        // Handle files properly based on structure
        if (item.data.files && Array.isArray(item.data.files)) {
            let fileIndex = 0;
 
            item.data.files.forEach((fileGroup, groupIndex) => {
                console.log(`Processing group ${groupIndex}:`, fileGroup);
 
                if (fileGroup.files && Array.isArray(fileGroup.files)) {
                    fileGroup.files.forEach((fileObj) => {
                        // Extract the actual File object
                        let file = null;
 
                        if (fileObj instanceof File) {
                            file = fileObj;
                        } else if (fileObj.file instanceof File) {
                            file = fileObj.file;
                        } else if (fileObj.processedFile instanceof File) {
                            file = fileObj.processedFile;
                        }
 
                        if (file) {
                            console.log(`Adding file ${fileIndex}:`, file.name, file.size, file.type);
                            formData.append(`files[${fileIndex}]`, file);
 
                            // Add metadata if available
                            if (fileObj.metadata) {
                                formData.append(`metadata[${fileIndex}]`, JSON.stringify(fileObj.metadata));
                            }
 
                            fileIndex++;
                        } else {
                            console.error('Invalid file object:', fileObj);
                        }
                    });
                } else {
                    console.error('Invalid file group structure:', fileGroup);
                }
            });
 
            console.log(`Total files added to FormData: ${fileIndex}`);
        }
 
        return await this.makeRequest(
            item,
            'uploads',
            'POST',
            formData,
            { 'action_nonce': jvbSettings.dash },
            'Uploading Files'
        );
    }
 
    /**
     * Process favourite toggle operation
     *
     * @param {Object} item Queue item
     * @returns {Promise<Object>} Operation result
     */
    async processFavourite(item) {
        const batchData = {
            adds: [],
            removes: [],
            id: item.id,
            user: item.user
        };
 
        // Sort adds and removes
        item.data.forEach(favItem => {
            const action = favItem.action;
            const itemCopy = {...favItem};
            delete itemCopy.action;
 
            if (action === 'add') {
                batchData.adds.push(itemCopy);
            } else {
                batchData.removes.push(itemCopy);
            }
        });
 
        return await this.makeRequest(
            item,
            'favourites',
            'POST',
            batchData,
            { 'action_nonce': jvbSettings.dash },
            'Setting Favourites'
        );
    }
 
    /**
     * Process favourite notes operation
     *
     * @param {Object} item Queue item
     * @returns {Promise<Object>} Operation result
     */
    async processFavouriteNotes(item) {
        return await this.makeRequest(
            item,
            'favourites',
            'POST',
            {
                operation: 'update_notes',
                type: item.data.type,
                target_id: item.data.target_id,
                notes: item.data.notes,
                id: item.id
            },
            { 'action_nonce': jvbSettings.favourites },
            'Saving Note'
        );
    }
 
    /**
     * Process favourite list create operation
     *
     * @param {Object} item Queue item
     * @returns {Promise<Object>} Operation result
     */
    async processFavouriteListCreate(item) {
        return await this.makeRequest(
            item,
            'favourites/lists',
            'POST',
            {
                operation: 'create',
                name: item.data.name,
                description: item.data.description,
                items: item.data.items,
                id: item.id
            },
            { 'action_nonce': jvbSettings.favourites },
            'Creating List'
        );
    }
 
    /**
     * Process adding items to a favourite list
     *
     * @param {Object} item Queue item
     * @returns {Promise<Object>} Operation result
     */
    async processFavouriteListAddItems(item) {
        return await this.makeRequest(
            item,
            'favourites/lists',
            'POST',
            {
                id: item.id,
                items: item.data.items,
                list_id: item.data.list_id,
                operation: 'add_items'
            },
            { 'action_nonce': jvbSettings.favourites },
            'Adding to List'
        );
    }
 
    /**
     * Process removing items from a favourite list
     *
     * @param {Object} item Queue item
     * @returns {Promise<Object>} Operation result
     */
    async processFavouriteListRemoveItems(item) {
        return await this.makeRequest(
            item,
            'favourites/lists',
            'POST',
            {
                id: item.id,
                items: item.data.items,
                list_id: item.data.list_id,
                operation: 'remove_items'
            },
            { 'action_nonce': jvbSettings.favourites },
            'Removing from List'
        );
    }
 
    /**
     * Process favourite list delete operation
     *
     * @param {Object} item Queue item
     * @returns {Promise<Object>} Operation result
     */
    async processFavouriteListDelete(item) {
        return await this.makeRequest(
            item,
            'favourites/lists',
            'POST',
            {
                operation: 'delete',
                list_id: item.id
            },
            { 'action_nonce': jvbSettings.favourites },
            'Deleting list'
        );
    }
 
    /**
     * Process favourite list share operation
     *
     * @param {Object} item Queue item
     * @returns {Promise<Object>} Operation result
     */
    async processFavouriteListShare(item) {
        return await this.makeRequest(
            item,
            'favourites/lists/shares',
            'POST',
            {
                operation: 'add',
                email: item.data.email,
                list_id: item.id},
            { 'action_nonce': jvbSettings.favourites },
            'Sharing List'
        );
    }
 
    /**
     * Process favourite list unshare operation
     *
     * @param {Object} item Queue item
     * @returns {Promise<Object>} Operation result
     */
    async processFavouriteListUnshare(item) {
        return await this.makeRequest(
            item,
            'favourites/lists/shares',
            'POST',
            {
                operation: 'remove',
                email: item.data.email,
                list_id: item.id
            },
            { 'action_nonce': jvbSettings.favourites },
            'Removing Share Access'
        );
    }
 
    /**
     * Try to merge similar operations to reduce queue size
     *
     * @param {Object} operation New operation
     * @returns {Object|false} Merged operation or false if no merge
     */
    mergeOperations(operation) {
        // Find pending operations of the same type
        const pendingOperations = [...this.queue.values()].filter(item =>
            item.status === 'queued' &&
            item.type === operation.type
        );
 
        if (pendingOperations.length === 0) return false;
 
        // Handle based on operation type
        switch (operation.type) {
            case 'content_update':
                return this.mergeContentUpdates(pendingOperations, operation);
 
            case 'user_settings':
            case 'bio_update':
                return this.mergeSettingsUpdates(pendingOperations, operation);
 
            case 'favourite_toggle':
                return this.mergeFavouriteToggles(pendingOperations, operation);
 
            case 'image_upload':
                return this.mergeImageUploads(pendingOperations, operation);
 
            default:
                return false;
        }
    }
 
    /**
     * Merge content update operations
     *
     * @param {Array} existingOperations Existing operations
     * @param {Object} newOperation New operation
     * @returns {Object|false} Merged operation or false
     */
    mergeContentUpdates(existingOperations, newOperation) {
        if (!existingOperations.length) return false;
 
        // Start with empty set of merged posts
        const mergedPosts = {};
 
        // Gather existing post data
        existingOperations.forEach(operation => {
            if (!operation.data || !operation.data.posts) return;
 
            Object.entries(operation.data.posts).forEach(([postID, postData]) => {
                if (!mergedPosts[postID]) {
                    mergedPosts[postID] = { ...postData };
                } else {
                    mergedPosts[postID] = this.mergePostData(mergedPosts[postID], postData);
                }
            });
        });
 
        // Merge in new operation's posts
        if (newOperation.data && newOperation.data.posts) {
            Object.entries(newOperation.data.posts).forEach(([postID, postData]) => {
                if (!mergedPosts[postID]) {
                    mergedPosts[postID] = { ...postData };
                } else {
                    mergedPosts[postID] = this.mergePostData(mergedPosts[postID], postData);
                }
            });
        }
 
        // Remove all pending content updates
        existingOperations.forEach(op => {
            this.queue.delete(op.id);
        });
 
        // Return merged operation
        return {
            type: 'content_update',
            data: {
                posts: mergedPosts,
                content: newOperation.data.content
            }
        };
    }
 
    /**
     * Merge post data from multiple updates
     *
     * @param {Object} existing Existing post data
     * @param {Object} update New post data
     * @returns {Object} Merged post data
     */
    mergePostData(existing, update) {
        const merged = { ...existing };
 
        // Ensure content stays consistent
        merged.content = existing.content;
 
        // Merge fields
        Object.entries(update).forEach(([key, value]) => {
            if (key === 'taxonomies') {
                // Special handling for taxonomies
                merged.taxonomies = merged.taxonomies || {};
                Object.entries(value).forEach(([taxKey, terms]) => {
                    // Keep most recent terms
                    merged.taxonomies[taxKey] = [...terms];
                });
            } else if (key !== 'content') {
                // For other fields, take newest value
                merged[key] = value;
            }
        });
 
        return merged;
    }
 
    /**
     * Merge settings update operations
     *
     * @param {Array} existingOperations Existing operations
     * @param {Object} newOperation New operation
     * @returns {Object|false} Merged operation or false
     */
    mergeSettingsUpdates(existingOperations, newOperation) {
        if (!existingOperations.length) return false;
 
        // Get most recent state of each field
        const mergedFields = {};
 
        // Gather existing fields
        existingOperations.forEach(operation => {
            if (!operation.data) return;
 
            Object.entries(operation.data).forEach(([field, value]) => {
                // Skip user field
                if (field !== 'user') {
                    if (Array.isArray(value)) {
                        // For arrays, merge and remove duplicates
                        mergedFields[field] = mergedFields[field] || [];
                        mergedFields[field] = [...new Set([...mergedFields[field], ...value])];
                    } else {
                        // For regular fields, take latest value
                        mergedFields[field] = value;
                    }
                }
            });
        });
 
        // Merge in new operation's fields
        if (newOperation.data) {
            Object.entries(newOperation.data).forEach(([field, value]) => {
                if (field !== 'user') {
                    if (Array.isArray(value)) {
                        mergedFields[field] = mergedFields[field] || [];
                        mergedFields[field] = [...new Set([...mergedFields[field], ...value])];
                    } else {
                        mergedFields[field] = value;
                    }
                }
            });
        }
 
        // Remove pending operations
        existingOperations.forEach(op => {
            this.queue.delete(op.id);
        });
 
        // Return merged operation
        return {
            type: newOperation.type,
            data: {
                user: newOperation.data.user,
                ...mergedFields
            }
        };
    }
 
    /**
     * Merge favourite toggle operations
     *
     * @param {Array} existingOperations Existing operations
     * @param {Object} newOperation New operation
     * @returns {Object|false} Merged operation or false
     */
    mergeFavouriteToggles(existingOperations, newOperation) {
        if (!existingOperations.length || !newOperation.data || !newOperation.data[0]) return false;
 
        // Find toggle for this target
        const targetId = newOperation.data[0].target_id;
        const targetType = newOperation.data[0].type;
 
        const existingOperation = existingOperations.find(op =>
            op.data && op.data[0] &&
            op.data[0].target_id === targetId &&
            op.data[0].type === targetType
        );
 
        if (existingOperation) {
            // Use latest toggle action
            this.queue.delete(existingOperation.id);
            return newOperation;
        }
 
        return false;
    }
 
    /**
     * Merge image upload operations
     *
     * @param {Array} existingOperations Existing operations
     * @param {Object} newOperation New operation
     * @returns {Object|false} Merged operation or false
     */
    mergeImageUploads(existingOperations, newOperation) {
        if (!existingOperations.length || !newOperation.data) return false;
 
        // Only merge if there's a groupId
        if (!newOperation.data.groupId) return false;
 
        // Find uploads with same groupId
        const groupUploads = existingOperations.filter(op =>
            op.data && op.data.groupId === newOperation.data.groupId
        );
 
        if (!groupUploads.length) return false;
 
        // Collect all files from group
        const files = [];
 
        // Add files from existing operations
        groupUploads.forEach(op => {
            if (op.data.files) {
                files.push(...op.data.files);
            } else if (op.data.file) {
                files.push(op.data.file);
            }
        });
 
        // Add files from new operation
        if (newOperation.data.files) {
            files.push(...newOperation.data.files);
        } else if (newOperation.data.file) {
            files.push(newOperation.data.file);
        }
 
        // Remove individual uploads
        groupUploads.forEach(op => {
            this.queue.delete(op.id);
        });
 
        // Return batch operation
        return {
            type: 'image_upload',
            data: {
                groupId: newOperation.data.groupId,
                content: newOperation.data.content,
                postId: newOperation.data.postId,
                fieldName: newOperation.data.fieldName,
                files: files
            }
        };
    }
 
    //TODO: Still necessary?
    /**
     * Initialize the refresh button
     */
    initRefreshButton() {
 
        this.refreshButton.addEventListener('click', () => {
            if(this.refreshedOnce && this.panelList.children.length === 1 && this.panelList.children[0].classList.contains('no-operations')){
                this.addPopup('Nothing to refresh');
                return;
            }
            this.refreshedOnce = true;
            // Show refreshing state
            this.refreshButton.classList.add('refreshing');
 
            // Clear existing countdown and polling
            this.stopPolling();
 
            // Get current filter
            const activeFilter = this.filterButtonsContainer.querySelector('.active');
            const currentFilter = activeFilter ? activeFilter.dataset.filter : 'all';
 
            // Fetch operations with current filter and force flag
            this.fetchOperations({
                initial: false,
                force: true
            }).then(() => {}).finally(() => {
                // Remove refreshing state
                this.refreshButton.classList.remove('refreshing');
            });
        });
    }
}
 
// Initialize QueueManager on page load
document.addEventListener('DOMContentLoaded', () => {
    window.jvbQueue = new QueueManagerBackup();
});
 
// Theme switching functionality
document.addEventListener('DOMContentLoaded', function() {
    const themeSwitch = document.getElementById('theme-switch');
 
    if (!themeSwitch) return;
 
    // Initialize theme from localStorage or system preference
    const prefersDark = window.matchMedia('(prefers-color-scheme: dark)');
    const storedTheme = localStorage.getItem('theme');
 
    if (storedTheme) {
        document.documentElement.classList.toggle('dark', storedTheme === 'dark');
        themeSwitch.checked = storedTheme === 'dark';
    } else {
        document.documentElement.classList.toggle('dark', prefersDark.matches);
        themeSwitch.checked = prefersDark.matches;
    }
 
    // Handle theme switch changes
    themeSwitch.addEventListener('change', async function () {
        const isDark = this.checked;
        document.documentElement.classList.toggle('dark', isDark);
        localStorage.setItem('theme', isDark ? 'dark' : 'light');
 
        // If user is logged in, save preference
        if (jvbSettings.currentUser !== null) {
            try {
                await fetch(`${jvbSettings.api}settings`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'X-WP-Nonce': jvbSettings.nonce,
                        'action_nonce': jvbSettings.dash,
                    },
                    body: JSON.stringify({
                        dark_mode: isDark
                    })
                });
            } catch (error) {
                console.error('Failed to save theme preference:', error);
            }
        }
 
        // Update label
        const label = document.getElementById('theme-switch');
        if (label) {
            label.title = isDark ? 'Toggle Light Mode' : 'Toggle Dark Mode';
        }
    });
 
    // Handle system theme changes
    prefersDark.addEventListener('change', (e) => {
        if (!localStorage.getItem('theme')) {
            const isDark = e.matches;
            document.documentElement.classList.toggle('dark', isDark);
            themeSwitch.checked = isDark;
        }
    });
});