Spaces:
Pradeepccc
/
a
Running on Zero

a
File size: 90,149 Bytes
e9017a4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
<!DOCTYPE html>
<html lang="en" class="dark">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Qwen Studio 2.1 - Uncensored All-In-One LoRA Studio</title>
  
  <!-- Plus Jakarta Sans & JetBrains Mono Fonts -->
  <link rel="preconnect" href="https://fonts.googleapis.com">
  <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
  <link href="https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@300;400;500;600;700;800&family=JetBrains+Mono:wght@400;500;600&display=swap" rel="stylesheet">
  
  <!-- Lucide Icons & SortableJS -->
  <script src="https://unpkg.com/lucide@latest"></script>
  <script src="https://cdn.jsdelivr.net/npm/sortablejs@1.15.2/Sortable.min.js"></script>

  <!-- Tailwind CSS CDN -->
  <script src="https://cdn.tailwindcss.com"></script>
  <script>
    tailwind.config = {
      darkMode: 'class',
      theme: {
        extend: {
          fontFamily: {
            sans: ['"Plus Jakarta Sans"', 'system-ui', '-apple-system', 'sans-serif'],
            mono: ['"JetBrains Mono"', 'monospace'],
          },
          colors: {
            border: 'var(--border)',
            input: 'var(--input)',
            ring: 'var(--ring)',
            background: 'var(--background)',
            foreground: 'var(--foreground)',
            card: {
              DEFAULT: 'var(--card)',
              foreground: 'var(--foreground)',
            },
            primary: {
              DEFAULT: 'var(--primary)',
              foreground: 'var(--primary-foreground)',
            },
            secondary: {
              DEFAULT: 'var(--secondary)',
              foreground: 'var(--secondary-foreground)',
            },
            muted: {
              DEFAULT: 'var(--muted)',
              foreground: 'var(--muted-foreground)',
            },
            accent: {
              DEFAULT: 'var(--accent)',
              foreground: 'var(--accent-foreground)',
            },
          },
          borderRadius: {
            lg: '8px',
            md: '8px',
            sm: '8px',
          }
        }
      }
    }
  </script>

  <style>
    /* CSS Variables for Shadcn Monochromatic Theme */
    :root {
      --background: #ffffff;
      --foreground: #09090b;
      --card: #ffffff;
      --border: #e4e4e7;
      --input: #e4e4e7;
      --primary: #18181b;
      --primary-foreground: #fafafa;
      --secondary: #f4f4f5;
      --secondary-foreground: #18181b;
      --muted: #f4f4f5;
      --muted-foreground: #71717a;
      --accent: #f4f4f5;
      --accent-foreground: #18181b;
      --ring: #18181b;
    }
    .dark {
      --background: #09090b;
      --foreground: #fafafa;
      --card: #111114;
      --border: #27272a;
      --input: #27272a;
      --primary: #fafafa;
      --primary-foreground: #18181b;
      --secondary: #18181b;
      --secondary-foreground: #fafafa;
      --muted: #18181b;
      --muted-foreground: #a1a1aa;
      --accent: #1e1e22;
      --accent-foreground: #fafafa;
      --ring: #d4d4d8;
    }

    body {
      background-color: var(--background);
      color: var(--foreground);
      font-family: 'Plus Jakarta Sans', system-ui, sans-serif;
      letter-spacing: -0.011em;
      line-height: 1.5;
      transition: background-color 0.2s ease, color 0.2s ease;
      min-height: 100vh;
    }

    /* Custom input & button styles for 8px uniform radius */
    input, select, textarea {
      border: 1px solid var(--border);
      background-color: var(--background);
      color: var(--foreground);
      border-radius: 8px;
    }
    input:focus, select:focus, textarea:focus {
      outline: none;
      border-color: var(--ring);
      box-shadow: 0 0 0 1px var(--ring);
    }

    /* Drag & drop active highlight styles */
    .drag-active {
      border-color: var(--foreground) !important;
      background-color: var(--accent) !important;
      transform: scale(1.01);
    }

    /* Modal Backdrop */
    .modal-backdrop {
      background-color: rgba(0, 0, 0, 0.85);
      backdrop-filter: blur(4px);
    }
  </style>
</head>
<body class="p-4 sm:p-6 lg:p-8 flex flex-col items-center">

  <!-- TAILWIND CONTAINER (MAX-W-[1440PX], CENTERED MX-AUTO, NOT FULL WIDTH) -->
  <div class="w-full max-w-[1440px] mx-auto flex flex-col gap-6">

    <!-- NAVBAR HEADER -->
    <header class="w-full flex items-center justify-between p-4 border border-border rounded-lg bg-card shadow-sm">
      <div class="flex items-center gap-4 flex-wrap">
        <div class="flex items-center gap-3">
          <!-- Official Alibaba Qwen Logo: Vector SVG, no shadow, no border -->
          <div class="w-8 h-8 flex-shrink-0 flex items-center justify-center">
            <svg class="w-8 h-8 text-foreground" viewBox="0 0 24 24" fill="currentColor" fill-rule="evenodd" xmlns="http://www.w3.org/2000/svg">
              <path d="M12.604 1.34c.393.69.784 1.382 1.174 2.075a.18.18 0 00.157.091h5.552c.174 0 .322.11.446.327l1.454 2.57c.19.337.24.478.024.837-.26.43-.513.864-.76 1.3l-.367.658c-.106.196-.223.28-.04.512l2.652 4.637c.172.301.111.494-.043.77-.437.785-.882 1.564-1.335 2.34-.159.272-.352.375-.68.37-.777-.016-1.552-.01-2.327.016a.099.099 0 00-.081.05 575.097 575.097 0 01-2.705 4.74c-.169.293-.38.363-.725.364-.997.003-2.002.004-3.017.002a.537.537 0 01-.465-.271l-1.335-2.323a.09.09 0 00-.083-.049H4.982c-.285.03-.553-.001-.805-.092l-1.603-2.77a.543.543 0 01-.002-.54l1.207-2.12a.198.198 0 000-.197 550.951 550.951 0 01-1.875-3.272l-.79-1.395c-.16-.31-.173-.496.095-.965.465-.813.927-1.625 1.387-2.436.132-.234.304-.334.584-.335a338.3 338.3 0 012.589-.001.124.124 0 00.107-.063l2.806-4.895a.488.488 0 01.422-.246c.524-.001 1.053 0 1.583-.006L11.704 1c.341-.003.724.032.9.34zm-3.432.403a.06.06 0 00-.052.03L6.254 6.788a.157.157 0 01-.135.078H3.253c-.056 0-.07.025-.041.074l5.81 10.156c.025.042.013.062-.034.063l-2.795.015a.218.218 0 00-.2.116l-1.32 2.31c-.044.078-.021.118.068.118l5.716.008c.046 0 .08.02.104.061l1.403 2.454c.046.081.092.082.139 0l5.006-8.76.783-1.382a.055.055 0 01.096 0l1.424 2.53a.122.122 0 00.107.062l2.763-.02a.04.04 0 00.035-.02.041.041 0 000-.04l-2.9-5.086a.108.108 0 010-.113l.293-.507 1.12-1.977c.024-.041.012-.062-.035-.062H9.2c-.059 0-.073-.026-.043-.077l1.434-2.505a.107.107 0 000-.114L9.225 1.774a.06.06 0 00-.053-.031zm6.29 8.02c.046 0 .058.02.034.06l-.832 1.465-2.613 4.585a.056.056 0 01-.05.029.058.058 0 01-.05-.029L8.498 9.841c-.02-.034-.01-.052.028-.054l.216-.012 6.722-.012z"/>
            </svg>
          </div>
          <div>
            <div class="font-bold text-base tracking-tight text-foreground leading-tight">Qwen Studio 2.1</div>
            <div class="text-xs text-muted-foreground">Uncensored GGUF Diffusion & LoRA Speed Hub</div>
          </div>
        </div>

        <!-- Badges -->
        <div class="hidden sm:flex items-center gap-2">
          <span class="inline-flex items-center gap-1.5 text-xs font-medium px-2.5 py-1 rounded-lg border border-border bg-background text-foreground">
            <i data-lucide="shield-alert" class="w-3 h-3 opacity-80"></i> Uncensored GGUF Q4_K_M
          </span>
          <span class="inline-flex items-center gap-1.5 text-xs font-medium px-2.5 py-1 rounded-lg border border-border bg-secondary text-foreground">
            <i data-lucide="zap" class="w-3 h-3 text-amber-500"></i> Viggle Turbo (6 Steps)
          </span>
          <span class="inline-flex items-center gap-1.5 text-xs font-medium px-2.5 py-1 rounded-lg border border-border bg-muted text-muted-foreground">
            <i data-lucide="hard-drive" class="w-3 h-3 opacity-80"></i> Private Browser IndexedDB
          </span>
        </div>
      </div>

      <!-- Theme Switcher -->
      <button id="theme-btn" onclick="toggleTheme()" class="inline-flex items-center gap-2 text-xs font-medium px-3 py-2 rounded-lg border border-border bg-card hover:bg-secondary text-foreground transition-all cursor-pointer">
        <i id="theme-icon" data-lucide="sun" class="w-4 h-4"></i>
        <span>Theme</span>
      </button>
    </header>

    <!-- MAIN 2-COLUMN STUDIO GRID -->
    <main class="w-full grid grid-cols-1 lg:grid-cols-2 gap-6 items-start">

      <!-- LEFT COLUMN: STUDIO CONTROLS (EXACTLY ONE CARD, ZERO NESTED CARDS) -->
      <div class="bg-card border border-border rounded-lg p-6 flex flex-col gap-5 shadow-sm">
        
        <!-- SECTION 1: GENERATION MODE (COLLAPSIBLE) -->
        <div class="border-b border-border pb-4">
          <button type="button" onclick="toggleCollapse('mode-content', 'mode-chevron')" class="w-full flex items-center justify-between text-left text-xs font-semibold text-foreground uppercase tracking-wider hover:opacity-80 transition-opacity">
            <span class="inline-flex items-center gap-2">
              <i data-lucide="layers" class="w-4 h-4"></i> Generation Mode
            </span>
            <i id="mode-chevron" data-lucide="chevron-down" class="w-4 h-4 transition-transform duration-200"></i>
          </button>
          
          <div id="mode-content" class="mt-3">
            <div class="grid grid-cols-2 sm:grid-cols-4 gap-2" id="mode-selector">
              <button type="button" onclick="setMode('Text to Image')" data-mode="Text to Image" class="mode-btn h-9 px-3 rounded-lg border border-border bg-primary text-primary-foreground text-xs font-medium flex items-center justify-center gap-1.5 transition-all">
                <i data-lucide="type" class="w-3.5 h-3.5"></i> Text to Image
              </button>
              <button type="button" onclick="setMode('Edit Image (1 Ref)')" data-mode="Edit Image (1 Ref)" class="mode-btn h-9 px-3 rounded-lg border border-border bg-background text-foreground hover:bg-secondary text-xs font-medium flex items-center justify-center gap-1.5 transition-all">
                <i data-lucide="image" class="w-3.5 h-3.5"></i> Edit (1 Ref)
              </button>
              <button type="button" onclick="setMode('Transform & Swap (2 Refs)')" data-mode="Transform & Swap (2 Refs)" class="mode-btn h-9 px-3 rounded-lg border border-border bg-background text-foreground hover:bg-secondary text-xs font-medium flex items-center justify-center gap-1.5 transition-all">
                <i data-lucide="repeat" class="w-3.5 h-3.5"></i> Transform (2 Refs)
              </button>
              <button type="button" onclick="setMode('Transparent PNG')" data-mode="Transparent PNG" class="mode-btn h-9 px-3 rounded-lg border border-border bg-background text-foreground hover:bg-secondary text-xs font-medium flex items-center justify-center gap-1.5 transition-all">
                <i data-lucide="sparkles" class="w-3.5 h-3.5"></i> Transparent PNG
              </button>
            </div>
          </div>
        </div>

        <!-- SECTION 2: REFERENCE IMAGES & MEDIA LIBRARY (COLLAPSIBLE, HIDDEN ON TEXT-TO-IMAGE) -->
        <div id="reference-section" class="hidden border-b border-border pb-4">
          <button type="button" onclick="toggleCollapse('reference-content', 'ref-section-chevron')" class="w-full flex items-center justify-between text-left text-xs font-semibold text-foreground hover:opacity-80 transition-opacity">
            <span class="inline-flex items-center gap-2">
              <i data-lucide="image" class="w-4 h-4"></i> Reference Images & Media Inputs
            </span>
            <i id="ref-section-chevron" data-lucide="chevron-down" class="w-4 h-4 transition-transform duration-200"></i>
          </button>
          
          <div id="reference-content" class="flex flex-col gap-4 mt-3">
            
            <!-- LARGE REFERENCE IMAGE INPUT BOXES (WITH FULL VISUAL PREVIEWS) -->
            <div id="ref-boxes-container" class="grid grid-cols-1 gap-4">
              
              <!-- Reference Image 1 (Base/Character) - Large Box with Drag & Drop -->
              <div id="ref-1-wrapper" class="flex flex-col gap-1.5">
                <div class="flex items-center justify-between">
                  <label id="ref-1-title" class="text-xs font-semibold text-foreground flex items-center gap-1.5">
                    <i data-lucide="image" class="w-3.5 h-3.5"></i> Reference Image 1 (Base / Character)
                  </label>
                  <button type="button" id="ref-1-clear-btn" onclick="clearRef1()" class="hidden text-xs text-muted-foreground hover:text-red-500 flex items-center gap-1">
                    <i data-lucide="x" class="w-3 h-3"></i> Clear
                  </button>
                </div>

                <!-- Large Drag & Drop Box -->
                <div id="ref-1-dropzone" class="relative group border-2 border-dashed border-border rounded-lg bg-secondary/30 min-h-[200px] h-[220px] flex flex-col items-center justify-center p-3 transition-all cursor-pointer overflow-hidden">
                  <input type="file" id="ref-1-input" accept="image/*" class="hidden" onchange="handleSingleUpload(event, 1)">
                  
                  <!-- Empty View -->
                  <div id="ref-1-empty-view" class="flex flex-col items-center gap-2 text-center p-4">
                    <div class="w-10 h-10 rounded-full bg-secondary border border-border flex items-center justify-center text-muted-foreground group-hover:text-foreground group-hover:scale-105 transition-all">
                      <i data-lucide="upload-cloud" class="w-5 h-5"></i>
                    </div>
                    <div>
                      <span class="text-xs font-medium text-foreground">Click to browse or drag & drop image here</span>
                      <p class="text-[11px] text-muted-foreground">or select an image from the Media Library below</p>
                    </div>
                  </div>

                  <!-- Full Visual Preview (Updated when library button is pressed) -->
                  <div id="ref-1-preview-container" class="hidden relative w-full h-full flex items-center justify-center">
                    <img id="ref-1-img-preview" class="w-full h-full object-contain rounded-lg">
                    <div class="absolute bottom-2 left-2 px-2.5 py-1 rounded-md bg-black/75 backdrop-blur-sm text-[11px] font-mono text-white flex items-center gap-1.5 shadow-sm">
                      <i data-lucide="check-circle-2" class="w-3.5 h-3.5 text-emerald-400"></i>
                      <span id="ref-1-badge-name">Selected Reference</span>
                    </div>
                    <button type="button" onclick="event.stopPropagation(); clearRef1()" title="Remove reference" class="absolute top-2 right-2 w-7 h-7 rounded-full bg-black/75 hover:bg-red-600 text-white flex items-center justify-center transition-colors shadow-sm">
                      <i data-lucide="x" class="w-4 h-4"></i>
                    </button>
                  </div>
                </div>
              </div>

              <!-- Reference Image 2 (Donor/Pose) - Large Box (Visible in Transform mode) -->
              <div id="ref-2-wrapper" class="hidden flex flex-col gap-1.5">
                <div class="flex items-center justify-between">
                  <label class="text-xs font-semibold text-foreground flex items-center gap-1.5">
                    <i data-lucide="repeat" class="w-3.5 h-3.5"></i> Reference Image 2 (Donor / Pose)
                  </label>
                  <button type="button" id="ref-2-clear-btn" onclick="clearRef2()" class="hidden text-xs text-muted-foreground hover:text-red-500 flex items-center gap-1">
                    <i data-lucide="x" class="w-3 h-3"></i> Clear
                  </button>
                </div>

                <!-- Large Drag & Drop Box -->
                <div id="ref-2-dropzone" class="relative group border-2 border-dashed border-border rounded-lg bg-secondary/30 min-h-[200px] h-[220px] flex flex-col items-center justify-center p-3 transition-all cursor-pointer overflow-hidden">
                  <input type="file" id="ref-2-input" accept="image/*" class="hidden" onchange="handleSingleUpload(event, 2)">
                  
                  <!-- Empty View -->
                  <div id="ref-2-empty-view" class="flex flex-col items-center gap-2 text-center p-4">
                    <div class="w-10 h-10 rounded-full bg-secondary border border-border flex items-center justify-center text-muted-foreground group-hover:text-foreground group-hover:scale-105 transition-all">
                      <i data-lucide="upload-cloud" class="w-5 h-5"></i>
                    </div>
                    <div>
                      <span class="text-xs font-medium text-foreground">Click to browse or drag & drop image here</span>
                      <p class="text-[11px] text-muted-foreground">or select an image from the Media Library below</p>
                    </div>
                  </div>

                  <!-- Full Visual Preview (Updated when library button is pressed) -->
                  <div id="ref-2-preview-container" class="hidden relative w-full h-full flex items-center justify-center">
                    <img id="ref-2-img-preview" class="w-full h-full object-contain rounded-lg">
                    <div class="absolute bottom-2 left-2 px-2.5 py-1 rounded-md bg-black/75 backdrop-blur-sm text-[11px] font-mono text-white flex items-center gap-1.5 shadow-sm">
                      <i data-lucide="check-circle-2" class="w-3.5 h-3.5 text-emerald-400"></i>
                      <span id="ref-2-badge-name">Selected Reference</span>
                    </div>
                    <button type="button" onclick="event.stopPropagation(); clearRef2()" title="Remove reference" class="absolute top-2 right-2 w-7 h-7 rounded-full bg-black/75 hover:bg-red-600 text-white flex items-center justify-center transition-colors shadow-sm">
                      <i data-lucide="x" class="w-4 h-4"></i>
                    </button>
                  </div>
                </div>
              </div>

            </div>

            <!-- MEDIA LIBRARY (COLLAPSIBLE DRAWER WITH 1-CLICK ASSIGNMENT) -->
            <div class="flex flex-col rounded-lg border border-border bg-secondary/20 p-3.5">
              <button type="button" onclick="toggleCollapse('library-content', 'library-chevron')" class="w-full flex items-center justify-between text-left text-xs font-semibold text-foreground hover:opacity-80 transition-opacity">
                <div class="flex items-center gap-2">
                  <i data-lucide="images" class="w-4 h-4 text-foreground"></i>
                  <span>Media Library (Batch Staging)</span>
                  <span id="library-count-badge" class="text-[11px] font-mono px-2 py-0.5 rounded-full bg-secondary border border-border text-muted-foreground">0 photos</span>
                </div>
                <div class="flex items-center gap-2 text-muted-foreground">
                  <span class="text-[11px] hidden sm:inline">1-Click Input Assignment</span>
                  <i id="library-chevron" data-lucide="chevron-down" class="w-4 h-4 transition-transform duration-200"></i>
                </div>
              </button>

              <div id="library-content" class="flex flex-col gap-3 mt-3">
                <!-- Batch Dropzone -->
                <div id="batch-dropzone" class="relative border border-dashed border-border rounded-lg p-3 flex items-center justify-center gap-2.5 bg-background/50 hover:bg-secondary/60 hover:border-foreground/50 transition-all cursor-pointer text-xs text-muted-foreground">
                  <input type="file" id="batch-file-input" multiple accept="image/*" class="hidden" onchange="handleBatchFileSelect(event)">
                  <i data-lucide="upload-cloud" class="w-4 h-4 text-foreground opacity-80"></i>
                  <span class="font-medium text-foreground">Click to upload multiple images or drag & drop files here</span>
                  <span class="text-[11px] opacity-75">(PNG, JPG, WEBP)</span>
                </div>

                <!-- Staged Images Tray -->
                <div id="media-library-tray" class="grid grid-cols-2 sm:grid-cols-4 gap-2.5 max-h-56 overflow-y-auto pr-1">
                  <div id="media-library-empty" class="col-span-full py-4 text-center text-xs text-muted-foreground italic">
                    No media uploaded to library yet. Drag & drop images above to build your asset pool.
                  </div>
                </div>
              </div>
            </div>

          </div>
        </div>

        <!-- SECTION 3: PROMPT DESCRIPTION (COLLAPSIBLE) -->
        <div class="border-b border-border pb-4">
          <button type="button" onclick="toggleCollapse('prompt-content', 'prompt-chevron')" class="w-full flex items-center justify-between text-left text-xs font-semibold text-foreground hover:opacity-80 transition-opacity">
            <span class="inline-flex items-center gap-2">
              <i data-lucide="pen-tool" class="w-4 h-4"></i> Prompt Description
            </span>
            <i id="prompt-chevron" data-lucide="chevron-down" class="w-4 h-4 transition-transform duration-200"></i>
          </button>
          
          <div id="prompt-content" class="mt-3 flex flex-col gap-1.5">
            <textarea id="prompt-input" rows="4" placeholder="Describe your vision, character, scene, or requested edit in rich detail..." class="w-full p-3 text-sm rounded-lg border border-border bg-background text-foreground resize-y focus:outline-none focus:ring-1 focus:ring-ring transition-all"></textarea>
          </div>
        </div>

        <!-- SECTION 4: PROMPT HISTORY (COLLAPSIBLE, AUTO-DEDUPLICATED, 1-CLICK APPLY) -->
        <div class="border-b border-border pb-4">
          <div class="w-full flex items-center justify-between">
            <button type="button" onclick="toggleCollapse('history-content', 'history-chevron')" class="flex items-center gap-2 text-left text-xs font-semibold text-foreground hover:opacity-80 transition-opacity">
              <i data-lucide="history" class="w-4 h-4"></i>
              <span>Prompt History</span>
              <span id="history-count-badge" class="text-[11px] font-mono px-2 py-0.5 rounded-full bg-secondary border border-border text-muted-foreground">0 saved</span>
            </button>
            <div class="flex items-center gap-3">
              <button type="button" onclick="clearPromptHistory()" class="text-[11px] text-muted-foreground hover:text-red-500 transition-colors inline-flex items-center gap-1 cursor-pointer">
                <i data-lucide="trash-2" class="w-3 h-3"></i> Clear History
              </button>
              <button type="button" onclick="toggleCollapse('history-content', 'history-chevron')" class="text-muted-foreground hover:text-foreground">
                <i id="history-chevron" data-lucide="chevron-down" class="w-4 h-4 transition-transform duration-200"></i>
              </button>
            </div>
          </div>

          <div id="history-content" class="flex flex-col gap-2 mt-3">
            <span class="text-[11px] text-muted-foreground">Click any prompt below to load it into the prompt box (duplicates automatically prevented):</span>
            
            <div id="history-list" class="flex flex-col gap-1.5 max-h-48 overflow-y-auto pr-1">
              <div id="history-empty" class="py-4 text-center text-xs text-muted-foreground italic">
                No prompt history yet. Prompts you generate will be saved here automatically.
              </div>
            </div>
          </div>
        </div>

        <!-- SECTION 5: PROMPT TEMPLATES & PRESETS (COLLAPSIBLE) -->
        <div class="border-b border-border pb-4">
          <button type="button" onclick="toggleCollapse('presets-acc', 'presets-acc-chevron')" class="w-full flex items-center justify-between text-left text-xs font-semibold text-foreground hover:opacity-80 transition-opacity">
            <span class="inline-flex items-center gap-2">
              <i data-lucide="bookmark" class="w-4 h-4"></i> Prompt Templates & Presets
            </span>
            <i id="presets-acc-chevron" data-lucide="chevron-down" class="w-4 h-4 transition-transform duration-200"></i>
          </button>
          
          <div id="presets-acc" class="flex flex-col gap-3 mt-3">
            <!-- Preset Chips -->
            <div id="presets-list" class="flex flex-wrap gap-1.5 min-h-[32px]">
              <!-- Dynamically populated chips -->
            </div>

            <!-- ROW 1: Template Name + Save Button (Flex, Height 40px, Aligned) -->
            <div class="flex flex-col gap-1.5">
              <label class="text-xs font-semibold text-foreground">Template Name</label>
              <div class="flex items-center gap-2">
                <input type="text" id="new-preset-name" placeholder="e.g. Cyberpunk Portrait (same name = overwrite)" class="flex-1 h-10 px-3 text-sm rounded-lg border border-border bg-background text-foreground focus:outline-none focus:ring-1 focus:ring-ring">
                <button type="button" onclick="saveCurrentPromptAsPreset()" class="h-10 px-4 rounded-lg border border-border bg-secondary hover:bg-accent text-xs font-medium text-foreground inline-flex items-center justify-center gap-1.5 transition-all flex-shrink-0 cursor-pointer">
                  <i data-lucide="bookmark-plus" class="w-3.5 h-3.5"></i> Save Current Prompt
                </button>
              </div>
            </div>

            <!-- ROW 2: Select Template to Delete + Delete Button (Flex, Height 40px, Aligned) -->
            <div class="flex flex-col gap-1.5">
              <label class="text-xs font-semibold text-foreground">Select Template to Delete</label>
              <div class="flex items-center gap-2">
                <select id="delete-preset-select" class="flex-1 h-10 px-3 text-sm rounded-lg border border-border bg-background text-foreground focus:outline-none focus:ring-1 focus:ring-ring">
                  <option value="">-- Choose a template to delete --</option>
                </select>
                <button type="button" onclick="deleteSelectedPreset()" class="h-10 px-4 rounded-lg border border-border bg-secondary hover:bg-red-500/10 hover:border-red-500 hover:text-red-500 text-xs font-medium text-foreground inline-flex items-center justify-center gap-1.5 transition-all flex-shrink-0 cursor-pointer">
                  <i data-lucide="trash-2" class="w-3.5 h-3.5"></i> Delete Template
                </button>
              </div>
            </div>
          </div>
        </div>

        <!-- SECTION 6: LORA ADAPTERS & ACCELERATION (COLLAPSIBLE) -->
        <div class="border-b border-border pb-4">
          <button type="button" onclick="toggleCollapse('lora-content', 'lora-chevron')" class="w-full flex items-center justify-between text-left text-xs font-semibold text-foreground hover:opacity-80 transition-opacity">
            <span class="inline-flex items-center gap-2">
              <i data-lucide="zap" class="w-4 h-4 text-amber-500"></i> LoRA Adapters & Acceleration
            </span>
            <i id="lora-chevron" data-lucide="chevron-down" class="w-4 h-4 transition-transform duration-200"></i>
          </button>
          
          <div id="lora-content" class="flex flex-col gap-3 mt-3">
            <div class="grid grid-cols-1 sm:grid-cols-2 gap-3 items-center">
              <div class="flex flex-col gap-1">
                <label class="text-xs font-semibold text-foreground">LoRA Adapter</label>
                <select id="lora-select" onchange="onLoraSelectChange()" class="h-10 px-3 text-sm rounded-lg border border-border bg-background text-foreground">
                  <option value="Viggle Turbo (6-Step Acceleration)">Viggle Turbo (6-Step Acceleration)</option>
                  <option value="Face / Head Swap (BFS 2.1)">Face / Head Swap (BFS 2.1)</option>
                  <option value="Face / Head Swap - Strong Expression (BFS alt)">Face / Head Swap - Strong Expression (BFS alt)</option>
                  <option value="Pose / Body Swap (BFS Body 2.1)">Pose / Body Swap (BFS Body 2.1)</option>
                  <option value="None (Base Qwen-Image-2.1 Uncensored)">None (Base Qwen-Image-2.1 Uncensored)</option>
                  <option value="Real Characters & Anatomy">Real Characters & Anatomy</option>
                  <option value="Photo Restore & Ultra HD">Photo Restore & Ultra HD</option>
                  <option value="Studio Lighting & Cinematic">Studio Lighting & Cinematic</option>
                  <option value="Anime & Manga 2.0">Anime & Manga 2.0</option>
                  <option value="Outfit & Fashion Swap">Outfit & Fashion Swap</option>
                  <option value="Skin Texture & Portrait Retouch">Skin Texture & Portrait Retouch</option>
                  <option value="Custom / Hugging Face LoRA">Custom / Hugging Face LoRA</option>
                </select>
              </div>
              <div class="flex flex-col gap-1">
                <div class="flex items-center justify-between">
                  <label class="text-xs font-semibold text-foreground">LoRA Strength</label>
                  <span id="lora-strength-val" class="text-xs font-mono text-muted-foreground">1.0</span>
                </div>
                <input type="range" id="lora-strength" min="0" max="1.5" step="0.05" value="1.0" oninput="document.getElementById('lora-strength-val').textContent = this.value; updateLoraBanner();" class="h-10 accent-foreground cursor-pointer">
              </div>
            </div>

            <!-- Active LoRA Status Banner -->
            <div id="lora-status-banner" class="flex items-center gap-2 p-2.5 rounded-lg border border-border bg-secondary text-xs text-foreground font-mono">
              <span class="w-2 h-2 rounded-full bg-emerald-500 flex-shrink-0"></span>
              <span id="lora-banner-text" class="truncate">Active LoRA: Viggle Turbo (6-Step Fast) · Weight: 1.0</span>
            </div>

            <!-- LoRA Tabs -->
            <div class="border-b border-border flex gap-4 text-xs font-medium">
              <button type="button" onclick="setLoraTab('curated')" id="tab-curated-btn" class="lora-tab-btn pb-2 border-b-2 border-foreground text-foreground flex items-center gap-1.5">
                <i data-lucide="sparkles" class="w-3.5 h-3.5"></i> Curated Presets
              </button>
              <button type="button" onclick="setLoraTab('hf-explorer')" id="tab-hf-btn" class="lora-tab-btn pb-2 border-b-2 border-transparent text-muted-foreground hover:text-foreground flex items-center gap-1.5">
                <i data-lucide="search" class="w-3.5 h-3.5"></i> Hugging Face Live Explorer
              </button>
              <button type="button" onclick="setLoraTab('custom')" id="tab-custom-btn" class="lora-tab-btn pb-2 border-b-2 border-transparent text-muted-foreground hover:text-foreground flex items-center gap-1.5">
                <i data-lucide="wrench" class="w-3.5 h-3.5"></i> Custom Repo ID
              </button>
            </div>

            <!-- Tab 1: Curated 3x3 Grid -->
            <div id="tab-curated-pane" class="grid grid-cols-3 gap-2">
              <button type="button" onclick="applyCuratedPreset('Real Anatomy')" class="h-9 px-2 text-xs rounded-lg border border-border bg-secondary hover:bg-accent text-foreground flex items-center justify-center gap-1 truncate">
                <i data-lucide="user" class="w-3 h-3"></i> Real Anatomy
              </button>
              <button type="button" onclick="applyCuratedPreset('Body Swap')" class="h-9 px-2 text-xs rounded-lg border border-border bg-secondary hover:bg-accent text-foreground flex items-center justify-center gap-1 truncate">
                <i data-lucide="repeat" class="w-3 h-3"></i> Body Swap
              </button>
              <button type="button" onclick="applyCuratedPreset('Face Swap')" class="h-9 px-2 text-xs rounded-lg border border-border bg-secondary hover:bg-accent text-foreground flex items-center justify-center gap-1 truncate">
                <i data-lucide="smile" class="w-3 h-3"></i> Face Swap
              </button>
              <button type="button" onclick="applyCuratedPreset('Studio Light')" class="h-9 px-2 text-xs rounded-lg border border-border bg-secondary hover:bg-accent text-foreground flex items-center justify-center gap-1 truncate">
                <i data-lucide="sun" class="w-3 h-3"></i> Studio Light
              </button>
              <button type="button" onclick="applyCuratedPreset('Phone Photo')" class="h-9 px-2 text-xs rounded-lg border border-border bg-secondary hover:bg-accent text-foreground flex items-center justify-center gap-1 truncate">
                <i data-lucide="camera" class="w-3 h-3"></i> Phone Photo
              </button>
              <button type="button" onclick="applyCuratedPreset('Restore Photo')" class="h-9 px-2 text-xs rounded-lg border border-border bg-secondary hover:bg-accent text-foreground flex items-center justify-center gap-1 truncate">
                <i data-lucide="image" class="w-3 h-3"></i> Restore Photo
              </button>
              <button type="button" onclick="applyCuratedPreset('Outfit Swap')" class="h-9 px-2 text-xs rounded-lg border border-border bg-secondary hover:bg-accent text-foreground flex items-center justify-center gap-1 truncate">
                <i data-lucide="shirt" class="w-3 h-3"></i> Outfit Swap
              </button>
              <button type="button" onclick="applyCuratedPreset('Anime')" class="h-9 px-2 text-xs rounded-lg border border-border bg-secondary hover:bg-accent text-foreground flex items-center justify-center gap-1 truncate">
                <i data-lucide="palette" class="w-3 h-3"></i> Anime
              </button>
              <button type="button" onclick="applyCuratedPreset('Viggle Turbo (6-Step Fast)')" class="h-9 px-2 text-xs rounded-lg border border-border bg-secondary hover:bg-accent text-foreground flex items-center justify-center gap-1 truncate font-medium">
                <i data-lucide="zap" class="w-3 h-3 text-amber-500"></i> Viggle Turbo
              </button>
            </div>

            <!-- Tab 2: HF Live Explorer -->
            <div id="tab-hf-pane" class="hidden flex flex-col gap-3">
              <span class="text-xs text-muted-foreground">Search and test ANY community LoRA for Qwen-Image-2.1 live from Hugging Face Hub:</span>
              <!-- Search Row (Flex, Height 40px, Aligned) -->
              <div class="flex flex-col gap-1.5">
                <label class="text-xs font-semibold text-foreground">Search Community LoRAs</label>
                <div class="flex items-center gap-2">
                  <input type="text" id="hf-search-query" placeholder="e.g. anatomy, realism, portrait, lighting, swap, 80s" class="flex-1 h-10 px-3 text-sm rounded-lg border border-border bg-background text-foreground focus:outline-none focus:ring-1 focus:ring-ring">
                  <button type="button" onclick="searchHfLoras()" id="hf-search-btn" class="h-10 px-4 rounded-lg border border-border bg-secondary hover:bg-accent text-xs font-medium text-foreground inline-flex items-center justify-center gap-1.5 transition-all flex-shrink-0 cursor-pointer">
                    <i data-lucide="search" class="w-3.5 h-3.5"></i> Search Models
                  </button>
                </div>
              </div>
              <div class="grid grid-cols-1 sm:grid-cols-2 gap-2">
                <select id="hf-models-select" onchange="onHfModelSelect()" class="h-10 px-3 text-xs rounded-lg border border-border bg-background text-foreground">
                  <option value="">-- Found Repositories --</option>
                </select>
                <select id="hf-files-select" class="h-10 px-3 text-xs rounded-lg border border-border bg-background text-foreground">
                  <option value="">-- Safetensors Weights File --</option>
                </select>
              </div>
              <button type="button" onclick="applyHfSelection()" class="h-10 px-4 rounded-lg bg-primary text-primary-foreground text-xs font-semibold inline-flex items-center justify-center gap-2 hover:opacity-90 transition-all">
                <i data-lucide="rocket" class="w-3.5 h-3.5"></i> Apply Selected LoRA
              </button>
            </div>

            <!-- Tab 3: Custom Repo ID -->
            <div id="tab-custom-pane" class="hidden flex flex-col gap-3">
              <span class="text-xs text-muted-foreground">Direct manual entry for any Hugging Face model repo and weights filename:</span>
              <div class="grid grid-cols-1 sm:grid-cols-2 gap-2">
                <input type="text" id="custom-repo-input" placeholder="e.g. WarmBloodAban/Qwen-Image-2.1-LoRAs" class="h-10 px-3 text-xs rounded-lg border border-border bg-background text-foreground">
                <input type="text" id="custom-file-input" placeholder="e.g. Qwen2.1_Anything2Real.safetensors" class="h-10 px-3 text-xs rounded-lg border border-border bg-background text-foreground">
              </div>
              <button type="button" onclick="applyCustomSelection()" class="h-10 px-4 rounded-lg bg-primary text-primary-foreground text-xs font-semibold inline-flex items-center justify-center gap-2 hover:opacity-90 transition-all">
                <i data-lucide="sliders" class="w-3.5 h-3.5"></i> Apply Custom LoRA
              </button>
            </div>
          </div>
        </div>

        <!-- SECTION 7: GENERATION SETTINGS (COLLAPSIBLE) -->
        <div class="border-b border-border pb-4">
          <button type="button" onclick="toggleCollapse('settings-content', 'settings-chevron')" class="w-full flex items-center justify-between text-left text-xs font-semibold text-foreground hover:opacity-80 transition-opacity">
            <span class="inline-flex items-center gap-2">
              <i data-lucide="sliders" class="w-4 h-4"></i> Generation Settings (Resolution, Steps, Seed)
            </span>
            <i id="settings-chevron" data-lucide="chevron-down" class="w-4 h-4 transition-transform duration-200"></i>
          </button>
          
          <div id="settings-content" class="flex flex-col gap-3 mt-3">
            <div class="grid grid-cols-1 sm:grid-cols-2 gap-3 items-center">
              <div class="flex flex-col gap-1">
                <label class="text-xs font-semibold text-foreground">Aspect Ratio & Resolution</label>
                <select id="aspect-ratio-select" class="h-10 px-3 text-sm rounded-lg border border-border bg-background text-foreground">
                  <option value="Auto - Match Input Image (or 1024²)">Auto - Match Input Image (or 1024²)</option>
                  <option value="1:1 Square (1024x1024)">1:1 Square (1024x1024)</option>
                  <option value="16:9 Landscape (1344x768)">16:9 Landscape (1344x768)</option>
                  <option value="9:16 Portrait (768x1344)">9:16 Portrait (768x1344)</option>
                  <option value="4:3 Standard (1152x896)">4:3 Standard (1152x896)</option>
                  <option value="3:4 Standard (896x1152)">3:4 Standard (896x1152)</option>
                </select>
              </div>
              <div class="flex flex-col gap-1">
                <div class="flex items-center justify-between">
                  <label class="text-xs font-semibold text-foreground">Inference Steps</label>
                  <span id="steps-val" class="text-xs font-mono text-muted-foreground">6</span>
                </div>
                <input type="range" id="steps-slider" min="4" max="40" step="1" value="6" oninput="document.getElementById('steps-val').textContent = this.value" class="h-10 accent-foreground cursor-pointer">
              </div>
            </div>

            <!-- Seed & Randomize Row (Flex, Aligned) -->
            <div class="flex items-end gap-4">
              <div class="flex-1 flex flex-col gap-1">
                <label class="text-xs font-semibold text-foreground">Seed</label>
                <input type="number" id="seed-input" value="42" class="h-10 px-3 text-sm rounded-lg border border-border bg-background text-foreground font-mono focus:outline-none focus:ring-1 focus:ring-ring">
              </div>
              <label class="h-10 inline-flex items-center gap-2 text-xs font-medium text-foreground cursor-pointer flex-shrink-0">
                <input type="checkbox" id="randomize-seed-cb" checked class="w-4 h-4 rounded border-border text-foreground accent-foreground">
                <span>Randomize Seed</span>
              </label>
            </div>
          </div>
        </div>

        <!-- Primary Action: Generate Image Button -->
        <button type="button" id="generate-btn" onclick="triggerGeneration()" class="w-full h-12 rounded-lg bg-primary text-primary-foreground font-semibold text-sm inline-flex items-center justify-center gap-2 hover:opacity-90 active:scale-[0.99] transition-all cursor-pointer shadow-sm">
          <i data-lucide="wand-2" class="w-4 h-4"></i>
          <span id="generate-btn-text">Generate Image</span>
        </button>

      </div>

      <!-- RIGHT COLUMN: CANVAS PREVIEW & BROWSER GALLERY (EXACTLY ONE CARD, ZERO NESTED CARDS) -->
      <div class="bg-card border border-border rounded-lg p-6 flex flex-col gap-5 shadow-sm">
        
        <!-- SECTION 8: GENERATED RESULT & CANVAS (COLLAPSIBLE) -->
        <div class="border-b border-border pb-4">
          <button type="button" onclick="toggleCollapse('canvas-section-content', 'canvas-chevron')" class="w-full flex items-center justify-between text-left text-xs font-semibold text-foreground hover:opacity-80 transition-opacity">
            <span class="inline-flex items-center gap-2">
              <i data-lucide="sparkles" class="w-4 h-4 text-amber-500"></i> Generated Result & Canvas Viewport
            </span>
            <i id="canvas-chevron" data-lucide="chevron-down" class="w-4 h-4 transition-transform duration-200"></i>
          </button>

          <div id="canvas-section-content" class="mt-3 flex flex-col gap-3">
            <!-- Output Canvas Viewport (500px, 8px radius) -->
            <div id="output-canvas" class="relative w-full h-[500px] rounded-lg border border-dashed border-border bg-secondary/30 flex flex-col items-center justify-center overflow-hidden transition-all">
              <div id="canvas-empty" class="flex flex-col items-center gap-3 text-muted-foreground p-6 text-center">
                <i data-lucide="image" class="w-12 h-12 stroke-[1.25] opacity-50"></i>
                <div>
                  <div class="text-sm font-medium text-foreground">Canvas Preview</div>
                  <div class="text-xs text-muted-foreground">Generated image will render here with full resolution</div>
                </div>
              </div>
              <img id="canvas-img" class="hidden w-full h-full object-contain rounded-lg">
              
              <!-- Loading Overlay -->
              <div id="canvas-loading" class="hidden absolute inset-0 bg-background/80 backdrop-blur-sm flex flex-col items-center justify-center gap-3">
                <div class="w-8 h-8 border-2 border-foreground border-t-transparent rounded-full animate-spin"></div>
                <span class="text-xs font-medium text-foreground">Diffusing image with Viggle Turbo...</span>
              </div>
            </div>
          </div>
        </div>

        <!-- SECTION 9: DOWNLOAD & PROMPT DETAILS (COLLAPSIBLE) -->
        <div class="border-b border-border pb-4">
          <button type="button" onclick="toggleCollapse('details-content', 'details-chevron')" class="w-full flex items-center justify-between text-left text-xs font-semibold text-foreground hover:opacity-80 transition-opacity">
            <span class="inline-flex items-center gap-2">
              <i data-lucide="file-output" class="w-4 h-4"></i> Output Download & Model Prompt
            </span>
            <i id="details-chevron" data-lucide="chevron-down" class="w-4 h-4 transition-transform duration-200"></i>
          </button>

          <div id="details-content" class="flex flex-col gap-3 mt-3">
            <!-- Download Button -->
            <div class="flex flex-col gap-1">
              <label class="text-xs font-semibold text-foreground">Download High-Res Output</label>
              <a id="download-btn" href="#" download="generated_qwen.png" class="h-10 px-4 rounded-lg border border-border bg-background hover:bg-secondary text-xs font-medium text-foreground inline-flex items-center justify-between transition-all opacity-50 pointer-events-none">
                <span class="inline-flex items-center gap-2">
                  <i data-lucide="download" class="w-4 h-4"></i>
                  <span id="download-filename">No output generated yet</span>
                </span>
                <span id="download-size" class="text-muted-foreground font-mono text-[11px]">-</span>
              </a>
            </div>

            <!-- Prompt sent to the model -->
            <div class="flex flex-col gap-1">
              <label class="text-xs font-semibold text-foreground">Prompt sent to the model</label>
              <textarea id="used-prompt-view" rows="2" readonly class="w-full p-2.5 text-xs font-mono rounded-lg border border-border bg-secondary text-muted-foreground resize-none"></textarea>
            </div>
          </div>
        </div>

        <!-- SECTION 10: PRIVATE BROWSER GALLERY (COLLAPSIBLE) -->
        <div>
          <button type="button" onclick="toggleCollapse('gallery-content-section', 'gallery-chevron')" class="w-full flex items-center justify-between text-left text-xs font-semibold text-foreground hover:opacity-80 transition-opacity">
            <div class="flex items-center gap-2">
              <i data-lucide="hard-drive" class="w-4 h-4"></i>
              <span>Private Browser Gallery (IndexedDB)</span>
            </div>
            <i id="gallery-chevron" data-lucide="chevron-down" class="w-4 h-4 transition-transform duration-200"></i>
          </button>

          <div id="gallery-content-section" class="flex flex-col gap-3 mt-3">
            <!-- Storage Header + Clear Button -->
            <div class="flex items-center justify-between p-2.5 rounded-lg border border-border bg-secondary text-xs">
              <span id="gallery-count-label" class="inline-flex items-center gap-1.5 text-foreground font-medium">
                <i data-lucide="database" class="w-3.5 h-3.5 opacity-80"></i> Browser Storage: 0 image(s) (100% Private, 0 KB on Space)
              </span>
              <button type="button" onclick="clearBrowserStorage()" class="h-8 px-3 rounded-lg border border-red-500/30 bg-red-500/10 hover:bg-red-500 hover:text-white text-red-500 text-xs font-medium inline-flex items-center gap-1.5 transition-all cursor-pointer">
                <i data-lucide="trash-2" class="w-3.5 h-3.5"></i> Clear Storage
              </button>
            </div>

            <!-- Gallery Grid -->
            <div id="gallery-grid" class="grid grid-cols-3 sm:grid-cols-4 gap-2.5 max-h-60 overflow-y-auto pr-1">
              <div id="gallery-empty" class="col-span-full py-6 text-center text-xs text-muted-foreground italic">
                No images saved in your browser yet. Generated images will be saved automatically here.
              </div>
            </div>
          </div>
        </div>

      </div>

    </main>

    <!-- FOOTER -->
    <footer class="w-full text-center py-4 text-xs text-muted-foreground border-t border-border flex items-center justify-center gap-4 flex-wrap">
      <span>Qwen Studio 2.1 Viggle Turbo</span>
      <span>•</span>
      <span>100% Client-Side Storage</span>
      <span>•</span>
      <span>Shadcn Monochromatic UI</span>
    </footer>

  </div>

  <!-- LIGHTBOX MODAL FOR GALLERY PREVIEW -->
  <div id="gallery-modal" class="hidden fixed inset-0 z-50 modal-backdrop flex items-center justify-center p-4">
    <div class="relative max-w-4xl w-full bg-card border border-border rounded-lg p-5 flex flex-col gap-4 shadow-2xl max-h-[90vh]">
      <div class="flex items-center justify-between">
        <span id="modal-title" class="text-sm font-semibold text-foreground truncate max-w-lg">Image Details</span>
        <button type="button" onclick="closeModal()" class="w-8 h-8 rounded-lg border border-border bg-secondary hover:bg-accent text-foreground flex items-center justify-center cursor-pointer">
          <i data-lucide="x" class="w-4 h-4"></i>
        </button>
      </div>
      <div class="flex-1 overflow-hidden flex items-center justify-center bg-secondary/40 rounded-lg min-h-[300px]">
        <img id="modal-img" class="max-h-[60vh] max-w-full object-contain rounded-lg">
      </div>
      <div class="flex items-center justify-between text-xs text-muted-foreground flex-wrap gap-2">
        <span id="modal-meta" class="font-mono">Seed: - · Steps: -</span>
        <div class="flex items-center gap-2">
          <button type="button" onclick="copyModalPrompt()" class="h-8 px-3 rounded-lg border border-border bg-secondary hover:bg-accent text-foreground inline-flex items-center gap-1.5 cursor-pointer">
            <i data-lucide="copy" class="w-3.5 h-3.5"></i> Copy Prompt
          </button>
          <a id="modal-dl" href="#" download="saved_qwen.png" class="h-8 px-3 rounded-lg bg-primary text-primary-foreground font-medium inline-flex items-center gap-1.5 cursor-pointer">
            <i data-lucide="download" class="w-3.5 h-3.5"></i> Download
          </a>
        </div>
      </div>
    </div>
  </div>

  <!-- APPLICATION LOGIC (INDEXEDDB, API, TABS, THEME, MEDIA POOL, PROMPT HISTORY, COLLAPSIBLE) -->
  <script>
    // Initialize Lucide Icons
    function refreshIcons() {
      if (window.lucide) { window.lucide.createIcons(); }
    }

    // Unified Collapsible Toggle
    function toggleCollapse(contentId, chevronId) {
      const content = document.getElementById(contentId);
      const chevron = document.getElementById(chevronId);
      if (!content) return;
      const isHidden = content.classList.toggle('hidden');
      if (chevron) {
        chevron.style.transform = isHidden ? 'rotate(-90deg)' : 'rotate(0deg)';
      }
    }

    // Theme Management
    function initTheme() {
      const saved = localStorage.getItem('qwen_theme') || 'light';
      document.documentElement.classList.toggle('dark', saved === 'dark');
      updateThemeIcon(saved === 'dark');
    }

    function toggleTheme() {
      const isDark = document.documentElement.classList.toggle('dark');
      localStorage.setItem('qwen_theme', isDark ? 'dark' : 'light');
      updateThemeIcon(isDark);
    }

    function updateThemeIcon(isDark) {
      const icon = document.getElementById('theme-icon');
      if (icon) {
        icon.setAttribute('data-lucide', isDark ? 'sun' : 'moon');
        refreshIcons();
      }
    }

    // ============================================================
    // Mode Selector & Reference Images State
    // ============================================================
    let currentMode = 'Text to Image';
    let mediaLibrary = []; // Array of { id, dataUrl, name }
    let ref1Data = null;
    let ref1Name = null;
    let ref2Data = null;
    let ref2Name = null;

    function setMode(mode) {
      currentMode = mode;
      document.querySelectorAll('.mode-btn').forEach(btn => {
        const isMatch = btn.getAttribute('data-mode') === mode;
        btn.className = isMatch 
          ? 'mode-btn h-9 px-3 rounded-lg border border-border bg-primary text-primary-foreground text-xs font-medium flex items-center justify-center gap-1.5 transition-all'
          : 'mode-btn h-9 px-3 rounded-lg border border-border bg-background text-foreground hover:bg-secondary text-xs font-medium flex items-center justify-center gap-1.5 transition-all';
      });

      const refSection = document.getElementById('reference-section');
      const refBoxes = document.getElementById('ref-boxes-container');
      const ref1Title = document.getElementById('ref-1-title');
      const ref2Wrapper = document.getElementById('ref-2-wrapper');

      if (mode === 'Text to Image') {
        refSection.classList.add('hidden');
      } else {
        refSection.classList.remove('hidden');

        if (mode === 'Transform & Swap (2 Refs)') {
          refBoxes.className = 'grid grid-cols-1 sm:grid-cols-2 gap-4';
          ref1Title.innerHTML = '<i data-lucide="image" class="w-3.5 h-3.5"></i> Reference Image 1 (Base)';
          ref2Wrapper.classList.remove('hidden');
        } else {
          // Edit Image (1 Ref) or Transparent PNG
          refBoxes.className = 'grid grid-cols-1 gap-4';
          ref1Title.innerHTML = '<i data-lucide="image" class="w-3.5 h-3.5"></i> Reference Image (Base / Input)';
          ref2Wrapper.classList.add('hidden');
        }

        renderMediaLibrary();
      }
      refreshIcons();
    }

    // ============================================================
    // Big Reference Image Visual Box Handlers
    // ============================================================
    function handleSingleUpload(event, targetIndex) {
      const file = event.target.files[0];
      if (file) {
        readFileAsDataUrl(file, dataUrl => {
          setRefImage(targetIndex, dataUrl, file.name);
          addToLibrary(dataUrl, file.name);
        });
      }
      event.target.value = '';
    }

    function setRefImage(index, dataUrl, name) {
      if (index === 1) {
        ref1Data = dataUrl;
        ref1Name = name || 'reference_1.png';
        const emptyView = document.getElementById('ref-1-empty-view');
        const previewCont = document.getElementById('ref-1-preview-container');
        const img = document.getElementById('ref-1-img-preview');
        const badge = document.getElementById('ref-1-badge-name');
        const clearBtn = document.getElementById('ref-1-clear-btn');

        img.src = dataUrl;
        badge.textContent = ref1Name;
        emptyView.classList.add('hidden');
        previewCont.classList.remove('hidden');
        clearBtn.classList.remove('hidden');
      } else if (index === 2) {
        ref2Data = dataUrl;
        ref2Name = name || 'reference_2.png';
        const emptyView = document.getElementById('ref-2-empty-view');
        const previewCont = document.getElementById('ref-2-preview-container');
        const img = document.getElementById('ref-2-img-preview');
        const badge = document.getElementById('ref-2-badge-name');
        const clearBtn = document.getElementById('ref-2-clear-btn');

        img.src = dataUrl;
        badge.textContent = ref2Name;
        emptyView.classList.add('hidden');
        previewCont.classList.remove('hidden');
        clearBtn.classList.remove('hidden');
      }

      renderMediaLibrary();
    }

    function clearRef1() {
      ref1Data = null;
      ref1Name = null;
      document.getElementById('ref-1-empty-view').classList.remove('hidden');
      document.getElementById('ref-1-preview-container').classList.add('hidden');
      document.getElementById('ref-1-clear-btn').classList.add('hidden');
      renderMediaLibrary();
    }

    function clearRef2() {
      ref2Data = null;
      ref2Name = null;
      document.getElementById('ref-2-empty-view').classList.remove('hidden');
      document.getElementById('ref-2-preview-container').classList.add('hidden');
      document.getElementById('ref-2-clear-btn').classList.add('hidden');
      renderMediaLibrary();
    }

    function readFileAsDataUrl(file, callback) {
      if (!file.type.startsWith('image/')) return;
      const reader = new FileReader();
      reader.onload = e => callback(e.target.result);
      reader.readAsDataURL(file);
    }

    function addToLibrary(dataUrl, name) {
      const exists = mediaLibrary.some(item => item.dataUrl === dataUrl);
      if (!exists) {
        mediaLibrary.unshift({
          id: Date.now() + Math.random(),
          dataUrl: dataUrl,
          name: name
        });
        renderMediaLibrary();
      }
    }

    // ============================================================
    // Media Library Batch Handlers
    // ============================================================
    function handleBatchFileSelect(event) {
      const files = event.target.files;
      if (files && files.length > 0) {
        processBatchFiles(files);
      }
      event.target.value = '';
    }

    function processBatchFiles(files) {
      Array.from(files).forEach((file, i) => {
        readFileAsDataUrl(file, dataUrl => {
          addToLibrary(dataUrl, file.name);
          // If Ref 1 is currently empty, automatically set the first uploaded file as Ref 1!
          if (!ref1Data && i === 0) {
            setRefImage(1, dataUrl, file.name);
          } else if (currentMode === 'Transform & Swap (2 Refs)' && !ref2Data && i === 1) {
            setRefImage(2, dataUrl, file.name);
          }
        });
      });
    }

    function renderMediaLibrary() {
      const tray = document.getElementById('media-library-tray');
      const badge = document.getElementById('library-count-badge');
      if (!tray) return;

      badge.textContent = `${mediaLibrary.length} photo${mediaLibrary.length === 1 ? '' : 's'}`;

      if (mediaLibrary.length === 0) {
        tray.innerHTML = '<div class="col-span-full py-4 text-center text-xs text-muted-foreground italic">No media uploaded to library yet. Drag & drop images above to build your asset pool.</div>';
        refreshIcons();
        return;
      }

      tray.innerHTML = '';
      mediaLibrary.forEach(item => {
        const isRef1 = ref1Data === item.dataUrl;
        const isRef2 = ref2Data === item.dataUrl;

        const card = document.createElement('div');
        card.className = `relative rounded-lg border ${isRef1 || isRef2 ? 'border-foreground ring-1 ring-foreground bg-secondary' : 'border-border bg-card'} p-2 flex flex-col gap-2 transition-all shadow-sm`;

        let actionBtns = '';
        if (currentMode === 'Transform & Swap (2 Refs)') {
          actionBtns = `
            <div class="grid grid-cols-2 gap-1.5 w-full">
              <button type="button" onclick="setRefImage(1, '${item.dataUrl}', '${item.name.replace(/'/g, "\\'")}')" class="h-7 px-1 text-[11px] font-medium rounded ${isRef1 ? 'bg-primary text-primary-foreground font-semibold' : 'bg-secondary hover:bg-accent text-foreground'} flex items-center justify-center gap-1 truncate">
                <i data-lucide="${isRef1 ? 'check' : 'arrow-up'}" class="w-3 h-3 flex-shrink-0"></i> Ref 1
              </button>
              <button type="button" onclick="setRefImage(2, '${item.dataUrl}', '${item.name.replace(/'/g, "\\'")}')" class="h-7 px-1 text-[11px] font-medium rounded ${isRef2 ? 'bg-primary text-primary-foreground font-semibold' : 'bg-secondary hover:bg-accent text-foreground'} flex items-center justify-center gap-1 truncate">
                <i data-lucide="${isRef2 ? 'check' : 'arrow-up'}" class="w-3 h-3 flex-shrink-0"></i> Ref 2
              </button>
            </div>
          `;
        } else {
          // Edit Image (1 Ref)
          actionBtns = `
            <button type="button" onclick="setRefImage(1, '${item.dataUrl}', '${item.name.replace(/'/g, "\\'")}')" class="w-full h-7 px-2 text-xs font-medium rounded ${isRef1 ? 'bg-primary text-primary-foreground font-semibold' : 'bg-secondary hover:bg-accent text-foreground'} flex items-center justify-center gap-1.5 transition-all">
              <i data-lucide="${isRef1 ? 'check-circle-2' : 'arrow-up'}" class="w-3.5 h-3.5"></i> ${isRef1 ? 'Active Input' : 'Use as Input'}
            </button>
          `;
        }

        card.innerHTML = `
          <div class="relative w-full aspect-square rounded overflow-hidden bg-secondary/50 flex items-center justify-center">
            <img src="${item.dataUrl}" class="w-full h-full object-cover">
            <button type="button" onclick="removeFromLibrary(${item.id})" title="Remove from library" class="absolute top-1 right-1 w-6 h-6 rounded bg-black/60 hover:bg-red-600 text-white flex items-center justify-center transition-colors">
              <i data-lucide="trash-2" class="w-3 h-3"></i>
            </button>
            ${isRef1 ? '<span class="absolute bottom-1 left-1 bg-black/80 text-white text-[9px] font-mono px-1.5 py-0.5 rounded">Ref 1</span>' : ''}
            ${isRef2 ? '<span class="absolute bottom-1 right-1 bg-black/80 text-white text-[9px] font-mono px-1.5 py-0.5 rounded">Ref 2</span>' : ''}
          </div>
          <span class="text-[11px] text-foreground truncate px-0.5" title="${item.name}">${item.name}</span>
          ${actionBtns}
        `;
        tray.appendChild(card);
      });

      refreshIcons();
    }

    function removeFromLibrary(id) {
      const item = mediaLibrary.find(m => m.id === id);
      if (item) {
        if (ref1Data === item.dataUrl) clearRef1();
        if (ref2Data === item.dataUrl) clearRef2();
        mediaLibrary = mediaLibrary.filter(m => m.id !== id);
        renderMediaLibrary();
      }
    }

    // ============================================================
    // Robust Drag & Drop System for All Dropzones
    // ============================================================
    function setupDragAndDrop() {
      // 1. Ref 1 Dropzone
      const ref1Zone = document.getElementById('ref-1-dropzone');
      ref1Zone.onclick = e => {
        if (e.target.closest('button')) return;
        document.getElementById('ref-1-input').click();
      };
      bindDropEvents(ref1Zone, files => {
        if (files[0]) {
          readFileAsDataUrl(files[0], dataUrl => {
            setRefImage(1, dataUrl, files[0].name);
            addToLibrary(dataUrl, files[0].name);
          });
        }
      });

      // 2. Ref 2 Dropzone
      const ref2Zone = document.getElementById('ref-2-dropzone');
      ref2Zone.onclick = e => {
        if (e.target.closest('button')) return;
        document.getElementById('ref-2-input').click();
      };
      bindDropEvents(ref2Zone, files => {
        if (files[0]) {
          readFileAsDataUrl(files[0], dataUrl => {
            setRefImage(2, dataUrl, files[0].name);
            addToLibrary(dataUrl, files[0].name);
          });
        }
      });

      // 3. Batch Dropzone
      const batchZone = document.getElementById('batch-dropzone');
      batchZone.onclick = () => document.getElementById('batch-file-input').click();
      bindDropEvents(batchZone, files => processBatchFiles(files));

      // Global window drag prevention
      window.addEventListener('dragover', e => e.preventDefault(), false);
      window.addEventListener('drop', e => e.preventDefault(), false);
    }

    function bindDropEvents(element, onDropCallback) {
      ['dragenter', 'dragover'].forEach(eventName => {
        element.addEventListener(eventName, e => {
          e.preventDefault();
          e.stopPropagation();
          element.classList.add('drag-active');
        }, false);
      });

      ['dragleave', 'dragend'].forEach(eventName => {
        element.addEventListener(eventName, e => {
          e.preventDefault();
          e.stopPropagation();
          element.classList.remove('drag-active');
        }, false);
      });

      element.addEventListener('drop', e => {
        e.preventDefault();
        e.stopPropagation();
        element.classList.remove('drag-active');
        const files = e.dataTransfer.files;
        if (files && files.length > 0) {
          onDropCallback(files);
        }
      }, false);
    }

    // ============================================================
    // Prompt History (Deduplicated, Auto-Saved, 1-Click Load)
    // ============================================================
    let promptHistory = JSON.parse(localStorage.getItem('qwen_prompt_history')) || [];

    function renderPromptHistory() {
      const list = document.getElementById('history-list');
      const badge = document.getElementById('history-count-badge');
      if (!list) return;

      badge.textContent = `${promptHistory.length} saved`;

      if (promptHistory.length === 0) {
        list.innerHTML = '<div class="py-4 text-center text-xs text-muted-foreground italic">No prompt history yet. Prompts you generate will be saved here automatically.</div>';
        refreshIcons();
        return;
      }

      list.innerHTML = '';
      promptHistory.forEach(item => {
        const row = document.createElement('div');
        row.className = 'group flex items-center justify-between p-2 rounded-lg border border-border bg-secondary/40 hover:bg-secondary hover:border-foreground/40 transition-all cursor-pointer';
        row.onclick = () => useHistoryPrompt(item.id);

        row.innerHTML = `
          <div class="flex items-start gap-2 flex-1 min-w-0 pr-2">
            <i data-lucide="corner-down-left" class="w-3.5 h-3.5 mt-0.5 text-muted-foreground group-hover:text-foreground flex-shrink-0"></i>
            <div class="flex flex-col min-w-0">
              <span class="text-xs text-foreground font-medium truncate" title="${item.text}">${item.text}</span>
              <span class="text-[10px] text-muted-foreground font-mono">${item.timestamp || 'Recent'}</span>
            </div>
          </div>
          <div class="flex items-center gap-1 opacity-0 group-hover:opacity-100 transition-opacity">
            <button type="button" onclick="event.stopPropagation(); copyTextToClipboard('${item.text.replace(/'/g, "\\'")}')" title="Copy to clipboard" class="p-1 text-muted-foreground hover:text-foreground">
              <i data-lucide="copy" class="w-3 h-3"></i>
            </button>
            <button type="button" onclick="event.stopPropagation(); deleteHistoryPrompt(${item.id})" title="Delete from history" class="p-1 text-muted-foreground hover:text-red-500">
              <i data-lucide="trash-2" class="w-3 h-3"></i>
            </button>
          </div>
        `;
        list.appendChild(row);
      });

      refreshIcons();
    }

    function addPromptToHistory(promptText) {
      if (!promptText || !promptText.trim()) return;
      const clean = promptText.trim();

      // Check if prompt already exists in list (deduplication)
      const existingIdx = promptHistory.findIndex(p => p.text.trim().toLowerCase() === clean.toLowerCase());
      if (existingIdx !== -1) {
        // Remove old entry so it gets moved to top
        promptHistory.splice(existingIdx, 1);
      }

      promptHistory.unshift({
        id: Date.now(),
        text: clean,
        timestamp: new Date().toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })
      });

      // Keep maximum 40 entries
      if (promptHistory.length > 40) promptHistory.pop();
      localStorage.setItem('qwen_prompt_history', JSON.stringify(promptHistory));
      renderPromptHistory();
    }

    function useHistoryPrompt(id) {
      const item = promptHistory.find(p => p.id === id);
      if (item) {
        const input = document.getElementById('prompt-input');
        input.value = item.text;
        input.focus();
      }
    }

    function deleteHistoryPrompt(id) {
      promptHistory = promptHistory.filter(p => p.id !== id);
      localStorage.setItem('qwen_prompt_history', JSON.stringify(promptHistory));
      renderPromptHistory();
    }

    function clearPromptHistory() {
      if (confirm('Clear all prompt history?')) {
        promptHistory = [];
        localStorage.removeItem('qwen_prompt_history');
        renderPromptHistory();
      }
    }

    function copyTextToClipboard(text) {
      navigator.clipboard.writeText(text);
      alert('Prompt copied to clipboard!');
    }

    // ============================================================
    // Default Presets
    // ============================================================
    const DEFAULT_PRESETS = [
      { label: "Real Anatomy", prompt: "hyperrealistic 8k raw photograph, anatomically correct human body, perfect hands with 5 fingers, micro skin texture, cinematic lighting", fav: true },
      { label: "Body Swap", prompt: "seamless body swap composite, maintaining exact facial features and skin tone match, photo studio lighting, high resolution", fav: true },
      { label: "Face Swap", prompt: "high precision face identity transfer, identical eyes, nose, lips and facial structure, photorealistic blend", fav: true },
      { label: "Studio Light", prompt: "professional studio portrait, 3-point rim lighting, soft shadow falloff, Hasselblad medium format camera, 85mm lens f/1.4", fav: false },
      { label: "Phone Photo", prompt: "unfiltered candid smartphone photograph, natural daytime sunlight, subtle film grain, authentic real-life snapshot", fav: false },
      { label: "Restore Photo", prompt: "restored vintage photograph, ultra high definition remaster, noise removed, rich color grade, crystal sharp focus", fav: false }
    ];

    let userPresets = JSON.parse(localStorage.getItem('qwen_presets')) || DEFAULT_PRESETS;

    function renderPresets() {
      const list = document.getElementById('presets-list');
      const select = document.getElementById('delete-preset-select');
      if (!list || !select) return;

      list.innerHTML = '';
      select.innerHTML = '<option value="">-- Choose a template to delete --</option>';

      userPresets.forEach((p, idx) => {
        const chip = document.createElement('div');
        chip.className = 'inline-flex items-center border border-border rounded-lg bg-secondary text-foreground text-xs overflow-hidden transition-all hover:border-foreground';
        chip.innerHTML = `
          <button type="button" onclick="usePreset(${idx})" class="px-2.5 py-1 text-xs font-medium hover:bg-accent text-left">${p.label}</button>
          <button type="button" onclick="toggleFav(${idx})" class="px-1.5 py-1 text-muted-foreground hover:text-amber-400">
            <i data-lucide="star" class="w-3 h-3 ${p.fav ? 'fill-amber-400 text-amber-400' : ''}"></i>
          </button>
        `;
        list.appendChild(chip);

        const opt = document.createElement('option');
        opt.value = p.label;
        opt.textContent = p.label;
        select.appendChild(opt);
      });

      refreshIcons();
    }

    function usePreset(idx) {
      const p = userPresets[idx];
      if (p) {
        document.getElementById('prompt-input').value = p.prompt;
      }
    }

    function toggleFav(idx) {
      if (userPresets[idx]) {
        userPresets[idx].fav = !userPresets[idx].fav;
        localStorage.setItem('qwen_presets', JSON.stringify(userPresets));
        renderPresets();
      }
    }

    function saveCurrentPromptAsPreset() {
      const name = document.getElementById('new-preset-name').value.trim();
      const prompt = document.getElementById('prompt-input').value.trim();
      if (!name) { alert('Please enter a Template Name!'); return; }
      if (!prompt) { alert('Prompt is empty!'); return; }

      const existingIdx = userPresets.findIndex(p => p.label.toLowerCase() === name.toLowerCase());
      if (existingIdx !== -1) {
        userPresets[existingIdx].prompt = prompt;
      } else {
        userPresets.unshift({ label: name, prompt: prompt, fav: false });
      }

      localStorage.setItem('qwen_presets', JSON.stringify(userPresets));
      document.getElementById('new-preset-name').value = '';
      renderPresets();
    }

    function deleteSelectedPreset() {
      const select = document.getElementById('delete-preset-select');
      const val = select.value;
      if (!val) { alert('Please choose a template to delete.'); return; }

      userPresets = userPresets.filter(p => p.label !== val);
      localStorage.setItem('qwen_presets', JSON.stringify(userPresets));
      renderPresets();
    }

    // ============================================================
    // Curated LoRA Presets
    // ============================================================
    function applyCuratedPreset(name) {
      const promptEl = document.getElementById('prompt-input');
      const loraEl = document.getElementById('lora-select');
      
      const mapping = {
        'Real Anatomy': { 
          lora: 'Real Characters & Anatomy', 
          trigger: 'photorealistic portrait, natural human anatomy, detailed skin pores, realistic body proportions, soft lighting', 
          steps: 6 
        },
        'Body Swap': { 
          lora: 'Pose / Body Swap (BFS Body 2.1)', 
          trigger: 'body_swap: start with <image1> as the base image, keeping its lighting, environment, and background. replace the body from <image1> with the body from <image2>, strictly preserving the clothing, body shape and proportions from <image2>. copy the pose, direction of the eye, head rotation, micro expressions from <image1>', 
          steps: 6,
          mode: 'Transform & Swap (2 Refs)'
        },
        'Face Swap': { 
          lora: 'Face / Head Swap (BFS 2.1)', 
          trigger: 'head_swap: start with <image1> as the base image, keeping its lighting, environment, and background. remove the head from <image1> completely and replace it with the head from <image2>, strictly preserving the hair, eye color, nose structure from <image2>. copy the direction of the eye, head rotation, micro expressions from <image1>, high quality, sharp details, 4k', 
          steps: 6,
          mode: 'Transform & Swap (2 Refs)'
        },
        'Studio Light': { 
          lora: 'Studio Lighting & Cinematic', 
          trigger: 'dramatic studio lighting, soft key light, rim lighting, 85mm lens', 
          steps: 6 
        },
        'Phone Photo': { 
          lora: 'Viggle Turbo (6-Step Acceleration)', 
          trigger: 'candid smartphone photo, natural light, raw photo', 
          steps: 6 
        },
        'Restore Photo': { 
          lora: 'Photo Restore & Ultra HD', 
          trigger: 'Restore the photo: remove blur, noise and compression artifacts and recover sharp, natural detail, keeping the same composition, people and colors.', 
          steps: 6,
          mode: 'Edit Image (1 Ref)'
        },
        'Outfit Swap': { 
          lora: 'Outfit & Fashion Swap', 
          trigger: 'outfit change, haute couture fashion attire, high texture detail', 
          steps: 6 
        },
        'Anime': { 
          lora: 'Anime & Manga 2.0', 
          trigger: 'masterpiece anime artwork, vibrant colors, clean lineart', 
          steps: 6 
        },
        'Viggle Turbo (6-Step Fast)': { 
          lora: 'Viggle Turbo (6-Step Acceleration)', 
          trigger: '', 
          steps: 6 
        },
      };

      const preset = mapping[name];
      if (preset) {
        if (preset.mode) {
          setMode(preset.mode);
        }
        loraEl.value = preset.lora;
        if (preset.trigger) {
          if (preset.mode === 'Transform & Swap (2 Refs)') {
            promptEl.value = preset.trigger;
          } else if (!promptEl.value.includes(preset.trigger)) {
            promptEl.value = promptEl.value ? promptEl.value + ', ' + preset.trigger : preset.trigger;
          }
        }
        document.getElementById('steps-slider').value = preset.steps;
        document.getElementById('steps-val').textContent = preset.steps;
        updateLoraBanner();
      }
    }

    function onLoraSelectChange() {
      updateLoraBanner();
    }

    function updateLoraBanner() {
      const lora = document.getElementById('lora-select').value;
      const strength = document.getElementById('lora-strength').value;
      document.getElementById('lora-banner-text').textContent = `Active LoRA: ${lora} · Weight: ${strength}`;
    }

    // LoRA Tab Switching (Curated vs HF Live Explorer vs Custom Repo)
    function setLoraTab(tab) {
      const curatedPane = document.getElementById('tab-curated-pane');
      const hfPane = document.getElementById('tab-hf-pane');
      const customPane = document.getElementById('tab-custom-pane');
      
      const curatedBtn = document.getElementById('tab-curated-btn');
      const hfBtn = document.getElementById('tab-hf-btn');
      const customBtn = document.getElementById('tab-custom-btn');
      
      if (curatedPane) curatedPane.classList.toggle('hidden', tab !== 'curated');
      if (hfPane) hfPane.classList.toggle('hidden', tab !== 'hf-explorer');
      if (customPane) customPane.classList.toggle('hidden', tab !== 'custom');
      
      [
        { btn: curatedBtn, active: tab === 'curated' },
        { btn: hfBtn, active: tab === 'hf-explorer' },
        { btn: customBtn, active: tab === 'custom' }
      ].forEach(({ btn, active }) => {
        if (!btn) return;
        if (active) {
          btn.className = 'lora-tab-btn pb-2 border-b-2 border-foreground text-foreground flex items-center gap-1.5 font-semibold';
        } else {
          btn.className = 'lora-tab-btn pb-2 border-b-2 border-transparent text-muted-foreground hover:text-foreground flex items-center gap-1.5';
        }
      });
      refreshIcons();
    }

    // ============================================================
    // Hugging Face Explorer
    // ============================================================
    async function searchHfLoras() {
      const q = document.getElementById('hf-search-query').value.trim();
      const btn = document.getElementById('hf-search-btn');
      btn.innerHTML = `<div class="w-3.5 h-3.5 border-2 border-foreground border-t-transparent rounded-full animate-spin"></div> Searching...`;

      try {
        const res = await fetch(`/api/search-loras?q=${encodeURIComponent(q)}`);
        const data = await res.json();
        const select = document.getElementById('hf-models-select');
        select.innerHTML = '<option value="">-- Choose Repository --</option>';
        (data.models || []).forEach(m => {
          const opt = document.createElement('option');
          opt.value = m.repo_id;
          opt.textContent = `${m.repo_id} (${m.likes || 0} ♥, ${m.downloads || 0} dl)`;
          select.appendChild(opt);
        });
      } catch (err) {
        console.error(err);
      } finally {
        btn.innerHTML = `<i data-lucide="search" class="w-3.5 h-3.5"></i> Search Models`;
        refreshIcons();
      }
    }

    async function onHfModelSelect() {
      const repo = document.getElementById('hf-models-select').value;
      if (!repo) return;

      const fileSelect = document.getElementById('hf-files-select');
      fileSelect.innerHTML = '<option value="">Fetching files...</option>';

      try {
        const res = await fetch(`/api/repo-files?repo=${encodeURIComponent(repo)}`);
        const data = await res.json();
        fileSelect.innerHTML = '<option value="">-- Choose Safetensors File --</option>';
        (data.files || []).forEach(f => {
          const opt = document.createElement('option');
          opt.value = f;
          opt.textContent = f;
          fileSelect.appendChild(opt);
        });
      } catch (err) {
        console.error(err);
        fileSelect.innerHTML = '<option value="">Error fetching files</option>';
      }
    }

    function applyHfSelection() {
      const repo = document.getElementById('hf-models-select').value;
      const file = document.getElementById('hf-files-select').value;
      if (!repo) { alert('Please select a repository first.'); return; }
      
      const loraSelect = document.getElementById('lora-select');
      loraSelect.value = 'Custom / Hugging Face LoRA';
      document.getElementById('lora-banner-text').textContent = `Active HF LoRA: ${repo} / ${file || 'default'}`;
      alert(`Applied LoRA: ${repo}`);
    }

    function applyCustomSelection() {
      const repo = document.getElementById('custom-repo-input').value.trim();
      const file = document.getElementById('custom-file-input').value.trim();
      if (!repo) { alert('Please enter a Hugging Face Repo ID.'); return; }
      
      const loraSelect = document.getElementById('lora-select');
      loraSelect.value = 'Custom / Hugging Face LoRA';
      document.getElementById('lora-banner-text').textContent = `Active Custom LoRA: ${repo} / ${file || 'default'}`;
      alert(`Applied Custom LoRA: ${repo}`);
    }

    // ============================================================
    // IndexedDB Private Browser Gallery
    // ============================================================
    const DB_NAME = 'QwenStudioDB';
    const DB_VERSION = 1;
    const STORE_NAME = 'generations';

    function openDB() {
      return new Promise((resolve, reject) => {
        const req = indexedDB.open(DB_NAME, DB_VERSION);
        req.onupgradeneeded = e => {
          const db = e.target.result;
          if (!db.objectStoreNames.contains(STORE_NAME)) {
            db.createObjectStore(STORE_NAME, { keyPath: 'id' });
          }
        };
        req.onsuccess = e => resolve(e.target.result);
        req.onerror = e => reject(e.target.error);
      });
    }

    async function saveToDB(item) {
      const db = await openDB();
      return new Promise((resolve, reject) => {
        const tx = db.transaction(STORE_NAME, 'readwrite');
        const store = tx.objectStore(STORE_NAME);
        item.id = Date.now();
        const req = store.add(item);
        req.onsuccess = () => resolve(req.result);
        req.onerror = e => reject(e.target.error);
      });
    }

    async function getAllFromDB() {
      const db = await openDB();
      return new Promise((resolve, reject) => {
        const tx = db.transaction(STORE_NAME, 'readonly');
        const store = tx.objectStore(STORE_NAME);
        const req = store.getAll();
        req.onsuccess = () => resolve((req.result || []).sort((a, b) => b.id - a.id));
        req.onerror = e => reject(e.target.error);
      });
    }

    async function deleteFromDB(id) {
      const db = await openDB();
      return new Promise((resolve, reject) => {
        const tx = db.transaction(STORE_NAME, 'readwrite');
        const store = tx.objectStore(STORE_NAME);
        const req = store.delete(Number(id));
        req.onsuccess = () => resolve();
        req.onerror = e => reject(e.target.error);
      });
    }

    async function clearAllFromDB() {
      const db = await openDB();
      return new Promise((resolve, reject) => {
        const tx = db.transaction(STORE_NAME, 'readwrite');
        const store = tx.objectStore(STORE_NAME);
        const req = store.clear();
        req.onsuccess = () => resolve();
        req.onerror = e => reject(e.target.error);
      });
    }

    async function renderGallery() {
      const items = await getAllFromDB();
      const grid = document.getElementById('gallery-grid');
      const countLabel = document.getElementById('gallery-count-label');

      countLabel.innerHTML = `<i data-lucide="database" class="w-3.5 h-3.5 opacity-80"></i> Browser Storage: ${items.length} image(s) (100% Private, 0 KB on Space)`;

      if (items.length === 0) {
        grid.innerHTML = '<div class="col-span-full py-6 text-center text-xs text-muted-foreground italic">No images saved in your browser yet. Generated images will be saved automatically here.</div>';
        refreshIcons();
        return;
      }

      grid.innerHTML = '';
      items.forEach(item => {
        const card = document.createElement('div');
        card.className = 'group relative aspect-square rounded-lg border border-border bg-secondary overflow-hidden cursor-pointer';
        card.innerHTML = `
          <img src="${item.img_data}" class="w-full h-full object-cover transition-transform duration-200 group-hover:scale-105">
          <div class="absolute inset-0 bg-black/60 opacity-0 group-hover:opacity-100 transition-opacity p-2 flex flex-col justify-between text-white">
            <span class="text-[10px] font-mono leading-tight truncate">${item.prompt}</span>
            <div class="flex items-center justify-between">
              <span class="text-[9px] font-mono opacity-70">${item.width}x${item.height}</span>
              <button type="button" onclick="event.stopPropagation(); deleteGalleryItem(${item.id})" class="p-1 rounded bg-red-600/80 hover:bg-red-600 text-white">
                <i data-lucide="trash-2" class="w-3 h-3"></i>
              </button>
            </div>
          </div>
        `;
        card.onclick = () => openModal(item);
        grid.appendChild(card);
      });

      refreshIcons();
    }

    async function deleteGalleryItem(id) {
      if (confirm('Delete this image from browser storage?')) {
        await deleteFromDB(id);
        renderGallery();
      }
    }

    async function clearBrowserStorage() {
      if (confirm('Clear all private browser gallery images?')) {
        await clearAllFromDB();
        renderGallery();
      }
    }

    // Modal Lightbox
    let activeModalItem = null;
    function openModal(item) {
      activeModalItem = item;
      document.getElementById('modal-title').textContent = item.prompt || 'Generated Output';
      document.getElementById('modal-img').src = item.img_data;
      document.getElementById('modal-meta').textContent = `Seed: ${item.seed} · Steps: ${item.steps} · Size: ${item.width}×${item.height} · LoRA: ${item.lora || 'Base'}`;
      document.getElementById('modal-dl').href = item.img_data;
      document.getElementById('gallery-modal').classList.remove('hidden');
      refreshIcons();
    }

    function closeModal() {
      document.getElementById('gallery-modal').classList.add('hidden');
    }

    function copyModalPrompt() {
      if (activeModalItem && activeModalItem.prompt) {
        navigator.clipboard.writeText(activeModalItem.prompt);
        alert('Prompt copied to clipboard!');
      }
    }

    // ============================================================
    // GENERATE IMAGE WORKFLOW (API CALL)
    // ============================================================
    async function triggerGeneration() {
      const prompt = document.getElementById('prompt-input').value.trim();
      if (!prompt) {
        alert('Please enter a prompt describing your image.');
        return;
      }

      // Check if reference image is required
      if (currentMode === 'Edit Image (1 Ref)' && !ref1Data) {
        alert('Please upload or select an image as Reference Input 1.');
        return;
      }
      if (currentMode === 'Transform & Swap (2 Refs)' && (!ref1Data || !ref2Data)) {
        alert('Please select both Image 1 (Base) and Image 2 (Donor / Pose) for Transform mode.');
        return;
      }

      // Automatically add prompt to Prompt History (auto-deduplicated!)
      addPromptToHistory(prompt);

      const btn = document.getElementById('generate-btn');
      const btnText = document.getElementById('generate-btn-text');
      const loading = document.getElementById('canvas-loading');
      
      btn.disabled = true;
      btn.classList.add('opacity-75');
      btnText.textContent = 'Generating Image...';
      loading.classList.remove('hidden');

      const payload = {
        prompt: prompt,
        mode: currentMode,
        lora_adapter: document.getElementById('lora-select').value,
        lora_strength: parseFloat(document.getElementById('lora-strength').value),
        aspect_ratio: document.getElementById('aspect-ratio-select').value,
        steps: parseInt(document.getElementById('steps-slider').value),
        seed: parseInt(document.getElementById('seed-input').value),
        randomize_seed: document.getElementById('randomize-seed-cb').checked,
        custom_repo: document.getElementById('custom-repo-input')?.value || '',
        custom_file: document.getElementById('custom-file-input')?.value || '',
        ref_image_1_b64: ref1Data || null,
        ref_image_2_b64: ref2Data || null,
      };

      try {
        const response = await fetch('/api/generate', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify(payload)
        });

        const data = await response.json();
        if (data.error) {
          alert('Generation Error: ' + data.error);
          return;
        }

        // Render Image to Canvas
        const imgEl = document.getElementById('canvas-img');
        const emptyEl = document.getElementById('canvas-empty');
        imgEl.src = data.image_url || data.image_b64;
        imgEl.classList.remove('hidden');
        emptyEl.classList.add('hidden');

        // Update Download Button
        const dlBtn = document.getElementById('download-btn');
        dlBtn.href = data.image_url || data.image_b64;
        dlBtn.download = `qwen_${data.seed}_${data.width}x${data.height}.png`;
        dlBtn.classList.remove('opacity-50', 'pointer-events-none');
        document.getElementById('download-filename').textContent = `qwen_${data.seed}_${data.width}x${data.height}.png`;
        document.getElementById('download-size').textContent = `${data.width}×${data.height}`;

        // Prompt Sent
        document.getElementById('used-prompt-view').value = data.prompt;

        // Auto Save to IndexedDB Gallery
        await saveToDB({
          img_data: data.image_url || data.image_b64,
          prompt: data.prompt,
          seed: data.seed,
          steps: data.steps,
          width: data.width,
          height: data.height,
          lora: payload.lora_adapter,
          timestamp: new Date().toLocaleString()
        });

        renderGallery();

      } catch (err) {
        console.error(err);
        alert('Failed to connect to server: ' + err.message);
      } finally {
        btn.disabled = false;
        btn.classList.remove('opacity-75');
        btnText.textContent = 'Generate Image';
        loading.classList.add('hidden');
        refreshIcons();
      }
    }

    // Startup Initialization
    window.addEventListener('DOMContentLoaded', () => {
      initTheme();
      renderPresets();
      renderPromptHistory();
      renderGallery();
      setupDragAndDrop();
      refreshIcons();
    });
  </script>
</body>
</html>