Spaces:
Sleeping

File size: 85,568 Bytes
9713441
e602d40
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9713441
 
 
 
 
 
 
 
 
 
 
 
e602d40
9713441
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e602d40
9713441
e602d40
9713441
 
e602d40
9713441
 
 
 
 
 
 
 
e602d40
9713441
 
 
 
e602d40
9713441
 
 
 
 
 
e602d40
 
9713441
e602d40
9713441
e602d40
 
 
9713441
e602d40
9713441
e602d40
9713441
e602d40
9713441
e602d40
9713441
e602d40
9713441
 
e602d40
9713441
e602d40
 
 
 
 
 
 
 
9713441
 
 
 
e602d40
9713441
e602d40
 
9713441
 
e602d40
 
9713441
 
 
 
 
 
 
e602d40
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9713441
 
 
 
e602d40
 
9713441
 
 
 
 
e602d40
9713441
 
 
 
 
 
 
 
 
 
 
e602d40
9713441
 
e602d40
 
 
 
 
 
 
 
 
 
 
9713441
 
 
 
 
 
 
e602d40
9713441
e602d40
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9713441
 
e602d40
9713441
e602d40
9713441
 
e602d40
 
 
9713441
 
 
e602d40
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9713441
e602d40
9713441
 
 
e602d40
9713441
e602d40
9713441
 
 
 
 
 
 
 
 
 
 
e602d40
9713441
e602d40
9713441
e602d40
 
 
 
 
9713441
 
e602d40
 
9713441
 
 
e602d40
9713441
e602d40
 
9713441
 
e602d40
 
 
9713441
 
 
 
 
e602d40
9713441
 
e602d40
9713441
 
 
 
e602d40
9713441
 
 
 
e602d40
9713441
 
 
 
 
 
 
 
 
 
 
e602d40
9713441
e602d40
 
9713441
 
 
 
 
 
 
 
e602d40
9713441
 
 
 
 
 
 
e602d40
9713441
 
 
e602d40
9713441
 
e602d40
9713441
 
 
e602d40
9713441
e602d40
 
9713441
 
e602d40
 
9713441
 
 
 
e602d40
9713441
e602d40
 
9713441
 
e602d40
 
9713441
 
 
 
 
 
e602d40
9713441
 
 
 
 
 
 
e602d40
9713441
 
 
e602d40
 
 
9713441
e602d40
 
 
9713441
 
 
 
 
e602d40
9713441
e602d40
9713441
 
 
 
 
e602d40
9713441
e602d40
 
 
9713441
 
 
 
e602d40
9713441
 
 
 
 
e602d40
9713441
 
 
 
 
 
 
 
 
 
e602d40
9713441
 
 
 
 
 
e602d40
9713441
 
 
e602d40
9713441
 
 
 
 
 
 
 
e602d40
9713441
e602d40
 
9713441
 
e602d40
 
 
 
 
 
 
 
 
 
 
 
9713441
 
 
 
 
 
e602d40
9713441
 
 
 
 
e602d40
9713441
 
 
 
e602d40
9713441
 
 
 
 
 
e602d40
9713441
 
 
 
 
e602d40
9713441
 
 
 
e602d40
9713441
 
 
 
 
 
e602d40
9713441
 
 
 
e602d40
9713441
e602d40
 
9713441
 
e602d40
 
9713441
 
 
 
 
 
 
e602d40
9713441
 
 
 
 
 
 
 
 
 
e602d40
9713441
e602d40
 
9713441
 
e602d40
9713441
e602d40
 
 
9713441
e602d40
9713441
e602d40
9713441
 
 
 
 
 
e602d40
9713441
e602d40
 
9713441
 
e602d40
 
 
9713441
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e602d40
 
 
9713441
e602d40
9713441
 
 
e602d40
9713441
e602d40
9713441
 
 
e602d40
 
 
 
 
 
 
9713441
 
 
 
 
 
e602d40
 
 
 
 
 
 
 
 
9713441
 
e602d40
9713441
 
 
 
 
e602d40
9713441
e602d40
 
9713441
 
 
e602d40
 
 
 
 
 
 
9713441
e602d40
9713441
e602d40
 
9713441
 
e602d40
 
 
9713441
 
 
 
 
 
 
 
 
 
 
e602d40
9713441
 
 
 
 
 
 
 
 
e602d40
 
9713441
 
e602d40
9713441
e602d40
 
9713441
 
e602d40
9713441
 
 
 
 
 
 
 
e602d40
9713441
 
 
 
 
 
 
 
 
e602d40
 
 
 
9713441
 
 
 
 
 
 
 
e602d40
9713441
e602d40
 
 
 
 
 
 
 
 
 
 
9713441
 
 
 
 
 
 
 
 
e602d40
9713441
 
e602d40
 
 
 
 
 
 
 
9713441
 
 
 
e602d40
 
9713441
 
 
 
 
 
 
 
 
 
 
e602d40
9713441
e602d40
9713441
 
 
 
 
 
 
 
 
 
 
 
e602d40
9713441
 
e602d40
9713441
 
 
 
 
 
 
 
e602d40
9713441
 
e602d40
9713441
 
 
 
 
 
 
e602d40
9713441
 
e602d40
 
9713441
 
 
 
 
 
 
e602d40
9713441
 
e602d40
 
9713441
 
 
 
 
 
 
e602d40
9713441
 
e602d40
9713441
 
 
 
 
 
 
 
 
e602d40
9713441
 
 
 
 
 
 
 
 
e602d40
9713441
 
 
 
 
 
e602d40
9713441
 
e602d40
9713441
 
 
 
 
 
 
 
 
 
e602d40
9713441
 
 
 
 
e602d40
 
 
9713441
 
 
 
 
e602d40
9713441
 
 
 
 
 
 
 
 
e602d40
 
 
9713441
 
 
 
 
e602d40
 
 
9713441
 
 
 
 
 
 
 
 
 
e602d40
9713441
 
e602d40
9713441
 
 
 
 
 
 
 
 
 
 
e602d40
9713441
 
 
 
 
 
 
 
 
e602d40
 
9713441
 
 
e602d40
 
 
 
9713441
 
 
 
 
 
 
 
 
e602d40
9713441
e602d40
 
9713441
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e602d40
9713441
 
e602d40
9713441
 
 
 
e602d40
9713441
e602d40
 
9713441
 
e602d40
 
 
 
9713441
e602d40
 
9713441
 
e602d40
 
 
9713441
 
 
 
e602d40
9713441
e602d40
9713441
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e602d40
9713441
e602d40
 
 
9713441
 
 
 
 
 
 
e602d40
9713441
e602d40
 
9713441
 
e602d40
9713441
 
 
 
 
 
 
 
e602d40
9713441
e602d40
 
 
9713441
 
 
 
 
 
 
 
 
e602d40
9713441
e602d40
9713441
 
e602d40
9713441
 
 
 
 
 
 
 
 
 
 
e602d40
9713441
e602d40
9713441
e602d40
9713441
 
e602d40
 
 
9713441
 
 
 
 
 
 
 
 
 
 
 
e602d40
9713441
 
 
 
 
 
 
e602d40
 
 
9713441
 
 
 
 
 
 
 
e602d40
 
 
9713441
 
 
 
 
 
e602d40
9713441
e602d40
 
9713441
 
 
 
e602d40
9713441
e602d40
 
9713441
 
 
 
 
 
 
e602d40
 
9713441
 
 
 
 
 
 
e602d40
 
 
9713441
e602d40
9713441
e602d40
9713441
 
 
 
 
 
 
 
 
 
e602d40
9713441
 
 
 
e602d40
 
9713441
 
e602d40
9713441
 
e602d40
9713441
 
 
 
 
 
 
 
 
 
 
 
 
 
e602d40
 
9713441
e602d40
9713441
e602d40
 
 
 
 
 
9713441
e602d40
9713441
 
 
e602d40
9713441
e602d40
 
9713441
 
e602d40
 
 
9713441
 
 
e602d40
9713441
e602d40
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9713441
 
 
 
 
e602d40
9713441
 
 
 
 
 
 
 
 
 
 
e602d40
9713441
e602d40
9713441
 
 
 
 
e602d40
9713441
 
 
 
e602d40
9713441
 
e602d40
 
 
 
9713441
 
 
 
 
 
 
 
 
 
e602d40
9713441
 
 
 
 
 
e602d40
9713441
 
e602d40
9713441
e602d40
9713441
 
 
e602d40
 
 
 
 
 
 
9713441
 
 
 
 
 
e602d40
9713441
 
 
 
 
 
 
 
e602d40
9713441
e602d40
9713441
e602d40
9713441
 
 
e602d40
 
 
 
 
9713441
 
 
 
 
 
 
e602d40
9713441
 
 
 
 
 
 
 
e602d40
9713441
e602d40
9713441
e602d40
9713441
 
 
e602d40
 
 
9713441
 
 
 
 
 
 
 
 
 
 
 
e602d40
 
 
9713441
e602d40
 
 
 
 
9713441
e602d40
9713441
 
 
e602d40
9713441
e602d40
 
9713441
 
e602d40
 
 
9713441
e602d40
9713441
 
 
 
 
 
 
 
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
import React, { useState, useEffect, useRef } from 'react';
import {
  Film,
  Mic,
  Volume2,
  Square,
  Play,
  RefreshCw,
  ArrowUp,
  ArrowDown,
  Copy,
  Plus,
  Trash2,
  Sparkles,
  Wand2,
  Code2,
  Download,
  Smartphone,
  Monitor,
  Square as SquareIcon,
  Image as ImageIcon,
  Globe,
  Search,
  FolderOpen,
  Clock,
  CheckCircle2,
  Sliders,
  History,
  Cloud,
  Laptop,
  X,
  Lock,
  Link2,
  LayoutTemplate,
  Zap,
  Scissors,
  Tag,
} from 'lucide-react';
import { api } from '../api';
import type {
  Project,
  ScenePacket,
  AssetItem,
  BrandKit,
  FrozenRecipe,
  AIProviderProfile,
  RenderJob,
  AspectRatio,
  SceneRole,
} from '@olokaflow/shared';
import { Button, Badge } from './ui/primitives';

interface Props {
  projects: Project[];
  activeProject: Project | null;
  catalog: any;
  brands: BrandKit[];
  recipes: FrozenRecipe[];
  profiles: AIProviderProfile[];
  assets: AssetItem[];
  onSelectProject: (id: string) => void;
  onRefreshAll: () => void;
}

const SCENE_ROLES: SceneRole[] = [
  'Hook',
  'Problem',
  'Product_Intro',
  'Key_Feature',
  'Benefits',
  'Data_Proof',
  'Social_Proof',
  'CTA',
];

export const StudioWorkspaceView: React.FC<Props> = ({
  projects,
  activeProject,
  catalog,
  brands,
  recipes,
  profiles,
  assets,
  onSelectProject,
  onRefreshAll,
}) => {
  // New Project Creation Form State
  const [showCreateModal, setShowCreateModal] = useState(!activeProject);
  const [prompt, setPrompt] = useState('');
  const [title, setTitle] = useState('');
  const [aspectRatio, setAspectRatio] = useState<AspectRatio>('9:16');
  const [creationMode, setCreationMode] = useState<'auto' | 'storyboard_review'>('auto');
  const [framePresetId, setFramePresetId] = useState('editorial-clean-light');
  const [voiceId, setVoiceId] = useState('Hải Đăng');
  const [voiceSpeed, setVoiceSpeed] = useState(1.0);
  const [bgmTrackId, setBgmTrackId] = useState('bgm-corporate-pulse');
  const [brandKitId, setBrandKitId] = useState('');
  const [recipeId, setRecipeId] = useState('');
  const [manualAssetLock, setManualAssetLock] = useState(false);
  const [overrideDirectorProfileId, setOverrideDirectorProfileId] = useState('');
  const [overrideCoderProfileId, setOverrideCoderProfileId] = useState('');
  const [creating, setCreating] = useState(false);

  // Active Studio State
  const [selectedSceneIdx, setSelectedSceneIdx] = useState<number>(0);
  const [localScenes, setLocalScenes] = useState<ScenePacket[]>([]);
  const [scenesDirty, setScenesDirty] = useState(false);
  const [savingScenes, setSavingScenes] = useState(false);
  const [busySceneAction, setBusySceneAction] = useState<string | null>(null);

  // AI Copilot Edit State
  const [editPrompt, setEditPrompt] = useState('');
  const [editTargetIdx, setEditTargetIdx] = useState<number | 'all'>('all');
  const [editingBusy, setEditingBusy] = useState(false);
  const [lastEditSummary, setLastEditSummary] = useState('');

  // Live SSE Progress & Render State
  const [liveProgress, setLiveProgress] = useState<{
    stage: string;
    progress: number;
    message: string;
  } | null>(null);
  const [versions, setVersions] = useState<
    Array<{ id: string; versionNum: number; label: string; createdAt: string }>
  >([]);
  const [renderJobs, setRenderJobs] = useState<RenderJob[]>([]);
  const [renderingProvider, setRenderingProvider] = useState<'modal' | 'local'>('modal');
  const [startingRender, setStartingRender] = useState(false);
  const [iframeKey, setIframeKey] = useState(1);

  // Modals: Media Picker & HTML Code Inspector
  const [mediaModalSceneIdx, setMediaModalSceneIdx] = useState<number | null>(null);
  const [mediaModalTab, setMediaModalTab] = useState<'ai_gen' | 'url_scrape' | 'web_search' | 'library'>('library');
  const [modalImagePrompt, setModalImagePrompt] = useState('');
  const [modalScrapeUrl, setModalScrapeUrl] = useState('');
  const [modalWebQuery, setModalWebQuery] = useState('');
  const [modalMediaBusy, setModalMediaBusy] = useState(false);
  const [modalMediaMessage, setModalMediaMessage] = useState('');

  const [showCodeModal, setShowCodeModal] = useState(false);
  const [rawHtmlCode, setRawHtmlCode] = useState('');

  // Audio player ref for previewing voice samples or scene TTS
  const audioPreviewRef = useRef<HTMLAudioElement | null>(null);
  const [playingAudioUrl, setPlayingAudioUrl] = useState<string>('');

  useEffect(() => {
    if (activeProject) {
      setLocalScenes(activeProject.scenes || []);
      setScenesDirty(false);
      if (selectedSceneIdx >= (activeProject.scenes?.length || 1)) {
        setSelectedSceneIdx(0);
      }
      setIframeKey((k) => k + 1);
      void loadProjectDetails(activeProject.id);
    } else {
      setShowCreateModal(true);
    }
  }, [activeProject?.id, activeProject?.updatedAt]);

  useEffect(() => {
    if (!activeProject) return;
    const evSource = new EventSource(`/api/projects/${activeProject.id}/events`);
    evSource.onmessage = (ev) => {
      try {
        const data = JSON.parse(ev.data);
        setLiveProgress(data);
        if (
          data.status === 'ready' ||
          data.status === 'awaiting_storyboard_review' ||
          data.status === 'error'
        ) {
          onRefreshAll();
          setIframeKey((k) => k + 1);
        }
      } catch {}
    };
    return () => evSource.close();
  }, [activeProject?.id]);

  useEffect(() => {
    if (!activeProject) return;
    const hasRunning = renderJobs.some((j) =>
      ['queued', 'bundling', 'rendering'].includes(j.status)
    );
    if (!hasRunning) return;
    const timer = setInterval(() => {
      void loadProjectDetails(activeProject.id);
    }, 3000);
    return () => clearInterval(timer);
  }, [activeProject?.id, renderJobs]);

  async function loadProjectDetails(projectId: string) {
    try {
      const [projData, rndData] = await Promise.all([
        api.getProject(projectId),
        api.getRenderJobs(projectId),
      ]);
      setVersions(projData.versions || []);
      setRenderJobs(rndData.jobs || []);
    } catch {}
  }

  function playAudioUrl(url: string) {
    if (!url) return;
    if (audioPreviewRef.current) {
      if (playingAudioUrl === url) {
        audioPreviewRef.current.pause();
        setPlayingAudioUrl('');
        return;
      }
      audioPreviewRef.current.src = url;
      audioPreviewRef.current.play().catch(() => {});
      setPlayingAudioUrl(url);
    }
  }

  const detectedUrls = (prompt.match(/https?:\/\/[^\s"'<>]+/gi) || []).slice(0, 4);

  async function handleCreateProject(e: React.FormEvent) {
    e.preventDefault();
    if (!prompt.trim()) return;
    setCreating(true);
    try {
      const res = await api.createProject({
        title: title.trim() || undefined,
        prompt: prompt.trim(),
        aspectRatio,
        creationMode,
        framePresetId,
        voiceId,
        voiceSpeed,
        bgmTrackId,
        brandKitId: brandKitId || undefined,
        recipeId: recipeId || undefined,
        manualAssetLock,
        overrideDirectorProfileId: overrideDirectorProfileId || undefined,
        overrideCoderProfileId: overrideCoderProfileId || undefined,
      });
      setPrompt('');
      setTitle('');
      setShowCreateModal(false);
      onRefreshAll();
      onSelectProject(res.project.id);
    } catch (err: any) {
      alert(`Lỗi tạo dự án: ${err.message}`);
    } finally {
      setCreating(false);
    }
  }

  function updateLocalScene(idx: number, patch: Partial<ScenePacket>) {
    setLocalScenes((prev) =>
      prev.map((sc, i) => (i === idx ? { ...sc, ...patch } : sc))
    );
    setScenesDirty(true);
  }

  function addSceneBelow(idx: number) {
    const refScene = localScenes[idx];
    const newScene: ScenePacket = {
      id: `sc-${Date.now().toString(36)}`,
      index: idx + 1,
      slug: `scene-${idx + 2}`,
      title: 'Tiêu đề phân cảnh mới',
      role: 'Key_Feature',
      narrationText: 'Nhập lời bình thuyết minh cho phân cảnh này...',
      visualDirection: 'Bố cục chuyển động hiện đại, rõ nét',
      imagePrompt: 'Modern clean product showcase studio lighting',
      catalogQuery: '',
      blueprintId: refScene?.blueprintId || 'kinetic-type-beats',
      motionRuleIds: refScene?.motionRuleIds || ['spring-pop', 'stagger-words'],
      registryBlockName: refScene?.registryBlockName || 'glass-callout-card',
      transitionOut: 'fade-blur',
      sfxCue: 'whoosh-soft',
      startSec: 0,
      durationSec: 4.5,
      audioUrl: '',
      audioDurationSec: 4.0,
      words: [],
      assignedAssetIds: [],
      referenceImageUrl: refScene?.referenceImageUrl || '',
      videoTrimStartSec: 0,
      filePath: '',
      status: 'planned',
    };
    const next = [...localScenes];
    next.splice(idx + 1, 0, newScene);
    setLocalScenes(next);
    setSelectedSceneIdx(idx + 1);
    setScenesDirty(true);
  }

  function duplicateScene(idx: number) {
    const source = localScenes[idx];
    if (!source) return;
    const copy: ScenePacket = {
      ...source,
      id: `sc-${Date.now().toString(36)}`,
      title: `${source.title} (Bản sao)`,
    };
    const next = [...localScenes];
    next.splice(idx + 1, 0, copy);
    setLocalScenes(next);
    setSelectedSceneIdx(idx + 1);
    setScenesDirty(true);
  }

  function moveScene(idx: number, dir: -1 | 1) {
    const target = idx + dir;
    if (target < 0 || target >= localScenes.length) return;
    const next = [...localScenes];
    const [item] = next.splice(idx, 1);
    next.splice(target, 0, item);
    setLocalScenes(next);
    setSelectedSceneIdx(target);
    setScenesDirty(true);
  }

  function deleteScene(idx: number) {
    if (localScenes.length <= 1) {
      alert('Dự án cần ít nhất 1 phân cảnh.');
      return;
    }
    const next = localScenes.filter((_, i) => i !== idx);
    setLocalScenes(next);
    setSelectedSceneIdx(Math.max(0, idx - 1));
    setScenesDirty(true);
  }

  async function handleSaveAndCompileScenes(
    overrideScenes?: ScenePacket[],
    overridePresetId?: string,
    overrideVoiceId?: string
  ) {
    if (!activeProject) return;
    setSavingScenes(true);
    try {
      await api.updateStoryboard(activeProject.id, {
        scenes: overrideScenes || localScenes,
        framePresetId: overridePresetId || activeProject.framePresetId,
        voiceId: overrideVoiceId || activeProject.voiceId,
        rebuildComposition: true,
      });
      setScenesDirty(false);
      onRefreshAll();
      setIframeKey((k) => k + 1);
    } catch (err: any) {
      alert(`Lỗi lưu phân cảnh: ${err.message}`);
    } finally {
      setSavingScenes(false);
    }
  }

  async function handleResynthesizeSceneVoice(idx: number) {
    if (!activeProject) return;
    const sc = localScenes[idx];
    if (!sc) return;
    setBusySceneAction(`tts-${idx}`);
    try {
      await api.resynthesizeSceneVoice(
        activeProject.id,
        idx,
        sc.narrationText,
        activeProject.voiceId,
        activeProject.voiceSpeed
      );
      onRefreshAll();
      setIframeKey((k) => k + 1);
    } catch (err: any) {
      alert(`Lỗi tạo giọng đọc: ${err.message}`);
    } finally {
      setBusySceneAction(null);
    }
  }

  async function handleApproveStoryboard() {
    if (!activeProject) return;
    setSavingScenes(true);
    try {
      await api.updateStoryboard(activeProject.id, {
        scenes: localScenes,
        rebuildComposition: false,
      });
      await api.approveStoryboardAndBuild(activeProject.id);
      onRefreshAll();
      setIframeKey((k) => k + 1);
    } catch (err: any) {
      alert(`Lỗi dựng video: ${err.message}`);
    } finally {
      setSavingScenes(false);
    }
  }

  async function handlePromptEdit(e: React.FormEvent) {
    e.preventDefault();
    if (!activeProject || !editPrompt.trim()) return;
    setEditingBusy(true);
    setLastEditSummary('');
    try {
      const res = await api.promptEditProject(
        activeProject.id,
        editPrompt.trim(),
        editTargetIdx === 'all' ? undefined : editTargetIdx
      );
      setEditPrompt('');
      setLastEditSummary(res.summary);
      setVersions(res.versions || []);
      onRefreshAll();
      setIframeKey((k) => k + 1);
    } catch (err: any) {
      alert(`Lỗi chỉnh sửa: ${err.message}`);
    } finally {
      setEditingBusy(false);
    }
  }

  async function handleAspectRatioChange(ratio: AspectRatio) {
    if (!activeProject || activeProject.aspectRatio === ratio) return;
    setEditingBusy(true);
    try {
      const res = await api.remixAspectRatio(activeProject.id, ratio);
      setVersions(res.versions || []);
      onRefreshAll();
      setIframeKey((k) => k + 1);
    } catch (err: any) {
      alert(`Lỗi đổi tỷ lệ khung hình: ${err.message}`);
    } finally {
      setEditingBusy(false);
    }
  }

  async function handleStartRender() {
    if (!activeProject) return;
    setStartingRender(true);
    try {
      if (scenesDirty) {
        await handleSaveAndCompileScenes();
      }
      await api.startRender(activeProject.id, renderingProvider);
      await loadProjectDetails(activeProject.id);
      onRefreshAll();
    } catch (err: any) {
      alert(`Lỗi khởi chạy Render: ${err.message}`);
    } finally {
      setStartingRender(false);
    }
  }

  function openMediaPickerForScene(idx: number) {
    const sc = localScenes[idx];
    setMediaModalSceneIdx(idx);
    setModalImagePrompt(sc?.imagePrompt || sc?.visualDirection || sc?.title || '');
    setModalWebQuery(sc?.catalogQuery || sc?.title || '');
    setModalMediaMessage('');
    setMediaModalTab('library');
  }

  async function handleAssignAssetToScene(asset: AssetItem) {
    if (mediaModalSceneIdx === null || !activeProject) return;
    const updated = localScenes.map((sc, i) =>
      i === mediaModalSceneIdx
        ? {
            ...sc,
            assignedAssetIds: [asset.id],
            referenceImageUrl: asset.publicUrl,
          }
        : sc
    );
    setLocalScenes(updated);
    setMediaModalSceneIdx(null);
    await handleSaveAndCompileScenes(updated);
  }

  async function handleModalGenerateAiImage() {
    if (mediaModalSceneIdx === null || !activeProject) return;
    setModalMediaBusy(true);
    setModalMediaMessage('Đang tạo hình ảnh AI tham khảo cho phân cảnh...');
    try {
      await api.regenerateSceneImage(
        activeProject.id,
        mediaModalSceneIdx,
        modalImagePrompt.trim()
      );
      onRefreshAll();
      setIframeKey((k) => k + 1);
      setMediaModalSceneIdx(null);
    } catch (err: any) {
      setModalMediaMessage(`Lỗi tạo ảnh: ${err.message}`);
    } finally {
      setModalMediaBusy(false);
    }
  }

  async function handleModalScrapeUrl() {
    if (!modalScrapeUrl.trim() || !activeProject) return;
    setModalMediaBusy(true);
    setModalMediaMessage('Đang cào ảnh/logo từ URL & phân tích Vision AI...');
    try {
      const res = await api.scrapeUrlAssets({
        url: modalScrapeUrl.trim(),
        projectId: activeProject.id,
      });
      setModalMediaMessage(
        `Đã thu thập & phân tích ${res.scrapedAssets?.length || 0} tài nguyên! Bấm vào ảnh bên dưới để gán vào cảnh.`
      );
      onRefreshAll();
      setMediaModalTab('library');
    } catch (err: any) {
      setModalMediaMessage(`Lỗi cào URL: ${err.message}`);
    } finally {
      setModalMediaBusy(false);
    }
  }

  async function handleModalSearchWeb() {
    if (!modalWebQuery.trim() || !activeProject) return;
    setModalMediaBusy(true);
    setModalMediaMessage('Đang tìm ảnh thực tế trên Web...');
    try {
      const res = await api.searchWebAssets({
        query: modalWebQuery.trim(),
        projectId: activeProject.id,
        limit: 4,
      });
      setModalMediaMessage(
        `Đã tìm thấy ${res.foundAssets?.length || 0} ảnh thực tế! Bấm vào ảnh bên dưới để gán vào cảnh.`
      );
      onRefreshAll();
      setMediaModalTab('library');
    } catch (err: any) {
      setModalMediaMessage(`Lỗi tìm ảnh: ${err.message}`);
    } finally {
      setModalMediaBusy(false);
    }
  }

  async function handleOpenCodeInspector() {
    if (!activeProject) return;
    try {
      const resp = await fetch(`/api/projects/${activeProject.id}/preview`);
      const text = await resp.text();
      setRawHtmlCode(text);
      setShowCodeModal(true);
    } catch {}
  }

  const voicesList = catalog?.voices || [];
  const selectedVoiceObj = voicesList.find(
    (v: any) =>
      v.id === (activeProject?.voiceId || voiceId) ||
      v.voiceId === (activeProject?.voiceId || voiceId)
  );

  const isBuilding =
    activeProject &&
    ['scraping_assets', 'planning_storyboard', 'generating_media', 'coding_scenes', 'validating'].includes(
      activeProject.status
    );

  return (
    <div className="space-y-4">
      <audio
        ref={audioPreviewRef}
        onEnded={() => setPlayingAudioUrl('')}
        className="hidden"
      />

      {/* =====================================================================
          1. FLIKI STUDIO TOP HEADER TOOLBAR (DESIGN.MD + SHADCN PRIMITIVES)
         ===================================================================== */}
      <div className="fliki-card px-5 py-3 flex flex-wrap items-center justify-between gap-3 bg-white">
        <div className="flex items-center gap-3 flex-wrap">
          <div className="flex items-center gap-2">
            <span className="w-2 h-2 rounded-full bg-[#E11D48]" />
            <select
              value={activeProject?.id || ''}
              onChange={(e) => {
                if (e.target.value) {
                  setShowCreateModal(false);
                  onSelectProject(e.target.value);
                }
              }}
              className="bg-zinc-50 border border-zinc-200 hover:border-zinc-300 rounded-xl px-3.5 py-1.5 text-xs font-bold text-zinc-900 focus:outline-none focus:border-[#E11D48] cursor-pointer"
            >
              {projects.length === 0 && <option value="">Chưa có dự án nào</option>}
              {projects.map((p) => (
                <option key={p.id} value={p.id}>
                  {p.title} ({p.aspectRatio} • {Math.round(p.totalDurationSec || 0)}s)
                </option>
              ))}
            </select>
          </div>

          {activeProject && (
            <Badge
              variant={
                activeProject.status === 'ready' || activeProject.status === 'rendered'
                  ? 'emerald'
                  : activeProject.status === 'awaiting_storyboard_review'
                    ? 'amber'
                    : 'crimson'
              }
            >
              <CheckCircle2 className="w-3 h-3" />
              {activeProject.status === 'ready'
                ? 'Sẵn sàng 60fps'
                : activeProject.status === 'rendered'
                  ? 'Đã xuất MP4'
                  : activeProject.status === 'awaiting_storyboard_review'
                    ? 'Chờ duyệt Storyboard'
                    : activeProject.status}
            </Badge>
          )}

          {/* Aspect Ratio Switcher */}
          {activeProject && (
            <div className="flex items-center bg-zinc-100 p-1 rounded-xl border border-zinc-200">
              {(
                [
                  { ratio: '9:16' as AspectRatio, label: '9:16', Icon: Smartphone },
                  { ratio: '16:9' as AspectRatio, label: '16:9', Icon: Monitor },
                  { ratio: '1:1' as AspectRatio, label: '1:1', Icon: SquareIcon },
                ] as const
              ).map(({ ratio, label, Icon }) => (
                <button
                  key={ratio}
                  onClick={() => handleAspectRatioChange(ratio)}
                  disabled={editingBusy}
                  className={`px-2.5 py-1 rounded-lg text-xs font-mono tabular-nums font-bold flex items-center gap-1.5 transition-all cursor-pointer ${
                    activeProject.aspectRatio === ratio
                      ? 'bg-white text-[#E11D48] shadow-2xs'
                      : 'text-zinc-600 hover:text-zinc-900'
                  }`}
                >
                  <Icon className="w-3.5 h-3.5" />
                  <span>{label}</span>
                </button>
              ))}
            </div>
          )}

          {/* Frame Preset Style Selector */}
          {activeProject && (
            <div className="flex items-center gap-1.5 bg-zinc-50 border border-zinc-200 rounded-xl px-2.5 py-1">
              <Sliders className="w-3.5 h-3.5 text-zinc-500" />
              <select
                value={activeProject.framePresetId}
                onChange={(e) =>
                  handleSaveAndCompileScenes(localScenes, e.target.value, undefined)
                }
                className="bg-transparent text-xs font-semibold text-zinc-800 focus:outline-none cursor-pointer"
                title="Đổi bảng màu & Typography (HyperFrames Frame Preset)"
              >
                {(catalog?.framePresets || []).map((fp: any) => (
                  <option key={fp.id} value={fp.id}>
                    Preset: {fp.name}
                  </option>
                ))}
              </select>
            </div>
          )}

          {/* Global Voice Selector + Sample Preview */}
          {activeProject && (
            <div className="flex items-center gap-1.5 bg-zinc-50 border border-zinc-200 rounded-xl px-2.5 py-1">
              <Mic className="w-3.5 h-3.5 text-[#E11D48]" />
              <select
                value={activeProject.voiceId}
                onChange={(e) =>
                  handleSaveAndCompileScenes(localScenes, undefined, e.target.value)
                }
                className="bg-transparent text-xs font-semibold text-zinc-800 focus:outline-none max-w-[170px] cursor-pointer"
              >
                {voicesList.map((v: any) => (
                  <option key={v.id} value={v.voiceId || v.id}>
                    {v.name}
                  </option>
                ))}
              </select>
              {selectedVoiceObj?.previewUrl && (
                <button
                  type="button"
                  onClick={() => playAudioUrl(selectedVoiceObj.previewUrl)}
                  className="px-2 py-0.5 rounded-md bg-rose-50 hover:bg-rose-100 text-[#E11D48] text-[11px] font-bold flex items-center gap-1 cursor-pointer"
                  title="Nghe thử mẫu giọng này"
                >
                  {playingAudioUrl === selectedVoiceObj.previewUrl ? (
                    <>
                      <Square className="w-2.5 h-2.5 fill-current" />
                      <span>Dừng</span>
                    </>
                  ) : (
                    <>
                      <Volume2 className="w-3 h-3" />
                      <span>Mẫu</span>
                    </>
                  )}
                </button>
              )}
            </div>
          )}
        </div>

        {/* Right Actions: Undo/Redo, New Video, Export MP4 */}
        <div className="flex items-center gap-2">
          {versions.length > 0 && activeProject && (
            <div className="flex items-center gap-1.5 bg-zinc-50 border border-zinc-200 rounded-xl px-2.5 py-1.5">
              <History className="w-3.5 h-3.5 text-zinc-500" />
              <select
                defaultValue=""
                onChange={async (e) => {
                  if (!e.target.value) return;
                  await api.restoreVersion(activeProject.id, e.target.value);
                  e.target.value = '';
                  onRefreshAll();
                  setIframeKey((k) => k + 1);
                }}
                className="bg-transparent text-xs font-semibold text-zinc-700 focus:outline-none cursor-pointer"
              >
                <option value="">Lịch sử ({versions.length})</option>
                {versions.map((v) => (
                  <option key={v.id} value={v.id}>
                    v{v.versionNum}: {v.label}
                  </option>
                ))}
              </select>
            </div>
          )}

          <Button
            type="button"
            variant="secondary"
            onClick={() => setShowCreateModal(!showCreateModal)}
          >
            <Plus className="w-3.5 h-3.5 text-[#E11D48]" />
            <span>{showCreateModal ? 'Đóng khung tạo' : 'Tạo Video Mới'}</span>
          </Button>

          {activeProject && (
            <div className="flex items-center gap-1.5">
              <div className="flex items-center gap-1 bg-zinc-50 border border-zinc-200 rounded-xl px-2.5 py-1.5">
                {renderingProvider === 'modal' ? (
                  <Cloud className="w-3.5 h-3.5 text-[#E11D48]" />
                ) : (
                  <Laptop className="w-3.5 h-3.5 text-zinc-600" />
                )}
                <select
                  value={renderingProvider}
                  onChange={(e) => setRenderingProvider(e.target.value as 'modal' | 'local')}
                  className="bg-transparent text-xs font-semibold text-zinc-700 focus:outline-none cursor-pointer"
                >
                  <option value="modal">Modal Cloud (cpu24w22)</option>
                  <option value="local">Local HyperFrames CLI</option>
                </select>
              </div>
              <Button
                type="button"
                variant="primary"
                onClick={handleStartRender}
                disabled={startingRender}
              >
                <Download className="w-3.5 h-3.5" />
                <span>{startingRender ? 'Đang gửi Render...' : 'Xuất MP4'}</span>
              </Button>
            </div>
          )}
        </div>
      </div>

      {/* =====================================================================
          2. NEW VIDEO PROMPT-TO-VIDEO DRAWER (FLIKI IDEA-TO-VIDEO WIZARD)
         ===================================================================== */}
      {showCreateModal && (
        <form
          onSubmit={handleCreateProject}
          className="fliki-card p-6 bg-white border-zinc-200 space-y-5"
        >
          <div className="flex items-center justify-between border-b border-zinc-100 pb-4">
            <div>
              <Badge variant="crimson" className="mb-1.5">
                <Sparkles className="w-3 h-3" />
                Fliki Idea-to-Video • HyperFrames 4-Tier Catalog Engine
              </Badge>
              <h2 className="text-lg font-bold tracking-tight text-zinc-900">
                Tạo Video Chuyên Nghiệp Từ Prompt Hoặc URL Sản Phẩm
              </h2>
              <p className="text-xs text-zinc-500 mt-0.5">
                Nhập ý tưởng hoặc dán link trang web — Hệ thống tự động cào ảnh/logo chuẩn thương hiệu, viết kịch bản, đọc giọng OlokaTTS và dựng đồ họa chuyển động 60fps.
              </p>
            </div>
            {activeProject && (
              <Button
                type="button"
                variant="ghost"
                size="sm"
                onClick={() => setShowCreateModal(false)}
              >
                <X className="w-4 h-4" />
                <span>Đóng</span>
              </Button>
            )}
          </div>

          {/* Quick Prompt Templates */}
          <div className="flex items-center gap-2 flex-wrap">
            <span className="text-xs font-semibold text-zinc-500">Mẫu gợi ý nhanh:</span>
            {[
              {
                label: 'Ra mắt nền tảng SaaS AI',
                text: 'Tạo video quảng cáo 5 cảnh ra mắt nền tảng OlokaFlow AI Video Studio: tự động hóa dựng video 60fps bằng HyperFrames, tích hợp giọng đọc AI tiếng Việt tự nhiên và render đám mây siêu tốc.',
                preset: 'editorial-clean-light',
              },
              {
                label: 'Mỹ phẩm & Skincare Cao cấp',
                text: 'Tạo video giới thiệu tinh chất Serum Vitamin C & Hyaluronic Acid dưỡng sáng da tự nhiên, cấp ẩm chuyên sâu 24h, cam kết chính hãng và ưu đãi đặt hàng hôm nay.',
                preset: 'luxury-minimal-cream',
              },
              {
                label: 'Báo cáo Tăng trưởng & Số liệu',
                text: 'Tạo video thuyết trình báo cáo tăng trưởng doanh thu thương mại điện tử Q4 tăng 320%, tỷ lệ chuyển đổi đạt 8.4% và lộ trình mở rộng thị trường Đông Nam Á.',
                preset: 'fintech-emerald-trust',
              },
            ].map((tpl, i) => (
              <button
                key={i}
                type="button"
                onClick={() => {
                  setPrompt(tpl.text);
                  setFramePresetId(tpl.preset);
                }}
                className="px-3 py-1.5 rounded-full text-xs font-semibold bg-zinc-50 hover:bg-rose-50 text-zinc-700 hover:text-[#E11D48] border border-zinc-200 hover:border-rose-200 transition-colors cursor-pointer flex items-center gap-1.5"
              >
                <Sparkles className="w-3 h-3 text-[#E11D48]" />
                <span>{tpl.label}</span>
              </button>
            ))}
          </div>

          <div className="grid grid-cols-1 lg:grid-cols-12 gap-5">
            <div className="lg:col-span-7 space-y-3">
              <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
                <div>
                  <label className="block text-xs font-semibold text-zinc-700 mb-1">
                    Tên dự án (Tùy chọn)
                  </label>
                  <input
                    type="text"
                    value={title}
                    onChange={(e) => setTitle(e.target.value)}
                    placeholder="VD: TVC Ra mắt Sản phẩm Q4..."
                    className="w-full bg-zinc-50 border border-zinc-200 rounded-xl px-3.5 py-2 text-xs text-zinc-900 focus:outline-none focus:border-[#E11D48] focus:bg-white"
                  />
                </div>
                <div>
                  <label className="block text-xs font-semibold text-zinc-700 mb-1">
                    Chế độ khởi tạo
                  </label>
                  <div className="grid grid-cols-2 bg-zinc-100 p-1 rounded-xl border border-zinc-200">
                    <button
                      type="button"
                      onClick={() => setCreationMode('auto')}
                      className={`py-1.5 rounded-lg text-xs font-semibold cursor-pointer transition-all flex items-center justify-center gap-1.5 ${
                        creationMode === 'auto'
                          ? 'bg-white text-[#E11D48] shadow-2xs'
                          : 'text-zinc-600'
                      }`}
                    >
                      <Zap className="w-3.5 h-3.5" />
                      <span>Tự động 100%</span>
                    </button>
                    <button
                      type="button"
                      onClick={() => setCreationMode('storyboard_review')}
                      className={`py-1.5 rounded-lg text-xs font-semibold cursor-pointer transition-all flex items-center justify-center gap-1.5 ${
                        creationMode === 'storyboard_review'
                          ? 'bg-white text-zinc-900 shadow-2xs'
                          : 'text-zinc-600'
                      }`}
                    >
                      <LayoutTemplate className="w-3.5 h-3.5" />
                      <span>Duyệt Storyboard</span>
                    </button>
                  </div>
                </div>
              </div>

              <div>
                <label className="block text-xs font-semibold text-zinc-700 mb-1">
                  Prompt kịch bản / Nội dung / Link URL sản phẩm *
                </label>
                <textarea
                  rows={4}
                  value={prompt}
                  onChange={(e) => setPrompt(e.target.value)}
                  placeholder="Mô tả chi tiết video bạn muốn tạo, hoặc dán trực tiếp URL sản phẩm/bài viết (VD: https://...) để AI tự động cào hình ảnh, logo và phân tích đưa vào video..."
                  className="w-full bg-zinc-50 border border-zinc-200 rounded-xl p-3.5 text-sm text-zinc-900 focus:outline-none focus:border-[#E11D48] focus:bg-white"
                  required
                />
                {detectedUrls.length > 0 && (
                  <div className="mt-2 flex items-center gap-2 px-3 py-2 rounded-xl bg-rose-50/70 border border-rose-200 text-xs text-rose-800 font-medium">
                    <Link2 className="w-3.5 h-3.5 text-[#E11D48] shrink-0" />
                    <span>Đã phát hiện {detectedUrls.length} URL:</span>
                    <span className="font-mono truncate">{detectedUrls.join(', ')}</span>
                    <span className="ml-auto font-bold text-[#E11D48]">
                      Tự động cào ảnh & phân tích Vision AI
                    </span>
                  </div>
                )}
              </div>
            </div>

            <div className="lg:col-span-5 grid grid-cols-1 sm:grid-cols-2 gap-3 bg-zinc-50/80 p-4 rounded-2xl border border-zinc-200/80">
              <div>
                <label className="block text-xs font-semibold text-zinc-700 mb-1">
                  Tỷ lệ khung hình
                </label>
                <select
                  value={aspectRatio}
                  onChange={(e) => setAspectRatio(e.target.value as AspectRatio)}
                  className="w-full bg-white border border-zinc-200 rounded-xl px-3 py-2 text-xs font-semibold text-zinc-800"
                >
                  <option value="9:16">9:16 Dọc (TikTok / Reels / Shorts)</option>
                  <option value="16:9">16:9 Ngang (YouTube / Web Hero)</option>
                  <option value="1:1">1:1 Vuông (Facebook / Instagram Feed)</option>
                </select>
              </div>

              <div>
                <label className="block text-xs font-semibold text-zinc-700 mb-1">
                  Phong cách thiết kế (Frame Preset)
                </label>
                <select
                  value={framePresetId}
                  onChange={(e) => setFramePresetId(e.target.value)}
                  className="w-full bg-white border border-zinc-200 rounded-xl px-3 py-2 text-xs font-semibold text-zinc-800"
                >
                  {(catalog?.framePresets || []).map((fp: any) => (
                    <option key={fp.id} value={fp.id}>
                      {fp.name} ({fp.category})
                    </option>
                  ))}
                </select>
              </div>

              <div className="sm:col-span-2">
                <label className="block text-xs font-semibold text-zinc-700 mb-1">
                  Giọng đọc AI (25 Giọng OlokaTTS Việt Nam & OpenAI)
                </label>
                <div className="flex items-center gap-2">
                  <select
                    value={voiceId}
                    onChange={(e) => setVoiceId(e.target.value)}
                    className="flex-1 bg-white border border-zinc-200 rounded-xl px-3 py-2 text-xs font-semibold text-zinc-800"
                  >
                    {voicesList.map((v: any) => (
                      <option key={v.id} value={v.voiceId || v.id}>
                        {v.name} — {v.description}
                      </option>
                    ))}
                  </select>
                  {(() => {
                    const vObj = voicesList.find(
                      (v: any) => v.id === voiceId || v.voiceId === voiceId
                    );
                    return vObj?.previewUrl ? (
                      <Button
                        type="button"
                        variant="outlineCrimson"
                        size="sm"
                        onClick={() => playAudioUrl(vObj.previewUrl)}
                      >
                        {playingAudioUrl === vObj.previewUrl ? (
                          <>
                            <Square className="w-3 h-3 fill-current" />
                            <span>Dừng</span>
                          </>
                        ) : (
                          <>
                            <Volume2 className="w-3.5 h-3.5" />
                            <span>Nghe thử</span>
                          </>
                        )}
                      </Button>
                    ) : null;
                  })()}
                </div>
              </div>

              <div>
                <label className="block text-xs font-semibold text-zinc-700 mb-1">
                  Bộ nhận diện (Brand Kit)
                </label>
                <select
                  value={brandKitId}
                  onChange={(e) => setBrandKitId(e.target.value)}
                  className="w-full bg-white border border-zinc-200 rounded-xl px-3 py-2 text-xs font-semibold text-zinc-800"
                >
                  <option value="">Mặc định theo Preset</option>
                  {brands.map((b) => (
                    <option key={b.id} value={b.id}>
                      {b.name} ({b.brandName})
                    </option>
                  ))}
                </select>
              </div>

              <div>
                <label className="block text-xs font-semibold text-zinc-700 mb-1">
                  Công thức dựng sẵn (Frozen Recipe)
                </label>
                <select
                  value={recipeId}
                  onChange={(e) => setRecipeId(e.target.value)}
                  className="w-full bg-white border border-zinc-200 rounded-xl px-3 py-2 text-xs font-semibold text-zinc-800"
                >
                  <option value="">AI Director tự động chọn Blueprint</option>
                  {recipes.map((r) => (
                    <option key={r.id} value={r.id}>
                      {r.name}
                    </option>
                  ))}
                </select>
              </div>

              <div className="sm:col-span-2 flex items-center justify-between pt-2">
                <label className="flex items-center gap-2 text-xs font-medium text-zinc-600 cursor-pointer">
                  <input
                    type="checkbox"
                    checked={manualAssetLock}
                    onChange={(e) => setManualAssetLock(e.target.checked)}
                    className="rounded border-zinc-300 text-[#E11D48] focus:ring-[#E11D48]"
                  />
                  <Lock className="w-3.5 h-3.5 text-zinc-400" />
                  <span>Khóa tài nguyên thủ công (Chỉ dùng ảnh đã upload)</span>
                </label>

                <Button type="submit" variant="primary" size="lg" disabled={creating}>
                  <Film className="w-4 h-4" />
                  <span>
                    {creating
                      ? 'Đang khởi tạo Pipeline...'
                      : creationMode === 'storyboard_review'
                        ? 'Lập Storyboard & Tạo Media'
                        : 'Tạo Video HyperFrames Ngay'}
                  </span>
                </Button>
              </div>
            </div>
          </div>
        </form>
      )}

      {/* =====================================================================
          3. LIVE PIPELINE PROGRESS BANNER (WHEN BUILDING)
         ===================================================================== */}
      {(isBuilding || (liveProgress && liveProgress.progress < 100)) && (
        <div className="fliki-card p-4 bg-white border-rose-200 flex items-center justify-between gap-4">
          <div className="flex items-center gap-3 flex-1">
            <div className="w-9 h-9 rounded-xl bg-[#E11D48] text-white flex items-center justify-center">
              <RefreshCw className="w-4 h-4 animate-spin" />
            </div>
            <div className="flex-1">
              <div className="flex items-center justify-between text-xs font-bold text-zinc-900 mb-1">
                <span>{liveProgress?.message || 'Đang xử lý pipeline HyperFrames...'}</span>
                <span className="font-mono tabular-nums text-[#E11D48]">
                  {liveProgress?.progress || 45}%
                </span>
              </div>
              <div className="w-full h-2 bg-zinc-100 rounded-full overflow-hidden">
                <div
                  className="h-full bg-[#E11D48] transition-all duration-500"
                  style={{ width: `${liveProgress?.progress || 45}%` }}
                />
              </div>
            </div>
          </div>
          {activeProject && (
            <Button
              type="button"
              variant="danger"
              size="sm"
              onClick={() => api.abortProject(activeProject.id)}
            >
              <Square className="w-3 h-3 fill-current" />
              <span>Dừng</span>
            </Button>
          )}
        </div>
      )}

      {/* =====================================================================
          4. FLIKI SPLIT-SCREEN SCENE-BY-SCENE WORKSPACE (LEFT SCENES / RIGHT PLAYER)
         ===================================================================== */}
      {activeProject && (
        <div className="grid grid-cols-1 xl:grid-cols-12 gap-5 items-start">
          {/* -----------------------------------------------------------------
              LEFT COLUMN (7/12): FLIKI SCENE-BY-SCENE BLOCK EDITOR
             ----------------------------------------------------------------- */}
          <div className="xl:col-span-7 space-y-3.5">
            {activeProject.status === 'awaiting_storyboard_review' && (
              <div className="fliki-card p-4 bg-amber-50/90 border-amber-300 flex flex-wrap items-center justify-between gap-3">
                <div>
                  <h3 className="text-sm font-bold text-amber-950 flex items-center gap-2">
                    <LayoutTemplate className="w-4 h-4 text-amber-700" />
                    Chế độ Duyệt Storyboard Trước Khi Sinh Code HyperFrames
                  </h3>
                  <p className="text-xs text-amber-800 mt-0.5">
                    Kiểm tra lời bình, nghe thử giọng đọc, đổi ảnh tham khảo hoặc Blueprint từng cảnh rồi bấm nút bên phải để dựng video 60fps.
                  </p>
                </div>
                <Button
                  type="button"
                  variant="primary"
                  onClick={handleApproveStoryboard}
                  disabled={savingScenes}
                >
                  <Film className="w-3.5 h-3.5" />
                  <span>
                    {savingScenes
                      ? 'Đang dựng HyperFrames...'
                      : 'Duyệt & Dựng Video HyperFrames 60fps'}
                  </span>
                </Button>
              </div>
            )}

            {/* Scene Stack Header */}
            <div className="flex items-center justify-between px-1">
              <div className="flex items-center gap-2">
                <h3 className="text-sm font-bold text-zinc-900 flex items-center gap-2">
                  <span>Danh sách Phân cảnh Kịch bản</span>
                  <span className="px-2 py-0.5 rounded-md bg-zinc-100 text-zinc-700 font-mono tabular-nums text-xs">
                    {localScenes.length} cảnh •{' '}
                    {localScenes
                      .reduce((acc, s) => acc + Number(s.durationSec || 0), 0)
                      .toFixed(1)}
                    s
                  </span>
                </h3>
                {scenesDirty && (
                  <Badge variant="amber">Có thay đổi chưa lưu</Badge>
                )}
              </div>

              <div className="flex items-center gap-2">
                {scenesDirty && (
                  <Button
                    type="button"
                    variant="primary"
                    size="sm"
                    onClick={() => handleSaveAndCompileScenes()}
                    disabled={savingScenes}
                  >
                    <RefreshCw
                      className={`w-3.5 h-3.5 ${savingScenes ? 'animate-spin' : ''}`}
                    />
                    <span>
                      {savingScenes ? 'Đang biên dịch...' : 'Lưu & Cập nhật Player 60fps'}
                    </span>
                  </Button>
                )}
                <Button
                  type="button"
                  variant="secondary"
                  size="sm"
                  onClick={() => addSceneBelow(localScenes.length - 1)}
                >
                  <Plus className="w-3.5 h-3.5" />
                  <span>Thêm cảnh</span>
                </Button>
              </div>
            </div>

            {/* FLIKI SCENE CARDS LIST */}
            <div className="space-y-3">
              {localScenes.map((scene, idx) => {
                const isSelected = selectedSceneIdx === idx;
                const wordCount = (scene.narrationText || '')
                  .trim()
                  .split(/\s+/)
                  .filter(Boolean).length;
                const paddedIdx = String(idx + 1).padStart(2, '0');

                return (
                  <div
                    key={scene.id || idx}
                    onClick={() => setSelectedSceneIdx(idx)}
                    className={`${
                      isSelected ? 'fliki-card-active' : 'fliki-card'
                    } p-4 bg-white transition-all`}
                  >
                    {/* SCENE CARD HEADER BAR */}
                    <div className="flex flex-wrap items-center justify-between gap-2 pb-3 mb-3 border-b border-zinc-100">
                      <div className="flex items-center gap-2 flex-wrap">
                        <span
                          className={`px-2.5 py-1 rounded-lg text-xs font-mono tabular-nums font-bold ${
                            isSelected
                              ? 'bg-[#E11D48] text-white'
                              : 'bg-zinc-100 text-zinc-700'
                          }`}
                        >
                          #{paddedIdx}
                        </span>

                        {/* Role Badge Selector */}
                        <select
                          value={scene.role}
                          onChange={(e) =>
                            updateLocalScene(idx, { role: e.target.value as SceneRole })
                          }
                          className="bg-zinc-50 border border-zinc-200 rounded-lg px-2.5 py-1 text-xs font-semibold text-zinc-700 focus:outline-none focus:border-[#E11D48] cursor-pointer"
                        >
                          {SCENE_ROLES.map((r) => (
                            <option key={r} value={r}>
                              {r}
                            </option>
                          ))}
                        </select>

                        {/* Fliki Voiceover Pill */}
                        <div className="flex items-center gap-1.5 bg-rose-50/70 border border-rose-200/80 rounded-full px-2.5 py-0.5 text-xs">
                          <Mic className="w-3 h-3 text-[#E11D48]" />
                          <span className="font-semibold text-rose-900">
                            {activeProject.voiceId}
                          </span>
                          {scene.audioUrl && (
                            <button
                              type="button"
                              onClick={(e) => {
                                e.stopPropagation();
                                playAudioUrl(scene.audioUrl);
                              }}
                              className="px-2 py-0.5 rounded-full bg-white hover:bg-rose-100 text-[#E11D48] font-semibold text-[11px] border border-rose-200 flex items-center gap-1 cursor-pointer"
                            >
                              {playingAudioUrl === scene.audioUrl ? (
                                <>
                                  <Square className="w-2.5 h-2.5 fill-current" />
                                  <span>Dừng</span>
                                </>
                              ) : (
                                <>
                                  <Play className="w-2.5 h-2.5 fill-current" />
                                  <span>Nghe</span>
                                </>
                              )}
                            </button>
                          )}
                          <button
                            type="button"
                            onClick={(e) => {
                              e.stopPropagation();
                              void handleResynthesizeSceneVoice(idx);
                            }}
                            disabled={busySceneAction === `tts-${idx}`}
                            className="px-2 py-0.5 rounded-full bg-[#E11D48] hover:bg-[#BE123C] text-white font-semibold text-[11px] flex items-center gap-1 cursor-pointer"
                            title="Tổng hợp lại giọng đọc TTS cho cảnh này"
                          >
                            <RefreshCw
                              className={`w-2.5 h-2.5 ${
                                busySceneAction === `tts-${idx}` ? 'animate-spin' : ''
                              }`}
                            />
                            <span>
                              {busySceneAction === `tts-${idx}` ? 'Đang đọc...' : 'Đọc lại TTS'}
                            </span>
                          </button>
                        </div>

                        {/* Scene Duration Pill */}
                        <div className="flex items-center gap-1 bg-zinc-50 border border-zinc-200 rounded-lg px-2 py-0.5 text-xs text-zinc-600">
                          <Clock className="w-3 h-3 text-zinc-400" />
                          <input
                            type="number"
                            step="0.2"
                            min="2.0"
                            max="30.0"
                            value={scene.durationSec}
                            onChange={(e) =>
                              updateLocalScene(idx, {
                                durationSec: Number(e.target.value) || 4.5,
                              })
                            }
                            className="w-12 bg-transparent font-mono tabular-nums font-bold text-zinc-900 focus:outline-none text-center"
                          />
                          <span className="font-mono">s</span>
                        </div>
                      </div>

                      {/* Scene Block Controls (Up / Down / Duplicate / Add Below / Delete) */}
                      <div className="flex items-center gap-1">
                        <button
                          type="button"
                          onClick={(e) => {
                            e.stopPropagation();
                            moveScene(idx, -1);
                          }}
                          disabled={idx === 0}
                          className="p-1.5 rounded-lg hover:bg-zinc-100 text-zinc-500 disabled:opacity-30 cursor-pointer"
                          title="Di chuyển cảnh lên"
                        >
                          <ArrowUp className="w-3.5 h-3.5" />
                        </button>
                        <button
                          type="button"
                          onClick={(e) => {
                            e.stopPropagation();
                            moveScene(idx, 1);
                          }}
                          disabled={idx === localScenes.length - 1}
                          className="p-1.5 rounded-lg hover:bg-zinc-100 text-zinc-500 disabled:opacity-30 cursor-pointer"
                          title="Di chuyển cảnh xuống"
                        >
                          <ArrowDown className="w-3.5 h-3.5" />
                        </button>
                        <button
                          type="button"
                          onClick={(e) => {
                            e.stopPropagation();
                            duplicateScene(idx);
                          }}
                          className="px-2 py-1 rounded-lg hover:bg-zinc-100 text-zinc-600 text-xs font-semibold flex items-center gap-1 cursor-pointer"
                          title="Nhân bản cảnh này"
                        >
                          <Copy className="w-3 h-3" />
                          <span>Nhân bản</span>
                        </button>
                        <button
                          type="button"
                          onClick={(e) => {
                            e.stopPropagation();
                            addSceneBelow(idx);
                          }}
                          className="px-2 py-1 rounded-lg hover:bg-zinc-100 text-zinc-700 text-xs font-semibold flex items-center gap-1 cursor-pointer"
                          title="Chèn cảnh mới bên dưới"
                        >
                          <Plus className="w-3 h-3" />
                          <span>Cảnh dưới</span>
                        </button>
                        <button
                          type="button"
                          onClick={(e) => {
                            e.stopPropagation();
                            deleteScene(idx);
                          }}
                          className="p-1.5 rounded-lg hover:bg-rose-50 text-zinc-400 hover:text-[#E11D48] cursor-pointer"
                          title="Xóa phân cảnh"
                        >
                          <Trash2 className="w-3.5 h-3.5" />
                        </button>
                      </div>
                    </div>

                    {/* SCENE CARD MAIN BODY: LEFT SCRIPT & HEADLINE / RIGHT MEDIA THUMBNAIL */}
                    <div className="grid grid-cols-1 sm:grid-cols-12 gap-4 items-start">
                      <div className="sm:col-span-9 space-y-2.5">
                        {/* On-screen Headline Input */}
                        <div>
                          <label className="block text-[11px] font-bold uppercase tracking-wider text-zinc-400 mb-1">
                            Tiêu đề hiển thị trên màn hình (Headline Layer)
                          </label>
                          <input
                            type="text"
                            value={scene.title}
                            onChange={(e) =>
                              updateLocalScene(idx, { title: e.target.value })
                            }
                            placeholder="Nhập tiêu đề chính hiển thị trên cảnh..."
                            className="w-full bg-zinc-50/70 hover:bg-zinc-50 focus:bg-white border border-zinc-200 focus:border-[#E11D48] rounded-xl px-3.5 py-2 text-sm font-bold text-zinc-900 focus:outline-none transition-colors"
                          />
                        </div>

                        {/* Narration Script Textarea */}
                        <div>
                          <div className="flex items-center justify-between mb-1">
                            <label className="text-[11px] font-bold uppercase tracking-wider text-zinc-400">
                              Lời bình thuyết minh (Voiceover Script & Phụ đề Karaoke)
                            </label>
                            <span className="text-[11px] text-zinc-400 font-mono tabular-nums">
                              {wordCount} từ • ~{Math.max(2.5, wordCount / 2.9).toFixed(1)}s đọc
                            </span>
                          </div>
                          <textarea
                            rows={2}
                            value={scene.narrationText}
                            onChange={(e) =>
                              updateLocalScene(idx, { narrationText: e.target.value })
                            }
                            placeholder="Nhập lời thoại tiếng Việt cho phân cảnh này..."
                            className="w-full bg-zinc-50/70 hover:bg-zinc-50 focus:bg-white border border-zinc-200 focus:border-[#E11D48] rounded-xl p-3 text-sm text-zinc-800 leading-relaxed focus:outline-none transition-colors"
                          />
                        </div>

                        {/* HyperFrames Blueprint & Motion Layer Pills */}
                        <div className="flex flex-wrap items-center gap-2 pt-1">
                          <div className="flex items-center gap-1.5 bg-zinc-100 border border-zinc-200 rounded-lg px-2.5 py-1 text-xs">
                            <LayoutTemplate className="w-3.5 h-3.5 text-[#E11D48]" />
                            <span className="text-zinc-600 font-semibold">Blueprint:</span>
                            <select
                              value={scene.blueprintId}
                              onChange={(e) =>
                                updateLocalScene(idx, { blueprintId: e.target.value })
                              }
                              className="bg-transparent font-semibold text-zinc-900 focus:outline-none cursor-pointer"
                            >
                              {(catalog?.sceneBlueprints || []).map((bp: any) => (
                                <option key={bp.id} value={bp.id}>
                                  {bp.name} ({bp.id})
                                </option>
                              ))}
                            </select>
                          </div>

                          <div className="flex items-center gap-1 bg-zinc-100 border border-zinc-200 rounded-lg px-2.5 py-1 text-xs text-zinc-700">
                            <Sparkles className="w-3 h-3 text-[#E11D48]" />
                            <span className="font-semibold">Motion:</span>
                            <span className="font-mono text-[11px]">
                              {(scene.motionRuleIds || []).join(', ') || 'spring-pop'}
                            </span>
                          </div>

                          <div className="flex items-center gap-1 bg-zinc-100 border border-zinc-200 rounded-lg px-2.5 py-1 text-xs text-zinc-700">
                            <Scissors className="w-3 h-3 text-zinc-500" />
                            <span className="font-semibold">Trim:</span>
                            <input
                              type="number"
                              step="0.5"
                              min="0"
                              value={scene.videoTrimStartSec || 0}
                              onChange={(e) =>
                                updateLocalScene(idx, {
                                  videoTrimStartSec: Number(e.target.value) || 0,
                                })
                              }
                              className="w-10 bg-transparent font-mono tabular-nums font-bold text-center focus:outline-none"
                              title="Mốc cắt giây bắt đầu của video B-Roll (data-media-start)"
                            />
                            <span className="font-mono">s</span>
                          </div>
                        </div>
                      </div>

                      {/* Right 3 Cols: Fliki Clickable Media Layer Box */}
                      <div className="sm:col-span-3 flex flex-col items-center">
                        <div
                          onClick={(e) => {
                            e.stopPropagation();
                            openMediaPickerForScene(idx);
                          }}
                          className="group relative w-full aspect-square max-w-[140px] rounded-2xl border border-zinc-200 hover:border-[#E11D48] overflow-hidden bg-zinc-100 cursor-pointer shadow-2xs transition-all"
                          title="Bấm để đổi hình ảnh / video B-roll hoặc tạo ảnh AI mới"
                        >
                          {scene.referenceImageUrl ? (
                            <img
                              src={scene.referenceImageUrl}
                              alt={scene.title}
                              className="w-full h-full object-cover group-hover:scale-105 transition-transform duration-300"
                            />
                          ) : (
                            <div className="w-full h-full flex flex-col items-center justify-center p-2 text-center text-zinc-400">
                              <ImageIcon className="w-6 h-6 mb-1" />
                              <span className="text-[11px] font-semibold">Chọn Media</span>
                            </div>
                          )}
                          <div className="absolute inset-x-0 bottom-0 bg-gradient-to-t from-zinc-950/85 via-zinc-950/50 to-transparent p-2 text-center">
                            <span className="text-[11px] font-semibold text-white flex items-center justify-center gap-1">
                              <RefreshCw className="w-3 h-3" />
                              <span>Đổi Media</span>
                            </span>
                          </div>
                        </div>
                        <button
                          type="button"
                          onClick={(e) => {
                            e.stopPropagation();
                            openMediaPickerForScene(idx);
                          }}
                          className="mt-1.5 text-[11px] font-semibold text-[#E11D48] hover:text-[#BE123C] cursor-pointer flex items-center gap-1"
                        >
                          <Plus className="w-3 h-3" />
                          <span>Kho Media / Tạo AI</span>
                        </button>
                      </div>
                    </div>
                  </div>
                );
              })}
            </div>
          </div>

          {/* -----------------------------------------------------------------
              RIGHT COLUMN (5/12): STICKY LIVE 60FPS PLAYER + TIMELINE + AI COPILOT
             ----------------------------------------------------------------- */}
          <div className="xl:col-span-5 xl:sticky xl:top-4 space-y-4">
            {/* LIVE 60FPS HYPERFRAMES STAGE CARD */}
            <div className="fliki-card p-4 bg-white space-y-3">
              <div className="flex items-center justify-between border-b border-zinc-100 pb-2.5">
                <div className="flex items-center gap-2">
                  <span className="w-2 h-2 rounded-full bg-emerald-500" />
                  <h3 className="text-xs font-bold uppercase tracking-wider text-zinc-800">
                    HyperFrames 60fps Live Stage ({activeProject.aspectRatio})
                  </h3>
                </div>
                <div className="flex items-center gap-1.5">
                  <Button
                    type="button"
                    variant="secondary"
                    size="sm"
                    onClick={() => setIframeKey((k) => k + 1)}
                  >
                    <RefreshCw className="w-3 h-3" />
                    <span>Phát lại</span>
                  </Button>
                  <Button
                    type="button"
                    variant="secondary"
                    size="sm"
                    onClick={handleOpenCodeInspector}
                  >
                    <Code2 className="w-3.5 h-3.5 text-[#E11D48]" />
                    <span>Mã HTML</span>
                  </Button>
                </div>
              </div>

              {/* Iframe Preview Stage */}
              <div className="w-full bg-zinc-100/90 rounded-2xl p-3 flex items-center justify-center border border-zinc-200/80 min-h-[360px]">
                <div
                  className="relative overflow-hidden rounded-xl shadow-md bg-zinc-950 border border-zinc-300"
                  style={{
                    width:
                      activeProject.aspectRatio === '9:16'
                        ? '260px'
                        : activeProject.aspectRatio === '1:1'
                          ? '320px'
                          : '100%',
                    aspectRatio:
                      activeProject.aspectRatio === '9:16'
                        ? '9 / 16'
                        : activeProject.aspectRatio === '1:1'
                          ? '1 / 1'
                          : '16 / 9',
                  }}
                >
                  <iframe
                    key={`${activeProject.id}-${iframeKey}`}
                    src={`/api/projects/${activeProject.id}/preview?t=${iframeKey}`}
                    title="HyperFrames 60fps Live Preview"
                    className="w-full h-full border-0"
                    sandbox="allow-scripts allow-same-origin"
                  />
                </div>
              </div>

              {/* Scene Scrubber Pills */}
              <div className="space-y-1.5">
                <div className="flex items-center justify-between text-[11px] font-semibold text-zinc-500">
                  <span>Thanh thời gian Phân cảnh (Timeline Scrubber)</span>
                  <span className="font-mono tabular-nums">
                    Tổng: {activeProject.totalDurationSec || 0}s
                  </span>
                </div>
                <div className="flex items-center gap-1.5 overflow-x-auto pb-1">
                  {localScenes.map((sc, i) => (
                    <button
                      key={sc.id || i}
                      type="button"
                      onClick={() => setSelectedSceneIdx(i)}
                      className={`px-2.5 py-1.5 rounded-xl text-xs font-mono tabular-nums font-semibold shrink-0 border transition-all cursor-pointer ${
                        selectedSceneIdx === i
                          ? 'bg-[#E11D48] text-white border-[#E11D48] shadow-2xs'
                          : 'bg-zinc-50 hover:bg-zinc-100 text-zinc-700 border-zinc-200'
                      }`}
                    >
                      #{String(i + 1).padStart(2, '0')} {sc.role} ({sc.durationSec}s)
                    </button>
                  ))}
                </div>
              </div>
            </div>

            {/* FLIKI AI PROMPT EDIT COPILOT CARD */}
            <div className="fliki-card p-4 bg-white space-y-3">
              <div className="flex items-center justify-between gap-2">
                <div className="flex items-center gap-2">
                  <Wand2 className="w-4 h-4 text-[#E11D48]" />
                  <h3 className="text-xs font-bold uppercase tracking-wider text-zinc-900">
                    AI Prompt Edit Copilot
                  </h3>
                </div>
                <select
                  value={editTargetIdx}
                  onChange={(e) =>
                    setEditTargetIdx(
                      e.target.value === 'all' ? 'all' : Number(e.target.value)
                    )
                  }
                  className="bg-zinc-50 border border-zinc-200 rounded-lg px-2.5 py-1 text-xs font-semibold text-zinc-700 cursor-pointer"
                >
                  <option value="all">Phạm vi: Tự động (JEV Router)</option>
                  {localScenes.map((sc, i) => (
                    <option key={sc.id || i} value={i}>
                      Chỉ sửa Cảnh #{String(i + 1).padStart(2, '0')} ({sc.role})
                    </option>
                  ))}
                </select>
              </div>

              <form onSubmit={handlePromptEdit} className="flex gap-2">
                <input
                  type="text"
                  value={editPrompt}
                  onChange={(e) => setEditPrompt(e.target.value)}
                  placeholder="VD: Đổi lời thoại cảnh 1 ngắn gọn hơn, tạo lại ảnh cảnh 2 sáng đẹp..."
                  className="flex-1 bg-zinc-50 border border-zinc-200 focus:border-[#E11D48] focus:bg-white rounded-xl px-3.5 py-2 text-xs text-zinc-900 focus:outline-none"
                />
                <Button
                  type="submit"
                  variant="primary"
                  disabled={editingBusy || !editPrompt.trim()}
                >
                  <Sparkles className="w-3.5 h-3.5" />
                  <span>{editingBusy ? 'Đang sửa...' : 'Áp dụng AI'}</span>
                </Button>
              </form>

              <div className="flex flex-wrap gap-1.5">
                {[
                  `Tạo lại ảnh cho Cảnh ${selectedSceneIdx + 1} theo phong cách studio cao cấp`,
                  `Viết lại lời thoại Cảnh ${selectedSceneIdx + 1} cuốn hút và ngắn gọn hơn`,
                  `Đổi hiệu ứng Cảnh ${selectedSceneIdx + 1} sang thống kê số liệu dataviz-countup`,
                ].map((chip, i) => (
                  <button
                    key={i}
                    type="button"
                    onClick={() => setEditPrompt(chip)}
                    className="px-2.5 py-1 rounded-full bg-zinc-50 hover:bg-rose-50 text-zinc-600 hover:text-[#E11D48] border border-zinc-200 text-[11px] font-medium cursor-pointer"
                  >
                    + {chip}
                  </button>
                ))}
              </div>

              {lastEditSummary && (
                <div className="p-2.5 rounded-xl bg-emerald-50 border border-emerald-200 text-xs text-emerald-800 font-medium flex items-center gap-1.5">
                  <CheckCircle2 className="w-3.5 h-3.5 text-emerald-600 shrink-0" />
                  <span>{lastEditSummary}</span>
                </div>
              )}
            </div>

            {/* RENDERED MP4 & SOCIAL PUBLISH KIT CARD */}
            {(activeProject.renderOutputUrl || renderJobs.length > 0) && (
              <div className="fliki-card p-4 bg-white space-y-3 border-emerald-200">
                <div className="flex items-center justify-between">
                  <h3 className="text-xs font-bold uppercase tracking-wider text-zinc-900 flex items-center gap-1.5">
                    <Film className="w-3.5 h-3.5 text-emerald-600" />
                    <span>Xuất bản Video MP4 & Bộ Social Kit</span>
                  </h3>
                  {activeProject.renderOutputUrl && (
                    <div className="flex items-center gap-2">
                      <a
                        href={activeProject.renderOutputUrl}
                        download
                        className="px-3 py-1 rounded-lg bg-emerald-600 hover:bg-emerald-500 text-white text-xs font-semibold flex items-center gap-1"
                      >
                        <Download className="w-3 h-3" />
                        <span>Tải MP4</span>
                      </a>
                      <a
                        href={`/api/projects/${activeProject.id}/srt`}
                        download
                        className="px-3 py-1 rounded-lg bg-zinc-100 hover:bg-zinc-200 text-zinc-700 text-xs font-semibold flex items-center gap-1"
                      >
                        <Download className="w-3 h-3" />
                        <span>Phụ đề .SRT</span>
                      </a>
                    </div>
                  )}
                </div>

                {renderJobs[0] &&
                  ['queued', 'bundling', 'rendering'].includes(renderJobs[0].status) && (
                    <div className="p-3 rounded-xl bg-zinc-50 border border-zinc-200 space-y-1.5">
                      <div className="flex justify-between text-xs font-bold text-zinc-900">
                        <span>
                          Đang Render MP4 qua{' '}
                          {renderJobs[0].provider === 'modal'
                            ? 'Modal Serverless Cloud'
                            : 'Local CLI'}
                          ...
                        </span>
                        <span className="font-mono tabular-nums text-[#E11D48]">
                          {renderJobs[0].progress}%
                        </span>
                      </div>
                      <div className="w-full h-2 bg-zinc-200 rounded-full overflow-hidden">
                        <div
                          className="h-full bg-[#E11D48] transition-all"
                          style={{ width: `${renderJobs[0].progress}%` }}
                        />
                      </div>
                    </div>
                  )}

                {activeProject.renderOutputUrl && (
                  <video
                    src={activeProject.renderOutputUrl}
                    controls
                    className="w-full max-h-[260px] rounded-xl bg-zinc-950"
                  />
                )}

                {activeProject.socialKit && (
                  <div className="p-3 rounded-xl bg-zinc-50 border border-zinc-200 space-y-1.5 text-xs">
                    <div className="font-bold text-zinc-700">
                      Tiêu đề gợi ý đăng TikTok / YouTube / Reels:
                    </div>
                    <div className="text-zinc-900 font-medium">
                      {activeProject.socialKit.suggestedTitles?.[0]}
                    </div>
                    <div className="text-[#E11D48] font-mono text-[11px]">
                      {(activeProject.socialKit.hashtags || []).join(' ')}
                    </div>
                  </div>
                )}
              </div>
            )}
          </div>
        </div>
      )}

      {/* =====================================================================
          5. FLIKI 4-TAB SCENE MEDIA PICKER MODAL
         ===================================================================== */}
      {mediaModalSceneIdx !== null && activeProject && (
        <div className="fixed inset-0 z-50 bg-zinc-950/50 backdrop-blur-xs flex items-center justify-center p-4">
          <div className="bg-white border border-zinc-200 rounded-2xl max-w-4xl w-full max-h-[88vh] flex flex-col shadow-2xl overflow-hidden">
            {/* Modal Header */}
            <div className="px-6 py-4 border-b border-zinc-100 flex items-center justify-between">
              <div>
                <h3 className="text-base font-bold text-zinc-900 flex items-center gap-2">
                  <ImageIcon className="w-4 h-4 text-[#E11D48]" />
                  <span>
                    Chọn hoặc Tạo Media cho Phân cảnh #{mediaModalSceneIdx + 1}: "
                    {localScenes[mediaModalSceneIdx]?.title}"
                  </span>
                </h3>
                <p className="text-xs text-zinc-500 mt-0.5">
                  Chọn từ Kho Tài nguyên đã phân tích Vision AI, tạo ảnh mới bằng FLUX.1/OpenAI, cào trực tiếp từ URL hoặc tìm ảnh thực tế.
                </p>
              </div>
              <Button
                type="button"
                variant="secondary"
                size="sm"
                onClick={() => setMediaModalSceneIdx(null)}
              >
                <X className="w-3.5 h-3.5" />
                <span>Đóng</span>
              </Button>
            </div>

            {/* 4-Tab Bar */}
            <div className="px-6 pt-3 bg-zinc-50 border-b border-zinc-200 flex gap-2 overflow-x-auto">
              {[
                {
                  id: 'library',
                  label: `Kho Tài Nguyên Đã Có (${assets.length})`,
                  Icon: FolderOpen,
                },
                {
                  id: 'ai_gen',
                  label: 'Tạo Ảnh Tham Khảo AI (FLUX.1 / OpenAI)',
                  Icon: Sparkles,
                },
                {
                  id: 'url_scrape',
                  label: 'Cào Ảnh / Logo Từ URL Trang Web',
                  Icon: Globe,
                },
                {
                  id: 'web_search',
                  label: 'Tìm Ảnh Thực Tế Trên Web',
                  Icon: Search,
                },
              ].map((t) => {
                const Icon = t.Icon;
                return (
                  <button
                    key={t.id}
                    type="button"
                    onClick={() => setMediaModalTab(t.id as any)}
                    className={`px-4 py-2.5 rounded-t-xl text-xs font-semibold border-b-2 transition-all cursor-pointer flex items-center gap-1.5 ${
                      mediaModalTab === t.id
                        ? 'bg-white text-[#E11D48] border-[#E11D48]'
                        : 'text-zinc-600 border-transparent hover:text-zinc-900'
                    }`}
                  >
                    <Icon className="w-3.5 h-3.5" />
                    <span>{t.label}</span>
                  </button>
                );
              })}
            </div>

            {/* Modal Content */}
            <div className="p-6 overflow-y-auto flex-1 space-y-4">
              {modalMediaMessage && (
                <div className="p-3 rounded-xl bg-zinc-100 border border-zinc-200 text-xs font-semibold text-zinc-800">
                  {modalMediaMessage}
                </div>
              )}

              {/* TAB 1: ASSET LIBRARY */}
              {mediaModalTab === 'library' && (
                <div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 gap-3.5">
                  {assets.map((ast) => (
                    <div
                      key={ast.id}
                      onClick={() => handleAssignAssetToScene(ast)}
                      className="group border border-zinc-200 hover:border-[#E11D48] rounded-xl overflow-hidden bg-white cursor-pointer shadow-2xs hover:shadow-md transition-all flex flex-col"
                    >
                      <div className="aspect-square bg-zinc-100 relative overflow-hidden">
                        <img
                          src={ast.publicUrl}
                          alt={ast.name}
                          className="w-full h-full object-cover group-hover:scale-105 transition-transform"
                        />
                        <span className="absolute top-2 left-2 px-2 py-0.5 rounded-md bg-zinc-900/75 text-white text-[10px] font-mono font-semibold">
                          {ast.source}
                        </span>
                      </div>
                      <div className="p-2.5">
                        <div className="text-xs font-bold text-zinc-800 truncate">
                          {ast.name}
                        </div>
                        <div className="text-[11px] text-zinc-500 line-clamp-1 mt-0.5">
                          {ast.analysis?.shortCaption ||
                            ast.analysis?.subject ||
                            'Bấm để gán vào cảnh'}
                        </div>
                      </div>
                    </div>
                  ))}
                </div>
              )}

              {/* TAB 2: AI IMAGE GENERATOR */}
              {mediaModalTab === 'ai_gen' && (
                <div className="space-y-3 max-w-2xl">
                  <label className="block text-xs font-semibold text-zinc-700">
                    Prompt mô tả hình ảnh cần tạo cho Phân cảnh #{mediaModalSceneIdx + 1}:
                  </label>
                  <textarea
                    rows={3}
                    value={modalImagePrompt}
                    onChange={(e) => setModalImagePrompt(e.target.value)}
                    className="w-full bg-zinc-50 border border-zinc-200 rounded-xl p-3.5 text-sm text-zinc-900 focus:outline-none focus:border-[#E11D48]"
                    placeholder="Mô tả chi tiết hình ảnh tham khảo cần tạo..."
                  />
                  <Button
                    type="button"
                    variant="primary"
                    onClick={handleModalGenerateAiImage}
                    disabled={modalMediaBusy}
                  >
                    <Sparkles className="w-3.5 h-3.5" />
                    <span>
                      {modalMediaBusy
                        ? 'Đang tạo ảnh AI...'
                        : 'Tạo Ảnh AI Mới & Gán Vào Phân Cảnh Này'}
                    </span>
                  </Button>
                </div>
              )}

              {/* TAB 3: URL SCRAPER */}
              {mediaModalTab === 'url_scrape' && (
                <div className="space-y-3 max-w-2xl">
                  <label className="block text-xs font-semibold text-zinc-700">
                    Nhập URL trang sản phẩm / bài viết cần cào ảnh & logo:
                  </label>
                  <div className="flex gap-2">
                    <input
                      type="url"
                      value={modalScrapeUrl}
                      onChange={(e) => setModalScrapeUrl(e.target.value)}
                      placeholder="https://example.com/product"
                      className="flex-1 bg-zinc-50 border border-zinc-200 rounded-xl px-3.5 py-2 text-sm text-zinc-900"
                    />
                    <Button
                      type="button"
                      variant="primary"
                      onClick={handleModalScrapeUrl}
                      disabled={modalMediaBusy}
                    >
                      <Globe className="w-3.5 h-3.5" />
                      <span>
                        {modalMediaBusy ? 'Đang cào & phân tích...' : 'Cào Ảnh & Phân Tích AI'}
                      </span>
                    </Button>
                  </div>
                </div>
              )}

              {/* TAB 4: WEB SEARCH */}
              {mediaModalTab === 'web_search' && (
                <div className="space-y-3 max-w-2xl">
                  <label className="block text-xs font-semibold text-zinc-700">
                    Từ khóa tìm kiếm hình ảnh thực tế (Wikimedia / Openverse):
                  </label>
                  <div className="flex gap-2">
                    <input
                      type="text"
                      value={modalWebQuery}
                      onChange={(e) => setModalWebQuery(e.target.value)}
                      placeholder="VD: coffee shop, skincare serum, electric car..."
                      className="flex-1 bg-zinc-50 border border-zinc-200 rounded-xl px-3.5 py-2 text-sm text-zinc-900"
                    />
                    <Button
                      type="button"
                      variant="primary"
                      onClick={handleModalSearchWeb}
                      disabled={modalMediaBusy}
                    >
                      <Search className="w-3.5 h-3.5" />
                      <span>{modalMediaBusy ? 'Đang tìm...' : 'Tìm Ảnh Web'}</span>
                    </Button>
                  </div>
                </div>
              )}
            </div>
          </div>
        </div>
      )}

      {/* =====================================================================
          6. HYPERFRAMES HTML5 + GSAP CODE INSPECTOR MODAL
         ===================================================================== */}
      {showCodeModal && (
        <div className="fixed inset-0 z-50 bg-zinc-950/50 backdrop-blur-xs flex items-center justify-center p-4">
          <div className="bg-white border border-zinc-200 rounded-2xl max-w-5xl w-full max-h-[85vh] flex flex-col shadow-2xl overflow-hidden">
            <div className="px-6 py-4 border-b border-zinc-100 flex items-center justify-between">
              <div>
                <h3 className="text-base font-bold text-zinc-900 flex items-center gap-2">
                  <Code2 className="w-4 h-4 text-[#E11D48]" />
                  <span>
                    Mã Nguồn HyperFrames Composition (index.html • Deterministic GSAP)
                  </span>
                </h3>
                <p className="text-xs text-zinc-500 mt-0.5">
                  Đã qua kiểm định JEV & Self-Healing Validator (WCAG AA Contrast, Safe-Zone, __hf Timeline).
                </p>
              </div>
              <Button
                type="button"
                variant="secondary"
                size="sm"
                onClick={() => setShowCodeModal(false)}
              >
                <X className="w-3.5 h-3.5" />
                <span>Đóng</span>
              </Button>
            </div>
            <pre className="p-5 bg-zinc-950 text-emerald-300 text-xs font-mono overflow-auto flex-1 leading-relaxed">
              {rawHtmlCode}
            </pre>
          </div>
        </div>
      )}
    </div>
  );
};