File size: 223,800 Bytes
2c22341
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
450d167
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>hf-sandbox</title>
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body {
            background: #0a0a0a;
            color: #0f0;
            font-family: 'SF Mono', 'Fira Code', monospace;
            font-size: 14px;
            line-height: 1.6;
            padding: 2rem;
            min-height: 100vh;
        }
        .container { max-width: 640px; margin: 0 auto; }
        h1 {
            font-size: 1.4rem;
            font-weight: normal;
            margin-bottom: 1rem;
            padding-bottom: 1rem;
            border-bottom: 1px solid #222;
        }
        h1::before { content: '$ '; opacity: 0.4; }
        h2 {
            color: #666;
            font-size: 0.75rem;
            font-weight: normal;
            text-transform: uppercase;
            letter-spacing: 0.1em;
            margin: 2rem 0 0.5rem;
        }
        .prompt {
            background: #111;
            border-left: 2px solid #0f0;
            padding: 0.75rem 1rem;
            margin: 0.5rem 0;
            color: #fff;
        }
        .prompt::before {
            content: '→ ';
            color: #0f0;
        }
        a { color: #0af; text-decoration: none; }
        a:hover { text-decoration: underline; }
        .dim { color: #444; }
        .blink { animation: blink 1s step-end infinite; }
        @keyframes blink { 50% { opacity: 0; } }
    </style>
</head>
<body>
    <div class="container">
        <h1>hf-sandbox<span class="blink">_</span></h1>
        <p style="color:#888;">remote code execution for <a href="https://agentskills.io">ai agents</a></p>

        <h2>install</h2>
        <pre>git clone https://huggingface.co/spaces/burtenshaw/sandbox .claude/skills/hf-sandbox</pre>

        <h2>create sandbox</h2>
        <div class="prompt">create a sandbox called my-sandbox on hugging face</div>

        <h2>store a value</h2>
        <div class="prompt">save 42 to a file called foo in the sandbox</div>

        <h2>read it back</h2>
        <div class="prompt">read the value of foo from the sandbox</div>

        <h2>run uv script</h2>
        <div class="prompt">run a python script that prints "hello" using requests</div>

        <h2>background job</h2>
        <div class="prompt">run train.py in the background and save output to a log file</div>

    </div>
</body>
</html>
    <div class="container py-8">
        <header class="text-center mb-12 bg-white p-6 rounded-xl shadow-lg border-b-4 border-blue-500">
            <h1 class="text-4xl font-extrabold text-gray-900">Tạo Cốt Truyện Bằng AI</h1>
            <p class="mt-2 text-lg text-gray-600">Duy trì tính nhất quán cho các nhân vật và bối cảnh câu chuyện</p>
        </header>

        <main class="grid lg:grid-cols-3 gap-8">
            <div id="storyboard" class="lg:col-span-2 space-y-8">
                <div id="intro-card" class="story-page text-center">
                    <h2 class="text-3xl font-bold text-gray-800 mb-6">Bước 1: Bắt Đầu Câu Chuyện Mới</h2>
                    <p class="text-gray-600 mb-6">Tải lên một hoặc nhiều hình ảnh để tạo bối cảnh HOẶC nhập ý tưởng cốt truyện của bạn để bắt đầu.</p>
                    <div class="mb-6 p-4 bg-blue-50 rounded-lg border border-blue-200">
                        <label for="story-idea-input" class="block text-blue-800 font-semibold mb-2 text-left">Ý tưởng Cốt truyện (Bắt buộc):</label>
                        <textarea id="story-idea-input" rows="3" class="w-full p-3 border border-blue-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 transition duration-200 shadow-inner" placeholder="Nhập ý tưởng chính cho câu chuyện của bạn ở đây..."></textarea>
                    </div>
                    <div class="flex flex-col sm:flex-row gap-4 justify-center items-center">
                        <div class="bg-gray-200 p-4 rounded-xl flex flex-col items-center justify-center shadow-md">
                            <label for="image-upload-input-intro" class="cursor-pointer bg-indigo-600 hover:bg-indigo-700 text-white font-semibold py-3 px-8 rounded-full transition duration-300 shadow-xl transform hover:scale-105">Tải lên Hình ảnh</label>
                            <input type="file" id="image-upload-input-intro" accept="image/*" class="hidden" multiple>
                            <p class="text-xs text-gray-500 mt-2">(Để phân tích nhân vật/bối cảnh)</p>
                        </div>
                        <span class="text-gray-500 font-semibold text-2xl">HOẶC</span>
                        <div class="bg-gray-200 p-4 rounded-xl flex flex-col items-center justify-center shadow-md">
                            <button id="generate-story-from-idea-btn" class="cursor-pointer bg-green-600 hover:bg-green-700 text-white font-semibold py-3 px-8 rounded-full transition duration-300 shadow-xl transform hover:scale-105">Tạo Cốt Truyện</button>
                            <p class="text-xs text-gray-500 mt-2">(Nhận diện nhân vật & Tự động tạo cảnh)</p>
                        </div>
                    </div>
                </div>
            </div>

            <div id="dialogue-editing-panel" class="lg:col-span-2 space-y-6 p-8 bg-white rounded-xl shadow-2xl hidden border-t-4 border-indigo-500">
                <h2 id="dialogue-panel-title" class="text-3xl font-bold text-gray-800 border-b pb-3 mb-4">Bước 4: Tạo Bong bóng Rỗng & Lời Thoại</h2>
                <div id="dialogue-instruction-container" class="bg-yellow-100 p-4 rounded-lg border border-yellow-300">
                    <p id="dialogue-instruction" class="text-sm text-gray-700">
                        <span class="font-bold text-yellow-800">HƯỚNG DẪN:</span> Kéo **bong bóng thoại** đến vị trí mong muốn. Kéo các **góc tròn màu xanh** để **thay đổi kích thước** thủ công. Vị trí này sẽ được AI sử dụng để **vẽ bong bóng rỗng**.
                    </p>
                </div>
                <div class="bg-white p-5 rounded-xl shadow-inner border border-gray-200">
                    <h3 class="text-2xl font-bold text-gray-800 border-b pb-2 mb-4">1. Đặt Vị trí Bong bóng Thoại:</h3>
                    <div id="interactive-dialogue-area" class="border-4 border-dashed border-gray-400 rounded-lg shadow-xl overflow-hidden relative" style="line-height: 0;"></div>
                    <div class="my-4">
                        <label for="font-select" class="block text-gray-700 font-semibold mb-2">Chọn Font Chữ cho Trang (Áp dụng cho tất cả):</label>
                        <select id="font-select" class="w-full p-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-indigo-500 transition duration-200 shadow-inner">
                            <option value="'Bangers', cursive" style="font-family: 'Bangers', cursive;">Bangers (Mặc định)</option>
                            <option value="'Klee One', cursive" style="font-family: 'Klee One', cursive;">Klee One (Phong cách Manga)</option>
                            <option value="'Comic Neue', cursive" style="font-family: 'Comic Neue', cursive;">Comic Neue</option>
                            <option value="'Patrick Hand', cursive" style="font-family: 'Patrick Hand', cursive;">Patrick Hand</option>
                            <option value="'Luckiest Guy', cursive" style="font-family: 'Luckiest Guy', cursive;">Luckiest Guy</option>
                            <option value="'Kalam', cursive" style="font-family: 'Kalam', cursive;">Kalam</option>
                            <option value="'Architects Daughter', cursive" style="font-family: 'Architects Daughter', cursive;">Architects Daughter</option>
                            <option value="'Inter', sans-serif" style="font-family: 'Inter', sans-serif;">Inter (Cơ bản)</option>
                        </select>
                    </div>
                    <div class="flex justify-between items-center mb-4 pt-4 border-t border-gray-200">
                        <h3 class="text-xl font-semibold text-gray-700">Danh sách Lời thoại & Hình dạng:</h3>
                        <button id="add-generic-dialogue-btn" class="bg-gray-400 hover:bg-gray-500 text-white text-sm font-semibold py-2 px-4 rounded-lg transition duration-200 shadow-md transform hover:scale-105">+ Thêm Lời Thoại Mới (Chung)</button>
                    </div>
                    <div id="dialogue-inputs-container" class="space-y-4 max-h-80 overflow-y-auto p-3 border border-gray-200 rounded-lg bg-gray-50"></div>
                </div>
                <div id="dialogue-loading-indicator" class="mt-6 hidden text-center p-4 bg-indigo-50 rounded-lg">
                    <div class="animate-spin inline-block w-10 h-10 border-4 border-t-4 border-indigo-600 border-gray-200 rounded-full"></div>
                    <p id="dialogue-loading-message" class="mt-3 text-lg font-medium text-indigo-700">Đang xử lý...</p>
                </div>
                <div class="mt-6 mb-4 p-4 bg-teal-50 rounded-lg border border-teal-200">
                    <label for="ai-layout-style-select" class="block text-teal-900 font-bold mb-2">Phong cách Bố cục AI (Cho nút Tạo Bố cục Động):</label>
                    <select id="ai-layout-style-select" class="w-full p-3 border border-teal-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-teal-500 transition duration-200 shadow-inner text-gray-800">
                        <option value="dynamic">Động / Truyện tranh (Mặc định)</option>
                        <option value="advertisement">Quảng cáo (Advertisement)</option>
                        <option value="newspaper">Báo in (Newspaper)</option>
                        <option value="magazine">Tạp chí (Magazine)</option>
                        <option value="brochure">Giới thiệu / Brochure</option>
                        <option value="manga">Manga (Nhật Bản)</option>
                        <option value="cinematic">Điện ảnh (Cinematic)</option>
                    </select>
                </div>
                <div class="flex flex-wrap gap-4 mt-6">
                    <button id="back-from-dialogue-btn" class="w-full sm:w-auto flex-grow bg-gray-500 hover:bg-gray-600 text-white font-bold py-3 px-4 rounded-lg transition duration-300 shadow-md transform hover:scale-105">Quay lại (Bước 3)</button>
                    <button id="use-fallback-layout-btn" class="w-full sm:w-auto flex-grow bg-orange-600 hover:bg-orange-700 text-white font-bold py-3 px-4 rounded-lg transition duration-300 shadow-lg transform hover:scale-105">Sử dụng Lưới Cơ bản & Vẽ Bong bóng</button>
                    <button id="finalize-ai-layout-btn" class="w-full sm:w-auto flex-grow bg-teal-600 hover:bg-teal-700 text-white font-bold py-3 px-4 rounded-lg transition duration-300 shadow-lg transform hover:scale-105">Tạo Bố cục AI Động & Bong bóng Rỗng</button>
                    <button id="capture-final-page-btn" class="w-full bg-green-600 hover:bg-green-700 text-white font-bold py-3 px-4 rounded-lg transition duration-300 shadow-lg transform hover:scale-105 hidden">HOÀN TẤT Trang Truyện (In Văn bản)</button>
                    <input type="hidden" id="editing-page-id" value="">
                </div>
            </div>

            <div id="character-setup-panel" class="lg:col-span-2 space-y-4 p-8 bg-white rounded-xl shadow-2xl hidden border-t-4 border-orange-500">
                <h2 class="text-3xl font-bold text-gray-800 border-b pb-3 mb-4">Bước 2: Đặt Tên Nhân Vật</h2>
                <p class="text-gray-600 mb-6">Đặt tên cho các nhân vật được phát hiện. Bạn có thể đặt cùng tên cho nhiều mô tả để hợp nhất chúng thành một nhân vật duy nhất.</p>
                <div id="existing-characters-list" class="mb-4"></div>
                <div id="character-naming-inputs" class="space-y-4"></div>
                <div class="flex gap-4 mt-6">
                    <button id="back-to-image-select-btn" class="w-full bg-gray-500 hover:bg-gray-600 text-white font-bold py-3 px-4 rounded-lg transition duration-300 shadow-md transform hover:scale-105">Quay lại (Bước 1)</button>
                    <button id="finalize-characters-btn" class="w-full bg-green-600 hover:bg-green-700 text-white font-bold py-3 px-4 rounded-lg transition duration-300 shadow-md transform hover:scale-105">Lưu Nhân Vật & Tiếp tục</button>
                </div>
                <button id="skip-naming-btn" class="w-full bg-yellow-500 hover:bg-yellow-600 text-white font-bold py-3 px-4 rounded-lg transition duration-300 shadow-md mt-4 transform hover:scale-105">Bỏ qua & Chỉ dùng Bối cảnh</button>
            </div>

            <div class="lg:col-span-1 space-y-8">
                <div id="creation-panel" class="p-8 bg-white rounded-xl shadow-2xl border-t-4 border-blue-500 hidden">
                    <h2 class="text-2xl font-semibold text-gray-700 mb-4">Bước 3: Tạo Lời Nhắc</h2>
                    <div id="input-image-section" class="mb-6 pb-4 border-b border-gray-200">
                        <h3 class="text-xl font-semibold text-gray-700 mb-3">Ảnh Đầu vào (Nhân vật & Bối cảnh)</h3>
                        <p class="text-xs text-gray-600 mb-3 p-2 bg-blue-50 rounded-lg border border-blue-200">Di chuột qua ảnh để Lưu, Trích xuất Bối cảnh hoặc Xóa ảnh. **Nhấn "Nhận diện Nhân vật" để trích xuất nhân vật.**</p>
                        <div id="input-image-container" class="grid grid-cols-1 gap-4 p-3 bg-gray-50 rounded-lg border">
                            <p class="text-sm text-gray-500 col-span-2 input-placeholder-text">Chưa có ảnh đầu vào.</p>
                        </div>
                        <div class="mt-4">
                            <label for="story-idea-input-panel" class="block text-gray-700 font-medium mb-2">Ý tưởng Cốt truyện (Tùy chọn):</label>
                            <textarea id="story-idea-input-panel" rows="3" class="w-full p-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 transition duration-200 shadow-inner" placeholder="Nhập ý tưởng chính cho câu chuyện của bạn ở đây... (Sử dụng để tạo cốt truyện hoặc kết hợp làm ngữ cảnh)"></textarea>
                        </div>
                        <div class="flex items-center my-3 p-3 bg-indigo-50 rounded-lg border border-indigo-200">
                            <input type="checkbox" id="is-comic-page-check" class="h-5 w-5 text-indigo-600 border-gray-300 rounded focus:ring-indigo-500">
                            <label for="is-comic-page-check" class="ml-3 block text-base font-medium text-gray-700">Ảnh tải lên là một trang truyện (để tiếp diễn)</label>
                        </div>
                        <div class="mt-4 flex flex-wrap gap-4 items-center">
                            <label for="image-upload-input" class="cursor-pointer bg-blue-500 hover:bg-blue-600 text-white font-semibold py-2 px-4 rounded-lg transition duration-200 shadow-md transform hover:scale-105">Tải lên</label>
                            <input type="file" id="image-upload-input" accept="image/*" class="hidden" multiple>
                            <button id="confirm-selection-btn" class="bg-green-500 hover:bg-green-600 text-white font-semibold py-2 px-4 rounded-lg transition duration-200 shadow-md transform hover:scale-105">Phân tích & Đặt tên (Bước 2)</button>
                            <button id="generate-story-from-idea-panel-btn" class="cursor-pointer bg-yellow-500 hover:bg-yellow-600 text-white font-semibold py-2 px-4 rounded-lg transition duration-300 shadow-md transform hover:scale-105">Tạo Cốt Truyện</button>
                        </div>
                    </div>
                    <div id="prompt-section" class="hidden">
                        <div class="mb-4 pb-3 border-b border-gray-200">
                            <h3 class="text-xl font-semibold text-gray-700 mb-3">Quản lý Nhân vật & Vật dụng</h3>
                            <div class="mb-3 p-3 bg-white rounded-lg border border-gray-200 shadow-sm">
                                <h4 class="text-sm font-semibold text-gray-600 mb-2">Nhân vật trong Cảnh này (Được chọn):</h4>
                                <div id="scene-characters-list" class="flex flex-wrap gap-2 min-h-[36px] p-2 bg-gray-100 rounded-lg border border-dashed">
                                    <p id="scene-char-placeholder" class="text-sm text-gray-500 italic">Chọn nhân vật từ danh sách bên dưới.</p>
                                </div>
                            </div>
                            <div class="mb-3 p-3 bg-white rounded-lg border border-gray-200 shadow-sm">
                                <h4 class="text-sm font-semibold text-gray-600 mb-2">Tất cả Nhân vật đã biết (Click ảnh để phóng to):</h4>
                                <div class="flex justify-between items-center mb-2">
                                    <button id="show-add-char-modal-btn" class="bg-green-500 hover:bg-green-600 text-white text-xs font-semibold py-1 px-3 rounded-lg shadow-md transform hover:scale-105">+ Thêm Mới</button>
                                </div>
                                <div id="all-characters-pool" class="flex flex-wrap gap-2 min-h-[36px]">
                                    <p class="text-sm text-gray-500">Chưa có nhân vật được đặt tên.</p>
                                </div>
                            </div>
                            <div class="mb-3 p-3 bg-white rounded-lg border border-gray-200 shadow-sm">
                                <h4 class="text-sm font-semibold text-gray-600 mb-2">Vật dụng để sử dụng trong Cảnh:</h4>
                                <div id="scene-items-pool" class="flex flex-col gap-2 min-h-[36px] p-2 bg-gray-100 rounded-lg border border-dashed max-h-48 overflow-y-auto">
                                    <p id="scene-items-placeholder" class="text-sm text-gray-500 italic">Nhân vật đang hoạt động không có vật dụng nào.</p>
                                </div>
                            </div>
                        </div>
                        <div class="mb-6 pt-2 border-t border-gray-200">
                            <h3 class="text-xl font-semibold text-gray-700 mb-3">Thông tin Bối cảnh & Nhân vật đã đặt tên</h3>
                            <div id="context-info-container" class="space-y-4 p-3 bg-gray-50 rounded-lg border">
                                <p class="text-sm text-gray-500">Chưa có thông tin bối cảnh.</p>
                            </div>
                        </div>
                        <div class="mb-4 space-y-4 pt-2 border-t border-gray-200">
                            <h3 class="text-xl font-semibold text-gray-700 mb-3">Gợi ý Cốt truyện & Tùy chỉnh Trang</h3>
                            <div class="grid grid-cols-1 sm:grid-cols-2 gap-4">
                                <div>
                                    <label for="genre-select" class="block text-sm font-medium text-gray-700">Chọn Thể loại:</label>
                                    <select id="genre-select" class="w-full p-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 transition duration-200 shadow-inner">
                                        <option value="">(Tự động / Chung)</option>
                                        <option value="Hành động">Hành động (Action)</option>
                                        <option value="Quảng cáo">Quảng cáo (Advertisement)</option>
                                        <option value="Kinh dị">Kinh dị (Horror)</option>
                                        <option value="Viễn tưởng">Viễn tưởng (Sci-Fi)</option>
                                        <option value="Ngôn tình">Ngôn tình (Romance)</option>
                                        <option value="Hài hước">Hài hước (Comedy)</option>
                                    </select>
                                </div>
                                <div>
                                    <label for="scene-count-select" class="block text-sm font-medium text-gray-700">Số lượng Cảnh:</label>
                                    <select id="scene-count-select" class="w-full p-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 transition duration-200 shadow-inner">
                                        <option value="1">1 Cảnh</option>
                                        <option value="2">2 Cảnh</option>
                                        <option value="3">3 Cảnh</option>
                                        <option value="4" selected>4 Cảnh (Lưới 2x2)</option>
                                    </select>
                                </div>
                            </div>
                            <div class="space-y-2 pt-2 border-t border-gray-100">
                                <p class="text-sm font-medium text-gray-700">Tạo Gợi ý Cảnh:</p>
                                <button id="generate-all-scenes-btn" class="w-full bg-yellow-500 hover:bg-yellow-600 text-white font-semibold py-2 px-4 rounded-lg transition duration-200 shadow-md transform hover:scale-105">Tạo Mới (Cùng Lúc)</button>
                                <button id="generate-sequential-scenes-btn" class="w-full bg-yellow-600 hover:bg-yellow-700 text-white font-semibold py-2 px-4 rounded-lg transition duration-200 shadow-md transform hover:scale-105">Tạo Mới (Từng Cảnh Tuần Tự)</button>
                                <button id="continue-all-scenes-btn" class="w-full bg-indigo-500 hover:bg-indigo-600 text-white font-semibold py-2 px-4 rounded-lg transition duration-200 shadow-md transform hover:scale-105" disabled>Tiếp diễn (Cùng Lúc)</button>
                                <button id="continue-sequential-scenes-btn" class="w-full bg-indigo-600 hover:bg-indigo-700 text-white font-semibold py-2 px-4 rounded-lg transition duration-200 shadow-md transform hover:scale-105" disabled>Tiếp diễn (Từng Cảnh Tuần Tự)</button>
                            </div>
                        </div>
                        <div class="mb-4 space-y-3 pt-2 border-t border-gray-200">
                            <label for="style-select" class="block text-gray-700 font-semibold">Chọn Phong Cách:</label>
                            <select id="style-select" class="w-full p-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 transition duration-200 shadow-inner">
                                <option value="">(Mặc định) Dựa trên ảnh đầu vào</option>
                                <option value="comic_book_style">Phong cách truyện tranh (Comic)</option>
                                <option value="anime_style">Phong cách Anime</option>
                                <option value="watercolor_style">Phong cách sơn màu nước</option>
                                <option value="photorealistic_style">Phong cách Siêu thực (Photorealistic)</option>
                                <option value="cinematic_style">Điện ảnh (Cinematic)</option>
                                <option value="dark_fantasy_style">Dark Fantasy</option>
                                <option value="mythological_style">Thần thoại (Mythological)</option>
                            </select>
                            <label for="aspect-ratio-select" class="block text-gray-700 font-semibold">Tỷ lệ Trang:</label>
                            <select id="aspect-ratio-select" class="w-full p-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 transition duration-200 shadow-inner">
                                <option value="1:1">1:1 (Vuông)</option>
                                <option value="3:4">3:4 (Chân dung)</option>
                                <option value="2:3">2:3 (Chân dung dài)</option>
                                <option value="16:9">16:9 (Màn ảnh rộng)</option>
                            </select>
                            <label for="border-style-select" class="block text-gray-700 font-semibold">Kiểu Viền Khung:</label>
                            <select id="border-style-select" class="w-full p-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 transition duration-200 shadow-inner">
                                <option value="classic black">Viền đen cổ điển</option>
                                <option value="no borders">Không viền (liền mạch)</option>
                                <option value="colored borders">Viền màu (dựa trên ảnh)</option>
                            </select>
                        </div>
                        <div id="prompts-container" class="space-y-4 mb-6"></div>
                        <div class="flex items-center gap-2 mb-4 pt-2 border-t border-gray-200">
                            <button id="add-prompt-btn" class="bg-gray-200 hover:bg-gray-300 text-gray-700 font-semibold py-2 px-4 rounded-lg transition duration-200 shadow-sm transform hover:scale-105">Thêm Cảnh</button>
                            <p class="text-sm text-gray-500">(Tối đa 4 cảnh)</p>
                        </div>
                        <div class="flex items-center my-4 p-3 bg-yellow-50 rounded-lg border border-yellow-200">
                            <input type="checkbox" id="auto-fill-dialogue-check" class="h-5 w-5 text-indigo-600 border-gray-300 rounded focus:ring-indigo-500">
                            <label for="auto-fill-dialogue-check" class="ml-3 block text-base font-medium text-gray-700">Tự động tạo lời thoại (Đối thoại)</label>
                        </div>
                        <div class="flex items-center my-4 p-3 bg-teal-50 rounded-lg border border-teal-200">
                            <input type="checkbox" id="auto-fill-product-features-check" class="h-5 w-5 text-teal-600 border-gray-300 rounded focus:ring-teal-500">
                            <label for="auto-fill-product-features-check" class="ml-3 block text-base font-medium text-gray-700">Tự động trích xuất Tính năng/Thông số (Quảng cáo)</label>
                        </div>
                        <button id="generate-btn" class="w-full bg-red-600 hover:bg-red-700 text-white font-bold py-3 px-4 rounded-lg transition duration-300 shadow-lg transform hover:scale-105">Tạo Trang Nháp</button>
                    </div>
                    <div id="loading-indicator" class="mt-6 hidden text-center p-4 bg-blue-50 rounded-lg">
                        <div class="animate-spin inline-block w-10 h-10 border-4 border-t-4 border-blue-600 border-gray-200 rounded-full"></div>
                        <p id="loading-message" class="mt-3 text-lg font-medium text-blue-700">Đang xử lý...</p>
                    </div>
                </div>

                <div id="library-panel" class="p-8 bg-white rounded-xl shadow-2xl border-t-4 border-gray-500">
                    <h2 class="text-2xl font-semibold text-gray-700 mb-4">Thư Viện Ảnh Đã Lưu</h2>
                    <div class="flex justify-center gap-4 mb-4">
                        <button id="download-excel-btn" title="Tải xuống tệp Excel (CSV)" class="bg-teal-500 hover:bg-teal-600 text-white font-semibold py-2 px-5 rounded-lg transition duration-200 shadow-md transform hover:scale-105 hidden">Tải xuống Excel</button>
                    </div>
                    <div id="image-library-container" class="grid grid-cols-2 gap-4 p-3 bg-gray-50 rounded-lg border">
                        <p class="text-center text-gray-400 col-span-2">Thư viện trống.</p>
                    </div>
                </div>
            </div>
        </main>
        <div id="fullScreenModal" class="modal">
            <span class="close-btn">&times;</span>
            <div class="modal-content"><img id="modalImage" src="" alt="Full screen image"></div>
        </div>
        <input type="file" id="image-upload-input" accept="image/*" class="hidden" multiple>

        <div id="cropperModal" class="modal">
            <div class="modal-content bg-white rounded-xl shadow-2xl w-full max-w-3xl p-6 relative">
                <span id="cancel-crop-btn" class="close-btn text-gray-800 hover:text-red-600" style="top: 15px; right: 25px; font-size: 30px;">&times;</span>
                <h2 class="text-3xl font-bold text-gray-800 mb-4">Cắt Ảnh Cảnh</h2>
                <div id="cropper-container" class="mb-6 rounded-lg overflow-hidden border border-gray-300 shadow-inner"><img id="modalCropImage" src="" alt="Image to crop"></div>
                <div class="flex flex-wrap gap-3 mb-6">
                    <button id="crop-aspect-1-1" class="bg-gray-200 hover:bg-gray-300 text-gray-700 font-semibold py-2 px-4 rounded-lg text-sm shadow-sm">1:1 (Vuông)</button>
                    <button id="crop-aspect-2-3" class="bg-gray-200 hover:bg-gray-300 text-gray-700 font-semibold py-2 px-4 rounded-lg text-sm shadow-sm">2:3 (Dọc)</button>
                    <button id="crop-aspect-3-4" class="bg-gray-200 hover:bg-gray-300 text-gray-700 font-semibold py-2 px-4 rounded-lg text-sm shadow-sm">3:4 (Dọc)</button>
                    <button id="crop-aspect-free" class="bg-blue-100 hover:bg-blue-200 text-blue-800 font-semibold py-2 px-4 rounded-lg text-sm shadow-sm">Tự do</button>
                </div>
                <button id="confirm-crop-btn" class="w-full bg-green-600 hover:bg-green-700 text-white font-bold py-3 px-4 rounded-lg transition duration-300 shadow-lg transform hover:scale-105">Xác nhận Cắt</button>
            </div>
        </div>

        <div id="assignItemsModal" class="modal">
            <div class="modal-content bg-white rounded-xl shadow-2xl w-full max-w-3xl p-6 relative">
                <span id="cancel-assign-items-btn" class="close-btn text-gray-800 hover:text-red-600" style="top: 15px; right: 25px; font-size: 30px;">&times;</span>
                <h2 class="text-2xl font-bold text-gray-800 mb-4">Gán Vật dụng & Phụ kiện</h2>
                <p class="text-gray-600 mb-4 text-sm">AI đã tìm thấy các vật dụng sau. Vui lòng chọn nhân vật sở hữu chúng.</p>
                <div class="grid grid-cols-1 md:grid-cols-5 gap-6">
                    <div class="md:col-span-2">
                        <h3 class="text-sm font-semibold text-gray-500 mb-2">Ảnh Gốc:</h3>
                        <img id="assign-items-preview-img" class="w-full rounded border" src="" alt="Original Image">
                    </div>
                    <div class="md:col-span-3 space-y-3 max-h-[60vh] overflow-y-auto pr-2" id="found-items-list-container">
                        <p class="text-center text-gray-500 italic mt-10">Đang tải danh sách...</p>
                    </div>
                </div>
                <div class="mt-6 flex justify-end gap-3">
                    <button id="close-assign-items-btn" class="bg-gray-500 hover:bg-gray-600 text-white font-bold py-2 px-4 rounded-lg">Hủy</button>
                    <button id="confirm-assign-items-btn" class="bg-blue-600 hover:bg-blue-700 text-white font-bold py-2 px-6 rounded-lg shadow-lg">Lưu vào Kho đồ</button>
                </div>
            </div>
        </div>

        <div id="itemSelectionModal" class="modal">
            <div class="modal-content bg-white rounded-xl shadow-2xl w-full max-w-4xl p-6 relative">
                <span id="cancel-item-select-btn" class="close-btn text-gray-800 hover:text-red-600" style="top: 15px; right: 25px; font-size: 30px;">&times;</span>
                <h2 class="text-3xl font-bold text-gray-800 mb-4">Chọn Vật dụng để Trích xuất</h2>
                <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                    <div>
                        <h3 class="text-xl font-semibold text-gray-700 mb-2">Ảnh Gốc</h3>
                        <img id="item-selection-preview-img" src="" alt="Image to select items from" class="rounded-lg border-4 border-gray-300 w-full shadow-md">
                    </div>
                    <div>
                        <h3 class="text-xl font-semibold text-gray-700 mb-2">Vật dụng được phát hiện:</h3>
                        <div id="item-selection-list" class="space-y-3 max-h-80 overflow-y-auto p-4 bg-gray-50 rounded-lg border border-dashed">
                            <p class="text-gray-500 italic">Đang phân tích...</p>
                        </div>
                    </div>
                </div>
                <div id="item-extraction-loading" class="mt-6 hidden text-center p-4 bg-blue-50 rounded-lg">
                    <div class="animate-spin inline-block w-10 h-10 border-4 border-t-4 border-blue-600 border-gray-200 rounded-full"></div>
                    <p class="mt-3 text-lg font-medium text-blue-700" id="item-extraction-message">Đang trích xuất vật dụng...</p>
                </div>
                <button id="confirm-item-select-btn" class="w-full bg-green-600 hover:bg-green-700 text-white font-bold py-3 px-4 rounded-lg transition duration-300 shadow-lg mt-6 transform hover:scale-105">Xác nhận & Trích xuất</button>
            </div>
        </div>

        <div id="addCharacterModal" class="modal">
            <div class="modal-content bg-white rounded-xl shadow-2xl w-full max-w-lg p-6 relative">
                <span id="cancel-add-char-btn" class="close-btn text-gray-800 hover:text-red-600" style="top: 15px; right: 25px; font-size: 30px;">&times;</span>
                <h2 class="text-3xl font-bold text-gray-800 mb-4">Thêm Nhân vật Mới</h2>
                <div class="space-y-4">
                    <div>
                        <label for="new-char-name" class="block text-base font-semibold text-gray-700">Tên Nhân vật (Bắt buộc):</label>
                        <input type="text" id="new-char-name" class="w-full p-3 border border-gray-300 rounded-lg mt-1 shadow-inner" placeholder="Ví dụ: Peter, Người Ngoài Hành Tinh...">
                    </div>
                    <div>
                        <label for="new-char-desc" class="block text-base font-semibold text-gray-700">Mô tả Nhân vật (Bắt buộc):</label>
                        <textarea id="new-char-desc" rows="3" class="w-full p-3 border border-gray-300 rounded-lg mt-1 shadow-inner" placeholder="Mô tả chi tiết ngoại hình, quần áo, đặc điểm..."></textarea>
                    </div>
                </div>
                <button id="confirm-add-char-btn" class="w-full bg-green-600 hover:bg-green-700 text-white font-bold py-3 px-4 rounded-lg transition duration-300 shadow-lg mt-6 transform hover:scale-105">Lưu Nhân vật</button>
            </div>
        </div>
        
        <div id="associationModal" class="modal">
            <div class="modal-content bg-white rounded-xl shadow-2xl w-full max-w-sm p-6 relative">
                <span id="cancel-association-btn-x" class="close-btn text-gray-800 hover:text-red-600" style="top: 15px; right: 25px; font-size: 30px;">&times;</span>
                <h2 class="text-2xl font-bold text-gray-800 mb-4">Gán ảnh Tham Chiếu Nhân Vật</h2>
                <p class="text-gray-600 mb-4">Ảnh tham chiếu đã được trích xuất. Chọn nhân vật bạn muốn gán ảnh này:</p>
                <div id="association-target-container" class="space-y-3 max-h-60 overflow-y-auto p-3 bg-gray-50 rounded-lg border">
                    <p class="text-sm text-gray-500 italic">Vui lòng tạo nhân vật trước (Bước 2).</p>
                </div>
                <div id="association-loading" class="mt-4 hidden text-center text-blue-600">Đang gán và lưu ảnh tham chiếu...</div>
                <button id="cancel-association-btn" class="w-full bg-gray-500 hover:bg-gray-600 text-white font-bold py-3 px-4 rounded-lg transition duration-300 shadow-lg mt-6">Hủy bỏ</button>
            </div>
        </div>

        <div id="message-toast" class="fixed bottom-6 right-6 bg-gray-800 text-white py-3 px-6 rounded-full shadow-2xl transition-all duration-300 transform scale-0 opacity-0 font-medium z-[3000]">Tin nhắn</div>
    </div>
    <script type="module">
        let storyPages = [];
        let imageLibrary = [];
        const inputImages = new Map();
        let pageCounter = 0;
        let tempNewPage = null; 
        let tempSettingContexts = []; 
        let tempContinuationData = null; 
        const NARRATOR_NAME = 'Dẫn Truyện'; 
        let isFinalReviewMode = false; 
        let storyContext = {
            characters: new Map(), 
            settings: [], 
            allBackgroundsPlain: false,
            extractedTexts: [],
            keyProducts: [],
        };
        const FALLBACK_GRIDS = {
            1: { cols: 1, rows: 1 },
            2: { cols: 2, rows: 1 },
            3: { cols: 3, rows: 1 },
            4: { cols: 2, rows: 2 }
        };
        const storyboardEl = document.getElementById('storyboard');
        const creationPanelEl = document.getElementById('creation-panel');
        const generateBtn = document.getElementById('generate-btn');
        const loadingIndicatorEl = document.getElementById('loading-indicator');
        const loadingMessageEl = document.getElementById('loading-message');
        const addPromptBtn = document.getElementById('add-prompt-btn');
        const promptsContainerEl = document.getElementById('prompts-container');
        const styleSelectEl = document.getElementById('style-select');
        const aspectRatioSelectEl = document.getElementById('aspect-ratio-select');
        const borderStyleSelectEl = document.getElementById('border-style-select');
        const libraryContainerEl = document.getElementById('image-library-container');
        const fullScreenModal = document.getElementById('fullScreenModal');
        const modalImage = document.getElementById('modalImage');
        const closeBtn = document.querySelector('.close-btn');
        const imageUploadInput = document.getElementById('image-upload-input');
        const imageUploadInputIntro = document.getElementById('image-upload-input-intro');
        const introCard = document.getElementById('intro-card');
        const contextInfoContainerEl = document.getElementById('context-info-container');
        const inputImageContainerEl = document.getElementById('input-image-container');
        const promptSectionEl = document.getElementById('prompt-section');
        const confirmSelectionBtn = document.getElementById('confirm-selection-btn');
        const messageToast = document.getElementById('message-toast');
        const generateAllScenesBtn = document.getElementById('generate-all-scenes-btn');
        const generateSequentialScenesBtn = document.getElementById('generate-sequential-scenes-btn');
        const continueAllScenesBtn = document.getElementById('continue-all-scenes-btn');
        const continueSequentialScenesBtn = document.getElementById('continue-sequential-scenes-btn');
        const storyIdeaInput = document.getElementById('story-idea-input'); 
        const storyIdeaInputPanel = document.getElementById('story-idea-input-panel'); 
        const generateStoryFromIdeaBtn = document.getElementById('generate-story-from-idea-btn'); 
        const generateStoryFromIdeaPanelBtn = document.getElementById('generate-story-from-idea-panel-btn'); 
        const genreSelectEl = document.getElementById('genre-select'); 
        const sceneCountSelectEl = document.getElementById('scene-count-select'); 
        const charSetupPanel = document.getElementById('character-setup-panel');
        const charNamingInputs = document.getElementById('character-naming-inputs');
        const finalizeCharsBtn = document.getElementById('finalize-characters-btn');
        const skipNamingBtn = document.getElementById('skip-naming-btn'); 
        const backToImageSelectBtn = document.getElementById('back-to-image-select-btn');
        const dialogueEditPanel = document.getElementById('dialogue-editing-panel');
        const interactiveDialogueArea = document.getElementById('interactive-dialogue-area');
        const dialogueInputsContainer = document.getElementById('dialogue-inputs-container');
        const finalizeAILayoutBtn = document.getElementById('finalize-ai-layout-btn'); 
        const useFallbackLayoutBtn = document.getElementById('use-fallback-layout-btn');
        const captureFinalPageBtn = document.getElementById('capture-final-page-btn'); 
        const dialogueLoadingIndicator = document.getElementById('dialogue-loading-indicator');
        const dialogueLoadingMessageEl = document.getElementById('dialogue-loading-message'); 
        const addGenericDialogueBtn = document.getElementById('add-generic-dialogue-btn');
        const fontSelectEl = document.getElementById('font-select');
        const dialoguePanelTitle = document.getElementById('dialogue-panel-title');
        const dialogueInstruction = document.getElementById('dialogue-instruction');
        const editingPageIdInput = document.getElementById('editing-page-id'); 
        const aiLayoutStyleSelectEl = document.getElementById('ai-layout-style-select');
        const allCharactersPoolEl = document.getElementById('all-characters-pool');
        const sceneCharactersListEl = document.getElementById('scene-characters-list');
        const sceneItemsPoolEl = document.getElementById('scene-items-pool');
        let activeDraggableItem = null;
        let dialogueIdCounter = 0; 
        let activeResizer = null; 
        let initialResizeInfo = {};
        let isSequentialMode = false;
        let activeChars = new Set(); 
        let cropper = null;
        let currentCropTargetGroup = null;
        const cropperModal = document.getElementById('cropperModal');
        const modalCropImage = document.getElementById('modalCropImage');
        const confirmCropBtn = document.getElementById('confirm-crop-btn');
        const cancelCropBtn = document.getElementById('cancel-crop-btn');
        const addCharacterModal = document.getElementById('addCharacterModal');
        const showAddCharModalBtn = document.getElementById('show-add-char-modal-btn');
        const newCharNameInput = document.getElementById('new-char-name');
        const newCharDescInput = document.getElementById('new-char-desc');
        const associationModal = document.getElementById('associationModal');
        const associationTargetContainer = document.getElementById('association-target-container');
        const associationLoading = document.getElementById('association-loading');
        const assignItemsModal = document.getElementById('assignItemsModal');
        const assignItemsPreviewImg = document.getElementById('assign-items-preview-img');
        const foundItemsListContainer = document.getElementById('found-items-list-container');
        const closeAssignItemsBtn = document.getElementById('close-assign-items-btn');
        const cancelAssignItemsBtn = document.getElementById('cancel-assign-items-btn');
        const confirmAssignItemsBtn = document.getElementById('confirm-assign-items-btn');
        const DEFAULT_FONT_SIZE_PX = 20; 
        const REFERENCE_CAPTURE_WIDTH_PX = 1000; 
        const DEFAULT_DIALOGUE_SIZE = { width: 30, height: 18 }; 
        const TEXT_MODEL = 'gemini-2.5-flash-preview-09-2025';
        const IMAGE_MODEL = 'gemini-2.5-flash-image-preview';
        const cinematicShotDirective = `Analyze the scene's primary content (Dialogue, Action, or Setting) and the content/shot of the IMMEDIATE PRECEDING SCENE. You MUST select the single most visually impactful cinematic shot type that creates VISUAL CONTRAST and maintains a professional cinematic flow. Rules: 1. If previous shot was Close-up/Extreme Close-up, new shot should be Medium Shot, Wide Shot, or Dynamic Action Shot. 2. If previous shot was Wide Shot/Aerial/Flycam, new shot should be Close-up, Extreme Close-up, or POV/First-Person. 3. Choose from: Extreme Close-up, Close-up, Medium Shot, Wide Shot, Aerial/Flycam, Low-Angle, High-Angle, or POV/First-Person. 4. Integrate the selected shot type into the prompt for maximum visual impact.`;
        window.autoResizeTextarea = (textarea) => { textarea.style.height = 'auto'; textarea.style.height = textarea.scrollHeight + 'px'; };
        window.autoResizeBox = (wrapperEl) => {
            const textarea = wrapperEl.querySelector('textarea');
            if (textarea) { textarea.style.height = '100%'; textarea.style.width = '100%'; }
            const parentRect = interactiveDialogueArea.getBoundingClientRect();
            const wrapperRect = wrapperEl.getBoundingClientRect();
            wrapperEl.dataset.widthPercent = ((wrapperRect.width / parentRect.width) * 100).toFixed(2);
            wrapperEl.dataset.heightPercent = ((wrapperRect.height / parentRect.height) * 100).toFixed(2);
        }
        function registerDragAndResizeListeners(wrapper) {
            wrapper.addEventListener('mousedown', dragStart);
            wrapper.addEventListener('touchstart', dragStart, { passive: false });
            wrapper.querySelectorAll('.resize-handle').forEach(handle => {
                handle.addEventListener('mousedown', resizeStart);
                handle.addEventListener('touchstart', resizeStart, { passive: false });
            });
        }
        function unregisterDragAndResizeListeners(wrapper) {
            wrapper.removeEventListener('mousedown', dragStart);
            wrapper.removeEventListener('touchstart', dragStart);
            wrapper.querySelectorAll('.resize-handle').forEach(handle => {
                handle.removeEventListener('mousedown', resizeStart);
                handle.removeEventListener('touchstart', resizeStart);
            });
        }
        async function readFilesAsBase64(fileList) {
            const promises = Array.from(fileList).map(file => {
                return new Promise((r, j) => {
                    const reader = new FileReader();
                    reader.onload = () => r(reader.result.split(',')[1]);
                    reader.onerror = (e) => j(e);
                    reader.readAsDataURL(file);
                });
            });
            return Promise.all(promises);
        }
        function renderImageLibrary() {
            libraryContainerEl.innerHTML = '';
            if (imageLibrary.length === 0) {
                libraryContainerEl.innerHTML = '<p class="text-center text-gray-400 col-span-2">Thư viện trống.</p>';
                document.getElementById('download-excel-btn').classList.add('hidden');
                return;
            }
            document.getElementById('download-excel-btn').classList.remove('hidden');
            imageLibrary.forEach((item, index) => {
                const div = document.createElement('div');
                div.className = 'relative group rounded-lg overflow-hidden border-2 border-gray-300 shadow-md cursor-pointer';
                div.innerHTML = `<img src="data:image/png;base64,${item.base64}" class="w-full h-auto object-cover library-image-preview" alt="Library Image ${index+1}"><div class="absolute top-2 left-2 flex flex-col gap-1 opacity-0 group-hover:opacity-100 transition-opacity duration-200"><button class="bg-green-500 text-white rounded-full p-1.5 make-input-btn shadow-lg" title="Làm ảnh đầu vào"><svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4v16m8-8H4" /></svg></button><button class="bg-blue-500 text-white rounded-full p-1.5 assign-scene-btn shadow-lg" title="Gán vào Cảnh" data-index="${index}"><svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 5l7 7-7 7M5 5l7 7-7 7" /></svg></button><button class="bg-indigo-500 text-white rounded-full p-1.5 download-lib-btn shadow-lg" title="Tải xuống" data-index="${index}"><svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4" /></svg></button></div><button class="absolute top-2 right-2 bg-red-500 text-white rounded-full p-1.5 opacity-0 group-hover:opacity-100 transition-opacity duration-200 remove-library-image shadow-lg" data-index="${index}" title="Xóa"><svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12" /></svg></button><div class="absolute inset-x-0 bottom-0 bg-black bg-opacity-50 text-white p-1 text-xs text-center opacity-0 group-hover:opacity-100 transition-opacity duration-200">${item.prompts.vi[0].substring(0, 30)}...</div>`;
                div.querySelector('.remove-library-image').addEventListener('click', (e) => { e.stopPropagation(); imageLibrary.splice(parseInt(e.currentTarget.dataset.index), 1); renderImageLibrary(); displayToast('Đã xóa ảnh khỏi thư viện.'); });
                div.querySelector('.make-input-btn').addEventListener('click', (e) => { e.stopPropagation(); const base64Data = item.base64; const id = `input-img-lib-${Date.now()}-${index}`; inputImages.set(id, base64Data); renderInputImage(base64Data, id); updateInputImageContainer(); displayToast('Đã thêm ảnh từ thư viện vào mục Ảnh Đầu Vào.'); });
                div.querySelector('.download-lib-btn').addEventListener('click', (e) => { e.stopPropagation(); const link = document.createElement('a'); link.href = `data:image/png;base64,${item.base64}`; link.download = `library_image_${index + 1}.png`; link.click(); displayToast('Đang tải xuống ảnh từ thư viện...'); });
                div.querySelector('.assign-scene-btn').addEventListener('click', (e) => { e.stopPropagation(); const groups = document.querySelectorAll('.prompt-input-group'); if (groups.length === 0) { displayToast('Chưa có cảnh nào để gán.', 'bg-yellow-500'); return; } const sceneNum = prompt(`Nhập số thứ tự cảnh (1 - ${groups.length}):`); if (sceneNum === null) return; const sceneIndex = parseInt(sceneNum) - 1; if (!isNaN(sceneIndex) && sceneIndex >= 0 && sceneIndex < groups.length) { const group = groups[sceneIndex]; const base64Data = item.base64; group.dataset.panelImageBase64 = base64Data; const previewContainer = group.querySelector('.image-preview-container'); previewContainer.innerHTML = `<img src="data:image/png;base64,${base64Data}" alt="Xem trước cảnh đã gán" class="rounded-md shadow-md">`; previewContainer.classList.remove('hidden'); group.querySelector('.save-panel-to-lib-btn')?.classList.remove('hidden'); group.querySelector('.crop-panel-image-btn')?.classList.remove('hidden'); group.querySelector('.generate-variant-btn')?.classList.remove('hidden'); displayToast(`Đã gán ảnh thư viện vào Cảnh ${sceneNum}!`); } else { displayToast('Số thứ tự cảnh không hợp lệ.', 'bg-red-500'); } });
                div.querySelector('.library-image-preview').addEventListener('click', (e) => { modalImage.src = e.target.src; fullScreenModal.style.display = 'flex'; });
                libraryContainerEl.appendChild(div);
            });
        }
        fullScreenModal.addEventListener('click', (e) => { if (e.target === fullScreenModal || e.target.classList.contains('close-btn')) { fullScreenModal.style.display = 'none'; modalImage.src = ''; } });
        function renderAllCharactersPool() {
            allCharactersPoolEl.innerHTML = '';
            if (storyContext.characters.size === 0) { allCharactersPoolEl.innerHTML = '<p class="text-sm text-gray-500">Chưa có nhân vật được đặt tên.</p>'; sceneCharactersListEl.innerHTML = '<p id="scene-char-placeholder" class="text-sm text-gray-500 italic">Chọn nhân vật từ danh sách bên dưới.</p>'; return; }
            storyContext.characters.forEach((charData, name) => {
                const isSelected = activeChars.has(name);
                const charChip = document.createElement('div');
                charChip.className = `cursor-pointer char-pool-chip flex items-center p-2 rounded-lg text-sm font-medium transition duration-200 shadow-md ${isSelected ? 'bg-blue-600 text-white hover:bg-blue-700' : 'bg-gray-200 text-gray-800 hover:bg-gray-300'}`;
                charChip.dataset.charName = name;
                const refImages = charData.items.filter(i => i.vi_name === 'Ảnh Tham Chiếu');
                if (refImages.length > 0) {
                    charChip.innerHTML = `<div class="flex items-center gap-3"><div class="char-ref-chip w-16 h-16" title="Xem ảnh gốc"><img src="data:image/png;base64,${refImages[0].base64}" alt="Ref" class="full-view-trigger"></div><span class="font-bold text-lg">${name}</span></div>`;
                    setTimeout(() => { const img = charChip.querySelector('.full-view-trigger'); if(img) { img.addEventListener('click', (e) => { e.stopPropagation(); modalImage.src = e.target.src; fullScreenModal.style.display = 'flex'; }); } }, 0);
                } else { charChip.innerHTML = `${name} <span class="ml-2 text-xs opacity-75">(${charData.items.length} vật dụng)</span>`; }
                charChip.addEventListener('click', (e) => { if (!e.target.classList.contains('full-view-trigger')) { if (activeChars.has(name)) { activeChars.delete(name); } else { activeChars.add(name); } renderAllCharactersPool(); renderActiveCharacterList(); renderActiveItemsPool(); } });
                allCharactersPoolEl.appendChild(charChip);
            });
            renderActiveCharacterList();
        }
        function renderActiveCharacterList() {
            sceneCharactersListEl.innerHTML = '';
            if (activeChars.size === 0) { sceneCharactersListEl.innerHTML = '<p id="scene-char-placeholder" class="text-sm text-gray-500 italic">Chọn nhân vật từ danh sách bên trên để thêm vào cảnh.</p>'; return; }
            activeChars.forEach(name => {
                const charData = storyContext.characters.get(name);
                const refImage = charData.items.find(i => i.vi_name === 'Ảnh Tham Chiếu');
                const charChip = document.createElement('div');
                charChip.className = 'flex items-center p-2 rounded-full text-sm font-medium bg-blue-100 text-blue-800 border border-blue-300';
                let innerHtml = name;
                if (refImage) { innerHtml = `${name} <div class="char-ref-chip ml-2 w-8 h-8 border-none shadow-none" title="Ảnh Tham Chiếu"><img src="data:image/png;base64,${refImage.base64}" alt="Ref"></div>`; }
                charChip.innerHTML = innerHtml;
                sceneCharactersListEl.appendChild(charChip);
            });
        }
        function renderActiveItemsPool() {
            sceneItemsPoolEl.innerHTML = '';
            const allItems = new Map();
            activeChars.forEach(charName => {
                const charData = storyContext.characters.get(charName);
                if (charData && charData.items) { charData.items.filter(i => i.vi_name !== 'Ảnh Tham Chiếu').forEach((item, index) => { const uniqueId = `${charName}-${index}-${Date.now()}`; allItems.set(uniqueId, { ...item, charName }); }); }
            });
            if (allItems.size === 0) { sceneItemsPoolEl.innerHTML = '<p id="scene-items-placeholder" class="text-sm text-gray-500 italic">Nhân vật đang hoạt động không có vật dụng nào.</p>'; return; }
            allItems.forEach((item, uniqueId) => {
                const itemId = `scene-item-${uniqueId}`;
                const checkbox = document.createElement('input'); checkbox.type = 'checkbox'; checkbox.id = itemId; checkbox.className = 'h-4 w-4 text-purple-600 border-gray-300 rounded focus:ring-purple-500 scene-item-check flex-shrink-0 mt-0.5';
                checkbox.dataset.itemDesc = item.en_desc; checkbox.dataset.itemBase64 = item.base64; checkbox.checked = true;
                const label = document.createElement('label'); label.htmlFor = itemId; label.className = 'ml-2 block text-sm font-medium text-gray-700 cursor-pointer flex-grow';
                label.innerHTML = `${item.vi_name} <span class="text-xs text-gray-500">(${item.charName})</span>`;
                const chip = document.createElement('div'); chip.className = 'flex items-start p-2 bg-white rounded-lg border border-purple-200 shadow-sm transition hover:bg-purple-50';
                chip.appendChild(checkbox); chip.appendChild(label);
                sceneItemsPoolEl.appendChild(chip);
            });
        }
        async function callGeminiImageAPI(prompt, imageParts = [], generationConfig = {}, model = TEXT_MODEL) {
            let result = null; let finalModel = model;
            if (generationConfig.responseModalities && generationConfig.responseModalities.includes("IMAGE")) finalModel = IMAGE_MODEL;
            for (let i = 0; i < 3; i++) {
                try {
                    const payload = { contents: [{ parts: [{ text: prompt }, ...imageParts] }], generationConfig: generationConfig };
                    const apiUrl = `https://generativelanguage.googleapis.com/v1beta/models/${finalModel}:generateContent?key=`;
                    const response = await fetch(apiUrl, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(payload) });
                    if (response.ok) { result = await response.json(); break; }
                    if (response.status === 429 && i < 2) { await new Promise(r => setTimeout(r, Math.pow(2, i) * 1000)); continue; }
                    throw new Error(`HTTP Error: ${response.status}`);
                } catch (error) { console.error(`Lỗi API (${finalModel}) attempt ${i + 1}:`, error); }
            }
            return result;
        }
        function base64ToArrayBuffer(base64) {
            const binaryString = atob(base64); const len = binaryString.length; const bytes = new Uint8Array(len);
            for (let i = 0; i < len; i++) { bytes[i] = binaryString.charCodeAt(i); }
            return bytes.buffer;
        }
        function pcmToWav(pcmData, sampleRate) {
            const numChannels = 1; const bytesPerSample = 2;
            const buffer = new ArrayBuffer(44 + pcmData.length * bytesPerSample);
            const view = new DataView(buffer);
            writeString(view, 0, 'RIFF'); view.setUint32(4, 36 + pcmData.length * bytesPerSample, true); writeString(view, 8, 'WAVE');
            writeString(view, 12, 'fmt '); view.setUint32(16, 16, true); view.setUint16(20, 1, true); view.setUint16(22, numChannels, true); view.setUint32(24, sampleRate, true); view.setUint32(28, sampleRate * numChannels * bytesPerSample, true); view.setUint16(32, numChannels * bytesPerSample, true); view.setUint16(34, 16, true);
            writeString(view, 36, 'data'); view.setUint32(40, pcmData.length * bytesPerSample, true);
            let offset = 44;
            for (let i = 0; i < pcmData.length; i++) { view.setInt16(offset, pcmData[i], true); offset += bytesPerSample; }
            return new Blob([view], { type: 'audio/wav' });
        }
        function writeString(view, offset, string) { for (let i = 0; i < string.length; i++) { view.setUint8(offset + i, string.charCodeAt(i)); } }
        async function callGeminiTtsAPI(text, voiceName = 'Kore', rate = 24000) {
            const payload = { contents: [{ parts: [{ text: text }] }], generationConfig: { responseModalities: ["AUDIO"], speechConfig: { voiceConfig: { prebuiltVoiceConfig: { voiceName: voiceName } }, audioConfig: { sampleRateHertz: rate } } }, model: "gemini-2.5-flash-preview-tts" };
            const apiUrl = `https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-preview-tts:generateContent?key=`;
            const response = await fetch(apiUrl, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(payload) });
            const result = await response.json();
            const part = result?.candidates?.[0]?.content?.parts?.[0];
            const audioData = part?.inlineData?.data; const mimeType = part?.inlineData?.mimeType;
            if (audioData && mimeType && mimeType.startsWith("audio/L16")) {
                const pcmData = base64ToArrayBuffer(audioData); const pcm16 = new Int16Array(pcmData); const rateMatch = mimeType.match(/rate=(\d+)/); const sampleRate = rateMatch ? parseInt(rateMatch[1], 10) : 24000;
                return URL.createObjectURL(pcmToWav(pcm16, sampleRate));
            } else { console.error("TTS API error:", mimeType); throw new Error("TTS API Error: Could not generate audio."); }
        }
        window.generateAndPlayTts = async (button) => {
            const inputGroup = button.closest('.flex-col'); const textarea = inputGroup.querySelector('textarea'); const text = textarea.value.trim();
            if (!text) { displayToast('Vui lòng nhập lời thoại trước.', 'bg-red-500'); return; }
            const originalText = button.innerHTML; button.disabled = true; button.innerHTML = '<div class="animate-spin w-4 h-4 border-2 border-t-2 border-white rounded-full"></div>';
            try {
                const audioUrl = await callGeminiTtsAPI(text, 'Kore'); const audio = new Audio(audioUrl); audio.play();
                audio.onended = () => { button.disabled = false; button.innerHTML = originalText; URL.revokeObjectURL(audioUrl); };
                audio.onerror = () => { button.disabled = false; button.innerHTML = originalText; displayToast('Lỗi phát âm thanh.', 'bg-red-500'); URL.revokeObjectURL(audioUrl); };
            } catch (error) { console.error('TTS Error:', error); displayToast('Lỗi tạo Audio.', 'bg-red-700'); button.disabled = false; button.innerHTML = originalText; }
        };
        async function identifyMultipleItems(base64Data) {
            const itemPrompt = `Analyze this image. Identify all distinct, significant items, objects, or accessories. Return a JSON array of objects with "vi_name": A short, clear name in Vietnamese, and "en_desc": A short, English description for image generation. If no items, return empty array.`;
            const result = await callGeminiImageAPI(itemPrompt, [{ inlineData: { mimeType: "image/png", data: base64Data } }], { responseMimeType: "application/json", responseSchema: { type: "ARRAY", items: { type: "OBJECT", properties: { "vi_name": { "type": "STRING" }, "en_desc": { "type": "STRING" } } } } }, TEXT_MODEL);
            const jsonText = result?.candidates?.[0]?.content?.parts?.[0]?.text;
            return jsonText ? JSON.parse(jsonText) : [];
        }
        async function extractSpecificItem(base64Data, item_en_desc) {
            const prompt = `From the provided image, find and extract ONLY the item described as: "${item_en_desc}". Isolation: The item MUST be fully isolated from the original background. Background: Place the isolated item on a completely plain, solid white background. Removal: You MUST remove all other elements. Return ONLY the new image.`;
            const result = await callGeminiImageAPI(prompt, [{ inlineData: { mimeType: "image/png", data: base64Data } }], { responseModalities: ["IMAGE"] }, IMAGE_MODEL);
            return result?.candidates?.[0]?.content?.parts?.find(p => p.inlineData)?.inlineData?.data || null;
        }
        function goBackToCreationPanel() {
            creationPanelEl.classList.remove('hidden'); dialogueEditPanel.classList.add('hidden'); charSetupPanel.classList.add('hidden'); storyboardEl.classList.remove('lg:col-span-1');
            editingPageIdInput.value = '';
        }
        backToImageSelectBtn.addEventListener('click', () => {
            charSetupPanel.classList.add('hidden'); creationPanelEl.classList.add('hidden'); dialogueEditPanel.classList.add('hidden'); storyboardEl.classList.remove('lg:col-span-1'); introCard.classList.remove('hidden'); displayToast('Đã quay lại màn hình Bắt đầu (Bước 1).', 'bg-gray-500');
        });
        document.getElementById('back-from-dialogue-btn').addEventListener('click', () => {
            if (isFinalReviewMode) { startDialogueEditing(tempNewPage); displayToast('Đã quay lại chế độ Chỉnh sửa Thô.', 'bg-yellow-600'); }
            else { goBackToCreationPanel(); displayToast('Đã quay lại Bước 3: Tạo Lời Nhắc.', 'bg-gray-500'); }
        });
        async function detectAndRenderSubjects(base64Data, imageDiv) {
            const detectionArea = imageDiv.querySelector('.detected-chars-area');
            const detectBtn = imageDiv.querySelector('.detect-chars-btn');
            if (detectionArea.dataset.isProcessed === 'true') {
                detectionArea.classList.toggle('active');
                if(detectionArea.style.display === 'none') { detectionArea.style.display = 'block'; }
                else {
                    detectionArea.innerHTML = '';
                    detectionArea.dataset.isProcessed = 'false';
                    detectionArea.innerHTML = `<button class="detect-chars-btn bg-yellow-500 hover:bg-yellow-600 text-white text-xs font-semibold py-1.5 px-2 rounded-lg transition shadow-md col-span-1">Nhận diện Nhân vật</button><button class="detect-items-btn bg-purple-500 hover:bg-purple-600 text-white text-xs font-semibold py-1.5 px-2 rounded-lg transition shadow-md col-span-1">Quét Vật dụng (Mới)</button>`;
                    imageDiv.querySelector('.detect-chars-btn').addEventListener('click', (e) => detectAndRenderSubjects(base64Data, imageDiv));
                    imageDiv.querySelector('.detect-items-btn').addEventListener('click', (e) => detectAndAssignItems(base64Data, imageDiv));
                }
                return;
            }
            detectBtn.disabled = true; detectBtn.textContent = 'Đang nhận diện...';
            detectionArea.innerHTML = '<div class="text-center p-2"><div class="animate-spin inline-block w-5 h-5 border-2 border-t-2 border-blue-600 border-gray-200 rounded-full"></div><p class="mt-1 text-sm text-blue-600">Đang nhận diện nhân vật...</p></div>';
            const subjectPrompt = `Analyze this image in detail. Identify all main characters and significant accessories. Return a JSON array of objects. For each detected person/character, provide: "vi_name": A simple name in Vietnamese, and "en_desc": A concise English design description for extraction. Return an empty array if no clear characters are present.`;
            const result = await callGeminiImageAPI(subjectPrompt, [{ inlineData: { mimeType: "image/png", data: base64Data } }], { responseMimeType: "application/json", responseSchema: { type: "ARRAY", items: { type: "OBJECT", properties: { "vi_name": { "type": "STRING" }, "en_desc": { "type": "STRING" } } } } }, TEXT_MODEL);
            let subjects = [];
            try { const jsonText = result?.candidates?.[0]?.content?.parts?.[0]?.text; subjects = jsonText ? JSON.parse(jsonText) : []; } catch (e) { console.error("Lỗi phân tích JSON nhân vật:", e); }
            detectionArea.dataset.isProcessed = 'true';
            detectionArea.innerHTML = '';
            detectionArea.classList.add('p-2', 'bg-white', 'rounded-lg', 'border', 'border-yellow-300', 'shadow-inner');
            const header = document.createElement('div');
            header.className = 'flex justify-between items-center mb-2 pb-2 border-b';
            header.innerHTML = `<p class="text-sm font-semibold text-gray-700">Nhân vật được tìm thấy:</p><button class="close-detection-btn text-gray-400 hover:text-red-500 text-xs font-bold px-2 py-1 rounded hover:bg-red-50 transition">Đóng (Quay lại)</button>`;
            header.querySelector('.close-detection-btn').addEventListener('click', () => {
                detectionArea.dataset.isProcessed = 'false'; detectionArea.innerHTML = ''; detectionArea.classList.remove('p-2', 'bg-white', 'rounded-lg', 'border', 'border-yellow-300', 'shadow-inner');
                detectionArea.innerHTML = `<button class="detect-chars-btn bg-yellow-500 hover:bg-yellow-600 text-white text-xs font-semibold py-1.5 px-2 rounded-lg transition shadow-md col-span-1">Nhận diện Nhân vật</button><button class="detect-items-btn bg-purple-500 hover:bg-purple-600 text-white text-xs font-semibold py-1.5 px-2 rounded-lg transition shadow-md col-span-1">Quét Vật dụng (Mới)</button>`;
                detectionArea.querySelector('.detect-chars-btn').addEventListener('click', () => detectAndRenderSubjects(base64Data, imageDiv));
                detectionArea.querySelector('.detect-items-btn').addEventListener('click', () => detectAndAssignItems(base64Data, imageDiv));
            });
            detectionArea.appendChild(header);
            if (subjects.length === 0 || !Array.isArray(subjects)) {
                const noResult = document.createElement('p'); noResult.className = 'text-sm text-red-600 font-semibold'; noResult.textContent = 'Không tìm thấy nhân vật rõ ràng. Thử ảnh khác hoặc thêm thủ công.'; detectionArea.appendChild(noResult);
            } else {
                const listContainer = document.createElement('div'); listContainer.className = 'space-y-2';
                subjects.forEach(subject => {
                    const subjectDiv = document.createElement('div');
                    subjectDiv.className = 'flex justify-between items-center p-2 bg-yellow-100 rounded-md border border-yellow-300';
                    subjectDiv.innerHTML = `<span class="text-sm text-yellow-800 font-medium">${subject.vi_name}</span><button class="extract-and-associate-btn bg-purple-600 hover:bg-purple-700 text-white text-xs font-semibold py-1 px-3 rounded-full transition shadow-md" data-vi-name="${subject.vi_name}" data-en-desc="${subject.en_desc}">Trích xuất & Gán</button>`;
                    listContainer.appendChild(subjectDiv);
                });
                detectionArea.appendChild(listContainer);
                detectionArea.querySelectorAll('.extract-and-associate-btn').forEach(btn => {
                    btn.addEventListener('click', (e) => extractAndAssociateCharacter(e.currentTarget, base64Data, e.currentTarget.dataset.viName, e.currentTarget.dataset.enDesc));
                });
            }
        }
        async function extractAndAssociateCharacter(button, base64Data, vi_name, en_desc) {
            if (storyContext.characters.size === 0) { displayToast('Vui lòng tạo ít nhất một nhân vật (Bước 2) trước khi gán ảnh tham chiếu.', 'bg-red-500'); return; }
            const originalText = button.textContent; button.textContent = 'Đang trích xuất...'; button.disabled = true;
            const prompt = `From the provided image, find and extract ONLY the character described as: "${en_desc}". Appearance: Preserve their outfit, facial features, and physical characteristics for continuity. Pose: Change the character's pose to a neutral, standing, straight-facing, full-body reference pose (like a character sheet), removing dynamic actions. Style: Render the character in a detailed, realistic style (keeping their original features) or high-fidelity isolation to be used as a clear reference. Background: Place the isolated character on a completely plain, solid white background. Return ONLY the new image (PNG format).`;
            const result = await callGeminiImageAPI(prompt, [{ inlineData: { mimeType: "image/png", data: base64Data } }], { responseModalities: ["IMAGE"] }, IMAGE_MODEL);
            try {
                const newBase64Data = result?.candidates?.[0]?.content?.parts?.find(p => p.inlineData)?.inlineData?.data;
                if (newBase64Data) { showAssociationModal(newBase64Data, vi_name); }
                else { throw new Error("AI did not return a valid extracted image."); }
            } catch (error) { console.error("Lỗi khi trích xuất nhân vật:", error); displayToast('Lỗi khi trích xuất nhân vật. Vui lòng thử lại.', 'bg-red-500'); }
            finally { button.textContent = originalText; button.disabled = false; }
        }
        function showAssociationModal(extractedBase64, detectedViName) {
            associationModal.style.display = 'flex'; associationLoading.classList.add('hidden'); associationTargetContainer.innerHTML = '';
            const charNames = Array.from(storyContext.characters.keys());
            if (charNames.length === 0) { associationTargetContainer.innerHTML = '<p class="text-sm text-red-500 italic">Chưa có nhân vật nào. Vui lòng tạo nhân vật mới (Bước 2) trước khi gán.</p>'; return; }
            charNames.forEach(name => {
                const charData = storyContext.characters.get(name); const refCount = charData.items.filter(i => i.vi_name === 'Ảnh Tham Chiếu').length;
                const button = document.createElement('button'); button.className = 'w-full text-left p-3 bg-white hover:bg-indigo-100 text-gray-800 rounded-lg border border-indigo-300 shadow-sm transition flex justify-between items-center';
                button.innerHTML = `<span>${name}</span><span class="text-xs font-semibold px-2 py-1 rounded-full ${refCount > 0 ? 'bg-orange-500 text-white' : 'bg-gray-200 text-gray-600'}">${refCount > 0 ? 'Ghi đè ảnh cũ' : 'Chưa có ảnh'}</span>`;
                button.onclick = () => associateReferenceImage(name, extractedBase64, detectedViName, button);
                associationTargetContainer.appendChild(button);
            });
        }
        document.getElementById('cancel-association-btn').onclick = () => { associationModal.style.display = 'none'; };
        document.getElementById('cancel-association-btn-x').onclick = () => { associationModal.style.display = 'none'; };
        function associateReferenceImage(charName, extractedBase64, detectedViName, button) {
            const charData = storyContext.characters.get(charName);
            if (!charData) { displayToast(`Lỗi: Không tìm thấy nhân vật ${charName}.`, 'bg-red-500'); return; }
            charData.items = charData.items.filter(i => i.vi_name !== 'Ảnh Tham Chiếu');
            charData.items.push({ vi_name: 'Ảnh Tham Chiếu', en_desc: `reference image for ${detectedViName}`, base64: extractedBase64 });
            associationModal.style.display = 'none';
            displayToast(`Đã gán thành công ảnh tham chiếu MỚI cho "${charName}"! (Ảnh cũ đã bị ghi đè)`);
            renderAllCharactersPool(); renderActiveCharacterList(); renderContextInfo();
        }
        async function translateSinglePrompt(vietnamesePrompt) {
            if (!vietnamesePrompt) return "";
            const translationPrompt = `Translate the following Vietnamese comic book scene description into a concise, clear English equivalent for an image generation AI. Do not add any explanatory text, just return the translated phrase.\n\nVietnamese: "${vietnamesePrompt}"\n\nEnglish:`;
            const result = await callGeminiImageAPI(translationPrompt, [], {}, TEXT_MODEL);
            const englishText = result?.candidates?.[0]?.content?.parts?.[0]?.text;
            return englishText ? englishText.trim().replace(/"/g, '') : vietnamesePrompt;
        }
        async function generateDialogueFromPrompt(vietnamesePrompt, charName, charactersInScene) {
            if (!vietnamesePrompt) return "";
            const dialoguePrompt = `Bạn là một nhà biên kịch truyện tranh ngắn gọn. Dựa trên mô tả cảnh và nhân vật nói, hãy viết MỘT dòng thoại ngắn (bằng tiếng Việt) phù hợp với cảnh. Quy tắc: Lời thoại phải RẤT ngắn (tối đa 15 từ) và bao gồm dấu câu. Chỉ trả về văn bản lời thoại.\n- Bối cảnh: "${vietnamesePrompt}"\n- Người nói: "${charName}"`;
            const result = await callGeminiImageAPI(dialoguePrompt, [], {}, TEXT_MODEL);
            const dialogueText = result?.candidates?.[0]?.content?.parts?.[0]?.text;
            return dialogueText ? dialogueText.trim().replace(/"/g, '') : '...';
        }
        async function generateProductFeatureFromPrompt(vietnamesePrompt) {
            if (!vietnamesePrompt) return "";
            const featurePrompt = `Bạn là một AI chuyên trích xuất thông tin quảng cáo. Phân tích mô tả cảnh sau đây. Nhiệm vụ: Tìm và trích xuất MỘT tính năng, thông số kỹ thuật, hoặc điểm bán hàng nổi bật nhất của sản phẩm được mô tả. Quy tắc: Trả về MỘT cụm từ hoặc câu ngắn gọn (tối đa 15 từ) mô tả tính năng đó. Chỉ trả về văn bản thô.`;
            const result = await callGeminiImageAPI(featurePrompt, [], {}, TEXT_MODEL);
            const featureText = result?.candidates?.[0]?.content?.parts?.[0]?.text;
            return featureText ? featureText.trim().replace(/"/g, '') : '...';
        }
        async function generateSinglePanelImage(button) {
            const group = button.closest('.prompt-input-group');
            const textarea = group.querySelector('textarea');
            const previewContainer = group.querySelector('.image-preview-container');
            let panelPromptVi = textarea.value.trim();
            let panelPromptEn = textarea.dataset.english || panelPromptVi;
            const originalVi = textarea.dataset.originalVi || '';
            if (panelPromptVi !== originalVi) {
                const originalButtonText = button.textContent; button.textContent = 'Đang dịch...'; button.disabled = true;
                try { const newEnglishPrompt = await translateSinglePrompt(panelPromptVi); if (newEnglishPrompt) { panelPromptEn = newEnglishPrompt; textarea.dataset.english = newEnglishPrompt; textarea.dataset.originalVi = panelPromptVi; } }
                catch (e) { console.error("Translation failed:", e); displayToast('Lỗi dịch lời nhắc. Sẽ thử dùng tiếng Việt.', 'bg-red-500'); }
                button.textContent = originalButtonText; button.disabled = false;
            }
            if (!panelPromptVi) { displayToast('Vui lòng nhập lời nhắc cho cảnh này.', 'bg-red-500'); return; }
            if (!panelPromptEn || panelPromptEn === panelPromptVi) {
                if (inputImages.size === 0) { displayToast('Cảnh báo: Không có ảnh tham chiếu và dịch thất bại. Sử dụng lời nhắc tiếng Việt.', 'bg-yellow-500'); panelPromptEn = panelPromptVi; }
                else { try { panelPromptEn = await translateSinglePrompt(panelPromptVi); if (!panelPromptEn) panelPromptEn = panelPromptVi; } catch (e) { panelPromptEn = panelPromptVi; } }
            }
            button.disabled = true; loadingIndicatorEl.classList.remove('hidden');
            previewContainer.innerHTML = `<div class="animate-spin inline-block w-6 h-6 border-4 border-t-4 border-blue-500 border-gray-200 rounded-full"></div><p class="ml-2 text-sm text-gray-500">Đang tạo ảnh...</p>`;
            previewContainer.classList.remove('hidden');
            const styleValue = styleSelectEl.value;
            let stylePrefix = "", exclusionDirective = "";
            switch (styleValue) {
                case "comic_book_style": stylePrefix = "dynamic American comic book style, bold lines, flat colors, action-oriented, professional quality, "; break;
                case "anime_style": stylePrefix = "high quality anime key frame, sharp focus, vibrant colors, expressive character design, clean line art, "; break;
                case "watercolor_style": stylePrefix = "detailed watercolor painting, soft edges, visible brushstrokes, natural color palette, high resolution, "; exclusionDirective = "STRICTLY AVOID ANY TRACE OF PHOTOREALISM OR CINEMATIC LIGHTING. "; break;
                case "photorealistic_style": stylePrefix = "ultra photorealistic, hyper-detailed, 8k photograph, sharp focus, cinematic lighting, realistic textures, "; exclusionDirective = "THE IMAGE MUST STRICTLY AVOID ANY TRACE OF CARTOON, COMIC BOOK, OR ANIME STYLING, CELL SHADING, OR FLAT COLORING. "; break;
                case "cinematic_style": stylePrefix = "epic cinematic movie still, 4k, shallow depth of field, high contrast lighting, anamorphic lens, film grain, "; exclusionDirective = "THE IMAGE MUST STRICTLY AVOID ANY TRACE OF CARTOON, COMIC BOOK, OR ANIME STYLING, CELL SHADING, OR FLAT COLORING. "; break;
                case "dark_fantasy_style": stylePrefix = "dark fantasy hyper-detailed illustration, gloomy atmosphere, strong shadows, high contrast, grim texture, volumetric lighting, "; exclusionDirective = "THE IMAGE MUST STRICTLY AVOID ANY TRACE OF CARTOON, COMIC BOOK, OR ANIME STYLING, CELL SHADING, OR FLAT COLORING. "; break;
                case "mythological_style": stylePrefix = "epic mythological illustration, inspired by classical sculpture, dramatic god rays, polished texture, grand scale, fantasy lighting, "; exclusionDirective = "THE IMAGE MUST STRICTLY AVOID ANY TRACE OF CARTOON, COMIC BOOK, OR ANIME STYLING, CELL SHADING, OR FLAT COLORING. "; break;
                default: stylePrefix = "high-quality, vivid, visually consistent comic panel art, "; break;
            }
            const aspectRatio = aspectRatioSelectEl.value;
            const speakersString = group.dataset.selectedSpeakers || '';
            const selectedSpeakers = speakersString.split(',').filter(name => name.trim().length > 0);
            const selectedCharactersForScene = [];
            storyContext.characters.forEach((charData, name) => { if (selectedSpeakers.includes(name)) { selectedCharactersForScene.push(`${name}, ${charData.description}`); } });
            const detailedCharsPrompt = selectedCharactersForScene.length > 0 ? `The panel MUST feature ONLY the following characters with consistent appearance: ${selectedCharactersForScene.join('; ')}.` : "The scene does not feature the main characters or only requires generic characters.";
            const allKnownCharacters = Array.from(storyContext.characters.keys()).filter(name => !selectedSpeakers.includes(name));
            const negativeCharInstruction = allKnownCharacters.length > 0 ? `STRICTLY FORBIDDEN to include characters: ${allKnownCharacters.join(', ')}.` : "";
            const imageParts = [];
            let referenceHint = "";
            const allGroups = Array.from(promptsContainerEl.querySelectorAll('.prompt-input-group'));
            const panelIndex = allGroups.indexOf(group);
            if (inputImages.size > 0) { inputImages.forEach(base64 => { imageParts.push({ inlineData: { mimeType: "image/png", data: base64 } }); }); }
            if (panelIndex > 0) {
                const previousGroup = allGroups[panelIndex - 1];
                const refImageBase64 = previousGroup.dataset.panelImageBase64;
                if (refImageBase64) { imageParts.push({ inlineData: { mimeType: "image/png", data: refImageBase64 } }); referenceHint = "Use the provided images for main style/context. Use the LAST image (from the previous panel) for sequential continuity. Create the next scene based on the text prompt. CRITICAL: Ensure the shot type and composition are dramatically different from the last image to maintain visual flow."; }
            } else {
                if (inputImages.size === 0 && storyContext.characters.size === 0 && !storyIdeaInputPanel.value.trim()) { displayToast('Không có ảnh, nhân vật, hoặc ý tưởng cốt truyện. Vui lòng cung cấp ít nhất một.', 'bg-red-500'); button.disabled = false; previewContainer.innerHTML = `<p class="text-yellow-600 text-xs p-2">Cần ảnh, nhân vật hoặc ý tưởng.</p>`; previewContainer.classList.remove('hidden'); return; }
                referenceHint = inputImages.size > 0 ? "Use the provided image(s) as the initial style and context reference for the first panel." : "There are no reference images. Rely strictly on the character descriptions and prompt text to generate the scene.";
            }
            const selectedItems = [];
            document.querySelectorAll('.scene-item-check:checked').forEach(checkbox => { const itemDesc = checkbox.dataset.itemDesc; const itemBase64 = checkbox.dataset.itemBase64; selectedItems.push(itemDesc); if (itemBase64 && itemBase64 !== "undefined") { imageParts.push({ inlineData: { mimeType: "image/png", data: itemBase64 } }); } });
            storyContext.characters.forEach(charData => { charData.items.filter(i => i.vi_name === 'Ảnh Tham Chiếu').forEach(refImage => { imageParts.push({ inlineData: { mimeType: "image/png", data: refImage.base64 } }); }); });
            const detailedItemsPrompt = selectedItems.length > 0 ? `The scene must also explicitly include: ${selectedItems.join(', ')}.` : "";
            const negativeInstruction = `Absolutely NO speech bubbles, text, captions, word balloons, or any form of lettering or dialogue in the image. ${negativeCharInstruction}`;
            const imageBackgroundInstruction = inputImages.size > 0 ? "The scene must prioritize character consistency, pose, and action. CRITICAL: If reference images are provided, STRICTLY IGNORE AND REPLACE their background and setting with the one described in the prompt to avoid mixing contexts." : "";
            loadingMessageEl.textContent = 'Đang tạo cảnh truyện tranh...';
            const prompt = `Create a single, high-resolution, full-bleed comic panel scene. The resulting image must strictly adhere to the ${aspectRatio} aspect ratio. ${referenceHint} ${imageBackgroundInstruction} STYLE OVERRIDE: ${exclusionDirective} STARTING PROMPT: ${stylePrefix} ${detailedCharsPrompt} ${detailedItemsPrompt} ${negativeInstruction} The scene is: ${panelPromptEn}`;
            const result = await callGeminiImageAPI(prompt, imageParts, { responseModalities: ["IMAGE"] }, IMAGE_MODEL);
            try {
                const base64Data = result?.candidates?.[0]?.content?.parts?.find(p => p.inlineData)?.inlineData?.data;
                if (base64Data) {
                    group.dataset.panelImageBase64 = base64Data;
                    previewContainer.innerHTML = `<img src="data:image/png;base64,${base64Data}" alt="Xem trước cảnh" class="rounded-md shadow-md">`;
                    button.textContent = 'Tạo lại Ảnh';
                    group.querySelector('.save-panel-to-lib-btn')?.classList.remove('hidden');
                    group.querySelector('.crop-panel-image-btn')?.classList.remove('hidden');
                    group.querySelector('.generate-variant-btn')?.classList.remove('hidden');
                    loadingMessageEl.textContent = 'Tạo ảnh hoàn tất.';
                } else { console.error("AI did not return a valid image.", result); throw new Error("AI did not return a valid image."); }
            } catch (error) { console.error("Lỗi khi tạo ảnh cho cảnh:", error); previewContainer.innerHTML = `<p class="text-red-500 text-xs p-2">Lỗi tạo ảnh. Vui lòng thử lại: ${error.message}</p>`; loadingMessageEl.textContent = 'Lỗi tạo ảnh. Vui lòng thử lại.'; }
            finally { button.disabled = false; loadingIndicatorEl.classList.add('hidden'); }
        }
        generateBtn.addEventListener('click', async () => {
            const allGroups = promptsContainerEl.querySelectorAll('.prompt-input-group');
            if (allGroups.length === 0) { displayToast('Vui lòng thêm ít nhất một cảnh!', 'bg-red-500'); return; }
            const panelImages = []; const promptsVi = []; const promptsEn = []; const speakersPerPanel = []; let allPanelsReady = true;
            allGroups.forEach(group => {
                const base64 = group.dataset.panelImageBase64; const textarea = group.querySelector('textarea');
                const promptVi = textarea.value.trim(); const promptEn = textarea.dataset.english || promptVi;
                const speakers = (group.dataset.selectedSpeakers || '').split(',').filter(name => name.trim().length > 0);
                if (!base64) { allPanelsReady = false; }
                panelImages.push(base64); promptsVi.push(promptVi); promptsEn.push(promptEn); speakersPerPanel.push(speakers);
            });
            if (!allPanelsReady) { displayToast('Vui lòng tạo ảnh cho TẤT CẢ các cảnh trước khi tạo trang nháp!', 'bg-red-500'); return; }
            const panelCount = panelImages.length;
            generateBtn.disabled = true; loadingIndicatorEl.classList.remove('hidden');
            loadingMessageEl.textContent = '1/2: Đang kết hợp các cảnh thành bố cục lưới dự phòng...';
            const aspectRatio = aspectRatioSelectEl.value; const borderStyle = borderStyleSelectEl.value;
            const autoFillDialogue = document.getElementById('auto-fill-dialogue-check').checked;
            const autoFillProductFeatures = document.getElementById('auto-fill-product-features-check').checked;
            try {
                const fallbackBase64 = await generateFallbackGrid(panelImages, { settings: { aspectRatio, borderStyle } });
                if (!fallbackBase64) { throw new Error("Lỗi khi tạo lưới dự phòng."); }
                tempNewPage = {
                    prompts: { vi: promptsVi, en: promptsEn }, panelImages: panelImages,
                    base64_composed_no_bubbles: fallbackBase64, settings: { aspectRatio, borderStyle },
                    speakersPerPanel: speakersPerPanel, dialogue: { fullText: [] },
                    autoFillDialogue: autoFillDialogue, autoFillProductFeatures: autoFillProductFeatures,
                    fontValue: fontSelectEl.value, base64_ai_layout_no_bubbles: null, base64_ai_layout_empty_text: null
                };
                loadingMessageEl.textContent = '2/2: Đang chuyển sang Chỉnh sửa Lời thoại...';
                await startDialogueEditing(tempNewPage);
            } catch (error) { console.error("Lỗi khi tạo trang nháp:", error); displayToast(`Lỗi tạo trang nháp: ${error.message}`, 'bg-red-700'); }
            finally { generateBtn.disabled = false; loadingIndicatorEl.classList.add('hidden'); }
        });
        function addPromptInput(initialPrompts = null) {
            if (promptsContainerEl.childElementCount >= 4) { if (isSequentialMode) { promptsContainerEl.querySelectorAll('.generate-next-scene-btn:not(:disabled)').forEach(btn => { btn.disabled = true; btn.classList.add('hidden'); }); } return; }
            const pIdx = promptsContainerEl.childElementCount;
            const div = document.createElement('div');
            div.className = 'prompt-input-group flex items-start gap-3 mb-4 p-4 bg-gray-50 rounded-xl border border-gray-200 shadow-sm';
            const initialSpeakers = Array.from(activeChars).join(','); div.dataset.selectedSpeakers = initialSpeakers;
            div.innerHTML = `<div class="flex-grow"><label class="block text-base font-semibold text-gray-800 mb-1">Cảnh ${pIdx + 1}:</label><textarea rows="1" placeholder="Lời nhắc cho cảnh ${pIdx + 1}" class="w-full p-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 transition duration-200 prompt-textarea shadow-inner" oninput="autoResizeTextarea(this)" required></textarea><input type="file" class="hidden upload-panel-image-input" accept="image/*"><div class="image-preview-container mt-3 hidden p-2 border border-dashed border-gray-300 rounded-lg"><p class="text-sm text-gray-400">Xem trước ảnh sẽ hiện ở đây</p></div><div class="prompt-actions mt-3 flex flex-wrap gap-2"><button type="button" class="generate-panel-image-btn bg-blue-600 hover:bg-blue-700 text-white text-xs font-semibold py-1.5 px-3 rounded-lg transition duration-200 shadow-md">Tạo Ảnh</button><button type="button" class="upload-panel-image-btn bg-green-600 hover:bg-green-700 text-white text-xs font-semibold py-1.5 px-3 rounded-lg transition duration-200 shadow-md">Tải lên</button><button type="button" class="crop-panel-image-btn bg-yellow-500 hover:bg-yellow-600 text-white text-xs font-semibold py-1.5 px-3 rounded-lg transition duration-200 shadow-md hidden">Cắt ảnh</button><button type="button" class="save-panel-to-lib-btn bg-purple-500 hover:bg-purple-600 text-white text-xs font-semibold py-1.5 px-3 rounded-lg transition duration-200 shadow-md hidden">Lưu</button><button type="button" class="generate-variant-btn bg-cyan-500 hover:bg-cyan-600 text-white text-xs font-semibold py-1.5 px-3 rounded-lg transition duration-200 shadow-md hidden">Tạo Biến Thể & Lưu</button><button type="button" class="download-panel-image-btn bg-teal-500 hover:bg-teal-600 text-white text-xs font-semibold py-1.5 px-3 rounded-lg transition duration-200 shadow-md">Tải ảnh</button><button type="button" class="regenerate-scene-btn bg-gray-500 hover:bg-gray-600 text-white text-xs font-semibold py-1.5 px-3 rounded-lg transition duration-200 shadow-md">Tạo lại Gợi ý</button>${isSequentialMode ? `<button type="button" class="generate-next-scene-btn bg-orange-500 hover:bg-orange-600 text-white text-xs font-semibold py-1.5 px-3 rounded-lg transition duration-200 shadow-md">Tạo Cảnh Tiếp</button>` : ''}</div><div class="mt-4 pt-3 border-t border-gray-300 speaker-select-area"><label class="block text-sm font-semibold text-gray-700 mb-2">Chọn Nhân vật thoại:</label><div class="flex flex-wrap gap-x-3 gap-y-1" data-scene-index="${pIdx}"></div></div></div><button type="button" class="remove-prompt-btn bg-red-500 hover:bg-red-600 text-white p-2.5 rounded-full leading-none transition duration-200 shadow-md" title="Xóa"><svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12" /></svg></button>`;
            promptsContainerEl.appendChild(div);
            div.querySelector('.remove-prompt-btn').addEventListener('click', () => { promptsContainerEl.removeChild(div); });
            div.querySelector('.generate-panel-image-btn').addEventListener('click', (e) => generateSinglePanelImage(e.target));
            div.querySelector('.crop-panel-image-btn').addEventListener('click', (e) => { const group = e.target.closest('.prompt-input-group'); window.openCropper(group); });
            div.querySelector('.generate-variant-btn').addEventListener('click', (e) => { window.generateVariantAndSave(e.target); });
            div.querySelector('.download-panel-image-btn').addEventListener('click', (e) => { const group = e.target.closest('.prompt-input-group'); const base64Data = group.dataset.panelImageBase64; if (base64Data) { const link = document.createElement('a'); link.href = `data:image/png;base64,${base64Data}`; link.download = `scene_image_${pIdx + 1}.png`; link.click(); displayToast('Đang tải xuống ảnh cảnh...'); } else { displayToast('Không có ảnh để tải xuống.', 'bg-red-500'); } });
            div.querySelector('.save-panel-to-lib-btn').addEventListener('click', (e) => { const group = e.target.closest('.prompt-input-group'); const base64Data = group.dataset.panelImageBase64; if (base64Data) { const textarea = group.querySelector('textarea'); const item = { base64: base64Data, prompts: { en: [textarea.dataset.english || textarea.value], vi: [textarea.value] } }; imageLibrary.push(item); renderImageLibrary(); displayToast('Đã lưu ảnh cảnh vào Thư viện!'); } else { displayToast('Không có ảnh để lưu.', 'bg-red-500'); } });
            const uploadBtn = div.querySelector('.upload-panel-image-btn');
            const uploadInput = div.querySelector('.upload-panel-image-input');
            uploadBtn.addEventListener('click', () => uploadInput.click());
            uploadInput.addEventListener('change', (e) => {
                const file = e.target.files[0]; if (file) {
                    const reader = new FileReader(); reader.onload = (event) => {
                        const base64Data = event.target.result.split(',')[1]; const group = div;
                        const previewContainer = group.querySelector('.image-preview-container');
                        group.dataset.panelImageBase64 = base64Data; previewContainer.innerHTML = `<img src="data:image/png;base64,${base64Data}" alt="Xem trước cảnh đã tải lên" class="rounded-md shadow-md">`; previewContainer.classList.remove('hidden');
                        group.querySelector('.save-panel-to-lib-btn')?.classList.remove('hidden'); group.querySelector('.crop-panel-image-btn')?.classList.remove('hidden'); group.querySelector('.generate-variant-btn')?.classList.remove('hidden'); displayToast('Đã tải lên ảnh thay thế cho cảnh.');
                    }; reader.readAsDataURL(file);
                } e.target.value = null;
            });
            div.querySelector('.regenerate-scene-btn').addEventListener('click', async (e) => {
                const currentGroup = e.target.closest('.prompt-input-group'); const currentTextarea = currentGroup.querySelector('textarea');
                const currentIndex = Array.from(promptsContainerEl.children).indexOf(currentGroup);
                const originalButtonText = e.target.textContent; e.target.disabled = true; e.target.textContent = 'Đang tạo lại...';
                loadingIndicatorEl.classList.remove('hidden'); loadingMessageEl.textContent = 'Đang yêu cầu AI tạo lại gợi ý cảnh...';
                let previousSceneData = null; let generationType = 'new';
                if (currentIndex > 0) { const previousGroup = promptsContainerEl.querySelectorAll('.prompt-input-group')[currentIndex - 1]; previousSceneData = { prompt: previousGroup.querySelector('textarea').value, imageBase64: previousGroup.dataset.panelImageBase64 }; generationType = 'continue'; }
                else if (storyPages.length > 0) { const lastPage = storyPages[storyPages.length - 1]; previousSceneData = { prompt: lastPage.prompts.vi.slice(-1)[0] || '', imageBase64: lastPage.panelImages?.slice(-1)[0] || null, }; generationType = 'continue'; }
                else { generationType = 'new'; }
                const generatedPrompts = await generateNextScenePrompt(previousSceneData, generationType);
                if (generatedPrompts && generatedPrompts.vi) { currentTextarea.value = generatedPrompts.vi; currentTextarea.dataset.english = generatedPrompts.en; currentTextarea.dataset.originalVi = generatedPrompts.vi; window.autoResizeTextarea(currentTextarea); displayToast('Đã tạo lại gợi ý cảnh thành công!'); }
                else { displayToast('Không thể tạo lại gợi ý. Vui lòng thử lại.', 'bg-red-500'); }
                loadingIndicatorEl.classList.add('hidden'); e.target.textContent = originalButtonText; e.target.disabled = false;
            });
            if (initialPrompts) { const textarea = div.querySelector('textarea'); textarea.value = initialPrompts.vi; textarea.dataset.english = initialPrompts.en; textarea.dataset.originalVi = initialPrompts.vi; setTimeout(() => autoResizeTextarea(textarea), 0); } else { autoResizeTextarea(div.querySelector('textarea')); }
            const nextSceneBtn = div.querySelector('.generate-next-scene-btn');
            if (nextSceneBtn) {
                promptsContainerEl.querySelectorAll('.generate-next-scene-btn').forEach((btn, index) => { if (index < promptsContainerEl.childElementCount - 1) { btn.disabled = true; btn.classList.add('hidden'); } });
                nextSceneBtn.addEventListener('click', async (e) => {
                    const currentGroup = e.target.closest('.prompt-input-group'); const currentTextarea = currentGroup.querySelector('textarea');
                    const currentPromptVi = currentTextarea.value; const currentImageBase64 = currentGroup.dataset.panelImageBase64;
                    if (!currentPromptVi) { displayToast('Vui lòng nhập lời nhắc cho cảnh hiện tại trước.', 'bg-red-500'); return; }
                    nextSceneBtn.disabled = true; nextSceneBtn.textContent = 'Đang tạo...';
                    const previousSceneData = { prompt: currentPromptVi, imageBase64: currentImageBase64 };
                    const generatedPrompts = await generateNextScenePrompt(previousSceneData, 'continue');
                    if (generatedPrompts) { nextSceneBtn.disabled = true; nextSceneBtn.classList.add('hidden'); addPromptInput(generatedPrompts); }
                    else { displayToast('Không thể tạo gợi ý. Vui lòng thử lại.', 'bg-red-500'); nextSceneBtn.disabled = false; nextSceneBtn.textContent = 'Tạo Cảnh Tiếp'; }
                });
            }
            renderCharacterSelectorsInPrompts(div.querySelector('.speaker-select-area div'));
        }
        function renderCharacterSelectorsInPrompts(containerEl) {
            if (!containerEl) { promptsContainerEl.querySelectorAll('.speaker-select-area div').forEach(renderCharacterSelectorsInPrompts); return; }
            const sceneIndex = parseInt(containerEl.dataset.sceneIndex, 10);
            const parentGroup = containerEl.closest('.prompt-input-group');
            const currentSpeakers = (parentGroup.dataset.selectedSpeakers || '').split(',').filter(name => name.trim().length > 0);
            containerEl.innerHTML = '';
            if (storyContext.characters.size === 0) { containerEl.innerHTML = '<p class="text-xs text-gray-500 italic">Chưa có nhân vật.</p>'; return; }
            storyContext.characters.forEach((charData, name) => {
                const isSelected = currentSpeakers.includes(name);
                const charChip = document.createElement('span');
                charChip.className = `cursor-pointer text-xs font-semibold py-1 px-2 rounded-full transition duration-150 shadow-sm ${isSelected ? 'bg-indigo-600 text-white hover:bg-indigo-700' : 'bg-gray-200 text-gray-800 hover:bg-gray-300'}`;
                charChip.textContent = name; charChip.dataset.charName = name; charChip.dataset.sceneIndex = sceneIndex;
                charChip.addEventListener('click', (e) => {
                    const charName = e.target.dataset.charName; const group = e.target.closest('.prompt-input-group');
                    let speakers = (group.dataset.selectedSpeakers || '').split(',').filter(name => name.trim().length > 0);
                    if (speakers.includes(charName)) { speakers = speakers.filter(n => n !== charName); } else { speakers.push(charName); }
                    group.dataset.selectedSpeakers = speakers.join(','); renderCharacterSelectorsInPrompts(e.target.closest('.speaker-select-area div'));
                });
                containerEl.appendChild(charChip);
            });
        }
        window.generateVariantAndSave = async (button) => {
            const group = button.closest('.prompt-input-group'); const originalBase64 = group.dataset.panelImageBase64;
            const textarea = group.querySelector('textarea'); let panelPromptVi = textarea.value.trim(); let panelPromptEn = textarea.dataset.english || panelPromptVi;
            if (!originalBase64) { displayToast('Không có ảnh cảnh để tạo biến thể.', 'bg-red-500'); return; }
            const originalButtonText = button.textContent; button.disabled = true; button.textContent = 'Đang tạo biến thể...';
            loadingIndicatorEl.classList.remove('hidden'); loadingMessageEl.textContent = 'Đang yêu cầu AI tạo biến thể...';
            try {
                const prompt = `Create a visually distinct variant of the provided image. The new image must retain the same characters, key objects, and overall scene setting/theme as the original, but change the composition, camera angle, lighting, or specific action/pose slightly. The new scene must still match the core narrative: "${panelPromptEn}". Output only the single new image.`;
                const result = await callGeminiImageAPI(prompt, [{ inlineData: { mimeType: "image/png", data: originalBase64 } }], { responseModalities: ["IMAGE"] }, IMAGE_MODEL);
                const newBase64 = result?.candidates?.[0]?.content?.parts?.find(p => p.inlineData)?.inlineData?.data;
                if (newBase64) {
                    const item = { base64: newBase64, prompts: { en: [panelPromptEn + " (Variant)"], vi: [panelPromptVi + " (Biến thể)"] } };
                    imageLibrary.push(item); renderImageLibrary(); displayToast('Đã tạo và lưu biến thể ảnh vào Thư viện!', 'bg-green-500');
                    modalImage.src = `data:image/png;base64,${newBase64}`; fullScreenModal.style.display = 'flex';
                } else { throw new Error("AI did not return a valid variant image."); }
            } catch (error) { console.error("Lỗi khi tạo biến thể:", error); displayToast(`Lỗi tạo biến thể: ${error.message}`, 'bg-red-700'); }
            finally { button.textContent = originalButtonText; button.disabled = false; loadingIndicatorEl.classList.add('hidden'); }
        }
        window.openCropper = (group) => {
            const base64Data = group.dataset.panelImageBase64;
            if (!base64Data) { displayToast('Không có ảnh để cắt.', 'bg-red-500'); return; }
            currentCropTargetGroup = group;
            modalCropImage.src = `data:image/png;base64,${base64Data}`;
            cropperModal.style.display = 'flex';
            if (cropper) { cropper.destroy(); }
            setTimeout(() => { cropper = new Cropper(modalCropImage, { aspectRatio: NaN, viewMode: 1, autoCropArea: 0.9, responsive: true, background: false, }); }, 50);
        }
        function closeCropper() { if (cropper) { cropper.destroy(); cropper = null; } cropperModal.style.display = 'none'; }
        document.getElementById('crop-aspect-1-1').addEventListener('click', () => { if(cropper) cropper.setAspectRatio(1 / 1); });
        document.getElementById('crop-aspect-2-3').addEventListener('click', () => { if(cropper) cropper.setAspectRatio(2 / 3); });
        document.getElementById('crop-aspect-3-4').addEventListener('click', () => { if(cropper) cropper.setAspectRatio(3 / 4); });
        document.getElementById('crop-aspect-free').addEventListener('click', () => { if(cropper) cropper.setAspectRatio(NaN); });
        confirmCropBtn.addEventListener('click', () => {
            if (!cropper || !currentCropTargetGroup) return;
            const croppedCanvas = cropper.getCroppedCanvas({ imageSmoothingQuality: 'high' });
            if (!croppedCanvas) { displayToast('Không thể cắt ảnh.', 'bg-red-500'); return; }
            const newBase64 = croppedCanvas.toDataURL('image/png').split(',')[1];
            currentCropTargetGroup.dataset.panelImageBase64 = newBase64;
            const previewContainer = currentCropTargetGroup.querySelector('.image-preview-container');
            previewContainer.innerHTML = `<img src="data:image/png;base64,${newBase64}" alt="Xem trước cảnh đã cắt" class="rounded-md shadow-md">`;
            displayToast('Đã cắt và cập nhật ảnh cảnh.'); closeCropper();
        });
        cancelCropBtn.addEventListener('click', closeCropper);
        showAddCharModalBtn.addEventListener('click', () => { newCharNameInput.value = ''; newCharDescInput.value = ''; addCharacterModal.style.display = 'flex'; });
        document.getElementById('cancel-add-char-btn').addEventListener('click', () => { addCharacterModal.style.display = 'none'; });
        document.getElementById('confirm-add-char-btn').addEventListener('click', async () => {
            const name = newCharNameInput.value.trim(); const desc = newCharDescInput.value.trim();
            if (!name || !desc) { displayToast('Tên và Mô tả nhân vật là bắt buộc!', 'bg-red-500'); return; }
            if (storyContext.characters.has(name)) { displayToast('Tên nhân vật đã tồn tại. Vui lòng chọn tên khác.', 'bg-red-500'); return; }
            storyContext.characters.set(name, { description: desc, items: [] });
            activeChars.add(name); addCharacterModal.style.display = 'none';
            displayToast(`Đã thêm nhân vật "${name}"!`); renderAllCharactersPool(); renderActiveCharacterList(); renderActiveItemsPool(); renderContextInfo(); renderCharacterSelectorsInPrompts();
        });
        document.getElementById('cancel-association-btn').onclick = () => { associationModal.style.display = 'none'; };
        document.getElementById('cancel-association-btn-x').onclick = () => { associationModal.style.display = 'none'; };
        async function extractContextFromImage(base64Data) {
            const contextPrompt = `Analyze this image with high precision. Characters: For each main character, provide a strictly physical description including appearance and significant items. Infer 'gender' and 'age_category'. Setting: Describe the overall background/setting. Plain Background: Return 'true' for 'isPlainBackground' if the background is plain. Extracted Text: Read ALL visible text. Key Products: Identify key products or significant objects in the setting. Return a JSON object with 'characters' (array of objects), 'setting' (string), 'isPlainBackground' (boolean), 'extracted_text' (string), and 'key_products' (array of strings).`;
            const result = await callGeminiImageAPI(contextPrompt, [{ inlineData: { mimeType: "image/png", data: base64Data } }], { responseMimeType: "application/json", responseSchema: { type: "OBJECT", properties: { "characters": { type: "ARRAY", items: { type: "OBJECT", properties: { "description": { "type": "STRING" }, "gender": { "type": "STRING" }, "age_category": { "type": "STRING" } } } }, "setting": { "type": "STRING" }, "isPlainBackground": { "type": "BOOLEAN" }, "extracted_text": { "type": "STRING" }, "key_products": { type: "ARRAY", items: { "type": "STRING" } } } } }, TEXT_MODEL);
            const jsonText = result?.candidates?.[0]?.content?.parts?.[0]?.text;
            return jsonText ? JSON.parse(jsonText) : { characters: [], setting: '', isPlainBackground: false, extracted_text: '', key_products: [] };
        }
        async function extractCharactersFromIdea(ideaText) {
            const charExtractionPrompt = `Analyze the following story idea in Vietnamese. Identify the main recurring characters and secondary characters. Tasks: 1. Infer a simple, single 'name' (in Vietnamese) for each character. 2. Provide a 'description' (in Vietnamese) of their physical appearance, clothing, and key attributes. 3. Infer their 'gender' (nam/nữ/unknown) and 'age_category' (adult/child/teenager/elderly). Return a JSON array of objects.\nStory Idea: "${ideaText}"`;
            const result = await callGeminiImageAPI(charExtractionPrompt, [], { responseMimeType: "application/json", responseSchema: { type: "ARRAY", items: { type: "OBJECT", properties: { "name": { "type": "STRING" }, "description": { "type": "STRING" }, "gender": { "type": "STRING" }, "age_category": { "type": "STRING" } } } } }, TEXT_MODEL);
            try {
                const rawJsonText = result?.candidates?.[0]?.content?.parts?.[0]?.text;
                if (!rawJsonText) throw new Error("AI did not return any JSON text for character extraction.");
                let jsonText = rawJsonText.trim();
                if (jsonText.startsWith('\\`\\`\\`json')) { jsonText = jsonText.substring(7); if (jsonText.endsWith('\\`\\`\\`')) { jsonText = jsonText.substring(0, jsonText.length - 3).trim(); } }
                else if (jsonText.startsWith('\\`\\`\\`')) { jsonText = jsonText.substring(3); if (jsonText.endsWith('\\`\\`\\`')) { jsonText = jsonText.substring(0, jsonText.length - 3).trim(); } }
                const parsedResult = JSON.parse(jsonText); return Array.isArray(parsedResult) ? parsedResult : [];
            } catch (error) { console.error("Lỗi phân tích JSON nhân vật (Idea-based):", error); return []; }
        }
        async function analyzeComicPageForContinuation(base64Data) {
            const comicAnalysisPrompt = `Analyze this single comic book page. Identify all main characters (including name or description, gender, age_category), briefly describe the overall setting in Vietnamese, provide a 'full_page_summary' (in Vietnamese) describing the entire page's plot, provide 'last_scene_dialogue' (in Vietnamese) from the last panel, infer 'inferred_genre' (Vietnamese value), and infer 'inferred_style' (English value). Return a single JSON object.`;
            const extractLastPanelPrompt = `From the provided comic page, identify and extract only the very last panel as a single, clean image. Do NOT include any surrounding page borders, gutters, or elements from other panels.`;
            let analysisResult = null; let imageResult = null;
            const analysisPromise = callGeminiImageAPI(comicAnalysisPrompt, [{ inlineData: { mimeType: "image/png", data: base64Data } }], { responseMimeType: "application/json", responseSchema: { type: "OBJECT", properties: { "characters": { type: "ARRAY", items: { type: "OBJECT", properties: { "name": { "type": "STRING" }, "description": { "type": "STRING" }, "gender": { "type": "STRING" }, "age_category": { "type": "STRING" } } } }, "setting": { "type": "STRING" }, "full_page_summary": { "type": "STRING" }, "last_scene_dialogue": { "type": "STRING" }, "inferred_genre": { type: "STRING" }, "inferred_style": { "type": "STRING" } } } }, TEXT_MODEL);
            const imagePromise = callGeminiImageAPI(extractLastPanelPrompt, [{ inlineData: { mimeType: "image/png", data: base64Data } }], { responseModalities: ["IMAGE"] }, IMAGE_MODEL);
            const [analysisResponse, imageResponse] = await Promise.all([analysisPromise, imagePromise]);
            analysisResult = analysisResponse; imageResult = imageResponse;
            const jsonText = analysisResult?.candidates?.[0]?.content?.parts?.[0]?.text;
            const lastPanelBase64 = imageResult?.candidates?.[0]?.content?.parts?.find(p => p.inlineData)?.inlineData?.data;
            if (!jsonText || !lastPanelBase64) throw new Error("AI did not return required data.");
            return { analysisData: JSON.parse(jsonText), lastPanelBase64 };
        }
        async function detectSubjectsForPerspective(base64Data) { return []; }
        async function regeneratePrompts(type = 'new') {
            loadingIndicatorEl.classList.remove('hidden');
            loadingMessageEl.textContent = type === 'new' ? 'Đang tạo mới cốt truyện...' : 'Đang tiếp diễn cốt truyện...';
            promptsContainerEl.innerHTML = '';
            try {
                const userIdea = storyIdeaInputPanel.value.trim(); const sceneCount = parseInt(sceneCountSelectEl.value, 10);
                await combineAndGeneratePrompts(type, userIdea, sceneCount);
                displayToast(type === 'new' ? 'Đã tạo gợi ý cốt truyện thành công!' : 'Đã tạo gợi ý tiếp diễn thành công!');
                if (type === 'new') { continueAllScenesBtn.disabled = (storyPages.length > 0) ? false : true; continueSequentialScenesBtn.disabled = (storyPages.length > 0) ? false : true; }
                else if (type === 'continue') { continueAllScenesBtn.disabled = false; continueSequentialScenesBtn.disabled = false; }
            } catch(e) { console.error("Lỗi khi tạo cốt truyện tự động:", e); displayToast('Lỗi khi tạo gợi ý tự động. Vui lòng nhập lời nhắc thủ công.', 'bg-red-700'); promptsContainerEl.innerHTML = ''; addPromptInput(); }
            finally { loadingIndicatorEl.classList.add('hidden'); }
        }
        async function combineAndGeneratePrompts(type = 'new', userIdea = '', sceneCount = 4) {
            const genre = genreSelectEl.value; const genrePrefix = genre ? `Theo thể loại ${genre},` : ''; let lightingPrompt = "";
            switch (genre) {
                case "Hành động": lightingPrompt = "Hãy bao gồm các mô tả về ánh sáng động, tương phản cao. "; break;
                case "Quảng cáo": lightingPrompt = "Hãy bao gồm các mô tả về ánh sáng rõ ràng, sạch sẽ, thương mại. "; break;
                case "Kinh dị": lightingPrompt = "Hãy bao gồm các mô tả về ánh sáng tối, u ám, nhiều bóng sâu, và tương phản sáng tối (chiaroscuro). "; break;
                case "Viễn tưởng": lightingPrompt = "Hãy bao gồm các mô tả về ánh sáng neon, ánh sáng tương lai, và tông màu lạnh. "; break;
                case "Ngôn tình": lightingPrompt = "Hãy bao gồm các mô tả về ánh sáng mềm mại, ấm áp, như giờ vàng. "; break;
                case "Hài hước": lightingPrompt = "Hãy bao gồm các mô tả về ánh sáng rực rỡ, đều, và màu sắc sống động. "; break;
            }
            const MAX_CONTEXT_CHAR_LIMIT = 1500;
            const activeCharDescriptions = [];
            storyContext.characters.forEach((charData, name) => { const simpleDesc = charData.description.substring(0, 100); activeCharDescriptions.push(`${name}, ${simpleDesc}`); });
            let charListForAI = activeCharDescriptions.join('; '); if (charListForAI.length > MAX_CONTEXT_CHAR_LIMIT) { charListForAI = charListForAI.substring(0, MAX_CONTEXT_CHAR_LIMIT) + '... (Ngữ cảnh nhân vật bị cắt ngắn)'; }
            let settingDescription = storyContext.settings.join('. '); if (settingDescription.length > 500) { settingDescription = settingDescription.substring(0, 500) + '... (Ngữ cảnh bối cảnh bị cắt ngắn)'; }
            const imageParts = [];
            const detectedTextForAI = storyContext.extractedTexts ? storyContext.extractedTexts.join('. ') : '';
            const detectedProductsForAI = storyContext.keyProducts ? storyContext.keyProducts.join(', ') : '';
            if (inputImages.size > 0) { inputImages.forEach(base64 => { imageParts.push({ inlineData: { mimeType: "image/png", data: base64 } }); }); }
            storyContext.characters.forEach(charData => { charData.items.filter(i => i.vi_name === 'Ảnh Tham Chiếu').forEach(refImage => { imageParts.push({ inlineData: { mimeType: "image/png", data: refImage.base64 } }); }); });
            if (storyContext.characters.size === 0 && settingDescription === '' && !userIdea) { promptsContainerEl.innerHTML = '<p class="text-red-500">Lỗi: Cần ít nhất một ý tưởng cốt truyện, một nhân vật đã đặt tên HOẶC ảnh đầu vào.</p>'; addPromptInput(); throw new Error("Missing essential context for generation."); }
            const backgroundDirective = inputImages.size > 0 ? "Bối cảnh/background của cảnh truyện tranh phải được tạo dựa trên nội dung lời nhắc cảnh và 'Bối cảnh' đã được cung cấp. QUAN TRỌNG: Nếu có ảnh tham chiếu được cung cấp, PHẢI BỎ QUA bối cảnh cụ thể trong ảnh đó (trừ khi nó được liệt kê trong phần 'Bối cảnh' bên dưới)." : "";
            let basePrompt;
            if (type === 'continue' && storyPages.length > 0) {
                const lastPage = storyPages[storyPages.length - 1];
                const lastPageSummary = `Tóm tắt trang trước: Các cảnh mô tả: "${lastPage.prompts.vi.join('. ')}". Lời thoại chính: "${lastPage.dialogue.fullText.map(d => `${d.charName}: ${d.text}`).join('. ')}"`;
                let referenceImageFound = false;
                if (lastPage.panelImages && lastPage.panelImages.length > 0) { const lastPanelImageBase64 = lastPage.panelImages[lastPage.panelImages.length - 1]; if (lastPanelImageBase64) { imageParts.push({ inlineData: { mimeType: "image/png", data: lastPanelImageBase64 } }); referenceImageFound = true; } }
                basePrompt = `${cinematicShotDirective} Bạn là một người kể chuyện tuần tự. Tiếp tục một câu chuyện truyện tranh dựa trên bản tóm tắt của trang trước. ${referenceImageFound ? "QUAN TRỌNG: Một hình ảnh từ cảnh cuối cùng của trang trước được cung cấp làm tham chiếu. Hãy phân tích nó để đảm bảo tính liên tục của nhân vật và bối cảnh." : ""} ${lastPageSummary} Tạo ${sceneCount} mô tả cảnh tuần tự mới cho trang tiếp theo một cách logic. Xuất ra dưới dạng đối tượng JSON có các khóa "en" và "vi".`;
            } else if (userIdea) {
                basePrompt = `${cinematicShotDirective} Dựa trên ý tưởng cốt truyện sau đây: "${userIdea}", và các nhân vật/bối cảnh được cung cấp, hãy tạo một danh sách gồm ${sceneCount} mô tả cảnh truyện tranh riêng biệt và tuần tự. Đảm bảo tính liên tục chặt chẽ giữa các cảnh. Cung cấp đầu ra dưới dạng một đối tượng JSON có hai khóa: "en" cho mô tả tiếng Anh và "vi" cho các bản dịch tiếng Việt tương ứng.`;
            } else {
                basePrompt = `${cinematicShotDirective} Dựa trên các nhân vật và bối cảnh sau đây, hãy tạo một danh sách gồm ${sceneCount} mô tả cảnh truyện tranh riêng biệt và tuần tự. Đảm bảo tính liên tục chặt chẽ giữa các cảnh. Ngoại hình nhân vật phải nhất quán. Cung cấp đầu ra dưới dạng đối tượng JSON có các khóa "en" và "vi".`;
            }
            basePrompt = backgroundDirective + " " + genrePrefix + lightingPrompt + basePrompt;
            let contextForAI = `\nNhân vật: ${charListForAI}`;
            if (settingDescription) contextForAI += `\nBối cảnh: ${settingDescription}`;
            if (detectedTextForAI) contextForAI += `\nVăn bản phát hiện: ${detectedTextForAI}`;
            if (detectedProductsForAI) contextForAI += `\nSản phẩm/Đối tượng chính: ${detectedProductsForAI}`;
            const finalPrompt = `${basePrompt}${contextForAI}`;
            const result = await callGeminiImageAPI(finalPrompt, imageParts, { responseMimeType: "application/json", responseSchema: { type: "OBJECT", properties: { "en": { type: "ARRAY", items: { "type": "STRING" } }, "vi": { type: "ARRAY", items: { "type": "STRING" } } } } }, TEXT_MODEL);
            try {
                const rawJsonText = result?.candidates?.[0]?.content?.parts?.[0]?.text;
                if (!rawJsonText) throw new Error("AI did not return any JSON text.");
                let jsonText = rawJsonText.trim();
                if (jsonText.startsWith('\\`\\`\\`json')) { jsonText = jsonText.substring(7); if (jsonText.endsWith('\\`\\`\\`')) { jsonText = jsonText.substring(0, jsonText.length - 3).trim(); } }
                else if (jsonText.startsWith('\\`\\`\\`')) { jsonText = jsonText.substring(3); if (jsonText.endsWith('\\`\\`\\`')) { jsonText = jsonText.substring(0, jsonText.length - 3).trim(); } }
                const parsedScenes = JSON.parse(jsonText);
                const parsedEnglishScenes = parsedScenes.en || [];
                const parsedVietnameseScenes = parsedScenes.vi || [];
                if (parsedVietnameseScenes.length === 0 || parsedVietnameseScenes.length !== parsedEnglishScenes.length) { throw new Error("AI returned JSON but the scene arrays are invalid or empty."); }
                promptsContainerEl.innerHTML = '';
                parsedVietnameseScenes.forEach((p, index) => {
                    addPromptInput();
                    const allGroups = promptsContainerEl.querySelectorAll('.prompt-input-group');
                    const newGroup = allGroups[allGroups.length-1];
                    const textarea = newGroup.querySelector('textarea');
                    textarea.value = p; textarea.dataset.english = parsedEnglishScenes[index] || ''; textarea.dataset.originalVi = p;
                    setTimeout(() => autoResizeTextarea(textarea), 0);
                });
                return { en: parsedEnglishScenes, vi: parsedVietnameseScenes };
            } catch (error) { console.error("Lỗi khi tạo/phân tích prompt tự động:", error); throw new Error("AI API Error: Failed to generate structured prompts."); }
        }
        async function generateNextScenePrompt(previousSceneData, type = 'new') {
            loadingMessageEl.textContent = 'Đang tạo gợi ý cảnh tiếp theo...';
            const genre = genreSelectEl.value; const genrePrefix = genre ? `Theo thể loại ${genre}, ` : ''; let lightingPrompt = "";
            switch (genre) {
                case "Hành động": lightingPrompt = "Hãy bao gồm các mô tả về ánh sáng động, tương phản cao. "; break;
                case "Quảng cáo": lightingPrompt = "Hãy bao gồm các mô tả về ánh sáng rõ ràng, sạch sẽ, thương mại. "; break;
                case "Kinh dị": lightingPrompt = "Hãy bao gồm các mô tả về ánh sáng tối, u ám, nhiều bóng sâu, và tương phản sáng tối (chiaroscuro). "; break;
                case "Viễn tưởng": lightingPrompt = "Hãy bao gồm các mô tả về ánh sáng neon, ánh sáng tương lai, và tông màu lạnh. "; break;
                case "Ngôn tình": lightingPrompt = "Hãy bao gồm các mô tả về ánh sáng mềm mại, ấm áp, như giờ vàng. "; break;
                case "Hài hước": lightingPrompt = "Hãy bao gồm các mô tả về ánh sáng rực rỡ, đều, và màu sắc sống động. "; break;
            }
            const MAX_CONTEXT_CHAR_LIMIT = 1500;
            const activeCharDescriptions = [];
            storyContext.characters.forEach((charData, name) => { const simpleDesc = charData.description.substring(0, 100); activeCharDescriptions.push(`${name}, ${simpleDesc}`); });
            let charListForAI = activeCharDescriptions.join('; '); if (charListForAI.length > MAX_CONTEXT_CHAR_LIMIT) { charListForAI = charListForAI.substring(0, MAX_CONTEXT_CHAR_LIMIT) + '... (Ngữ cảnh nhân vật bị cắt ngắn)'; }
            let settingDescription = storyContext.settings.join('. '); if (settingDescription.length > 500) { settingDescription = settingDescription.substring(0, 500) + '... (Ngữ cảnh bối cảnh bị cắt ngắn)'; }
            const userIdea = storyIdeaInputPanel.value.trim();
            const detectedTextForAI = storyContext.extractedTexts ? storyContext.extractedTexts.join('. ') : '';
            const detectedProductsForAI = storyContext.keyProducts ? storyContext.keyProducts.join(', ') : '';
            const backgroundDirective = inputImages.size > 0 ? "Bối cảnh/background của cảnh truyện tranh phải được tạo dựa trên nội dung lời nhắc cảnh và 'Bối cảnh' đã được cung cấp. QUAN TRỌNG: Nếu có ảnh tham chiếu được cung cấp, PHẢI BỎ QUA bối cảnh cụ thể trong ảnh đó (trừ khi nó được liệt kê trong phần 'Bối cảnh' bên dưới)." : "";
            let basePrompt = "Bạn là một người viết kịch bản truyện tranh tuần tự. Hãy tạo MỘT lời nhắc cảnh DUY NHẤT.";
            if (type === 'new' && !previousSceneData) {
                basePrompt += userIdea ? ` Bắt đầu câu chuyện dựa trên ý tưởng này: "${userIdea}".` : " Bắt đầu một câu chuyện mới thú vị.";
            } else if (type === 'continue' && !previousSceneData) {
                const lastPage = storyPages[storyPages.length - 1];
                const lastScene = lastPage.prompts.vi.slice(-1)[0] || '';
                const lastDialogue = lastPage.dialogue.fullText.filter(d => d.panelIndex === lastPage.prompts.vi.length - 1).map(d => `${d.charName}: ${d.text}`).join('. ');
                basePrompt += ` Tiếp tục câu chuyện từ cảnh trước: (Lời nhắc: "${lastScene}", Lời thoại: "${lastDialogue}"). Đảm bảo tính liên tục chặt chẽ.`;
            } else if (previousSceneData) {
                basePrompt += ` Tiếp tục một cách logic từ cảnh ngay trước đó: (Lời nhắc: "${previousSceneData.prompt}").`;
                if (previousSceneData.imageBase64) { basePrompt += " Phân tích hình ảnh của cảnh trước để đảm bảo tính liên tục."; } else { basePrompt += " Đảm bảo tính liên tục của các yếu tố từ lời nhắc trước."; }
            }
            basePrompt = backgroundDirective + " " + cinematicShotDirective + " " + genrePrefix + lightingPrompt + basePrompt;
            basePrompt += " Xuất ra dưới dạng đối tượng JSON có hai khóa: \"en\" cho mô tả tiếng Anh và \"vi\" cho bản dịch tiếng Việt tương ứng.";
            let contextForAI = `\nNhân vật có sẵn: ${charListForAI}`;
            if (settingDescription) contextForAI += `\nBối cảnh: ${settingDescription}`;
            if (detectedTextForAI) contextForAI += `\nVăn bản phát hiện: ${detectedTextForAI}`;
            if (detectedProductsForAI) contextForAI += `\nSản phẩm/Đối tượng chính: ${detectedProductsForAI}`;
            if (userIdea) contextForAI += `\nÝ tưởng Cốt truyện Tổng thể: ${userIdea}`;
            const finalPrompt = `${basePrompt}${contextForAI}`;
            const imageParts = [];
            if (inputImages.size > 0) { inputImages.forEach(base64 => { imageParts.push({ inlineData: { mimeType: "image/png", data: base64 } }); }); }
            if (previousSceneData && previousSceneData.imageBase64) { imageParts.push({ inlineData: { mimeType: "image/png", data: previousSceneData.imageBase64 } }); }
            storyContext.characters.forEach(charData => { charData.items.filter(i => i.vi_name === 'Ảnh Tham Chiếu').forEach(refImage => { imageParts.push({ inlineData: { mimeType: "image/png", data: refImage.base64 } }); }); });
            const result = await callGeminiImageAPI(finalPrompt, imageParts, { responseMimeType: "application/json", responseSchema: { type: "OBJECT", properties: { "en": { "type": "STRING" }, "vi": { "type": "STRING" } } } }, TEXT_MODEL);
            try {
                const rawJsonText = result?.candidates?.[0]?.content?.parts?.[0]?.text;
                if (!rawJsonText) throw new Error("AI did not return any JSON text.");
                let jsonText = rawJsonText.trim();
                if (jsonText.startsWith('\\`\\`\\`json')) { jsonText = jsonText.substring(7); if (jsonText.endsWith('\\`\\`\\`')) { jsonText = jsonText.substring(0, jsonText.length - 3).trim(); } }
                else if (jsonText.startsWith('\\`\\`\\`')) { jsonText = jsonText.substring(3); if (jsonText.endsWith('\\`\\`\\`')) { jsonText = jsonText.substring(0, jsonText.length - 3).trim(); } }
                const parsedScene = JSON.parse(jsonText);
                if (parsedScene.vi && parsedScene.en) { return parsedScene; }
                throw new Error("AI returned JSON but it was not in the expected {en: string, vi: string} format.");
            } catch (error) { console.error("Lỗi khi tạo cảnh tiếp theo:", error); throw new Error("AI API Error: Failed to generate structured next scene prompt."); }
        }
        function renderContextInfo() {
            contextInfoContainerEl.innerHTML = '';
            let html = '<div class="space-y-3">';
            if (storyContext.characters.size > 0) {
                html += `<h4 class="text-base font-bold text-gray-700">Nhân vật đã đặt tên:</h4>`;
                storyContext.characters.forEach((char, name) => {
                    const refImage = char.items.find(i => i.vi_name === 'Ảnh Tham Chiếu');
                    const refChipHtml = refImage ? `<div class="char-ref-chip w-16 h-16 mr-2"><img src="data:image/png;base64,${refImage.base64}" alt="Ref"></div>` : '';
                    const otherItems = char.items.filter(i => i.vi_name !== 'Ảnh Tham Chiếu');
                    const itemNames = otherItems.map(i => i.vi_name).join(', ') || 'Không có vật dụng';
                    html += `<div class="p-2 bg-white rounded border border-gray-200 shadow-sm text-sm flex items-center">${refChipHtml}<div><p><strong>${name}</strong>: ${char.description}</p><p class="text-xs text-gray-500">Vật dụng: ${itemNames}</p></div></div>`;
                });
            } else { html += '<p class="text-sm text-gray-500">Chưa có nhân vật được đặt tên.</p>'; }
            if (storyContext.settings.length > 0) { html += `<h4 class="text-base font-bold text-gray-700 mt-4">Bối cảnh cốt truyện:</h4><p class="text-sm text-gray-600">${storyContext.settings.join('; ')}</p>`; }
            if (storyContext.keyProducts.length > 0) { html += `<h4 class="text-base font-bold text-gray-700 mt-4">Đối tượng/Sản phẩm chính:</h4><p class="text-sm text-gray-600">${storyContext.keyProducts.join(', ')}</p>`; }
            html += '</div>';
            contextInfoContainerEl.innerHTML = html;
            renderAllCharactersPool(); renderActiveItemsPool();
        }
        async function handleNewStoryPromptGeneration(userIdea) {
            loadingIndicatorEl.classList.remove('hidden');
            loadingMessageEl.textContent = 'Đang phân tích bối cảnh và tạo lời nhắc...';
            promptsContainerEl.innerHTML = `<div class="text-center p-4"><div class="animate-spin inline-block w-6 h-6 border-4 border-t-4 border-yellow-500 border-gray-200 rounded-full"></div><p class="mt-2 text-sm text-gray-500">AI đang tạo cốt truyện...</p></div>`;
            renderCharacterSelectorsInPrompts();
            try {
                const sceneCount = parseInt(sceneCountSelectEl.value, 10);
                await combineAndGeneratePrompts('new', userIdea, sceneCount);
                displayToast('Đã tạo gợi ý cốt truyện thành công!');
                continueAllScenesBtn.disabled = true; continueSequentialScenesBtn.disabled = true;
                promptSectionEl.classList.remove('hidden');
            } catch(e) {
                console.error("Lỗi khi tạo cốt truyện tự động:", e);
                displayToast('Lỗi khi tạo gợi ý tự động. Vui lòng nhập lời nhắc thủ công.', 'bg-red-700');
                promptsContainerEl.innerHTML = ''; addPromptInput(); promptSectionEl.classList.remove('hidden');
            } finally { loadingIndicatorEl.classList.add('hidden'); }
        }
        function setupCharacterNaming(detectedCharacters) {
            const existingDescriptions = Array.from(storyContext.characters.values()).map(c => c.description);
            let charactersToName = detectedCharacters.filter(char => !existingDescriptions.includes(char.description));
            charNamingInputs.innerHTML = ''; document.getElementById('existing-characters-list').innerHTML = '';
            if(storyContext.characters.size > 0) {
                let listHtml = '<h3 class="text-xl font-semibold text-gray-700 mb-3">Nhân vật đã tồn tại:</h3><div class="space-y-3 p-3 bg-gray-100 rounded-lg border">';
                storyContext.characters.forEach((charData, name) => {
                    const refImage = charData.items.filter(i => i.vi_name === 'Ảnh Tham Chiếu');
                    const refChipHtml = refImage.length > 0 ? `<div class="char-ref-chip w-6 h-6 mr-2"><img src="data:image/png;base64,${refImage[0].base64}" alt="Ref"></div>` : '';
                    listHtml += `<div class="p-3 bg-white rounded-md border border-gray-200 shadow-sm flex items-center">${refChipHtml}<div><p class="font-bold text-gray-800">${name}</p><p class="text-sm text-gray-600 italic">${charData.description.substring(0, 50)}...</p></div></div>`;
                });
                listHtml += '</div><hr class="my-4">';
                document.getElementById('existing-characters-list').innerHTML = listHtml;
            }
            if (charactersToName.length === 0) { handleFinalizeCharacters(false); return; }
            charactersToName.forEach((char, index) => {
                const charEl = document.createElement('div'); charEl.className = 'p-4 bg-yellow-50 rounded-xl border border-yellow-300 shadow-md';
                charEl.id = `new-char-${index}`; charEl.dataset.description = char.description; charEl.dataset.gender = char.gender || 'unknown'; charEl.dataset.age_category = char.age_category || 'unknown';
                charEl.innerHTML = `<div class="flex justify-between items-center mb-2"><label class="block text-base font-semibold text-yellow-800">Nhân vật Mới ${index + 1} (Mô tả):</label><button type="button" class="text-sm text-gray-500 hover:text-red-600 hover:underline skip-char-btn" title="Bỏ qua nhân vật này">Bỏ qua</button></div><p class="text-sm text-gray-700 italic mb-3">${char.description}</p><p class="text-xs text-gray-500 mb-3">AI nhận diện: ${char.gender}, ${char.age_category}</p><label class="block text-base font-semibold text-gray-800 mb-1">Đặt Tên Nhân Vật:</label><input type="text" class="w-full p-3 border border-gray-300 rounded-lg char-name-input shadow-inner" placeholder="Nhập tên nhân vật..." value="${char.name || ''}" required>`;
                charNamingInputs.appendChild(charEl);
                charEl.querySelector('.skip-char-btn').addEventListener('click', () => {
                    charEl.remove();
                    if (charNamingInputs.children.length === 0) { displayToast('Đã bỏ qua tất cả nhân vật mới. Đang tiếp tục...', 'bg-gray-500'); handleFinalizeCharacters(true); }
                    else { displayToast('Đã bỏ qua nhân vật.', 'bg-gray-500'); }
                });
            });
            creationPanelEl.classList.add('hidden'); dialogueEditPanel.classList.add('hidden'); charSetupPanel.classList.remove('hidden'); storyboardEl.classList.add('lg:col-span-1');
            displayToast('Bước 2: Đặt tên cho nhân vật mới.', 'bg-orange-500');
        }
        async function handleFinalizeCharacters(processInputs) {
            let newlyAddedCount = 0;
            if (processInputs) {
                const charDivs = charNamingInputs.querySelectorAll('.p-4');
                const nameToCharacterData = new Map();
                let hasError = false;
                charDivs.forEach(div => {
                    const input = div.querySelector('.char-name-input'); const name = input.value.trim(); const description = div.dataset.description;
                    if (!name) { displayToast('Vui lòng đặt tên hợp lệ cho tất cả nhân vật mới.', 'bg-red-500'); input.focus(); hasError = true; return; }
                    if (storyContext.characters.has(name) && !nameToCharacterData.has(name)) { displayToast(`Tên nhân vật "${name}" đã tồn tại! Vui lòng chọn tên khác.`, 'bg-red-500'); input.focus(); hasError = true; return; }
                    if (!nameToCharacterData.has(name)) { nameToCharacterData.set(name, []); }
                    nameToCharacterData.get(name).push({ description: description });
                });
                if (hasError) return;
                nameToCharacterData.forEach((dataArray, name) => {
                    const descriptions = dataArray.map(d => d.description).filter(desc => typeof desc === 'string' && desc.trim().length > 0);
                    const combinedDescription = descriptions.join('; ');
                    if (storyContext.characters.has(name)) {
                        const existingData = storyContext.characters.get(name);
                        if (!existingData.description.includes(combinedDescription)) { existingData.description += `. Also seen as: ${combinedDescription}`; }
                        storyContext.characters.set(name, existingData);
                    } else { storyContext.characters.set(name, { description: combinedDescription, items: [] }); newlyAddedCount++; }
                });
            }
            const combinedSettings = new Set();
            tempSettingContexts.forEach(context => { if (!context.isPlainBackground && context.setting) { combinedSettings.add(context.setting); } });
            storyContext.settings = Array.from(combinedSettings);
            storyContext.allBackgroundsPlain = tempSettingContexts.every(c => c.isPlainBackground);
            const allDetectedTexts = []; const allDetectedProducts = new Set();
            tempSettingContexts.forEach(context => {
                if (context && context.extracted_text) { allDetectedTexts.push(context.extracted_text); }
                if (context && context.key_products && context.key_products.length > 0) { context.key_products.forEach(prod => allDetectedProducts.add(prod)); }
            });
            storyContext.extractedTexts = allDetectedTexts.filter(Boolean);
            storyContext.keyProducts = Array.from(allDetectedProducts);
            goBackToCreationPanel();
            activeChars.clear(); storyContext.characters.forEach((data, name) => activeChars.add(name));
            renderContextInfo(); renderAllCharactersPool(); renderActiveItemsPool();
            const userIdea = storyIdeaInput.value.trim() || storyIdeaInputPanel.value.trim();
            storyIdeaInputPanel.value = userIdea;
            if (tempContinuationData) {
                if (tempContinuationData.setting) { storyContext.settings.push(tempContinuationData.setting); }
                const fakePageZero = {
                    id: 'page-0-uploaded', prompts: { vi: [tempContinuationData.full_summary || "Cảnh cuối của trang trước."], en: [] },
                    dialogue: { fullText: [{ charName: 'Generic', text: tempContinuationData.last_dialogue || "", panelIndex: 0, x_percent: 50, y_percent: 50, width_percent: DEFAULT_DIALOGUE_SIZE.width, height_percent: DEFAULT_DIALOGUE_SIZE.height, font_family: fontSelectEl.value, font_size: DEFAULT_FONT_SIZE_PX }] },
                    panelImages: [tempContinuationData.lastPanelBase64], settings: { aspectRatio: '1:1', borderStyle: 'classic black' }
                };
                storyPages = [fakePageZero]; pageCounter = 1;
                if (tempContinuationData.style) { styleSelectEl.value = tempContinuationData.style; }
                if (tempContinuationData.genre) { genreSelectEl.value = tempContinuationData.genre; }
                continueAllScenesBtn.disabled = false; continueSequentialScenesBtn.disabled = false;
                promptSectionEl.classList.remove('hidden');
                displayToast(`Đã phân tích trang. Hãy chọn "Tiếp diễn" để tạo trang mới.`);
                tempContinuationData = null;
            } else {
                if (newlyAddedCount > 0) { displayToast(`Đã lưu ${newlyAddedCount} nhân vật mới. Đang tạo gợi ý...`); }
                else if (processInputs === false) { displayToast(`Đã bỏ qua bước đặt tên. Đang tạo gợi ý...`); }
                else { displayToast(`Đã hoàn tất đặt tên nhân vật. Đang tạo gợi ý...`); }
                if (userIdea || storyContext.characters.size > 0 || storyContext.settings.length > 0) { await handleNewStoryPromptGeneration(userIdea); }
                else { displayToast('AI không tìm thấy nhân vật/bối cảnh nào. Vui lòng thêm thủ công hoặc bắt đầu tạo cảnh ngay.', 'bg-yellow-600'); promptsContainerEl.innerHTML = ''; addPromptInput(); promptSectionEl.classList.remove('hidden'); }
            }
        }
        finalizeCharsBtn.addEventListener('click', () => handleFinalizeCharacters(true));
        skipNamingBtn.addEventListener('click', () => handleFinalizeCharacters(false));
        async function startIdeaBasedStoryFlow(userIdea) {
            if (!userIdea) { displayToast('Vui lòng nhập ý tưởng cốt truyện trước!', 'bg-red-500'); return; }
            introCard.classList.add('hidden'); creationPanelEl.classList.remove('hidden'); storyboardEl.classList.add('lg:col-span-1');
            loadingIndicatorEl.classList.remove('hidden'); loadingMessageEl.textContent = 'Đang phân tích ý tưởng cốt truyện để nhận diện nhân vật...';
            try {
                storyContext.characters.clear(); storyContext.settings = []; storyPages = []; pageCounter = 0; tempContinuationData = null;
                const detectedCharacters = await extractCharactersFromIdea(userIdea);
                tempSettingContexts = [{ setting: userIdea, isPlainBackground: false }]; storyIdeaInputPanel.value = userIdea;
                setupCharacterNaming(detectedCharacters.map(char => ({ name: char.name, description: char.description, gender: char.gender, age_category: char.age_category })));
            } catch(e) {
                console.error("Lỗi nghiêm trọng khi trích xuất nhân vật từ ý tưởng:", e);
                displayToast('Lỗi API: Không thể phân tích ý tưởng cốt truyện. Vui lòng thử lại hoặc thêm nhân vật thủ công.', 'bg-red-700');
                goBackToCreationPanel(); promptSectionEl.classList.remove('hidden'); promptsContainerEl.innerHTML = ''; addPromptInput();
            } finally { loadingIndicatorEl.classList.add('hidden'); }
        }
        generateStoryFromIdeaBtn.addEventListener('click', () => { const userIdea = storyIdeaInput.value.trim(); startIdeaBasedStoryFlow(userIdea); });
        generateStoryFromIdeaPanelBtn.addEventListener('click', async () => {
            const userIdea = storyIdeaInputPanel.value.trim();
            if (storyContext.characters.size > 0 && !userIdea) {
                activeChars.clear(); storyContext.characters.forEach((data, name) => activeChars.add(name)); renderAllCharactersPool();
                let generationType = 'new';
                if (storyPages.length > 0) { generationType = 'continue'; displayToast('Tự động tiếp diễn câu chuyện...', 'bg-blue-500'); }
                else { displayToast('Đang tạo cốt truyện mới từ bối cảnh...'); }
                promptSectionEl.classList.remove('hidden'); isSequentialMode = false;
                await regeneratePrompts(generationType);
                renderCharacterSelectorsInPrompts();
            } else { startIdeaBasedStoryFlow(userIdea); }
        });
        function renderInputImage(base64Data, id) {
            const existingEl = document.getElementById(id); if (existingEl) { existingEl.remove(); }
            const div = document.createElement('div');
            div.id = id; div.className = 'relative group rounded-lg overflow-hidden border-2 border-gray-300 shadow-md p-2 bg-white col-span-1';
            div.innerHTML = `<div class="relative"><img src="data:image/png;base64,${base64Data}" class="w-full h-auto object-cover rounded-md" alt="Input image for context"><button class="absolute top-2 right-2 bg-red-500 text-white rounded-full p-1.5 opacity-0 group-hover:opacity-100 transition-opacity duration-200 remove-input-image shadow-lg"><svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12" /></svg></button><div class="absolute top-2 left-2 flex flex-col gap-1 opacity-0 group-hover:opacity-100 transition-opacity duration-200"><button class="save-input-lib-btn bg-blue-600 text-white text-xs font-semibold rounded-lg py-0.5 px-2 shadow-md">Lưu</button><button class="extract-bg-btn bg-teal-600 text-white text-xs font-semibold rounded-lg py-0.5 px-2 shadow-md">Bối cảnh</button></div></div><div class="mt-3 detected-chars-area transition-all duration-300 grid grid-cols-2 gap-2"><button class="detect-chars-btn bg-yellow-500 hover:bg-yellow-600 text-white text-xs font-semibold py-1.5 px-2 rounded-lg transition shadow-md col-span-1">Nhận diện Nhân vật</button><button class="detect-items-btn bg-purple-500 hover:bg-purple-600 text-white text-xs font-semibold py-1.5 px-2 rounded-lg transition shadow-md col-span-1">Quét Vật dụng (Mới)</button></div>`;
            inputImageContainerEl.appendChild(div);
            div.querySelector('.remove-input-image').addEventListener('click', () => { inputImages.delete(id); div.remove(); updateInputImageContainer(); });
            div.querySelector('.save-input-lib-btn').addEventListener('click', () => { imageLibrary.push({ base64: base64Data, prompts: { en: ["Input image"], vi: ["Ảnh đầu vào"] } }); renderImageLibrary(); displayToast('Đã lưu ảnh đầu vào vào Thư viện!'); });
            div.querySelector('.extract-bg-btn').addEventListener('click', (e) => extractSettingFromImage(e.currentTarget, base64Data, id));
            div.querySelector('.detect-chars-btn').addEventListener('click', (e) => detectAndRenderSubjects(base64Data, div));
            div.querySelector('.detect-items-btn').addEventListener('click', (e) => detectAndAssignItems(base64Data, div));
        }
        async function detectAndAssignItems(base64Data, imageDiv) {
            if (storyContext.characters.size === 0) { displayToast('Vui lòng tạo ít nhất một nhân vật (Bước 2) trước khi quét vật dụng.', 'bg-red-500'); return; }
            const btn = imageDiv.querySelector('.detect-items-btn'); const originalText = btn.textContent; btn.textContent = 'Đang quét...'; btn.disabled = true;
            try {
                const itemPrompt = `Analyze this image. Identify distinct physical items, objects, weapons, tools, accessories (like hats, glasses, jewelry), or significant props held or worn by characters or present in the scene. Ignore the characters' bodies/faces and background elements unless they are specific props. Return a JSON array of objects. For each item: "vi_name" (Vietnamese Name), "en_desc" (Detailed English visual description).`;
                const result = await callGeminiImageAPI(itemPrompt, [{ inlineData: { mimeType: "image/png", data: base64Data } }], { responseMimeType: "application/json", responseSchema: { type: "ARRAY", items: { type: "OBJECT", properties: { "vi_name": { "type": "STRING" }, "en_desc": { "type": "STRING" } } } } }, TEXT_MODEL);
                const jsonText = result?.candidates?.[0]?.content?.parts?.[0]?.text;
                const items = jsonText ? JSON.parse(jsonText) : [];
                if (items.length > 0) { showItemAssignmentModal(items, base64Data); }
                else { displayToast('Không tìm thấy vật dụng rõ ràng nào.', 'bg-yellow-500'); }
            } catch (e) { console.error("Lỗi nhận diện vật dụng:", e); displayToast('Lỗi khi quét vật dụng. Vui lòng thử lại.', 'bg-red-500'); }
            finally { btn.textContent = originalText; btn.disabled = false; }
        }
        function showItemAssignmentModal(items, base64Data) {
            foundItemsListContainer.innerHTML = ''; assignItemsPreviewImg.src = `data:image/png;base64,${base64Data}`;
            const charNames = Array.from(storyContext.characters.keys());
            items.forEach((item, index) => {
                const itemDiv = document.createElement('div'); itemDiv.className = 'flex items-center justify-between p-3 bg-gray-50 rounded border border-gray-200';
                let optionsHtml = `<option value="">-- Chọn Nhân vật --</option>`;
                charNames.forEach(name => { optionsHtml += `<option value="${name}">${name}</option>`; });
                itemDiv.innerHTML = `<div class="flex-grow"><p class="font-bold text-gray-800">${item.vi_name}</p><p class="text-xs text-gray-500 truncate w-48" title="${item.en_desc}">${item.en_desc}</p></div><select class="p-2 border rounded text-sm assign-char-select bg-white" data-index="${index}">${optionsHtml}</select>`;
                itemDiv.dataset.viName = item.vi_name; itemDiv.dataset.enDesc = item.en_desc;
                foundItemsListContainer.appendChild(itemDiv);
            });
            assignItemsModal.style.display = 'flex';
            confirmAssignItemsBtn.onclick = () => {
                const selects = foundItemsListContainer.querySelectorAll('.assign-char-select'); let assignedCount = 0;
                selects.forEach(select => {
                    const charName = select.value;
                    if (charName) {
                        const itemDiv = select.closest('div.flex'); const viName = itemDiv.dataset.viName; const enDesc = itemDiv.dataset.enDesc;
                        const charData = storyContext.characters.get(charName);
                        if (charData) { charData.items.push({ vi_name: viName, en_desc: enDesc, base64: base64Data }); assignedCount++; }
                    }
                });
                if (assignedCount > 0) { displayToast(`Đã gán ${assignedCount} vật dụng vào kho đồ!`, 'bg-green-600'); renderContextInfo(); renderAllCharactersPool(); assignItemsModal.style.display = 'none'; }
                else { displayToast('Bạn chưa chọn nhân vật nào để gán.', 'bg-yellow-500'); }
            };
        }
        closeAssignItemsBtn.onclick = () => { assignItemsModal.style.display = 'none'; };
        cancelAssignItemsBtn.onclick = () => { assignItemsModal.style.display = 'none'; };
        async function extractSettingFromImage(button, base64Data, originalId) {
            const originalText = button.textContent; button.textContent = 'Đang...'; button.disabled = true;
            const prompt = `Analyze the provided image. CRITICAL TASK: Create a new image containing only the background/setting. Removal: You MUST remove all characters, people, animals, and significant foreground objects. Inpainting: Use generative AI to intelligently fill in the areas where the subjects were removed, creating a complete and seamless background scene. No Change: Do NOT change the style or core elements of the background. Return ONLY the new image of the complete, empty background.`;
            const result = await callGeminiImageAPI(prompt, [{ inlineData: { mimeType: "image/png", data: base64Data } }], { responseModalities: ["IMAGE"] }, IMAGE_MODEL);
            try {
                const newBase64Data = result?.candidates?.[0]?.content?.parts?.find(p => p.inlineData)?.inlineData?.data;
                if (newBase64Data) { const newId = `input-img-${Date.now()}-bg`; inputImages.set(newId, newBase64Data); renderInputImage(newBase64Data, newId); updateInputImageContainer(); displayToast('Đã trích xuất và thêm ảnh bối cảnh mới.'); }
                else { throw new Error("AI did not return a valid image."); }
            } catch (error) { console.error("Lỗi khi trích xuất bối cảnh:", error); displayToast('Lỗi khi trích xuất bối cảnh. Vui lòng thử lại.', 'bg-red-500'); }
            finally { button.textContent = originalText; button.disabled = false; }
        }
        function updateInputImageContainer() {
            const imagesCount = inputImages.size; const placeholderText = 'Chưa có ảnh đầu vào. Vui lòng tải lên hoặc chọn từ thư viện.';
            const placeholderEl = inputImageContainerEl.querySelector('.input-placeholder-text');
            if (imagesCount === 0) { if (!placeholderEl) { inputImageContainerEl.innerHTML = `<p class="text-sm text-gray-500 col-span-2 input-placeholder-text">${placeholderText}</p>`; } inputImageContainerEl.classList.remove('grid-cols-2'); inputImageContainerEl.classList.add('grid-cols-1'); }
            else { if (placeholderEl) { placeholderEl.remove(); } inputImageContainerEl.classList.remove('grid-cols-1'); inputImageContainerEl.classList.add('grid-cols-2'); }
        }
        imageUploadInput.addEventListener('change', (e) => {
            const files = e.target.files;
            if (files.length > 0) {
                introCard.classList.add('hidden'); creationPanelEl.classList.remove('hidden');
                const isComicPage = document.getElementById('is-comic-page-check').checked;
                if (isComicPage && files.length > 1) { displayToast('Chế độ "trang truyện" chỉ hỗ trợ 1 ảnh. Đang tải ảnh đầu tiên.', 'bg-yellow-500'); }
                const filePromises = [];
                for (let i = 0; i < files.length; i++) {
                    if (isComicPage && i > 0) break;
                    filePromises.push(new Promise((resolve, reject) => {
                        const file = files[i];
                        const reader = new FileReader();
                        reader.onload = (event) => {
                            const base64Data = event.target.result.split(',')[1];
                            const id = `input-img-${Date.now()}-${Math.random().toString(36).substring(2, 8)}`;
                            inputImages.set(id, base64Data); renderInputImage(base64Data, id); resolve();
                        };
                        reader.onerror = reject; reader.readAsDataURL(file);
                    }));
                }
                Promise.all(filePromises).then(() => { updateInputImageContainer(); }).catch(error => {
                    console.error("Lỗi khi tải ảnh:", error); displayToast('Lỗi khi tải ảnh. Vui lòng thử lại.', 'bg-red-700'); updateInputImageContainer();
                });
            }
            e.target.value = null;
        });
        imageUploadInputIntro.addEventListener('change', (e) => { imageUploadInput.files = e.target.files; imageUploadInput.dispatchEvent(new Event('change', { bubbles: true })); e.target.value = null; });
        confirmSelectionBtn.addEventListener('click', async () => {
            if (inputImages.size === 0) { displayToast('Vui lòng chọn hoặc tải lên ít nhất một hình ảnh!', 'bg-red-500'); return; }
            confirmSelectionBtn.disabled = true; loadingIndicatorEl.classList.remove('hidden');
            const isComicPage = document.getElementById('is-comic-page-check').checked;
            if (!isComicPage) {
                loadingMessageEl.textContent = 'Đang phân tích ảnh để xác định nhân vật và bối cảnh...';
                const uploadedContexts = [];
                const processingPromises = Array.from(inputImages.values()).map(base64Data => extractContextFromImage(base64Data).then(context => uploadedContexts.push(context)));
                await Promise.all(processingPromises);
                const allDetectedCharacters = []; uploadedContexts.forEach(context => { if(context && context.characters) { allDetectedCharacters.push(...context.characters); } });
                tempSettingContexts = uploadedContexts;
                setupCharacterNaming(allDetectedCharacters);
            } else {
                loadingMessageEl.textContent = 'Đang phân tích trang truyện để tiếp diễn...';
                const base64Data = inputImages.values().next().value;
                const result = await analyzeComicPageForContinuation(base64Data);
                if (result && result.analysisData && result.lastPanelBase64) {
                    const { analysisData, lastPanelBase64 } = result;
                    storyContext.characters.clear(); storyContext.settings = []; storyPages = []; pageCounter = 0; tempContinuationData = null;
                    tempContinuationData = { characters: analysisData.characters, setting: analysisData.setting, full_summary: analysisData.full_page_summary, last_dialogue: analysisData.last_scene_dialogue, lastPanelBase64: lastPanelBase64, genre: analysisData.inferred_genre, style: analysisData.inferred_style };
                    setupCharacterNaming(analysisData.characters);
                } else { displayToast('Không thể phân tích trang truyện. Vui lòng thử lại.', 'bg-red-500'); }
            }
            loadingIndicatorEl.classList.add('hidden'); confirmSelectionBtn.disabled = false;
        });
        addPromptBtn.addEventListener('click', addPromptInput);
        generateAllScenesBtn.addEventListener('click', async () => { isSequentialMode = false; await regeneratePrompts('new'); });
        continueAllScenesBtn.addEventListener('click', async () => { if (storyPages.length === 0) { displayToast('Chưa có trang hoàn chỉnh để tiếp diễn!', 'bg-red-500'); return; } isSequentialMode = false; await regeneratePrompts('continue'); });
        generateSequentialScenesBtn.addEventListener('click', async () => {
            isSequentialMode = true; promptsContainerEl.innerHTML = '';
            loadingIndicatorEl.classList.remove('hidden'); loadingMessageEl.textContent = 'Đang tạo cảnh đầu tiên (Tuần tự)...';
            const generatedPrompts = await generateNextScenePrompt(null, 'new');
            loadingIndicatorEl.classList.add('hidden');
            if (generatedPrompts) { addPromptInput(generatedPrompts); promptSectionEl.classList.remove('hidden'); displayToast('Đã tạo gợi ý cảnh 1. Nhấn "Tạo Cảnh Tiếp" để tiếp tục.'); }
            else { displayToast('Không thể tạo gợi ý cảnh đầu tiên.', 'bg-red-500'); }
        });
        continueSequentialScenesBtn.addEventListener('click', async () => {
            if (storyPages.length === 0) { displayToast('Chưa có trang hoàn chỉnh để tiếp diễn!', 'bg-red-500'); return; }
            isSequentialMode = true; promptsContainerEl.innerHTML = '';
            loadingIndicatorEl.classList.remove('hidden'); loadingMessageEl.textContent = 'Đang tạo cảnh tiếp diễn (Tuần tự)...';
            const lastPage = storyPages[storyPages.length - 1];
            const previousSceneData = { prompt: lastPage.prompts.vi.slice(-1)[0] || '', imageBase64: lastPage.panelImages?.slice(-1)[0] || null, };
            const generatedPrompts = await generateNextScenePrompt(previousSceneData, 'continue');
            loadingIndicatorEl.classList.add('hidden');
            if (generatedPrompts) { addPromptInput(generatedPrompts); promptSectionEl.classList.remove('hidden'); displayToast('Đã tạo gợi ý cảnh tiếp diễn. Nhấn "Tạo Cảnh Tiếp" để tiếp tục.'); }
            else { displayToast('Không thể tạo gợi ý cảnh tiếp diễn.', 'bg-red-500'); }
        });
        function getPanelIndexFromCoords(x, y, parentWidth, parentHeight, panelCount) {
            const relativeX = x / parentWidth; const relativeY = y / parentHeight;
            const coords = FALLBACK_GRIDS[Math.min(panelCount, 4)] || FALLBACK_GRIDS[1];
            const cols = coords.cols; const rows = coords.rows;
            const col = Math.min(cols-1, Math.floor(relativeX * cols));
            const row = Math.min(rows-1, Math.floor(relativeY * rows));
            return row * cols + col;
        }
        function getPanelCoordinates(pIdx, totalPanels) {
            const sizeW = DEFAULT_DIALOGUE_SIZE.width; const sizeH = DEFAULT_DIALOGUE_SIZE.height;
            const count = Math.min(totalPanels, 4);
            const coords = FALLBACK_GRIDS[count] || FALLBACK_GRIDS[1];
            const cols = coords.cols; const rows = coords.rows;
            const panelW = 100 / cols; const panelH = 100 / rows;
            const col = pIdx % cols; const row = Math.floor(pIdx / cols);
            const panelLeft = col * panelW; const panelTop = row * panelH;
            const x_center = panelLeft + (panelW / 2); const y_center = panelTop + (panelH / 2);
            return { x: x_center, y: y_center, width: sizeW, height: sizeH };
        }
        function createDialogueBox(pIdx, charName, initialText = '', initialFontSize = DEFAULT_FONT_SIZE_PX, isFinal = false, initialShape = 'automatic') {
            const uniqueId = `dialogue-${dialogueIdCounter++}`;
            const boxType = charName === 'Generic' ? 'Lời thoại chung' : charName;
            const currentFont = fontSelectEl.value;
            let initialX, initialY, initialW, initialH, initialFS, bubbleShape;
            let existingData = tempNewPage?.dialogue?.fullText.find(d => d.dialogueId === uniqueId);
            if (!existingData) {
                const nextId = dialogueIdCounter - 1;
                existingData = tempNewPage?.dialogue?.fullText.find(d => parseInt(d.dialogueId.split('-')[1] || 0) === nextId && d.panelIndex === pIdx && d.charName === charName);
            }
            if (existingData) {
                initialW = existingData.width_percent; initialH = existingData.height_percent;
                initialX = existingData.x_percent - (initialW / 2); initialY = existingData.y_percent - (initialH / 2);
                initialFS = existingData.font_size; bubbleShape = existingData.shape || initialShape;
                dialogueIdCounter = Math.max(dialogueIdCounter, parseInt(existingData.dialogueId.split('-')[1] || 0) + 1);
            } else {
                const { x: x_center, y: y_center, width, height } = getPanelCoordinates(pIdx, tempNewPage.prompts.en.length);
                initialW = width; initialH = height; initialX = x_center - (width / 2); initialY = y_center - (height / 2);
                initialFS = initialFontSize; bubbleShape = initialShape;
                const newDialogueEntry = {
                    panelIndex: pIdx, charName: charName, text: initialText,
                    x_percent: x_center, y_percent: y_center,
                    width_percent: initialW, height_percent: initialH,
                    font_family: currentFont, font_size: initialFS,
                    shape: bubbleShape, dialogueId: uniqueId
                };
                if (!tempNewPage.dialogue.fullText) tempNewPage.dialogue.fullText = [];
                tempNewPage.dialogue.fullText.push(newDialogueEntry);
            }
            const wrapper = document.createElement('div');
            wrapper.id = uniqueId;
            wrapper.className = `dialogue-box-wrapper ${isFinal ? 'final-text-container' : ''}`;
            wrapper.style.left = `${initialX}%`; wrapper.style.top = `${initialY}%`;
            wrapper.dataset.panelIndex = pIdx; wrapper.dataset.charName = charName; wrapper.dataset.isGeneric = charName === 'Generic';
            wrapper.dataset.fontSize = initialFS; wrapper.dataset.fontFamily = currentFont; wrapper.dataset.bubbleShape = bubbleShape;
            wrapper.dataset.dialogueId = uniqueId;
            wrapper.style.width = `${initialW}%`; wrapper.style.height = `${initialH}%`;
            wrapper.dataset.widthPercent = initialW; wrapper.dataset.heightPercent = initialH;
            const dragBox = document.createElement('textarea');
            dragBox.className = 'dialogue-box-textarea prompt-textarea'; dragBox.rows = 1; dragBox.placeholder = `Nhập ${boxType}...`; dragBox.value = initialText;
            dragBox.oninput = (e) => { window.syncDialogueTextToInput(e.target); };
            dragBox.dataset.syncTargetId = uniqueId; dragBox.style.fontFamily = currentFont; dragBox.style.fontSize = `${initialFS}px`;
            const handles = ['top-left', 'top-right', 'bottom-left', 'bottom-right'];
            handles.forEach(pos => { const handle = document.createElement('div'); handle.className = `resize-handle ${pos}`; handle.dataset.direction = pos; wrapper.appendChild(handle); });
            const staticContentDiv = document.createElement('div');
            staticContentDiv.className = 'dialogue-box-static-content'; staticContentDiv.textContent = initialText;
            staticContentDiv.style.fontFamily = currentFont; staticContentDiv.style.fontSize = `${initialFS}px`;
            wrapper.appendChild(dragBox); wrapper.appendChild(staticContentDiv); interactiveDialogueArea.appendChild(wrapper);
            const staticInputGroup = document.createElement('div');
            staticInputGroup.className = 'flex flex-col p-3 bg-white rounded-lg border border-gray-200 shadow-sm';
            staticInputGroup.innerHTML = `<div class="flex items-start mb-2"><div class="flex-grow"><label class="block text-sm font-semibold text-gray-700 mb-1">${boxType} (Cảnh ${pIdx + 1}):</label><textarea rows="1" class="w-full p-2 border border-gray-300 rounded dialogue-sync-input prompt-textarea shadow-inner" data-target-id="${uniqueId}" data-initial-fs="${initialFontSize}" oninput="window.syncDialogueText(this)" placeholder="${boxType}..."></textarea></div><button type="button" class="remove-dialogue-btn ml-3 bg-red-500 hover:bg-red-600 text-white p-2.5 rounded-full leading-none transition duration-200 shadow-md flex-shrink-0" data-target-id="${uniqueId}" title="Xóa Lời Thoại"><svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12" /></svg></button></div><div class="flex items-center justify-between mb-2"><label class="text-xs font-medium text-gray-500 mr-2">Hình dạng:</label><select class="bubble-shape-select text-xs p-1 border border-gray-300 rounded focus:ring-blue-500" data-target-id="${uniqueId}" onchange="window.syncBubbleShape(this)"><option value="automatic" ${bubbleShape === 'automatic' ? 'selected' : ''}>Tự động</option><option value="normal" ${bubbleShape === 'normal' ? 'selected' : ''}>Nói thường (Oval/Tròn)</option><option value="thought" ${bubbleShape === 'thought' ? 'selected' : ''}>Suy nghĩ (Đám mây)</option><option value="shout" ${bubbleShape === 'shout' ? 'selected' : ''}>Hét lớn/Mạnh (Gai góc)</option><option value="rectangle" ${bubbleShape === 'rectangle' ? 'selected' : ''}>Hộp Chữ Nhật (Caption)</option></select></div><div class="flex items-center pt-2 border-t border-gray-200"><button type="button" class="play-tts-btn flex items-center bg-blue-500 hover:bg-blue-600 text-white text-xs font-semibold py-1 px-3 rounded-full transition shadow-sm" onclick="window.generateAndPlayTts(this)"><svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4 mr-1" viewBox="0 0 20 20" fill="currentColor"><path fill-rule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zM9.555 7.168A1 1 0 008 8v4a1 1 0 001.555.832l3-2a1 1 0 000-1.664l-3-2z" clip-rule="evenodd" /></svg>Play Audio</button><label class="text-xs font-medium text-gray-500 mr-2 ml-4 min-w-[50px]">Cỡ chữ:</label><input type="range" min="12" max="40" value="${initialFS}" class="flex-grow font-size-slider" data-target-id="${uniqueId}" oninput="window.syncFontSize(this)"><span class="text-xs text-gray-700 font-semibold ml-2 min-w-[30px] text-right">${initialFS}px</span></div>`;
            dialogueInputsContainer.appendChild(staticInputGroup);
            const staticInput = staticInputGroup.querySelector('textarea'); staticInput.value = initialText; window.autoResizeTextarea(staticInput);
            registerDragAndResizeListeners(wrapper);
            staticInputGroup.querySelector('.remove-dialogue-btn').addEventListener('click', () => {
                const targetIdToRemove = staticInputGroup.querySelector('.remove-dialogue-btn').dataset.targetId;
                const wrapperToRemove = document.getElementById(targetIdToRemove);
                if (wrapperToRemove) { unregisterDragAndResizeListeners(wrapperToRemove); wrapperToRemove.remove(); }
                staticInputGroup.remove();
                if (tempNewPage && tempNewPage.dialogue.fullText) { tempNewPage.dialogue.fullText = tempNewPage.dialogue.fullText.filter(d => d.dialogueId !== targetIdToRemove); }
            });
            window.autoResizeBox(wrapper);
            return uniqueId;
        }
        window.syncBubbleShape = (select) => { const targetId = select.dataset.targetId; const wrapper = document.getElementById(targetId); if (wrapper) { wrapper.dataset.bubbleShape = select.value; } };
        addGenericDialogueBtn.addEventListener('click', () => { createDialogueBox(0, 'Generic', '(Lời dẫn truyện hoặc mô tả...)', DEFAULT_FONT_SIZE_PX, isFinalReviewMode, 'automatic'); displayToast('Đã thêm hộp thoại chung.', 'bg-gray-500'); });
        window.syncDialogueText = (input) => {
            const wrapper = document.getElementById(input.dataset.targetId);
            if (wrapper) {
                const dragBox = wrapper.querySelector('textarea'); const staticContent = wrapper.querySelector('.dialogue-box-static-content');
                if (dragBox) { dragBox.value = input.value; } if (staticContent) { staticContent.textContent = input.value; }
            }
        };
        window.syncDialogueTextToInput = (textarea) => {
            const targetId = textarea.dataset.syncTargetId; const wrapper = document.getElementById(targetId);
            const staticInput = dialogueInputsContainer.querySelector(`.dialogue-sync-input[data-target-id="${targetId}"]`);
            const staticContent = wrapper ? wrapper.querySelector('.dialogue-box-static-content') : null;
            if (staticInput) { staticInput.value = textarea.value; window.autoResizeTextarea(staticInput); }
            if (staticContent) { staticContent.textContent = textarea.value; }
            if (wrapper) { window.autoResizeBox(wrapper); }
        };
        window.syncFontSize = (slider) => {
            const size = slider.value; const targetId = slider.dataset.targetId; const wrapper = document.getElementById(targetId); const sizeSpan = slider.nextElementSibling;
            if (wrapper) {
                wrapper.dataset.fontSize = size;
                const dragBox = wrapper.querySelector('textarea'); const staticContent = wrapper.querySelector('.dialogue-box-static-content');
                if (dragBox) { dragBox.style.fontSize = `${size}px`; } if (staticContent) { staticContent.style.fontSize = `${size}px`; }
                window.autoResizeBox(wrapper);
            }
            if (sizeSpan) { sizeSpan.textContent = `${size}px`; }
        }
        async function finalizeFallbackLayout() {
            const layoutPrompt = "classic, round, clean comic book speech bubble, white fill, black outline";
            if (!tempNewPage) return;
            useFallbackLayoutBtn.disabled = true; finalizeAILayoutBtn.disabled = true;
            document.getElementById('back-from-dialogue-btn').disabled = true;
            dialogueLoadingIndicator.classList.remove('hidden');
            dialogueLoadingMessageEl.textContent = '1/2: Đang thu thập dữ liệu lời thoại...';
            const allDialogueData = collectDialogueDataFromUI();
            if (allDialogueData.length === 0) {
                displayToast('Vui lòng thêm ít nhất một lời thoại trước khi tiếp tục.', 'bg-red-500');
                useFallbackLayoutBtn.disabled = false; finalizeAILayoutBtn.disabled = false;
                document.getElementById('back-from-dialogue-btn').disabled = false;
                dialogueLoadingIndicator.classList.add('hidden');
                return;
            }
            tempNewPage.dialogue.fullText = allDialogueData;
            tempNewPage.fontValue = fontSelectEl.value; tempNewPage.layoutPrompt = layoutPrompt;
            try {
                const fallbackBase64 = tempNewPage.base64_composed_no_bubbles;
                if (!fallbackBase64) { throw new Error("Không tìm thấy bố cục lưới cơ bản. Vui lòng tạo lại trang nháp."); }
                dialogueLoadingMessageEl.textContent = '2/2: Đang vẽ bong bóng rỗng (Tự động tránh mặt nhân vật)...';
                const aiLayoutBase64 = await generateAILayoutWithEmptyBubbles(fallbackBase64, layoutPrompt, allDialogueData);
                if (!aiLayoutBase64) { throw new Error("AI không thể tạo bong bóng rỗng trên bố cục lưới cơ bản. Vui lòng thử lại."); }
                tempNewPage.base64_ai_layout_empty_text = aiLayoutBase64;
                tempNewPage.base64_ai_layout_no_bubbles = fallbackBase64;
                dialogueLoadingMessageEl.textContent = 'Đang chuẩn bị giao diện xem lại bố cục cuối...';
                goBackToFinalDialogueReview(tempNewPage);
            } catch(error) {
                console.error("Lỗi nghiêm trọng khi Tạo Bong bóng Rỗng trên lưới cơ bản:", error);
                displayToast(`Lỗi: Không thể tạo bong bóng AI trên lưới cơ bản. ${error.message}. Vui lòng thử lại.`, 'bg-red-700');
                startDialogueEditing(tempNewPage);
            } finally {
                useFallbackLayoutBtn.disabled = false; finalizeAILayoutBtn.disabled = false;
                document.getElementById('back-from-dialogue-btn').disabled = false;
                dialogueLoadingIndicator.classList.add('hidden');
            }
        }
        useFallbackLayoutBtn.addEventListener('click', finalizeFallbackLayout);
        finalizeAILayoutBtn.addEventListener('click', async () => {
            const layoutStyleKey = aiLayoutStyleSelectEl.value;
            let layoutPrompt = "dynamic, creative, professional comic book speech bubble";
            if (!tempNewPage) return;
            finalizeAILayoutBtn.disabled = true; useFallbackLayoutBtn.disabled = true;
            document.getElementById('back-from-dialogue-btn').disabled = true;
            aiLayoutStyleSelectEl.disabled = true;
            dialogueLoadingIndicator.classList.remove('hidden');
            dialogueLoadingMessageEl.textContent = '1/3: Đang thu thập dữ liệu lời thoại...';
            const allDialogueData = collectDialogueDataFromUI();
            if (allDialogueData.length === 0) {
                displayToast('Vui lòng thêm ít nhất một lời thoại trước khi tiếp tục.', 'bg-red-500');
                finalizeAILayoutBtn.disabled = false; useFallbackLayoutBtn.disabled = false;
                document.getElementById('back-from-dialogue-btn').disabled = false;
                aiLayoutStyleSelectEl.disabled = false;
                dialogueLoadingIndicator.classList.add('hidden');
                return;
            }
            tempNewPage.dialogue.fullText = allDialogueData;
            tempNewPage.fontValue = fontSelectEl.value; tempNewPage.layoutPrompt = layoutPrompt;
            try {
                dialogueLoadingMessageEl.textContent = `1/3: Đang tạo bố cục AI phong cách ${layoutStyleKey}...`;
                const aiLayoutNoBubblesBase64 = await generateCreativePanelLayout(tempNewPage.panelImages, tempNewPage, layoutStyleKey);
                if (!aiLayoutNoBubblesBase64) { throw new Error("AI không thể tạo bố cục trang động. Vui lòng thử lại."); }
                tempNewPage.base64_ai_layout_no_bubbles = aiLayoutNoBubblesBase64;
                dialogueLoadingMessageEl.textContent = '2/3: Đang vẽ bong bóng rỗng (Tự động tránh mặt nhân vật)...';
                const aiLayoutBase64 = await generateAILayoutWithEmptyBubbles(aiLayoutNoBubblesBase64, layoutPrompt, allDialogueData);
                if (!aiLayoutBase64) { throw new Error("AI không thể tạo bong bóng rỗng trên bố cục động. Vui lòng thử lại."); }
                tempNewPage.base64_ai_layout_empty_text = aiLayoutBase64;
                dialogueLoadingMessageEl.textContent = '3/3: Đang chuẩn bị giao diện xem lại bố cục cuối...';
                goBackToFinalDialogueReview(tempNewPage);
            } catch(error) {
                console.error("Lỗi nghiêm trọng khi Tạo Bong bóng Rỗng:", error);
                displayToast(`Lỗi: Không thể tạo bố cục/bong bóng AI. ${error.message}. Vui lòng thử lại.`, 'bg-red-700');
                startDialogueEditing(tempNewPage);
            } finally {
                finalizeAILayoutBtn.disabled = false; useFallbackLayoutBtn.disabled = false;
                document.getElementById('back-from-dialogue-btn').disabled = false;
                aiLayoutStyleSelectEl.disabled = false;
                dialogueLoadingIndicator.classList.add('hidden');
            }
        });
        function collectDialogueDataFromUI() {
            const dialogueInputs = dialogueInputsContainer.querySelectorAll('.dialogue-sync-input');
            const allDialogueData = [];
            dialogueInputs.forEach(input => {
                const dialogueId = input.dataset.targetId; const wrapper = document.getElementById(dialogueId); const text = input.value.trim();
                if (wrapper && text) {
                    const width_percent = parseFloat(wrapper.dataset.widthPercent);
                    const height_percent = parseFloat(wrapper.dataset.heightPercent);
                    const left_percent = parseFloat(wrapper.style.left);
                    const top_percent = parseFloat(wrapper.style.top);
                    const x_center = left_percent + (width_percent / 2);
                    const y_center = top_percent + (height_percent / 2);
                    const fontSize = parseFloat(wrapper.dataset.fontSize);
                    const fontFamily = wrapper.dataset.fontFamily;
                    const shape = wrapper.dataset.bubbleShape || 'automatic';
                    allDialogueData.push({
                        panelIndex: parseInt(wrapper.dataset.panelIndex, 10), charName: wrapper.dataset.charName, text: text,
                        x_percent: x_center, y_percent: y_center, width_percent: width_percent, height_percent: height_percent,
                        font_family: fontFamily, font_size: fontSize, shape: shape, dialogueId: dialogueId
                    });
                }
            });
            return allDialogueData;
        }
        async function generateCreativePanelLayout(panelBase64s, pageData, layoutStyleKey = 'dynamic') {
            const panelCount = panelBase64s.length;
            const panelImageParts = panelBase64s.map(base64 => ({ inlineData: { mimeType: "image/png", data: base64 } }));
            const aspectRatio = pageData.settings.aspectRatio;
            const style = styleSelectEl.value;
            const borderStyle = borderStyleSelectEl.value;
            const borderInstruction = borderStyle === 'no borders' ? "Use a completely borderless, full-bleed design." : "Use classic comic panel borders, with a small gutter between them.";
            const styleInstruction = style ? `The entire page must adhere strictly to the ${style.replace('_style', '').replace('_', ' ')} style.` : "Maintain a visually consistent comic book style.";
            let layoutSpecificInstruction = "";
            switch (layoutStyleKey) {
                case "advertisement": layoutSpecificInstruction = "LAYOUT STYLE: High-end Product Advertisement. Create a bold, commercial layout. Feature ONE main 'Hero Panel' significantly larger than the others to showcase the product/action. Arrange smaller panels as supporting details or inset shots. Use clean lines and ample negative space for implied text overlays."; break;
                case "newspaper": layoutSpecificInstruction = "LAYOUT STYLE: Classic Newspaper/Newsletter. Arrange panels in a strict, orderly grid or column-based structure. Use straight edges and consistent spacing, resembling a vintage Sunday comic strip or a formal news layout."; break;
                case "magazine": layoutSpecificInstruction = "LAYOUT STYLE: Modern Magazine Spread. Create a stylish, artistic layout. Use overlapping panels, varied aspect ratios, and dynamic composition typical of fashion or lifestyle magazines. Prioritize aesthetics and visual flow."; break;
                case "brochure": layoutSpecificInstruction = "LAYOUT STYLE: Informational Brochure/Pamphlet. Arrange panels in a clear, instructional sequence (step-by-step flow). Use distinct sections and a clean, easy-to-follow structure."; break;
                case "manga": layoutSpecificInstruction = "LAYOUT STYLE: Traditional Japanese Manga. Use dynamic diagonal cuts, vertical reading flow, and dramatic panel sizing. Focus on action lines and high-contrast composition."; break;
                case "cinematic": layoutSpecificInstruction = "LAYOUT STYLE: Cinematic Storyboard. Use wide, horizontal panels (widescreen aspect ratio) stacked vertically or arranged to mimic a film strip. Focus on panoramic views and dramatic sequence."; break;
                default: layoutSpecificInstruction = "LAYOUT STYLE: Dynamic Comic Book. Create a standard, engaging comic page layout. Use varying panel sizes to emphasize action. Avoid simple 2x2 grids; use creative framing."; break;
            }
            const panelPrompts = pageData.prompts.en;
            const panelPromptInstruction = panelPrompts.map((p, i) => `Panel ${i+1} content: ${p}`).join('; ');
            const prompt = `You are a professional layout designer. Your task is to combine the ${panelCount} provided images (Panels 1 to ${panelCount}) into a single, cohesive page layout.\n\nCRITICAL DIRECTIVE 1 (Panel Count & Content Fidelity): The final page MUST contain EXACTLY ${panelCount} panels. You MUST use the EXACT ORIGINAL IMAGE CONTENT of the provided images for each panel's visual information (Images 0 to ${panelCount-1}). ABSOLUTELY NO REDRAWING, INPAINTING, OR MODIFICATION of the characters, facial features, or internal details of the input panels. MAINTAIN 100% VISUAL FIDELITY.\n\nCRITICAL DIRECTIVE 2 (Layout Style): ${layoutSpecificInstruction}\n\nCRITICAL DIRECTIVE 3 (Format): The final image must strictly adhere to the ${aspectRatio} aspect ratio. ${borderInstruction}\n\nCRITICAL DIRECTIVE 4 (No Text): The final image MUST NOT contain any speech bubbles, text, or captions.\n\nStyle Context: ${styleInstruction}\n\nPanel Content Details: ${panelPromptInstruction}\n\nOutput: Return only the single, combined, dynamically laid out comic page image.`;
            const result = await callGeminiImageAPI(prompt, panelImageParts, { responseModalities: ["IMAGE"] }, IMAGE_MODEL);
            const finalImage = result?.candidates?.[0]?.content?.parts?.find(p => p.inlineData?.mimeType === 'image/png')?.inlineData?.data;
            return finalImage;
        }
        async function generateAILayoutWithEmptyBubbles(layoutBase64, bubbleStylePrompt, dialogueData) {
            const requiredBubbleCount = dialogueData.length;
            const dialogueInfo = dialogueData.map((d, index) => ({
                speaker: d.charName,
                position: { x: d.x_percent, y: d.y_percent, w: d.width_percent, h: d.height_percent },
                intent: `Text: ${d.text}. Speaker: ${d.charName}.`,
                shape: d.shape
            }));
            const prompt = `You are a comic book letterer. Your task is to overlay ONLY empty speech bubbles onto the provided comic page layout (Image 0).\n\nCRITICAL DIRECTIVE 1: BACKGROUND (MANDATORY): The FIRST image provided is the BACKGROUND. You MUST use this exact image as the background. You MUST NOT redraw, rearrange, or alter the panels or the layout structure. ABSOLUTELY NO REDRAWING OR DISTORTION OF CHARACTERS, FACIAL FEATURES, OR ANY EXISTING IMAGE CONTENT. MAINTAIN 100% VISUAL FIDELITY.\n\nCRITICAL DIRECTIVE 2: EXACT BUBBLE COUNT (MANDATORY): You MUST render EXACTLY ${requiredBubbleCount} empty speech bubbles on the page. The number of bubbles MUST precisely match the number of objects in the Dialogue Data JSON array below. The coordinate (0,0) is top-left, (100, 100) is bottom-right.\n\nCRITICAL DIRECTIVE 3: SMART PLACEMENT (FACE AVOIDANCE): Ensure that the placed bubbles DO NOT overlap with any character's face or critical details. Identify face locations and position the bubbles in open space near the speaker (or the target coordinates) without obstructing facial expressions.\n\nCRITICAL DIRECTIVE 4: BUBBLE SHAPES: Respect the 'shape' property for each bubble:\n- 'thought': Draw a cloud-like thought bubble.\n- 'shout': Draw a jagged, spiked burst bubble.\n- 'normal': Draw a smooth oval or round bubble.\n- 'rectangle': Draw a clean, sharp rectangular box with straight edges (often used for narration or captions).\n- 'automatic': Choose the most appropriate shape based on context.\n\nCRITICAL DIRECTIVE 5: DRAW EXTREMELY LARGE EMPTY BUBBLES (3X): The drawn bubble should be visually AT LEAST 300% LARGER (TRIPLE THE SIZE) than the specified bounding box (position: w, h) to guarantee the final text overlay fits comfortably. The bubble style MUST be: ${bubbleStylePrompt}. The final drawn bubble's center should be close to the coordinates provided by (position: x, y) but adjust slightly to AVOID FACES.\n\nCRITICAL DIRECTIVE 6: NO TEXT: The interior of all drawn bubbles MUST be completely EMPTY. Do NOT add any text, lettering, captions, or dialogue.\n\nDialogue Data (JSON) for bubble placement (Total Bubbles: ${requiredBubbleCount}): ${JSON.stringify(dialogueInfo)}\n\nOutput: Return only the final image with the exact background and the empty bubbles overlaid.`;
            const imageParts = [ { inlineData: { mimeType: "image/png", data: layoutBase64 } } ];
            const result = await callGeminiImageAPI(prompt, imageParts, { responseModalities: ["IMAGE"] }, IMAGE_MODEL);
            const finalImage = result?.candidates?.[0]?.content?.parts?.find(p => p.inlineData?.mimeType === 'image/png')?.inlineData?.data;
            return finalImage;
        }
        async function printFinalTextOnAILayout(pageData) {
            const base64Bg = pageData.base64_ai_layout_empty_text;
            interactiveDialogueArea.classList.add('final-capture-mode');
            let html = `<img src="data:image/png;base64,${base64Bg}" alt="AI Layout with Empty Bubbles" style="position: absolute; top: 0; left: 0; width: 100%; height: 100%; object-fit: contain;">`;
            pageData.dialogue.fullText.forEach(d => {
                const textEl = document.createElement('div');
                textEl.className = 'dialogue-box-final-text';
                textEl.style.left = `${d.x_percent}%`; textEl.style.top = `${d.y_percent}%`;
                textEl.style.width = `${d.width_percent}%`; textEl.style.height = `${d.height_percent}%`;
                const vw_size = (d.font_size / REFERENCE_CAPTURE_WIDTH_PX) * 100;
                textEl.style.fontFamily = d.font_family || pageData.fontValue;
                textEl.style.fontSize = `${vw_size}vw`;
                textEl.textContent = d.text;
                html += textEl.outerHTML;
            });
            interactiveDialogueArea.innerHTML = html;
            const finalCanvas = await html2canvas(interactiveDialogueArea, { allowTaint: true, useCORS: true, backgroundColor: null });
            const finalBase64 = finalCanvas.toDataURL('image/png').split(',')[1];
            interactiveDialogueArea.classList.remove('final-capture-mode');
            return finalBase64;
        }
        function resizeStart(e) {
            if (e.target.classList.contains('resize-handle')) e.stopPropagation();
            if (e.type === "touchstart") e.preventDefault();
            activeResizer = e.target;
            activeDraggableItem = activeResizer.closest('.dialogue-box-wrapper');
            const direction = activeResizer.dataset.direction;
            const clientX = e.type === "touchstart" ? e.touches[0].clientX : e.clientX;
            const clientY = e.type === "touchstart" ? e.touches[0].clientY : e.clientY;
            const rect = activeDraggableItem.getBoundingClientRect();
            const parentRect = interactiveDialogueArea.getBoundingClientRect();
            initialResizeInfo = {
                startX: clientX, startY: clientY, startW: rect.width, startH: rect.height,
                startL: rect.left - parentRect.left, startT: rect.top - parentRect.top, direction: direction
            };
            function resizeMove(e) {
                if (!activeResizer) return;
                if (e.type === "touchmove") e.preventDefault();
                const clientX = e.type === "touchmove" ? e.touches[0].clientX : e.clientX;
                const clientY = e.type === "touchmove" ? e.touches[0].clientY : e.clientY;
                const dx = clientX - initialResizeInfo.startX;
                const dy = clientY - initialResizeInfo.startY;
                let newW = initialResizeInfo.startW; let newH = initialResizeInfo.startH;
                let newL = initialResizeInfo.startL; let newT = initialResizeInfo.startT;
                const minW = 50; const minH = 20;
                if (direction.includes('right')) newW = Math.max(minW, initialResizeInfo.startW + dx);
                if (direction.includes('left')) {
                    newW = Math.max(minW, initialResizeInfo.startW - dx);
                    if (newW > minW) newL = initialResizeInfo.startL + dx; else newL = initialResizeInfo.startL + (initialResizeInfo.startW - minW);
                }
                if (direction.includes('bottom')) newH = Math.max(minH, initialResizeInfo.startH + dy);
                if (direction.includes('top')) {
                    newH = Math.max(minH, initialResizeInfo.startH - dy);
                    if (newH > minH) newT = initialResizeInfo.startT + dy; else newT = initialResizeInfo.startT + (initialResizeInfo.startH - minH);
                }
                newW = Math.min(newW, parentRect.width - newL); newH = Math.min(newH, parentRect.height - newT);
                newL = Math.max(0, newL); newT = Math.max(0, newT);
                const leftPercent = (newL / parentRect.width) * 100; const topPercent = (newT / parentRect.height) * 100;
                const widthPercent = (newW / parentRect.width) * 100; const heightPercent = (newH / parentRect.height) * 100;
                activeDraggableItem.style.width = `${widthPercent}%`; activeDraggableItem.style.height = `${heightPercent}%`;
                activeDraggableItem.style.left = `${leftPercent}%`; activeDraggableItem.style.top = `${topPercent}%`;
                activeDraggableItem.dataset.widthPercent = widthPercent.toFixed(2);
                activeDraggableItem.dataset.heightPercent = heightPercent.toFixed(2);
                window.autoResizeBox(activeDraggableItem);
            }
            function resizeEnd() {
                activeResizer = null; activeDraggableItem = null;
                document.removeEventListener('mousemove', resizeMove); document.removeEventListener('mouseup', resizeEnd);
                document.removeEventListener('touchmove', resizeMove); document.removeEventListener('touchend', resizeEnd);
            }
            document.addEventListener('mousemove', resizeMove); document.addEventListener('mouseup', resizeEnd);
            document.addEventListener('touchmove', resizeMove, { passive: false }); document.addEventListener('touchend', resizeEnd);
        }
        function dragStart(e) {
            if (e.target.classList.contains('resize-handle')) return;
            if (e.touches && e.touches.length > 1) return;
            if (e.type === "touchstart") e.preventDefault();
            activeDraggableItem = e.target.closest('.dialogue-box-wrapper');
            if (!activeDraggableItem) return;
            const clientX = e.type === "touchstart" ? e.touches[0].clientX : e.clientX;
            const clientY = e.type === "touchstart" ? e.touches[0].clientY : e.clientY;
            const rect = activeDraggableItem.getBoundingClientRect();
            const parentRect = activeDraggableItem.parentElement.getBoundingClientRect();
            const xOffset = clientX - rect.left;
            const yOffset = clientY - rect.top;
            function drag(e) {
                if (activeDraggableItem) {
                    if (e.type === "touchmove") e.preventDefault();
                    const clientX = e.type === "touchmove" ? e.touches[0].clientX : e.clientX;
                    const clientY = e.type === "touchmove" ? e.touches[0].clientY : e.clientY;
                    let newX = clientX - xOffset; let newY = clientY - yOffset;
                    let relativeX = newX - parentRect.left; let relativeY = newY - parentRect.top;
                    relativeX = Math.max(0, relativeX); relativeX = Math.min(relativeX, parentRect.width - activeDraggableItem.offsetWidth);
                    relativeY = Math.max(0, relativeY); relativeY = Math.min(relativeY, parentRect.height - activeDraggableItem.offsetHeight);
                    const leftPercent = (relativeX / parentRect.width) * 100;
                    const topPercent = (relativeY / parentRect.height) * 100;
                    activeDraggableItem.style.left = `${leftPercent}%`; activeDraggableItem.style.top = `${topPercent}%`;
                }
            }
            function dragEnd() {
                if (activeDraggableItem && activeDraggableItem.classList.contains('dialogue-box-wrapper')) {
                    const parentRect = interactiveDialogueArea.getBoundingClientRect();
                    const boxRect = activeDraggableItem.getBoundingClientRect();
                    const width_percent = boxRect.width / parentRect.width * 100;
                    const height_percent = boxRect.height / parentRect.height * 100;
                    activeDraggableItem.dataset.widthPercent = width_percent.toFixed(2);
                    activeDraggableItem.dataset.heightPercent = height_percent.toFixed(2);
                    const panelCount = tempNewPage.prompts.en.length;
                    if (!isFinalReviewMode) {
                        const newPanelIndex = getPanelIndexFromCoords(
                            boxRect.left - parentRect.left + boxRect.width / 2,
                            boxRect.top - parentRect.top + boxRect.height / 2,
                            parentRect.width, parentRect.height, panelCount
                        );
                        if (parseInt(activeDraggableItem.dataset.panelIndex, 10) !== newPanelIndex) {
                            activeDraggableItem.dataset.panelIndex = newPanelIndex;
                            const dialogueId = activeDraggableItem.id;
                            const staticInputEl = dialogueInputsContainer.querySelector(`.dialogue-sync-input[data-target-id="${dialogueId}"]`);
                            if (staticInputEl) {
                                const staticInputLabel = staticInputEl.closest('.flex-grow').querySelector('label');
                                if (staticInputLabel) {
                                    const charName = activeDraggableItem.dataset.charName === 'Generic' ? 'Lời thoại chung' : activeDraggableItem.dataset.charName;
                                    staticInputLabel.textContent = `${charName} (Cảnh ${newPanelIndex + 1}):`;
                                }
                                displayToast(`Lời thoại của ${activeDraggableItem.dataset.charName} đã được chuyển sang Cảnh ${newPanelIndex + 1}.`, 'bg-blue-500');
                            }
                        }
                    }
                }
                activeDraggableItem = null;
                document.removeEventListener('mousemove', drag); document.removeEventListener('mouseup', dragEnd);
                document.removeEventListener('touchmove', drag); document.removeEventListener('touchend', dragEnd);
            }
            document.addEventListener('mousemove', drag); document.addEventListener('mouseup', dragEnd);
            document.addEventListener('touchmove', drag, { passive: false }); document.addEventListener('touchend', dragEnd);
        }
        async function generateFallbackGrid(panelBase64s, pageData) {
            return new Promise((r, j) => {
                try {
                    const panelCount = panelBase64s.length;
                    const aspectRatio = pageData.settings.aspectRatio.replace(':', '/');
                    const [ratioX, ratioY] = aspectRatio.split('/').map(Number);
                    const canvasWidth = 1000;
                    const canvasHeight = Math.floor(canvasWidth * (ratioY / ratioX));
                    const canvas = document.createElement('canvas');
                    canvas.width = canvasWidth; canvas.height = canvasHeight;
                    const ctx = canvas.getContext('2d');
                    ctx.fillStyle = 'white'; ctx.fillRect(0, 0, canvasWidth, canvasHeight);
                    const gutter = (pageData.settings.borderStyle !== 'no borders') ? 10 : 0;
                    let panelCoords = [];
                    const count = Math.min(panelCount, 4);
                    const coords = FALLBACK_GRIDS[count] || FALLBACK_GRIDS[1];
                    const cols = coords.cols; const rows = coords.rows;
                    const w = (canvasWidth - (cols + 1) * gutter) / cols;
                    const h = (canvasHeight - (rows + 1) * gutter) / rows;
                    for(let i = 0; i < panelCount; i++) {
                        if (i >= 4) break;
                        const col = i % cols; const row = Math.floor(i / cols);
                        panelCoords.push({ x: gutter * (col + 1) + w * col, y: gutter * (row + 1) + h * row, w: w, h: h });
                    }
                    let loadedCount = 0;
                    panelBase64s.forEach((base64, index) => {
                        if (index >= 4) return;
                        if (base64) {
                            const img = new Image();
                            img.onload = () => {
                                try {
                                    const coord = panelCoords[index];
                                    if (coord) {
                                        ctx.drawImage(img, coord.x, coord.y, coord.w, coord.h);
                                        if (pageData.settings.borderStyle === 'classic black' || pageData.settings.borderStyle === 'colored borders') {
                                            ctx.strokeStyle = (pageData.settings.borderStyle === 'classic black') ? 'black' : '#888';
                                            ctx.lineWidth = 4; ctx.strokeRect(coord.x, coord.y, coord.w, coord.h);
                                        }
                                    }
                                } catch (error) {
                                    console.error(`Lỗi vẽ ảnh panel ${index+1}:`, error);
                                    const coord = panelCoords[index];
                                    if (coord) {
                                        ctx.fillStyle = '#fef3c7'; ctx.fillRect(coord.x, coord.y, coord.w, coord.h);
                                        ctx.font = '30px Inter, sans-serif'; ctx.fillStyle = '#d97706'; ctx.textAlign = 'center';
                                        ctx.fillText(`Cảnh ${index + 1}: Lỗi Ảnh`, coord.x + coord.w / 2, coord.y + coord.h / 2);
                                    }
                                }
                                loadedCount++;
                                if (loadedCount === panelCount || loadedCount === 4) { r(canvas.toDataURL('image/png').split(',')[1]); }
                            };
                            img.onerror = (e) => {
                                console.error(`Lỗi tải ảnh panel ${index+1}:`, e);
                                const coord = panelCoords[index];
                                if (coord) {
                                    ctx.fillStyle = '#fef3c7'; ctx.fillRect(coord.x, coord.y, coord.w, coord.h);
                                    ctx.font = '30px Inter, sans-serif'; ctx.fillStyle = '#d97706'; ctx.textAlign = 'center';
                                    ctx.fillText(`Cảnh ${index + 1}: Lỗi Tải Ảnh`, coord.x + coord.w / 2, coord.y + coord.h / 2);
                                }
                                loadedCount++;
                                if (loadedCount === panelCount || loadedCount === 4) { r(canvas.toDataURL('image/png').split(',')[1]); }
                            };
                            img.src = `data:image/png;base64,${base64}`;
                        } else {
                            const coord = panelCoords[index];
                            if (coord) {
                                ctx.fillStyle = '#fef3c7'; ctx.fillRect(coord.x, coord.y, coord.w, coord.h);
                                ctx.font = '30px Inter, sans-serif'; ctx.fillStyle = '#d97706'; ctx.textAlign = 'center';
                                ctx.fillText(`Cảnh ${index + 1}: Lỗi Ảnh`, coord.x + coord.w / 2, coord.y + coord.h / 2);
                            }
                            loadedCount++;
                            if (loadedCount === panelCount || loadedCount === 4) { r(canvas.toDataURL('image/png').split(',')[1]); }
                        }
                    });
                } catch (error) { console.error("Lỗi trong generateFallbackGrid:", error); j(new Error(`Lỗi kết hợp ảnh: ${error.message}`)); }
            });
        }
        async function startDialogueEditing(pageData) {
            isFinalReviewMode = false; tempNewPage = pageData;
            creationPanelEl.classList.add('hidden'); charSetupPanel.classList.add('hidden'); dialogueEditPanel.classList.remove('hidden'); storyboardEl.classList.add('lg:col-span-1');
            dialoguePanelTitle.textContent = "Bước 4: Tạo Bong bóng Rỗng & Lời Thoại (Đặt vị trí Thô)";
            dialogueInstruction.innerHTML = '<span class="font-bold text-yellow-800">HƯỚNG DẪN:</span> Kéo **bong bóng thoại** đến vị trí mong muốn. Kéo các **góc tròn màu xanh** để **thay đổi kích thước** thủ công. Bố cục trang truyện này chỉ là **LƯỚI DỰ PHÒNG** để bạn đặt tọa độ. Bố cục **AI Động** sẽ được tạo sau bước này.';
            finalizeAILayoutBtn.classList.remove('hidden'); useFallbackLayoutBtn.classList.remove('hidden');
            captureFinalPageBtn.classList.add('hidden');
            interactiveDialogueArea.classList.remove('final-review-mode');
            document.getElementById('back-from-dialogue-btn').textContent = 'Quay lại (Bước 3)';
            interactiveDialogueArea.innerHTML = '';
            const img = document.createElement('img');
            img.src = `data:image/png;base64,${pageData.base64_composed_no_bubbles}`;
            img.alt = "Generated Comic Page for Dialogue Placement (Fallback Grid)";
            img.id = 'base-grid-image';
            img.style.width = '100%'; img.style.height = '100%'; img.style.objectFit = 'contain';
            interactiveDialogueArea.appendChild(img);
            interactiveDialogueArea.style.aspectRatio = pageData.settings.aspectRatio.replace(':', ' / ');
            dialogueInputsContainer.innerHTML = '';
            const hasExistingDialogue = pageData.dialogue && pageData.dialogue.fullText && pageData.dialogue.fullText.length > 0;
            if (hasExistingDialogue) {
                if (pageData.fontValue) fontSelectEl.value = pageData.fontValue;
                pageData.dialogue.fullText.forEach(async dialogue => {
                    const fontSize = dialogue.font_size || DEFAULT_FONT_SIZE_PX;
                    const shape = dialogue.shape || 'automatic';
                    createDialogueBox(dialogue.panelIndex, dialogue.charName, dialogue.text, fontSize, isFinalReviewMode, shape);
                });
            } else {
                let totalSpeakers = 0;
                const panelPrompts = pageData.prompts.vi || [];
                const speakersData = pageData.speakersPerPanel || [];
                for (const [pIdx, speakers] of speakersData.entries()) {
                    if (speakers.length > 0) {
                        totalSpeakers += speakers.length;
                        const promptText = panelPrompts[pIdx] || '';
                        const charactersInScene = speakers;
                        for (const charName of speakers) {
                            let initialText = '';
                            const autoFillNormal = pageData.autoFillDialogue || false;
                            const autoFillFeatures = pageData.autoFillProductFeatures || false;
                            if (autoFillFeatures && promptText) {
                                dialogueLoadingMessageEl.textContent = `Đang trích xuất tính năng cho cảnh ${pIdx + 1}...`;
                                initialText = await generateProductFeatureFromPrompt(promptText);
                            } else if (autoFillNormal && promptText) {
                                dialogueLoadingMessageEl.textContent = `Đang tạo lời thoại cho ${charName} ở cảnh ${pIdx + 1}...`;
                                initialText = await generateDialogueFromPrompt(promptText, charName, charactersInScene);
                            }
                            createDialogueBox(pIdx, charName, initialText, DEFAULT_FONT_SIZE_PX, isFinalReviewMode, 'automatic');
                        }
                    }
                }
                if (totalSpeakers === 0) { dialogueInputsContainer.innerHTML = '<p class="text-gray-500 italic">Không có nhân vật thoại nào được yêu cầu. Bạn có thể thêm lời thoại chung nếu cần.</p>'; }
            }
            fontSelectEl.onchange = updatePreviewFont; updatePreviewFont();
            interactiveDialogueArea.querySelectorAll('.dialogue-box-wrapper').forEach(registerDragAndResizeListeners);
            displayToast('Bước 4: Kéo bong bóng thoại và nhập lời thoại. Điều chỉnh cỡ chữ.','bg-indigo-500');
            dialogueLoadingMessageEl.textContent = 'Đang xử lý...';
        }
        async function goBackToFinalDialogueReview(pageData) {
            isFinalReviewMode = true; tempNewPage = pageData;
            creationPanelEl.classList.add('hidden'); charSetupPanel.classList.add('hidden'); dialogueEditPanel.classList.remove('hidden'); storyboardEl.classList.add('lg:col-span-1');
            dialoguePanelTitle.textContent = "Bước 4: Xem lại & Hoàn tất (Bố cục AI Động/Cơ bản)";
            dialogueInstruction.innerHTML = '<span class="font-bold text-teal-800">FINAL REVIEW:</span> AI đã tạo bố cục và vẽ bong bóng rỗng. Vui lòng **kéo/chỉnh kích thước lần cuối** để vùng text khớp với hình bong bóng trên ảnh nền. <span class="font-bold text-red-800">HÃY CHẮC CHẮN!</span>';
            finalizeAILayoutBtn.classList.add('hidden'); useFallbackLayoutBtn.classList.add('hidden');
            captureFinalPageBtn.classList.remove('hidden');
            interactiveDialogueArea.classList.add('final-review-mode');
            document.getElementById('back-from-dialogue-btn').textContent = 'Quay lại Chỉnh sửa Layout Thô';
            interactiveDialogueArea.innerHTML = '';
            const img = document.createElement('img');
            img.src = `data:image/png;base64,${pageData.base64_ai_layout_empty_text}`;
            img.alt = "AI Layout with Empty Bubbles (Final Review)";
            img.id = 'ai-layout-image';
            img.style.width = '100%'; img.style.height = '100%'; img.style.objectFit = 'contain';
            interactiveDialogueArea.appendChild(img);
            interactiveDialogueArea.style.aspectRatio = pageData.settings.aspectRatio.replace(':', ' / ');
            dialogueInputsContainer.innerHTML = '';
            dialogueIdCounter = 0;
            if (pageData.fontValue) fontSelectEl.value = pageData.fontValue;
            const dialogueDataCopy = JSON.parse(JSON.stringify(pageData.dialogue.fullText));
            tempNewPage.dialogue.fullText = [];
            dialogueDataCopy.forEach(dialogue => {
                const fontSize = dialogue.font_size || DEFAULT_FONT_SIZE_PX;
                const shape = dialogue.shape || 'automatic';
                createDialogueBox(dialogue.panelIndex, dialogue.charName, dialogue.text, fontSize, isFinalReviewMode, shape);
            });
            fontSelectEl.onchange = updatePreviewFont; updatePreviewFont();
            interactiveDialogueArea.querySelectorAll('.dialogue-box-wrapper').forEach(registerDragAndResizeListeners);
            displayToast('BƯỚC REVIEW: Di chuyển/Chỉnh kích thước vùng text để khớp với bong bóng AI đã vẽ.', 'bg-teal-600');
        }
        function updatePreviewFont() {
            const selectedFont = fontSelectEl.value;
            if (tempNewPage) tempNewPage.fontValue = selectedFont;
            document.querySelectorAll('.dialogue-box-wrapper').forEach(wrapper => {
                const ta = wrapper.querySelector('textarea'); const staticContent = wrapper.querySelector('.dialogue-box-static-content');
                wrapper.dataset.fontFamily = selectedFont;
                if (ta) ta.style.fontFamily = selectedFont;
                if (staticContent) staticContent.style.fontFamily = selectedFont;
                const dialogueId = wrapper.dataset.dialogueId;
                const dialogueEntry = tempNewPage?.dialogue?.fullText.find(d => d.dialogueId === dialogueId);
                if (dialogueEntry) { dialogueEntry.font_family = selectedFont; }
                window.autoResizeBox(wrapper);
            });
            displayToast(`Đã đổi font chữ thành ${fontSelectEl.options[fontSelectEl.selectedIndex].text}`, 'bg-gray-500');
        }
        fontSelectEl.onchange = updatePreviewFont;
        function displayToast(message, bgColor = 'bg-gray-800') {
            messageToast.textContent = message;
            messageToast.className = `fixed bottom-6 right-6 ${bgColor} text-white py-3 px-6 rounded-full shadow-2xl transition-all duration-300 transform scale-100 opacity-100 font-medium z-[3000]`;
            setTimeout(() => { messageToast.className = `fixed bottom-6 right-6 bg-gray-800 text-white py-3 px-6 rounded-full shadow-2xl transition-all duration-300 transform scale-0 opacity-0 font-medium z-[3000]`; }, 3000);
        }
        captureFinalPageBtn.addEventListener('click', async () => {
            if (!tempNewPage || !tempNewPage.base64_ai_layout_empty_text) return;
            captureFinalPageBtn.disabled = true;
            dialogueLoadingIndicator.classList.remove('hidden');
            dialogueLoadingMessageEl.textContent = 'Đang in văn bản lên bố cục cuối cùng...';
            try {
                const finalDialogueData = collectDialogueDataFromUI();
                tempNewPage.dialogue.fullText = finalDialogueData;
                const finalImageWithTextBase64 = await printFinalTextOnAILayout(tempNewPage);
                if (finalImageWithTextBase64) {
                    tempNewPage.imageUrl = `data:image/png;base64,${finalImageWithTextBase64}`;
                    const editingPageId = editingPageIdInput.value;
                    if (editingPageId) {
                        const index = storyPages.findIndex(p => p.id === editingPageId);
                        if (index !== -1) { storyPages[index] = { ...tempNewPage, id: editingPageId }; displayToast(`Đã cập nhật Trang ${editingPageId.split('-')[1]} thành công!`, 'bg-green-600'); }
                        else { displayToast('Lỗi: Không tìm thấy trang để cập nhật.', 'bg-red-700'); }
                        editingPageIdInput.value = '';
                    } else { finalizePage(tempNewPage); }
                    goBackToCreationPanel();
                    renderStoryPages();
                } else { displayToast('Lỗi khi in văn bản lên ảnh. Vui lòng thử lại.', 'bg-red-700'); }
            } catch (error) {
                console.error("Lỗi khi hoàn tất trang truyện:", error);
                displayToast(`Lỗi: ${error.message}. Vui lòng thử lại.`, 'bg-red-700');
            } finally { captureFinalPageBtn.disabled = false; dialogueLoadingIndicator.classList.add('hidden'); }
        });
        function finalizePage(pageData) {
            if (!pageData || !pageData.imageUrl) { displayToast('Lỗi: Dữ liệu trang truyện không đầy đủ.', 'bg-red-700'); return; }
            pageData.id = `page-${pageCounter++}`;
            storyPages.push(pageData);
            promptsContainerEl.innerHTML = '';
            addPromptInput();
            continueAllScenesBtn.disabled = false;
            continueSequentialScenesBtn.disabled = false;
            displayToast(`Đã tạo trang truyện ${pageData.id} thành công!`, 'bg-green-600');
        }
        function renderStoryPages() {
            const existingPages = storyboardEl.querySelectorAll('.story-page:not(#intro-card)');
            existingPages.forEach(p => p.remove());
            if (storyPages.length > 0) { introCard.classList.add('hidden'); }
            const fragment = document.createDocumentFragment();
            storyPages.forEach(page => {
                const card = document.createElement('div');
                card.id = page.id; card.className = 'story-page space-y-4';
                const panelCount = page.prompts.vi.length;
                const aspectRatio = page.settings.aspectRatio.replace(':', ' / ');
                const layoutType = page.base64_ai_layout_no_bubbles === page.base64_composed_no_bubbles ? 'Lưới Cơ bản' : 'AI Động';
                card.innerHTML = `<h3 class="text-2xl font-bold text-gray-800 border-b pb-2 mb-3">Trang Truyện ${page.id.split('-')[1]} (${panelCount} Cảnh)</h3><div class="final-page-composite" style="aspect-ratio: ${aspectRatio};"><img src="${page.imageUrl}" alt="Hoàn thành trang truyện ${page.id}" class="w-full h-full object-contain"></div><div class="p-3 bg-gray-50 rounded-lg border border-gray-200"><p class="text-sm font-semibold text-gray-700 mb-1">Tóm tắt Cảnh:</p><ul class="list-disc list-inside text-sm text-gray-600 space-y-1 ml-4">${page.prompts.vi.map((p, i) => `<li>Cảnh ${i+1}: ${p}</li>`).join('')}</ul><p class="text-xs text-gray-400 mt-2">Bố cục: ${layoutType}</p></div><div class="flex justify-end gap-2 pt-2 border-t border-gray-100 flex-wrap"><button class="edit-page-btn bg-yellow-500 hover:bg-yellow-600 text-white text-sm font-semibold py-2 px-4 rounded-lg transition duration-200 shadow-md transform hover:scale-105" data-page-id="${page.id}">Quay lại Chỉnh sửa Trang</button><button class="use-as-input-btn bg-blue-500 hover:bg-blue-600 text-white text-sm font-semibold py-2 px-4 rounded-lg transition duration-200 shadow-md transform hover:scale-105" data-page-id="${page.id}">Làm ảnh đầu vào</button><button class="download-page-btn bg-teal-500 hover:bg-teal-600 text-white text-sm font-semibold py-2 px-4 rounded-lg transition duration-200 shadow-md transform hover:scale-105" data-page-id="${page.id}">Tải xuống PNG</button><button class="save-page-lib-btn bg-purple-500 hover:bg-purple-600 text-white text-sm font-semibold py-2 px-4 rounded-lg transition duration-200 shadow-md transform hover:scale-105" data-page-id="${page.id}">Lưu Trang vào Thư viện</button></div>`;
                fragment.appendChild(card);
            });
            const firstChild = storyboardEl.querySelector('#intro-card') || null;
            if (firstChild && !firstChild.classList.contains('hidden')) { storyboardEl.insertBefore(fragment, firstChild.nextSibling); }
            else { storyboardEl.appendChild(fragment); }
            storyboardEl.querySelectorAll('.download-page-btn').forEach(btn => {
                btn.addEventListener('click', (e) => {
                    const pageId = e.target.dataset.pageId;
                    const pageData = storyPages.find(p => p.id === pageId);
                    if (pageData && pageData.imageUrl) { const link = document.createElement('a'); link.href = pageData.imageUrl; link.download = `comic_page_${pageId}.png`; link.click(); }
                    else { displayToast('Không tìm thấy ảnh để tải xuống.', 'bg-red-500'); }
                });
            });
            storyboardEl.querySelectorAll('.save-page-lib-btn').forEach(btn => {
                btn.addEventListener('click', (e) => {
                    const pageId = e.target.dataset.pageId; const pageData = storyPages.find(p => p.id === pageId);
                    if (pageData && pageData.imageUrl) {
                        const base64Data = pageData.imageUrl.split(',')[1]; const prompts = pageData.prompts.vi;
                        imageLibrary.push({ base64: base64Data, prompts: { en: pageData.prompts.en, vi: prompts } });
                        renderImageLibrary(); displayToast(`Đã lưu Trang ${pageId.split('-')[1]} vào Thư viện!`, 'bg-green-500');
                    } else { displayToast('Không tìm thấy dữ liệu trang để lưu.', 'bg-red-500'); }
                });
            });
            storyboardEl.querySelectorAll('.use-as-input-btn').forEach(btn => {
                btn.addEventListener('click', (e) => {
                    const pageId = e.target.dataset.pageId; const pageData = storyPages.find(p => p.id === pageId);
                    if (pageData && pageData.imageUrl) {
                        const base64Data = pageData.imageUrl.split(',')[1]; const id = `input-img-page-${pageId}`;
                        inputImages.set(id, base64Data); renderInputImage(base64Data, id); updateInputImageContainer();
                        displayToast(`Đã thêm Trang ${pageId.split('-')[1]} vào mục Ảnh Đầu Vào.`, 'bg-blue-500');
                    } else { displayToast('Không tìm thấy dữ liệu ảnh của trang này.', 'bg-red-500'); }
                });
            });
            storyboardEl.querySelectorAll('.edit-page-btn').forEach(btn => {
                btn.addEventListener('click', (e) => {
                    const pageId = e.target.dataset.pageId; const pageData = storyPages.find(p => p.id === pageId);
                    if (pageData) { editingPageIdInput.value = pageId; goBackToFinalDialogueReview(pageData); displayToast(`Đang chỉnh sửa lại Trang ${pageId.split('-')[1]}. Vui lòng nhấn "HOÀN TẤT" sau khi xong.`, 'bg-yellow-600'); }
                    else { displayToast('Không tìm thấy dữ liệu trang để chỉnh sửa.', 'bg-red-500'); }
                });
            });
        }
        introCard.classList.remove('hidden');
        creationPanelEl.classList.add('hidden');
        dialogueEditPanel.classList.add('hidden');
        charSetupPanel.classList.add('hidden');
        storyboardEl.classList.remove('lg:col-span-1');
        updateInputImageContainer();
        renderImageLibrary();
    </script>
</body>
</html>