File size: 233,098 Bytes
0b4ac11
71cad45
a515c85
1af2cba
ac490ae
0b4ac11
aee79c9
1b765ca
ba9e4dc
c27967a
482a617
 
 
 
 
620c39a
e136ba6
3f0189a
a4ad87e
a515c85
494db15
50c6100
539a0b9
6d3b450
482dcd8
 
61cb1f1
0ed74ae
d9830ba
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
823995d
620c39a
823995d
482a617
0b4ac11
ce6bce9
482a617
 
482dcd8
a4ad87e
 
482a617
 
 
482dcd8
a4ad87e
 
482a617
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3acf8c3
482a617
 
 
 
 
 
 
a4ad87e
 
 
 
 
 
 
 
 
 
 
 
 
 
482a617
 
 
 
 
 
 
 
 
 
 
 
 
3acf8c3
 
482a617
 
 
 
 
 
 
 
3acf8c3
 
 
482a617
3acf8c3
 
482a617
3acf8c3
482a617
3acf8c3
482a617
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3acf8c3
 
5d28904
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
823995d
508dba9
 
 
 
773a66f
 
 
 
1af2cba
 
 
00d8c9c
1af2cba
faa0818
8d2c63c
a8323ae
cb61e26
123ce36
d9830ba
c27967a
 
 
508dba9
77bce56
 
bf6dd9c
 
 
 
 
 
823995d
508dba9
 
6d3b450
 
5d28904
 
482dcd8
 
823995d
 
9dc14f3
50ae26a
17509ae
 
 
 
 
 
1b765ca
 
17509ae
 
 
1b765ca
 
 
 
0a41a32
123ce36
27dc058
 
 
123ce36
0a41a32
 
38512ac
 
 
 
 
 
 
 
 
 
2ceb9b4
ac490ae
2ceb9b4
 
 
 
 
 
c6e0817
9dc14f3
 
 
 
a4e0359
 
 
c6e0817
9dc14f3
 
d7919ff
 
db214bb
 
 
 
 
 
 
 
 
 
 
 
0ed74ae
d7919ff
50ae26a
d7919ff
50ae26a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0b4ac11
50ae26a
a515c85
9cea1a9
50ae26a
 
a515c85
0b4ac11
482dcd8
0b4ac11
50ae26a
9cea1a9
 
 
 
 
 
 
 
 
 
50ae26a
 
 
 
 
 
 
71cad45
50ae26a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a515c85
50ae26a
 
 
 
 
 
 
 
 
496a77c
0b4ac11
9cea1a9
a515c85
50ae26a
 
 
 
 
 
 
 
 
 
 
a515c85
50ae26a
 
 
 
 
 
 
 
 
a515c85
50ae26a
 
 
 
71cad45
 
50ae26a
 
 
5d28904
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
496a77c
5d28904
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
496a77c
5d28904
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
682a86e
5d28904
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
71cad45
 
 
 
 
 
 
 
 
 
 
f58297b
 
bca6f9b
f58297b
 
 
 
 
 
bca6f9b
 
a4e0359
50b84fe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bf6dd9c
1af2cba
aee79c9
a515c85
ac490ae
5d28904
539a0b9
 
 
 
1af2cba
50ae26a
5d28904
 
 
 
9dc14f3
50ae26a
77bce56
1af2cba
823995d
50ae26a
 
 
f58297b
 
1b765ca
 
 
620c39a
3acf8c3
 
77bce56
db214bb
d9830ba
 
 
 
77bce56
cb61e26
123ce36
77bce56
ce6bce9
b05fdf3
1b765ca
 
 
 
 
77bce56
 
 
 
 
2859be5
 
2ceb9b4
17aa277
 
46a41a4
 
 
 
77bce56
50ae26a
1af2cba
db214bb
d9830ba
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c27967a
 
d9830ba
 
 
 
 
cb61e26
123ce36
50ae26a
 
0ed74ae
 
1e6ba7c
50ae26a
d7919ff
50ae26a
3acf8c3
 
 
 
50ae26a
c27967a
 
 
 
 
 
 
a8323ae
ce6bce9
b05fdf3
482a617
482dcd8
482a617
620c39a
fc41158
 
 
2ceb9b4
17aa277
bf6dd9c
 
 
50ae26a
50c6100
 
 
 
 
 
 
 
 
482a617
3acf8c3
 
 
ce6bce9
 
f524325
7437837
50ae26a
773a66f
9d2278b
 
1af2cba
 
00d8c9c
1af2cba
21ee370
50ae26a
4e08a32
 
 
1af2cba
a8323ae
a515c85
3acf8c3
 
 
 
 
 
a82506c
 
0b4ac11
a515c85
482dcd8
 
0b4ac11
 
1bcca6b
 
 
 
 
 
0b4ac11
 
 
 
 
 
 
 
 
a515c85
cb61e26
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
747e93d
123ce36
 
38512ac
 
 
 
747e93d
 
0a41a32
747e93d
 
 
 
 
 
 
 
 
 
 
2ceb9b4
ac490ae
2ceb9b4
 
 
 
747e93d
 
 
2ceb9b4
ac490ae
747e93d
2ceb9b4
747e93d
 
 
 
2ceb9b4
 
 
 
747e93d
 
2ceb9b4
 
 
ac490ae
2ceb9b4
 
747e93d
2ceb9b4
 
747e93d
 
 
38512ac
 
 
 
 
 
 
 
 
 
 
 
 
 
747e93d
0ed74ae
faa0818
3acf8c3
5d28904
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0b4ac11
 
5d28904
 
 
 
 
482a617
 
 
3acf8c3
482a617
3acf8c3
 
 
 
 
 
482a617
 
0b4ac11
482a617
 
 
0b4ac11
3acf8c3
0b4ac11
 
 
482a617
 
0b4ac11
6d3b450
 
 
 
 
a515c85
c27967a
 
 
 
 
0ed74ae
 
7039ee0
3acf8c3
7039ee0
 
 
db214bb
 
3acf8c3
 
7039ee0
db214bb
 
 
 
7039ee0
 
 
3acf8c3
 
 
 
 
 
1e6ba7c
 
3acf8c3
1e6ba7c
 
 
 
 
3acf8c3
 
 
faa0818
1af2cba
7039ee0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3acf8c3
 
4e08a32
0b4ac11
a515c85
 
 
 
 
 
 
 
 
 
 
0b4ac11
4e08a32
 
 
 
 
0b4ac11
4e08a32
3acf8c3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
482a617
3acf8c3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d7919ff
 
5d28904
d7919ff
 
 
 
 
 
 
 
 
5d28904
1af2cba
d7919ff
50ae26a
 
 
d7919ff
 
 
 
 
 
 
 
 
50ae26a
 
 
 
 
 
 
 
 
 
 
 
d7919ff
 
 
 
 
 
 
 
50ae26a
d7919ff
 
50ae26a
 
 
 
a43a939
0ed74ae
 
 
 
 
 
a43a939
0ed74ae
 
 
 
 
 
 
 
 
 
1e6ba7c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
50ae26a
 
c6e0817
 
 
 
 
 
 
 
 
 
50ae26a
 
40c69f1
 
 
50ae26a
 
 
c6e0817
50ae26a
 
 
 
 
 
 
40c69f1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
50ae26a
 
 
 
 
 
 
 
 
 
 
 
50b84fe
 
 
 
 
 
 
3870ab8
ba9e4dc
 
3870ab8
 
 
 
 
50ae26a
77bce56
50ae26a
bca6f9b
3870ab8
bca6f9b
 
 
f58297b
 
 
3870ab8
50ae26a
 
77bce56
 
 
1b765ca
ce6bce9
77bce56
 
 
cb61e26
2859be5
2ceb9b4
77bce56
3acf8c3
 
 
 
 
 
 
 
 
 
 
1b765ca
 
 
77bce56
 
 
1b765ca
77bce56
 
 
4e08a32
8901845
4e08a32
 
50ae26a
 
77bce56
 
 
 
 
 
 
1b765ca
 
ce6bce9
77bce56
 
 
cb61e26
2859be5
17aa277
2ceb9b4
17aa277
 
77bce56
3acf8c3
 
 
 
 
 
 
 
1b765ca
 
 
77bce56
 
 
b05fdf3
77bce56
 
 
 
b05fdf3
77bce56
1b765ca
77bce56
 
 
 
cb61e26
747e93d
17aa277
77bce56
1b765ca
 
 
 
77bce56
 
 
1b765ca
 
 
 
77bce56
 
8901845
 
 
 
 
 
 
 
 
 
50ae26a
 
823995d
 
5d28904
4e08a32
 
 
 
50ae26a
c27967a
1af2cba
77bce56
 
1b765ca
77bce56
 
71cad45
 
 
 
 
 
 
 
db214bb
71cad45
 
 
 
 
 
 
 
 
 
 
 
db214bb
 
f301af7
 
 
 
 
db214bb
 
 
71cad45
 
 
77bce56
3acf8c3
 
 
 
 
 
 
2859be5
db214bb
 
d9830ba
 
 
 
 
 
 
 
 
1b765ca
 
 
 
 
 
 
 
 
 
 
 
77bce56
 
db214bb
 
 
 
77bce56
cb61e26
 
 
 
17aa277
 
 
71cad45
 
77bce56
 
 
 
 
 
 
 
 
 
1b765ca
 
ce6bce9
77bce56
 
d9830ba
 
 
 
77bce56
cb61e26
2859be5
2ceb9b4
77bce56
ce6bce9
1b765ca
 
 
77bce56
 
 
1b765ca
2859be5
 
46a41a4
 
 
 
2859be5
cb61e26
77bce56
 
 
9dc14f3
 
db214bb
f301af7
 
 
 
db214bb
 
1af2cba
50ae26a
1af2cba
db214bb
 
1af2cba
 
 
50ae26a
1af2cba
 
00d8c9c
db214bb
faa0818
d6d9180
a8323ae
cb61e26
747e93d
d9830ba
 
 
c27967a
 
 
1af2cba
9dc14f3
 
 
 
 
db214bb
f301af7
 
 
 
db214bb
 
9dc14f3
 
 
 
db214bb
 
9dc14f3
 
 
50ae26a
9dc14f3
 
 
db214bb
8d2c63c
 
a8323ae
cb61e26
747e93d
d9830ba
 
 
c27967a
 
 
9dc14f3
 
 
 
1af2cba
823995d
 
50ae26a
 
f524325
50ae26a
a515c85
 
 
 
 
 
 
 
 
 
 
0b4ac11
50ae26a
 
 
 
9dc14f3
 
 
6d3b450
a96e391
 
6d3b450
 
 
 
 
 
 
 
61cb1f1
 
 
 
 
 
 
 
 
 
 
 
d7919ff
2859be5
 
 
 
 
 
 
 
 
 
17aa277
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2859be5
50ae26a
d7919ff
 
 
9dc14f3
77bce56
50ae26a
 
 
 
 
 
8361b47
50ae26a
 
 
1b765ca
50ae26a
 
823995d
508dba9
77bce56
71cad45
1b765ca
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
71cad45
 
 
 
 
 
 
 
 
 
 
 
 
 
 
50b84fe
 
 
 
 
 
 
 
 
 
 
 
 
2859be5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
17aa277
2859be5
 
 
17aa277
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2859be5
 
17aa277
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2859be5
 
 
 
 
17aa277
 
 
 
 
 
 
 
 
 
 
 
 
 
 
13a99cd
 
17aa277
 
 
 
2859be5
17aa277
 
 
 
71cad45
77bce56
50ae26a
9dc14f3
 
 
 
 
 
 
 
 
 
 
f58297b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9dc14f3
 
 
 
 
bca6f9b
3870ab8
bca6f9b
 
 
9dc14f3
 
 
f58297b
bca6f9b
f58297b
bca6f9b
 
50b84fe
 
 
 
 
 
 
 
 
 
 
3870ab8
 
 
 
 
 
ba9e4dc
 
 
3870ab8
9dc14f3
5637e9d
 
 
 
 
cab864c
 
5637e9d
 
 
 
 
 
 
 
 
9dc14f3
 
 
 
50ae26a
9dc14f3
 
 
 
 
 
 
40c69f1
 
 
 
9dc14f3
40c69f1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9dc14f3
 
 
 
 
 
 
 
 
 
 
 
 
 
50ae26a
 
9dc14f3
 
40c69f1
9dc14f3
c6e0817
9dc14f3
 
 
c6e0817
9dc14f3
 
50ae26a
9dc14f3
 
50ae26a
9dc14f3
d7919ff
9dc14f3
d7919ff
9dc14f3
d7919ff
9dc14f3
 
 
50ae26a
9dc14f3
d7919ff
 
9dc14f3
 
d7919ff
 
9dc14f3
d7919ff
9dc14f3
 
 
 
 
 
 
 
77bce56
 
 
 
 
 
1af2cba
77bce56
 
 
 
 
1af2cba
 
77bce56
 
0a41a32
77bce56
 
 
 
0a41a32
77bce56
 
d7919ff
77bce56
 
 
1af2cba
77bce56
1af2cba
77bce56
 
 
 
 
1af2cba
 
77bce56
 
 
 
1af2cba
 
 
77bce56
 
0a41a32
17aa277
4967544
 
 
 
 
17aa277
 
 
4967544
 
 
17aa277
 
 
4967544
17aa277
 
 
4967544
17aa277
 
 
 
 
 
13a99cd
 
17aa277
 
 
 
 
0a41a32
 
 
 
 
 
77bce56
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4d46136
77bce56
 
4d46136
77bce56
 
 
 
 
00d8c9c
77bce56
 
 
 
 
 
 
aee79c9
77bce56
 
 
 
 
00d8c9c
 
77bce56
 
 
fa0f29c
77bce56
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bf6dd9c
77bce56
 
 
 
1af2cba
77bce56
 
d7919ff
1af2cba
bca6f9b
823995d
50ae26a
 
 
bca6f9b
 
 
 
 
823995d
d7919ff
50ae26a
 
 
823995d
50ae26a
 
 
482a617
 
482dcd8
482a617
 
 
 
 
 
 
 
 
 
 
 
620c39a
a4ad87e
 
 
 
 
620c39a
 
 
0b4ac11
620c39a
a4ad87e
620c39a
0b4ac11
620c39a
d7919ff
 
 
a515c85
 
 
0b4ac11
 
 
ce6bce9
0b4ac11
50ae26a
d7919ff
50ae26a
d7919ff
 
 
 
 
 
496a77c
0b4ac11
5d28904
 
7a7fa7c
50c6100
 
 
6918ee1
9cea1a9
7a7fa7c
 
9cea1a9
 
0b4ac11
 
 
 
a515c85
7a7fa7c
d7919ff
 
 
 
 
 
210c927
d7919ff
a515c85
 
0b4ac11
a515c85
ce6bce9
a515c85
 
 
 
 
0b4ac11
 
482dcd8
0b4ac11
 
a515c85
 
 
0b4ac11
482dcd8
a515c85
d7919ff
a515c85
d7919ff
 
 
 
 
 
 
508dba9
d7919ff
508dba9
482a617
d7919ff
a8323ae
 
482a617
a8323ae
482a617
 
 
 
 
 
 
 
 
 
482dcd8
a4ad87e
 
 
 
482a617
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a4ad87e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
482a617
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
482dcd8
482a617
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a8323ae
 
6d3b450
482a617
6d3b450
210c927
6d3b450
210c927
6d3b450
 
 
482dcd8
 
 
6d3b450
 
 
482dcd8
a515c85
 
6d3b450
620c39a
0b4ac11
620c39a
 
 
539a0b9
 
 
 
 
620c39a
 
 
 
 
 
 
 
 
 
496a77c
 
9cea1a9
50c6100
 
6918ee1
9cea1a9
 
539a0b9
9cea1a9
 
 
539a0b9
9cea1a9
6d3b450
 
0b4ac11
 
482dcd8
0b4ac11
 
6d3b450
620c39a
6d3b450
620c39a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
68b3e01
 
 
ce6bce9
a4ad87e
68b3e01
 
 
 
ce6bce9
68b3e01
ce6bce9
 
 
a4ad87e
 
ce6bce9
68b3e01
 
496a77c
5d28904
 
 
26f2e6b
68b3e01
 
26f2e6b
a8323ae
68b3e01
 
 
 
 
 
a8323ae
68b3e01
a4ad87e
ce6bce9
 
 
 
a4ad87e
 
 
 
 
68b3e01
 
 
 
a8323ae
 
68b3e01
 
 
6d3b450
 
 
 
 
 
 
 
 
 
 
 
0b4ac11
 
 
 
 
 
 
 
482dcd8
0b4ac11
 
 
68b3e01
6d3b450
 
482a617
6d3b450
 
 
50ae26a
482a617
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d7919ff
1af2cba
d7919ff
 
 
 
 
210c927
d7919ff
 
 
 
 
210c927
d7919ff
 
 
 
 
 
 
 
 
 
 
 
 
 
1af2cba
d7919ff
 
50ae26a
 
 
 
 
 
 
 
 
 
 
 
 
d7919ff
50ae26a
 
 
 
 
 
 
 
1b765ca
 
 
 
 
 
 
 
46a41a4
1b765ca
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
46a41a4
 
1b765ca
620c39a
0b4ac11
a515c85
 
 
0b4ac11
 
 
ce6bce9
0b4ac11
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1b765ca
 
 
 
 
 
 
 
 
 
 
 
 
ce6bce9
2859be5
68b3e01
 
 
 
 
 
 
 
 
 
 
 
 
 
ce6bce9
68b3e01
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
747e93d
 
 
 
 
 
 
68b3e01
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1b765ca
 
f524325
a515c85
 
0b4ac11
 
 
46a41a4
 
 
 
 
1b765ca
46a41a4
1b765ca
 
46a41a4
 
 
 
 
 
 
 
 
 
1b765ca
46a41a4
1b765ca
 
46a41a4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1b765ca
46a41a4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1b765ca
 
 
 
 
482a617
 
 
 
 
a4ad87e
 
 
 
620c39a
 
 
0b4ac11
620c39a
a4ad87e
620c39a
0b4ac11
620c39a
1b765ca
 
 
 
 
 
 
 
 
 
 
 
 
 
aee79c9
1b765ca
 
46a41a4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1b765ca
 
 
 
 
 
 
 
 
68b3e01
d934eeb
68b3e01
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1b765ca
 
68b3e01
d934eeb
68b3e01
 
 
 
 
 
 
46a41a4
 
 
 
68b3e01
 
 
 
1b765ca
 
 
 
 
 
 
 
 
496a77c
a515c85
7a7fa7c
50c6100
 
 
6918ee1
9cea1a9
7a7fa7c
 
9cea1a9
 
0b4ac11
 
 
 
a515c85
7a7fa7c
1b765ca
 
 
 
 
 
 
 
a515c85
0b4ac11
ce6bce9
a515c85
 
 
 
 
0b4ac11
 
482dcd8
0b4ac11
 
a515c85
 
 
0b4ac11
482dcd8
a515c85
1b765ca
a515c85
1b765ca
 
 
 
 
 
 
 
 
 
482a617
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
482dcd8
a4ad87e
 
 
 
482a617
 
 
 
 
 
 
68b3e01
482a617
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a4ad87e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
482a617
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
482dcd8
482a617
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1b765ca
68b3e01
6d3b450
482a617
6d3b450
bf6dd9c
 
 
 
6d3b450
bf6dd9c
 
6d3b450
 
 
482dcd8
 
 
6d3b450
 
 
482dcd8
a515c85
 
6d3b450
620c39a
0b4ac11
620c39a
 
 
539a0b9
 
 
 
 
620c39a
 
 
 
 
 
 
 
 
 
496a77c
 
9cea1a9
50c6100
 
6918ee1
9cea1a9
 
539a0b9
9cea1a9
 
 
539a0b9
9cea1a9
6d3b450
 
0b4ac11
 
482dcd8
0b4ac11
 
6d3b450
620c39a
6d3b450
620c39a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
68b3e01
 
 
ce6bce9
a4ad87e
68b3e01
 
 
 
ce6bce9
68b3e01
ce6bce9
 
 
a4ad87e
 
ce6bce9
68b3e01
 
496a77c
68b3e01
26f2e6b
68b3e01
 
26f2e6b
1b765ca
68b3e01
 
 
 
 
 
1b765ca
68b3e01
a4ad87e
ce6bce9
 
 
 
a4ad87e
 
 
 
 
68b3e01
 
 
 
1b765ca
68b3e01
 
 
 
6d3b450
 
 
 
 
 
 
 
 
 
 
 
0b4ac11
 
 
 
 
 
 
 
482dcd8
0b4ac11
 
 
68b3e01
6d3b450
 
482a617
6d3b450
 
 
1b765ca
 
482a617
 
 
 
 
 
bf6dd9c
 
482a617
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1b765ca
 
fa0f29c
 
bf6dd9c
 
1b765ca
 
bf6dd9c
1b765ca
46a41a4
 
 
1b765ca
210c927
1b765ca
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6a63129
1b765ca
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
46a41a4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1b765ca
4d46136
1b765ca
 
4d46136
1b765ca
 
 
 
 
 
 
 
 
fa0f29c
1b765ca
 
 
 
 
 
 
 
 
46a41a4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1b765ca
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
46a41a4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bf6dd9c
1b765ca
 
 
 
 
 
 
210c927
1b765ca
 
 
210c927
1b765ca
 
 
 
 
 
210c927
1b765ca
 
 
 
 
 
 
77bce56
1b765ca
 
77bce56
d7919ff
 
0ed74ae
 
 
 
d7919ff
50ae26a
d7919ff
 
 
 
 
 
0ed74ae
 
 
 
 
 
 
 
 
 
 
 
 
d7919ff
 
50b84fe
 
 
 
 
cb61e26
50b84fe
 
cb61e26
 
 
 
 
 
 
17aa277
 
 
 
 
bf6dd9c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
17aa277
bf6dd9c
682a86e
bf6dd9c
 
21ee370
1e6ba7c
c27967a
d9830ba
 
c27967a
 
 
 
 
d9830ba
c27967a
d9830ba
 
c27967a
 
 
d9830ba
 
 
 
 
 
c27967a
 
30ade77
 
 
 
0dee604
c27967a
 
 
 
 
 
d9830ba
 
 
 
 
 
 
c27967a
d9830ba
c27967a
 
d9830ba
 
 
 
 
 
 
 
 
 
 
c27967a
 
61cb1f1
 
 
 
 
 
 
 
 
 
1e6ba7c
 
 
 
 
 
 
 
 
a43a939
 
1e6ba7c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
db214bb
 
 
 
 
 
 
 
1e6ba7c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
773a66f
d9830ba
c27967a
1e6ba7c
 
0ed74ae
1e6ba7c
 
0ed74ae
 
1e6ba7c
0ed74ae
d9830ba
c27967a
d9830ba
 
 
 
 
 
 
 
773a66f
 
30ade77
0dee604
c27967a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
50ae26a
 
 
 
 
 
 
 
 
4e08a32
50ae26a
9134973
50ae26a
a43a939
50ae26a
 
 
 
a43a939
50ae26a
 
 
 
 
 
 
 
 
1b765ca
 
 
 
 
 
 
 
 
46a41a4
1b765ca
 
 
 
 
 
 
 
 
 
 
 
 
 
 
46a41a4
 
 
1b765ca
 
d9830ba
 
 
 
1b765ca
cb61e26
2859be5
1b765ca
68b3e01
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d9830ba
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
68b3e01
 
 
 
 
 
 
cb61e26
 
 
 
 
 
 
747e93d
 
 
 
 
 
 
68b3e01
 
1b765ca
 
68b3e01
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d934eeb
68b3e01
 
 
 
 
 
 
46a41a4
 
 
 
 
68b3e01
 
 
cb61e26
68b3e01
1b765ca
 
cb61e26
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
17aa277
 
 
 
 
1b765ca
 
 
46a41a4
f301af7
46a41a4
 
f301af7
 
 
 
 
 
 
 
 
 
 
46a41a4
 
f301af7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
46a41a4
 
f301af7
 
 
 
 
 
46a41a4
 
 
 
 
f301af7
46a41a4
 
 
 
f301af7
46a41a4
17aa277
1b765ca
682a86e
1b765ca
bf6dd9c
 
1b765ca
d9830ba
 
 
 
 
 
 
 
c27967a
d9830ba
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1e6ba7c
0ed74ae
 
 
 
 
 
1e6ba7c
0ed74ae
 
a43a939
 
0ed74ae
 
 
1e6ba7c
0ed74ae
 
1e6ba7c
0ed74ae
 
 
 
 
 
 
1e6ba7c
 
 
 
0ed74ae
1e6ba7c
db214bb
 
1e6ba7c
 
db214bb
 
 
 
 
 
 
 
 
 
 
 
 
 
1e6ba7c
 
 
 
 
 
 
db214bb
 
 
 
 
 
 
 
 
 
 
 
 
 
1e6ba7c
 
 
 
 
0ed74ae
1e6ba7c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0ed74ae
1b765ca
d9830ba
 
1e6ba7c
 
 
 
 
 
 
 
 
1b765ca
 
d9830ba
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1b765ca
 
 
 
 
 
 
 
 
 
 
 
a43a939
1b765ca
 
 
 
a43a939
1b765ca
 
 
 
 
 
77bce56
1b765ca
 
77bce56
50ae26a
d7919ff
77bce56
 
 
 
 
 
 
 
 
 
d7919ff
 
50ae26a
3acf8c3
0b4ac11
3acf8c3
d7919ff
 
3acf8c3
 
 
 
 
 
 
 
 
 
 
 
 
d7919ff
 
21ee370
50ae26a
6d3b450
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
56d0d35
6d3b450
56d0d35
6d3b450
482dcd8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6d3b450
 
823995d
508dba9
50ae26a
 
1e6ba7c
50ae26a
4e08a32
 
 
 
 
 
 
 
3acf8c3
50ae26a
1e6ba7c
50ae26a
 
1e6ba7c
 
50ae26a
3f0189a
a515c85
 
56d0d35
3f0189a
56d0d35
a515c85
482dcd8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
50ae26a
 
 
 
 
 
0b4ac11
 
 
 
 
 
 
50ae26a
 
 
 
 
508dba9
71cad45
d7919ff
3acf8c3
 
 
 
508dba9
a572c0b
50ae26a
 
508dba9
50ae26a
 
 
 
508dba9
 
 
50ae26a
508dba9
50ae26a
 
 
 
 
 
 
 
71cad45
 
508dba9
823995d
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
import { useState, useRef, useEffect, useCallback, useMemo, type ReactNode } from "react";
import ReactDOM from "react-dom";
import { useNavigate } from "react-router-dom";
import { useAuth } from "../hooks/useAuth";
import { isPaidPlan } from "../lib/plan";
import { useCraftedTemplates } from "../contexts/CraftedTemplatesContext";
import { useErrorModal } from "../contexts/ErrorModalContext";
import { BulkLinksSection } from "./BulkLinksSection";
import { classifyUrl, classifyUrlScrapability } from "../utils/urlScrapability";
import { getVoicePreviews, getMyVoices, getPrebuiltVoices, previewVoice, getBgmTracks, BACKEND_URL, type TemplateMeta, type CraftedTemplateItem, type VoicePreview, type BulkProjectItem, type CustomTemplateItem, type SavedVoiceFromAPI, type ElevenLabsVoice } from "../api/client";
import {
  primeBlogUrlFormStep2Prefetch,
  fetchBlogUrlFormBuiltinTemplatesDeduped,
  fetchBlogUrlFormAvailabilityDeduped,
} from "../api/blogUrlFormStep2Prefetch";
import { VIDEO_STYLE_OPTIONS, normalizeVideoStyle, type VideoStyleId } from "../constants/videoStyles";
import { SUPPORTED_CONTENT_LANGUAGES, getLanguageOptionLabel } from "../constants/languages";
import UpgradePlanModal from "./UpgradePlanModal";
import { TEMPLATE_PREVIEWS, TEMPLATE_DESCRIPTIONS, NewTemplateBadge, PopularTemplateBadge, CustomTemplateBadge } from "./templatePreviewRegistry";
import CustomPreview from "./templatePreviews/CustomPreview";
import CustomPreviewLandscape from "./templatePreviews/CustomPreviewLandscape";
import CraftedTemplatePreviewSmart from "./templatePreviews/CraftedTemplatePreviewSmart";
import useIsMobileViewport from "../hooks/useIsMobileViewport";
import CraftYourTemplateCard from "./CraftYourTemplateCard";
import GetMoreTemplatesModal from "./GetMoreTemplatesModal";
import DesignerTemplateRequestModal from "./DesignerTemplateRequestModal";
import CraftYourVoiceCard from "./CraftYourVoiceCard";
import VoiceItem, { formatVoiceSubtitle, getMyVoiceDisplayName, subtitleForSavedVoice } from "./VoiceItem";
import AdvancedVoiceOptions from "./AdvancedVoiceOptions";
import {
  VOICE_STABILITY_DEFAULT,
  VOICE_STABILITY_MIN,
  VOICE_STABILITY_MAX,
  VOICE_SPEED_DEFAULT,
  VOICE_SPEED_MIN,
  VOICE_SPEED_MAX,
  VOICE_TUNING_STEP,
  VOICE_STYLE_DEFAULT,
  VOICE_STYLE_MIN,
  VOICE_STYLE_MAX,
  VOICE_EMOTIONS,
  parseVoiceTuning,
  serializeVoiceTuning,
} from "./voiceTuning";

export const VIDEO_STYLES = VIDEO_STYLE_OPTIONS;

const DEFAULT_VIDEO_STYLE: VideoStyleId = "auto";
const CRAFTED_TEMPLATE_MENU_THUMBNAIL_FRAME = 128; // ~85% of 5s * 30fps first scene

/** Source-bucket sentinel values for the genre dropdown (not real template genres). */
const GENRE_CUSTOM = "__custom__";
export const GENRE_CRAFTED = "__crafted__";
const GENRE_NEW = "__new__";
const GENRE_POPULAR = "__popular__";

function genreTemplateListCaption(genreFilter: string): string {
  if (genreFilter === GENRE_CUSTOM) return "Custom templates";
  if (genreFilter === GENRE_CRAFTED) return "Designer templates";
  if (genreFilter === GENRE_NEW) return "New templates";
  if (genreFilter === GENRE_POPULAR) return "Popular templates";
  if (genreFilter) return `Templates for ${genreFilter}`;
  return "All templates";
}

function templateBucketsForGenre(
  genreFilter: string,
  builtinTemplates: TemplateMeta[],
  readyCustomTemplates: CustomTemplateItem[],
  readyCraftedTemplates: CraftedTemplateItem[]
): {
  suggestedTemplates: TemplateMeta[];
  customTemplatesForStyle: CustomTemplateItem[];
  craftedTemplatesForStyle: CraftedTemplateItem[];
} {
  const sourceList = builtinTemplates;
  if (genreFilter === GENRE_CUSTOM) {
    return {
      suggestedTemplates: [],
      customTemplatesForStyle: readyCustomTemplates,
      craftedTemplatesForStyle: [],
    };
  }
  if (genreFilter === GENRE_CRAFTED) {
    return {
      suggestedTemplates: [],
      customTemplatesForStyle: [],
      craftedTemplatesForStyle: readyCraftedTemplates,
    };
  }
  if (genreFilter === GENRE_NEW) {
    return {
      suggestedTemplates: sourceList.filter((t) => t.new_template === true),
      customTemplatesForStyle: [],
      craftedTemplatesForStyle: [],
    };
  }
  if (genreFilter === GENRE_POPULAR) {
    return {
      suggestedTemplates: sourceList.filter((t) => t.popular_template === true),
      customTemplatesForStyle: [],
      craftedTemplatesForStyle: [],
    };
  }
  if (genreFilter) {
    const matchesGenre = (g?: string[]): boolean => (g ?? []).includes(genreFilter);
    return {
      suggestedTemplates: sourceList.filter((t) => matchesGenre(t.genres)),
      customTemplatesForStyle: [],
      craftedTemplatesForStyle: [],
    };
  }
  return {
    suggestedTemplates: sourceList,
    customTemplatesForStyle: readyCustomTemplates,
    craftedTemplatesForStyle: readyCraftedTemplates,
  };
}

/** First entry in template `genres` from meta.json; "" if missing. */
function defaultGenreForTemplate(meta: TemplateMeta | undefined | null): string {
  const raw = meta?.genres?.[0];
  return typeof raw === "string" && raw.trim() !== "" ? raw : "";
}

/** Genre aligned with a bulk row template id (built-in meta or custom genres). */
function defaultGenreForBulkTemplateId(
  templateId: string,
  builtinTemplates: TemplateMeta[],
  customTemplatesList: CustomTemplateItem[]
): string {
  if (templateId.startsWith("custom_")) {
    const cid = parseInt(templateId.replace("custom_", ""), 10);
    if (Number.isNaN(cid)) return "";
    const ct = customTemplatesList.find((t) => t.id === cid);
    return ct?.genres?.[0] ?? "";
  }
  return defaultGenreForTemplate(builtinTemplates.find((t) => t.id === templateId));
}

/**
 * After the style/genre split: video_style no longer changes per template β€” it's an orthogonal
 * user choice (Auto by default). These helpers exist only as no-op shims so existing call sites
 * keep compiling; they always return the form-wide default style.
 */
function defaultVideoStyleForTemplate(_meta: TemplateMeta | undefined | null): VideoStyleId {
  return DEFAULT_VIDEO_STYLE;
}

function videoStyleForBulkTemplateId(
  _templateId: string,
  _builtinTemplates: TemplateMeta[],
  _customTemplatesList: CustomTemplateItem[]
): VideoStyleId {
  return DEFAULT_VIDEO_STYLE;
}

/** Read-only demo mode used by help videos: forces step + seeds state without firing API calls. */
export interface BlogUrlFormDemoMode {
  step: 1 | 2 | 3;
  url?: string;
  name?: string;
  videoLength?: "short" | "medium" | "detailed";
  template?: string;
  videoStyle?: VideoStyleId;
  voiceGender?: "female" | "male" | "none";
  voiceAccent?: string;
  customVoiceId?: string;
  templatesData?: TemplateMeta[];
  customTemplatesData?: CustomTemplateItem[];
  myVoicesData?: SavedVoiceFromAPI[];
  voicePreviewsData?: Record<string, VoicePreview>;
  /** Replaces every built-in template preview with a static filler (used by help videos). */
  templatePreviewOverride?: (opts: { templateId: string; selected: boolean; thumbnail: boolean }) => ReactNode;
}

interface Props {
  onSubmit: (
    url: string,
    name?: string,
    voiceGender?: string,
    voiceAccent?: string,
    accentColor?: string,
    bgColor?: string,
    textColor?: string,
    animationInstructions?: string,
    logoFile?: File,
    logoPosition?: string,
    logoOpacity?: number,
    customVoiceId?: string,
    aspectRatio?: string,
    uploadFiles?: File[],
    template?: string,
    videoStyle?: VideoStyleId,
    videoLength?: "short" | "medium" | "detailed" | "more_detailed",
    contentLanguage?: string | null,
    voiceEmotion?: string,
    bgmTrackId?: string | null,
    bgmVolume?: number
  ) => Promise<void>;
  /** Bulk create: one call with array of configs; per-project logo via logoIndices + logoFiles. */
  onSubmitBulk?: (items: BulkProjectItem[], logoOptions: { logoIndices: number[]; logoFiles: File[] } | null) => Promise<void>;
  /**
   * Extra creation options that don't fit `onSubmit`'s positional list (already
   * 22 args). Read by the caller when building the create payload; the form
   * pushes the current values here whenever they change.
   */
  onExtraOptionsChange?: (opts: { stockFootageEnabled: boolean }) => void;
  loading?: boolean;
  asModal?: boolean;
  onClose?: () => void;
  /** Invoked before navigating to My Templates to craft a template (e.g. close the new-project modal). */
  onDismissFlow?: () => void;
  /** When set, the form renders in read-only demo mode for help videos. */
  demoMode?: BlogUrlFormDemoMode;
  /** Pre-select a genre filter when step 2 opens (e.g. GENRE_CRAFTED to show Designer Templates). */
  initialGenre?: string;
}

const MAX_UPLOAD_FILES = 5;
const MAX_UPLOAD_SIZE = 5 * 1024 * 1024;
const viteEnv =
  typeof import.meta !== "undefined" ? import.meta.env : undefined;
const processEnv =
  typeof globalThis !== "undefined" && "process" in globalThis
    ? (globalThis as { process?: { env?: Record<string, string | undefined> } }).process?.env
    : undefined;

const MAX_BULK_LINKS = (() => {
  const raw = (viteEnv?.VITE_MAX_BULK_LINKS || processEnv?.VITE_MAX_BULK_LINKS) as
    | string
    | undefined;
  const parsed = raw ? parseInt(raw, 10) : NaN;
  return Number.isFinite(parsed) && parsed > 0 ? parsed : 10;
})();

/** Estimated wall-clock range per tier (UI only; backend still uses short | medium | detailed). */
const VIDEO_LENGTH_DURATION_LABELS: Record<"short" | "medium" | "detailed" | "more_detailed", string> = {
  short: "Short  ~  30 sec – 1 min",
  medium: "Medium  ~  1 - 3 mins",
  detailed: "Detailed  ~  3 – 8 mins",
  more_detailed: "More Detailed  ~  8+ mins",
};

/**
 * Minimum source-content word count each tier needs to actually reach that length.
 * Mirrors the backend thresholds in pipeline.py (_effective_video_length_for_content):
 * below these counts the video is automatically shortened to a smaller tier.
 */
const VIDEO_LENGTH_MIN_WORDS: Partial<Record<"short" | "medium" | "detailed" | "more_detailed", number>> = {
  detailed: 1500,
  more_detailed: 2000,
};

/**
 * Long-form lengths reserved for paid plans; FREE users top out at "medium".
 * Mirrors _PAID_ONLY_VIDEO_LENGTHS in backend/app/routers/projects.py, which
 * rejects these with 403 `video_length_requires_paid` β€” this is the UI half of
 * the same rule, not the enforcement.
 */
const PAID_ONLY_VIDEO_LENGTHS = new Set<string>(["detailed", "more_detailed"]);

const ALLOWED_EXTENSIONS = [".pdf", ".docx", ".pptx", ".md", ".markdown", ".txt", ".vtt"];
const ALLOWED_TYPES = [
  "application/pdf",
  "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
  "application/vnd.openxmlformats-officedocument.presentationml.presentation",
  "text/plain",
  "text/markdown",
  "text/x-markdown",
  "text/vtt",
];

const VOICE_PREVIEW_KEYS = ["female_american", "female_british", "male_american", "male_british"];

const normalizeVoiceGender = (value?: string | null): "female" | "male" | null => {
  const v = (value ?? "").trim().toLowerCase();
  if (v === "female" || v === "male") return v;
  return null;
};

const normalizeVoiceAccent = (value?: string | null): string | null => {
  const v = (value ?? "").trim();
  if (!v) return null;
  return v.toLowerCase();
};


// Step indicator β€” order: 1 Content, 2 Template, 3 Voice
function StepIndicator({ current, total }: { current: number; total: number }) {
  const stepLabels = ["Project", "Template", "Voice"];
  return (
    <div className="flex flex-col items-center gap-2 mb-6">
      <div className="flex items-center gap-2">
        {Array.from({ length: total }, (_, i) => i + 1).map((n) => (
          <div key={n} className="flex items-center gap-2">
            <div
              className={`w-6 h-6 rounded-full text-[10px] font-semibold flex items-center justify-center transition-all ${
                n === current
                  ? "bg-purple-600 text-white"
                  : n < current
                  ? "bg-purple-100 text-purple-600"
                  : "bg-gray-100 text-gray-400"
              }`}
            >
              {n < current ? (
                <svg className="w-3 h-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2.5} d="M5 13l4 4L19 7" />
                </svg>
              ) : (
                n
              )}
            </div>
            {n < total && (
              <div
                className={`h-px w-8 transition-all ${
                  n < current ? "bg-purple-300" : "bg-gray-200"
                }`}
              />
            )}
          </div>
        ))}
      </div>
      <span className="text-[11px] text-gray-400 font-medium">
        Step {current} β€” {stepLabels[current - 1]}
      </span>
    </div>
  );
}

// ─── Template video player lightbox
interface VideoLightboxProps {
  templateId: string;
  onClose: () => void;
  onSelect: () => void;
  isSelected: boolean;
  customTemplate?: CustomTemplateItem | CraftedTemplateItem | null;
}
function TemplateVideoLightbox({ templateId, onClose, onSelect, isSelected, customTemplate }: VideoLightboxProps) {
  const { ensureCraftedTemplateDetail } = useCraftedTemplates();
  const PreviewComp = TEMPLATE_PREVIEWS[templateId];
  const desc = TEMPLATE_DESCRIPTIONS[templateId];
  const title = customTemplate ? customTemplate.name : (desc?.title ?? templateId);
  const subtitle = customTemplate
    ? (templateId.startsWith("crafted_") ? "Designer template" : "Custom template")
    : desc?.subtitle;

  // Crafted templates ship summary-only by default; the full layout package
  // (frontend_files, frontend_entry_rel, public_asset_urls) is fetched here
  // on demand so the lightbox can render the real composition. The context
  // dedupes concurrent calls and caches the result.
  useEffect(() => {
    if (templateId.startsWith("crafted_")) {
      void ensureCraftedTemplateDetail(templateId);
    }
  }, [templateId, ensureCraftedTemplateDetail]);

  // Close on Escape
  useEffect(() => {
    const handler = (e: KeyboardEvent) => { if (e.key === "Escape") onClose(); };
    window.addEventListener("keydown", handler);
    return () => window.removeEventListener("keydown", handler);
  }, [onClose]);

  return ReactDOM.createPortal(
    <div className="fixed inset-0 z-[60] flex items-center justify-center p-4">
      {/* Backdrop */}
      <div className="absolute inset-0 bg-black/70 backdrop-blur-sm" onClick={onClose} />

      {/* Player container */}
      <div className="relative w-full max-w-2xl">
        {/* Screen bezel */}
        <div className="rounded-2xl overflow-hidden shadow-[0_0_0_1px_rgba(255,255,255,0.08),0_32px_80px_rgba(0,0,0,0.7)] bg-[#0f0f0f]">
          {/* Top bar */}
          <div className="flex items-center justify-between px-4 py-2.5 bg-[#1a1a1a] border-b border-white/[0.06]">
            <div className="flex items-center gap-2.5">
              {/* macOS-style dots */}
              <div className="w-2.5 h-2.5 rounded-full bg-[#FF5F57]" />
              <div className="w-2.5 h-2.5 rounded-full bg-[#FEBC2E]" />
              <div className="w-2.5 h-2.5 rounded-full bg-[#28C840]" />
            </div>
            <span className="text-[11px] text-white/40 font-medium tracking-wide">
              {title} β€” Preview
            </span>
            <button onClick={onClose} className="text-white/30 hover:text-white/70 transition-colors">
              <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
              </svg>
            </button>
          </div>

          {/* Video content */}
          <div className="relative aspect-video overflow-hidden bg-black">
            {customTemplate && customTemplate.theme ? (
              <CustomPreview theme={customTemplate.theme} name={customTemplate.name} previewImageUrl={customTemplate.preview_image_url ?? undefined} introCode={customTemplate.intro_code || undefined} outroCode={customTemplate.outro_code || undefined} contentCodes={customTemplate.content_codes || undefined} contentArchetypeIds={customTemplate.content_archetype_ids || undefined} validLayouts={(customTemplate as any).valid_layouts || undefined} frontendFiles={(customTemplate as any).frontend_files || undefined} frontendEntryRel={(customTemplate as any).frontend_entry_rel || undefined} publicAssetUrls={templateId.startsWith("crafted_") ? ((customTemplate as CraftedTemplateItem).public_asset_urls ?? undefined) : undefined} logoUrls={customTemplate.logo_urls ?? undefined} ogImage={customTemplate.og_image ?? undefined} showLoaderOnEmptyOrError={templateId.startsWith("crafted_")} />
            ) : PreviewComp ? (
              <PreviewComp />
            ) : (
              <div className="w-full aspect-video bg-gray-900 flex items-center justify-center text-gray-500 text-sm">
                No preview available
              </div>
            )}
          </div>

          {/* Bottom controls bar */}
          <div className="flex items-center justify-between px-4 py-3 bg-[#1a1a1a] border-t border-white/[0.06]">
            <div className="text-[11px] text-white/40">
              {subtitle}
            </div>
            <button
              onClick={() => { onSelect(); onClose(); }}
              className={`px-4 py-1.5 rounded-lg text-xs font-semibold transition-all ${
                isSelected
                  ? "bg-purple-500/20 text-purple-300 border border-purple-500/30"
                  : "bg-purple-600 text-white hover:bg-purple-700"
              }`}
            >
              {isSelected ? "Selected" : "Use this template"}
            </button>
          </div>
        </div>
      </div>
    </div>,
    document.body
  );
}

type BlogUrlFormDemoStep = 1 | 2 | 3;

/**
 * @deprecated Use `<BlogUrlForm demoMode={...} />` directly. Kept temporarily for backwards compatibility.
 */
export function BlogUrlFormDemoModal({
  step,
  focus = "source",
}: {
  step: BlogUrlFormDemoStep;
  focus?: "new" | "source" | "template" | "voice" | "generate";
}) {
  const selectedTemplateId = "spotlight";
  const SelectedPreview = TEMPLATE_PREVIEWS[selectedTemplateId];
  const selectedDesc = TEMPLATE_DESCRIPTIONS[selectedTemplateId];
  const demoTemplates = ["spotlight", "nightfall", "gridcraft", "default"];

  const inputClass =
    "w-full px-4 py-2.5 bg-white/80 border border-gray-200/60 rounded-xl text-sm text-gray-900 placeholder-gray-300 focus:outline-none focus:ring-2 focus:ring-purple-500/40 focus:border-transparent transition-all";

  const step1 = (
    <div className="flex flex-col flex-1 min-h-0">
      <div className="flex-1 flex flex-col space-y-5 min-h-0">
        <div className="flex gap-1 p-1 bg-gray-100/60 rounded-xl w-fit">
          {(["url", "upload", "bulk"] as const).map((mode) => (
            <button
              key={mode}
              type="button"
              className={`px-4 py-1.5 rounded-lg text-xs font-medium transition-all ${
                mode === "url" ? "bg-white text-purple-600 shadow-sm" : "text-gray-400 hover:text-gray-600"
              }`}
            >
              {mode === "url" ? "Link" : mode === "upload" ? "Upload" : "Multi Link"}
            </button>
          ))}
        </div>

        <div className="space-y-1.5">
          <label className="block text-[11px] font-medium text-gray-400 uppercase tracking-wider">
            Blog / Article URL
          </label>
          <input
            type="url"
            readOnly
            value="https://yourblog.com/how-ai-search-works"
            className={`${inputClass} ${focus === "source" ? "ring-2 ring-purple-500/40 border-transparent" : ""}`}
          />
        </div>

        <div className="space-y-1.5">
          <label className="block text-[11px] font-medium text-gray-400 uppercase tracking-wider">
            Project name <span className="normal-case text-gray-300">(optional)</span>
          </label>
          <input type="text" readOnly value="AI Search Explainer" className={inputClass} />
        </div>

        <div className="space-y-1.5">
          <label className="block text-[11px] font-medium text-gray-400 uppercase tracking-wider">
            Estimated duration
          </label>
          <button
            type="button"
            className="flex w-full items-center justify-between rounded-xl border border-gray-200/60 bg-white/80 px-4 py-2.5 text-left text-sm text-gray-700"
          >
            <span>Medium  ~  1 - 3 mins</span>
            <svg className="h-4 w-4 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 9l-7 7-7-7" />
            </svg>
          </button>
        </div>
      </div>

      <div className="mt-5 flex gap-2 pt-1">
        <button
          type="button"
          className="flex-1 py-3 bg-purple-600 hover:bg-purple-700 text-white text-sm font-medium rounded-xl transition-colors flex items-center justify-center gap-2"
        >
          Go to step 2
          <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 5l7 7-7 7" />
          </svg>
        </button>
      </div>
    </div>
  );

  const step2 = (
    <div className="space-y-5">
      <div>
        <label className="block text-[11px] font-medium text-gray-400 mb-2 uppercase tracking-wider">
          Selected Template
        </label>
        <div className="rounded-xl overflow-hidden border-2 border-purple-500 shadow-[0_0_0_4px_rgba(124,58,237,0.1)]">
          <div className="relative aspect-video overflow-hidden">{SelectedPreview ? <SelectedPreview /> : null}</div>
          <div className="px-4 py-2.5 bg-purple-50/80 flex flex-col sm:flex-row items-start sm:items-center justify-between gap-3">
            <div>
              <div className="flex items-center gap-2">
                <span className="text-sm font-semibold text-gray-800">{selectedDesc?.title ?? "Spotlight"}</span>
              </div>
              <div className="text-[11px] text-gray-400 mt-0.5">{selectedDesc?.subtitle}</div>
            </div>
            <div className="w-6 h-6 rounded-full bg-purple-600 flex items-center justify-center flex-shrink-0">
              <svg className="w-3.5 h-3.5 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={3} d="M5 13l4 4L19 7" />
              </svg>
            </div>
          </div>
        </div>
      </div>

      <div>
        <div className="flex items-center justify-between mb-2">
          <label className="block text-[11px] font-medium text-gray-400 uppercase tracking-wider">
            Video Style
          </label>
          <div className="flex flex-wrap items-center gap-1 p-1 bg-gray-100/60 rounded-xl justify-center">
            {VIDEO_STYLES.map((style) => (
              <button
                key={style.id}
                type="button"
                className={`px-3 py-1.5 rounded-lg text-[11px] font-medium transition-all ${
                  style.id === "promotional" ? "bg-white text-purple-600 shadow-sm" : "text-gray-400 hover:text-gray-600"
                }`}
              >
                {style.label}
              </button>
            ))}
          </div>
        </div>
        <p className="text-[10px] text-gray-500 mb-1.5 font-medium">
          Suggested templates for the selected video style
        </p>
        <div className="border border-gray-200/60 rounded-xl p-2.5 max-h-[220px] overflow-y-auto bg-gray-50/40">
          <div className="grid grid-cols-2 sm:grid-cols-3 gap-2">
            <CraftYourTemplateCard
              variant="default"
              isPro
              onClick={() => undefined}
              onKeyDown={() => undefined}
            />
            {demoTemplates.map((templateId) => {
              const Preview = TEMPLATE_PREVIEWS[templateId];
              const desc = TEMPLATE_DESCRIPTIONS[templateId];
              const selected = templateId === selectedTemplateId;
              return (
                <div
                  key={templateId}
                  className={`relative rounded-lg overflow-hidden cursor-pointer transition-all group ${
                    selected
                      ? "border-2 border-purple-500 shadow-[0_0_0_3px_rgba(124,58,237,0.1)]"
                      : "border-2 border-gray-200/60 hover:border-purple-300/60"
                  }`}
                >
                  <div className="relative h-[70px] overflow-hidden">
                    {Preview ? <Preview thumbnailMode /> : null}
                    {selected && (
                      <div className="absolute top-1.5 right-1.5 w-4 h-4 rounded-full bg-purple-600 flex items-center justify-center shadow-sm">
                        <svg className="w-2.5 h-2.5 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={3} d="M5 13l4 4L19 7" />
                        </svg>
                      </div>
                    )}
                  </div>
                  <div className={`px-2 py-1 transition-colors ${selected ? "bg-purple-50/80" : "bg-white/80"}`}>
                    <div className="text-[10px] font-semibold text-gray-800 truncate">{desc?.title ?? templateId}</div>
                  </div>
                </div>
              );
            })}
          </div>
        </div>
      </div>

      <div className="flex gap-2 pt-1">
        <button type="button" className="px-5 py-3 text-sm font-medium text-gray-500 bg-gray-50 hover:bg-gray-100 rounded-xl transition-colors border border-gray-200/60">
          Back
        </button>
        <button type="button" className="flex-1 py-3 bg-purple-600 hover:bg-purple-700 text-white text-sm font-medium rounded-xl transition-colors flex items-center justify-center gap-2">
          Go to step 3
          <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 5l7 7-7 7" />
          </svg>
        </button>
      </div>
    </div>
  );

  const voiceRows = [
    { name: "Rachel", subtitle: "Female - American - clear product narration", selected: true },
    { name: "Alice", subtitle: "Female - British - soft and polished", selected: false },
    { name: "Bill", subtitle: "Male - American - friendly and articulate", selected: false },
  ];

  const step3 = (
    <div className="space-y-5">
      <div className="flex items-center gap-2 px-3 py-2.5 rounded-xl bg-purple-50/60 border border-purple-200/50">
        <svg className="w-4 h-4 text-purple-400 shrink-0" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
          <path strokeLinecap="round" strokeLinejoin="round" d="M3 5h12M9 3v2m1.048 9.5A18.022 18.022 0 016.412 9m6.088 9h7M11 21l5-10 5 10M12.751 5C11.783 10.77 8.07 15.61 3 18.129" />
        </svg>
        <p className="text-[11px] text-purple-600 leading-relaxed">
          Choose narration language. Keep <span className="font-semibold">Auto</span> to detect from content.
        </p>
      </div>
      <div className="space-y-1.5">
        <label className="block text-[11px] font-medium text-gray-400 uppercase tracking-wider">
          Language
        </label>
        <button type="button" className="flex w-full items-center justify-between rounded-xl border border-gray-200/60 bg-white/80 px-4 py-2.5 text-left text-sm text-gray-700">
          <span>Auto</span>
          <svg className="h-4 w-4 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 9l-7 7-7-7" />
          </svg>
        </button>
        <p className="text-[11px] text-gray-500">Language of the video content</p>
      </div>
      <label className="flex items-center gap-2.5 cursor-pointer select-none p-3 rounded-xl bg-gray-50/60 border border-gray-200/60 hover:border-gray-300/60 transition-all">
        <input type="checkbox" readOnly checked={false} className="w-4 h-4 rounded border-gray-300 text-purple-600 focus:ring-purple-500/30 cursor-pointer accent-purple-600" />
        <div>
          <p className="text-[11px] text-gray-400 mt-0.5">No voiceover</p>
        </div>
      </label>
      <div>
        <label className="block text-[11px] font-medium text-gray-400 mb-3 uppercase tracking-wider">
          Voice - Select and Play to Preview
        </label>
        <div className="space-y-2 max-h-[320px] overflow-y-auto">
          {voiceRows.map((voice) => (
            <VoiceItem
              key={voice.name}
              name={voice.name}
              subtitle={voice.subtitle}
              hasPreview
              isPlaying={focus === "voice" && voice.selected}
              onPlay={() => undefined}
              isSelected={voice.selected}
              actions={
                voice.selected ? (
                  <div className="w-5 h-5 rounded-full bg-purple-600 flex items-center justify-center flex-shrink-0">
                    <svg className="w-3 h-3 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={3} d="M5 13l4 4L19 7" />
                    </svg>
                  </div>
                ) : null
              }
            />
          ))}
        </div>
      </div>
      <div className="flex gap-2 pt-1">
        <button type="button" className="px-5 py-3 text-sm font-medium text-gray-500 bg-gray-50 hover:bg-gray-100 rounded-xl transition-colors border border-gray-200/60">
          Back
        </button>
        <button
          type="button"
          className={`flex-1 py-3 text-white text-sm font-medium rounded-xl transition-colors flex items-center justify-center gap-2 ${
            focus === "generate" ? "bg-purple-700 ring-4 ring-purple-500/20" : "bg-purple-600 hover:bg-purple-700"
          }`}
        >
          Generate Video
        </button>
      </div>
    </div>
  );

  const content = step === 1 ? step1 : step === 2 ? step2 : step3;

  return (
    <div className="relative w-full max-w-xl bg-white/90 backdrop-blur-xl border border-gray-200/40 rounded-2xl shadow-[0_8px_40px_rgba(0,0,0,0.08)] p-7 max-h-[85vh] overflow-y-auto">
      <div className="flex items-center justify-between mb-6">
        <h2 className="text-base font-semibold text-gray-900">New Project</h2>
        <button className="text-gray-300 hover:text-gray-500 transition-colors">
          <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
          </svg>
        </button>
      </div>
      <StepIndicator current={step} total={3} />
      <div className="relative min-h-[420px] flex flex-col">
        <div className="min-h-[420px] flex flex-col">{content}</div>
      </div>
    </div>
  );
}

function deriveNameFromUrl(url: string): string {
  try {
    const parsed = new URL(url);
    const segments = parsed.pathname.replace(/\/$/, "").split("/");
    const path = segments[segments.length - 1] || parsed.hostname;
    return path.replace(/[-_]/g, " ").replace(/\b\w/g, (c: string) => c.toUpperCase()).slice(0, 100) || "Untitled Project";
  } catch {
    return "Untitled Project";
  }
}

/** Returns true if the trimmed string has any whitespace in the middle (not just at start/end). */
function hasSpacesInMiddle(s: string): boolean {
  const t = s.trim();
  return t.length > 0 && /\s/.test(t);
}

/** Treat as a link only if it contains a dot (e.g. example.com). Rejects single words or plain sentences. */
function containsDot(s: string): boolean {
  return s.trim().includes(".");
}

const FILE_EXTENSIONS = [".pdf", ".doc", ".docx", ".ppt", ".pptx", ".xls", ".xlsx", ".odt", ".odp", ".ods", ".txt", ".md", ".markdown", ".rtf", ".csv"];

/** Returns the matched file extension if the URL ends with a document extension, else null. */
function getFileExtension(s: string): string | null {
  const trimmed = s.trim().toLowerCase();
  // Check the raw input first (covers "hello.pdf", "example.com/file.pdf", etc.)
  const directMatch = FILE_EXTENSIONS.find((ext) => trimmed.endsWith(ext));
  if (directMatch) return directMatch;
  // Also check the pathname of a parsed URL (handles query strings, e.g. site.com/doc.pdf?v=1)
  try {
    const url = new URL(trimmed.startsWith("http") ? trimmed : `https://${trimmed}`);
    const path = url.pathname.toLowerCase();
    return FILE_EXTENSIONS.find((ext) => path.endsWith(ext)) ?? null;
  } catch {
    return null;
  }
}

export default function BlogUrlForm({ onSubmit, onSubmitBulk, onExtraOptionsChange, loading, asModal, onClose, onDismissFlow, demoMode, initialGenre }: Props) {
  const { user } = useAuth();
  const { showError } = useErrorModal();
  const navigate = useNavigate();
  const isPro = demoMode ? true : isPaidPlan(user?.plan);
  const isDemo = !!demoMode;
  // On mobile, crafted/custom grid tiles render a static themed placeholder
  // instead of a live Remotion Player; only the selected tile plays live. A grid
  // of live Players exhausts iOS Safari's per-tab memory and reloads the tab.
  const isMobile = useIsMobileViewport();

  // Wizard step
  const [step, setStep] = useState<1 | 2 | 3>(demoMode?.step ?? 1);
  useEffect(() => {
    if (demoMode?.step) setStep(demoMode.step);
  }, [demoMode?.step]);

  // Step 1 β€” input
  const [mode, setMode] = useState<"url" | "upload" | "bulk">("url");
  const [urls, setUrls] = useState<string[]>([""]);
  const [name, setName] = useState("");
  const [docFiles, setDocFiles] = useState<File[]>([]);
  const [docError, setDocError] = useState<string | null>(null);
  const docInputRef = useRef<HTMLInputElement>(null);
  /** URL validation error for single-link mode (shown only after blur). */
  const [urlError, setUrlError] = useState<string | null>(null);
  // Bulk: rows (url); per-row name, template, voice, format, logo
  const [bulkRows, setBulkRows] = useState<{ url: string }[]>([{ url: "" }]);
  const [bulkNames, setBulkNames] = useState<string[]>([""]);
  const [bulkTemplates, setBulkTemplates] = useState<string[]>(["default"]);
  const bulkTemplatesRef = useRef<string[]>(["default"]);
  bulkTemplatesRef.current = bulkTemplates;
  const [bulkVoiceGender, setBulkVoiceGender] = useState<("female" | "male" | "none")[]>(["female"]);
  const [bulkVoiceAccent, setBulkVoiceAccent] = useState<string[]>(["american"]);
  const [bulkVoiceStability, setBulkVoiceStability] = useState<number[]>(() => [parseVoiceTuning(user?.preferred_voice_emotion)[0]]);
  const [bulkVoiceSpeed, setBulkVoiceSpeed] = useState<number[]>(() => [parseVoiceTuning(user?.preferred_voice_emotion)[1]]);
  const [bulkVoiceEmotion, setBulkVoiceEmotion] = useState<string[]>(() => [parseVoiceTuning(user?.preferred_voice_emotion)[2]]);
  const [bulkVoiceStyle, setBulkVoiceStyle] = useState<number[]>(() => [parseVoiceTuning(user?.preferred_voice_emotion)[3]]);
  const [bulkCustomVoiceId, setBulkCustomVoiceId] = useState<string[]>([]);
  const [bulkContentLanguage, setBulkContentLanguage] = useState<string[]>(["auto"]);
  const [bulkVideoLength, setBulkVideoLength] = useState<("short" | "medium" | "detailed" | "more_detailed")[]>(["short"]);
  const [bulkAspectRatio, setBulkAspectRatio] = useState<("landscape" | "portrait")[]>(["landscape"]);
  const [bulkVideoStyles, setBulkVideoStyles] = useState<VideoStyleId[]>([DEFAULT_VIDEO_STYLE]);
  const bulkStyleManuallySet = useRef<boolean[]>([false]);
  // Empty string = "not yet set from template"; we derive from template.preview_colors on step 2.
  const [bulkAccentColors, setBulkAccentColors] = useState<string[]>([""]);
  const [bulkBgColors, setBulkBgColors] = useState<string[]>([""]);
  const [bulkTextColors, setBulkTextColors] = useState<string[]>([""]);
  const [bulkActiveIndex, setBulkActiveIndex] = useState(0);
  const [bulkLogoFile, setBulkLogoFile] = useState<(File | null)[]>([null]);
  const [bulkLogoPosition, setBulkLogoPosition] = useState<string[]>(["bottom_right"]);
  const [bulkLogoOpacity, setBulkLogoOpacity] = useState<number[]>([0.9]);
  const [bulkLogoRowIndex, setBulkLogoRowIndex] = useState<number | null>(null);
  const bulkLogoInputRef = useRef<HTMLInputElement>(null);
  const [bulkApplyLengthAll, setBulkApplyLengthAll] = useState(true);
  const [bulkLengthMasterIndex, setBulkLengthMasterIndex] = useState(0);
  const [bulkStockFootage, setBulkStockFootage] = useState<boolean[]>([true]);
  const [bulkApplyStockAll, setBulkApplyStockAll] = useState(true);
  const [bulkStockMasterIndex, setBulkStockMasterIndex] = useState(0);
  const [bulkApplyTemplateAll, setBulkApplyTemplateAll] = useState(true);
  const [bulkTemplateMasterIndex, setBulkTemplateMasterIndex] = useState(0);
  const [bulkApplyVoiceAll, setBulkApplyVoiceAll] = useState(true);
  const [bulkVoiceMasterIndex, setBulkVoiceMasterIndex] = useState(0);

  // Step 2 β€” voice
  const [voiceGender, setVoiceGender] = useState<"female" | "male" | "none">("female");
  const [voiceAccent, setVoiceAccent] = useState<string>("american");
  // Voice tuning sliders (paid). Initialized from the remembered per-user preference so a returning
  // user sees their last settings pre-selected.
  const [voiceStability, setVoiceStability] = useState<number>(() => parseVoiceTuning(user?.preferred_voice_emotion)[0]);
  const [voiceSpeed, setVoiceSpeed] = useState<number>(() => parseVoiceTuning(user?.preferred_voice_emotion)[1]);
  const [voiceEmotion, setVoiceEmotion] = useState<string>(() => parseVoiceTuning(user?.preferred_voice_emotion)[2]);
  const [voiceStyle, setVoiceStyle] = useState<number>(() => parseVoiceTuning(user?.preferred_voice_emotion)[3]);
  // Live voice-preview playback state (Advanced Options "Listen").
  const [previewState, setPreviewState] = useState<"idle" | "loading" | "playing">("idle");
  const previewAudioRef = useRef<HTMLAudioElement | null>(null);
  const previewUrlRef = useRef<string | null>(null);

  const stopVoicePreview = useCallback(() => {
    previewAudioRef.current?.pause();
    previewAudioRef.current = null;
    if (previewUrlRef.current) {
      URL.revokeObjectURL(previewUrlRef.current);
      previewUrlRef.current = null;
    }
    setPreviewState("idle");
  }, []);

  // Synthesize + play a short sample with the given voice + tuning. Toggling while playing stops it.
  const handleVoicePreview = useCallback(
    async (args: { gender: string; accent: string; customVoiceId: string; stability: number; speed: number; emotion: string; style: number }) => {
      if (previewState === "playing") {
        stopVoicePreview();
        return;
      }
      if (previewState === "loading") return;
      setPreviewState("loading");
      try {
        const url = await previewVoice({
          voice_gender: args.gender,
          voice_accent: args.accent,
          custom_voice_id: args.customVoiceId || undefined,
          voice_emotion: serializeVoiceTuning(args.stability, args.speed, args.emotion, args.style, true),
        });
        if (previewUrlRef.current) URL.revokeObjectURL(previewUrlRef.current);
        previewUrlRef.current = url;
        const audio = new Audio(url);
        audio.addEventListener("ended", stopVoicePreview);
        previewAudioRef.current = audio;
        await audio.play();
        setPreviewState("playing");
      } catch (err: any) {
        setPreviewState("idle");
        const status = err?.response?.status;
        if (status === 429) showError("Please wait a moment before previewing again.");
        else if (status === 403) showError("Voice preview requires a Pro or Standard plan.");
        else showError("Couldn't generate a voice preview. Please try again.");
      }
    },
    [previewState, stopVoicePreview, showError]
  );

  // Stop any preview playback when the component unmounts.
  useEffect(() => () => stopVoicePreview(), [stopVoicePreview]);
  // Whether the "Advanced Options" tab (voice tuning sliders) is expanded. Paid-only.
  const [showAdvancedOptions, setShowAdvancedOptions] = useState<boolean>(false);
  // Active tab in the Step 3 voice/music panel: voice | bgm | advanced (paid).
  const [voicePanelTab, setVoicePanelTab] = useState<"voice" | "bgm" | "advanced">("voice");
  // Master switch for the expressive v3 path. Off β†’ standard v2 voice. Only when ON is the voice
  // tuning sent (which is what routes the project through eleven_v3 + [excited] + emotive narration).
  // Defaults ON for users who previously enabled it (a saved preference exists) β€” it stays enabled
  // across sessions until they explicitly turn it off on a voiced video.
  const [expressiveEnabled, setExpressiveEnabled] = useState<boolean>(() => parseVoiceTuning(user?.preferred_voice_emotion)[4]);
  const [contentLanguage, setContentLanguage] = useState<string>("auto");
  const [videoLength, setVideoLength] = useState<"short" | "medium" | "detailed" | "more_detailed">("short");
  const [customVoiceId, setCustomVoiceId] = useState("");
  const [voicePreviews, setVoicePreviews] = useState<Record<string, VoicePreview>>({});
  const [myVoicesList, setMyVoicesList] = useState<SavedVoiceFromAPI[]>([]);
  const [myVoicesLoading, setMyVoicesLoading] = useState(true);
  const [premiumTeaserVoices, setPremiumTeaserVoices] = useState<ElevenLabsVoice[]>([]);
  const audioRef = useRef<HTMLAudioElement | null>(null);
  const preloadedAudioRef = useRef<Record<string, HTMLAudioElement>>({});
  const [playingKey, setPlayingKey] = useState<string | null>(null);
  const voiceGenderRef = useRef(voiceGender);
  const customVoiceIdRef = useRef(customVoiceId);
  voiceGenderRef.current = voiceGender;
  customVoiceIdRef.current = customVoiceId;

  // Background music
  const [bgmTracks, setBgmTracks] = useState<import("../api/client").BgmTrack[]>([]);
  const [selectedBgmTrackId, setSelectedBgmTrackId] = useState<string | null>(null);
  const [selectedBgmVolume, setSelectedBgmVolume] = useState<number>(0.10);
  const [bgmPlayingId, setBgmPlayingId] = useState<string | null>(null);
  const bgmAudioRef = useRef<HTMLAudioElement | null>(null);

  // Step 2 β€” video style & template
  const [videoStyle, setVideoStyle] = useState<VideoStyleId>(DEFAULT_VIDEO_STYLE);
  const styleManuallySet = useRef(false);
  /** Genre dropdown filter β€” populated dynamically from all templates' meta.genres. "" = show all. */
  const [genre, setGenre] = useState<string>(initialGenre ?? "");
  const [genreDropdownOpen, setGenreDropdownOpen] = useState(false);
  const [template, setTemplate] = useState("default");
  // Stock footage at generation time: available on every plan and every
  // template (builtin, custom, crafted). Free users get a clip on a single
  // scene (the backend caps it), paid users on all image-capable scenes.
  const [stockFootageEnabled, setStockFootageEnabled] = useState(true);
  const stockFootageAvailable = true;
  useEffect(() => {
    onExtraOptionsChange?.({ stockFootageEnabled: stockFootageAvailable && stockFootageEnabled });
  }, [onExtraOptionsChange, stockFootageAvailable, stockFootageEnabled]);
  const [templates, setTemplates] = useState<TemplateMeta[]>([]);
  const { craftedTemplates, loading: craftedTemplatesCacheLoading, initialized: craftedTemplatesInitialized, ensureCraftedTemplateDetail } = useCraftedTemplates();
  // When a crafted template is selected, fetch its full bundle (frontend_files,
  // entry, public assets) on demand so its picker card can render the REAL
  // composition via the module graph (falls back to the marquee until ready).
  useEffect(() => {
    if (template.startsWith("crafted_")) {
      void ensureCraftedTemplateDetail(template);
    }
  }, [template, ensureCraftedTemplateDetail]);
  /** Built-in template list fetch β€” drives step 2 loading overlay (often warmed by Dashboard prefetch). */
  const [builtinTemplatesLoading, setBuiltinTemplatesLoading] = useState(true);
  /** After built-ins load: session random pick (or skip) has finished β€” step 2 can interact. */
  const [sessionBuiltinInitDone, setSessionBuiltinInitDone] = useState(false);
  /** Random built-in default for new rows / initial pick; stable until templates reload. */
  const [pickerDefaultTemplateId, setPickerDefaultTemplateId] = useState<string>("default");
  const templateManuallySelectedRef = useRef(false);

  const [aspectRatio, setAspectRatio] = useState<"landscape" | "portrait">("landscape");
  const [accentColor, setAccentColor] = useState("#7C3AED");
  const [bgColor, setBgColor] = useState("#FFFFFF");
  const [textColor, setTextColor] = useState("#000000");
  const [logoFile, setLogoFile] = useState<File | null>(null);
  const [logoPosition, setLogoPosition] = useState("bottom_right");
  const [logoOpacity, setLogoOpacity] = useState(0.9);
  const logoInputRef = useRef<HTMLInputElement>(null);
  const [showUpgrade, setShowUpgrade] = useState(false);
  const [videoPreviewId, setVideoPreviewId] = useState<string | null>(null);
  const submitButtonRef = useRef<HTMLButtonElement>(null);
  /** When we navigated to step 3 (ms). Used to ignore submit from replayed click after "Go to step 3". */
  const step3EnteredAtRef = useRef<number | null>(null);

  // Load all templates once (filtering by style is done in UI)
  const [customTemplates, setCustomTemplates] = useState<CustomTemplateItem[]>([]);
  const templatesRef = useRef<TemplateMeta[]>(templates);
  const customTemplatesRef = useRef<CustomTemplateItem[]>(customTemplates);
  const pickerDefaultTemplateIdRef = useRef(pickerDefaultTemplateId);
  templatesRef.current = templates;
  customTemplatesRef.current = customTemplates;
  pickerDefaultTemplateIdRef.current = pickerDefaultTemplateId;
  // Only show templates that have finished generating (intro_code exists)
  const readyCustomTemplates = customTemplates.filter((ct) => !!ct.intro_code);
  const readyCraftedTemplates = craftedTemplates.filter((ct) => !!ct.theme);
  const [showCustomTemplateUpgrade, setShowCustomTemplateUpgrade] = useState(false);
  const [showGetMoreTemplates, setShowGetMoreTemplates] = useState(false);
  const [showDesignerRequest, setShowDesignerRequest] = useState(false);
  const [customTemplatesLoading, setCustomTemplatesLoading] = useState(false);
  const [hasCraftedTemplatesEligible, setHasCraftedTemplatesEligible] = useState(false);
  // Show the crafted-template loader until the first R2 roundtrip resolves
  // (not just during the non-silent fetch window), so eligible users never
  // see the "no templates" state flash while we silently revalidate the
  // localStorage cache against R2.
  const craftedTemplatesLoading =
    hasCraftedTemplatesEligible && (craftedTemplatesCacheLoading || !craftedTemplatesInitialized);
  const [templateAvailabilityLoading, setTemplateAvailabilityLoading] = useState(true);
  const allTemplates = useMemo<TemplateMeta[]>(() => {
    const byId = new Map<string, TemplateMeta>();
    for (const t of templates) byId.set(t.id, t);
    for (const ct of craftedTemplates) {
      if (!byId.has(ct.id)) byId.set(ct.id, ct as unknown as TemplateMeta);
    }
    return Array.from(byId.values());
  }, [templates, craftedTemplates]);

  const renderLanguageDropdown = (
    value: string,
    onSelect: (next: string) => void
  ) => (
    <details className="relative group">
      <summary className="list-none w-full px-3 py-2.5 rounded-xl bg-white border border-gray-200 text-sm text-gray-700 cursor-pointer focus:outline-none focus:ring-2 focus:ring-purple-500/30 focus:border-purple-400 flex items-center justify-between">
        <span>{getLanguageOptionLabel(value)}</span>
        <svg
          className="w-4 h-4 text-gray-400 transition-transform group-open:rotate-180"
          fill="none"
          stroke="currentColor"
          viewBox="0 0 24 24"
        >
          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 9l-7 7-7-7" />
        </svg>
      </summary>
      <div className="absolute z-20 mt-1 w-full rounded-xl border border-gray-200 bg-white shadow-lg overflow-hidden">
        {/* ~12 visible rows; rest scrollable */}
        <div className="max-h-[18.5rem] overflow-y-auto py-1">
          <button
            type="button"
            onClick={(e) => {
              onSelect("auto");
              const details = (e.currentTarget.closest("details") as HTMLDetailsElement | null);
              details?.removeAttribute("open");
            }}
            className={`w-full text-left px-3 py-2 text-sm hover:bg-purple-50 ${
              value === "auto" ? "bg-purple-50 text-purple-700" : "text-gray-700"
            }`}
          >
            Auto
          </button>
          {SUPPORTED_CONTENT_LANGUAGES.map((lang) => (
            <button
              key={lang.code}
              type="button"
              onClick={(e) => {
                onSelect(lang.code);
                const details = (e.currentTarget.closest("details") as HTMLDetailsElement | null);
                details?.removeAttribute("open");
              }}
              className={`w-full text-left px-3 py-2 text-sm hover:bg-purple-50 ${
                value === lang.code ? "bg-purple-50 text-purple-700" : "text-gray-700"
              }`}
            >
              {lang.code} - {lang.name}
            </button>
          ))}
        </div>
      </div>
    </details>
  );

  const renderVideoLengthDropdown = (
    value: "short" | "medium" | "detailed" | "more_detailed",
    onSelect: (next: "short" | "medium" | "detailed" | "more_detailed") => void
  ) => {
    const minWords = VIDEO_LENGTH_MIN_WORDS[value];
    return (
    <>
    <details className="relative group">
      <summary className="list-none w-full px-3 py-2.5 rounded-xl bg-white border border-gray-200 text-sm text-gray-700 cursor-pointer focus:outline-none focus:ring-2 focus:ring-purple-500/30 focus:border-purple-400 flex items-center justify-between">
        <span>{VIDEO_LENGTH_DURATION_LABELS[value]}</span>
        <svg
          className="w-4 h-4 text-gray-400 transition-transform group-open:rotate-180"
          fill="none"
          stroke="currentColor"
          viewBox="0 0 24 24"
        >
          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 9l-7 7-7-7" />
        </svg>
      </summary>
      <div className="absolute z-20 mt-1 w-full rounded-xl border border-gray-200 bg-white shadow-lg overflow-hidden">
        <div className="max-h-[18.5rem] overflow-y-auto py-1">
          {(["short", "medium", "detailed", "more_detailed"] as const).map((opt) => {
            // Long-form lengths require a paid plan β€” the backend rejects them
            // with 403 video_length_requires_paid, so gate them here too rather
            // than letting a free user pick an option that will fail on submit.
            const locked = !isPro && PAID_ONLY_VIDEO_LENGTHS.has(opt);
            return (
            <button
              key={opt}
              type="button"
              disabled={locked}
              title={locked ? "Requires a paid plan (Lite, Standard, or Pro)" : undefined}
              onClick={(e) => {
                if (locked) return;
                onSelect(opt);
                const details = (e.currentTarget.closest("details") as HTMLDetailsElement | null);
                details?.removeAttribute("open");
              }}
              className={`w-full text-left px-3 py-2 text-sm flex items-center justify-between gap-2 ${
                locked
                  ? "text-gray-400 cursor-not-allowed"
                  : `hover:bg-purple-50 ${value === opt ? "bg-purple-50 text-purple-700" : "text-gray-700"}`
              }`}
            >
              <span>{VIDEO_LENGTH_DURATION_LABELS[opt]}</span>
              {locked && (
                <span className="shrink-0 px-1.5 py-0.5 rounded bg-purple-50 text-purple-600 text-[10px] font-medium">
                  Paid only
                </span>
              )}
            </button>
            );
          })}
        </div>
      </div>
    </details>
    {minWords && (
      <p className="mt-1.5 flex items-start gap-1 text-[11px] text-red-600 leading-relaxed">
        <svg className="w-3.5 h-3.5 flex-shrink-0 mt-px" fill="none" stroke="currentColor" viewBox="0 0 24 24">
          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 9v2m0 4h.01M10.29 3.86L1.82 18a2 2 0 001.71 3h16.94a2 2 0 001.71-3L13.71 3.86a2 2 0 00-3.42 0z" />
        </svg>
        <span>
          Make sure your content is at least ~{minWords.toLocaleString()} words for this length,
          otherwise the video will be automatically shortened.
        </span>
      </p>
    )}
    </>
    );
  };

  // Load templates, voice previews, and user's saved voices once
  useEffect(() => {
    let mounted = true;
    if (isDemo) {
      if (demoMode?.templatesData) setTemplates(demoMode.templatesData);
      if (demoMode?.customTemplatesData) setCustomTemplates(demoMode.customTemplatesData);
      if (demoMode?.myVoicesData) setMyVoicesList(demoMode.myVoicesData);
      if (demoMode?.voicePreviewsData) setVoicePreviews(demoMode.voicePreviewsData);
      if (demoMode?.url) setUrls([demoMode.url]);
      if (demoMode?.name) setName(demoMode.name);
      if (demoMode?.videoLength) setVideoLength(demoMode.videoLength);
      if (demoMode?.template) {
        setTemplate(demoMode.template);
        templateManuallySelectedRef.current = true;
      }
      if (demoMode?.videoStyle) {
        setVideoStyle(demoMode.videoStyle);
        styleManuallySet.current = true;
      }
      if (demoMode?.voiceGender) setVoiceGender(demoMode.voiceGender);
      if (demoMode?.voiceAccent) setVoiceAccent(demoMode.voiceAccent);
      if (demoMode?.customVoiceId) setCustomVoiceId(demoMode.customVoiceId);
      setBuiltinTemplatesLoading(false);
      setSessionBuiltinInitDone(true);
      setMyVoicesLoading(false);
      setCustomTemplatesLoading(false);
      setHasCraftedTemplatesEligible(false);
      setTemplateAvailabilityLoading(false);
      sessionRandomAppliedRef.current = true;
      return () => {
        mounted = false;
      };
    }
    primeBlogUrlFormStep2Prefetch();
    fetchBlogUrlFormBuiltinTemplatesDeduped()
      .then((data) => {
        if (mounted) {
          setTemplates(data);
          setBuiltinTemplatesLoading(false);
        }
      })
      .catch(() => {
        if (mounted) setBuiltinTemplatesLoading(false);
      });
    fetchBlogUrlFormAvailabilityDeduped()
      .then(({ hasCraftedTemplatesEligible: eligible, customTemplates }) => {
        if (!mounted) return;
        setHasCraftedTemplatesEligible(eligible);
        setCustomTemplates(customTemplates);
        setCustomTemplatesLoading(false);
        setTemplateAvailabilityLoading(false);
      })
      .catch(() => {
        if (!mounted) return;
        setHasCraftedTemplatesEligible(true);
        setCustomTemplates([]);
        setCustomTemplatesLoading(false);
        setTemplateAvailabilityLoading(false);
      });
    getVoicePreviews()
      .then((r) => {
        if (mounted) setVoicePreviews(r.data);
      })
      .catch(() => {});
    getBgmTracks()
      .then((r) => {
        if (mounted) setBgmTracks(r.data);
      })
      .catch(() => {});
    setMyVoicesLoading(true);
    getMyVoices()
      .then((r) => {
        if (!mounted) return;
        const list = r.data ?? [];
        setMyVoicesList(list);
        if (list.length > 0) {
          const first = list[0];
          const firstId = first.voice_id;
          // Single/link flow: default-select the first voice in Step 3 (read latest prefs via refs)
          if (!customVoiceIdRef.current && voiceGenderRef.current !== "none") {
            setCustomVoiceId(firstId);
            const g = normalizeVoiceGender(first.gender);
            const a = normalizeVoiceAccent(first.accent);
            if (g) setVoiceGender(g);
            if (a) setVoiceAccent(a);
          }
        }
      })
      .catch(() => {
        if (mounted) setMyVoicesList([]);
      })
      .finally(() => {
        if (mounted) setMyVoicesLoading(false);
      });
    getPrebuiltVoices()
      .then((r: { data?: { voices?: ElevenLabsVoice[] } }) => {
        if (!mounted) return;
        const voices = r.data?.voices ?? [];
        const paid = voices.filter((v) => v.plan === "paid");
        setPremiumTeaserVoices(paid.slice(0, 2));
      })
      .catch(() => {});
    return () => {
      mounted = false;
    };
  }, []);

  // Keep bulk rows in sync: whenever we have saved voices and bulk URLs,
  // ensure each populated row gets a default custom voice if it doesn't have one.
  useEffect(() => {
    if (!myVoicesList.length) return;
    const firstId = myVoicesList[0].voice_id;
    setBulkCustomVoiceId((prev) => {
      const next = [...prev];
      let changed = false;
      bulkRows.forEach((row, idx) => {
        if (row.url.trim() && !next[idx]) {
          next[idx] = firstId;
          changed = true;
        }
      });
      return changed ? next : prev;
    });
  }, [myVoicesList, bulkRows]);

  // Sync colors to the selected template when templates load or selection changes.
  // Runs before session random pick on the same commit so random pick can override starter "default" colors.
  useEffect(() => {
    if (allTemplates.length === 0) return;
    // Check custom templates first
    if (template.startsWith("custom_")) {
      const customId = parseInt(template.replace("custom_", ""));
      const ct = customTemplates.find((t) => t.id === customId);
      if (ct) {
        setAccentColor(ct.preview_colors.accent);
        setBgColor(ct.preview_colors.bg);
        setTextColor(ct.preview_colors.text);
      }
      return;
    }
    const meta = allTemplates.find((t) => t.id === template);
    if (meta?.preview_colors) {
      setAccentColor(meta.preview_colors.accent);
      setBgColor(meta.preview_colors.bg);
      setTextColor(meta.preview_colors.text);
    }
  }, [allTemplates, customTemplates, template]);

  // Built-ins loaded but empty (error / no data): unblock step 2 without random pick.
  useEffect(() => {
    if (builtinTemplatesLoading) return;
    if (templates.length === 0) {
      setSessionBuiltinInitDone(true);
    }
  }, [builtinTemplatesLoading, templates.length]);

  // Once per form mount: pick a random built-in template for this session (single + all bulk rows).
  const sessionRandomAppliedRef = useRef(false);
  useEffect(() => {
    if (templates.length === 0) return;
    if (sessionRandomAppliedRef.current) {
      setSessionBuiltinInitDone(true);
      return;
    }
    const idx = Math.floor(Math.random() * templates.length);
    const picked = templates[idx];
    if (!picked?.id) {
      setSessionBuiltinInitDone(true);
      return;
    }
    sessionRandomAppliedRef.current = true;
    setPickerDefaultTemplateId(picked.id);
    if (templateManuallySelectedRef.current) {
      setSessionBuiltinInitDone(true);
      return;
    }
    // Genre filter stays at "All genres" by default; users narrow the list explicitly.
    if (picked.preview_colors) {
      setAccentColor(picked.preview_colors.accent);
      setBgColor(picked.preview_colors.bg);
      setTextColor(picked.preview_colors.text);
    }
    setTemplate((prev) =>
      prev === "default" ? picked.id : prev
    );
    setBulkTemplates((prev) =>
      prev.length > 0
        ? prev.map((tpl) => (tpl === "default" ? picked.id : tpl))
        : [picked.id]
    );
    setSessionBuiltinInitDone(true);
  }, [templates]);

  // Preload voice preview audio on mount so it's ready by step 3
  useEffect(() => {
    if (isDemo) return;
    const base = BACKEND_URL ? `${BACKEND_URL}/api` : "/api";
    for (const key of VOICE_PREVIEW_KEYS) {
      if (preloadedAudioRef.current[key]) continue;
      const url = `${base}/voices/preview-audio?key=${encodeURIComponent(key)}`;
      const a = new Audio();
      a.preload = "auto";
      a.src = url;
      preloadedAudioRef.current[key] = a;
    }
  }, [isDemo]);

  // Cleanup audio only on unmount; do not clear preloadedAudioRef so step 3 can use it
  useEffect(() => {
    return () => {
      audioRef.current?.pause();
      for (const key of VOICE_PREVIEW_KEYS) {
        const a = preloadedAudioRef.current[key];
        if (a) {
          a.pause();
          a.removeAttribute("src");
          a.load();
        }
      }
      preloadedAudioRef.current = {};
    };
  }, []);

  // ─── Audio preview ───────────────────────────────────────────
  const playVoice = (key: string, url: string | null) => {
    if (!url) return;
    if (playingKey === key) {
      audioRef.current?.pause();
      setPlayingKey(null);
      return;
    }
    audioRef.current?.pause();
    // Always use preloaded instance when present so we don't refetch at step 3
    let audio = preloadedAudioRef.current[key];
    if (!audio) {
      audio = new Audio(url);
      audio.preload = "auto";
      preloadedAudioRef.current[key] = audio;
    }
    audio.currentTime = 0;
    audio.onended = () => setPlayingKey(null);
    audio.onerror = () => setPlayingKey(null);
    audio.play().catch(() => setPlayingKey(null));
    audioRef.current = audio;
    setPlayingKey(key);
  };

  const playMyVoice = (saved: { voice_id: string; preview_url?: string | null }) => {
    const key = `my_${saved.voice_id}`;
    if (playingKey === key) {
      audioRef.current?.pause();
      setPlayingKey(null);
      return;
    }
    const src = saved.preview_url;
    if (!src) return;
    audioRef.current?.pause();
    const audio = new Audio(src);
    audio.onended = () => setPlayingKey(null);
    audio.onerror = () => setPlayingKey(null);
    audio.play().catch(() => setPlayingKey(null));
    audioRef.current = audio;
    setPlayingKey(key);
  };

  const playPremiumTeaser = (voice: ElevenLabsVoice) => {
    const key = `premium_${voice.voice_id}`;
    if (playingKey === key) {
      audioRef.current?.pause();
      setPlayingKey(null);
      return;
    }
    if (!voice.preview_url) return;
    audioRef.current?.pause();
    const audio = new Audio(voice.preview_url);
    audio.onended = () => setPlayingKey(null);
    audio.onerror = () => setPlayingKey(null);
    audio.play().catch(() => setPlayingKey(null));
    audioRef.current = audio;
    setPlayingKey(key);
  };

  // ─── File helpers ────────────────────────────────────────────
  const isAllowedFile = (file: File) => {
    // 1) Extension check first β€” file.type can be empty / unreliable for .vtt
    //    on many browsers (Chrome reports "" or "application/octet-stream").
    const lowerName = (file.name || "").toLowerCase();
    const dotIdx = lowerName.lastIndexOf(".");
    if (dotIdx !== -1) {
      const ext = lowerName.slice(dotIdx); // includes the leading "."
      if (ALLOWED_EXTENSIONS.includes(ext)) return true;
    }
    // 2) Fallback to MIME type.
    return ALLOWED_TYPES.includes(file.type);
  };

  /** Add one or more files using functional state so paste / drop handlers never see stale `docFiles`. */
  const addDocFileArray = useCallback((incoming: File[]) => {
    if (incoming.length === 0) return;
    setDocError(null);
    for (const f of incoming) {
      if (!isAllowedFile(f)) {
        setDocError(`"${f.name}" is not supported. Use PDF, DOCX, PPTX, Markdown, TXT, or VTT.`);
        return;
      }
      if (f.size > MAX_UPLOAD_SIZE) {
        setDocError(`"${f.name}" exceeds the 5 MB size limit.`);
        return;
      }
    }
    setDocFiles((prev) => {
      if (prev.length + incoming.length > MAX_UPLOAD_FILES) {
        setTimeout(() => setDocError(`Maximum ${MAX_UPLOAD_FILES} files allowed.`), 0);
        return prev;
      }
      return [...prev, ...incoming];
    });
  }, []);

  const addDocFiles = useCallback((newFiles: FileList | null) => {
    if (!newFiles || newFiles.length === 0) return;
    addDocFileArray(Array.from(newFiles));
  }, [addDocFileArray]);

  /** Plain text from clipboard β†’ single .txt document (same limits as uploads). */
  const addPastedTextAsTxtFile = useCallback((text: string) => {
    const blob = new Blob([text], { type: "text/plain;charset=utf-8" });
    const file = new File([blob], "pasted-content.txt", { type: "text/plain" });
    addDocFileArray([file]);
  }, [addDocFileArray]);

  // Step 1 + Upload: Ctrl+V pastes plain text as a .txt doc, or pasted files as uploads.
  // Skips when focus is in an input/textarea so project name & other fields work normally.
  useEffect(() => {
    if (step !== 1 || mode !== "upload") return;

    const onPaste = (e: ClipboardEvent) => {
      const el = e.target as HTMLElement | null;
      if (el?.closest?.("input, textarea, select, [contenteditable='true']")) return;

      const cd = e.clipboardData;
      if (!cd) return;

      if (cd.files && cd.files.length > 0) {
        e.preventDefault();
        addDocFiles(cd.files);
        return;
      }

      const text = cd.getData("text/plain");
      const trimmed = text?.trim() ?? "";
      if (!trimmed) return;

      e.preventDefault();
      addPastedTextAsTxtFile(trimmed);
    };

    window.addEventListener("paste", onPaste);
    return () => window.removeEventListener("paste", onPaste);
  }, [step, mode, addDocFiles, addPastedTextAsTxtFile]);

  const removeDocFile = (index: number) => {
    setDocFiles((prev) => prev.filter((_, i) => i !== index));
    setDocError(null);
  };

  const formatFileSize = (bytes: number) => {
    if (bytes < 1024) return `${bytes} B`;
    if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
    return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
  };

  // ─── File-extension URL detection ────────────────────────────
  const urlFileExt = mode === "url" ? getFileExtension(urls[0] ?? "") : null;
  const bulkFileExtRows = mode === "bulk"
    ? bulkRows.map((r) => getFileExtension(r.url))
    : [];
  const hasBulkFileExt = bulkFileExtRows.some(Boolean);

  // ─── Non-scrapable link detection ────────────────────────────
  const urlClassification = mode === "url" ? classifyUrl(urls[0] ?? "") : { kind: "ok" as const };
  const urlScrape = urlClassification.kind;
  const bulkScrapeRows = mode === "bulk"
    ? bulkRows.map((r) => classifyUrlScrapability(r.url))
    : [];
  const hasBulkBlocked = bulkScrapeRows.some((s) => s === "blocked");

  // ─── Navigation ──────────────────────────────────────────────
  // Step order: 1 = Project (URL/Upload/Bulk), 2 = Template, 3 = Voice
  const canGoNext1 =
    mode === "url"
      ? !!urls[0]?.trim() && !hasSpacesInMiddle(urls[0]) && containsDot(urls[0]) && !urlFileExt && urlScrape !== "blocked"
      : mode === "upload"
        ? docFiles.length > 0
        : bulkRows.some((r) => r.url.trim()) &&
          bulkRows.every(
            (r) =>
              !r.url.trim() || (!hasSpacesInMiddle(r.url) && containsDot(r.url))
          ) && !hasBulkFileExt && !hasBulkBlocked;

  const goNext = () => {
    if (step === 1 && canGoNext1) {
      if (mode === "bulk") {
        const n = bulkRows.length;
        setBulkNames((prev) => resizeTo(prev, n, ""));
        setBulkTemplates((prev) => resizeTo(prev, n, pickerDefaultTemplateId));
        setBulkVoiceGender((prev) => resizeTo(prev, n, "female"));
        setBulkVoiceAccent((prev) => resizeTo(prev, n, "american"));
        setBulkCustomVoiceId((prev) => resizeTo(prev, n, ""));
        setBulkContentLanguage((prev) => resizeTo(prev, n, "auto"));
        setBulkVideoLength((prev) => resizeTo(prev, n, "short"));
        setBulkStockFootage((prev) => resizeTo(prev, n, true));
        setBulkAspectRatio((prev) => resizeTo(prev, n, "landscape"));
        setBulkVideoStyles((prev) =>
          resizeTo(
            prev,
            n,
            videoStyleForBulkTemplateId(
              pickerDefaultTemplateIdRef.current,
              templatesRef.current,
              customTemplatesRef.current
            )
          )
        );
        setBulkAccentColors((prev) => resizeTo(prev, n, ""));
        setBulkBgColors((prev) => resizeTo(prev, n, ""));
        setBulkTextColors((prev) => resizeTo(prev, n, ""));
        setBulkLogoFile((prev) => resizeTo(prev, n, null));
        setBulkLogoPosition((prev) => resizeTo(prev, n, "bottom_right"));
        setBulkLogoOpacity((prev) => resizeTo(prev, n, 0.9));
        setBulkActiveIndex(0);
      }
      setStep(2);
    } else if (step === 2) {
      step3EnteredAtRef.current = Date.now();
      setBulkActiveIndex(0);
      setStep(3);
    }
  };

  function resizeTo<T>(arr: T[], len: number, fill: T): T[] {
    if (arr.length >= len) return arr.slice(0, len);
    return [...arr, ...Array(len - arr.length).fill(fill)];
  }

  const addBulkRow = () => {
    if (bulkRows.length >= MAX_BULK_LINKS) return;
    setBulkRows((prev) => [...prev, { url: "" }]);
    setBulkNames((prev) => [...prev, ""]);
    setBulkTemplates((prev) => [...prev, pickerDefaultTemplateId]);
    setBulkVoiceGender((prev) => [...prev, "female"]);
    setBulkVoiceAccent((prev) => [...prev, "american"]);
    setBulkCustomVoiceId((prev) => [...prev, ""]);
    setBulkContentLanguage((prev) => [...prev, "auto"]);
    setBulkVideoLength((prev) => [...prev, "short"]);
    setBulkStockFootage((prev) => {
      const next = [...prev, bulkApplyStockAll ? (prev[bulkStockMasterIndex] ?? true) : true];
      return next;
    });
    setBulkAspectRatio((prev) => [...prev, "landscape"]);
    setBulkVideoStyles((prev) => [
      ...prev,
      videoStyleForBulkTemplateId(
        pickerDefaultTemplateIdRef.current,
        templatesRef.current,
        customTemplatesRef.current
      ),
    ]);
    setBulkAccentColors((prev) => [...prev, ""]);
    setBulkBgColors((prev) => [...prev, ""]);
    setBulkTextColors((prev) => [...prev, ""]);
    setBulkLogoFile((prev) => [...prev, null]);
    setBulkLogoPosition((prev) => [...prev, "bottom_right"]);
    setBulkLogoOpacity((prev) => [...prev, 0.9]);
    bulkStyleManuallySet.current = [...bulkStyleManuallySet.current, false];
  };

  const removeBulkRow = (index: number) => {
    if (bulkRows.length <= 1) return;
    bulkStyleManuallySet.current = bulkStyleManuallySet.current.filter((_, i) => i !== index);
    setBulkRows((prev) => prev.filter((_, i) => i !== index));
    setBulkNames((prev) => prev.filter((_, i) => i !== index));
    setBulkTemplates((prev) => prev.filter((_, i) => i !== index));
    setBulkVoiceGender((prev) => prev.filter((_, i) => i !== index));
    setBulkVoiceAccent((prev) => prev.filter((_, i) => i !== index));
    setBulkCustomVoiceId((prev) => prev.filter((_, i) => i !== index));
    setBulkContentLanguage((prev) => prev.filter((_, i) => i !== index));
    setBulkVideoLength((prev) => prev.filter((_, i) => i !== index));
    setBulkStockFootage((prev) => prev.filter((_, i) => i !== index));
    setBulkAspectRatio((prev) => prev.filter((_, i) => i !== index));
    setBulkVideoStyles((prev) => prev.filter((_, i) => i !== index));
    setBulkAccentColors((prev) => prev.filter((_, i) => i !== index));
    setBulkBgColors((prev) => prev.filter((_, i) => i !== index));
    setBulkTextColors((prev) => prev.filter((_, i) => i !== index));
    setBulkLogoFile((prev) => prev.filter((_, i) => i !== index));
    setBulkLogoPosition((prev) => prev.filter((_, i) => i !== index));
    setBulkLogoOpacity((prev) => prev.filter((_, i) => i !== index));
    setBulkActiveIndex((prev) => {
      if (prev >= bulkRows.length - 1) return Math.max(0, prev - 1);
      return prev;
    });
  };

 const goBack = () => {
  if (step === 2) {
    setStep(1);
    setBulkActiveIndex(0);
  } 
  else if (step === 3) {
    setStep(2);
    setBulkActiveIndex(0);
  }
};

  // ─── Submit ──────────────────────────────────────────────────
  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (isDemo) return;
    if (step !== 3) return;
    const enteredAt = step3EnteredAtRef.current;
    if (enteredAt != null && Date.now() - enteredAt < 400) return;
    step3EnteredAtRef.current = null;
    audioRef.current?.pause();
    bgmAudioRef.current?.pause();

    if (mode === "bulk" && onSubmitBulk) {
      const valid = bulkRows
        .map((r, i) => ({ url: r.url, name: bulkNames[i] ?? "", i }))
        .filter((r) => r.url.trim());
      if (valid.length === 0) return;
      // Detect duplicate URLs and auto-suffix names
      const urlCounts: Record<string, number> = {};
      const urlSeenSoFar: Record<string, number> = {};
      for (const { url } of valid) {
        const normalized = url.trim();
        urlCounts[normalized] = (urlCounts[normalized] ?? 0) + 1;
      }

      const firstSavedVoiceId = myVoicesList[0]?.voice_id;
      const items: BulkProjectItem[] = valid.map(({ url, name: n, i }) => {
        const normalized = url.trim();
        urlSeenSoFar[normalized] = (urlSeenSoFar[normalized] ?? 0) + 1;
        const isDuplicate = urlCounts[normalized] > 1;

        let resolvedName = n.trim() || undefined;
        if (!resolvedName && isDuplicate) {
          const occurrence = urlSeenSoFar[normalized];
          const derived = deriveNameFromUrl(normalized);
          resolvedName = occurrence === 1 ? derived : `${derived} (${occurrence})`;
        }

        const rowSelectedVoiceId = bulkCustomVoiceId[i]?.trim();
        const selectedVoice = myVoicesList.find((v) => v.voice_id === rowSelectedVoiceId);
        const rowGender = bulkVoiceGender[i] ?? "female";
        const inferredGender =
          rowGender === "none"
            ? "none"
            : (normalizeVoiceGender(selectedVoice?.gender) ?? rowGender);
        const inferredAccent = normalizeVoiceAccent(selectedVoice?.accent) ?? bulkVoiceAccent[i];
        const effectiveCustomVoiceId = rowSelectedVoiceId || firstSavedVoiceId;

        return {
        blog_url: normalized,
        name: resolvedName,
        template: bulkTemplates[i] !== "default" ? bulkTemplates[i] : undefined,
        video_style:
          bulkVideoStyles[i] ??
          videoStyleForBulkTemplateId(
            bulkTemplates[i] ?? "default",
            templatesRef.current,
            customTemplatesRef.current
          ),
        video_length: bulkVideoLength[i] ?? "short",
        voice_gender: inferredGender,
        voice_accent: inferredAccent,
        voice_emotion: (() => {
          const s = bulkVoiceStability[i] ?? VOICE_STABILITY_DEFAULT;
          const sp = bulkVoiceSpeed[i] ?? VOICE_SPEED_DEFAULT;
          const em = bulkVoiceEmotion[i] ?? "";
          const sty = bulkVoiceStyle[i] ?? VOICE_STYLE_DEFAULT;
          // Always send for Pro+voiced so the enabled/disabled flag + last values are remembered;
          // the backend only applies tuning to the project when the flag is on.
          return isPro && inferredGender !== "none" ? serializeVoiceTuning(s, sp, em, sty, expressiveEnabled) : undefined;
        })(),
        accent_color:
          bulkAccentColors[i] && bulkAccentColors[i].trim()
            ? bulkAccentColors[i]
            : accentColor,
        bg_color:
          bulkBgColors[i] && bulkBgColors[i].trim()
            ? bulkBgColors[i]
            : bgColor,
        text_color:
          bulkTextColors[i] && bulkTextColors[i].trim()
            ? bulkTextColors[i]
            : textColor,
        logo_position: bulkLogoPosition[i] ?? "bottom_right",
        logo_opacity: bulkLogoOpacity[i] ?? 0.9,
        custom_voice_id:
          inferredGender === "none"
            ? undefined
            : (effectiveCustomVoiceId || undefined),
        aspect_ratio: bulkAspectRatio[i] ?? "landscape",
        content_language:
          (bulkContentLanguage[i] ?? "auto") === "auto"
            ? null
            : (bulkContentLanguage[i] ?? "auto"),
        // Per-row now (with "apply to all" in step 1); the backend still decides
        // per project whether its template can render a clip and clears otherwise.
        stock_footage_enabled: bulkStockFootage[i] ?? false,
      };
      });
      const logoIndices: number[] = [];
      const logoFiles: File[] = [];
      valid.forEach((v, j) => {
        const f = bulkLogoFile[v.i];
        if (f) {
          logoIndices.push(j);
          logoFiles.push(f);
        }
      });
      await onSubmitBulk(items, logoIndices.length > 0 ? { logoIndices, logoFiles } : null);
      setBulkRows([{ url: "" }]);
      setBulkNames([""]);
      setBulkTemplates([pickerDefaultTemplateId]);
      setBulkVoiceGender(["female"]);
      setBulkVoiceAccent(["american"]);
      setBulkVoiceStability([VOICE_STABILITY_DEFAULT]);
      setBulkVoiceSpeed([VOICE_SPEED_DEFAULT]);
      setBulkVoiceEmotion([""]);
      setBulkVoiceStyle([VOICE_STYLE_DEFAULT]);
      setBulkCustomVoiceId([]);
      setBulkContentLanguage(["auto"]);
      setBulkVideoLength(["short"]);
      setBulkStockFootage([true]);
      setBulkAspectRatio(["landscape"]);
      setBulkVideoStyles([DEFAULT_VIDEO_STYLE]);
      setBulkAccentColors([""]);
      setBulkBgColors([""]);
      setBulkTextColors([""]);
      setBulkLogoFile([null]);
      setBulkLogoPosition(["bottom_right"]);
      setBulkLogoOpacity([0.9]);
      setBulkActiveIndex(0);
      setBulkApplyLengthAll(true);
      setBulkLengthMasterIndex(0);
      setBulkApplyTemplateAll(true);
      setBulkTemplateMasterIndex(0);
      setBulkApplyVoiceAll(true);
      setBulkVoiceMasterIndex(0);
      setVideoLength("short");
      setContentLanguage("auto");
      return;
    }

    if (mode === "upload") {
      if (docFiles.length === 0) return;
      const selectedVoice = myVoicesList.find((v) => v.voice_id === customVoiceId.trim());
      const inferredGender =
        voiceGender === "none"
          ? "none"
          : (normalizeVoiceGender(selectedVoice?.gender) ?? voiceGender);
      const inferredAccent = normalizeVoiceAccent(selectedVoice?.accent) ?? voiceAccent;
      const effectiveCustomVoiceId = customVoiceId.trim() || myVoicesList[0]?.voice_id || "";
      await onSubmit(
        "",
        name.trim() || undefined,
        inferredGender,
        inferredAccent,
        accentColor,
        bgColor,
        textColor,
        undefined,
        logoFile || undefined,
        logoPosition,
        logoOpacity,
        inferredGender === "none" ? undefined : (effectiveCustomVoiceId || undefined),
        aspectRatio,
        docFiles,
        template !== "default" ? template : undefined,
        videoStyle,
        videoLength,
        contentLanguage === "auto" ? null : contentLanguage,
        isPro && inferredGender !== "none"
          ? serializeVoiceTuning(voiceStability, voiceSpeed, voiceEmotion, voiceStyle, expressiveEnabled)
          : undefined,
        selectedBgmTrackId,
        selectedBgmVolume
      );
      setDocFiles([]);
      setName("");
    } else {
      const validUrls = urls.filter((u) => u.trim());
      if (validUrls.length === 0) return;
      const selectedVoice = myVoicesList.find((v) => v.voice_id === customVoiceId.trim());
      const inferredGender =
        voiceGender === "none"
          ? "none"
          : (normalizeVoiceGender(selectedVoice?.gender) ?? voiceGender);
      const inferredAccent = normalizeVoiceAccent(selectedVoice?.accent) ?? voiceAccent;
      const effectiveCustomVoiceId = customVoiceId.trim() || myVoicesList[0]?.voice_id || "";
      for (const url of validUrls) {
        await onSubmit(
          url.trim(),
          name.trim() || undefined,
          inferredGender,
          inferredAccent,
          accentColor,
          bgColor,
          textColor,
          undefined,
          logoFile || undefined,
          logoPosition,
          logoOpacity,
          inferredGender === "none" ? undefined : (effectiveCustomVoiceId || undefined),
          aspectRatio,
          undefined,
          template !== "default" ? template : undefined,
          videoStyle,
          videoLength,
          contentLanguage === "auto" ? null : contentLanguage,
          isPro && inferredGender !== "none"
          ? serializeVoiceTuning(voiceStability, voiceSpeed, voiceEmotion, voiceStyle, expressiveEnabled)
          : undefined,
          selectedBgmTrackId,
          selectedBgmVolume
        );
      }
      setUrls([""]);
      setName("");
    }
  };

  // ─── Template apply colors ───────────────────────────────────
  const applyTemplate = (id: string) => {
    templateManuallySelectedRef.current = true;
    setTemplate(id);
    // Custom template
    if (id.startsWith("custom_")) {
      const customId = parseInt(id.replace("custom_", ""));
      const ct = customTemplates.find((t) => t.id === customId);
      if (ct) {
        setAccentColor(ct.preview_colors.accent);
        setBgColor(ct.preview_colors.bg);
        setTextColor(ct.preview_colors.text);
      }
      return;
    }
    const meta = allTemplates.find((t) => t.id === id);
    if (meta?.preview_colors) {
      setAccentColor(meta.preview_colors.accent);
      setBgColor(meta.preview_colors.bg);
      setTextColor(meta.preview_colors.text);
    }
  };

  const openStep2CustomTemplateCreator = (style: VideoStyleId, _bulkRow: number | null) => {
    // Creation is open to all plans; the dashboard creator enforces the per-plan
    // template-creation cap (1 free + purchased slots) via can_create_custom_template.
    onDismissFlow?.();
    const params = new URLSearchParams();
    params.set("tab", "templates");
    params.set("openCustomCreator", "1");
    params.set("videoStyle", style);
    navigate(`/dashboard?${params.toString()}`);
  };

  const openStep3CustomVoiceCreator = () => {
    if (!isPro) {
      setShowCustomTemplateUpgrade(true);
      return;
    }
    onDismissFlow?.();
    const params = new URLSearchParams();
    params.set("tab", "voices");
    params.set("openCustomVoiceCreator", "1");
    navigate(`/dashboard?${params.toString()}`);
  };

  // ─── Step 1: Project (URL or Upload) ─────────────────────────
  const bulkStep1ActiveIndex = Math.min(bulkActiveIndex, Math.max(0, bulkRows.length - 1));
  const bulkStep1MasterIndex = Math.min(bulkLengthMasterIndex, Math.max(0, bulkRows.length - 1));
  const bulkStep1RowVideoLength = bulkVideoLength[bulkStep1ActiveIndex] ?? "short";
  const applyStep1LengthToAll = () => {
    setBulkVideoLength((prev) => {
      const next = resizeTo(prev, bulkRows.length, "short");
      const value = next[bulkStep1ActiveIndex] ?? "short";
      return next.map(() => value);
    });
  };
  const bulkStep1RowStockFootage = bulkStockFootage[bulkStep1ActiveIndex] ?? false;
  const applyStep1StockToAll = () => {
    setBulkStockFootage((prev) => {
      const next = resizeTo(prev, bulkRows.length, false);
      const value = next[bulkStep1ActiveIndex] ?? false;
      return next.map(() => value);
    });
  };
  const setBulkStockFootageAt = (value: boolean) => {
    // Mirrors the length dropdown: editing a non-master row while "apply to all"
    // is on breaks the sync; editing the master (or with sync off) sets one/all.
    if (bulkApplyStockAll && bulkStep1ActiveIndex !== bulkStockMasterIndex) {
      setBulkApplyStockAll(false);
      setBulkStockFootage((prev) => {
        const next = resizeTo(prev, bulkRows.length, false);
        next[bulkStep1ActiveIndex] = value;
        return next;
      });
      return;
    }
    if (bulkApplyStockAll && bulkStep1ActiveIndex === bulkStockMasterIndex) {
      setBulkStockFootage((prev) => resizeTo(prev, bulkRows.length, false).map(() => value));
      return;
    }
    setBulkStockFootage((prev) => {
      const next = resizeTo(prev, bulkRows.length, false);
      next[bulkStep1ActiveIndex] = value;
      return next;
    });
  };

  const step1 = (
    <div className="flex flex-col flex-1 min-h-0">
      <div className="flex-1 flex flex-col space-y-5 min-h-0">
      {/* Mode tabs β€” selected tab purple */}
      <div className="flex gap-1 p-1 bg-gray-100/60 rounded-xl w-fit">
        {(["url", "upload", ...(onSubmitBulk ? (["bulk"] as const) : [])] as const).map((m) => (
          <button
            key={m}
            type="button"
            onClick={() => setMode(m)}
            className={`px-4 py-1.5 rounded-lg text-xs font-medium transition-all ${
              mode === m
                ? "bg-white text-purple-600 shadow-sm"
                : "text-gray-400 hover:text-gray-600"
            }`}
          >
            {m === "url" ? "Link" : m === "upload" ? "Upload" : "Multi Link"}
          </button>
        ))}
      </div>

      {/* Bulk: multiple links (url + name per row) */}
      {mode === "bulk" && (<>
        <BulkLinksSection
          rows={bulkRows}
          maxBulkLinks={MAX_BULK_LINKS}
          aspectRatios={bulkAspectRatio}
          onChangeUrl={(index, value) =>
            setBulkRows((prev) => prev.map((r, i) => (i === index ? { ...r, url: value } : r)))
          }
          onChangeAspectRatio={(index, value) =>
            setBulkAspectRatio((prev) => {
              const next = [...prev];
              next[index] = value;
              return next;
            })
          }
          onAddRow={addBulkRow}
          onRemoveRow={removeBulkRow}
        />
        {(() => {
          const seen = new Set<string>();
          const hasDupes = bulkRows.some((r) => {
            const t = r.url.trim();
            if (!t) return false;
            if (seen.has(t)) return true;
            seen.add(t);
            return false;
          });
          return hasDupes ? (
            <p className="text-xs text-amber-600 bg-amber-50 rounded-lg px-3 py-2 mt-2">
              Duplicate URLs detected β€” suffixes will be added to project names to differentiate them.
            </p>
          ) : null;
        })()}
        {hasBulkFileExt && (
          <div className="mt-2 flex items-start gap-2 px-3 py-2.5 rounded-xl bg-purple-50 border border-purple-200/60">
            <svg className="w-4 h-4 text-purple-500 shrink-0 mt-0.5" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
              <path strokeLinecap="round" strokeLinejoin="round" d="M13 16h-1v-4h-1m1-4h.01M12 2a10 10 0 110 20A10 10 0 0112 2z" />
            </svg>
            <p className="text-[11px] text-purple-700 leading-relaxed">
              {bulkFileExtRows.map((ext, i) => ext ? (
                <span key={i}>Row {i + 1} has a <span className="font-semibold">{ext.toUpperCase()}</span> file link. </span>
              ) : null)}
              Please use the <span className="font-semibold">Upload</span> tab to upload files directly instead of linking to them.
            </p>
          </div>
        )}

        <div className="flex flex-wrap gap-1">
          <div className="flex flex-wrap gap-1 p-1 bg-gray-100/60 rounded-xl">
            {bulkRows.map((_, i) => (
              <button
                key={i}
                type="button"
                onClick={() => setBulkActiveIndex(i)}
                className={`px-3 py-1.5 rounded-lg text-[11px] font-medium transition-all ${
                  i === bulkStep1ActiveIndex
                    ? "bg-white text-purple-600 shadow-sm"
                    : "text-gray-400 hover:text-gray-600"
                }`}
              >
                Video #{i + 1}
              </button>
            ))}
          </div>
        </div>
        
        {/* One "apply to all" toggle drives both duration and footage sync. */}
        <div className="flex items-center justify-start">
          <label className="flex items-center gap-2 text-[11px] text-gray-500 cursor-pointer select-none">
            <input
              type="checkbox"
              checked={bulkApplyLengthAll && (!stockFootageAvailable || bulkApplyStockAll)}
              onChange={(e) => {
                const checked = e.target.checked;
                setBulkApplyLengthAll(checked);
                setBulkApplyStockAll(checked);
                if (checked) {
                  setBulkLengthMasterIndex(bulkStep1ActiveIndex);
                  setBulkStockMasterIndex(bulkStep1ActiveIndex);
                  applyStep1LengthToAll();
                  applyStep1StockToAll();
                }
              }}
              className="h-3.5 w-3.5 rounded border-gray-300 accent-purple-600 focus:ring-purple-500"
            />
            Apply to all
          </label>
        </div>

        {/* Estimated duration + stock footage side by side. */}
        <div className={`mt-1 grid gap-3 items-start ${stockFootageAvailable ? "grid-cols-2" : "grid-cols-1"}`}>
          <div className="space-y-1.5">
            <label className="block text-[11px] font-medium text-gray-400 uppercase tracking-wider">
              Estimated duration
            </label>
            {renderVideoLengthDropdown(bulkStep1RowVideoLength, (value) => {
              if (bulkApplyLengthAll && bulkStep1ActiveIndex !== bulkStep1MasterIndex) {
                setBulkApplyLengthAll(false);
                setBulkVideoLength((prev) => {
                  const next = resizeTo(prev, bulkRows.length, "short");
                  next[bulkStep1ActiveIndex] = value;
                  return next;
                });
                return;
              }
              if (bulkApplyLengthAll && bulkStep1ActiveIndex === bulkStep1MasterIndex) {
                setBulkVideoLength((prev) => resizeTo(prev, bulkRows.length, "short").map(() => value));
                return;
              }
              setBulkVideoLength((prev) => {
                const next = resizeTo(prev, bulkRows.length, "short");
                next[bulkStep1ActiveIndex] = value;
                return next;
              });
            })}
          </div>

          {stockFootageAvailable && (
            <div className="space-y-1.5">
              <label className="block text-[11px] font-medium text-gray-400 uppercase tracking-wider">
                Use stock footage
              </label>
              <label className="flex items-center gap-2.5 cursor-pointer select-none p-3 rounded-xl bg-gray-50/60 border border-gray-200/60 hover:border-purple-300/60 transition-all">
                <input
                  type="checkbox"
                  checked={bulkStep1RowStockFootage}
                  onChange={(e) => setBulkStockFootageAt(e.target.checked)}
                  className="w-4 h-4 shrink-0 rounded border-gray-300 text-purple-600 focus:ring-purple-500/30 cursor-pointer accent-purple-600"
                />
                <span className="text-xs font-small text-gray-700 min-w-0">
                  {isPro ? "Insert stock footage automatically" : "Insert stock footage automatically"}
                </span>
              </label>
            </div>
          )}
        </div>
        <p className="mt-1 text-[10px] text-gray-400 pb-10 leading-relaxed">
          Actual length may vary depending on content size and video style. If the scraped or uploaded content is
          very short, video might get shorten automatically.
        </p>
      </>)}

      {/* URL input */}
      {mode === "url" && (
        <div>
          <label className="block text-[11px] font-medium text-gray-400 mb-1.5 uppercase tracking-wider">
            Blog URL
          </label>
          {urls.map((url, i) => (
            <input
              key={i}
              type="url"
              required={i === 0}
              value={url}
              onChange={(e) => {
                const next = e.target.value;
                setUrls((prev) => prev.map((u, idx) => (idx === i ? next : u)));
                if (i === 0) {
                  setUrlError(null);
                }
              }}
              onBlur={(e) => {
                if (i !== 0) return;
                const value = e.target.value;
                const trimmed = value.trim();
                if (!trimmed) {
                  setUrlError(null);
                  return;
                }
                if (hasSpacesInMiddle(value)) {
                  setUrlError("Enter a valid link (e.g. example.com, https://example.com).");
                } else if (!containsDot(value)) {
                  setUrlError("Enter a valid link (e.g. example.com, https://example.com).");
                } else {
                  setUrlError(null);
                }
              }}
              placeholder={
                i === 0
                  ? "https://yourblog.com/your-article..."
                  : `URL ${i + 1} (optional)`
              }
              className={`w-full px-4 py-2.5 bg-white/80 border rounded-xl text-sm text-gray-900 placeholder-gray-300 focus:outline-none focus:ring-2 focus:ring-purple-500/40 focus:border-transparent transition-all mb-2 ${
                i === 0 && urls[0]?.trim() && (urlError || urlScrape === "blocked")
                  ? "border-red-400"
                  : "border-gray-200/60"
              }`}
              autoFocus={i === 0}
            />
          ))}
          {urlError && urls[0]?.trim() && (
            <p className="text-xs text-red-500 mt-1">
              {urlError}
            </p>
          )}
          {urlFileExt && urls[0]?.trim() && (
            <div className="mt-2 flex items-start gap-2 px-3 py-2.5 rounded-xl bg-purple-50 border border-purple-200/60">
              <svg className="w-4 h-4 text-purple-500 shrink-0 mt-0.5" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
                <path strokeLinecap="round" strokeLinejoin="round" d="M13 16h-1v-4h-1m1-4h.01M12 2a10 10 0 110 20A10 10 0 0112 2z" />
              </svg>
              <p className="text-[11px] text-purple-700 leading-relaxed">
                <span className="font-semibold">{urlFileExt.toUpperCase()} files</span> can't be processed as a URL. Please use the{" "}
                <span className="font-semibold">Upload</span> tab above to upload this file directly.
              </p>
            </div>
          )}
          {urlScrape === "blocked" && urls[0]?.trim() && (
            <p className="text-xs text-red-500 mt-1">
              This site can't be scraped, please use a different link.
            </p>
          )}
          {urlScrape === "warn" && urls[0]?.trim() && (
            <p className="text-[11px] text-amber-600 leading-relaxed mt-1">
              {urlClassification.message}
            </p>
          )}
          <p className="mt-0.5 text-[11px] text-gray-400 leading-relaxed">
            Use a paywall-free link for best results.{" "}
            <button
              type="button"
              onClick={() => {
                const demoUrls = [
                  "https://blog2video.app/"
                  
                ];
                const picked = demoUrls[Math.floor(Math.random() * demoUrls.length)];
                setUrls((prev) => prev.map((u, idx) => (idx === 0 ? picked : u)));
                setUrlError(null);
              }}
              className="text-purple-500 hover:text-purple-700 underline underline-offset-2 transition-colors"
            >
              Try a demo link
            </button>
          </p>
        </div>
      )}

      {/* Document upload */}
      {mode === "upload" && (
        <div>
          <label className="block text-[11px] font-medium text-gray-400 mb-1.5 uppercase tracking-wider">
            Documents{" "}
            <span className="text-gray-300 font-normal">(max 5 files, 5 MB each)</span>
          </label>
          <div
            role="button"
            tabIndex={0}
            aria-label="Upload documents or paste text"
            className="relative border-2 border-dashed border-gray-200/80 rounded-xl p-6 text-center hover:border-purple-400/60 transition-colors cursor-pointer focus:outline-none focus:ring-2 focus:ring-purple-500/40"
            onClick={() => docInputRef.current?.click()}
            onKeyDown={(e) => {
              if (e.key === "Enter" || e.key === " ") {
                e.preventDefault();
                docInputRef.current?.click();
              }
            }}
            onPaste={(e) => {
              e.stopPropagation();
              const cd = e.clipboardData;
              if (cd.files && cd.files.length > 0) {
                e.preventDefault();
                addDocFiles(cd.files);
                return;
              }
              const text = cd.getData("text/plain");
              const trimmed = text?.trim() ?? "";
              if (trimmed) {
                e.preventDefault();
                addPastedTextAsTxtFile(trimmed);
              }
            }}
            onDragOver={(e) => {
              e.preventDefault();
              e.currentTarget.classList.add("border-purple-400/60", "bg-purple-50/30");
            }}
            onDragLeave={(e) => {
              e.preventDefault();
              e.currentTarget.classList.remove("border-purple-400/60", "bg-purple-50/30");
            }}
            onDrop={(e) => {
              e.preventDefault();
              e.currentTarget.classList.remove("border-purple-400/60", "bg-purple-50/30");
              addDocFiles(e.dataTransfer.files);
            }}
          >
            <svg className="w-8 h-8 mx-auto mb-2 text-gray-300" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M7 16a4 4 0 01-.88-7.903A5 5 0 1115.9 6L16 6a5 5 0 011 9.9M15 13l-3-3m0 0l-3 3m3-3v12" />
            </svg>
            <p className="text-sm text-gray-500">
              Drop files here or <span className="text-purple-600 font-medium">paste text (Ctrl+V)</span>
            </p>
            <p className="text-[10px] text-gray-300 mt-1">PDF, Word, PowerPoint, Markdown, Text, VTT β€” or paste plain text as a .txt file</p>
            <input
              ref={docInputRef}
              type="file"
              accept=".pdf,.docx,.pptx,.md,.markdown,.txt,.vtt,application/pdf,application/vnd.openxmlformats-officedocument.wordprocessingml.document,application/vnd.openxmlformats-officedocument.presentationml.presentation,text/plain,text/markdown,text/x-markdown,text/vtt"
              multiple
              className="hidden"
              onChange={(e) => { addDocFiles(e.target.files); e.target.value = ""; }}
            />
          </div>
          {docError && <p className="mt-2 text-[11px] text-red-500">{docError}</p>}
          {docFiles.length > 0 && (
            <div className="mt-3 space-y-2">
              {docFiles.map((file, i) => (
                <div key={`${file.name}-${i}`} className="flex items-center gap-3 px-4 py-3 bg-gray-50/80 rounded-xl border border-gray-200/60">
                  <svg
                    className={`w-6 h-6 flex-shrink-0 ${file.name.endsWith(".pdf") ? "text-red-400" : file.name.endsWith(".docx") ? "text-blue-400" : "text-orange-400"}`}
                    fill="currentColor"
                    viewBox="0 0 20 20"
                  >
                    <path fillRule="evenodd" d="M4 4a2 2 0 012-2h4.586A2 2 0 0112 2.586L15.414 6A2 2 0 0116 7.414V16a2 2 0 01-2 2H6a2 2 0 01-2-2V4z" clipRule="evenodd" />
                  </svg>
                  <span className="flex-1 text-sm text-gray-700 truncate font-medium">{file.name}</span>
                  <span className="text-xs text-gray-400 flex-shrink-0">{formatFileSize(file.size)}</span>
                  <button
                    type="button"
                    onClick={(e) => { e.stopPropagation(); removeDocFile(i); }}
                    className="flex-shrink-0 px-2.5 py-1.5 rounded-lg text-xs font-medium text-red-600 bg-red-50 hover:bg-red-100 border border-red-200/60 transition-colors"
                  >
                    Remove
                  </button>
                </div>
              ))}
            </div>
          )}
        </div>
      )}

      {/* Project name (single-link / upload only; bulk has per-row name) */}
      {mode !== "bulk" && (
        <div>
          <label className="block text-[11px] font-medium text-gray-400 mb-1.5 uppercase tracking-wider">
            Project Name <span className="text-gray-300 font-normal">(optional)</span>
          </label>
          <input
            type="text"
            value={name}
            onChange={(e) => setName(e.target.value)}
            placeholder={mode === "url" ? "Auto-generated from URL" : "Auto-generated from file name"}
            className="w-full px-4 py-2.5 bg-white/80 border border-gray-200/60 rounded-xl text-sm text-gray-900 placeholder-gray-300 focus:outline-none focus:ring-2 focus:ring-purple-500/40 focus:border-transparent transition-all"
          />
        </div>
      )}

      {/* Format, duration + Logo (single-link / upload only; bulk has per-row in step 3) */}
      {mode !== "bulk" && (
        <>
          <div>
            <label className="block text-[11px] font-medium text-gray-400 mb-2 uppercase tracking-wider">
              Video Format
            </label>
            <div className="flex gap-2">
              {([
                { value: "landscape", label: "Landscape", sub: "YouTube" },
                { value: "portrait", label: "Portrait", sub: "TikTok / Reels" },
              ] as const).map((opt) => (
                <button
                  key={opt.value}
                  type="button"
                  onClick={() => setAspectRatio(opt.value)}
                  className={`flex-1 py-2.5 rounded-lg text-xs font-medium transition-all flex flex-col items-center gap-0.5 ${
                    aspectRatio === opt.value
                      ? "bg-purple-600 text-white shadow-sm"
                      : "bg-gray-50 text-gray-500 hover:bg-gray-100 border border-gray-200/60"
                  }`}
                >
                  <span>{opt.label}</span>
                  <span className={`text-[9px] ${aspectRatio === opt.value ? "text-purple-200" : "text-gray-300"}`}>
                    {opt.sub}
                  </span>
                </button>
              ))}
            </div>
          </div>

          <div>
            {/* Estimated duration + stock footage side by side in one row. */}
            {/* items-stretch + h-full on each column: the duration label can wrap
                to two lines while the checkbox stays one, so sizing each column
                to its own content leaves the two pills visibly different heights. */}
            <div className={`grid gap-2 items-stretch ${stockFootageAvailable ? "grid-cols-2" : "grid-cols-1"}`}>
              <div className="flex flex-col h-full">
                <label className="block text-[11px] font-medium text-gray-400 mb-1.5 uppercase tracking-wider">
                  Estimated duration
                </label>
                <div className="flex flex-1 flex-col [&>details]:flex-1 [&>details>summary]:h-full">
                  {renderVideoLengthDropdown(videoLength, setVideoLength)}
                </div>
              </div>

              {stockFootageAvailable && (
                <div className="flex flex-col h-full">
                  <label className="block text-[11px] font-medium text-gray-400 mb-1.5 uppercase tracking-wider">
                    Use stock footage
                  </label>
                  <label className="flex flex-1 items-center gap-2.5 cursor-pointer select-none p-3 rounded-xl bg-white border border-gray-200 hover:border-purple-300/60 transition-all">
                    <input
                      type="checkbox"
                      checked={stockFootageEnabled}
                      onChange={(e) => setStockFootageEnabled(e.target.checked)}
                      className="w-4 h-4 shrink-0 rounded border-gray-300 text-purple-600 focus:ring-purple-500/30 cursor-pointer accent-purple-600"
                    />
                    <span className="text-xs font-small text-gray-700 min-w-0">
                      {isPro ? "Insert stock footage automatically" : "Insert stock footage automatically"}
                    </span>
                  </label>
                </div>
              )}
            </div>
            <p className="mt-1 text-[10px] text-gray-400 leading-relaxed">
              Actual length may vary depending on content size and video style. If the scraped or uploaded content is
              very short, we may shorten the video.
            </p>
          </div>

          <div>
            <label className="block text-[11px] font-medium text-gray-400 mb-2 uppercase tracking-wider">
              Logo <span className="text-gray-300 font-normal">(optional Β· max 2 MB)</span>
            </label>
            <div className="flex items-center gap-3">
              <div className="relative mb-4 inline-block">
                <button
                  type="button"
                  onClick={() => logoInputRef.current?.click()}
                  className="px-3 py-2 rounded-lg text-xs font-medium bg-gray-50 text-gray-500 hover:bg-gray-100 border border-gray-200/60 transition-all pr-8"
                >
                  {logoFile ? logoFile.name : "Choose file"}
                </button>
                {logoFile && (
                  <button
                    type="button"
                    onClick={(e) => {
                      e.stopPropagation();
                      setLogoFile(null);
                      if (logoInputRef.current) logoInputRef.current.value = "";
                    }}
                    className="absolute top-0.5 right-0.5 w-6 h-6 rounded-full border border-purple-500/80 text-purple-600 hover:bg-purple-600 hover:text-white hover:border-purple-600 flex items-center justify-center transition-colors"
                    title="Remove logo"
                  >
                    <svg className="w-3 h-3" fill="none" stroke="currentColor" strokeWidth={2.5} viewBox="0 0 24 24">
                      <path strokeLinecap="round" strokeLinejoin="round" d="M6 18L18 6M6 6l12 12" />
                    </svg>
                  </button>
                )}
              </div>
              <input
                ref={logoInputRef}
                type="file"
                accept="image/png,image/jpeg,image/webp,image/svg+xml"
                className="hidden"
                onChange={(e) => {
                  const f = e.target.files?.[0] || null;
                  if (f && f.size > 2 * 1024 * 1024) {
                    showError("Logo must be under 2 MB.");
                    e.target.value = "";
                    return;
                  }
                  setLogoFile(f);
                }}
              />
            </div>
            {logoFile && (
              <div className="mt-2">
                <label className="block text-[10px] text-gray-400 mb-1">Position</label>
                <div className="grid grid-cols-2 sm:grid-cols-4 gap-1.5">
                  {([
                    { value: "top_left", label: "Top Left" },
                    { value: "top_right", label: "Top Right" },
                    { value: "bottom_left", label: "Bottom Left" },
                    { value: "bottom_right", label: "Bottom Right" },
                  ] as const).map((pos) => (
                    <button
                      key={pos.value}
                      type="button"
                      onClick={() => setLogoPosition(pos.value)}
                      className={`px-2 py-1 rounded text-[10px] font-medium transition-all ${
                        logoPosition === pos.value
                          ? "bg-purple-600 text-white"
                          : "bg-gray-50 text-gray-400 hover:bg-gray-100 border border-gray-200/60"
                      }`}
                    >
                      {pos.label}
                    </button>
                  ))}
                </div>
                <div className="mt-2.5 mb-3.5">
                  <label className="block text-[10px] text-gray-500 mb-1">
                    Opacity <span className="text-gray-500">{Math.round(logoOpacity * 100)}%</span>
                  </label>
                  <input
                    type="range"
                    min={10}
                    max={100}
                    step={5}
                    value={Math.round(logoOpacity * 100)}
                    onChange={(e) => setLogoOpacity(parseInt(e.target.value, 10) / 100)}
                    className="w-full h-1 bg-gray-300 rounded-full appearance-none cursor-pointer accent-purple-600"
                  />
                </div>
              </div>
            )}
          </div>
        </>
      )}
      </div>

      {/* Next β€” always visible; gray when disabled (invalid/empty URL) */}
      <button
        type="button"
        onClick={goNext}
        disabled={!canGoNext1}
        className={`w-full mb-3 py-3 mt-auto text-sm font-medium rounded-xl transition-colors flex items-center justify-center gap-2 flex-shrink-0 ${
          canGoNext1
            ? "bg-purple-600 hover:bg-purple-700 text-white"
            : "bg-gray-200 text-gray-500 cursor-not-allowed"
        }`}
      >
        Go to step 2
        <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 5l7 7-7 7" />
        </svg>
      </button>
    </div>
  );

  // ─── Step 2: Genre/source filter + Template list ──────────────────────────
  // Genre dropdown has two source-bucket options at the top β€” "Custom Templates"
  // and "Designer Templates" β€” encoded with sentinel values. Below them are
  // the actual genres, compiled from built-in templates' meta.json.
  const allGenres = useMemo(() => {
    const set = new Set<string>();
    for (const t of templates) (t.genres ?? []).forEach((g) => g && set.add(g));
    return Array.from(set).sort();
  }, [templates]);

  const {
    suggestedTemplates,
    customTemplatesForStyle,
    craftedTemplatesForStyle,
  } = templateBucketsForGenre(genre, templates, readyCustomTemplates, readyCraftedTemplates);

  const sortedSuggestedTemplates = [...suggestedTemplates].sort((a, b) => {
    const rank = (t: TemplateMeta) => (t.new_template ? 0 : t.popular_template ? 1 : 2);
    return rank(a) - rank(b);
  });

  const styleTemplateItems: Array<
    | { type: "builtin"; id: string; data: TemplateMeta }
    | { type: "custom"; id: string; data: CustomTemplateItem }
    | { type: "crafted"; id: string; data: CraftedTemplateItem }
  > = [
    ...sortedSuggestedTemplates.map((t) => ({ type: "builtin" as const, id: t.id, data: t })),
    ...customTemplatesForStyle.map((ct) => ({ type: "custom" as const, id: `custom_${ct.id}`, data: ct })),
    ...craftedTemplatesForStyle.map((ct) => ({ type: "crafted" as const, id: ct.id, data: ct })),
  ];

  const SelectedPreviewComp = TEMPLATE_PREVIEWS[template];
  const selectedDesc = TEMPLATE_DESCRIPTIONS[template];
  const selectedCustom = template.startsWith("custom_")
    ? customTemplates.find((ct) => ct.id === parseInt(template.replace("custom_", "")))
    : null;
  const selectedCrafted = template.startsWith("crafted_")
    ? craftedTemplates.find((ct) => ct.id === template)
    : null;
  const selectedBuiltinNew =
    !template.startsWith("custom_") && allTemplates.some((t) => t.id === template && t.new_template === true);

  const step2Template = (
    <div className="space-y-5">
      {/* Selected template β€” full-width preview */}
      <div>
        <label className="block text-[11px] font-medium text-gray-400 mb-2 uppercase tracking-wider">
          Selected Template
        </label>
        <div className="rounded-xl overflow-hidden border-2 border-purple-500 shadow-[0_0_0_4px_rgba(124,58,237,0.1)]">
          <div className="relative aspect-video overflow-hidden">
            {demoMode?.templatePreviewOverride && !selectedCustom && !selectedCrafted ? (
              demoMode.templatePreviewOverride({ templateId: template, selected: true, thumbnail: false })
            ) : selectedCustom ? (
              <CustomPreview theme={selectedCustom.theme} name={selectedCustom.name} previewImageUrl={selectedCustom.preview_image_url} introCode={selectedCustom.intro_code || undefined} outroCode={selectedCustom.outro_code || undefined} contentCodes={selectedCustom.content_codes || undefined} contentArchetypeIds={selectedCustom.content_archetype_ids || undefined} logoUrls={selectedCustom.logo_urls} ogImage={selectedCustom.og_image} thumbnailMode={isMobile} staticThumb={isMobile} key={`selected-custom-${selectedCustom.id}-${step}`} />
            ) : selectedCrafted && ((selectedCrafted as any).frontend_files || selectedCrafted.preview_file || selectedCrafted.preview_image_url || selectedCrafted.theme) ? (
              <CraftedTemplatePreviewSmart
                item={selectedCrafted}
                compileCacheScope={user?.id != null ? String(user.id) : undefined}
                showLoaderOnEmptyOrError
                thumbnailMode={isMobile}
                staticThumb={isMobile}
                key={`selected-crafted-${selectedCrafted.id}-${step}`}
              />
            ) : template.startsWith("crafted_") && craftedTemplatesLoading ? (
              <div className="w-full aspect-video bg-[#1a1a2e] flex items-center justify-center">
                <span className="w-7 h-7 border-2 border-purple-200/50 border-t-purple-500 rounded-full animate-spin" />
              </div>
            ) : SelectedPreviewComp ? (
              <SelectedPreviewComp thumbnailMode={isMobile} key={`selected-${template}-${step}`} />
            ) : (
              <div className="w-full aspect-video bg-gray-100 flex items-center justify-center text-gray-300 text-sm">
                {selectedDesc?.title ?? template}
              </div>
            )}
          </div>
          <div className="px-4 py-2.5 bg-purple-50/80 flex flex-col sm:flex-row items-start sm:items-center justify-between gap-3">
            <div>
              <div className="flex items-center gap-2">
                <span className="text-sm font-semibold text-gray-800">
                  {selectedCustom ? selectedCustom.name : selectedCrafted ? selectedCrafted.name : (selectedDesc?.title ?? template)}
                </span>
                {selectedBuiltinNew && <NewTemplateBadge className="shrink-0" />}
                {selectedCustom && (
                  <span className="px-1.5 py-0.5 rounded text-[9px] font-bold text-white" style={{ backgroundColor: selectedCustom.preview_colors.accent }}>
                    Custom
                  </span>
                )}
                {selectedCrafted && (
                  <span className="px-1.5 py-0.5 rounded text-[9px] font-bold text-white bg-amber-500">
                    Designer
                  </span>
                )}
              </div>
              {selectedCustom ? (
                <div className="text-[11px] text-gray-400 mt-0.5">Custom template</div>
              ) : selectedCrafted ? (
                <div className="text-[11px] text-gray-400 mt-0.5">Designer template</div>
              ) : selectedDesc?.subtitle ? (
                <div className="text-[11px] text-gray-400 mt-0.5">{selectedDesc.subtitle}</div>
              ) : null}
            </div>
            <div className="w-6 h-6 rounded-full bg-purple-600 flex items-center justify-center flex-shrink-0">
              <svg className="w-3.5 h-3.5 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={3} d="M5 13l4 4L19 7" />
              </svg>
            </div>
          </div>
        </div>
      </div>

      {/* Genre dropdown + Templates list (filtered by genre) */}
      <div>
        <div className="flex items-center justify-between mb-2">
          <label className="block text-[11px] font-medium text-gray-400 uppercase tracking-wider">
            Genre
          </label>
          <div className="relative">
            <button
              type="button"
              onClick={() => setGenreDropdownOpen((v) => !v)}
              className="flex items-center gap-2 px-3 py-1.5 rounded-xl bg-gray-100/60 hover:bg-gray-200/70 text-[11px] font-medium text-gray-700 transition-all min-w-[140px] justify-between"
            >
              <span>
                {genre === GENRE_CUSTOM
                  ? "Custom Templates"
                  : genre === GENRE_CRAFTED
                  ? "Designer"
                  : genre === GENRE_NEW
                  ? "New"
                  : genre === GENRE_POPULAR
                  ? "Popular"
                  : genre || "All genres"}
              </span>
              <svg
                className={`w-3 h-3 text-gray-500 transition-transform ${genreDropdownOpen ? "rotate-180" : ""}`}
                fill="none"
                stroke="currentColor"
                viewBox="0 0 24 24"
              >
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 9l-7 7-7-7" />
              </svg>
            </button>
            {genreDropdownOpen && (
              <>
                <div className="fixed inset-0 z-10" onClick={() => setGenreDropdownOpen(false)} />
                <div className="absolute right-0 top-full mt-1 z-20 bg-white rounded-xl shadow-lg border border-gray-200 py-1 min-w-[200px] max-h-[300px] overflow-y-auto">
                  <button
                    type="button"
                    onClick={() => {
                      setGenre("");
                      setGenreDropdownOpen(false);
                    }}
                    className={`w-full text-left px-3 py-1.5 text-[11px] font-medium transition-colors ${
                      genre === "" ? "bg-purple-50 text-purple-600" : "text-gray-700 hover:bg-gray-50"
                    }`}
                  >
                    All genres
                  </button>
                  {/* Source filters β€” independent of genre */}
                  <div className="my-1 border-t border-gray-100" />
                  <button
                    type="button"
                    onClick={() => {
                      setGenre(GENRE_NEW);
                      setGenreDropdownOpen(false);
                    }}
                    className={`w-full text-left px-3 py-1.5 text-[11px] font-medium transition-colors ${
                      genre === GENRE_NEW ? "bg-purple-50 text-purple-600" : "text-gray-700 hover:bg-gray-50"
                    }`}
                  >
                    ✦ New
                  </button>
                  <button
                    type="button"
                    onClick={() => {
                      setGenre(GENRE_POPULAR);
                      setGenreDropdownOpen(false);
                    }}
                    className={`w-full text-left px-3 py-1.5 text-[11px] font-medium transition-colors ${
                      genre === GENRE_POPULAR ? "bg-amber-50 text-amber-600" : "text-gray-700 hover:bg-gray-50"
                    }`}
                  >
                    Popular
                  </button>
                  <button
                    type="button"
                    onClick={() => {
                      setGenre(GENRE_CUSTOM);
                      setGenreDropdownOpen(false);
                    }}
                    className={`w-full text-left px-3 py-1.5 text-[11px] font-medium transition-colors ${
                      genre === GENRE_CUSTOM ? "bg-purple-50 text-purple-600" : "text-gray-700 hover:bg-gray-50"
                    }`}
                  >
                    Custom Templates
                  </button>
                  <button
                    type="button"
                    onClick={() => {
                      setGenre(GENRE_CRAFTED);
                      setGenreDropdownOpen(false);
                    }}
                    className={`w-full text-left px-3 py-1.5 text-[11px] font-medium transition-colors ${
                      genre === GENRE_CRAFTED ? "bg-purple-50 text-purple-600" : "text-gray-700 hover:bg-gray-50"
                    }`}
                  >
                    Designer Templates
                  </button>
                  {allGenres.length > 0 && <div className="my-1 border-t border-gray-100" />}
                  {allGenres.map((g) => (
                    <button
                      key={g}
                      type="button"
                      onClick={() => {
                        setGenre(g);
                        setGenreDropdownOpen(false);
                      }}
                      className={`w-full text-left px-3 py-1.5 text-[11px] font-medium transition-colors ${
                        genre === g ? "bg-purple-50 text-purple-600" : "text-gray-700 hover:bg-gray-50"
                      }`}
                    >
                      {g}
                    </button>
                  ))}
                </div>
              </>
            )}
          </div>
        </div>
        <p className="text-[10px] text-gray-500 mb-1.5 font-medium">
          {genreTemplateListCaption(genre)}
        </p>
        <div className="border border-gray-200/60 rounded-xl p-2.5 max-h-[260px] sm:max-h-[220px] overflow-y-auto bg-gray-50/40">
          <>
            <div className="grid grid-cols-2 sm:grid-cols-3 gap-2">
              <CraftYourTemplateCard
                variant="default"
                isPro={isPro}
                onClick={() => {
                  setShowGetMoreTemplates(true);
                }}
                onKeyDown={(e) => {
                  if (e.key === "Enter" || e.key === " ") {
                    e.preventDefault();
                    setShowGetMoreTemplates(true);
                  }
                }}
              />
              {styleTemplateItems.map((item) => {
                if (item.type === "custom" || item.type === "crafted") {
                  const ct = item.data;
                  const customId = item.id;
                  const isSelected = template === customId;
                  // Mobile: every grid tile renders a static themed placeholder
                  // and never mounts a Player β€” the selected template plays only
                  // in the full-width "Selected Template" preview above. A grid of
                  // live Players exhausts iOS Safari's memory and reloads the tab.
                  const staticThumb = isMobile;
                  return (
                    <div
                      key={customId}
                      onClick={() => applyTemplate(customId)}
                      className={`relative rounded-lg border-2 overflow-hidden cursor-pointer transition-all group ${
                        isSelected
                          ? "border-purple-500 shadow-[0_0_0_3px_rgba(124,58,237,0.1)]"
                          : "border-gray-200/60 hover:border-purple-300/60"
                      }`}
                    >
                      <div className="relative isolate h-[70px] overflow-hidden">
                        <div className="relative z-0 h-full">
                          {item.type === "crafted" ? (
                            <CraftedTemplatePreviewSmart
                              item={ct as any}
                              compileCacheScope={user?.id != null ? String(user.id) : undefined}
                              thumbnailMode
                              showLoaderOnEmptyOrError
                              staticThumb={staticThumb}
                              key={`${customId}-${step}`}
                            />
                          ) : (
                            <CustomPreviewLandscape {...({ theme: ct.theme, name: ct.name, introCode: ct.intro_code || undefined, outroCode: ct.outro_code || undefined, contentCodes: ct.content_codes || undefined, contentArchetypeIds: ct.content_archetype_ids || undefined, validLayouts: (ct as any).valid_layouts, frontendFiles: (ct as any).frontend_files, frontendEntryRel: (ct as any).frontend_entry_rel, publicAssetUrls: (ct as any).public_asset_urls, previewImageUrl: ct.preview_image_url, logoUrls: (ct as any).logo_urls, ogImage: (ct as any).og_image, showLoaderOnEmptyOrError: false, thumbnailFrame: 135, thumbnailMode: true, staticThumb } as any)} key={`${customId}-${step}`} />
                          )}
                        </div>
                        <div className="absolute top-0 left-0.5 z-[5]">
                          {item.type === "custom" ? <CustomTemplateBadge /> : (
                            <span className="pointer-events-none px-1.5 py-0.5 rounded text-[8px] font-bold uppercase tracking-wide text-white bg-amber-500 ring-1 ring-amber-300">
                              Designer
                            </span>
                          )}
                        </div>
                        {isSelected && (
                          <div className="absolute top-1.5 right-1.5 z-20 w-4 h-4 rounded-full bg-purple-600 flex items-center justify-center shadow-md ring-2 ring-white">
                            <svg className="w-2.5 h-2.5 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={3} d="M5 13l4 4L19 7" />
                            </svg>
                          </div>
                        )}
                      </div>
                      <div className={`px-2 py-1 transition-colors ${isSelected ? "bg-purple-50/80" : "bg-white/80"}`}>
                        <div className="text-[10px] font-semibold text-gray-800 truncate">
                          {ct.name}
                        </div>
                      </div>
                    </div>
                  );
                }

                const t = item.data;
                const PreviewComp = TEMPLATE_PREVIEWS[t.id];
                const desc = TEMPLATE_DESCRIPTIONS[t.id];
                const isSelected = template === t.id;
                const isNewTemplate = t.new_template === true;
                const isPopularTemplate = t.popular_template === true;
                return (
                  <div
                    key={t.id}
                    onClick={() => applyTemplate(t.id)}
                    className={`relative rounded-lg overflow-hidden cursor-pointer transition-all group ${
                      isSelected
                        ? "border-2 border-purple-500 shadow-[0_0_0_3px_rgba(124,58,237,0.1)]"
                        : isNewTemplate
                        ? "border border-purple-500 shadow-[0_0_0_2px_rgba(124,58,237,0.2)] hover:border-purple-600"
                        : isPopularTemplate
                        ? "border border-amber-400/60 shadow-[0_0_0_2px_rgba(245,158,11,0.15)] hover:border-amber-500"
                        : "border-2 border-gray-200/60 hover:border-purple-300/60"
                    }`}
                  >
                    <div className="relative h-[70px] overflow-hidden">
                      {demoMode?.templatePreviewOverride ? (
                        demoMode.templatePreviewOverride({ templateId: t.id, selected: isSelected, thumbnail: true })
                      ) : PreviewComp ? (
                        <PreviewComp key={`${t.id}-${step}`} thumbnailMode />
                      ) : (
                        <div className="w-full h-full min-h-[56px] bg-gray-100 flex items-center justify-center text-gray-300 text-[10px]">
                          {desc?.title ?? t.name}
                        </div>
                      )}
                      {isSelected && (
                        <div className="absolute top-1.5 right-1.5 w-4 h-4 rounded-full bg-purple-600 flex items-center justify-center shadow-sm">
                          <svg className="w-2.5 h-2.5 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={3} d="M5 13l4 4L19 7" />
                          </svg>
                        </div>
                      )}
                      {isNewTemplate && (
                        <div className="absolute top-0.5 left-0.5 z-[1]">
                          <NewTemplateBadge />
                        </div>
                      )}
                      {!isNewTemplate && isPopularTemplate && (
                        <div className="absolute top-0.5 left-0.5 z-[1]">
                          <PopularTemplateBadge />
                        </div>
                      )}
                    </div>
                    <div className={`px-2 py-1 transition-colors ${isSelected ? "bg-purple-50/80" : "bg-white/80"}`}>
                      <div className="text-[10px] font-semibold text-gray-800 truncate">
                        {desc?.title ?? t.name}
                      </div>
                    </div>
                  </div>
                );
              })}
              {customTemplatesLoading && (
                <div
                  className="rounded-lg border border-dashed border-gray-200/80 bg-white/70 flex flex-col items-center justify-center gap-2 min-h-[88px] px-2 py-3 text-center"
                  role="status"
                  aria-live="polite"
                >
                  <span className="w-4 h-4 border-2 border-purple-200 border-t-purple-600 rounded-full animate-spin shrink-0" aria-hidden />
                  <p className="text-[10px] text-gray-500 leading-snug">
                    Loading custom templates, please wait.
                  </p>
                </div>
              )}
              {craftedTemplatesLoading && (
                <div
                  className="rounded-lg border border-dashed border-gray-200/80 bg-white/70 flex flex-col items-center justify-center gap-2 min-h-[88px] px-2 py-3 text-center"
                  role="status"
                  aria-live="polite"
                >
                  <span className="w-4 h-4 border-2 border-amber-200 border-t-amber-500 rounded-full animate-spin shrink-0" aria-hidden />
                  <p className="text-[10px] text-gray-500 leading-snug">
                    Loading designer templates, please wait.
                  </p>
                </div>
              )}
            </div>
            {styleTemplateItems.length === 0 && (
              <p className="text-xs text-gray-500 py-3 text-center">
                No templates for this genre. Pick another genre above or add a custom template.
              </p>
            )}
          </>
        </div>

        {/* Video Style picker β€” orthogonal to genre. "Auto" lets the AI choose after scraping. */}
        <div className="mt-4">
          <div className="flex items-center justify-between mb-2">
            <label className="block text-[11px] font-medium text-gray-400 uppercase tracking-wider">
              Video Style
            </label>
            <div className="flex flex-wrap items-center gap-1 p-1 bg-gray-100/60 rounded-xl justify-center">
              {VIDEO_STYLES.map((s) => {
                const isSelected = videoStyle === s.id;
                return (
                  <button
                    key={s.id}
                    type="button"
                    onClick={() => {
                      styleManuallySet.current = true;
                      setVideoStyle(s.id);
                    }}
                    className={`px-3 py-1.5 rounded-lg text-[11px] font-medium transition-all ${
                      isSelected ? "bg-white text-purple-600 shadow-sm" : "text-gray-400 hover:text-gray-600"
                    }`}
                  >
                    {s.label}
                  </button>
                );
              })}
            </div>
          </div>
        </div>
      </div>

      {/* Video colors */}
      <div>
        <label className="block text-[11px] font-medium text-gray-400 mb-2 uppercase tracking-wider">
          Video Colors
        </label>
        <div className="flex items-center gap-3 sm:gap-5">
          {[
            { label: "Accent", value: accentColor, setter: setAccentColor },
            { label: "Background", value: bgColor, setter: setBgColor },
            { label: "Text", value: textColor, setter: setTextColor },
          ].map(({ label, value, setter }) => (
            <label key={label} className="flex items-center gap-2 cursor-pointer group">
              <span
                className="w-8 h-8 rounded-full border-2 border-gray-200 group-hover:border-gray-400 transition-all shadow-sm relative overflow-hidden"
                style={{ backgroundColor: value }}
              >
                <input
                  type="color"
                  value={value}
                  onChange={(e) => setter(e.target.value)}
                  className="absolute inset-0 opacity-0 cursor-pointer w-full h-full"
                />
              </span>
              <span className="text-[10px] text-gray-400 font-medium">{label}</span>
            </label>
          ))}
        </div>
      </div>

      <div className="flex gap-2 pt-1">
        <button
          type="button"
          onClick={goBack}
          className="px-5 py-3 text-sm font-medium text-gray-500 bg-gray-50 hover:bg-gray-100 rounded-xl transition-colors border border-gray-200/60"
        >
          Back
        </button>
        <button
          type="button"
          onClick={goNext}
          className="flex-1 py-3 bg-purple-600 hover:bg-purple-700 text-white text-sm font-medium rounded-xl transition-colors flex items-center justify-center gap-2"
        >
          Go to step 3
          <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 5l7 7-7 7" />
          </svg>
        </button>
      </div>
    </div>
  );

  // ─── Step 2 bulk: template per project (tabbed; same UI as single) ─────────
  const step2BulkTemplate = (() => {
    const indexed = bulkRows
      .map((row, i) => ({ row, i }))
      .filter(({ row }) => row.url.trim());
    if (indexed.length === 0) {
      return (
        <div className="space-y-5">
          <p className="text-sm text-gray-500">Please go back to step 1 to continue again.</p>
          <div className="flex gap-2 pt-1">
            <button
              type="button"
              onClick={goBack}
              className="px-5 py-3 text-sm font-medium text-gray-500 bg-gray-50 hover:bg-gray-100 rounded-xl transition-colors border border-gray-200/60"
            >
              Back
            </button>
          </div>
        </div>
      );
    }

    const active = Math.min(bulkActiveIndex, indexed.length - 1);
    const activeIndex = indexed[active].i;
    const activeRow = indexed[active].row;
    const masterIndex =
      indexed.find(({ i }) => i === bulkTemplateMasterIndex)?.i ?? indexed[0].i;

    const tpl = bulkTemplates[activeIndex] ?? "default";
    const templateMeta = allTemplates.find((t) => t.id === tpl);
    const selectedCustomBulk = tpl.startsWith("custom_")
      ? customTemplates.find((ct) => ct.id === parseInt(tpl.replace("custom_", "")))
      : null;
    const selectedCraftedBulk = tpl.startsWith("crafted_")
      ? craftedTemplates.find((ct) => ct.id === tpl)
      : null;
    const selectedBuiltinNewBulk = !tpl.startsWith("custom_") && templateMeta?.new_template === true;
    const defaultAccent =
      selectedCustomBulk?.preview_colors?.accent
      ?? selectedCraftedBulk?.preview_colors?.accent
      ?? templateMeta?.preview_colors?.accent
      ?? accentColor;
    const defaultBg =
      selectedCustomBulk?.preview_colors?.bg
      ?? selectedCraftedBulk?.preview_colors?.bg
      ?? templateMeta?.preview_colors?.bg
      ?? bgColor;
    const defaultText =
      selectedCustomBulk?.preview_colors?.text
      ?? selectedCraftedBulk?.preview_colors?.text
      ?? templateMeta?.preview_colors?.text
      ?? textColor;

    const accent =
      bulkAccentColors[activeIndex] && bulkAccentColors[activeIndex].trim()
        ? bulkAccentColors[activeIndex]
        : defaultAccent;
    const bg =
      bulkBgColors[activeIndex] && bulkBgColors[activeIndex].trim()
        ? bulkBgColors[activeIndex]
        : defaultBg;
    const text =
      bulkTextColors[activeIndex] && bulkTextColors[activeIndex].trim()
        ? bulkTextColors[activeIndex]
        : defaultText;
    const activeVideoStyle = bulkVideoStyles[activeIndex] ?? DEFAULT_VIDEO_STYLE;
    const rowVideoLength = bulkVideoLength[activeIndex] ?? "short";

    const applyTemplateToAll = () => {
      const targetIndices = indexed.map(({ i }) => i);
      // Template + video style + colors
      setBulkTemplates((prev) => {
        const next = [...prev];
        targetIndices.forEach((idx) => {
          next[idx] = tpl;
        });
        return next;
      });
      setBulkVideoStyles((prev) => {
        const next = [...prev];
        targetIndices.forEach((idx) => {
          next[idx] = activeVideoStyle || DEFAULT_VIDEO_STYLE;
        });
        return next;
      });
      setBulkAccentColors((prev) => {
        const next = [...prev];
        targetIndices.forEach((idx) => {
          next[idx] = accent;
        });
        return next;
      });
      setBulkBgColors((prev) => {
        const next = [...prev];
        targetIndices.forEach((idx) => {
          next[idx] = bg;
        });
        return next;
      });
      setBulkTextColors((prev) => {
        const next = [...prev];
        targetIndices.forEach((idx) => {
          next[idx] = text;
        });
        return next;
      });
      setBulkVideoLength((prev) => {
        const next = [...prev];
        targetIndices.forEach((idx) => {
          next[idx] = rowVideoLength;
        });
        return next;
      });
      // Logo (file, position, opacity)
      setBulkLogoFile((prev) => {
        const next = [...prev];
        targetIndices.forEach((idx) => {
          next[idx] = bulkLogoFile[activeIndex] ?? null;
        });
        return next;
      });
      setBulkLogoPosition((prev) => {
        const next = [...prev];
        targetIndices.forEach((idx) => {
          next[idx] = bulkLogoPosition[activeIndex] ?? "bottom_right";
        });
        return next;
      });
      setBulkLogoOpacity((prev) => {
        const next = [...prev];
        targetIndices.forEach((idx) => {
          next[idx] = bulkLogoOpacity[activeIndex] ?? 0.9;
        });
        return next;
      });
    };

    const applyBulkTemplate = (id: string) => {
      templateManuallySelectedRef.current = true;
      const colors = id.startsWith("custom_")
        ? customTemplates.find((t) => t.id === parseInt(id.replace("custom_", "")))?.preview_colors
        : id.startsWith("crafted_")
        ? craftedTemplates.find((t) => t.id === id)?.preview_colors
        : allTemplates.find((t) => t.id === id)?.preview_colors;
      const targetIndices = indexed.map(({ i }) => i);

      if (bulkApplyTemplateAll && activeIndex !== masterIndex) {
        setBulkApplyTemplateAll(false);
        setBulkTemplates((prev) => {
          const next = [...prev];
          next[activeIndex] = id;
          return next;
        });
        if (colors) {
          setBulkAccentColors((prev) => { const next = [...prev]; next[activeIndex] = colors.accent; return next; });
          setBulkBgColors((prev) => { const next = [...prev]; next[activeIndex] = colors.bg; return next; });
          setBulkTextColors((prev) => { const next = [...prev]; next[activeIndex] = colors.text; return next; });
        }
        return;
      }

      if (bulkApplyTemplateAll && activeIndex === masterIndex) {
        setBulkTemplates((prev) => {
          const next = [...prev];
          targetIndices.forEach((idx) => { next[idx] = id; });
          return next;
        });
        if (colors) {
          setBulkAccentColors((prev) => {
            const next = [...prev];
            targetIndices.forEach((idx) => { next[idx] = colors.accent; });
            return next;
          });
          setBulkBgColors((prev) => {
            const next = [...prev];
            targetIndices.forEach((idx) => { next[idx] = colors.bg; });
            return next;
          });
          setBulkTextColors((prev) => {
            const next = [...prev];
            targetIndices.forEach((idx) => { next[idx] = colors.text; });
            return next;
          });
        }
        return;
      }

      setBulkTemplates((prev) => {
        const next = [...prev];
        next[activeIndex] = id;
        return next;
      });
      if (colors) {
        setBulkAccentColors((prev) => { const next = [...prev]; next[activeIndex] = colors.accent; return next; });
        setBulkBgColors((prev) => { const next = [...prev]; next[activeIndex] = colors.bg; return next; });
        setBulkTextColors((prev) => { const next = [...prev]; next[activeIndex] = colors.text; return next; });
      }
    };

    const targetIndicesForTemplate = indexed.map(({ i }) => i);
    const setBulkColor = (kind: "accent" | "bg" | "text", v: string) => {
      if (bulkApplyTemplateAll && activeIndex !== masterIndex) {
        setBulkApplyTemplateAll(false);
        if (kind === "accent") setBulkAccentColors((prev) => { const n = [...prev]; n[activeIndex] = v; return n; });
        if (kind === "bg") setBulkBgColors((prev) => { const n = [...prev]; n[activeIndex] = v; return n; });
        if (kind === "text") setBulkTextColors((prev) => { const n = [...prev]; n[activeIndex] = v; return n; });
        return;
      }
      if (bulkApplyTemplateAll && activeIndex === masterIndex) {
        if (kind === "accent") setBulkAccentColors((prev) => { const n = [...prev]; targetIndicesForTemplate.forEach((idx) => { n[idx] = v; }); return n; });
        if (kind === "bg") setBulkBgColors((prev) => { const n = [...prev]; targetIndicesForTemplate.forEach((idx) => { n[idx] = v; }); return n; });
        if (kind === "text") setBulkTextColors((prev) => { const n = [...prev]; targetIndicesForTemplate.forEach((idx) => { n[idx] = v; }); return n; });
        return;
      }
      if (kind === "accent") setBulkAccentColors((prev) => { const n = [...prev]; n[activeIndex] = v; return n; });
      if (kind === "bg") setBulkBgColors((prev) => { const n = [...prev]; n[activeIndex] = v; return n; });
      if (kind === "text") setBulkTextColors((prev) => { const n = [...prev]; n[activeIndex] = v; return n; });
    };

    const SelectedPreviewComp = TEMPLATE_PREVIEWS[tpl];
    const selectedDesc = TEMPLATE_DESCRIPTIONS[tpl];

    const {
      suggestedTemplates,
      customTemplatesForStyle,
      craftedTemplatesForStyle,
    } = templateBucketsForGenre(genre, templates, readyCustomTemplates, readyCraftedTemplates);
    const sortedBulkSuggestedTemplates = [...suggestedTemplates].sort((a, b) => {
      const rank = (t: TemplateMeta) => (t.new_template ? 0 : t.popular_template ? 1 : 2);
      return rank(a) - rank(b);
    });
    const styleTemplateItems: Array<
      | { type: "builtin"; id: string; data: TemplateMeta }
      | { type: "custom"; id: string; data: CustomTemplateItem }
      | { type: "crafted"; id: string; data: CraftedTemplateItem }
    > = [
      ...sortedBulkSuggestedTemplates.map((t) => ({ type: "builtin" as const, id: t.id, data: t })),
      ...customTemplatesForStyle.map((ct) => ({ type: "custom" as const, id: `custom_${ct.id}`, data: ct })),
      ...craftedTemplatesForStyle.map((ct) => ({ type: "crafted" as const, id: ct.id, data: ct })),
    ];

    return (
      <div className="space-y-5">
        {/* Bulk logo picker (step 2) */}
        <input
          ref={bulkLogoInputRef}
          type="file"
          accept="image/png,image/jpeg,image/webp,image/svg+xml"
          className="hidden"
          onChange={(e) => {
            const f = e.target.files?.[0] || null;
            e.target.value = "";
            if (bulkLogoRowIndex === null) return;
            if (f && f.size > 2 * 1024 * 1024) {
              showError("Logo must be under 2 MB.");
              return;
            }
            const targetIndices = indexed.map(({ i }) => i);
            if (bulkApplyTemplateAll && bulkLogoRowIndex !== masterIndex) {
              setBulkApplyTemplateAll(false);
              setBulkLogoFile((prev) => {
                const n = [...prev];
                n[bulkLogoRowIndex] = f;
                return n;
              });
              setBulkLogoRowIndex(null);
              return;
            }
            if (bulkApplyTemplateAll && bulkLogoRowIndex === masterIndex) {
              setBulkLogoFile((prev) => {
                const n = [...prev];
                targetIndices.forEach((idx) => { n[idx] = f; });
                return n;
              });
              setBulkLogoRowIndex(null);
              return;
            }
            setBulkLogoFile((prev) => {
              const n = [...prev];
              n[bulkLogoRowIndex] = f;
              return n;
            });
            setBulkLogoRowIndex(null);
          }}
        />

        {/* Tabs for each bulk project β€” match Link/Upload/Multi Link tabs */}
        <div className="flex flex-wrap gap-1 mb-2">
          <div className="flex flex-wrap gap-1 p-1 bg-gray-100/60 rounded-xl">
            {indexed.map(({ row, i }, tabIdx) => (
              <button
                key={i}
                type="button"
                onClick={() => setBulkActiveIndex(tabIdx)}
                className={`px-3 py-1.5 rounded-lg text-[11px] font-medium transition-all ${
                  tabIdx === active
                    ? "bg-white text-purple-600 shadow-sm"
                    : "text-gray-400 hover:text-gray-600"
                }`}
                title={row.url.trim() || undefined}
              >
                Video #{tabIdx + 1}
              </button>
            ))}
          </div>
        </div>

        {/* Apply template, colors & logo to all */}
        <div className="flex items-center justify-start ml-1 mb-1">
          <label className="flex items-center gap-2 text-[11px] text-gray-500 cursor-pointer select-none">
            <input
              type="checkbox"
              checked={bulkApplyTemplateAll}
              onChange={(e) => {
                const checked = e.target.checked;
                setBulkApplyTemplateAll(checked);
                if (checked) {
                  setBulkTemplateMasterIndex(activeIndex);
                  applyTemplateToAll();
                }
              }}
              className="w-4 h-4 rounded border-gray-300 text-purple-600 focus:ring-purple-500/30 cursor-pointer accent-purple-600"
            />
            <span className="font-medium">Apply template, colors & logo to all videos</span>
          </label>
        </div>

        {/* Selected template β€” full-width preview (same UI as single) */}
        <div>
          <label className="block text-[11px] font-medium text-gray-400 mb-2 uppercase tracking-wider">
            Selected Template
          </label>
          <div className="rounded-xl overflow-hidden border-2 border-purple-500 shadow-[0_0_0_4px_rgba(124,58,237,0.1)]">
            <div className="relative aspect-video overflow-hidden">
              {selectedCustomBulk ? (
                <CustomPreview theme={selectedCustomBulk.theme} name={selectedCustomBulk.name} previewImageUrl={selectedCustomBulk.preview_image_url} introCode={selectedCustomBulk.intro_code || undefined} outroCode={selectedCustomBulk.outro_code || undefined} contentCodes={selectedCustomBulk.content_codes || undefined} contentArchetypeIds={selectedCustomBulk.content_archetype_ids || undefined} logoUrls={selectedCustomBulk.logo_urls} ogImage={selectedCustomBulk.og_image} thumbnailMode={isMobile} staticThumb={isMobile} key={`selected-bulk-custom-${tpl}-${activeIndex}-${step}`} />
              ) : selectedCraftedBulk && ((selectedCraftedBulk as any).frontend_files || selectedCraftedBulk.preview_file || selectedCraftedBulk.preview_image_url || selectedCraftedBulk.theme) ? (
                <CraftedTemplatePreviewSmart
                  item={selectedCraftedBulk}
                  compileCacheScope={user?.id != null ? String(user.id) : undefined}
                  showLoaderOnEmptyOrError
                  thumbnailMode={isMobile}
                  staticThumb={isMobile}
                  key={`selected-bulk-crafted-${tpl}-${activeIndex}-${step}`}
                />
              ) : tpl.startsWith("crafted_") && craftedTemplatesLoading ? (
                <div className="w-full aspect-video bg-[#1a1a2e] flex items-center justify-center">
                  <span className="w-7 h-7 border-2 border-purple-200/50 border-t-purple-500 rounded-full animate-spin" />
                </div>
              ) : SelectedPreviewComp ? (
                <SelectedPreviewComp thumbnailMode={isMobile} key={`selected-bulk-${tpl}-${activeIndex}-${step}`} />
              ) : (
                <div className="w-full aspect-video bg-gray-100 flex items-center justify-center text-gray-300 text-sm">
                  {selectedDesc?.title ?? tpl}
                </div>
              )}
            </div>
            <div className="px-4 py-2.5 bg-purple-50/80 flex items-center justify-between">
              <div>
                <div className="flex items-center gap-2">
                  <div className="text-sm font-semibold text-gray-800">{selectedCustomBulk ? selectedCustomBulk.name : selectedCraftedBulk ? selectedCraftedBulk.name : (selectedDesc?.title ?? tpl)}</div>
                  {selectedBuiltinNewBulk && <NewTemplateBadge className="shrink-0" />}
                  {selectedCustomBulk && (
                    <span className="px-1.5 py-0.5 rounded text-[9px] font-bold text-white" style={{ backgroundColor: selectedCustomBulk.preview_colors.accent }}>
                      Custom
                    </span>
                  )}
                  {selectedCraftedBulk && (
                    <span className="px-1.5 py-0.5 rounded text-[9px] font-bold text-white bg-amber-500">
                      Designer
                    </span>
                  )}
                </div>
                {selectedCustomBulk ? (
                  <div className="text-[11px] text-gray-400 mt-0.5">Custom template</div>
                ) : selectedCraftedBulk ? (
                  <div className="text-[11px] text-gray-400 mt-0.5">Designer template</div>
                ) : selectedDesc?.subtitle ? (
                  <div className="text-[11px] text-gray-400 mt-0.5">{selectedDesc.subtitle}</div>
                ) : null}
              </div>
              <div className="w-6 h-6 rounded-full bg-purple-600 flex items-center justify-center flex-shrink-0">
                <svg className="w-3.5 h-3.5 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={3} d="M5 13l4 4L19 7" />
                </svg>
              </div>
            </div>
          </div>
        </div>

        {/* Genre filter β€” same `genre` state as single-link step 2 */}
        <div>
          <div className="flex items-center justify-between mb-2">
            <label className="block text-[11px] font-medium text-gray-400 uppercase tracking-wider">
              Genre
            </label>
            <div className="relative">
              <button
                type="button"
                onClick={() => setGenreDropdownOpen((v) => !v)}
                className="flex items-center gap-2 px-3 py-1.5 rounded-xl bg-gray-100/60 hover:bg-gray-200/70 text-[11px] font-medium text-gray-700 transition-all min-w-[140px] justify-between"
              >
                <span>
                  {genre === GENRE_CUSTOM
                    ? "Custom Templates"
                    : genre === GENRE_CRAFTED
                    ? "Designer"
                    : genre === GENRE_NEW
                    ? "New"
                    : genre === GENRE_POPULAR
                    ? "Popular"
                    : genre || "All genres"}
                </span>
                <svg
                  className={`w-3 h-3 text-gray-500 transition-transform ${genreDropdownOpen ? "rotate-180" : ""}`}
                  fill="none"
                  stroke="currentColor"
                  viewBox="0 0 24 24"
                >
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 9l-7 7-7-7" />
                </svg>
              </button>
              {genreDropdownOpen && (
                <>
                  <div className="fixed inset-0 z-10" onClick={() => setGenreDropdownOpen(false)} />
                  <div className="absolute right-0 top-full mt-1 z-20 bg-white rounded-xl shadow-lg border border-gray-200 py-1 min-w-[200px] max-h-[300px] overflow-y-auto">
                    <button
                      type="button"
                      onClick={() => {
                        setGenre("");
                        setGenreDropdownOpen(false);
                      }}
                      className={`w-full text-left px-3 py-1.5 text-[11px] font-medium transition-colors ${
                        genre === "" ? "bg-purple-50 text-purple-600" : "text-gray-700 hover:bg-gray-50"
                      }`}
                    >
                      All genres
                    </button>
                    <div className="my-1 border-t border-gray-100" />
                    <button
                      type="button"
                      onClick={() => {
                        setGenre(GENRE_NEW);
                        setGenreDropdownOpen(false);
                      }}
                      className={`w-full text-left px-3 py-1.5 text-[11px] font-medium transition-colors ${
                        genre === GENRE_NEW ? "bg-purple-50 text-purple-600" : "text-gray-700 hover:bg-gray-50"
                      }`}
                    >
                      ✦ New
                    </button>
                    <button
                      type="button"
                      onClick={() => {
                        setGenre(GENRE_POPULAR);
                        setGenreDropdownOpen(false);
                      }}
                      className={`w-full text-left px-3 py-1.5 text-[11px] font-medium transition-colors ${
                        genre === GENRE_POPULAR ? "bg-amber-50 text-amber-600" : "text-gray-700 hover:bg-gray-50"
                      }`}
                    >
                      Popular
                    </button>
                    <button
                      type="button"
                      onClick={() => {
                        setGenre(GENRE_CUSTOM);
                        setGenreDropdownOpen(false);
                      }}
                      className={`w-full text-left px-3 py-1.5 text-[11px] font-medium transition-colors ${
                        genre === GENRE_CUSTOM ? "bg-purple-50 text-purple-600" : "text-gray-700 hover:bg-gray-50"
                      }`}
                    >
                      Custom Templates
                    </button>
                    <button
                      type="button"
                      onClick={() => {
                        setGenre(GENRE_CRAFTED);
                        setGenreDropdownOpen(false);
                      }}
                      className={`w-full text-left px-3 py-1.5 text-[11px] font-medium transition-colors ${
                        genre === GENRE_CRAFTED ? "bg-purple-50 text-purple-600" : "text-gray-700 hover:bg-gray-50"
                      }`}
                    >
                      Designer Templates
                    </button>
                    {allGenres.length > 0 && <div className="my-1 border-t border-gray-100" />}
                    {allGenres.map((g) => (
                      <button
                        key={g}
                        type="button"
                        onClick={() => {
                          setGenre(g);
                          setGenreDropdownOpen(false);
                        }}
                        className={`w-full text-left px-3 py-1.5 text-[11px] font-medium transition-colors ${
                          genre === g ? "bg-purple-50 text-purple-600" : "text-gray-700 hover:bg-gray-50"
                        }`}
                      >
                        {g}
                      </button>
                    ))}
                  </div>
                </>
              )}
            </div>
          </div>
        </div>
        <p className="text-[10px] text-gray-500 mb-1.5 font-medium">
          {genreTemplateListCaption(genre)}
        </p>
        {/* Template thumbnails β€” filtered by genre; video style below is orthogonal.
            Height matches the single-link grid: 2 columns make the cards taller,
            so mobile needs the extra room. */}
        <div className="border border-gray-200/60 rounded-xl p-2.5 max-h-[260px] sm:max-h-[220px] overflow-y-auto bg-gray-50/40">
          <>
            {/* Same responsive columns as the single-link template grid. */}
            <div className="grid grid-cols-2 sm:grid-cols-3 gap-2">
              <CraftYourTemplateCard
                variant="compact"
                isPro={isPro}
                onClick={() => {
                  setShowGetMoreTemplates(true);
                }}
                onKeyDown={(e) => {
                  if (e.key === "Enter" || e.key === " ") {
                    e.preventDefault();
                    setShowGetMoreTemplates(true);
                  }
                }}
              />
              {styleTemplateItems.map((item) => {
                if (item.type === "custom" || item.type === "crafted") {
                  const ct = item.data;
                  const customId = item.id;
                  const isSelected = tpl === customId;
                  // Mobile: every grid tile renders a static themed placeholder
                  // and never mounts a Player β€” the selected template plays only
                  // in the full-width "Selected Template" preview above. A grid of
                  // live Players exhausts iOS Safari's memory and reloads the tab.
                  const staticThumb = isMobile;
                  return (
                    <div
                      key={customId}
                      onClick={() => applyBulkTemplate(customId)}
                      className={`relative rounded-lg border-2 overflow-hidden cursor-pointer transition-all group ${
                        isSelected
                          ? "border-purple-500 shadow-[0_0_0_3px_rgba(124,58,237,0.1)]"
                          : "border-gray-200/60 hover:border-purple-300/60"
                      }`}
                    >
                      <div className="relative isolate h-[70px] overflow-hidden">
                        <div className="relative z-0 h-full">
                          {item.type === "crafted" ? (
                            <CraftedTemplatePreviewSmart
                              item={ct as any}
                              compileCacheScope={user?.id != null ? String(user.id) : undefined}
                              thumbnailMode
                              showLoaderOnEmptyOrError
                              staticThumb={staticThumb}
                              key={`${customId}-bulk-${activeIndex}`}
                            />
                          ) : (
                            <CustomPreviewLandscape {...({ theme: ct.theme, name: ct.name, introCode: ct.intro_code || undefined, outroCode: ct.outro_code || undefined, contentCodes: ct.content_codes || undefined, contentArchetypeIds: ct.content_archetype_ids || undefined, validLayouts: (ct as any).valid_layouts, frontendFiles: (ct as any).frontend_files, frontendEntryRel: (ct as any).frontend_entry_rel, publicAssetUrls: (ct as any).public_asset_urls, previewImageUrl: ct.preview_image_url, logoUrls: (ct as any).logo_urls, ogImage: (ct as any).og_image, showLoaderOnEmptyOrError: false, thumbnailFrame: 135, thumbnailMode: true, staticThumb } as any)} key={`${customId}-bulk-${activeIndex}`} />
                          )}
                        </div>
                        <div className="absolute top-0.5 left-0.5 z-[5]">
                          {item.type === "custom" ? <CustomTemplateBadge /> : (
                            <span className="pointer-events-none px-1.5 py-0.5 rounded text-[8px] font-bold uppercase tracking-wide text-white bg-amber-500 ring-1 ring-amber-300">
                              Designer
                            </span>
                          )}
                        </div>
                        {isSelected && (
                          <div className="absolute top-1.5 right-1.5 z-20 w-4 h-4 rounded-full bg-purple-600 flex items-center justify-center shadow-md ring-2 ring-white">
                            <svg className="w-2.5 h-2.5 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={3} d="M5 13l4 4L19 7" />
                            </svg>
                          </div>
                        )}
                      </div>
                      <div className={`px-2 py-1 transition-colors ${isSelected ? "bg-purple-50/80" : "bg-white/80"}`}>
                        <div className="text-[10px] font-semibold text-gray-800 truncate">
                          {ct.name}
                        </div>
                      </div>
                    </div>
                  );
                }

                const t = item.data;
                const PreviewComp = TEMPLATE_PREVIEWS[t.id];
                const desc = TEMPLATE_DESCRIPTIONS[t.id];
                const isSelected = tpl === t.id;
                const isNewTemplate = t.new_template === true;
                const isPopularTemplate = t.popular_template === true;
                return (
                  <div
                    key={t.id}
                    onClick={() => applyBulkTemplate(t.id)}
                    className={`relative rounded-lg overflow-hidden cursor-pointer transition-all group ${
                      isSelected
                        ? "border-2 border-purple-500 shadow-[0_0_0_3px_rgba(124,58,237,0.1)]"
                        : isNewTemplate
                        ? "border border-purple-500 shadow-[0_0_0_2px_rgba(124,58,237,0.2)] hover:border-purple-600"
                        : isPopularTemplate
                        ? "border border-amber-400/60 shadow-[0_0_0_2px_rgba(245,158,11,0.15)] hover:border-amber-500"
                        : "border-2 border-gray-200/60 hover:border-purple-300/60"
                    }`}
                  >
                    <div className="relative h-[70px] overflow-hidden">
                      {PreviewComp ? (
                        <PreviewComp key={`${t.id}-bulk-${activeIndex}`} thumbnailMode />
                      ) : (
                        <div className="w-full h-full min-h-[56px] bg-gray-100 flex items-center justify-center text-gray-300 text-[10px]">
                          {desc?.title ?? t.name}
                        </div>
                      )}
                      {isSelected && (
                        <div className="absolute top-1.5 right-1.5 w-4 h-4 rounded-full bg-purple-600 flex items-center justify-center shadow-sm">
                          <svg className="w-2.5 h-2.5 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={3} d="M5 13l4 4L19 7" />
                          </svg>
                        </div>
                      )}
                      {isNewTemplate && (
                        <div className="absolute top-0.5 left-0.5 z-[1]">
                          <NewTemplateBadge />
                        </div>
                      )}
                      {!isNewTemplate && isPopularTemplate && (
                        <div className="absolute top-0.5 left-0.5 z-[1]">
                          <PopularTemplateBadge />
                        </div>
                      )}
                    </div>
                    <div className={`px-2 py-1 transition-colors ${isSelected ? "bg-purple-50/80" : "bg-white/80"}`}>
                      <div className="text-[10px] font-semibold text-gray-800 truncate">
                        {desc?.title ?? t.name}
                      </div>
                    </div>
                  </div>
                );
              })}
              {customTemplatesLoading && (
                <div
                  className="rounded-lg border border-dashed border-gray-200/80 bg-white/70 flex flex-col items-center justify-center gap-2 min-h-[88px] px-2 py-3 text-center"
                  role="status"
                  aria-live="polite"
                >
                  <span className="w-4 h-4 border-2 border-purple-200 border-t-purple-600 rounded-full animate-spin shrink-0" aria-hidden />
                  <p className="text-[10px] text-gray-500 leading-snug">
                    Loading the custom template, please wait.
                  </p>
                </div>
              )}
              {craftedTemplatesLoading && (
                <div
                  className="rounded-lg border border-dashed border-gray-200/80 bg-white/70 flex flex-col items-center justify-center gap-2 min-h-[88px] px-2 py-3 text-center"
                  role="status"
                  aria-live="polite"
                >
                  <span className="w-4 h-4 border-2 border-amber-200 border-t-amber-500 rounded-full animate-spin shrink-0" aria-hidden />
                  <p className="text-[10px] text-gray-500 leading-snug">
                    Loading designer templates, please wait.
                  </p>
                </div>
              )}
            </div>
            {styleTemplateItems.length === 0 && (
              <p className="text-xs text-gray-500 py-3 text-center">
                No templates for this genre. Pick another genre above or add a custom template.
              </p>
            )}
          </>
        </div>

        {/* Video Style β€” orthogonal to genre (same behavior as single-link step 2) */}
        <div className="mt-4">
          <div className="flex items-center justify-between mb-2">
            <label className="block text-[11px] font-medium text-gray-400 uppercase tracking-wider">
              Video Style
            </label>
            {/* Same wrapping/alignment as the single-link Video Style row. */}
            <div className="flex flex-wrap items-center gap-1 p-1 bg-gray-100/60 rounded-xl justify-center">
              {VIDEO_STYLES.map((s) => {
                const isSelected = activeVideoStyle === s.id;
                return (
                  <button
                    key={s.id}
                    type="button"
                    onClick={() => {
                      const targetIndices = indexed.map(({ i }) => i);
                      if (bulkApplyTemplateAll && activeIndex !== masterIndex) {
                        setBulkApplyTemplateAll(false);
                        bulkStyleManuallySet.current[activeIndex] = true;
                        setBulkVideoStyles((prev) => {
                          const next = [...prev];
                          next[activeIndex] = s.id;
                          return next;
                        });
                        return;
                      }
                      if (bulkApplyTemplateAll && activeIndex === masterIndex) {
                        targetIndices.forEach((idx) => { bulkStyleManuallySet.current[idx] = true; });
                        setBulkVideoStyles((prev) => {
                          const next = [...prev];
                          targetIndices.forEach((idx) => { next[idx] = s.id; });
                          return next;
                        });
                        return;
                      }
                      bulkStyleManuallySet.current[activeIndex] = true;
                      setBulkVideoStyles((prev) => {
                        const next = [...prev];
                        next[activeIndex] = s.id;
                        return next;
                      });
                    }}
                    className={`px-3 py-1.5 rounded-lg text-[11px] font-medium transition-all ${
                      isSelected ? "bg-white text-purple-600 shadow-sm" : "text-gray-400 hover:text-gray-600"
                    }`}
                  >
                    {s.label}
                  </button>
                );
              })}
            </div>
          </div>
        </div>

        {/* Video colors (same UI as single) + Logo (bulk-only extra, placed to the right) */}
        <div className="flex flex-col gap-5">
          <div className="min-w-0">
            {/* Same label + swatch alignment as the single-link Video Colors row. */}
            <label className="block text-[11px] font-medium text-gray-400 mb-2 uppercase tracking-wider">
              Video Colors
            </label>
            <div className="flex items-center gap-3 sm:gap-5">
              {[
                { label: "Accent", value: accent, setter: (v: string) => setBulkColor("accent", v) },
                { label: "Background", value: bg, setter: (v: string) => setBulkColor("bg", v) },
                { label: "Text", value: text, setter: (v: string) => setBulkColor("text", v) },
              ].map(({ label, value, setter }) => (
                <label key={label} className="flex items-center gap-2 cursor-pointer group">
                  <span
                    className="w-8 h-8 rounded-full border-2 border-gray-200 group-hover:border-gray-400 transition-all shadow-sm relative overflow-hidden"
                    style={{ backgroundColor: value }}
                  >
                    <input
                      type="color"
                      value={value}
                      onChange={(e) => setter(e.target.value)}
                      className="absolute inset-0 opacity-0 cursor-pointer w-full h-full"
                    />
                  </span>
                  <span className="text-[10px] text-gray-400 font-medium">{label}</span>
                </label>
              ))}
            </div>
          </div>

          <div className="w-full">
            <label className="block text-[11px] font-medium text-gray-400 mb-2 uppercase tracking-wider">
              Logo <span className="text-gray-300 font-normal">(optional Β· max 2 MB)</span>
            </label>
            <div className="flex items-center gap-3">
              <div className="relative mb-4 inline-block">
                <button
                  type="button"
                  onClick={() => { setBulkLogoRowIndex(activeIndex); bulkLogoInputRef.current?.click(); }}
                  className="px-3 py-2 rounded-lg text-xs font-medium bg-gray-50 text-gray-500 hover:bg-gray-100 border border-gray-200/60 transition-all pr-8"
                >
                  {bulkLogoFile[activeIndex] ? bulkLogoFile[activeIndex]!.name : "Choose file"}
                </button>
                {bulkLogoFile[activeIndex] && (
                  <button
                    type="button"
                    onClick={(e) => {
                      e.stopPropagation();
                      const targetIndices = indexed.map(({ i }) => i);
                      if (bulkApplyTemplateAll && activeIndex !== masterIndex) {
                        setBulkApplyTemplateAll(false);
                        setBulkLogoFile((prev) => { const n = [...prev]; n[activeIndex] = null; return n; });
                        return;
                      }
                      if (bulkApplyTemplateAll && activeIndex === masterIndex) {
                        setBulkLogoFile((prev) => {
                          const n = [...prev];
                          targetIndices.forEach((idx) => { n[idx] = null; });
                          return n;
                        });
                        return;
                      }
                      setBulkLogoFile((prev) => { const n = [...prev]; n[activeIndex] = null; return n; });
                    }}
                    className="absolute top-0.5 right-0.5 w-6 h-6 rounded-full border border-purple-500/80 text-purple-600 hover:bg-purple-600 hover:text-white hover:border-purple-600 flex items-center justify-center transition-colors"
                    title="Remove logo"
                  >
                    <svg className="w-3 h-3" fill="none" stroke="currentColor" strokeWidth={2.5} viewBox="0 0 24 24">
                      <path strokeLinecap="round" strokeLinejoin="round" d="M6 18L18 6M6 6l12 12" />
                    </svg>
                  </button>
                )}
              </div>
            </div>
            {bulkLogoFile[activeIndex] && (
              <div className="mt-2">
                <label className="block text-[10px] text-gray-400 mb-1">Position</label>
                <div className="grid grid-cols-2 sm:grid-cols-4 gap-1.5">
                  {([
                    { value: "top_left", label: "Top Left" },
                    { value: "top_right", label: "Top Right" },
                    { value: "bottom_left", label: "Bottom Left" },
                    { value: "bottom_right", label: "Bottom Right" },
                  ] as const).map((pos) => (
                    <button
                      key={pos.value}
                      type="button"
                      onClick={() => {
                        const targetIndices = indexed.map(({ i }) => i);
                        if (bulkApplyTemplateAll && activeIndex !== masterIndex) {
                          setBulkApplyTemplateAll(false);
                          setBulkLogoPosition((prev) => { const n = [...prev]; n[activeIndex] = pos.value; return n; });
                          return;
                        }
                        if (bulkApplyTemplateAll && activeIndex === masterIndex) {
                          setBulkLogoPosition((prev) => {
                            const n = [...prev];
                            targetIndices.forEach((idx) => { n[idx] = pos.value; });
                            return n;
                          });
                          return;
                        }
                        setBulkLogoPosition((prev) => { const n = [...prev]; n[activeIndex] = pos.value; return n; });
                      }}
                      className={`px-2 py-1 rounded text-[10px] font-medium transition-all ${
                        (bulkLogoPosition[activeIndex] ?? "bottom_right") === pos.value
                          ? "bg-purple-600 text-white"
                          : "bg-gray-50 text-gray-400 hover:bg-gray-100 border border-gray-200/60"
                      }`}
                    >
                      {pos.label}
                    </button>
                  ))}
                </div>
                <div className="mt-2.5 mb-3.5">
                  <label className="block text-[10px] text-gray-500 mb-1">
                    Opacity <span className="text-gray-500">{Math.round((bulkLogoOpacity[activeIndex] ?? 0.9) * 100)}%</span>
                  </label>
                  <input
                    type="range"
                    min={10}
                    max={100}
                    step={5}
                    value={Math.round((bulkLogoOpacity[activeIndex] ?? 0.9) * 100)}
                    onChange={(e) => {
                      const val = parseInt(e.target.value, 10) / 100;
                      const targetIndices = indexed.map(({ i }) => i);
                      if (bulkApplyTemplateAll && activeIndex !== masterIndex) {
                        setBulkApplyTemplateAll(false);
                        setBulkLogoOpacity((prev) => { const n = [...prev]; n[activeIndex] = val; return n; });
                        return;
                      }
                      if (bulkApplyTemplateAll && activeIndex === masterIndex) {
                        setBulkLogoOpacity((prev) => {
                          const n = [...prev];
                          targetIndices.forEach((idx) => { n[idx] = val; });
                          return n;
                        });
                        return;
                      }
                      setBulkLogoOpacity((prev) => { const n = [...prev]; n[activeIndex] = val; return n; });
                    }}
                    className="w-full h-1 bg-gray-300 rounded-full appearance-none cursor-pointer accent-purple-600"
                  />
                </div>
              </div>
            )}
          </div>
        </div>

        <div className="flex flex-col sm:flex-row gap-2 pt-1">
          <button
            type="button"
            onClick={goBack}
            className="w-full sm:w-auto px-5 py-3 text-sm font-medium text-gray-500 bg-gray-50 hover:bg-gray-100 rounded-xl transition-colors border border-gray-200/60"
          >
            Back
          </button>
          <button
            type="button"
            onClick={goNext}
            className="w-full sm:flex-1 py-3 bg-purple-600 hover:bg-purple-700 text-white text-sm font-medium rounded-xl transition-colors flex items-center justify-center gap-2"
          >
            Go to step 3
            <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 5l7 7-7 7" />
            </svg>
          </button>
        </div>
      </div>
    );
  })();

  // ─── Step 3: Voice (last step) β€” audio playlist style ─────────
  const voiceOptions = [
    { gender: "female" as const, accent: "american" as const, key: "female_american" },
    { gender: "female" as const, accent: "british" as const, key: "female_british" },
    { gender: "male" as const, accent: "american" as const, key: "male_american" },
    { gender: "male" as const, accent: "british" as const, key: "male_british" },
  ];

  const getPlaybackUrl = (key: string): string | null => {
    if (!VOICE_PREVIEW_KEYS.includes(key)) return null;
    const base = BACKEND_URL ? `${BACKEND_URL}/api` : "/api";
    return `${base}/voices/preview-audio?key=${encodeURIComponent(key)}`;
  };

  const FALLBACK_VOICE_NAMES: Record<string, string> = {
    female_american: "Rachel",
    female_british: "Alice",
    male_american: "Bill",
    male_british: "Daniel",
  };
  const FALLBACK_VOICE_DESCS: Record<string, string> = {
    female_american: "Warm & confident, clear narration",
    female_british: "Soft & polished, refined tone",
    male_american: "Friendly & articulate, conversational",
    male_british: "Calm & authoritative, smooth delivery",
  };

  const step3Voice = (
    <div className="space-y-5">
      <div className="flex items-center gap-2 px-3 py-2.5 rounded-xl bg-purple-50/60 border border-purple-200/50">
        <svg className="w-4 h-4 text-purple-400 shrink-0" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
          <path strokeLinecap="round" strokeLinejoin="round" d="M3 5h12M9 3v2m1.048 9.5A18.022 18.022 0 016.412 9m6.088 9h7M11 21l5-10 5 10M12.751 5C11.783 10.77 8.07 15.61 3 18.129" />
        </svg>
        <p className="text-[11px] text-purple-600 leading-relaxed">
          Choose narration language. Keep <span className="font-semibold">Auto</span> to detect from content.
        </p>
      </div>
      <div className="space-y-1.5">
        <label className="block text-[11px] font-medium text-gray-400 uppercase tracking-wider">
          Language
        </label>
        {renderLanguageDropdown(contentLanguage, setContentLanguage)}
        <p className="text-[11px] text-gray-500">Language of the video content</p>
      </div>
      {/* No voiceover: label above the pill, description + checkbox inside it
          (mirrors the stock-footage pill in step 1). Stock footage moved to
          step 1 so the visual choice sits with format/length. */}
      <div>
        <label className="flex items-center gap-2.5 cursor-pointer select-none p-3 rounded-xl bg-gray-50/60 border border-gray-200/60 hover:border-gray-300/60 transition-all">
          <input
            type="checkbox"
            checked={voiceGender === "none"}
            onChange={(e) => {
              const noVoice = e.target.checked;
              if (noVoice) {
                setVoiceGender("none");
                return;
              }
              const id = customVoiceId.trim();
              const saved = id ? myVoicesList.find((v) => v.voice_id === id) : undefined;
              setVoiceGender(normalizeVoiceGender(saved?.gender) ?? "female");
              const a = normalizeVoiceAccent(saved?.accent);
              if (a) setVoiceAccent(a);
            }}
            className="w-4 h-4 shrink-0 rounded border-gray-300 text-purple-600 focus:ring-purple-500/30 cursor-pointer accent-purple-600"
          />
          <span className="text-sm font-medium text-gray-700 min-w-0">No voiceover</span>
        </label>
      </div>

      {/* Voices from user's saved list + premium teasers for free users */}
      <div>
        <div className="flex items-center justify-between mb-3">
          <label className="block text-[11px] font-medium text-gray-400 uppercase tracking-wider">
            {voicePanelTab === "advanced" && isPro
              ? "Advanced Options"
              : voicePanelTab === "bgm"
                ? "Music β€” Play to preview"
                : "Voice β€” Play to preview"}
          </label>
          <div className="flex gap-1 p-1 bg-gray-100/60 rounded-xl shrink-0">
            <button
              type="button"
              onClick={() => setVoicePanelTab("voice")}
              className={`whitespace-nowrap px-3 py-1 rounded-lg text-[11px] font-medium transition-all ${
                voicePanelTab === "voice"
                  ? "bg-white text-purple-600 shadow-sm"
                  : "text-gray-400 hover:text-gray-600"
              }`}
            >
              Voice
            </button>
            <button
              type="button"
              onClick={() => {
                setVoicePanelTab("bgm");
              }}
              className={`flex items-center gap-1.5 whitespace-nowrap px-3 py-1 rounded-lg text-[11px] font-medium transition-all ${
                voicePanelTab === "bgm"
                  ? "bg-white text-purple-600 shadow-sm"
                  : "text-gray-400 hover:text-gray-600"
              }`}
            >
              Music
            </button>
            <button
              type="button"
              onClick={() => {
                if (!isPro) {
                  setShowUpgrade(true);
                  return;
                }
                setVoicePanelTab("advanced");
              }}
              className={`flex items-center gap-1.5 whitespace-nowrap px-3 py-1 rounded-lg text-[11px] font-medium transition-all ${
                voicePanelTab === "advanced" && isPro
                  ? "bg-white text-purple-600 shadow-sm"
                  : "text-gray-400 hover:text-gray-600"
              }`}
            >
              Advanced Options
              <span className="inline-flex h-4 items-center justify-center rounded-full bg-purple-600 px-1.5 text-[9px] font-semibold text-white">
                Premium
              </span>
            </button>
          </div>
        </div>
        {voicePanelTab === "voice" && (
        <div className={`space-y-2 max-h-[320px] overflow-y-auto ${voiceGender === "none" ? "opacity-60 pointer-events-none" : ""}`}>
          <CraftYourVoiceCard
            isPro={isPro}
            onClick={openStep3CustomVoiceCreator}
            onKeyDown={(e) => {
              if (e.key === "Enter" || e.key === " ") {
                e.preventDefault();
                openStep3CustomVoiceCreator();
              }
            }}
          />
          {myVoicesLoading ? (
            <div className="flex items-center gap-2 py-3 px-3 rounded-xl bg-gray-50/60 border border-gray-200/60">
              <span className="w-4 h-4 border-2 border-purple-200 border-t-purple-600 rounded-full animate-spin shrink-0" />
              <p className="text-[11px] text-gray-500">Loading your voices…</p>
            </div>
          ) : (
            <>
              {myVoicesList.map((saved) => {
                const isSelected = customVoiceId === saved.voice_id;
                const canSelect = isPro || (saved.plan !== "paid" && !saved.custom_voice_id);
                const hasPreview = !!saved.preview_url;
                const myKey = `my_${saved.voice_id}`;
                const isPlaying = playingKey === myKey;
                const { displayName } = getMyVoiceDisplayName(saved.name);
                const isCustom = !!saved.custom_voice_id;
                return (
                  <VoiceItem
                    key={`saved_${saved.id}`}
                    name={displayName}
                    subtitle={subtitleForSavedVoice(saved)}
                    hasPreview={hasPreview}
                    isPlaying={isPlaying}
                    onPlay={() => playMyVoice(saved)}
                    disabled={false}
                    isSelected={isSelected}
                    onClick={() => {
                      if (!canSelect) {
                        setShowUpgrade(true);
                        return;
                      }
                      const nextId = isSelected ? "" : saved.voice_id;
                      setCustomVoiceId(nextId);
                      if (!isSelected) {
                        const g = normalizeVoiceGender(saved.gender);
                        const a = normalizeVoiceAccent(saved.accent);
                        if (g) setVoiceGender(g);
                        if (a) setVoiceAccent(a);
                      }
                    }}
                    badge={
                      isCustom ? (
                        <span className="inline-flex h-5 min-w-[4.5rem] items-center justify-center rounded-full bg-purple-600 px-2.5 py-0.5 text-[10px] font-semibold text-white">Custom</span>
                      ) : saved.plan === "paid" ? (
                        <span className="inline-flex h-5 min-w-[4.5rem] items-center justify-center rounded-full bg-purple-600 px-2.5 py-0.5 text-[10px] font-semibold text-white">Premium</span>
                      ) : null
                    }
                    actions={
                      isSelected ? (
                        <div className="w-5 h-5 rounded-full bg-purple-600 flex items-center justify-center flex-shrink-0">
                          <svg className="w-3 h-3 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={3} d="M5 13l4 4L19 7" />
                          </svg>
                        </div>
                      ) : null
                    }
                  />
                );
              })}
              {!isPro && premiumTeaserVoices.map((voice) => {
                const key = `premium_${voice.voice_id}`;
                const isPlaying = playingKey === key;
                const labels = voice.labels ?? {};
                const subtitle = formatVoiceSubtitle(labels.gender, labels.accent, voice.description ?? "Premium voice");
                return (
                  <VoiceItem
                    key={key}
                    name={voice.name}
                    subtitle={subtitle}
                    hasPreview={!!voice.preview_url}
                    isPlaying={isPlaying}
                    onPlay={() => playPremiumTeaser(voice)}
                    disabled={false}
                    isSelected={false}
                    onClick={() => setShowUpgrade(true)}
                    badge={
                      <span className="inline-flex h-5 min-w-[4.5rem] items-center justify-center rounded-full bg-purple-600 px-2.5 py-0.5 text-[10px] font-semibold text-white">Premium</span>
                    }
                  />
                );
              })}
            </>
          )}
        </div>
        )}
        {voicePanelTab === "voice" && !myVoicesLoading && myVoicesList.length === 0 && (
          <p className="text-[11px] text-gray-500 mt-2">
            No voices saved. Add voices in the Voices tab to use them here.{" "}
            {!isPro && (
              <button type="button" onClick={() => setShowUpgrade(true)} className="text-purple-600 hover:underline">
                Upgrade to add video
              </button>
            )}
          </p>
        )}
        {/* Advanced Options tab content β€” voice tuning sliders (paid) */}
        {voicePanelTab === "advanced" && isPro && voiceGender !== "none" && (
          <AdvancedVoiceOptions
            value={{ enabled: expressiveEnabled, stability: voiceStability, speed: voiceSpeed, emotion: voiceEmotion, style: voiceStyle }}
            onChange={(t) => { setExpressiveEnabled(t.enabled); setVoiceStability(t.stability); setVoiceSpeed(t.speed); setVoiceEmotion(t.emotion); setVoiceStyle(t.style); }}
            voiceGender={voiceGender}
            voiceAccent={voiceAccent}
            customVoiceId={customVoiceId}
          />
        )}
      </div>

      {/* ─── Music tab content (Premium; optional) ─────── */}
      {voicePanelTab === "bgm" && bgmTracks.length > 0 && (
        <div className="space-y-2">
          <p className="text-[11px] text-gray-400 mb-1">Ambient music behind your narration β€” optional.</p>

          {/* Volume β€” shown once a track is picked; applies to the whole project */}
          {selectedBgmTrackId && (
            <div className="mb-3">
              <div className="flex items-center justify-between mb-1">
                <span className="text-[11px] font-medium text-gray-600">Music volume</span>
                <span className="text-[11px] text-gray-400 tabular-nums">{Math.round(selectedBgmVolume * 100)}%</span>
              </div>
              <input
                type="range"
                min={0}
                max={100}
                step={1}
                value={Math.round(selectedBgmVolume * 100)}
                onChange={(e) => {
                  const v = Number(e.target.value) / 100;
                  setSelectedBgmVolume(v);
                  if (bgmAudioRef.current) bgmAudioRef.current.volume = Math.max(0, Math.min(1, v));
                }}
                className="w-full accent-purple-600 cursor-pointer"
              />
              <p className="text-[10px] text-gray-400 mt-0.5">Sets the volume for the whole video. After it's generated, you can fine-tune the music volume per scene in the <span className="font-medium text-gray-500">Audio</span> tab.</p>
            </div>
          )}

          <div className="space-y-1.5 max-h-[320px] overflow-y-auto">
            {/* None option */}
            <button
              type="button"
              onClick={() => {
                setSelectedBgmTrackId(null);
                bgmAudioRef.current?.pause();
                setBgmPlayingId(null);
              }}
              className={`w-full flex items-center gap-3 p-3 rounded-xl border transition-all text-left ${
                !selectedBgmTrackId
                  ? "border-purple-400 bg-purple-50/60"
                  : "border-gray-200/60 bg-gray-50/40 hover:border-gray-300/60"
              }`}
            >
              <div className="w-8 h-8 rounded-full bg-gray-200 flex items-center justify-center shrink-0">
                <svg className="w-4 h-4 text-gray-400" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
                  <path strokeLinecap="round" strokeLinejoin="round" d="M18.364 18.364A9 9 0 005.636 5.636m12.728 12.728A9 9 0 015.636 5.636m12.728 12.728L5.636 5.636" />
                </svg>
              </div>
              <div className="min-w-0 flex-1">
                <span className="text-sm font-medium text-gray-700">None</span>
                <p className="text-[11px] text-gray-400">No background music</p>
              </div>
              {!selectedBgmTrackId && (
                <div className="w-5 h-5 rounded-full bg-purple-600 flex items-center justify-center shrink-0">
                  <svg className="w-3 h-3 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={3} d="M5 13l4 4L19 7" />
                  </svg>
                </div>
              )}
            </button>

            {bgmTracks.map((track) => {
              const isSelected = selectedBgmTrackId === track.track_id;
              const isPlaying = bgmPlayingId === track.track_id;
              return (
                <div
                  key={track.track_id}
                  onClick={() => setSelectedBgmTrackId(isSelected ? null : track.track_id)}
                  className={`flex items-center gap-3 p-3 rounded-xl border transition-all cursor-pointer ${
                    isSelected
                      ? "border-purple-400 bg-purple-50/60"
                      : "border-gray-200/60 bg-gray-50/40 hover:border-gray-300/60"
                  }`}
                >
                  {/* Play/pause button */}
                  <button
                    type="button"
                    onClick={(e) => {
                      e.stopPropagation();
                      if (isPlaying) {
                        bgmAudioRef.current?.pause();
                        setBgmPlayingId(null);
                      } else {
                        if (bgmAudioRef.current) {
                          bgmAudioRef.current.pause();
                        }
                        const audio = new Audio(track.r2_url);
                        audio.volume = Math.max(0, Math.min(1, selectedBgmVolume));
                        audio.onended = () => setBgmPlayingId(null);
                        audio.play().catch(() => {});
                        bgmAudioRef.current = audio;
                        setBgmPlayingId(track.track_id);
                      }
                    }}
                    className={`w-8 h-8 rounded-full flex items-center justify-center shrink-0 transition-colors ${
                      isPlaying
                        ? "bg-purple-600 text-white"
                        : "bg-gray-200 text-gray-500 hover:bg-gray-300"
                    }`}
                  >
                    {isPlaying ? (
                      <svg className="w-3.5 h-3.5" fill="currentColor" viewBox="0 0 24 24">
                        <rect x="6" y="4" width="4" height="16" rx="1" />
                        <rect x="14" y="4" width="4" height="16" rx="1" />
                      </svg>
                    ) : (
                      <svg className="w-3.5 h-3.5 ml-0.5" fill="currentColor" viewBox="0 0 24 24">
                        <path d="M8 5v14l11-7z" />
                      </svg>
                    )}
                  </button>

                  <div className="min-w-0 flex-1">
                    <span className="text-sm font-medium text-gray-700">{track.display_name}</span>
                    <p className="text-[11px] text-gray-400">{track.mood}</p>
                  </div>

                  {isSelected && (
                    <div className="w-5 h-5 rounded-full bg-purple-600 flex items-center justify-center shrink-0">
                      <svg className="w-3 h-3 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={3} d="M5 13l4 4L19 7" />
                      </svg>
                    </div>
                  )}
                </div>
              );
            })}
          </div>
        </div>
      )}

      <div className="flex gap-2 pt-1">
        <button
          type="button"
          onClick={goBack}
          className="px-5 py-3 text-sm font-medium text-gray-500 bg-gray-50 hover:bg-gray-100 rounded-xl transition-colors border border-gray-200/60"
        >
          Back
        </button>
        <button
          ref={submitButtonRef}
          type="submit"
          data-action="new-project"
          disabled={loading}
          className="flex-1 py-3 bg-purple-600 hover:bg-purple-700 disabled:bg-purple-400 disabled:text-white text-white text-sm font-medium rounded-xl transition-colors flex items-center justify-center gap-2"
        >
          {loading ? (
            <>
              <span className="w-3.5 h-3.5 border-2 border-white/30 border-t-white rounded-full animate-spin" />
              Generating
            </>
          ) : (
            "Generate Video"
          )}
        </button>
      </div>
    </div>
  );

  // ─── Step 3 bulk: voice per project (tabbed) ───────────────────
  const step3BulkVoice = (() => {
    const indexed = bulkRows
      .map((row, i) => ({ row, i }))
      .filter(({ row }) => row.url.trim());

    if (indexed.length === 0) {
      return (
        <div className="space-y-5">
          <p className="text-sm text-gray-500">Please go back to step 1 to continue again.</p>
          <div className="flex gap-2 pt-1">
            <button
              type="button"
              onClick={goBack}
              className="px-5 py-3 text-sm font-medium text-gray-500 bg-gray-50 hover:bg-gray-100 rounded-xl transition-colors border border-gray-200/60"
            >
              Back
            </button>
          </div>
        </div>
      );
    }

    const active = Math.min(bulkActiveIndex, indexed.length - 1);
    const activeIndex = indexed[active].i;
    const masterIndex =
      indexed.find(({ i }) => i === bulkVoiceMasterIndex)?.i ??
      indexed[0].i;
    const rowVoiceGender = bulkVoiceGender[activeIndex] ?? "female";
    const rowVoiceAccent = bulkVoiceAccent[activeIndex] ?? "american";
    const rowVoiceStability = bulkVoiceStability[activeIndex] ?? VOICE_STABILITY_DEFAULT;
    const rowVoiceSpeed = bulkVoiceSpeed[activeIndex] ?? VOICE_SPEED_DEFAULT;
    const rowVoiceEmotion = bulkVoiceEmotion[activeIndex] ?? "";
    const rowVoiceStyle = bulkVoiceStyle[activeIndex] ?? VOICE_STYLE_DEFAULT;
    const rowCustomVoiceId = bulkCustomVoiceId[activeIndex] ?? "";
    const rowContentLanguage = bulkContentLanguage[activeIndex] ?? "auto";
    const rowVideoLength = bulkVideoLength[activeIndex] ?? "short";

    const applyVoiceToAll = () => {
      const targetIndices = indexed.map(({ i }) => i);
      setBulkVoiceGender((prev) => {
        const next = [...prev];
        targetIndices.forEach((idx) => {
          next[idx] = rowVoiceGender;
        });
        return next;
      });
      setBulkVoiceAccent((prev) => {
        const next = [...prev];
        targetIndices.forEach((idx) => {
          next[idx] = rowVoiceAccent;
        });
        return next;
      });
      setBulkVoiceStability((prev) => {
        const next = [...prev];
        targetIndices.forEach((idx) => {
          next[idx] = rowVoiceStability;
        });
        return next;
      });
      setBulkVoiceSpeed((prev) => {
        const next = [...prev];
        targetIndices.forEach((idx) => {
          next[idx] = rowVoiceSpeed;
        });
        return next;
      });
      setBulkVoiceEmotion((prev) => {
        const next = [...prev];
        targetIndices.forEach((idx) => {
          next[idx] = rowVoiceEmotion;
        });
        return next;
      });
      setBulkVoiceStyle((prev) => {
        const next = [...prev];
        targetIndices.forEach((idx) => {
          next[idx] = rowVoiceStyle;
        });
        return next;
      });
      setBulkCustomVoiceId((prev) => {
        const next = [...prev];
        targetIndices.forEach((idx) => {
          next[idx] = rowCustomVoiceId;
        });
        return next;
      });
      setBulkContentLanguage((prev) => {
        const next = [...prev];
        targetIndices.forEach((idx) => {
          next[idx] = rowContentLanguage;
        });
        return next;
      });
      setBulkVideoLength((prev) => {
        const next = [...prev];
        targetIndices.forEach((idx) => {
          next[idx] = rowVideoLength;
        });
        return next;
      });
    };

    return (
      <div className="space-y-5">
        {/* Tabs for each bulk project β€” match Link/Upload/Multi Link tabs */}
        <div className="flex flex-wrap gap-1 pb-2 mb-2">
          <div className="flex flex-wrap gap-1 p-1 bg-gray-100/60 rounded-xl">
            {indexed.map(({ row, i }, tabIdx) => (
              <button
                key={i}
                type="button"
                onClick={() => setBulkActiveIndex(tabIdx)}
                className={`px-3 py-1.5 rounded-lg text-[11px] font-medium transition-all ${
                  tabIdx === active
                    ? "bg-white text-purple-600 shadow-sm"
                    : "text-gray-400 hover:text-gray-600"
                }`}
                title={row.url.trim() || undefined}
              >
                Video #{tabIdx + 1}
              </button>
            ))}
          </div>
        </div>

        {/* Apply voice selection to all */}
        <div className="flex items-center justify-start mb-2 ml-1">
          <label className="flex items-center gap-2 text-[11px] text-gray-500 cursor-pointer select-none">
            <input
              type="checkbox"
              checked={bulkApplyVoiceAll}
              onChange={(e) => {
                const checked = e.target.checked;
                setBulkApplyVoiceAll(checked);
                if (checked) {
                  // Use the currently active video as the master when (re)enabling apply-to-all.
                  setBulkVoiceMasterIndex(activeIndex);
                  applyVoiceToAll();
                }
              }}
              className="w-4 h-4 rounded border-gray-300 text-purple-600 focus:ring-purple-500/30 cursor-pointer accent-purple-600"
            />
            <span className="font-medium">Apply settings to all videos</span>
          </label>
        </div>

        <div className="space-y-1.5">
          <label className="block text-[11px] font-medium text-gray-400 uppercase tracking-wider">
            Language
          </label>
          {renderLanguageDropdown(rowContentLanguage, (value) => {
            const targetIndices = indexed.map(({ i }) => i);
            if (bulkApplyVoiceAll && activeIndex === masterIndex) {
              setBulkContentLanguage((prev) => {
                const next = [...prev];
                targetIndices.forEach((idx) => {
                  next[idx] = value;
                });
                return next;
              });
            } else {
              setBulkApplyVoiceAll(false);
              setBulkContentLanguage((prev) => {
                const next = [...prev];
                next[activeIndex] = value;
                return next;
              });
            }
          })}
          <p className="text-[11px] text-gray-500">Language of the video content</p>
        </div>

        {/* No voiceover: label above the pill, description + checkbox inside it
            (mirrors step 1). Edits this row, or all rows when the apply-to-all
            voice sync is on. */}
        <div>
        <label className="flex items-center gap-2.5 cursor-pointer select-none p-3 rounded-xl bg-gray-50/60 border border-gray-200/60 hover:border-gray-300/60 transition-all">
          <input
            type="checkbox"
            checked={rowVoiceGender === "none"}
            onChange={(e) => {
              const noVoice = e.target.checked;
              const targetIndices = indexed.map(({ i }) => i);

              const applyNoVoiceoverToggle = (indices: number[]) => {
                if (noVoice) {
                  setBulkVoiceGender((prev) => {
                    const next = [...prev];
                    indices.forEach((idx) => {
                      next[idx] = "none";
                    });
                    return next;
                  });
                  return;
                }
                setBulkVoiceGender((prev) => {
                  const next = [...prev];
                  indices.forEach((idx) => {
                    const vid = (bulkCustomVoiceId[idx] ?? "").trim();
                    const saved = vid ? myVoicesList.find((v) => v.voice_id === vid) : undefined;
                    next[idx] = normalizeVoiceGender(saved?.gender) ?? "female";
                  });
                  return next;
                });
                setBulkVoiceAccent((prev) => {
                  const next = [...prev];
                  indices.forEach((idx) => {
                    const vid = (bulkCustomVoiceId[idx] ?? "").trim();
                    const saved = vid ? myVoicesList.find((v) => v.voice_id === vid) : undefined;
                    const a = normalizeVoiceAccent(saved?.accent);
                    if (a) next[idx] = a;
                  });
                  return next;
                });
              };

              if (bulkApplyVoiceAll && activeIndex !== masterIndex) {
                // Editing a non-master video breaks the global sync.
                setBulkApplyVoiceAll(false);
                applyNoVoiceoverToggle([activeIndex]);
                return;
              }

              if (bulkApplyVoiceAll && activeIndex === masterIndex) {
                // Master row change: keep all videos in sync.
                applyNoVoiceoverToggle(targetIndices);
                return;
              }

              // No global sync: only update this row.
              applyNoVoiceoverToggle([activeIndex]);
            }}
            className="w-4 h-4 shrink-0 rounded border-gray-300 text-purple-600 focus:ring-purple-500/30 cursor-pointer accent-purple-600"
          />
          <span className="text-sm font-medium text-gray-700 min-w-0">No voiceover</span>
        </label>
        </div>

        <div className={rowVoiceGender === "none" ? "opacity-60 pointer-events-none" : ""}>
          <div className="flex items-center justify-between mb-3">
            <label className="block text-[11px] font-medium text-gray-400 uppercase tracking-wider">
              {showAdvancedOptions && isPro ? "Advanced Options" : "Voice β€” select and play to preview"}
            </label>
            <div className="flex gap-1 p-1 bg-gray-100/60 rounded-xl">
              <button
                type="button"
                onClick={() => setShowAdvancedOptions(false)}
                className={`whitespace-nowrap px-3 py-1 rounded-lg text-[11px] font-medium transition-all ${
                  !(showAdvancedOptions && isPro)
                    ? "bg-white text-purple-600 shadow-sm"
                    : "text-gray-400 hover:text-gray-600"
                }`}
              >
                Voice
              </button>
              <button
                type="button"
                onClick={() => {
                  if (!isPro) {
                    setShowUpgrade(true);
                    return;
                  }
                  setShowAdvancedOptions(true);
                }}
                className={`flex items-center gap-1.5 px-3 py-1 rounded-lg text-[11px] font-medium transition-all ${
                  showAdvancedOptions && isPro
                    ? "bg-white text-purple-600 shadow-sm"
                    : "text-gray-400 hover:text-gray-600"
                }`}
              >
                Advanced Options
                <span className="inline-flex h-4 items-center justify-center rounded-full bg-purple-600 px-1.5 text-[9px] font-semibold text-white">
                  Premium
                </span>
              </button>
            </div>
          </div>
          {!(showAdvancedOptions && isPro) && (
          <div className="space-y-2 max-h-[320px] overflow-y-auto">
            {myVoicesLoading ? (
              <div className="flex items-center gap-2 py-3 px-3 rounded-xl bg-gray-50/60 border border-gray-200/60">
                <span className="w-4 h-4 border-2 border-purple-200 border-t-purple-600 rounded-full animate-spin shrink-0" />
                <p className="text-[11px] text-gray-500">Loading your voices…</p>
              </div>
            ) : (
              <>
                {myVoicesList.map((saved) => {
                  const isSelectedBulk = rowCustomVoiceId === saved.voice_id;
                  const canSelectBulk = isPro || (saved.plan !== "paid" && !saved.custom_voice_id);
                  const hasPreview = !!saved.preview_url;
                  const myKey = `my_${saved.voice_id}`;
                  const isPlaying = playingKey === myKey;
                  const { displayName } = getMyVoiceDisplayName(saved.name);
                  const isCustom = !!saved.custom_voice_id;
                  return (
                    <VoiceItem
                      key={`saved_${saved.id}`}
                      name={displayName}
                      subtitle={subtitleForSavedVoice(saved)}
                      hasPreview={hasPreview}
                      isPlaying={isPlaying}
                      onPlay={() => playMyVoice(saved)}
                      disabled={false}
                      isSelected={isSelectedBulk}
                      onClick={() => {
                        if (!canSelectBulk) {
                          setShowUpgrade(true);
                          return;
                        }
                        const value = isSelectedBulk ? "" : saved.voice_id;
                        const g = normalizeVoiceGender(saved.gender);
                        const a = normalizeVoiceAccent(saved.accent);
                        const targetIndices = indexed.map(({ i }) => i);
                        if (bulkApplyVoiceAll && activeIndex === masterIndex) {
                          if (g) {
                            setBulkVoiceGender((prev) => {
                              const next = [...prev];
                              targetIndices.forEach((idx) => { next[idx] = g; });
                              return next;
                            });
                          }
                          if (a) {
                            setBulkVoiceAccent((prev) => {
                              const next = [...prev];
                              targetIndices.forEach((idx) => { next[idx] = a; });
                              return next;
                            });
                          }
                          setBulkCustomVoiceId((prev) => {
                            const next = [...prev];
                            targetIndices.forEach((idx) => { next[idx] = value; });
                            return next;
                          });
                        } else {
                          setBulkApplyVoiceAll(false);
                          if (g) {
                            setBulkVoiceGender((prev) => {
                              const next = [...prev];
                              next[activeIndex] = g;
                              return next;
                            });
                          }
                          if (a) {
                            setBulkVoiceAccent((prev) => {
                              const next = [...prev];
                              next[activeIndex] = a;
                              return next;
                            });
                          }
                          setBulkCustomVoiceId((prev) => {
                            const next = [...prev];
                            next[activeIndex] = value;
                            return next;
                          });
                        }
                      }}
                      badge={
                        isCustom ? (
                          <span className="inline-flex h-5 min-w-[4.5rem] items-center justify-center rounded-full bg-purple-600 px-2.5 py-0.5 text-[10px] font-semibold text-white">Custom</span>
                        ) : saved.plan === "paid" ? (
                          <span className="inline-flex h-5 min-w-[4.5rem] items-center justify-center rounded-full bg-purple-600 px-2.5 py-0.5 text-[10px] font-semibold text-white">Premium</span>
                        ) : null
                      }
                      actions={
                        isSelectedBulk ? (
                          <div className="w-5 h-5 rounded-full bg-purple-600 flex items-center justify-center flex-shrink-0">
                            <svg className="w-3 h-3 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={3} d="M5 13l4 4L19 7" />
                            </svg>
                          </div>
                        ) : null
                      }
                    />
                  );
                })}
                {!isPro && premiumTeaserVoices.map((voice) => {
                  const key = `premium_${voice.voice_id}`;
                  const isPlaying = playingKey === key;
                  const labels = voice.labels ?? {};
                  const subtitle = formatVoiceSubtitle(labels.gender, labels.accent, voice.description ?? "Premium voice");
                  return (
                    <VoiceItem
                      key={key}
                      name={voice.name}
                      subtitle={subtitle}
                      hasPreview={!!voice.preview_url}
                      isPlaying={isPlaying}
                      onPlay={() => playPremiumTeaser(voice)}
                      disabled={false}
                      isSelected={false}
                      onClick={() => setShowUpgrade(true)}
                      badge={
                        <span className="inline-flex h-5 min-w-[4.5rem] items-center justify-center rounded-full bg-purple-600 px-2.5 py-0.5 text-[10px] font-semibold text-white">Premium</span>
                      }
                    />
                  );
                })}
              </>
            )}
          </div>
          )}
          {!(showAdvancedOptions && isPro) && !myVoicesLoading && myVoicesList.length === 0 && (
            <p className="text-[11px] text-gray-500 mt-2">
              No voices saved. Add voices in the Voices tab to use them here.{" "}
              {!isPro && (
                <button type="button" onClick={() => setShowUpgrade(true)} className="text-purple-600 hover:underline">
                  Upgrade to add video
                </button>
              )}
            </p>
          )}
        </div>

        {/* Voice tuning β€” Stability + Speed sliders (paid); apply-to-all sync mirrors other voice controls */}
        {(() => {
          const applyBulkTuning = <T,>(
            setter: React.Dispatch<React.SetStateAction<T[]>>,
            value: T,
          ) => {
            const targetIndices = indexed.map(({ i }) => i);
            if (bulkApplyVoiceAll && activeIndex === masterIndex) {
              setter((prev) => {
                const next = [...prev];
                targetIndices.forEach((idx) => { next[idx] = value; });
                return next;
              });
            } else {
              setBulkApplyVoiceAll(false);
              setter((prev) => {
                const next = [...prev];
                next[activeIndex] = value;
                return next;
              });
            }
          };
          return (
            <div className={rowVoiceGender === "none" ? "opacity-60 pointer-events-none" : ""}>
              {showAdvancedOptions && isPro && (
                <div className="space-y-4">
                  <div className="flex items-center justify-between gap-3 p-3 rounded-xl bg-gray-50/60 border border-gray-200/60">
                    <div>
                      <p className="text-sm font-medium text-gray-700">Enable</p>
                    </div>
                    <button
                      type="button"
                      role="switch"
                      aria-checked={expressiveEnabled}
                      onClick={() => setExpressiveEnabled((v) => !v)}
                      className={`relative inline-flex h-5 w-9 shrink-0 items-center rounded-full transition-colors ${expressiveEnabled ? "bg-purple-600" : "bg-gray-300"}`}
                    >
                      <span className={`inline-block h-4 w-4 transform rounded-full bg-white transition-transform ${expressiveEnabled ? "translate-x-4" : "translate-x-0.5"}`} />
                    </button>
                  </div>
                  <div
                    className={`space-y-4 transition-opacity ${expressiveEnabled ? "" : "opacity-50 pointer-events-none select-none"}`}
                    aria-disabled={!expressiveEnabled}
                  >
                      <div>
                        <div className="flex items-center justify-between mb-1.5">
                          <span className="text-[11px] font-medium text-gray-600">
                            Emotion <span className="font-normal text-gray-400">(optional)</span>
                          </span>
                        </div>
                        <div className="flex flex-wrap gap-1.5">
                          {VOICE_EMOTIONS.map((em) => {
                            const selected = rowVoiceEmotion === em.value;
                            return (
                              <button
                                key={em.value}
                                type="button"
                                aria-pressed={selected}
                                onClick={() => applyBulkTuning(setBulkVoiceEmotion, selected ? "" : em.value)}
                                className={`px-3 py-1 rounded-full text-[11px] font-medium border transition-colors ${
                                  selected
                                    ? "bg-purple-600 border-purple-600 text-white"
                                    : "bg-white border-gray-200 text-gray-600 hover:border-purple-300"
                                }`}
                              >
                                {em.label}
                              </button>
                            );
                          })}
                        </div>
                      </div>
                      <div>
                        <div className="flex items-center justify-between mb-1">
                          <span className="text-[11px] font-medium text-gray-600">Expressiveness</span>
                          <span className="text-[11px] text-gray-400 tabular-nums">{rowVoiceStability.toFixed(2)}</span>
                        </div>
                        <input
                          type="range"
                          min={VOICE_STABILITY_MIN}
                          max={VOICE_STABILITY_MAX}
                          step={VOICE_TUNING_STEP}
                          value={rowVoiceStability}
                          onChange={(e) => applyBulkTuning(setBulkVoiceStability, parseFloat(e.target.value))}
                          className="w-full accent-purple-600 cursor-pointer"
                        />
                        <div className="flex justify-between text-[10px] text-gray-400 mt-0.5">
                          <span>Steady</span>
                          <span>Expressive</span>
                        </div>
                      </div>
                      <div>
                        <div className="flex items-center justify-between mb-1">
                          <span className="text-[11px] font-medium text-gray-600">Character</span>
                          <span className="text-[11px] text-gray-400 tabular-nums">{rowVoiceStyle.toFixed(2)}</span>
                        </div>
                        <input
                          type="range"
                          min={VOICE_STYLE_MIN}
                          max={VOICE_STYLE_MAX}
                          step={VOICE_TUNING_STEP}
                          value={rowVoiceStyle}
                          onChange={(e) => applyBulkTuning(setBulkVoiceStyle, parseFloat(e.target.value))}
                          className="w-full accent-purple-600 cursor-pointer"
                        />
                        <div className="flex justify-between text-[10px] text-gray-400 mt-0.5">
                          <span>Natural</span>
                          <span>Dramatic</span>
                        </div>
                        {rowVoiceStyle >= 0.4 && rowVoiceStability >= 0.7 && (
                          <p className="text-[10px] text-amber-600 mt-0.5">High Character + high Expressiveness can sound distorted.</p>
                        )}
                      </div>
                      <div>
                        <div className="flex items-center justify-between mb-1">
                          <span className="text-[11px] font-medium text-gray-600">Speed</span>
                          <span className="text-[11px] text-gray-400 tabular-nums">{rowVoiceSpeed.toFixed(2)}x</span>
                        </div>
                        <input
                          type="range"
                          min={VOICE_SPEED_MIN}
                          max={VOICE_SPEED_MAX}
                          step={VOICE_TUNING_STEP}
                          value={rowVoiceSpeed}
                          onChange={(e) => applyBulkTuning(setBulkVoiceSpeed, parseFloat(e.target.value))}
                          className="w-full accent-purple-600 cursor-pointer"
                        />
                      </div>
                      <button
                        type="button"
                        onClick={() =>
                          handleVoicePreview({
                            gender: rowVoiceGender,
                            accent: rowVoiceAccent,
                            customVoiceId: rowCustomVoiceId,
                            stability: rowVoiceStability,
                            speed: rowVoiceSpeed,
                            emotion: rowVoiceEmotion,
                            style: rowVoiceStyle,
                          })
                        }
                        disabled={previewState === "loading"}
                        className="inline-flex items-center gap-2 px-3 py-1.5 rounded-lg text-xs font-medium border border-gray-200 text-gray-700 hover:border-purple-300 hover:text-purple-700 transition-colors disabled:opacity-50"
                      >
                        {previewState === "loading" ? (
                          <>
                            <span className="w-3.5 h-3.5 rounded-full border-2 border-purple-200 border-t-purple-600 animate-spin" />
                            Generating…
                          </>
                        ) : previewState === "playing" ? (
                          <>
                            <svg className="w-3.5 h-3.5" viewBox="0 0 24 24" fill="currentColor" aria-hidden><rect x="6" y="5" width="4" height="14" rx="1" /><rect x="14" y="5" width="4" height="14" rx="1" /></svg>
                            Stop
                          </>
                        ) : (
                          <>
                            <svg className="w-3.5 h-3.5" viewBox="0 0 24 24" fill="currentColor" aria-hidden><path d="M8 5v14l11-7z" /></svg>
                            Listen to a sample
                          </>
                        )}
                      </button>
                  </div>
                </div>
              )}
            </div>
          );
        })()}

        <div className="flex gap-2 pt-1">
          <button
            type="button"
            onClick={goBack}
            className="px-5 py-3 text-sm font-medium text-gray-500 bg-gray-50 hover:bg-gray-100 rounded-xl transition-colors border border-gray-200/60"
          >
            Back
          </button>
          <button
            ref={submitButtonRef}
            type="submit"
            disabled={loading || !onSubmitBulk}
            className="flex-1 py-3 bg-purple-600 hover:bg-purple-700 disabled:bg-purple-400 disabled:text-white text-white text-sm font-medium rounded-xl transition-colors flex items-center justify-center gap-2"
          >
            {loading ? (
              <>
                <span className="w-3.5 h-3.5 border-2 border-white/30 border-t-white rounded-full animate-spin" />
                Generating
              </>
            ) : (
              "Create all & generate"
            )}
          </button>
        </div>
      </div>
    );
  })();

  // ─── Render ──────────────────────────────────────────────────
  // Step order: 1 Project, 2 Template, 3 Voice
  const stepContent =
    step === 1
      ? step1
      : step === 2
        ? mode === "bulk"
          ? step2BulkTemplate
          : step2Template
        : mode === "bulk"
          ? step3BulkVoice
          : step3Voice;

  const modalWidth = "max-w-xl";

  const isStep2TemplatesPending =
    step === 2 && (builtinTemplatesLoading || templateAvailabilityLoading || !sessionBuiltinInitDone);

  // Constant form size: min-height so layout doesn’t jump between steps
  const stepContentWrapper = (
    <div className="relative min-h-[420px] flex flex-col">
      <div className="min-h-[420px] flex flex-col">{stepContent}</div>
      {isStep2TemplatesPending && (
        <div
          className="absolute inset-0 z-20 flex items-center justify-center rounded-xl bg-white/60 backdrop-blur-md ring-1 ring-gray-200/50 shadow-[inset_0_0_24px_rgba(124,58,237,0.06)]"
          aria-busy="true"
        >
          <span
            className="h-4 w-4 shrink-0 animate-spin rounded-full border-2 border-purple-200 border-t-purple-600"
            aria-hidden
          />
        </div>
      )}
    </div>
  );

  const formContent = (
    <>
      <form
        onSubmit={handleSubmit}
        onKeyDown={(e) => {
          // Prevent Enter from submitting unless the submit button is focused (avoids auto-submit when landing on step 3)
          if (e.key === "Enter" && document.activeElement !== submitButtonRef.current) {
            e.preventDefault();
          }
        }}
      >
        <div className="relative">
          <StepIndicator current={step} total={3} />
          {stepContentWrapper}
        </div>
        <UpgradePlanModal
          open={showUpgrade}
          onClose={() => setShowUpgrade(false)}
          title="Upgrade to unlock"
          subtitle="Unlock premium voices and more. Choose a plan below."
        />
        <UpgradePlanModal
          open={showCustomTemplateUpgrade}
          onClose={() => setShowCustomTemplateUpgrade(false)}
          subscriptionsOnly
          title="Upgrade to use custom template"
          subtitle="Custom templates are a Standard & Pro feature. Upgrade your plan to use this template in your videos."
        />
        <GetMoreTemplatesModal
          open={showGetMoreTemplates}
          onClose={() => setShowGetMoreTemplates(false)}
          onChooseLink={() => {
            setShowGetMoreTemplates(false);
            openStep2CustomTemplateCreator(videoStyle, null);
          }}
          onChooseDesigner={() => {
            setShowGetMoreTemplates(false);
            setShowDesignerRequest(true);
          }}
        />
        <DesignerTemplateRequestModal
          open={showDesignerRequest}
          onClose={() => setShowDesignerRequest(false)}
        />
      </form>
    </>
  );

  if (!asModal) {
    return (
      <div className="relative">
        <StepIndicator current={step} total={3} />
        <form
          onSubmit={handleSubmit}
          onKeyDown={(e) => {
            if (e.key === "Enter" && document.activeElement !== submitButtonRef.current) {
              e.preventDefault();
            }
          }}
        >
          {stepContentWrapper}
        </form>
        <UpgradePlanModal
          open={showUpgrade}
          onClose={() => setShowUpgrade(false)}
          title="Upgrade to unlock"
          subtitle="Unlock premium voices and more. Choose a plan below."
        />
        <UpgradePlanModal
          open={showCustomTemplateUpgrade}
          onClose={() => setShowCustomTemplateUpgrade(false)}
          subscriptionsOnly
          title="Upgrade to use custom template"
          subtitle="Custom templates are a Standard & Pro feature. Upgrade your plan to use this template in your videos."
        />
        <GetMoreTemplatesModal
          open={showGetMoreTemplates}
          onClose={() => setShowGetMoreTemplates(false)}
          onChooseLink={() => {
            setShowGetMoreTemplates(false);
            openStep2CustomTemplateCreator(videoStyle, null);
          }}
          onChooseDesigner={() => {
            setShowGetMoreTemplates(false);
            setShowDesignerRequest(true);
          }}
        />
        <DesignerTemplateRequestModal
          open={showDesignerRequest}
          onClose={() => setShowDesignerRequest(false)}
        />
        {videoPreviewId && (
          <TemplateVideoLightbox
            templateId={videoPreviewId}
            onClose={() => setVideoPreviewId(null)}
            onSelect={() => applyTemplate(videoPreviewId)}
            isSelected={template === videoPreviewId}
            customTemplate={
              videoPreviewId.startsWith("custom_")
                ? customTemplates.find((ct) => ct.id === parseInt(videoPreviewId.replace("custom_", "")))
                : videoPreviewId.startsWith("crafted_")
                ? craftedTemplates.find((ct) => ct.id === videoPreviewId)
                : null
            }
          />
        )}
      </div>
    );
  }

  return ReactDOM.createPortal(
    <div className="fixed inset-0 z-50 flex items-center justify-center p-8">
      <div
        className={`absolute inset-0 ${isStep2TemplatesPending ? "bg-black/45 backdrop-blur-md" : "bg-black/40 backdrop-blur-sm"}`}
        onClick={onClose}
      />
      <div
        className={`relative w-full ${modalWidth} bg-white/90 backdrop-blur-xl border border-gray-200/40 rounded-2xl shadow-[0_8px_40px_rgba(0,0,0,0.08)] p-7 mt-5 max-h-[85vh] overflow-y-auto transition-all duration-300`}
      >
        {/* Header */}
        <div className="flex items-center justify-between mb-6">
          <h2 className="text-base font-semibold text-gray-900">New Project</h2>
          <button onClick={onClose} className="text-gray-300 hover:text-gray-500 transition-colors">
            <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
            </svg>
          </button>
        </div>
        {formContent}
      </div>
      {videoPreviewId && (
        <TemplateVideoLightbox
          templateId={videoPreviewId}
          onClose={() => setVideoPreviewId(null)}
          onSelect={() => applyTemplate(videoPreviewId)}
          isSelected={template === videoPreviewId}
        />
      )}
    </div>,
    document.body
  );
}