File size: 51,536 Bytes
dc5fc4b
 
 
 
 
a1df431
dc5fc4b
08e9d45
 
dc5fc4b
 
 
 
a1df431
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dc5fc4b
 
 
a1df431
 
dc5fc4b
 
 
a1df431
dc5fc4b
a1df431
 
a46506b
a1df431
dc5fc4b
 
a1df431
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dc5fc4b
a1df431
 
 
 
dc5fc4b
a1df431
 
 
 
 
dc5fc4b
a1df431
 
 
dc5fc4b
a1df431
 
 
 
 
 
dc5fc4b
a1df431
 
 
dc5fc4b
 
 
a1df431
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dc5fc4b
 
a1df431
 
 
 
dc5fc4b
a1df431
 
dc5fc4b
 
 
a1df431
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dc5fc4b
a1df431
 
 
dc5fc4b
a1df431
dc5fc4b
 
a1df431
 
 
dc5fc4b
a1df431
 
 
dc5fc4b
a1df431
dc5fc4b
a1df431
 
 
 
 
 
 
 
 
48834e0
 
 
 
 
a1df431
48834e0
 
a1df431
 
48834e0
 
4d3af0c
48834e0
 
 
 
 
4d3af0c
48834e0
 
 
 
 
 
 
 
 
 
 
 
a1df431
 
 
 
 
dc5fc4b
a1df431
dc5fc4b
a1df431
 
 
 
dc5fc4b
a1df431
 
dc5fc4b
a1df431
 
 
 
 
 
dc5fc4b
a1df431
 
 
 
 
 
dc5fc4b
a1df431
 
 
 
 
dc5fc4b
a1df431
 
dc5fc4b
a1df431
 
 
dc5fc4b
a1df431
 
 
dc5fc4b
a1df431
 
 
dc5fc4b
 
a1df431
 
 
 
dc5fc4b
a1df431
 
 
dc5fc4b
a1df431
 
dc5fc4b
 
 
a1df431
 
 
dc5fc4b
a1df431
dc5fc4b
a1df431
 
 
 
dc5fc4b
a6d1165
 
 
 
 
 
 
 
 
dc5fc4b
a1df431
 
 
 
 
 
 
 
 
dc5fc4b
 
 
 
 
a1df431
dc5fc4b
a1df431
 
dc5fc4b
a1df431
 
 
 
dc5fc4b
a1df431
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dc5fc4b
 
a6d1165
 
 
 
a1df431
 
 
 
 
 
 
 
 
 
 
 
 
 
ade0af5
a1df431
48834e0
a1df431
dc5fc4b
 
a1df431
 
 
 
 
 
 
dc5fc4b
 
a1df431
dc5fc4b
 
a1df431
 
dc5fc4b
 
 
a1df431
dc5fc4b
a1df431
dc5fc4b
 
a1df431
 
dc5fc4b
 
 
a1df431
dc5fc4b
a1df431
 
 
 
 
dc5fc4b
 
 
a1df431
 
dc5fc4b
 
 
a1df431
dc5fc4b
48834e0
 
 
 
a1df431
 
 
dc5fc4b
a1df431
dc5fc4b
a1df431
 
 
 
 
 
 
 
 
 
 
 
ade0af5
 
 
 
 
a1df431
 
 
 
 
 
 
 
 
 
 
 
 
 
dc5fc4b
48834e0
 
 
08e9d45
689aadf
08e9d45
48834e0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
08e9d45
 
 
 
 
 
48834e0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
08e9d45
48834e0
 
08e9d45
 
48834e0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
08e9d45
 
689aadf
08e9d45
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
48834e0
08e9d45
 
48834e0
08e9d45
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
48834e0
08e9d45
48834e0
 
 
 
 
 
 
 
 
 
a1df431
dc5fc4b
 
a1df431
dc5fc4b
 
 
a1df431
 
 
 
 
a6d1165
dc5fc4b
 
 
 
 
 
a1df431
 
dc5fc4b
a1df431
dc5fc4b
a1df431
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
48834e0
dc5fc4b
a6d1165
a1df431
 
dc5fc4b
 
a1df431
 
 
dc5fc4b
a1df431
 
 
 
 
ade0af5
a1df431
dc5fc4b
a1df431
 
 
 
 
 
 
 
 
 
 
 
 
dc5fc4b
 
a1df431
 
 
 
 
ade0af5
a1df431
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ade0af5
a1df431
 
 
ade0af5
a1df431
 
 
 
dc5fc4b
a1df431
 
dc5fc4b
 
a1df431
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0a5169b
a1df431
 
 
ade0af5
a1df431
 
 
 
48834e0
a1df431
 
 
 
 
 
 
 
 
 
 
 
 
48834e0
 
 
 
a1df431
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dc5fc4b
a1df431
 
 
 
 
 
 
dc5fc4b
 
 
 
a1df431
 
 
dc5fc4b
 
a1df431
 
 
 
 
 
 
 
48834e0
 
 
 
 
a1df431
 
 
dc5fc4b
 
 
a1df431
dc5fc4b
 
a1df431
 
dc5fc4b
 
 
a1df431
 
dc5fc4b
 
a1df431
 
dc5fc4b
 
 
 
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
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>ace-step-jam</title>
  <link rel="preconnect" href="https://fonts.googleapis.com" />
  <link href="https://fonts.googleapis.com/css2?family=Hanken+Grotesk:wght@300;400;500;600;700&display=swap" rel="stylesheet" />
  <script src="https://cdn.jsdelivr.net/npm/mp4-muxer@5.1.3/build/mp4-muxer.min.js"></script>
  <style>
    *, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }

    :root {
      --bg:          oklch(0.13 0.006 260);
      --surface:     rgba(255, 255, 255, 0.04);
      --surface-2:   rgba(255, 255, 255, 0.06);
      --surface-3:   rgba(255, 255, 255, 0.09);
      --border:      rgba(255, 255, 255, 0.08);
      --accent:      oklch(0.90 0.005 260);
      --accent-dim:  oklch(0.40 0.005 260);
      --accent-glow: rgba(255, 255, 255, 0.08);
      --progress:    oklch(0.72 0.14 155);
      --text:        rgba(255, 255, 255, 0.87);
      --text-muted:  rgba(255, 255, 255, 0.40);
      --text-faint:  rgba(255, 255, 255, 0.25);
      --error:       oklch(0.68 0.19 22);
      --success:     oklch(0.72 0.14 155);
      --radius:      8px;
      --radius-lg:   10px;
      --font:        'Hanken Grotesk', system-ui, sans-serif;
    }

    html, body {
      height: 100%; background: var(--bg); color: var(--text);
      font-family: var(--font); font-size: 13.5px; line-height: 1.5;
      -webkit-font-smoothing: antialiased;
    }

    body { display: flex; flex-direction: column; min-height: 100vh; }

    /* ── Layout ───────────────────────────────────────────────────────────── */
    .page { display: flex; flex: 1; max-width: 1100px; width: 100%; margin: 0 auto; padding: 28px 20px 0; gap: 20px; align-items: flex-start; }
    .col-left { flex: 1; min-width: 0; max-width: 480px; position: sticky; top: 0; background: var(--bg); }
    .col-right { flex: 1; min-width: 0; }

    /* ── Header ───────────────────────────────────────────────────────────── */
    header { padding: 0 0 20px; text-align: left; }
    .wordmark { display: inline-flex; align-items: center; gap: 8px; margin-bottom: 4px; }
    .wordmark-logo {
      height: 21px; width: auto; color: var(--text); flex-shrink: 0;
    }
    .version {
      font-family: ui-monospace, 'SF Mono', monospace;
      font-size: 10px; font-weight: 500; letter-spacing: 0.03em;
      color: var(--text); border: 1px solid var(--border);
      border-radius: 4px; padding: 1px 5px;
      text-decoration: none; transition: border-color 0.15s, color 0.15s;
    }
    .version:hover { color: var(--text); border-color: rgba(255, 255, 255, 0.15); }
    header p { font-size: 14px; color: var(--text-muted); }

    /* ── Compose box ─────────────────────────────────────────────────────── */
    .compose-box {
      background: var(--surface); border: 1px solid var(--border);
      border-radius: var(--radius-lg); margin-bottom: 10px;
      transition: border-color 0.15s;
    }
    .compose-box:focus-within { border-color: rgba(255, 255, 255, 0.14); }
    .compose-box #description-input {
      background: transparent; border: none; border-radius: var(--radius-lg) var(--radius-lg) 0 0;
      padding: 14px 14px 6px; height: 80px;
    }
    .compose-box #description-input:focus,
    .compose-box #description-input:focus-visible { border: none; outline: none; }
    .compose-controls {
      display: flex; gap: 4px; padding: 4px 10px 10px;
      align-items: center; flex-wrap: wrap;
    }
    .compose-controls .pill {
      background: transparent; border: none; padding: 4px 8px;
      font-size: 11px; border-radius: 6px;
    }
    .compose-controls .pill:hover { background: var(--surface-2); }
    .compose-controls .pill select { font-size: 11px; min-width: 44px; background: transparent; border: none; }
    .compose-controls .pill input[type="checkbox"] { width: 11px; height: 11px; }
    .compose-controls .seed-input {
      width: 48px !important; font-size: 11px !important; padding: 3px 6px !important;
      background: transparent !important; border-radius: 6px !important;
    }
    .compose-controls .generate-btn {
      width: auto; padding: 5px 14px; font-size: 12px;
      border-radius: 6px; letter-spacing: 0;
    }

    /* ── Inputs ───────────────────────────────────────────────────────────── */
    textarea, input[type="text"], input[type="number"], select {
      width: 100%; background: var(--surface-2); border: 1px solid var(--border);
      border-radius: var(--radius); color: var(--text); font-family: var(--font);
      font-size: 13.5px; padding: 9px 11px; outline: none; transition: border-color 0.15s;
    }
    textarea:focus, input:focus, select:focus { border-color: rgba(255, 255, 255, 0.18); }
    textarea:focus-visible, input:focus-visible, select:focus-visible { outline: 1px solid rgba(255, 255, 255, 0.08); outline-offset: 1px; }
    textarea::placeholder, input::placeholder { color: var(--text-faint); }
    textarea { resize: none; }

    #description-input { height: 76px; font-size: 14px; }
    .prompt-hint { margin-top: 6px; font-size: 11px; color: var(--text-faint); }

    /* ── Controls row ─────────────────────────────────────────────────────── */
    .controls-row { display: flex; gap: 6px; margin-bottom: 10px; align-items: center; flex-wrap: wrap; }

    .pill {
      display: inline-flex; align-items: center; gap: 5px;
      font-size: 12px; color: var(--text-muted); cursor: pointer; user-select: none;
      background: var(--surface); border: 1px solid var(--border);
      border-radius: var(--radius); padding: 6px 10px; white-space: nowrap;
      transition: border-color 0.15s;
    }
    .pill:hover { border-color: rgba(255, 255, 255, 0.12); }
    .pill input[type="checkbox"] { width: 12px; height: 12px; accent-color: var(--accent); cursor: pointer; }
    .pill:has(input:checked) span { color: var(--text); }
    .pill select { background: transparent; border: none; color: var(--text); font-size: 12px; padding: 0; min-width: 56px; }

    .seed-input { width: 72px !important; font-size: 12px !important; padding: 6px 8px !important; }
    .spacer { flex: 1; }

    /* ── Generate button ──────────────────────────────────────────────────── */
    .generate-btn {
      width: 100%; background: var(--accent); border: none;
      border-radius: var(--radius); color: oklch(0.13 0.006 260); font-family: var(--font);
      font-size: 14px; font-weight: 600; padding: 11px; cursor: pointer;
      transition: opacity 0.15s, transform 0.1s; letter-spacing: -0.01em;
    }
    .generate-btn:hover:not(:disabled) { opacity: 0.88; }
    .generate-btn:active:not(:disabled) { transform: scale(0.99); }
    .generate-btn:disabled { background: var(--accent-dim); cursor: not-allowed; opacity: 0.5; }
    .generate-btn:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
    .generate-btn.loading { animation: btn-pulse 2s ease-in-out infinite; }
    @keyframes btn-pulse {
      0%, 100% { opacity: 1; }
      50% { opacity: 0.7; }
    }

    /* ── Status ───────────────────────────────────────────────────────────── */
    .status-bar { font-size: 11.5px; color: var(--text-muted); text-align: center; padding: 0; min-height: 0; display: none; }
    .status-bar.error { display: block; color: var(--error); padding: 6px 0; }
    .status-bar.success { display: none; }

    /* ── Output card ──────────────────────────────────────────────────────── */
    .output-card {
      background: var(--surface); border: 1px solid var(--border);
      border-radius: var(--radius-lg); padding: 14px; margin-bottom: 10px;
      animation: fade-in 0.25s ease;
    }
    @keyframes fade-in { from { opacity: 0; transform: translateY(4px); } to { opacity: 1; transform: translateY(0); } }

    #waveform {
      display: flex; align-items: end; gap: 1px; height: 56px;
      background: var(--surface-2); border-radius: var(--radius);
      padding: 8px 10px; cursor: pointer; margin-bottom: 10px;
    }
    #waveform .bar {
      flex: 1; background: var(--text-faint); border-radius: 1px;
      transition: background 0.15s;
    }
    .playback-controls { display: flex; align-items: center; gap: 10px; }
    .play-btn {
      width: 30px; height: 30px; background: var(--accent); border: none;
      border-radius: 50%; color: oklch(0.13 0.006 260); font-size: 12px; cursor: pointer;
      display: flex; align-items: center; justify-content: center; flex-shrink: 0;
      transition: opacity 0.15s;
    }
    .play-btn:hover { opacity: 0.85; }
    .play-btn:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
    .time-display { font-size: 11.5px; color: var(--text-muted); font-variant-numeric: tabular-nums; flex: 1; }
    .download-btn {
      display: inline-flex; align-items: center; gap: 4px; background: #fff;
      border: none; border-radius: 6px; color: #111;
      font-family: var(--font); font-size: 11px;
      font-weight: 600; padding: 5px 10px; cursor: pointer;
      transition: opacity 0.15s;
    }
    .download-btn:hover { opacity: 0.85; }
    .download-btn:disabled { opacity: 0.4; cursor: not-allowed; }
    .download-btn:focus-visible { outline: 2px solid var(--accent); outline-offset: 1px; }

    .share-icon-btn {
      display: inline-flex; align-items: center; justify-content: center;
      width: 16px; height: 16px; background: #fff; border: none; border-radius: 3px;
      color: #111; font-size: 10px; cursor: pointer; flex-shrink: 0; margin-left: 4px;
      transition: opacity 0.15s;
    }
    .share-icon-btn:hover { opacity: 0.85; }
    .share-icon-btn:disabled { opacity: 0.4; cursor: not-allowed; }
    .share-icon-btn svg { width: 9px; height: 9px; }

    /* Video generation overlay */
    .video-overlay {
      position: fixed; inset: 0; background: rgba(0,0,0,0.85);
      display: flex; flex-direction: column; align-items: center; justify-content: center;
      z-index: 100; gap: 12px;
    }
    .video-overlay .label { font-size: 13px; color: var(--text-muted); }
    .video-overlay .pct { font-size: 28px; font-weight: 600; color: var(--text); font-variant-numeric: tabular-nums; }
    .video-overlay .bar-track { width: 200px; height: 3px; background: rgba(255,255,255,0.1); border-radius: 2px; overflow: hidden; }
    .video-overlay .bar-fill { height: 100%; background: #fff; border-radius: 2px; transition: width 0.3s; }

    /* ── Community feed ───────────────────────────────────────────────────── */
    .feed-header {
      font-size: 11px; font-weight: 600; color: var(--text-muted);
      text-transform: uppercase; letter-spacing: 0.06em;
      margin-bottom: 10px;
    }
    .feed-empty { font-size: 12px; color: var(--text-faint); text-align: center; padding: 32px 0; }

    .song-card {
      background: transparent; border: 1px solid transparent;
      border-radius: var(--radius); padding: 8px 10px; margin-bottom: 6px;
      cursor: pointer; transition: background 0.15s;
    }
    .song-card:hover { background: var(--surface); }
    .song-card.playing { background: var(--surface); }

    .song-card-top { display: flex; align-items: center; gap: 8px; margin-bottom: 3px; }
    .song-play-btn {
      width: 26px; height: 26px; background: var(--surface-3); border: 1px solid var(--border);
      border-radius: 50%; color: var(--text-muted); font-size: 10px; cursor: pointer;
      display: flex; align-items: center; justify-content: center; flex-shrink: 0;
      transition: background 0.15s, color 0.15s, border-color 0.15s;
    }
    .song-play-btn:focus-visible { outline: 2px solid var(--accent); outline-offset: 1px; }
    .song-card:hover .song-play-btn { background: rgba(255, 255, 255, 0.08); color: var(--text); border-color: rgba(255, 255, 255, 0.12); }
    .song-card.playing .song-play-btn { background: var(--accent); color: oklch(0.13 0.006 260); border-color: var(--accent); }
    .song-title { font-size: 13px; font-weight: 500; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
    .song-tags { font-size: 11px; color: var(--text-muted); flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; text-align: right; }
    .song-duration { font-size: 11px; color: var(--text-muted); flex-shrink: 0; font-variant-numeric: tabular-nums; margin-left: 8px; }

    /* ── Placeholder (loading state) ──────────────────────────────────────── */
    .placeholder-card {
      background: var(--surface); border: 1px solid rgba(255, 255, 255, 0.12);
      border-radius: var(--radius-lg); padding: 14px;
      margin-bottom: 10px; animation: fade-in 0.25s ease;
    }
    .placeholder-title { font-size: 13px; font-weight: 600; color: var(--text); margin-bottom: 3px; }
    .placeholder-sub { font-size: 11px; color: var(--text-muted); margin-bottom: 10px; }

    .fake-waveform {
      display: flex; align-items: end; gap: 2px; height: 44px;
      background: var(--surface-2); border-radius: var(--radius); padding: 8px 10px;
    }
    .fake-waveform .bar {
      flex: 1; background: var(--accent); border-radius: 1px; opacity: 0.3;
      animation: wave-pulse 1.2s ease-in-out infinite;
    }
    @keyframes wave-pulse {
      0%, 100% { transform: scaleY(0.3); opacity: 0.15; }
      50% { transform: scaleY(1); opacity: 0.4; }
    }

    /* ── Mini waveform ────────────────────────────────────────────────────── */
    .mini-waveform {
      display: flex; align-items: end; gap: 1px; height: 22px; margin-top: 5px;
      cursor: pointer;
    }
    .mini-waveform .bar {
      flex: 1; background: var(--text-faint); border-radius: 1px;
      transition: background 0.2s;
    }
    .song-card.playing .mini-waveform .bar { background: var(--accent); }
    .song-card:hover .mini-waveform .bar { background: rgba(255, 255, 255, 0.22); }

    /* ── Spinner ──────────────────────────────────────────────────────────── */
    .spinner {
      display: inline-block; width: 12px; height: 12px;
      border: 2px solid rgba(0, 0, 0, 0.12); border-top-color: oklch(0.13 0.006 260);
      border-radius: 50%; animation: spin 0.7s linear infinite; vertical-align: middle;
    }
    @keyframes spin { to { transform: rotate(360deg); } }

    /* ── Footer ───────────────────────────────────────────────────────────── */
    footer { padding: 20px; text-align: center; font-size: 11px; color: var(--text-faint); }
    footer a { color: var(--text-muted); text-decoration: none; }
    footer a:hover { color: var(--text); }

    /* ── Upsell ───────────────────────────────────────────────────────────── */
    .upsell {
      font-size: 11px; color: var(--text-faint); text-align: center;
      margin: 6px 0 2px; padding: 0;
    }
    .upsell a { color: var(--text-muted); text-decoration: none; border-bottom: 1px dotted var(--border); }
    .upsell a:hover { color: var(--text); border-bottom-color: var(--text-muted); }
    .upsell.hidden { display: none; }

    /* ── Mobile ───────────────────────────────────────────────────────────── */
    .share-label-short { display: none; }
    @media (max-width: 800px) {
      .page { flex-direction: column; padding: 20px 16px 0; gap: 16px; }
      .col-left, .col-right { max-width: none; width: 100%; }
      .song-card-top .song-tags { display: none; }
      .controls-row { gap: 5px; }
      .seed-input { width: 60px !important; }
      .share-label-full { display: none; }
      .share-label-short { display: inline; }
    }
  </style>
</head>
<body>

  <div class="page">

    <!-- ════ LEFT: Create ════ -->
    <div class="col-left">

      <header>
        <div class="wordmark">
          <svg class="wordmark-logo" viewBox="0 0 1357 390" fill="none" xmlns="http://www.w3.org/2000/svg"><path fill="currentColor" d="M429.554 121.056c25.685-2.701 56.59 8.361 65.05 35.015 6.4 20.237-1.839 45.271-23.479 51.909-10.535 3.243-26.295 1.729-29.56-10.892-1.465-7.657 4.81-15.286 7.43-22.246 2.915-7.759 2.54-20.084-5.83-24.234-12.865-6.234-25.751 10.698-30.446 20.741-11.515 24.623-18.194 66.318-9.654 92.045 15.96 48.099 79.485 21.441 93.715-13.469 1.85-4.537.905-13.069 1.885-18.054 4.24-45.958 30.43-90.954 75.74-106.514 34.455-11.835 78.87-.084 91.26 37.146 4.43 13.542 2.515 29.945-3.84 42.61-14.065 26.676-46.055 36.676-72.945 45.039-6.48 2.225-18.736 5.131-24.076 7.796q.107 1.334.326 2.656c5.275 31.502 38.935 36.362 64.115 25.899 23.91-9.935 38.415-24.933 53.5-45.365 5.055-5.088 11.455-3.266 11.695 4.253.285 5.284-2.34 10.701-4.915 15.32-17.715 31.762-47.551 61.527-83.131 71.447-37.425 10.435-79.034-3.97-97.779-38.678-1.09-2.018-3.645-8.147-5.085-9.36-3.25 2.494-10.835 11.736-14.61 15.398-18.56 17.995-38.876 31.53-64.996 34.715a81.2 81.2 0 0 1-60.209-16.81c-17.921-14.293-27.46-36.077-29.707-58.502-6.195-61.85 28.272-131.158 95.546-137.865m181.456 70.616c5.125-13.489 7.57-43.481-14.165-42.209-24.88 6.91-34.32 59.526-33.31 81.763 5.11-1.34 8.85-2.705 13.775-4.704 15.59-7.135 27.52-18.594 33.7-34.85"/><path fill="currentColor" d="M252.566 31.328c13.489.15 28.638-1.107 40.747 5.829 14.378 8.235 13.358 26.043 14.32 40.355l2.323 33.361 7.744 101.628c1.854 26.297 3.277 52.889 7.327 78.938 1.466 9.43 5.535 20.237 13.799 25.7 2.658 1.75 6.034 4.031 6.681 7.386 2.157 11.18-15.813 8.85-23.014 8.805l-27.869-.166q-14.718-.014-29.435.166c-5.378.055-19.803 1.139-23.314-1.986-6.732-6 9.234-15.974 10.313-24.989 2.273-19.001.231-40.745-1.328-59.509-7.726-2.792-16.639-4.369-24.684-6.138-13.149-2.89-26.221-5.506-39.576-7.317-26.129 49.575-50.203 122.044-116.567 125.219-30.024-.73-51.661-17.32-43.553-49.833 2.48-9.949 16.708-26.894 26.499-15.203 3.194 3.815.678 17.184 3.565 22.031 5.484 10.919 20.75 10.089 29.943 5.274 26.071-13.664 41.425-42.9 54.985-67.806 3.709-6.846 8.069-15.671 10.602-22.698q-2.555-.012-5.109.052c-19.691.564-40.684 9.808-55.07 23.351-4.01 3.776-11.3 15.404-16.445 15.651-6.447.31-8.223-6.662-8.054-12.163.398-13.022 6.724-26.658 16.043-35.764 23.204-21.692 54.274-24.541 84.477-24.073 13.373-27.212 25.61-57.864 37.877-85.805 6.466-14.728 13.866-31.519 18.076-47.027 1.006-3.702.114-6.804-.832-10.394-4.37-4.675-25.115-13.02-5.264-19.847 6.059-2.084 17.892-2.365 24.562-2.782 3.149-.28 7.046-.282 10.231-.246m-11.933 74.358c-2.056 2.836-4.866 10.582-6.357 14.227l-12.001 29.498c-7.084 17.143-15.606 35.261-22.304 52.253 4.745.982 9.285 1.633 14.067 2.339 10.719 1.694 23.779 4.18 34.381 4.855-.456-12.059-4.748-99.339-7.786-103.172M751.392 71.823c-.34-9.52 19.635-7.66 25.921-7.67l26.78-.04c12.231-.03 25.492-.374 37.717.53 1.879.316 5.482 1.365 6.766 2.88 6.272 7.415-6.264 12.926-9.123 19.746-2.577 6.15-3.914 8.925-4.523 15.455-1.488 15.925-1.144 31.855-1.169 47.79l-.324 68.059c-.121 34.375 1.189 67.59-24.984 94.135-36.711 37.23-117.356 35.785-141.56-15.145-4.124-8.675-4.715-18.09-4.655-27.495a47.1 47.1 0 0 1 10.969-26.95c12.532-14.62 37.444-18.11 52.064-4.965a27.12 27.12 0 0 1 8.988 19.43c.401 14.01-6.404 17.145-14.45 25.775-12.126 13.465 3.685 27.82 18.108 25.8 34.753-4.875 30.803-53.81 30.832-79.675l.022-51.27-.083-45.14c-.062-14.645 1.538-35.665-6.982-47.905-2.659-3.745-10.142-8.515-10.314-13.345m195.843-9.245c12.179.095 24.785 2.39 33.048 12.225 8.54 10.165 15.095 43.36 18.885 57.315a4784 4784 0 0 0 33.182 114.901c4.95 16.344 9.74 35.189 16.79 50.634 2.01 4.405 6.36 8.5 10.52 11.01 10.66-9.845 9.61-34.86 9.84-48.38.27-16.265.11-32.69.37-48.98.38-21.295.57-42.59.58-63.89.14-16.01 1.85-34.3-1.62-50.005-1.39-6.29-3.63-11.715-8.4-16.22-1.79-1.68-3.86-3.26-5.09-5.405-.93-1.605-1.16-3.165-.56-4.955.73-2.195 2.16-3.65 4.24-4.62 2.31-1.075 4.81-1.395 7.32-1.61 9.48-.82 64.09-1.63 70.82 1.13 3.59 1.476 7.11 3.465 9.04 6.985 4.07 7.45 7.19 22.705 9.93 31.675 6.89 22.14 13.89 44.245 21.01 66.305 1.7 5.266 9.36 32.903 12.28 34.155 3.93-2.421 13.66-31.838 16.01-38.289l22.7-63.086c2.97-8.45 8.02-25.404 12.63-32.664 6.54-10.29 38.43-5.77 50.05-6.66 7.74-.595 17.31.319 25.1.439 1.84.03 5.8 1.49 7.28 2.775 6.32 6.505-8.06 15.936-10.21 24.03-4.25 16.02-4 33.681-4.07 50.001-.21 46.014-.95 91.855.43 137.839.23 7.98.77 17.025 3.85 24.4 1.8 5.35 11.31 10.78 11.29 16.415-.04 8.814-19.17 6.56-23.92 6.53l-24.93-.05c-11.57.01-23.48.55-34.81.225-13.23-.37-10.68-8.34-3.9-15.13 6.19-6.2 7.38-12.235 8.82-20.59 1.49-12.225 1.48-27.015 1.52-39.31l.08-43.34c.01-4.711.82-35.563-1.29-36.875-3.11 1.92-5.99 12.945-7.48 16.735-2.81 7.115-5.56 14.42-8.26 21.59l-28.89 77.345c-3.79 10.19-7.2 20.715-11.81 30.535-4.6 9.945-21.68 7.62-26.25-.93-6.24-11.665-10.05-27.12-14.24-39.845l-25.75-78.195c-1.55-4.689-8.26-28.116-11.64-28.965-1.32 1.15-1.96 4.495-1.99 6.17-.75 34.63-.79 69.4-.67 104.045.03 11.2 1.09 22.405 9.76 30.435 1.59 1.63 5.91 5.895 6.31 8.04 2.11 11.404-22.14 8.28-29.52 8.205l-35.05-.27-61.452-.04c-7.77.02-15.615.57-23.372.37-2.238-.06-6.194.01-8.107-1.214-1.381-.885-2.384-2.471-2.7-4.071-.959-4.86 5.28-9.225 7.673-12.98 6.088-9.545.193-28.165-2.33-38.38-.971-3.935-2.246-9.53-6.087-11.63-6.617-3.62-51.072-4.499-59.105-2.185-2.513.725-3.717 2.395-4.872 4.63-4.31 8.35-10.534 31.55-9.323 40.77.252 1.92 1.094 3.74 2.121 5.365 2.362 3.735 7.774 6.501 8.939 10.775.49 1.8.036 3.635-.991 5.16-1.309 1.939-2.962 2.64-5.191 3.11-7.781 1.635-27.562.18-36.554.245-6.542.045-13.637 1.1-20.092.515-2.462-.225-5.183-.915-7.202-2.4-1.51-1.11-2.693-2.71-2.759-4.645-.174-5.1 6.625-9.225 9.585-12.93 3.854-4.82 6.477-10.545 8.774-16.23 13.148-32.555 23.034-66.76 34.557-99.94l20.711-60.995c3.423-10.25 7.955-21.985 9.888-32.605 3.471-8.28-9.124-18.955-9.128-22.945-.009-9.225 38.877-11.295 43.682-11.575m-9.769 79.41c-2.886 3.83-24.901 73.496-24.944 78.31 3.007 2.44 15.374 1.64 19.785 1.575 4.813 0 21.568 1.005 24.674-1.604.802-.676.618-3.005.565-3.965-.305-5.51-15.823-71.054-17.593-72.785-.732-.715-1.577-1.106-2.487-1.531"/></svg>
          <a href="https://huggingface.co/ACE-Step/acestep-v15-xl-turbo" target="_blank" class="version">ACE-Step v1.5</a>
        </div>
        <p>Describe any song. AI writes &amp; produces it.</p>
      </header>

      <div class="compose-box">
        <textarea id="description-input"
          placeholder="A chill lo-fi track for studying, ninja battle anthem, love song about AI..."
        ></textarea>
        <div class="compose-controls">
          <label class="pill">
            <select id="duration-select">
              <option value="30">30s</option>
              <option value="60" selected>1 min</option>
              <option value="120">2 min</option>
            </select>
          </label>
          <label class="pill"><input type="checkbox" id="instrumental-check" /><span>Instrumental</span></label>
          <label class="pill"><input type="checkbox" id="community-check" checked /><span class="share-label-full">Share in community</span><span class="share-label-short">Share</span></label>
          <span class="spacer"></span>
          <button class="generate-btn" id="generate-btn">Generate</button>
        </div>
      </div>
      <p class="upsell" id="upsell-ace-studio">
        Want more control &amp; longer songs?
        <a href="https://acestudio.ai/" target="_blank" rel="noopener">Try ACE Studio β†’</a>
      </p>
      <div class="status-bar" id="status-bar"></div>

      <!-- Output -->
      <div id="output-section" style="display:none">
        <div class="output-card">
          <div style="display:flex;gap:10px;margin-bottom:8px;">
            <img id="song-thumb" style="width:48px;height:48px;border-radius:6px;object-fit:cover;display:none;" />
            <div style="min-width:0;flex:1;">
              <div id="song-title" style="font-size:13px;font-weight:600;margin-bottom:3px;"></div>
              <div id="song-tags" style="font-size:11px;color:var(--text-muted);"></div>
            </div>
          </div>
          <div id="waveform"></div>
          <div class="playback-controls">
            <button class="play-btn" id="play-btn" title="Play / Pause"><svg width="10" height="12" viewBox="0 0 10 12" fill="currentColor"><path d="M0 0l10 6-10 6z"/></svg></button>
            <span class="time-display" id="time-display">0:00 / 0:00</span>
            <button class="download-btn" id="download-btn">⬇ Download</button>
          </div>
        </div>
      </div>

    </div>

    <!-- ════ RIGHT: Community feed ════ -->
    <div class="col-right">
      <div class="feed-header">Community Songs</div>
      <div id="feed"></div>
    </div>

  </div>

  <footer>
    Powered by <a href="https://github.com/ace-step/ACE-Step" target="_blank">ACE-Step</a> Β·
    <a href="https://huggingface.co/ACE-Step/acestep-v15-xl-turbo" target="_blank">Model card</a>
  </footer>

  <script type="module">
    // ── ZeroGPU auth ──────────────────────────────────────────────────────────
    const ZEROGPU_HEADERS_MSG = "supports-zerogpu-headers";
    window.addEventListener("message", (e) => { if (e.data === ZEROGPU_HEADERS_MSG) window.supports_zerogpu_headers = true; });
    const _hn = window.location.hostname;
    if (_hn.endsWith(".hf.space") || _hn.includes(".dev.")) {
      const _o = _hn.includes(".dev.") ? `https://moon-${_hn.split(".")[1]}.dev.spaces.huggingface.tech` : "https://huggingface.co";
      window.parent.postMessage(ZEROGPU_HEADERS_MSG, _o);
    }

    import { Client } from "https://cdn.jsdelivr.net/npm/@gradio/client@1.15.2/dist/index.min.js";
    // WaveSurfer removed β€” using lightweight bar waveform with real audio peaks

    // ── DOM ──────────────────────────────────────────────────────────────────
    const descInput       = document.getElementById("description-input");
    const durationSelect  = document.getElementById("duration-select");
    const instrumentalChk = document.getElementById("instrumental-check");
    const communityChk    = document.getElementById("community-check");
    const generateBtn     = document.getElementById("generate-btn");
    const statusBar       = document.getElementById("status-bar");
    const outputSection   = document.getElementById("output-section");
    const songTitleEl     = document.getElementById("song-title");
    const songTagsEl      = document.getElementById("song-tags");
    const playBtn         = document.getElementById("play-btn");
    const timeDisplay     = document.getElementById("time-display");
    const downloadBtn     = document.getElementById("download-btn");
    const feedEl          = document.getElementById("feed");

    downloadBtn.addEventListener("click", () => {
      if (currentSong) generateShareVideo(currentSong, downloadBtn);
    });

    // ── Main player (plain Audio + bar waveform) ─────────────────────────────
    const mainAudio = new Audio();
    const waveformEl = document.getElementById("waveform");

    function fmt(s) { return `${Math.floor(s/60)}:${Math.floor(s%60).toString().padStart(2,"0")}`; }
    function updateTime() {
      const c = mainAudio.currentTime || 0, d = mainAudio.duration || 0;
      timeDisplay.textContent = `${fmt(c)} / ${fmt(d)}`;
    }
    function updateMainProgress() {
      if (mainAudio.paused && mainAudio.currentTime === 0) return;
      const pct = mainAudio.duration ? mainAudio.currentTime / mainAudio.duration : 0;
      waveformEl.querySelectorAll(".bar").forEach((b, i, arr) => {
        b.style.background = (i / arr.length) <= pct ? "var(--accent)" : "";
      });
      updateTime();
      if (!mainAudio.paused) requestAnimationFrame(updateMainProgress);
    }
    const playIcon = '<svg width="10" height="12" viewBox="0 0 10 12" fill="currentColor"><path d="M0 0l10 6-10 6z"/></svg>';
    const pauseIcon = '<svg width="10" height="12" viewBox="0 0 10 12" fill="currentColor"><rect x="0" y="0" width="3" height="12"/><rect x="7" y="0" width="3" height="12"/></svg>';
    mainAudio.addEventListener("play", () => { playBtn.innerHTML = pauseIcon; requestAnimationFrame(updateMainProgress); });
    mainAudio.addEventListener("pause", () => { playBtn.innerHTML = playIcon; });
    mainAudio.addEventListener("ended", () => { playBtn.innerHTML = playIcon; waveformEl.querySelectorAll(".bar").forEach(b => b.style.background = ""); });
    mainAudio.addEventListener("timeupdate", updateTime);

    playBtn.addEventListener("click", () => { stopFeedAudio(); mainAudio.paused ? mainAudio.play() : mainAudio.pause(); });

    waveformEl.addEventListener("click", (e) => {
      const rect = waveformEl.getBoundingClientRect();
      const ratio = Math.max(0, Math.min(1, (e.clientX - rect.left) / rect.width));
      if (mainAudio.duration) {
        stopFeedAudio();
        mainAudio.currentTime = mainAudio.duration * ratio;
        if (mainAudio.paused) mainAudio.play();
        requestAnimationFrame(updateMainProgress);
      }
    });

    // ── Current song state (for video generation) ────────────────────────────
    let currentSong = null;

    // ── Fast video generation (WebCodecs + MP4 muxer) ─────────────────────
    const { Muxer: Mp4MuxerClass, ArrayBufferTarget } = Mp4Muxer;

    async function generateShareVideo(song, btn) {
      const origHTML = btn.innerHTML;
      btn.disabled = true;
      btn.textContent = "…";
      stopFeedAudio();
      mainAudio.pause();

      const overlay = document.createElement("div");
      overlay.className = "video-overlay";
      overlay.innerHTML = `
        <div class="label">Generating video…</div>
        <div class="pct" id="vid-pct">0%</div>
        <div class="bar-track"><div class="bar-fill" id="vid-bar" style="width:0%"></div></div>
      `;
      document.body.appendChild(overlay);
      const pctEl = overlay.querySelector("#vid-pct");
      const barEl = overlay.querySelector("#vid-bar");

      try {
        await document.fonts.ready;

        const audioResp = await fetch(song.audio_url);
        const audioArrayBuf = await audioResp.arrayBuffer();
        const offCtx = new OfflineAudioContext(2, 1, 44100);
        const decoded = await offCtx.decodeAudioData(audioArrayBuf);

        const sampleRate = decoded.sampleRate;
        const numChannels = decoded.numberOfChannels;
        const audioLength = decoded.length;

        const raw = decoded.getChannelData(0);
        const numBars = 60;
        const blockSize = Math.floor(raw.length / numBars);
        const peaks = [];
        for (let i = 0; i < numBars; i++) {
          let sum = 0;
          for (let j = 0; j < blockSize; j++) sum += Math.abs(raw[i * blockSize + j]);
          peaks.push(sum / blockSize);
        }
        const mx = Math.max(...peaks);
        const normPeaks = peaks.map(p => mx > 0 ? p / mx : 0.5);

        let thumbImg = null;
        if (song.thumb_url) {
          thumbImg = new Image();
          thumbImg.crossOrigin = "anonymous";
          await new Promise(r => { thumbImg.onload = r; thumbImg.onerror = r; thumbImg.src = song.thumb_url; });
        }

        const W = 1080, H = 1080;
        const canvas = document.createElement("canvas");
        canvas.width = W; canvas.height = H;
        const ctx = canvas.getContext("2d", { willReadFrequently: true });

        const duration = decoded.duration;
        const FPS = 15;
        const totalFrames = Math.ceil(duration * FPS);

        function drawFrame(progress) {
          ctx.fillStyle = "#111111";
          ctx.fillRect(0, 0, W, H);

          const topY = 120;
          if (thumbImg && thumbImg.naturalWidth > 0) {
            ctx.save();
            ctx.beginPath();
            ctx.roundRect(90, topY, 120, 120, 14);
            ctx.clip();
            ctx.drawImage(thumbImg, 90, topY, 120, 120);
            ctx.restore();
          }

          const textX = thumbImg && thumbImg.naturalWidth > 0 ? 230 : 90;
          ctx.fillStyle = "#ffffff";
          ctx.font = "600 36px 'Hanken Grotesk', sans-serif";
          ctx.textAlign = "left";
          ctx.textBaseline = "middle";
          let title = song.title || "Untitled";
          while (ctx.measureText(title).width > W - textX - 90 && title.length > 3) title = title.slice(0, -1);
          if (title !== song.title) title += "…";
          ctx.fillText(title, textX, topY + 45);

          ctx.fillStyle = "rgba(255,255,255,0.45)";
          ctx.font = "400 22px 'Hanken Grotesk', sans-serif";
          let tags = song.tags || "";
          while (ctx.measureText(tags).width > W - textX - 90 && tags.length > 3) tags = tags.slice(0, -1);
          if (tags !== song.tags) tags += "…";
          ctx.fillText(tags, textX, topY + 90);

          const waveY = 440, waveH = 220, pad = 80;
          const totalW = W - pad * 2;
          const gap = 3;
          const barW = (totalW - (numBars - 1) * gap) / numBars;
          for (let i = 0; i < numBars; i++) {
            const x = pad + i * (barW + gap);
            const h = Math.max(4, normPeaks[i] * waveH);
            ctx.fillStyle = (i / numBars) <= progress ? "rgba(255,255,255,0.92)" : "rgba(255,255,255,0.15)";
            ctx.beginPath();
            ctx.roundRect(x, waveY + (waveH - h) / 2, barW, h, Math.min(barW / 2, 3));
            ctx.fill();
          }

          ctx.textAlign = "center";
          ctx.fillStyle = "rgba(255,255,255,0.40)";
          ctx.font = "400 36px 'Hanken Grotesk', sans-serif";
          ctx.fillText("Create your own song:", W / 2, 880);
          ctx.fillStyle = "rgba(255,255,255,0.55)";
          ctx.font = "500 33px 'Hanken Grotesk', sans-serif";
          ctx.fillText("hf.co/spaces/victor/ace-step-jam", W / 2, 930);
          ctx.textAlign = "left";
        }

        // ── Encode with WebCodecs + MP4 muxer ──
        const target = new ArrayBufferTarget();
        const muxer = new Mp4MuxerClass({
          target,
          video: { codec: "avc", width: W, height: H },
          audio: { codec: "aac", sampleRate, numberOfChannels: numChannels },
          firstTimestampBehavior: "offset",
          fastStart: "in-memory",
        });

        const audioEncoder = new AudioEncoder({
          output: (chunk, meta) => muxer.addAudioChunk(chunk, meta),
          error: e => console.error("AudioEncoder error:", e),
        });
        audioEncoder.configure({ codec: "mp4a.40.2", sampleRate, numberOfChannels: numChannels, bitrate: 128_000 });

        const audioChunkSize = 4096;
        for (let offset = 0; offset < audioLength; offset += audioChunkSize) {
          const len = Math.min(audioChunkSize, audioLength - offset);
          const audioData = new AudioData({
            format: "f32-planar", sampleRate, numberOfFrames: len, numberOfChannels: numChannels,
            timestamp: (offset / sampleRate) * 1_000_000,
            data: (() => {
              const buf = new Float32Array(len * numChannels);
              for (let ch = 0; ch < numChannels; ch++) {
                buf.set(decoded.getChannelData(ch).subarray(offset, offset + len), ch * len);
              }
              return buf;
            })(),
          });
          audioEncoder.encode(audioData);
          audioData.close();
        }
        await audioEncoder.flush();

        const videoEncoder = new VideoEncoder({
          output: (chunk, meta) => muxer.addVideoChunk(chunk, meta),
          error: e => console.error("VideoEncoder error:", e),
        });
        videoEncoder.configure({ codec: "avc1.640028", width: W, height: H, bitrate: 2_000_000, framerate: FPS });

        let frameIdx = 0;
        const batchSize = 5;
        await new Promise((resolve) => {
          function processBatch() {
            const end = Math.min(frameIdx + batchSize, totalFrames);
            for (; frameIdx < end; frameIdx++) {
              const progress = frameIdx / totalFrames;
              drawFrame(progress);
              const frame = new VideoFrame(canvas, { timestamp: (frameIdx / FPS) * 1_000_000 });
              videoEncoder.encode(frame, { keyFrame: frameIdx % (FPS * 2) === 0 });
              frame.close();
            }
            pctEl.textContent = `${Math.round((frameIdx / totalFrames) * 100)}%`;
            barEl.style.width = `${Math.round((frameIdx / totalFrames) * 100)}%`;
            if (frameIdx < totalFrames) setTimeout(processBatch, 0);
            else {
              videoEncoder.flush().then(() => {
                muxer.finalize();
                const blob = new Blob([target.buffer], { type: "video/mp4" });
                const url = URL.createObjectURL(blob);
                const a = document.createElement("a");
                a.href = url;
                const safeName = (song.title || "song").replace(/[^a-zA-Z0-9 -]/g, "").trim().replace(/\s+/g, "-") || "song";
                a.download = `${safeName}.mp4`;
                a.click();
                URL.revokeObjectURL(url);
                resolve();
              });
            }
          }
          processBatch();
        });
      } catch (e) {
        console.error("Video generation failed:", e);
      } finally {
        overlay.remove();
        btn.disabled = false;
        btn.innerHTML = origHTML;
      }
    }

    // ── Gradio client ───────────────────────────────────────────────────────
    let gradioClient = null;
    async function getClient() {
      if (!gradioClient) gradioClient = await Client.connect(window.location.origin);
      return gradioClient;
    }

    // ── UI helpers ──────────────────────────────────────────────────────────
    function setLoading(on) {
      generateBtn.disabled = on;
      if (on) { generateBtn.innerHTML = '<span class="spinner"></span> Creating…'; generateBtn.classList.add("loading"); }
      else    { generateBtn.textContent = "Generate"; generateBtn.classList.remove("loading"); }
      if (on) document.getElementById("upsell-ace-studio")?.classList.add("hidden");
    }
    function setStatus(msg, type = "") {
      statusBar.textContent = msg;
      statusBar.className = "status-bar" + (type ? ` ${type}` : "");
    }

    async function loadAudio(dataUrl) {
      const res = await fetch(dataUrl);
      const blob = await res.blob();
      const url = URL.createObjectURL(blob);

      // Extract real peaks for bar waveform
      const numBars = 80;
      try {
        const buf = await blob.arrayBuffer();
        const ctx = new (window.AudioContext || window.webkitAudioContext)();
        const decoded = await ctx.decodeAudioData(buf);
        const raw = decoded.getChannelData(0);
        const block = Math.floor(raw.length / numBars);
        const peaks = [];
        for (let i = 0; i < numBars; i++) {
          let sum = 0;
          for (let j = 0; j < block; j++) sum += Math.abs(raw[i * block + j]);
          peaks.push(sum / block);
        }
        const mx = Math.max(...peaks);
        waveformEl.innerHTML = peaks.map(p => {
          const h = mx > 0 ? 15 + (p / mx) * 85 : 50;
          return `<div class="bar" style="height:${h}%"></div>`;
        }).join("");
      } catch {
        waveformEl.innerHTML = Array.from({length: numBars}, () =>
          `<div class="bar" style="height:${15 + Math.random() * 85}%"></div>`
        ).join("");
      }

      mainAudio.src = url;
      currentSong = { ...currentSong, audio_url: url };
      outputSection.style.display = "block";
      document.getElementById("upsell-ace-studio")?.classList.add("hidden");
      stopFeedAudio();
      mainAudio.play();
    }

    // ── Community feed player ───────────────────────────────────────────────
    let feedAudio = null;
    let playingCard = null;

    function stopFeedAudio() {
      if (feedAudio) { feedAudio.pause(); feedAudio = null; }
      if (playingCard) {
        playingCard.querySelectorAll(".mini-waveform .bar").forEach(b => b.style.background = "");
        playingCard.classList.remove("playing");
        playingCard.querySelector(".song-play-btn").innerHTML = '<svg width="8" height="10" viewBox="0 0 10 12" fill="currentColor"><path d="M0 0l10 6-10 6z"/></svg>';
        playingCard = null;
      }
    }

    function playFeedSong(card, audioUrl, seekRatio) {
      // If same card and already playing, just seek (or pause if clicking play btn)
      if (playingCard === card && feedAudio) {
        if (seekRatio != null) {
          feedAudio.currentTime = feedAudio.duration * seekRatio;
          if (feedAudio.paused) feedAudio.play();
        } else {
          // Toggle play/pause (clicked the play button)
          if (feedAudio.paused) { feedAudio.play(); }
          else { feedAudio.pause(); }
        }
        return;
      }
      stopFeedAudio();
      mainAudio.pause();
      feedAudio = new Audio(audioUrl);
      playingCard = card;
      card.classList.add("playing");
      card.querySelector(".song-play-btn").innerHTML = '<svg width="8" height="10" viewBox="0 0 10 12" fill="currentColor"><rect x="0" y="0" width="3" height="12"/><rect x="7" y="0" width="3" height="12"/></svg>';
      feedAudio.play();
      if (seekRatio != null) {
        feedAudio.addEventListener("loadedmetadata", () => {
          feedAudio.currentTime = feedAudio.duration * seekRatio;
        }, { once: true });
      }
      // Update waveform progress during playback
      const waveEl = card.querySelector(".mini-waveform");
      const bars = waveEl ? waveEl.querySelectorAll(".bar") : [];
      function updateProgress() {
        if (playingCard !== card || !feedAudio || feedAudio.paused) return;
        const pct = feedAudio.currentTime / feedAudio.duration;
        bars.forEach((b, i) => {
          b.style.background = (i / bars.length) <= pct ? "var(--accent)" : "var(--text-faint)";
        });
        requestAnimationFrame(updateProgress);
      }
      if (bars.length) requestAnimationFrame(updateProgress);
      feedAudio.addEventListener("ended", () => {
        bars.forEach(b => b.style.background = "");
        stopFeedAudio();
      });
      feedAudio.addEventListener("error", () => stopFeedAudio());
      feedAudio.addEventListener("pause", () => {
        if (playingCard === card) card.querySelector(".song-play-btn").innerHTML = '<svg width="8" height="10" viewBox="0 0 10 12" fill="currentColor"><path d="M0 0l10 6-10 6z"/></svg>';
      });
      feedAudio.addEventListener("play", () => {
        if (playingCard === card) {
          card.querySelector(".song-play-btn").innerHTML = '<svg width="8" height="10" viewBox="0 0 10 12" fill="currentColor"><rect x="0" y="0" width="3" height="12"/><rect x="7" y="0" width="3" height="12"/></svg>';
          requestAnimationFrame(updateProgress);
        }
      });
    }

    // ── Load community feed ─────────────────────────────────────────────────
    async function loadFeed() {
      try {
        const client = await getClient();
        const res = await client.predict("/community");
        // Gradio JS client may return {data: [...]} or the value directly
        const raw = res?.data?.[0] ?? res?.data ?? res;
        const songs = JSON.parse(typeof raw === "string" ? raw : JSON.stringify(raw) || "[]");
        if (songs.length === 0) {
          feedEl.innerHTML = '<div class="feed-empty">No community songs yet.<br>Be the first β€” check "Share" and generate!</div>';
          return;
        }
        feedEl.innerHTML = "";
        for (const song of songs) {
          const card = document.createElement("div");
          card.className = "song-card";
          const dur = song.duration ? `${Math.round(song.duration)}s` : "";
          // Generate random mini waveform bars (seeded from title for consistency)
          const miniBars = Array.from({length: 80}, () =>
            `<div class="bar" style="height:${15 + Math.random() * 85}%"></div>`
          ).join("");
          const thumbHtml = song.thumb_url
            ? `<img src="${esc(song.thumb_url)}" style="width:24px;height:24px;border-radius:4px;object-fit:cover;flex-shrink:0;" loading="lazy" onerror="this.style.display='none'" />`
            : '';
          card.innerHTML = `
            <div class="song-card-top">
              <button class="song-play-btn"><svg width="8" height="10" viewBox="0 0 10 12" fill="currentColor"><path d="M0 0l10 6-10 6z"/></svg></button>
              ${thumbHtml}
              <div class="song-title">${esc(song.title || "Untitled")}</div>
              <div class="song-tags">${esc(song.tags || "")}</div>
              <div class="song-duration">${dur}</div>
              <button class="share-icon-btn" title="Download video"><svg viewBox="0 0 16 16" fill="currentColor"><path d="M3.5 13V8.5h1V12h7V8.5h1V13a.5.5 0 01-.5.5H4a.5.5 0 01-.5-.5zM8 10.25L4.75 7h2V2.5h2.5V7h2L8 10.25z"/></svg></button>
            </div>
            <div class="mini-waveform">${miniBars}</div>
          `;
          card.querySelector(".song-play-btn").addEventListener("click", (e) => {
            e.stopPropagation();
            playFeedSong(card, song.audio_url);
          });
          card.querySelector(".mini-waveform").addEventListener("click", (e) => {
            e.stopPropagation();
            const rect = e.currentTarget.getBoundingClientRect();
            const ratio = Math.max(0, Math.min(1, (e.clientX - rect.left) / rect.width));
            playFeedSong(card, song.audio_url, ratio);
          });
          card.querySelector(".share-icon-btn").addEventListener("click", (e) => {
            e.stopPropagation();
            generateShareVideo(song, e.currentTarget);
          });
          feedEl.appendChild(card);
        }
      } catch (e) {
        console.error("Feed load error:", e);
        feedEl.innerHTML = '<div class="feed-empty">Could not load community songs</div>';
      }
    }

    function esc(s) { const d = document.createElement("div"); d.textContent = s; return d.innerHTML; }

    // ── Generate ─────────────────────────────────────────────────────────────
    generateBtn.addEventListener("click", async () => {
      let desc = descInput.value.trim();
      if (!desc) { setStatus("Describe the song you want to create", "error"); descInput.focus(); return; }
      if (instrumentalChk.checked) desc += " (instrumental, no vocals)";

      stopFeedAudio();
      setLoading(true);
      setStatus("");

      // Show animated placeholder on the left, above output
      outputSection.style.display = "none";
      const placeholder = document.createElement("div");
      placeholder.className = "placeholder-card";
      placeholder.id = "gen-placeholder";
      const bars = Array.from({length: 40}, (_, i) =>
        `<div class="bar" style="height:100%;animation-delay:${(i * 0.06).toFixed(2)}s"></div>`
      ).join("");
      placeholder.innerHTML = `
        <div class="placeholder-title">${esc(desc.slice(0, 80))}</div>
        <div class="placeholder-sub">Composing &amp; generating…</div>
        <div class="fake-waveform">${bars}</div>
      `;
      outputSection.parentNode.insertBefore(placeholder, outputSection);

      try {
        const client = await getClient();
        const job = client.submit("/create", {
          description: desc,
          audio_duration: parseFloat(durationSelect.value),
          seed: -1,
          community: communityChk.checked,
        });

        for await (const msg of job) {
          if (msg.type === "status") {
            if (msg.queue_size > 0) {
              const eta = msg.eta != null ? ` Β· ~${Math.round(msg.eta)}s` : "";
              setStatus(`Queue ${msg.position}/${msg.queue_size}${eta}`);
            }
          } else if (msg.type === "data") {
            const raw = msg.data?.[0];
            if (!raw) throw new Error("No data returned");
            const result = JSON.parse(raw);
            songTitleEl.textContent = result.title || "";
            songTagsEl.textContent = result.tags || "";
            const thumbEl = document.getElementById("song-thumb");
            if (result.thumbnail) { thumbEl.src = result.thumbnail; thumbEl.style.display = "block"; }
            else { thumbEl.style.display = "none"; }
            currentSong = {
              title: result.title || "Untitled",
              tags: result.tags || "",
              thumb_url: result.thumbnail || null,
            };
            await loadAudio(result.audio);
            // Refresh feed if shared
            if (communityChk.checked) loadFeed();
          }
        }
      } catch (err) {
        console.error(err);
        setStatus(`Error: ${err.message}`, "error");
      } finally {
        placeholder.remove();
        setLoading(false);
      }
    });

    descInput.addEventListener("keydown", (e) => {
      if ((e.metaKey || e.ctrlKey) && e.key === "Enter") { e.preventDefault(); generateBtn.click(); }
    });

    // ── Init ─────────────────────────────────────────────────────────────────
    getClient().then(() => loadFeed()).catch(console.error);
  </script>

</body>
</html>