File size: 435,032 Bytes
060bb47
 
 
 
 
 
 
 
 
5dde9d0
 
060bb47
 
5dde9d0
 
 
 
 
060bb47
 
 
a9f0d6b
 
 
 
 
 
 
18fc544
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a5e129b
18fc544
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a5e129b
 
18fc544
 
 
 
a5e129b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
18fc544
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a5e129b
18fc544
 
 
 
 
 
060bb47
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
224927d
 
68f3abb
 
 
 
 
 
 
224927d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
060bb47
224927d
060bb47
224927d
 
060bb47
 
224927d
 
 
68f3abb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
224927d
 
68f3abb
224927d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
060bb47
 
 
 
 
 
68f3abb
 
 
 
 
060bb47
 
 
 
 
 
 
 
2abdf1b
 
 
 
29f4874
 
 
060bb47
 
 
29f4874
060bb47
 
 
 
 
 
 
 
 
 
a5e129b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
060bb47
 
 
 
 
 
cd5ab31
 
 
 
 
 
 
 
 
 
1ee54b6
 
 
cd5ab31
 
 
 
 
 
 
e4af262
 
8f87141
 
e4af262
 
 
8f87141
 
e4af262
8f87141
e4af262
 
 
 
8f87141
e4af262
 
 
a432a49
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6f3dd42
 
a432a49
 
0c44e17
a432a49
bb6a5eb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a432a49
 
 
 
 
 
 
bb6a5eb
a432a49
 
 
bb6a5eb
a432a49
 
 
 
0c44e17
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a432a49
 
 
 
2abdf1b
 
 
 
 
 
 
ae02f3d
060bb47
b1e8353
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
060bb47
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a9f0d6b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
060bb47
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
851108f
 
 
 
 
 
060bb47
 
 
 
 
 
851108f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
060bb47
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
94090e0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
060bb47
 
 
94090e0
 
 
 
 
060bb47
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4210428
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
060bb47
5dde9d0
 
060bb47
 
 
 
 
 
 
 
 
 
 
5dde9d0
 
 
 
 
 
 
 
 
 
 
 
060bb47
831f58e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
060bb47
5dde9d0
831f58e
 
 
 
 
 
 
 
 
 
 
060bb47
831f58e
 
 
060bb47
831f58e
 
060bb47
831f58e
060bb47
831f58e
060bb47
94090e0
 
 
 
 
 
060bb47
 
 
 
831f58e
 
 
 
 
 
5dde9d0
 
 
 
 
 
 
 
 
 
 
060bb47
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
26914b4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
060bb47
 
 
94090e0
 
 
 
 
060bb47
 
 
4d11623
 
 
6d4f32e
 
060bb47
4d11623
060bb47
26914b4
 
 
 
 
 
 
 
 
 
 
060bb47
 
 
 
 
 
 
 
 
 
 
 
 
 
2abdf1b
 
 
060bb47
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6d4f32e
060bb47
 
 
6d4f32e
 
 
 
 
060bb47
 
 
 
6d4f32e
060bb47
6d4f32e
 
060bb47
 
6d4f32e
 
 
 
 
 
060bb47
 
 
 
 
6d4f32e
75d0661
 
 
 
 
 
 
 
 
060bb47
 
 
 
 
 
 
4210428
 
 
 
 
 
6d4f32e
4210428
 
 
6d4f32e
 
 
 
 
060bb47
6d4f32e
060bb47
6d4f32e
060bb47
 
 
53ac929
1cac515
4af235d
 
 
 
 
 
 
 
 
1cac515
 
4af235d
1cac515
 
4af235d
1cac515
4af235d
 
 
 
 
 
1cac515
53ac929
 
060bb47
94090e0
 
 
 
060bb47
 
 
 
 
 
 
 
 
 
53ac929
 
 
060bb47
 
 
53ac929
 
 
 
 
 
 
 
 
 
4af235d
 
 
 
 
 
 
 
 
060bb47
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4e240b0
6d4f32e
060bb47
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4e240b0
30ffcab
 
 
4e240b0
30ffcab
 
 
 
 
 
 
 
4e240b0
 
30ffcab
 
4e240b0
30ffcab
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4e240b0
 
30ffcab
 
 
 
 
 
 
597bf69
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
30ffcab
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
597bf69
 
 
 
 
 
 
 
 
30ffcab
597bf69
 
 
 
 
 
 
 
 
30ffcab
4e240b0
30ffcab
 
 
 
 
 
 
4e240b0
597bf69
 
 
 
 
 
30ffcab
 
 
4e240b0
597bf69
30ffcab
4e240b0
30ffcab
 
597bf69
30ffcab
597bf69
30ffcab
 
4e240b0
30ffcab
 
 
 
 
 
 
 
 
597bf69
30ffcab
 
 
597bf69
 
 
 
30ffcab
 
 
597bf69
30ffcab
 
 
 
 
 
 
 
597bf69
 
30ffcab
 
597bf69
30ffcab
597bf69
 
30ffcab
 
597bf69
 
 
 
30ffcab
 
 
 
 
 
 
 
 
597bf69
 
 
 
 
30ffcab
 
 
 
 
597bf69
30ffcab
597bf69
 
 
 
 
 
30ffcab
597bf69
30ffcab
597bf69
 
30ffcab
 
 
 
 
 
 
 
597bf69
30ffcab
 
 
 
 
 
597bf69
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
30ffcab
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4e240b0
 
 
 
 
30ffcab
 
4e240b0
 
1fdd762
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
30ffcab
 
 
4e240b0
 
30ffcab
 
 
 
 
 
 
 
 
 
4e240b0
 
 
30ffcab
4e240b0
 
30ffcab
4e240b0
 
30ffcab
 
 
4e240b0
 
 
 
 
 
30ffcab
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4e240b0
 
 
30ffcab
 
4e240b0
30ffcab
 
4e240b0
30ffcab
4e240b0
30ffcab
 
 
4e240b0
 
30ffcab
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4e240b0
 
 
 
060bb47
18fc544
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5ddc4d7
 
 
 
 
 
 
 
 
 
 
 
 
060bb47
597bf69
 
 
 
 
060bb47
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5025379
 
 
 
 
 
 
 
 
 
 
060bb47
 
 
 
 
 
5025379
 
 
 
 
 
 
 
 
 
 
060bb47
 
 
 
 
 
 
 
 
 
 
6d4f32e
 
 
060bb47
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
94090e0
 
 
 
 
 
 
 
 
 
 
060bb47
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7446d10
060bb47
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6f3dd42
060bb47
6f3dd42
 
 
060bb47
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dd7ab2a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d7d4fe2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dd7ab2a
 
d7d4fe2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dd7ab2a
d7d4fe2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dd7ab2a
 
060bb47
 
 
 
 
 
 
 
 
dd7ab2a
 
 
 
 
 
 
 
 
060bb47
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4d11623
 
 
 
 
 
060bb47
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a635fbe
 
 
 
 
 
 
 
 
 
060bb47
 
 
 
 
a635fbe
060bb47
 
 
 
 
 
 
 
 
a635fbe
060bb47
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
20cdca4
 
 
 
 
 
 
 
 
 
0360d9f
 
20cdca4
 
 
 
 
0360d9f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
64f2cf2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0360d9f
64f2cf2
 
0360d9f
 
 
 
 
 
 
 
4615fe6
 
 
 
 
 
 
 
 
 
0360d9f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
20cdca4
 
 
4af235d
 
 
 
 
060bb47
4af235d
060bb47
 
0360d9f
060bb47
64f2cf2
060bb47
 
 
0360d9f
4615fe6
0360d9f
 
 
 
4af235d
0360d9f
 
060bb47
 
 
4af235d
060bb47
 
 
53ac929
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1cac515
 
 
 
53ac929
1cac515
 
 
 
 
53ac929
 
 
64f2cf2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
53ac929
64f2cf2
53ac929
 
 
 
 
 
627ddc3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
53ac929
 
 
 
 
 
4af235d
 
 
 
 
627ddc3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
53ac929
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
64f2cf2
 
 
 
53ac929
64f2cf2
53ac929
 
 
 
 
 
4615fe6
 
53ac929
 
 
 
 
 
 
 
 
5ddc4d7
 
53ac929
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4af235d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a635fbe
 
4af235d
a635fbe
 
4af235d
 
 
 
 
 
53ac929
 
060bb47
 
 
 
 
 
597bf69
 
 
060bb47
597bf69
060bb47
 
 
 
597bf69
 
 
060bb47
 
 
 
597bf69
060bb47
 
 
6d4f32e
060bb47
 
 
 
 
 
 
 
 
 
6d4f32e
060bb47
 
 
 
 
 
 
 
 
 
6d4f32e
 
 
 
 
 
 
 
 
060bb47
75d0661
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
060bb47
75d0661
 
060bb47
 
 
 
 
 
6d4f32e
060bb47
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6d4f32e
060bb47
 
 
6d4f32e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
75d0661
 
 
 
 
 
 
 
 
 
6d4f32e
 
4e240b0
 
 
30ffcab
4e240b0
30ffcab
 
 
 
 
4e240b0
 
30ffcab
 
4e240b0
1fdd762
 
 
 
060bb47
 
 
75d0661
060bb47
75d0661
 
 
060bb47
 
 
 
 
 
 
 
75d0661
 
 
 
32d4ba5
 
 
 
 
 
 
 
 
 
 
 
060bb47
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
597bf69
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7446d10
 
 
 
 
 
 
 
 
 
b465637
 
 
 
 
7446d10
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
060bb47
32d4ba5
 
 
 
060bb47
 
 
 
 
597bf69
 
 
 
 
 
 
 
 
060bb47
 
 
32d4ba5
 
 
 
 
 
 
 
 
 
 
 
 
 
597bf69
 
 
 
 
 
 
 
 
 
32d4ba5
 
 
4e240b0
 
75d0661
 
 
4e240b0
 
 
 
 
75d0661
18fc544
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
75d0661
 
 
 
 
 
 
18fc544
597bf69
 
 
 
 
 
 
 
 
4e240b0
 
 
1fdd762
 
 
 
 
 
 
 
 
 
 
 
 
 
060bb47
4e240b0
 
 
75d0661
 
 
 
 
 
060bb47
 
 
 
 
75d0661
 
 
 
 
 
 
 
 
 
4e240b0
 
 
 
 
 
 
 
 
060bb47
 
 
 
 
 
 
 
 
 
 
 
6d4f32e
32d4ba5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6d4f32e
 
32d4ba5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e52101b
 
 
 
 
 
32d4ba5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6d4f32e
 
 
 
 
 
 
 
 
 
 
 
 
 
32d4ba5
6d4f32e
32d4ba5
6d4f32e
 
 
 
 
 
 
 
 
32d4ba5
 
 
 
6d4f32e
 
32d4ba5
 
6d4f32e
32d4ba5
 
 
6d4f32e
 
 
32d4ba5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6d4f32e
 
 
32d4ba5
6d4f32e
 
 
 
32d4ba5
6d4f32e
 
 
32d4ba5
 
 
6d4f32e
32d4ba5
6d4f32e
 
32d4ba5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6d4f32e
 
32d4ba5
 
 
 
6d4f32e
32d4ba5
6d4f32e
 
 
32d4ba5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6d4f32e
32d4ba5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6d4f32e
 
060bb47
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1508f2b
 
 
 
 
 
 
 
 
 
 
 
 
 
3aaff74
a7f536d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b102465
a7f536d
7a41c01
 
 
 
 
 
 
 
a7f536d
 
224927d
 
 
 
 
fb93c97
 
224927d
8a091d1
fb93c97
 
 
 
 
68f3abb
 
 
 
 
fb93c97
 
 
a7f536d
7a41c01
 
 
 
 
 
 
dd2d535
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4229225
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a9f0d6b
 
 
 
 
 
 
 
 
 
 
 
 
 
7a41c01
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
df97b42
 
 
 
7a41c01
 
 
 
 
df97b42
7a41c01
 
df97b42
 
 
 
 
 
 
7a41c01
 
df97b42
7a41c01
 
 
 
 
 
 
 
 
 
 
 
 
 
df97b42
 
7a41c01
 
 
a7f536d
df97b42
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5025379
 
 
 
 
 
 
 
 
 
13a90b2
 
 
df97b42
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b102465
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
73c780f
 
 
 
 
 
be23b1b
b102465
 
 
 
 
 
 
 
 
 
 
 
 
 
a7f536d
 
 
 
 
 
 
 
b63af66
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a7f536d
 
 
b63af66
 
 
a7f536d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b63af66
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a7f536d
 
 
 
b63af66
 
 
 
 
a7f536d
 
 
 
 
 
995ee2a
 
 
dd2d535
 
 
 
 
 
 
 
 
995ee2a
345b9c9
 
 
 
 
 
 
8a091d1
 
 
 
 
 
 
 
 
 
 
 
 
93dc633
 
 
 
 
 
 
8a091d1
 
 
 
93dc633
8a091d1
93dc633
 
8a091d1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7a41c01
 
 
 
 
 
 
 
 
a7f536d
 
 
345b9c9
 
 
7a41c01
dd2d535
345b9c9
 
a7f536d
 
 
 
b102465
 
 
 
 
 
 
a7f536d
 
 
 
b63af66
a7f536d
 
 
 
 
 
 
8a091d1
a7f536d
 
 
6983e3b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
93dc633
 
 
6983e3b
 
ca7be50
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
73b3e85
 
cd5ab31
 
 
b54cfd9
73b3e85
 
 
 
cd5ab31
 
 
b54cfd9
cd5ab31
 
 
 
 
b54cfd9
cd5ab31
73b3e85
b54cfd9
 
 
 
 
 
 
 
ca7be50
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
73b3e85
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0360d9f
73b3e85
 
0360d9f
4615fe6
0360d9f
 
 
 
 
73b3e85
 
 
0360d9f
73b3e85
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
61e171c
 
 
 
 
 
 
 
 
 
 
 
 
 
13a90b2
 
 
 
 
 
 
 
 
 
b54cfd9
 
 
61e171c
13a90b2
 
 
 
b54cfd9
61e171c
 
 
 
 
13a90b2
61e171c
13a90b2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b54cfd9
61e171c
 
13a90b2
61e171c
b54cfd9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
61e171c
 
 
b54cfd9
61e171c
 
1c7c498
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1ee54b6
 
 
1c7c498
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1ee54b6
 
 
 
7446d10
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ca7be50
a7f536d
7446d10
dd2d535
 
 
 
 
 
 
 
 
 
 
 
7a41c01
6983e3b
 
 
 
 
 
 
7a41c01
 
 
 
ca7be50
3c2de37
7a41c01
 
ca7be50
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cd5ab31
 
 
 
 
 
 
 
 
 
ca7be50
a7f536d
 
 
 
 
 
 
995ee2a
 
 
 
 
 
 
a7f536d
995ee2a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
db7532c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7c54abf
 
 
 
 
 
 
 
 
 
 
 
 
 
db7532c
 
 
 
 
 
dd2d535
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
345b9c9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7a41c01
 
 
 
 
8a091d1
 
 
7a41c01
 
8a091d1
7a41c01
 
 
 
 
8a091d1
7a41c01
 
 
 
cd5ab31
 
 
 
 
 
 
a7f536d
ca7be50
cd5ab31
4615fe6
1b8382f
 
a7f536d
 
 
4615fe6
1b8382f
 
4615fe6
1b8382f
4615fe6
 
 
 
 
1b8382f
4615fe6
 
 
 
 
 
 
 
 
a7f536d
ca7be50
 
 
a7f536d
 
 
ca7be50
df97b42
4615fe6
 
 
 
 
 
 
 
df97b42
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a7f536d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ca7be50
 
 
 
 
 
1b8382f
 
 
 
 
 
ca7be50
 
 
 
 
73b3e85
 
 
 
 
 
 
 
b54cfd9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ca7be50
 
 
 
 
 
 
 
 
 
 
 
a7f536d
ca7be50
 
a7f536d
0360d9f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a7f536d
0360d9f
 
 
 
 
13a90b2
 
 
 
 
 
 
 
 
0360d9f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a7f536d
 
 
 
 
13a90b2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a7f536d
13a90b2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f0c3f5a
 
 
 
 
 
 
 
 
 
 
 
eeea851
 
438edb5
f0c3f5a
 
 
 
 
 
 
eeea851
f0c3f5a
 
1ee54b6
f0c3f5a
eeea851
 
 
 
 
 
 
 
 
 
f0c3f5a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
eeea851
 
 
 
 
f0c3f5a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7446d10
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f0c3f5a
1ee54b6
f0c3f5a
 
 
7446d10
f0c3f5a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7df48f4
 
 
eeea851
 
7df48f4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
eeea851
7df48f4
 
 
 
eeea851
7df48f4
 
eeea851
 
f0c3f5a
 
 
 
 
 
 
 
 
 
eeea851
 
f0c3f5a
 
eeea851
f0c3f5a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
eeea851
438edb5
f0c3f5a
 
 
 
 
 
 
438edb5
f0c3f5a
 
 
73c780f
93b09d3
73c780f
f0c3f5a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1ee54b6
7446d10
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1ee54b6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f0c3f5a
be23b1b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d67ba8e
be23b1b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4b21a7f
 
be23b1b
 
4b21a7f
be23b1b
4b21a7f
 
 
be23b1b
 
 
 
 
 
 
 
 
 
 
 
 
d67ba8e
be23b1b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4b21a7f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
be23b1b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d67ba8e
be23b1b
 
 
 
 
 
 
 
 
 
 
 
ec0167c
 
4b21a7f
ec0167c
 
4b21a7f
ec0167c
 
 
4b21a7f
ec0167c
 
 
be23b1b
 
 
 
ec0167c
 
d67ba8e
be23b1b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7446d10
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
be23b1b
 
29f4874
be23b1b
 
7446d10
ec0167c
 
 
 
 
 
be23b1b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
93b09d3
be23b1b
 
 
 
 
 
 
 
21dfced
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
be23b1b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
21dfced
 
 
 
be23b1b
21dfced
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
be23b1b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ec0167c
 
 
 
 
 
 
 
 
 
be23b1b
 
 
 
 
 
 
 
 
 
1ee54b6
 
 
 
 
 
 
 
be23b1b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e52101b
 
 
 
 
 
 
 
 
be23b1b
e52101b
be23b1b
ec0167c
 
 
 
 
 
 
 
 
 
d566e10
ec0167c
 
d566e10
 
 
 
 
4b21a7f
d566e10
 
ec0167c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4b21a7f
ec0167c
d566e10
ec0167c
 
 
4b21a7f
 
 
 
 
 
 
 
 
 
d566e10
 
 
 
 
 
 
 
 
 
 
 
 
4b21a7f
 
 
 
d566e10
4b21a7f
d566e10
 
 
 
 
 
4b21a7f
d566e10
 
 
 
4b21a7f
 
 
 
 
 
 
d566e10
 
 
 
 
4b21a7f
 
d566e10
4b21a7f
d566e10
 
 
 
 
 
 
 
 
ec0167c
d566e10
ec0167c
 
 
 
 
 
 
 
 
d67ba8e
 
ec0167c
 
 
 
 
 
4b21a7f
 
 
ec0167c
 
 
d566e10
 
 
 
 
 
4b21a7f
 
d566e10
 
 
 
 
 
 
4b21a7f
 
 
 
d566e10
4b21a7f
d566e10
 
4b21a7f
d566e10
 
4b21a7f
d566e10
 
 
 
 
 
ec0167c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d566e10
ec0167c
 
 
 
d566e10
ec0167c
 
d566e10
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ec0167c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d566e10
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ec0167c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a52c6ca
ec0167c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8803cb4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
93b09d3
8803cb4
29f4874
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8803cb4
 
 
 
 
 
 
29f4874
 
8803cb4
e52101b
 
 
 
 
 
8803cb4
 
 
 
29f4874
 
 
8803cb4
 
e52101b
8803cb4
 
 
 
 
 
 
 
 
 
 
29f4874
 
 
 
 
 
 
 
 
 
be23b1b
1ee54b6
 
 
 
 
 
 
 
 
 
 
 
 
 
94b29e6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1ee54b6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
94b29e6
 
 
 
 
 
 
 
1ee54b6
 
94b29e6
 
1ee54b6
 
 
 
 
 
 
 
 
 
 
 
94b29e6
1ee54b6
 
 
 
 
 
 
94b29e6
 
1ee54b6
 
 
94b29e6
 
1ee54b6
 
 
94b29e6
 
1ee54b6
 
 
 
94b29e6
1ee54b6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f94392e
 
 
 
385e30c
f94392e
 
 
 
 
 
 
 
 
 
94f48ef
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
35d1c3b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3c2de37
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8f6819e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
91ed780
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dbb031b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
91ed780
 
 
 
 
dbb031b
91ed780
dbb031b
 
 
91ed780
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
// Digital Evolution Engine — frontend controller.
// Single global state object; no framework. Talks to the Flask API at /api/*.

const state = {
    sessionId: null,
    preview: null,
    jobId: null,
    pollHandle: null,
    chosenCds: null,
    pollErrors: 0,      // consecutive transient poll failures (give up after a cap)
    pollStart: 0,       // ms timestamp of the first poll (overall wall-clock cap)
};

// Poll give-up limits — stop the spinner instead of retrying forever if the
// engine is wedged / restarting / still waking from cold start.
const MAX_POLL_ERRORS = 12;        // ~consecutive dropped polls before we bail
const MAX_POLL_MS = 6 * 60 * 1000; // overall wall-clock ceiling for a single run

const $ = (sel) => document.querySelector(sel);
const $$ = (sel) => document.querySelectorAll(sel);

// Shared "Try an example" payload: the EGFP coding sequence (a verified clean
// single-ORF CDS, ATG…TAA). GFP is the universal teaching target — a classic
// directed-evolution and knockout example — so Directed Evolution and CRISPR
// both preload it. Defined top-level so both the DE body and the CRISPR IIFE
// can read it.
const TD_EXAMPLE_GFP_CDS = 'ATGGTGAGCAAGGGCGAGGAGCTGTTCACCGGGGTGGTGCCCATCCTGGTCGAGCTGGACGGCGACGTAAACGGCCACAAGTTCAGCGTGTCCGGCGAGGGCGAGGGCGATGCCACCTACGGCAAGCTGACCCTGAAGTTCATCTGCACCACCGGCAAGCTGCCCGTGCCCTGGCCCACCCTCGTGACCACCCTGACCTACGGCGTGCAGTGCTTCAGCCGCTACCCCGACCACATGAAGCAGCACGACTTCTTCAAGTCCGCCATGCCCGAAGGCTACGTCCAGGAGCGCACCATCTTCTTCAAGGACGACGGCAACTACAAGACCCGCGCCGAGGTGAAGTTCGAGGGCGACACCCTGGTGAACCGCATCGAGCTGAAGGGCATCGACTTCAAGGAGGACGGCAACATCCTGGGGCACAAGCTGGAGTACAACTACAACAGCCACAACGTCTATATCATGGCCGACAAGCAGAAGAACGGCATCAAGGTGAACTTCAAGATCCGCCACAACATCGAGGACGGCAGCGTGCAGCTCGCCGACCACTACCAGCAGAACACCCCCATCGGCGACGGCCCCGTGCTGCTGCCCGACAACCACTACCTGAGCACCCAGTCCGCCCTGAGCAAAGACCCCAACGAGAAGCGCGATCACATGGTCCTGCTGGAGTTCGTGACCGCCGCCGGGATCACTCTCGGCATGGACGAGCTGTACAAGTAA';

// ============================================================== DISCLAIMERS
// Two-layer "research use only" consent:
//
//   1. First-use modal (localStorage) — shown on first visit to a browser,
//      blocks the app until the user accepts. Pairs with the
//      research-strip under the topbar that's always visible. This is the
//      durable "I understand this is a research tool" record.
//
//   2. Per-session synthesis confirmation (sessionStorage) — interposes
//      on every Synthesize / Copy designed insert action UNTIL the user
//      has ticked "I have visually verified this sequence" once in this
//      tab. After that, synth actions skip the modal but the RE-warn
//      confirms (and any future per-action gates) still fire when needed.
//
// Both are part of the legal narrative: a dispute over "your tool
// shipped wrong DNA" runs into a documented click-through where the
// user actively acknowledged responsibility for verifying the sequence.

const FIRST_USE_KEY = 'turingdna.firstuse.accepted.v1';
const SYNTH_VERIFIED_KEY = 'turingdna.synth.verified.v1';
const START_HERE_KEY = 'turingdna.starthere.seen.v1';

function hasAcceptedFirstUse() {
    try { return localStorage.getItem(FIRST_USE_KEY) === '1'; }
    catch { return false; }
}
function recordFirstUseAcceptance() {
    try {
        localStorage.setItem(FIRST_USE_KEY, '1');
        localStorage.setItem(FIRST_USE_KEY + '.at', new Date().toISOString());
    } catch {}
}
function hasSynthVerifiedThisSession() {
    try { return sessionStorage.getItem(SYNTH_VERIFIED_KEY) === '1'; }
    catch { return false; }
}
function recordSynthVerified() {
    try {
        sessionStorage.setItem(SYNTH_VERIFIED_KEY, '1');
        sessionStorage.setItem(SYNTH_VERIFIED_KEY + '.at', new Date().toISOString());
    } catch {}
}

function openFirstUseModal() {
    const modal = document.getElementById('firstUseModal');
    if (!modal) return;
    modal.hidden = false;
    // ESC + backdrop deliberately don't dismiss this — must click Accept.
    const accept = document.getElementById('firstUseAccept');
    if (accept) {
        accept.onclick = () => {
            recordFirstUseAcceptance();
            modal.hidden = true;
            // Orient the newcomer right after they accept (one time).
            if (!hasSeenStartHere()) openStartHere();
        };
    }
}

// ─── "Start here" goal router ────────────────────────────────────────────
// A one-time (re-openable) orientation: "What are you working on?" → routes
// to the right tool, so a first-timer who knows their goal doesn't have to
// guess the 4-tool map. Dismissible; never blocks the app.
function hasSeenStartHere() {
    try { return localStorage.getItem(START_HERE_KEY) === '1'; }
    catch { return false; }
}
function openStartHere() {
    const modal = document.getElementById('startHereModal');
    if (!modal) return;
    modal.hidden = false;
    try { document.body.style.overflow = 'hidden'; } catch {}
}
function closeStartHere() {
    const modal = document.getElementById('startHereModal');
    if (modal) modal.hidden = true;
    try { document.body.style.overflow = ''; } catch {}
    try { localStorage.setItem(START_HERE_KEY, '1'); } catch {}
}
function initStartHere() {
    const modal = document.getElementById('startHereModal');
    if (!modal) return;
    modal.querySelectorAll('[data-goal]').forEach((el) =>
        el.addEventListener('click', () => {
            const route = el.getAttribute('data-goal');
            closeStartHere();
            if (route) location.hash = '#' + route;
        }));
    modal.querySelectorAll('[data-starthere-close]').forEach((el) =>
        el.addEventListener('click', closeStartHere));
    document.addEventListener('keydown', (e) => {
        if (e.key === 'Escape' && !modal.hidden) closeStartHere();
    });
    const navStart = document.getElementById('navStartHere');
    if (navStart) {
        const open = (e) => { if (e) e.preventDefault(); openStartHere(); };
        navStart.addEventListener('click', open);
        navStart.addEventListener('keydown', (e) => {
            if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); open(); }
        });
    }
}
initStartHere();

// Returns a promise that resolves true if the user confirmed, false if
// they cancelled. Each call shows the modal with the supplied details.
function openSynthConfirmModal(detailsHtml) {
    return new Promise((resolve) => {
        const modal   = document.getElementById('synthConfirmModal');
        const details = document.getElementById('synthConfirmDetails');
        const check   = document.getElementById('synthConfirmCheck');
        const cancel  = document.getElementById('synthConfirmCancel');
        const proceed = document.getElementById('synthConfirmProceed');
        if (!modal || !details || !check || !cancel || !proceed) {
            // Modal markup missing — fail open with a native confirm so
            // we don't silently allow the action without ANY gate.
            resolve(window.confirm('Confirm this synthesis action.'));
            return;
        }
        // Reset state every open so a previous tick / cancel doesn't carry over.
        details.innerHTML = detailsHtml;
        check.checked = false;
        proceed.disabled = true;
        modal.hidden = false;

        const onCheckChange = () => { proceed.disabled = !check.checked; };
        const cleanup = () => {
            check.removeEventListener('change', onCheckChange);
            cancel.onclick = null;
            proceed.onclick = null;
            modal.hidden = true;
        };
        check.addEventListener('change', onCheckChange);
        cancel.onclick  = () => { cleanup(); resolve(false); };
        proceed.onclick = () => {
            if (!check.checked) return;
            recordSynthVerified();
            cleanup();
            resolve(true);
        };
    });
}

/**
 * Gate any synthesize / copy-designed-insert action through the per-session
 * verification modal. Returns true if the action should proceed, false if
 * the user cancelled. Skips the modal (and returns true immediately) once
 * the user has acknowledged at least once in this session.
 *
 * detailsHtml: a short inline summary the modal renders inside its info
 * block — variant ID, vendor name, length, GC%, etc. Use this to make the
 * confirm explicit about WHAT they're about to ship.
 */
async function ensureSynthVerified(detailsHtml) {
    if (hasSynthVerifiedThisSession()) return true;
    return openSynthConfirmModal(detailsHtml);
}

// Wire the first-use gate as early as possible — before any user action
// can fire. The modal blocks pointer events on the rest of the page via
// its fixed backdrop, but rendering the workspace underneath is fine.
if (!hasAcceptedFirstUse()) openFirstUseModal();
else if (!hasSeenStartHere()) openStartHere();   // already accepted earlier → orient now

// "Why?" link in the always-visible research strip re-opens the modal
// for users who want to re-read the disclaimer later.
const _whyBtn = document.getElementById('researchStripWhy');
if (_whyBtn) _whyBtn.addEventListener('click', openFirstUseModal);

// ============================================================== TAB SWITCHING

$$('.tab').forEach((tab) => {
    tab.addEventListener('click', () => {
        $$('.tab').forEach((t) => t.classList.remove('active'));
        $$('.tab-panel').forEach((p) => p.classList.remove('active'));
        tab.classList.add('active');
        document.querySelector(`.tab-panel[data-panel="${tab.dataset.tab}"]`)
            .classList.add('active');
    });
});

// ============================================================== PASTE TEXTAREA
// Line-numbered paste area. Gutter renders one <span> per source line, scrolls
// in sync with the textarea, and can highlight a specific line when the
// server reports an error at a known nucleotide position.

const pasteArea = $('#pasteArea');
const pasteGutter = $('#pasteGutter');
const pasteStats = $('#pasteStats');

// ── Base-ruler layout shared by both sequence paste editors (directed-
//    evolution #pasteArea and CRISPR #crisprInput). The sequence is wrapped to
//    a whole number of 10-base blocks that fit the box (_fitBasesPerLine), and
//    the gutter is numbered by base POSITION (1, 21, 41 … — step = line width)
//    instead of line index, so it reads as a real nucleotide ruler that adapts
//    to the screen. FASTA headers (>) are kept verbatim, take no base number,
//    and reset the counter (per-record numbering). Above SEQ_REWRAP_CAP chars
//    we force a 60-wide wrap so a giant paste can't spawn 100k gutter nodes.
const BASES_PER_LINE = 10;       // fallback/min line width (used when the box isn't measurable)
const SEQ_REWRAP_CAP = 30000;

function _seqLayout(raw, width) {
    const out = [], starts = [];
    let basePos = 1, pending = '';
    const flush = () => {
        for (let i = 0; i < pending.length; i += width) {
            out.push(pending.slice(i, i + width));
            starts.push(basePos + i);
        }
        basePos += pending.length;
        pending = '';
    };
    for (const line of raw.split('\n')) {
        if (line[0] === '>') { flush(); out.push(line); starts.push(null); basePos = 1; }
        else { pending += line.replace(/\s+/g, ''); }
    }
    flush();
    if (out.length === 0) { out.push(''); starts.push(1); }
    return { text: out.join('\n'), starts };
}
// Count chars that survive into the normalized text (header chars + non-
// whitespace sequence chars; newlines excluded) in raw[0, upTo) — lets us
// keep the caret on the same base across a reflow.
function _seqSig(raw, upTo) {
    let n = 0, idx = 0;
    const lines = raw.split('\n');
    for (let li = 0; li < lines.length; li++) {
        const line = lines[li], header = line[0] === '>';
        for (let ci = 0; ci < line.length; ci++) {
            if (idx >= upTo) return n;
            if (header || !/\s/.test(line[ci])) n++;
            idx++;
        }
        if (li < lines.length - 1) { if (idx >= upTo) return n; idx++; }
    }
    return n;
}
function _seqCaret(text, target) {
    if (target <= 0) return 0;
    let n = 0, idx = 0;
    const lines = text.split('\n');
    for (let li = 0; li < lines.length; li++) {
        const line = lines[li], header = line[0] === '>';
        for (let ci = 0; ci < line.length; ci++) {
            if (header || !/\s/.test(line[ci])) { n++; if (n === target) return idx + 1; }
            idx++;
        }
        if (li < lines.length - 1) idx++;
    }
    return text.length;
}
function _paintSeqGutter(gutterEl, starts) {
    if (!gutterEl) return;
    const frag = document.createDocumentFragment();
    for (let i = 0; i < starts.length; i++) {
        const s = document.createElement('span');
        s.dataset.line = i + 1;   // 1-based line — the error highlighter keys off this
        s.textContent = starts[i] === null ? '›' : starts[i];   // › marks a FASTA header
        frag.appendChild(s);
    }
    gutterEl.innerHTML = '';
    gutterEl.appendChild(frag);
}
// Measure the editor's monospace character width once (cached probe) so we can
// fit the line to the box.
let _charProbe = null;
function _monoCharWidth(font) {
    if (!_charProbe) {
        _charProbe = document.createElement('span');
        _charProbe.setAttribute('aria-hidden', 'true');
        _charProbe.style.cssText = 'position:absolute;left:-9999px;top:0;visibility:hidden;white-space:pre;padding:0;border:0;margin:0';
        document.body.appendChild(_charProbe);
    }
    _charProbe.style.font = font;
    _charProbe.textContent = 'ACGT'.repeat(25);   // 100 chars
    const w = _charProbe.getBoundingClientRect().width / 100;
    return w > 0 ? w : 0;
}
// How many bases fit on one line of THIS textarea, rounded down to a whole
// block of 10 and clamped to [10, 60]. Adapts to the device: a wide desktop
// box gets ~50–60/line, a phone ~20–30/line — so the sequence is never more
// than ~viewport-wide (no horizontal scroll) and a long gene isn't hundreds of
// 10-char lines. Falls back to BASES_PER_LINE when the box isn't laid out yet
// (hidden tab) — a later input/resize re-fits it.
function _fitBasesPerLine(ta) {
    const cs = getComputedStyle(ta);
    const avail = ta.clientWidth - (parseFloat(cs.paddingLeft) || 0) - (parseFloat(cs.paddingRight) || 0);
    if (!(avail > 0)) return BASES_PER_LINE;
    const cw = _monoCharWidth(cs.font || `${cs.fontSize} ${cs.fontFamily}`);
    if (!(cw > 0)) return BASES_PER_LINE;
    const fit = Math.floor((avail - cw) / cw);        // -1 char safety margin
    return Math.max(10, Math.min(60, Math.floor(fit / 10) * 10));
}
// Reflow a sequence textarea in place + repaint its gutter as a base ruler.
// Line width adapts to the box (multiple of 10). Returns the base count.
function reflowSeqEditor(ta, gutterEl) {
    const raw = ta.value;
    const width = raw.length > SEQ_REWRAP_CAP ? 60 : _fitBasesPerLine(ta);
    const { text, starts } = _seqLayout(raw, width);
    if (text !== raw) {
        const sig = _seqSig(raw, ta.selectionStart);
        ta.value = text;
        const pos = _seqCaret(text, sig);
        try { ta.setSelectionRange(pos, pos); } catch (e) {}
    }
    _paintSeqGutter(gutterEl, starts);
    let bases = 0;
    for (const line of text.split('\n')) if (line[0] !== '>') bases += line.length;
    return bases;
}

function renderGutter() {
    const bases = reflowSeqEditor(pasteArea, pasteGutter);
    pasteStats.textContent = bases === 0 ? '0 chars' : `${bases.toLocaleString()} chars`;
}

pasteArea.addEventListener('input', renderGutter);
pasteArea.addEventListener('scroll', () => {
    pasteGutter.scrollTop = pasteArea.scrollTop;
});
let _deGutterResizeT;
window.addEventListener('resize', () => {
    clearTimeout(_deGutterResizeT);
    _deGutterResizeT = setTimeout(renderGutter, 150);   // re-fit line width to the new box width
});
renderGutter();

// ====================================================== HASH-BASED ROUTING
// Sidebar nav links use #design / #library / #history / #docs. On hashchange
// (and on initial load), show the matching <section data-view="…"> and hide
// the others; update the sidebar active state to match. Library + History
// pages lazy-fetch their data the first time they're shown.

// Library + History routes removed 2026-05-27 — the local-filesystem
// endpoints they depended on (/api/library) were removed in audit fix C2.
// Per-user saved libraries now live on the landing site's /dashboard/
// page, backed by Supabase Storage with RLS-gated reads (task #98).
// Plasmid Editor is the workbench hub + default landing view (2026-06-04):
// 'plasmid' leads the list and is the no-hash fallback.
const ROUTES = ['plasmid', 'design', 'crispr', 'primers', 'docs'];

function currentRoute() {
    const hash = (window.location.hash || '').replace('#', '').toLowerCase();
    return ROUTES.includes(hash) ? hash : 'plasmid';
}

function showRoute(name) {
    document.querySelectorAll('[data-view]').forEach((el) => {
        el.hidden = el.dataset.view !== name;
    });
    document.querySelectorAll('.nav-item').forEach((a) => {
        const href = (a.getAttribute('href') || '').replace('#', '').toLowerCase();
        a.classList.toggle('active', href === name);
    });
    // Contextual topbar: show the current tool + a one-line description so
    // the user always knows where they are and what the tool does (replaces
    // the old static "Engine" title).
    const TOPBAR = {
        plasmid: ['Plasmid Editor',     'Map, annotate & clone your construct'],
        design:  ['Directed Evolution', 'ESM-2 variant libraries from a wild-type'],
        crispr:  ['CRISPR',             'Guide RNA design — knockout & base editing'],
        primers: ['Primer Analysis',    'Score & rank your candidate PCR primers'],
        docs:    ['Documentation',      'How TuringDNA works'],
    };
    const tb = TOPBAR[name] || ['Engine', ''];
    const tTitle = document.getElementById('topbarTitle');
    const tSub = document.getElementById('topbarSub');
    if (tTitle) tTitle.textContent = tb[0];
    if (tSub) tSub.textContent = tb[1];
    window.scrollTo({ top: 0, behavior: 'instant' });
}

window.addEventListener('hashchange', () => showRoute(currentRoute()));
showRoute(currentRoute());

// "My designs" sidebar nav item (2026-05-30). Opens the saved-designs
// modal from anywhere — no need to run a design first. Switches to the
// CRISPR route, then triggers the existing #crisprDesignsBtn handler
// (which fetches the list and routes anonymous users to the sign-in
// modal). The button lives in the hidden results card, but a programmatic
// .click() fires its listener regardless of visibility.
(function initMyDesignsNav() {
    const navMyDesigns = document.getElementById('navMyDesigns');
    if (!navMyDesigns) return;
    function open() {
        // Unified saved-work hub (all four tools). Registered by the
        // saved-hub controller below.
        if (window.TDSaved && window.TDSaved.open) window.TDSaved.open();
    }
    navMyDesigns.addEventListener('click', open);
    navMyDesigns.addEventListener('keydown', (e) => {
        if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); open(); }
    });
})();

// ─────────────────────────── THEME TOGGLE (light / dark) ──────────────────
// The initial theme is already applied by the anti-FOUC inline script in
// index.html <head> (dark by default). Here we wire the topbar button to
// flip + persist the choice.
(function initThemeToggle() {
    const btn = document.getElementById('themeToggle');
    const root = document.documentElement;
    const current = () => (root.getAttribute('data-theme') === 'light' ? 'light' : 'dark');
    function apply(theme) {
        root.setAttribute('data-theme', theme);
        try { localStorage.setItem('td-theme', theme); } catch (_) {}
        if (btn) btn.setAttribute('aria-pressed', String(theme === 'dark'));
    }
    if (btn) {
        btn.setAttribute('aria-pressed', String(current() === 'dark'));
        btn.addEventListener('click', () => apply(current() === 'dark' ? 'light' : 'dark'));
    }
})();

// ─────────────────────────── LIVING LOGO ──────────────────────────────────
// The sidebar brand mark is a closed circular plasmid that twists into a
// double helix and relaxes back — ONE continuous loop, never breaking into
// free ends (the two strands wind an integer number of turns so they always
// close). The centreline is a closed ellipse that morphs round (plasmid) ↔
// tall-and-narrow (helix). Theme-aware (re-reads --accent on theme change),
// pauses in background tabs (rAF), honours prefers-reduced-motion.
(function initPlasmidLogo() {
    let reduce = false; try { reduce = matchMedia('(prefers-reduced-motion: reduce)').matches; } catch (e) {}
    const N = 132, TURNS = 3;
    const smooth = x => { x = x < 0 ? 0 : x > 1 ? 1 : x; return x * x * (3 - 2 * x); };
    function rgba(c, a) {
        c = ('' + c).trim();
        if (c[0] === '#') { if (c.length === 4) c = '#' + c[1] + c[1] + c[2] + c[2] + c[3] + c[3]; return 'rgba(' + parseInt(c.substr(1, 2), 16) + ',' + parseInt(c.substr(3, 2), 16) + ',' + parseInt(c.substr(5, 2), 16) + ',' + a + ')'; }
        const mm = c.match(/^rgba?\(([^)]+)\)/); if (mm) return 'rgba(' + mm[1].split(',').slice(0, 3).join(',') + ',' + a + ')';
        return c;
    }
    function mount(cv) {
        const ctx = cv.getContext && cv.getContext('2d');
        if (!ctx) return;
        let W, H, DPR;
        function size() {
            const r = cv.getBoundingClientRect();
            W = r.width || 32; H = r.height || 32;
            DPR = Math.min(window.devicePixelRatio || 1, 2);
            cv.width = Math.round(W * DPR); cv.height = Math.round(H * DPR);
        }
        size(); window.addEventListener('resize', size);
        let color = '#3D3A34';
        const readColor = () => { try { color = (getComputedStyle(document.documentElement).getPropertyValue('--accent') || '#3D3A34').trim(); } catch (e) {} };
        readColor();
        try { new MutationObserver(readColor).observe(document.documentElement, { attributes: true, attributeFilter: ['data-theme'] }); } catch (e) {}
        function draw(now) {
            ctx.setTransform(DPR, 0, 0, DPR, 0, 0);
            // Choreographed morph — only ONE transformation at a time, so it
            // never tangles: hold ring → STRETCH round→tall (no twist) → TWIST
            // into helix → hold helix → untwist → unstretch. stretch shapes the
            // closed ellipse; twist scales the helical winding. period 11s.
            const t = now / 1000, period = 11, ph = (t % period) / period, TW = 0.12;
            let stretch, twist;
            if (ph < 0.10) { stretch = 0; twist = TW; }
            else if (ph < 0.32) { stretch = smooth((ph - 0.10) / 0.22); twist = TW; }
            else if (ph < 0.44) { stretch = 1; twist = TW + (1 - TW) * smooth((ph - 0.32) / 0.12); }
            else if (ph < 0.56) { stretch = 1; twist = 1; }
            else if (ph < 0.68) { stretch = 1; twist = 1 - (1 - TW) * smooth((ph - 0.56) / 0.12); }
            else if (ph < 0.90) { stretch = 1 - smooth((ph - 0.68) / 0.22); twist = TW; }
            else { stretch = 0; twist = TW; }
            const spin = t * 0.8, cx = W / 2, cy = H / 2, u = Math.min(W, H), R = u * 0.30, amp = u * 0.185;
            const a = R * (1 - 0.80 * stretch), b = R * (1 + 0.52 * stretch);
            ctx.clearRect(0, 0, W, H);
            const bb = [];
            for (let i = 0; i <= N; i++) { const s = i / N, th = 2 * Math.PI * s; bb.push([cx + a * Math.sin(th), cy - b * Math.cos(th)]); }
            const A = [], B = [], dep = [];
            for (let i = 0; i <= N; i++) {
                const p0 = bb[(i - 1 + N) % N], p1 = bb[(i + 1) % N];
                const tx = p1[0] - p0[0], ty = p1[1] - p0[1], L = Math.hypot(tx, ty) || 1, nx = -ty / L, ny = tx / L;
                const s = i / N, w = s * TURNS * 2 * Math.PI + spin, off = Math.sin(w) * amp * twist;
                A.push([bb[i][0] + nx * off, bb[i][1] + ny * off]); B.push([bb[i][0] - nx * off, bb[i][1] - ny * off]); dep.push(Math.cos(w));
            }
            ctx.lineCap = 'round'; ctx.lineJoin = 'round';
            for (let i = 4; i < N; i += 8) { ctx.strokeStyle = rgba(color, 0.22 * Math.min(1, twist * 1.6)); ctx.lineWidth = 1; ctx.beginPath(); ctx.moveTo(A[i][0], A[i][1]); ctx.lineTo(B[i][0], B[i][1]); ctx.stroke(); }
            ctx.shadowColor = color; ctx.shadowBlur = 3;
            const strand = (P, sign) => { for (let i = 0; i < N; i++) { const d = sign * dep[i], f = (d + 1) / 2; ctx.strokeStyle = rgba(color, 0.5 + 0.5 * f); ctx.lineWidth = 1.5 + 0.8 * f; ctx.beginPath(); ctx.moveTo(P[i][0], P[i][1]); ctx.lineTo(P[i + 1][0], P[i + 1][1]); ctx.stroke(); } };
            strand(B, -1); strand(A, 1); ctx.shadowBlur = 0;
        }
        // Perf: this was an UNTHROTTLED infinite rAF doing ~264 shadow-blurred
        // strokes/frame — it pegs a CPU core and spins laptop fans. Cap to
        // ~30fps and PAUSE entirely when the tab is hidden or the logo is
        // scrolled off-screen. Reduced-motion → a single static frame.
        let rafId = 0, running = false, inView = true, last = 0;
        const FRAME_MS = 1000 / 30;
        function loop(now) {
            if (!running) return;
            if (now - last >= FRAME_MS) { last = now; draw(now); }
            rafId = requestAnimationFrame(loop);
        }
        function play() { if (running || reduce) return; running = true; last = 0; rafId = requestAnimationFrame(loop); }
        function pause() { running = false; if (rafId) cancelAnimationFrame(rafId); rafId = 0; }
        if (reduce) { draw(performance.now()); return; }   // honor prefers-reduced-motion
        document.addEventListener('visibilitychange', function () {
            document.hidden ? pause() : (inView && play());
        });
        let hasIO = false;
        try {
            const io = new IntersectionObserver(function (es) {
                inView = es[0].isIntersecting;
                (inView && !document.hidden) ? play() : pause();
            }, { threshold: 0 });
            io.observe(cv); hasIO = true;
        } catch (e) {}
        if (!hasIO && !document.hidden) play();             // no IntersectionObserver → run (still capped + visibility-paused)
    }
    document.querySelectorAll('.brand-mark-canvas').forEach(mount);
})();

// ====================================================== LIBRARY + HISTORY
// Removed 2026-05-27 along with the /api/library endpoints they called
// (audit C2). Per-user saved libraries now live on the landing site's
// /dashboard/ page (task #98), backed by Supabase Storage with RLS-gated
// reads. The dead-code below previously listed files from the
// Space-shared ~/.dee/output/ directory — fine for a single-user desktop
// app, broken for a multi-tenant deployment.
const EMPTY_ICON_SVG = '';

// ====================================================== MOBILE NAV DRAWER
// On phones the sidebar is hidden off-screen by default and slides in when
// the hamburger button in the topbar is tapped. A scrim overlay covers the
// workspace while the drawer is open; tapping the scrim (or any nav-item,
// or pressing Escape) closes the drawer.
(function initMobileNavDrawer() {
    const toggle = document.getElementById('navToggle');
    const scrim = document.getElementById('sidebarScrim');
    const sidebar = document.getElementById('sidebar');
    if (!toggle || !scrim || !sidebar) return;

    function open() {
        document.body.classList.add('sidebar-open');
        toggle.setAttribute('aria-expanded', 'true');
        // Lock body scroll while the drawer is open so the page underneath
        // doesn't scroll along with momentum touches in the drawer.
        document.body.style.overflow = 'hidden';
    }
    function close() {
        document.body.classList.remove('sidebar-open');
        toggle.setAttribute('aria-expanded', 'false');
        document.body.style.overflow = '';
    }
    function isOpen() { return document.body.classList.contains('sidebar-open'); }

    toggle.addEventListener('click', () => (isOpen() ? close() : open()));
    scrim.addEventListener('click', close);

    // Tapping a nav item should navigate AND close the drawer in one motion.
    sidebar.querySelectorAll('.nav-item').forEach((item) => {
        item.addEventListener('click', () => {
            if (isOpen()) close();
        });
    });

    document.addEventListener('keydown', (e) => {
        if (e.key === 'Escape' && isOpen()) close();
    });

    // If the viewport grows past the breakpoint while the drawer is open
    // (rotation, devtools toggle), reset state so desktop layout doesn't
    // inherit a stuck `sidebar-open` class.
    const mql = window.matchMedia('(min-width: 960px)');
    const onMql = () => { if (mql.matches && isOpen()) close(); };
    if (mql.addEventListener) mql.addEventListener('change', onMql);
    else if (mql.addListener) mql.addListener(onMql);
})();

// Map a 0-indexed nucleotide position (in the cleaned/whitespace-stripped
// sequence) back to a {line, col} in the original pasted text. Mirrors what
// the engine's _clean() does: strips ANY whitespace, ignores FASTA header
// lines (those starting with ">").
function mapNtPositionToLineCol(text, ntPos) {
    let count = 0;
    let line = 1;
    let col = 1;
    let inHeader = false;
    let atLineStart = true;
    for (let i = 0; i < text.length; i++) {
        const ch = text[i];
        if (ch === '\n') {
            line++;
            col = 1;
            inHeader = false;
            atLineStart = true;
            continue;
        }
        if (atLineStart && ch === '>') inHeader = true;
        atLineStart = false;
        if (inHeader) {
            col++;
            continue;
        }
        if (/\s/.test(ch)) {
            col++;
            continue;
        }
        // ch counts toward the cleaned sequence; ntPos refers to its 0-indexed
        // position there. If we're about to consume the (ntPos)-th nucleotide,
        // that's our target.
        if (count === ntPos) {
            return { line, col, charIdx: i };
        }
        count++;
        col++;
    }
    return null;
}

function highlightPasteLine(line) {
    pasteGutter.querySelectorAll('span').forEach((s) => s.classList.remove('error-line'));
    const target = pasteGutter.querySelector(`span[data-line="${line}"]`);
    if (target) {
        target.classList.add('error-line');
        // Scroll the textarea to put the offending line in view.
        const lineHeight = parseFloat(getComputedStyle(pasteArea).lineHeight) || 20;
        const padTop = parseFloat(getComputedStyle(pasteArea).paddingTop) || 0;
        pasteArea.scrollTop = Math.max(0, (line - 3) * lineHeight) + padTop;
        pasteGutter.scrollTop = pasteArea.scrollTop;
    }
}

function clearPasteHighlight() {
    pasteGutter.querySelectorAll('span').forEach((s) => s.classList.remove('error-line'));
}

// ============================================================== INPUT

const dropzone = $('#dropzone');
const fileInput = $('#fileInput');

// NOTE: dropzone is a <label> wrapping fileInput, so clicking it natively
// triggers the file picker. Adding a manual fileInput.click() here causes the
// event to fire twice — first click opens the picker, second click closes
// it, requiring the user to click again. Trust the native label behavior.

['dragenter', 'dragover'].forEach((ev) => {
    dropzone.addEventListener(ev, (e) => {
        e.preventDefault();
        dropzone.classList.add('drag');
    });
});
['dragleave', 'drop'].forEach((ev) => {
    dropzone.addEventListener(ev, (e) => {
        e.preventDefault();
        dropzone.classList.remove('drag');
    });
});

dropzone.addEventListener('drop', (e) => {
    const file = e.dataTransfer.files[0];
    if (file) submitFile(file);
});

fileInput.addEventListener('change', (e) => {
    const file = e.target.files[0];
    if (file) submitFile(file);
});

$('#pasteSubmit').addEventListener('click', () => {
    const text = $('#pasteArea').value.trim();
    if (!text) {
        showError('Paste a sequence first.');
        return;
    }
    submitText(text, 'pasted');
});

// "Try an example" — preload GFP onto the Paste tab, ready to click "Use this
// sequence". Populate-only (no auto-run) so it behaves the same for anonymous
// trial users and signed-in researchers.
const _deExampleBtn = $('#deExampleBtn');
if (_deExampleBtn) _deExampleBtn.addEventListener('click', () => {
    clearError();
    const ta = $('#pasteArea');
    if (!ta) return;
    const pasteTab = document.querySelector('.tab[data-tab="paste"]');
    if (pasteTab) pasteTab.click();          // reveal the Paste panel
    ta.value = TD_EXAMPLE_GFP_CDS;
    ta.dispatchEvent(new Event('input', { bubbles: true }));   // refresh gutter/stats
    ta.scrollIntoView({ behavior: 'smooth', block: 'center' });
    ta.focus();
});

async function submitFile(file) {
    clearError();
    clearPasteHighlight();
    const fd = new FormData();
    fd.append('file', file);
    setDropzoneBusy(`Reading ${file.name}…`);
    try {
        const res = await fetch('/api/preview', { method: 'POST', body: fd });
        const data = await res.json();
        if (!res.ok) throw makeValidationError(data);
        handlePreview(data);
    } catch (err) {
        resetDropzone();
        showError(err.message, err.detail);
    }
}

async function submitText(text, name) {
    clearError();
    clearPasteHighlight();
    try {
        const res = await fetch('/api/preview', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ text, name }),
        });
        const data = await res.json();
        if (!res.ok) throw makeValidationError(data, text);
        // Persist the input so it survives the engine reload that happens
        // when an anonymous user gets bounced through /signin (trial timer
        // expired) and lands back on /app. Without this they lose their
        // sequence and have to re-paste. Cleared once they actually start
        // a run that completes, or when they explicitly upload a new one.
        _saveSessionResume({ pastedText: text, pastedName: name });
        handlePreview(data);
    } catch (err) {
        showError(err.message, err.detail);
    }
}

// ─── Session resume across reloads + signin bounce ────────────────────
// Why: when a trial expires mid-session, /api/run returns 402 and auth.js
// redirects the top window to /signin → user authenticates → back to /app
// → iframe reloads from scratch. Without persistence, the user's pasted
// sequence is gone and they have to paste it again — annoying, easily
// avoided.
//
// What we persist: pasted text + name only. File uploads (drag-drop) are
// not preserved — bringing back a 5 MB FASTA from localStorage doesn't
// scale. The user will see a hint to re-upload in that case.
//
// Stored in sessionStorage (per-tab) so:
//   - Resume works across iframe reloads + signin redirects
//   - Doesn't leak between tabs / browser windows
//   - Doesn't outlive the browser session
const RESUME_KEY = 'td_engine_resume';

function _saveSessionResume(payload) {
    try {
        sessionStorage.setItem(RESUME_KEY, JSON.stringify(payload));
    } catch (_) { /* private mode / quota full — silently drop */ }
}

function _readSessionResume() {
    try {
        const raw = sessionStorage.getItem(RESUME_KEY);
        if (!raw) return null;
        return JSON.parse(raw);
    } catch (_) {
        return null;
    }
}

function _clearSessionResume() {
    try { sessionStorage.removeItem(RESUME_KEY); } catch (_) {}
}

// Restore on engine boot. Fires once the DOM is ready. If we find a
// pasted sequence from a prior visit (same browser tab), drop it into
// the paste area + switch to the Paste tab so the user sees it.
// Doesn't auto-submit /api/preview — the user may want to edit first
// or pick a different option. A "We saved your sequence — pick up
// where you left off?" hint would be nicer; defer until we ship the
// dashboard.
function _maybeRestoreSessionResume() {
    const saved = _readSessionResume();
    if (!saved || !saved.pastedText) return;
    const ta = document.getElementById('pasteArea');
    if (!ta) return;
    ta.value = saved.pastedText;
    // Switch to Paste tab if it isn't already. The tab logic uses
    // .active classes on .tab and .tab-panel siblings.
    document.querySelectorAll('.tab').forEach((t) => {
        t.classList.toggle('active', t.dataset.tab === 'paste');
    });
    document.querySelectorAll('.tab-panel').forEach((p) => {
        p.classList.toggle('active', p.dataset.panel === 'paste');
    });
    // Auto-submit so the preview re-renders without an extra click —
    // matches the user expectation of "I'm back where I was".
    submitText(saved.pastedText, saved.pastedName || 'restored');
}

// Run on DOMContentLoaded; if the DOM is already past that point
// (script loaded with `defer`), fire immediately.
if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', _maybeRestoreSessionResume);
} else {
    _maybeRestoreSessionResume();
}

// Build a nicer Error object that carries server-supplied details, mapping
// a nucleotide position to a {line, col} pair when the paste textarea content
// is available so the banner can say "line 5, column 24" instead of just "nt 294".
function makeValidationError(data, pasteText) {
    const e = new Error(data.error || 'Could not parse sequence.');
    e.detail = { code: data.code, nt_position: data.nt_position };
    if (typeof data.nt_position === 'number' && pasteText) {
        const where = mapNtPositionToLineCol(pasteText, data.nt_position);
        if (where) {
            e.detail.line = where.line;
            e.detail.col = where.col;
            highlightPasteLine(where.line);
        }
    }
    return e;
}

function setDropzoneBusy(msg) {
    dropzone.querySelector('.dz-copy strong').textContent = msg;
}
function resetDropzone() {
    dropzone.querySelector('.dz-copy strong').textContent = 'Drop a sequence file here';
}

// ============================================================== PREVIEW

function handlePreview(data) {
    state.sessionId = data.session_id;
    state.preview = data;
    state.chosenCds = null;

    $('#metaIdent').textContent = data.identifier;
    $('#metaKind').textContent = data.detected_kind.replace('_', ' ');
    if (data.detected_kind === 'multi_orf') {
        const orfCount = (data.cds_options || []).length;
        $('#metaLen').textContent = `${orfCount} ORFs found`;
        $('#metaPreview').hidden = true;
    } else {
        $('#metaLen').textContent = data.protein_length
            ? `${data.protein_length} aa`
            : '—';
        $('#metaPreview').textContent = data.protein_preview;
        $('#metaPreview').hidden = false;
    }
    $('#preview').hidden = false;

    const opts = data.cds_options || [];
    if (opts.length > 1 || data.detected_kind === 'multi_orf' || data.detected_kind === 'plasmid') {
        renderCdsPicker(opts, data.detected_kind);
    } else {
        $('#cdsPicker').hidden = true;
    }

    updateRunButton();
    resetDropzone();
    // Reset BLAST UI for the new sequence; user can re-trigger if they want.
    const idPanel = document.getElementById('identifyPanel');
    if (idPanel) { idPanel.hidden = true; idPanel.innerHTML = ''; }
    bindIdentifyButton();
}

function renderCdsPicker(options, detectedKind) {
    const list = $('#cdsList');
    list.innerHTML = '';
    const markerPattern = /\b(aph|neo|npt|kan|bla|amp|cat|cmr|chlor|tet|hph|hyg|ble|zeo|pac|puro|sm|sptr|aada)\b/i;

    if (!options.length) {
        $('#cdsPicker').hidden = true;
        return;
    }

    const isOrf = detectedKind === 'multi_orf';

    // Update the picker's heading + hint to match what we found.
    const heading = $('#cdsPicker').querySelector('h3');
    const hint = $('#cdsPicker').querySelector('.muted');
    if (isOrf) {
        heading.textContent = `${options.length} open reading frames detected — pick one to evolve`;
        hint.textContent = "No annotated CDS features (you pasted raw DNA). I scanned all 6 reading frames for ATG…stop ORFs ≥ 50 aa. Picking the longest is usually right, but check the frame.";
    } else {
        heading.textContent = 'Multiple CDS features detected — pick the gene to evolve';
        hint.textContent = 'The longest CDS in a plasmid is usually the antibiotic resistance gene. Pick your gene of interest.';
    }

    // Default selection: longest non-marker, falling back to longest overall.
    const ranked = [...options].sort((a, b) => b.length_nt - a.length_nt);
    const nonMarker = ranked.find((o) => !markerPattern.test(o.label));
    const defaultPick = nonMarker || ranked[0];
    state.chosenCds = defaultPick.label;

    ranked.forEach((opt) => {
        const aa = opt.protein_length != null
            ? opt.protein_length
            : Math.max(0, Math.floor(opt.length_nt / 3) - 1);
        const frameLabel = opt.frame
            ? `frame ${opt.frame > 0 ? '+' : ''}${opt.frame} · `
            : '';
        const item = document.createElement('div');
        item.className = 'cds-item';
        if (markerPattern.test(opt.label)) item.classList.add('marker');
        if (opt.label === state.chosenCds) item.classList.add('selected');
        item.innerHTML = `
            <span class="cds-name">${escapeHtml(opt.label)}</span>
            <span class="cds-length">${frameLabel}${opt.length_nt} nt · ${aa} aa</span>
        `;
        item.addEventListener('click', () => {
            state.chosenCds = opt.label;
            $$('.cds-item').forEach((el) => el.classList.remove('selected'));
            item.classList.add('selected');
            updateRunButton();
        });
        list.appendChild(item);
    });

    $('#cdsPicker').hidden = false;
}

// ============================================================== RUN

function updateRunButton() {
    const btn = $('#runBtn');
    if (state.sessionId) {
        btn.disabled = false;
        btn.querySelector('.primary-sub').textContent =
            state.preview.detected_kind === 'plasmid'
                ? `Will evolve "${state.chosenCds || 'auto'}"`
                : `${state.preview.protein_length} aa · ESM-2 → SA → reverse-translate`;
    } else {
        btn.disabled = true;
        btn.querySelector('.primary-sub').textContent = 'Click after loading a sequence';
    }
}

$('#runBtn').addEventListener('click', startRun);

/**
 * Render shimmer placeholders inside the results card while the pipeline
 * is running. The skeleton lives directly inside the existing
 * .result-table-wrap so the layout doesn't jump when real data lands —
 * we just replace the <table> with the actual sortable variant table.
 *
 * Eight skeleton rows is enough to fill the typical first-screen height
 * without scrolling; if the user's k > 8, real rows will extend below.
 * The empty stats strip + run-meta + table toolbar stay hidden during
 * skeleton state so the user's focus is on the loading region itself.
 */
function renderSkeletonResultsTable() {
    const card = $('#resultsCard');
    if (!card) return;
    card.hidden = false;
    // Hide the toolbar, stats strip, and run meta — they'd render empty
    // and look broken next to the live skeleton.
    const toolbar = card.querySelector('.table-toolbar');
    const strip = document.getElementById('statsStrip');
    const meta = document.getElementById('runMeta');
    if (toolbar) toolbar.style.visibility = 'hidden';
    if (strip) strip.hidden = true;
    if (meta) meta.hidden = true;

    const wrap = card.querySelector('.result-table-wrap');
    if (!wrap) return;
    // Build 8 skeleton rows. The CSS .skeleton class supplies the shimmer
    // animation; we just need a grid of placeholder bars in the right
    // shape so the layout feels stable.
    const rows = Array.from({ length: 8 }, () => `
        <div class="skeleton-row">
            <div class="skeleton" style="width: 32px"></div>
            <div class="skeleton" style="width: 80%"></div>
            <div class="skeleton" style="width: 40px"></div>
            <div class="skeleton" style="width: 36px"></div>
            <div class="skeleton" style="width: 40px"></div>
            <div class="skeleton" style="width: 44px"></div>
            <div class="skeleton" style="width: 60px"></div>
        </div>
    `).join('');
    wrap.innerHTML = `<div class="skeleton-table" aria-label="Building variant library…">${rows}</div>`;
}

/**
 * Reverse of the above — when real results are about to render, restore
 * the real <table> structure and un-hide the toolbar / stats / meta.
 * Called from renderResults before the first row is appended.
 */
function teardownSkeleton() {
    const card = $('#resultsCard');
    if (!card) return;
    const wrap = card.querySelector('.result-table-wrap');
    if (!wrap) return;
    const isSkeleton = wrap.querySelector('.skeleton-table');
    if (!isSkeleton) return;
    // Rebuild the real <table> shell. renderVariantRows will populate <tbody>.
    wrap.innerHTML = `
        <table class="result-table" id="resultTable">
            <thead>
                <tr>
                    <th class="sortable" data-sort="rank" title="Rank by predicted fitness (1 = best).">Rank <span class="sort-ind">↕</span></th>
                    <th class="sortable" data-sort="mutations" title="Substitutions vs. the wild-type protein, in the format WT_aa-position-new_aa.">Mutations <span class="sort-ind">↕</span></th>
                    <th class="num sortable" data-sort="fitness" title="Cumulative ΣΔLL from ESM-2: sum of log-likelihood improvements over WT across all substitutions in this variant.">Fitness <span class="sort-ind">↕</span></th>
                    <th class="num sortable" data-sort="gc" title="GC content of the codon-optimized DNA, %.">GC% <span class="sort-ind">↕</span></th>
                    <th class="num sortable" data-sort="tm" title="Lower of the two primer Tm values (°C).">Tm (°C) <span class="sort-ind">↕</span></th>
                    <th class="num sortable" data-sort="length" title="Length of the codon-optimized DNA, bp.">bp <span class="sort-ind">↕</span></th>
                    <th class="row-actions-h"></th>
                </tr>
            </thead>
            <tbody></tbody>
        </table>
    `;
    const toolbar = card.querySelector('.table-toolbar');
    const strip = document.getElementById('statsStrip');
    if (toolbar) toolbar.style.visibility = '';
    if (strip) strip.hidden = false;
}

async function startRun() {
    if (!state.sessionId) return;
    clearError();
    // Show the results card immediately with a skeleton table so the user
    // sees something taking shape during the 30-90s pipeline run, not just
    // a progress bar and an empty void below it. Real rows replace the
    // skeleton when /api/result returns.
    renderSkeletonResultsTable();
    $('#progressShell').hidden = false;
    $('#runBtn').disabled = true;
    setProgress(0.02, 'Starting…', 'Queued.');

    const settings = {
        k: parseInt($('#settingK').value, 10),
        max_mutations: parseInt($('#settingMax').value, 10),
        percentile: parseFloat($('#settingPct').value),
        host: $('#settingHost').value,
        model: $('#settingModel').value,
    };

    const body = {
        session_id: state.sessionId,
        cds_feature: state.chosenCds,
        settings,
    };

    try {
        const res = await fetch('/api/run', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify(body),
        });
        const data = await res.json();
        if (!res.ok) {
            // Audit M7: special-case the "needs_cds_choice" response so
            // the user sees the chooser they didn't pick from, not just
            // a generic error toast. The server returned 400 + the
            // existing cds_options list — we re-render the CDS chooser
            // and scroll it into view so the user can pick one and retry.
            if (data.kind === 'needs_cds_choice' && Array.isArray(data.cds_options)) {
                if (typeof renderCdsChooser === 'function') {
                    renderCdsChooser({ cds_options: data.cds_options });
                }
                const chooser = document.getElementById('cdsChooser');
                if (chooser) chooser.scrollIntoView({ behavior: 'smooth', block: 'center' });
                $('#runBtn').disabled = false;
                showError('Pick which CDS to design against — auto-selection is disabled to avoid silently designing the wrong gene.');
                return;
            }
            throw new Error(data.error || 'Could not start run.');
        }
        state.jobId = data.job_id;
        state.pollErrors = 0;
        state.pollStart = Date.now();
        pollStatus();
    } catch (err) {
        $('#runBtn').disabled = false;
        showError(err.message);
    }
}

function pollStatus() {
    if (state.pollHandle) clearTimeout(state.pollHandle);
    state.pollHandle = setTimeout(async () => {
        try {
            // Overall wall-clock ceiling: a job stuck mid-"scoring" (e.g. the
            // worker died without setting status=error) shouldn't spin forever.
            if (state.pollStart && (Date.now() - state.pollStart) > MAX_POLL_MS) {
                state.pollHandle = null;
                $('#runBtn').disabled = false;
                $('#progressShell').hidden = true;
                showError(
                    'This run is taking longer than expected and may be stuck. ' +
                    'Click “Design library” to start a fresh run.'
                );
                return;
            }
            const res = await fetch(`/api/status/${state.jobId}`);

            // 404 means the backend doesn't know about this job — usually
            // because the HF Space rebuilt and dropped its in-memory job
            // dict. Stop polling and tell the user to start fresh rather
            // than crashing on a malformed response.
            if (res.status === 404) {
                state.pollHandle = null;
                $('#runBtn').disabled = false;
                $('#progressShell').hidden = true;
                showError(
                    'Connection to your job was lost (server restarted). ' +
                    'Click "Design library" to start a fresh run.'
                );
                return;
            }

            // Treat any other non-2xx as a transient blip — let the catch
            // block below handle reconnection. parsing the response body
            // as JSON for a 5xx would normally throw a SyntaxError; we
            // skip that path entirely.
            if (!res.ok) {
                throw new Error(`status ${res.status}`);
            }

            const data = await res.json();
            state.pollErrors = 0;   // a clean response resets the failure streak

            // Defensive guards: every field on the status payload can
            // legally be missing during the brief window between when
            // we enqueue a job and when the worker thread populates the
            // JobState. Read with fallbacks so the UI never crashes.
            const status   = data.status || 'queued';
            const progress = typeof data.progress === 'number' ? data.progress : 0;
            const elapsed  = (typeof data.elapsed_seconds === 'number')
                ? data.elapsed_seconds.toFixed(1)
                : '0.0';

            setProgress(
                progress,
                `${capitalize(status)} · ${elapsed}s`,
                data.message || '',
            );

            if (status === 'done') {
                await loadResults();
            } else if (status === 'error') {
                $('#runBtn').disabled = false;
                showError(data.error || data.message || 'The pipeline failed.');
                $('#progressShell').hidden = true;
                // Pull the skeleton table down too — leaving shimmer running
                // next to an error message reads as "still loading" and is
                // confusing. Hide the whole results card; the user will
                // re-run with adjusted settings.
                const card = $('#resultsCard');
                if (card) card.hidden = true;
            } else {
                pollStatus();
            }
        } catch (err) {
            // Transient network blip or a momentary 5xx during HF Space
            // GPU-warming. Don't show a panicky "Lost connection" banner
            // for every dropped poll — just back off and retry. If the
            // disconnection persists, the user will notice the progress
            // bar isn't moving and can reload.
            console.warn('[poll] transient error, retrying:', err?.message || err);
            state.pollErrors = (state.pollErrors || 0) + 1;
            if (state.pollErrors >= MAX_POLL_ERRORS) {
                state.pollHandle = null;
                $('#runBtn').disabled = false;
                $('#progressShell').hidden = true;
                showError(
                    'The engine isn’t responding — it may be waking from sleep or restarting. ' +
                    'Wait a few seconds, then click “Design library” to retry.'
                );
                return;
            }
            pollStatus();
        }
    }, 800);
}

function setProgress(frac, status, message) {
    $('#progressFill').style.width = `${Math.max(2, Math.min(100, frac * 100))}%`;
    $('#progressStatus').textContent = status;
    $('#progressElapsed').textContent = '';
    $('#progressMessage').textContent = message || '';
}

// ============================================================== RESULTS

async function loadResults() {
    try {
        const res = await fetch(`/api/result/${state.jobId}`);
        const data = await res.json();
        if (!res.ok) throw new Error(data.error || 'Could not fetch results.');
        renderResults(data);
        $('#progressShell').hidden = true;
        $('#runBtn').disabled = false;
    } catch (err) {
        showError(err.message);
    }
}

// Sort + filter state for the variant table. Re-rendered any time the user
// clicks a header or types into the filter input.
const tableState = {
    sortKey: 'rank',
    sortDir: 'asc',
    filter: '',
    variants: [],     // canonical (unsorted) copy
    wtProtein: '',    // needed for the diff view
};

// ───────────────────────── LEARNING FLYWHEEL (round 2) ─────────────────────
// Log measured fitness for the variants you tested → fit a surrogate on the
// server → propose a data-conditioned round-2 library (Design→Build→Test→Learn).
function _renderRound2Panel(data) {
    const panel = document.getElementById('round2Panel');
    const list = document.getElementById('round2List');
    if (!panel || !list) return;
    const evolved = (data.variants || []).filter((v) => v.Variant_ID !== 'WT').slice(0, 60);
    if (!evolved.length) { panel.hidden = true; return; }
    list.innerHTML = evolved.map((v) => {
        const mut = v.Mutations_AA || '';
        return `<label class="round2-row">
            <span class="r2-id">${escapeHtml(v.Variant_ID || '')}</span>
            <span class="r2-mut">${escapeHtml(mut || '(wild-type-like)')}</span>
            <input class="r2-val" type="number" step="any" inputmode="decimal"
                   data-mut="${escapeHtml(mut)}" placeholder="measured"
                   aria-label="measured value for ${escapeHtml(v.Variant_ID || '')}">
        </label>`;
    }).join('');
    const st = document.getElementById('round2Status');
    if (st) { st.hidden = true; st.textContent = ''; }
    panel.hidden = false;
}

function _collectRound2Measurements() {
    const out = [];
    document.querySelectorAll('#round2List .r2-val').forEach((inp) => {
        const raw = (inp.value || '').trim();
        if (raw === '') return;
        const num = parseFloat(raw);
        if (!isFinite(num)) return;
        out.push({ mutations: inp.getAttribute('data-mut') || '', measured_value: num, outcome: 'measured' });
    });
    return out;
}

function _round2Status(msg, kind) {
    const st = document.getElementById('round2Status');
    if (!st) return;
    st.hidden = false;
    st.textContent = msg;
    st.className = 'round2-status' + (kind ? ' round2-status-' + kind : '');
}

(function initRound2() {
    const btn = document.getElementById('round2Btn');
    const saveBtn = document.getElementById('round2SaveBtn');
    if (btn) btn.addEventListener('click', async () => {
        const data = state.lastRun || {};
        const meas = _collectRound2Measurements();
        if (!meas.length) { _round2Status('Enter a measured value for at least one variant you tested.', 'warn'); return; }
        const orig = btn.textContent; btn.disabled = true; btn.textContent = 'Designing round 2…';
        _round2Status(`Scoring and learning from your ${meas.length} result${meas.length === 1 ? '' : 's'}…`);
        try {
            const res = await fetch('/api/de/round2', {
                method: 'POST', headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({
                    library_id: data.library_id || '',
                    wt_protein: data.wt_protein || '',
                    wt_identifier: data.wt_identifier || '',
                    settings: data.settings_used || {},
                    measurements: meas,
                }),
            });
            const j = await res.json();
            if (res.status === 403) { window.dispatchEvent(new Event('td:signin-required')); _round2Status('Sign in to use round 2.', 'warn'); return; }
            if (!j.ok) { _round2Status(j.error || 'Round 2 failed.', 'warn'); return; }
            renderResults(j);   // renders the round-2 library + the "Round 2" banner
            const card = document.getElementById('resultsCard');
            if (card) card.scrollIntoView({ behavior: 'smooth', block: 'start' });
        } catch (e) { _round2Status('Round 2 failed — please try again.', 'warn'); }
        finally { btn.disabled = false; if (btn.textContent === 'Designing round 2…') btn.textContent = orig; }
    });
    if (saveBtn) saveBtn.addEventListener('click', async () => {
        const data = state.lastRun || {};
        if (!data.library_id) { _round2Status('Results are saved against a library — sign in and run a design first.', 'warn'); return; }
        const meas = _collectRound2Measurements();
        const orig = saveBtn.textContent; saveBtn.disabled = true; saveBtn.textContent = 'Saving…';
        try {
            const res = await fetch('/api/de/outcomes', {
                method: 'POST', headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ library_id: data.library_id, outcomes: meas }),
            });
            const j = await res.json();
            if (res.status === 403) { window.dispatchEvent(new Event('td:signin-required')); return; }
            if (j.ok) { saveBtn.textContent = 'Saved ✓'; setTimeout(() => { saveBtn.textContent = orig; }, 1500); }
            else { _round2Status(j.error || 'Could not save your results.', 'warn'); }
        } catch (e) { _round2Status('Could not save your results.', 'warn'); }
        finally { saveBtn.disabled = false; if (saveBtn.textContent === 'Saving…') saveBtn.textContent = orig; }
    });
})();

function renderResults(data) {
    const card = $('#resultsCard');
    card.hidden = false;
    // Swap the skeleton placeholder for the real table shell BEFORE we
    // render rows; otherwise renderVariantRows would write tbody.innerHTML
    // into the skeleton wrapper and the rows wouldn't appear in a real
    // table layout.
    if (typeof teardownSkeleton === 'function') teardownSkeleton();
    const empty = document.getElementById('emptyState');
    if (empty) empty.hidden = true;

    // Audit H2: /api/result no longer returns server filesystem paths
    // (csv_path / desktop_path). Library is downloaded via /api/download
    // and, for signed-in users, also persisted to Supabase Storage.
    const evolvedCount = (data.variants || []).filter(v => v.Variant_ID !== 'WT').length;
    const hasWt = (data.variants || []).some(v => v.Variant_ID === 'WT');
    $('#resultSummary').innerHTML =
        `<strong>${evolvedCount}</strong> variants${hasWt ? ' + wild type' : ''} of <strong>${escapeHtml(data.wt_identifier)}</strong> · ${data.wt_protein.length} aa · ready to download`;

    // Learning flywheel: remember this run + (re)build the round-2 panel.
    state.lastRun = data;
    _renderRound2Panel(data);
    const _r2b = $('#round2Banner');
    if (_r2b) {
        if (data.round === 2 && data.surrogate) {
            _r2b.hidden = false;
            _r2b.innerHTML = `<strong>Round 2.</strong> ${escapeHtml(data.surrogate.note || 'Designed from your logged bench results.')}`;
        } else { _r2b.hidden = true; _r2b.innerHTML = ''; }
    }

    renderStatsStrip(data);
    renderMutationMap(data);
    renderRunMeta(data);

    tableState.variants = data.variants || [];
    tableState.wtProtein = data.wt_protein || '';
    tableState.sortKey = 'rank';
    tableState.sortDir = 'asc';
    tableState.filter = '';
    const filterEl = document.getElementById('variantFilter');
    if (filterEl) filterEl.value = '';
    wireTableControls();
    renderVariantRows();

    // navLibCount badge was removed from the sidebar 2026-05-27 along with
    // the Library tab. Leaving the lookup as a defensive no-op so any
    // future re-introduction of a counter is one selector change away.

    wireDownloadMenu();

    card.scrollIntoView({ behavior: 'smooth', block: 'start' });
}

// ---- Sort / filter / render -------------------------------------------------

const COL_SORT = {
    rank:      v => Number(v.Variant_ID.replace(/[^0-9]/g, '')) || 0,
    mutations: v => (v.Mutations_AA || '').split(',').filter(Boolean).length,
    fitness:   v => Number(v.Predicted_Fitness_Score) || 0,
    gc:        v => Number(v.GC_Percent) || 0,
    tm:        v => Math.min(Number(v.Primer_Fwd_Tm_C) || Infinity, Number(v.Primer_Rev_Tm_C) || Infinity),
    bp:        v => Number(v.Length_bp) || 0,
};

function wireTableControls() {
    // Sort handlers (once).
    document.querySelectorAll('.result-table th.sortable').forEach((th) => {
        if (th.dataset.wired === '1') return;
        th.dataset.wired = '1';
        th.addEventListener('click', () => {
            const key = th.dataset.sort;
            if (tableState.sortKey === key) {
                tableState.sortDir = tableState.sortDir === 'asc' ? 'desc' : 'asc';
            } else {
                tableState.sortKey = key;
                tableState.sortDir = key === 'fitness' ? 'desc' : 'asc';
            }
            renderVariantRows();
        });
    });

    // Filter handler (once).
    const filterEl = document.getElementById('variantFilter');
    const clearEl  = document.getElementById('filterClear');
    if (filterEl && filterEl.dataset.wired !== '1') {
        filterEl.dataset.wired = '1';
        filterEl.addEventListener('input', (e) => {
            tableState.filter = e.target.value.trim().toLowerCase();
            if (clearEl) clearEl.hidden = tableState.filter.length === 0;
            renderVariantRows();
        });
    }
    if (clearEl && clearEl.dataset.wired !== '1') {
        clearEl.dataset.wired = '1';
        clearEl.addEventListener('click', () => {
            tableState.filter = '';
            if (filterEl) { filterEl.value = ''; filterEl.focus(); }
            clearEl.hidden = true;
            renderVariantRows();
        });
    }
}

function variantMatchesFilter(v, filter) {
    if (!filter) return true;
    const fields = [
        v.Variant_ID || '',
        v.Mutations_AA || '',
        String(v.GC_Percent ?? ''),
        String(v.Length_bp ?? ''),
    ].join(' ').toLowerCase();
    // Numeric range filter: "gc>50" / "gc<60" / "tm>58"
    const rangeMatch = filter.match(/^(gc|tm|fitness|bp)\s*(>|<|>=|<=|=)\s*(-?\d+(?:\.\d+)?)$/);
    if (rangeMatch) {
        const [, col, op, valStr] = rangeMatch;
        const val = parseFloat(valStr);
        const getter = { gc: 'GC_Percent', tm: 'Primer_Fwd_Tm_C', fitness: 'Predicted_Fitness_Score', bp: 'Length_bp' }[col];
        const actual = Number(v[getter]);
        if (!Number.isFinite(actual)) return false;
        return { '>': actual > val, '<': actual < val, '>=': actual >= val, '<=': actual <= val, '=': actual === val }[op];
    }
    return fields.includes(filter);
}

function renderVariantRows() {
    const tbody = document.querySelector('#resultTable tbody');
    if (!tbody) return;

    // Update sort indicators in column headers.
    document.querySelectorAll('.result-table th.sortable').forEach((th) => {
        const ind = th.querySelector('.sort-ind');
        if (!ind) return;
        if (th.dataset.sort === tableState.sortKey) {
            th.classList.add('sort-active');
            ind.textContent = tableState.sortDir === 'asc' ? '↑' : '↓';
        } else {
            th.classList.remove('sort-active');
            ind.textContent = '↕';
        }
    });

    const isWt = (v) => v.Variant_ID === 'WT';
    const filtered = tableState.variants.filter(v => variantMatchesFilter(v, tableState.filter));
    const sorter = COL_SORT[tableState.sortKey] || COL_SORT.rank;
    const dir = tableState.sortDir === 'asc' ? 1 : -1;
    // WT is always pinned to row 0, regardless of the chosen sort column. The
    // user-driven sort applies only to the evolved variants below it.
    const wtRow    = filtered.find(isWt);
    const evolved  = filtered.filter(v => !isWt(v));
    evolved.sort((a, b) => {
        const av = sorter(a), bv = sorter(b);
        if (typeof av === 'string') return av.localeCompare(bv) * dir;
        return (av - bv) * dir;
    });
    const sorted = wtRow ? [wtRow, ...evolved] : evolved;

    // Counter readout. WT is shown separately so the user sees how many
    // evolved variants the library contains.
    const counter = document.getElementById('tableCount');
    if (counter) {
        const evolvedTotal = tableState.variants.filter(v => !isWt(v)).length;
        const evolvedShown = sorted.filter(v => !isWt(v)).length;
        const wtSuffix = wtRow ? ' + WT' : '';
        counter.textContent = evolvedShown === evolvedTotal
            ? `${evolvedTotal} variants${wtSuffix}`
            : `${evolvedShown} of ${evolvedTotal} variants${wtSuffix}`;
    }

    tbody.innerHTML = '';
    sorted.forEach((v, idx) => {
        const tr = document.createElement('tr');
        const wt = isWt(v);
        // Row-level red border + chip when the variant still has
        // unresolvable forbidden restriction sites — gives the user an
        // at-a-glance signal in the table view before they ever expand
        // the detail panel. Detail panel has the full explanation.
        const reUnresolvedRow = Number(v.Restriction_Sites_Unresolved) || 0;
        const baseClass = wt ? 'expandable variant-wt-row' : 'expandable';
        tr.className = reUnresolvedRow > 0
            ? `${baseClass} variant-row-re-warn`
            : baseClass;
        const gc = Number(v.GC_Percent);
        const gcOutOfRange = !Number.isNaN(gc) && (gc < 40 || gc > 60);
        const minTm = Math.min(
            Number(v.Primer_Fwd_Tm_C) || Infinity,
            Number(v.Primer_Rev_Tm_C) || Infinity,
        );
        const tmDisplay = Number.isFinite(minTm) ? minTm.toFixed(1) : '—';
        // Audit H5: a WT_Error sentinel means the server couldn't build the
        // WT pseudo-row (codon optimization or RE-site scrub failed on the
        // user's protein). Render an explicit error badge instead of the
        // normal "wild type" badge so the user knows their reference sample
        // is missing AND why, rather than silently noticing later that the
        // WT row has empty DNA.
        const mutHtml = wt
            ? (v.WT_Error
                ? `<span class="wt-badge wt-badge-error" title="${escapeHtml(v.WT_Error)}">WT BUILD FAILED</span>`
                : '<span class="wt-badge" title="Unmutated wild-type sequence — order this to baseline alongside the evolved library.">wild type</span>')
            : renderMutationTokens(v.Mutations_AA || '');
        const fitnessCell = wt ? '<span class="muted">—</span>' : Number(v.Predicted_Fitness_Score).toFixed(3);
        const idCell = wt
            ? `<span class="rank-wt">WT</span>`
            : escapeHtml(v.Variant_ID);
        tr.innerHTML = `
            <td class="rank">${idCell}</td>
            <td class="mutations">${mutHtml}</td>
            <td class="num">${fitnessCell}</td>
            <td class="num">${Number.isNaN(gc) ? '—' : gc.toFixed(1)}${gcOutOfRange ? '<span class="gc-warn">!</span>' : ''}</td>
            <td class="num">${tmDisplay}</td>
            <td class="num">${escapeHtml(String(v.Length_bp ?? '—'))}</td>
            <td class="row-actions">
                ${(() => {
                    // Two structure engines, side by side:
                    //  • ESMFold folds THIS exact variant, but its free public
                    //    endpoint caps at ~400 aa — so it's pre-gated (disabled
                    //    with a tooltip) for longer proteins instead of dead-
                    //    ending on click.
                    //  • AlphaFold has NO length cap, but can't fold a novel
                    //    sequence: it shows the closest KNOWN structure found by
                    //    BLAST → AlphaFold-DB. That makes it the path for large
                    //    proteins ESMFold can't handle, so we flag it as such.
                    const aaLen = (v.Mutant_AA_Seq || '').length;
                    const tooLong = aaLen > ESMFOLD_MAX_RES;
                    const esm = tooLong
                        ? `<button class="fold-btn ghost-btn fold-btn-disabled" data-idx="${idx}" type="button"
                                  disabled aria-label="Sequence too long for ESMFold"
                                  title="ESMFold folds the exact variant but its free endpoint caps at ${ESMFOLD_MAX_RES} aa (this protein is ${aaLen} aa). Use AlphaFold → for larger proteins.">ESMFold</button>`
                        : `<button class="fold-btn ghost-btn" data-idx="${idx}" type="button"
                                  aria-label="Fold this exact variant with ESMFold (≤${ESMFOLD_MAX_RES} aa)"
                                  title="ESMFold · folds this exact variant (≤${ESMFOLD_MAX_RES} aa)">ESMFold</button>`;
                    const af = `<button class="alphafold-btn ghost-btn${tooLong ? ' alphafold-btn-suggested' : ''}" data-idx="${idx}" type="button"
                                  aria-label="Closest known structure via AlphaFold-DB — no length cap, best for large proteins"
                                  title="AlphaFold · closest known structure (BLAST → AlphaFold-DB). No length cap — the path for proteins too large for ESMFold.">AlphaFold</button>`;
                    return esm + af;
                })()}
                <button class="expand-toggle" data-idx="${idx}" aria-label="Show PCR details">›</button>
            </td>
        `;
        // --row-i feeds the staggered fade-in animation in app.css. The CSS
        // caps the multiplier at 20 so libraries with hundreds of rows
        // don't take 5 seconds to finish appearing.
        tr.style.setProperty('--row-i', String(idx));
        tbody.appendChild(tr);

        const detail = document.createElement('tr');
        detail.className = 'detail-row';
        detail.hidden = true;
        detail.innerHTML = `<td colspan="7"></td>`;
        detail.dataset.populated = '0';
        tbody.appendChild(detail);

        tr.addEventListener('click', (e) => {
            // The :not(.expand-toggle) filter already skips the Fold button
            // (it's not .expand-toggle), so the row's expand/collapse only
            // fires for empty-cell clicks. Fold has its own handler below.
            if (e.target.matches('a, button:not(.expand-toggle), input, select')) return;
            toggleDetailRow(idx, tr, detail, v);
        });

        // Per-row Fold button → ESMFold modal. stopPropagation keeps the
        // row click from also expanding the detail panel.
        const foldBtn = tr.querySelector('.fold-btn');
        if (foldBtn) {
            foldBtn.addEventListener('click', (e) => {
                e.stopPropagation();
                openFoldModal(v);
            });
        }
        // Per-row AlphaFold button → closest-known-structure modal (BLAST →
        // AlphaFold-DB). The structure path for proteins too large for ESMFold.
        const afBtn = tr.querySelector('.alphafold-btn');
        if (afBtn) {
            afBtn.addEventListener('click', (e) => {
                e.stopPropagation();
                openAlphaFoldModal(v);
            });
        }
    });
}

// ---- BLOSUM62 mutation classification --------------------------------------
// Minimal BLOSUM62 substitution lookup. Used to color each X→Y substitution:
//   ≥ 0  → conservative (chemically similar AA)
//   -1 to -2 → moderate
//   ≤ -3 → drastic (e.g., D→W)
const BLOSUM62 = (() => {
    const aas = 'ARNDCQEGHILKMFPSTWYV';
    // Standard BLOSUM62 matrix, 20×20, indexed by aas above.
    const rows = [
        " 4-1-2-2 0-1-1 0-2-1-1-1-1-2-1 1 0-3-2 0", // A
        "-1 5 0-2-3 1 0-2 0-3-2 2-1-3-2-1-1-3-2-3", // R
        "-2 0 6 1-3 0 0 0 1-3-3 0-2-3-2 1 0-4-2-3", // N
        "-2-2 1 6-3 0 2-1-1-3-4-1-3-3-1 0-1-4-3-3", // D
        " 0-3-3-3 9-3-4-3-3-1-1-3-1-2-3-1-1-2-2-1", // C
        "-1 1 0 0-3 5 2-2 0-3-2 1 0-3-1 0-1-2-1-2", // Q
        "-1 0 0 2-4 2 5-2 0-3-3 1-2-3-1 0-1-3-2-2", // E
        " 0-2 0-1-3-2-2 6-2-4-4-2-3-3-2 0-2-2-3-3", // G
        "-2 0 1-1-3 0 0-2 8-3-3-1-2-1-2-1-2-2 2-3", // H
        "-1-3-3-3-1-3-3-4-3 4 2-3 1 0-3-2-1-3-1 3", // I
        "-1-2-3-4-1-2-3-4-3 2 4-2 2 0-3-2-1-2-1 1", // L
        "-1 2 0-1-3 1 1-2-1-3-2 5-1-3-1 0-1-3-2-2", // K
        "-1-1-2-3-1 0-2-3-2 1 2-1 5 0-2-1-1-1-1 1", // M
        "-2-3-3-3-2-3-3-3-1 0 0-3 0 6-4-2-2 1 3-1", // F
        "-1-2-2-1-3-1-1-2-2-3-3-1-2-4 7-1-1-4-3-2", // P
        " 1-1 1 0-1 0 0 0-1-2-2 0-1-2-1 4 1-3-2-2", // S
        " 0-1 0-1-1-1-1-2-2-1-1-1-1-2-1 1 5-2-2 0", // T
        "-3-3-4-4-2-2-3-2-2-3-2-3-1 1-4-3-2 11 2-3", // W
        "-2-2-2-3-2-1-2-3 2-1-1-2-1 3-3-2-2 2 7-1", // Y
        " 0-3-3-3-1-2-2-3-3 3 1-2 1-1-2-2 0-3-1 4", // V
    ];
    const m = {};
    for (let i = 0; i < aas.length; i++) {
        // Parse each row of width-3 fixed fields including sign.
        const raw = rows[i];
        const cells = [];
        for (let j = 0; j < 20; j++) {
            cells.push(parseInt(raw.slice(j * 3, j * 3 + 3).trim(), 10));
        }
        for (let j = 0; j < aas.length; j++) {
            m[aas[i] + aas[j]] = cells[j];
        }
    }
    return m;
})();

function blosumScore(wt, mut) {
    return BLOSUM62[wt + mut] ?? 0;
}

function classifyMutation(wt, mut) {
    const s = blosumScore(wt, mut);
    if (s >= 0) return 'mut-cons';
    if (s >= -2) return 'mut-mod';
    return 'mut-drastic';
}

function renderMutationTokens(mutString) {
    if (!mutString) return '';
    return mutString.split(',').map((raw) => {
        const m = raw.trim().match(/^([A-Z])(\d+)([A-Z\*])$/);
        if (!m) return `<span class="mut-token mut-cons">${escapeHtml(raw)}</span>`;
        const [, wt, pos, mut] = m;
        const klass = classifyMutation(wt, mut);
        const s = blosumScore(wt, mut);
        const tip = `BLOSUM62 ${wt}→${mut} = ${s} (${
            s >= 0 ? 'conservative' : s >= -2 ? 'moderate' : 'drastic'
        })`;
        return `<span class="mut-token ${klass}" title="${escapeHtml(tip)}">${escapeHtml(raw)}</span>`;
    }).join('');
}

function toggleDetailRow(idx, headRow, detailRow, v) {
    const open = !detailRow.hidden;
    const toggle = headRow.querySelector('.expand-toggle');
    if (open) {
        detailRow.hidden = true;
        toggle.classList.remove('open');
        return;
    }
    if (detailRow.dataset.populated !== '1') {
        detailRow.querySelector('td').innerHTML = renderDetailPanel(v);
        wireCopyButtons(detailRow);
        wireCloningControls(detailRow);
        wireDnaEdit(detailRow, v);
        detailRow.dataset.populated = '1';
    }
    detailRow.hidden = false;
    toggle.classList.add('open');
}

// Catalog of synthesis vendors the "Synthesize DNA" button can redirect to.
// User selects one in the Results-card header; choice persists in
// localStorage so it sticks across page loads and across runs.
// Vendor URLs pinned to each company's homepage rather than a deep
// gene-synthesis path. Vendor sites reorganize their product pages often
// enough that deep links break (e.g. genscript.com/gene-synthesis.html now
// 404s); homepages are durable, and the user already has the sequence on
// the clipboard so one extra in-site click is acceptable.
const VENDORS = {
    genscript: {
        name: 'GenScript',
        url: 'https://www.genscript.com/',
        hint: 'Click "Quick Order" or REAGENT SERVICES → Gene Synthesis.',
    },
    twist: {
        name: 'Twist',
        url: 'https://www.twistbioscience.com/',
        hint: 'Click Products → Genes.',
    },
    idt: {
        name: 'IDT',
        url: 'https://www.idtdna.com/',
        hint: 'Click Products → Genes & Gene Fragments.',
    },
};

// =============================================================== CLONING
// Designer — multi-step picker (method → vector → enzymes → tags → linker)
// driven by the curated reference data in cloning_db.js (window.ENZYMES,
// window.VECTORS, window.CLONING_METHODS, window.TAGS, window.LINKERS).
//
// Everything is client-side. The Designer state is per-variant so two
// expanded rows in the table can have different configurations at once.
//
// Section coloring in the live preview:
//   - vector_5p / vector_3p → amber (vector arm + RE site)
//   - n_tag / c_tag         → magenta (fusion tag)
//   - linker_n / linker_c   → blue (linker, often a cleavage site)
//   - cds                   → brand teal (codon-optimized ORF)

const STOP_CODONS = new Set(['TAA', 'TAG', 'TGA']);
const stripLeadingAtg   = (cds) => cds.startsWith('ATG') ? cds.slice(3) : cds;
const stripTrailingStop = (cds) => STOP_CODONS.has(cds.slice(-3).toUpperCase()) ? cds.slice(0, -3) : cds;

// Per-variant Designer state: which method, vector, enzymes, tags, linkers.
const cloningState = new Map();   // variantId -> { method, vectorId, enzyme5p, enzyme3p, ggEnzyme, gg5pOverhang, gg3pOverhang, nTag, cTag, linker, bareCds }

function defaultDesignerState(bareCds) {
    return {
        method:        'type_ii_restriction',
        vectorId:      'pet28a',
        enzyme5p:      'NdeI',
        enzyme3p:      'XhoI',
        ggEnzyme:      'BsaI',
        gg5pOverhang:  'AATG',          // MoClo CDS module 5' overhang
        gg3pOverhang:  'GCTT',          // MoClo CDS module 3' overhang
        nTag:          'none',
        cTag:          'his6',
        linker:        'none',
        gibsonArm:     20,
        bareCds:       bareCds || '',
    };
}

// --- Insert builder --------------------------------------------------------
//
// Given the Designer state for one variant, returns:
//   { sections: [{kind, label, dna}, ...], full: string, warnings: [...] }
// where sections preserve the order on the final linear insert so the
// preview can color-code them.

// Full IUPAC complement table — used when reverse-complementing a Type IIS
// enzyme's recognition site. The original lookup ({A:'T', T:'A', G:'C', C:'G'})
// silently passed ambiguity codes through, producing an INCORRECT reverse
// complement for any enzyme entry using degenerate bases. Most Type IIS
// enzymes are unambiguous, but if anyone ever adds a Type IIB or a
// degenerate-site enzyme to the cloning database, the silent miscomputation
// would assemble Golden Gate constructs with the wrong 3' end.
const IUPAC_COMPLEMENT = {
    A: 'T', T: 'A', G: 'C', C: 'G', U: 'A',
    R: 'Y', Y: 'R', S: 'S', W: 'W', K: 'M', M: 'K',
    B: 'V', V: 'B', D: 'H', H: 'D', N: 'N',
};
function reverseComplementIupac(seq) {
    return seq.toUpperCase().split('').reverse()
        .map((b) => IUPAC_COMPLEMENT[b] || b)
        .join('');
}

function buildInsert(state) {
    const cds      = state.bareCds || '';
    const method   = (window.CLONING_METHODS || {})[state.method] || {};
    const vector   = (window.VECTORS         || {})[state.vectorId];
    const nTag     = (window.TAGS            || {})[state.nTag];
    const cTag     = (window.TAGS            || {})[state.cTag];
    const linker   = (window.LINKERS         || {})[state.linker];

    // Always start by trimming the start codon and stop codon — the chosen
    // vector / tags / overhangs will provide them. (For "Bare CDS" with the
    // dummy method we leave them; that case is handled in 'none' method below.)
    let cdsInner = cds;
    let willProvideStart = false;
    let willProvideStop  = false;

    // Build 5'/3' wrappers depending on method.
    const sections = [];
    // Frame-correctness ledger. Sections marked translated:true are part of
    // the in-frame ORF and their lengths must each be multiples of 3 (and
    // their cumulative sum must be a multiple of 3 too). Vector arms and
    // restriction-site flanks aren't translated and don't carry a frame
    // requirement at this layer. We collect violations into a list and
    // surface them as HIGH warnings further down.
    const frameViolations = [];

    function pushSec(kind, label, dna, opts = {}) {
        if (!dna) return;
        const translated = !!opts.translated;
        if (translated && dna.length % 3 !== 0) {
            frameViolations.push({
                kind, label,
                length: dna.length,
                detail: `length ${dna.length} bp is not a multiple of 3`,
            });
        }
        sections.push({ kind, label, dna, translated });
    }

    // Helper: encode a tag's DNA (for now we use the canonical DNA in the TAGS
    // table; full MBP/GST/SUMO are left as placeholders since their sequences
    // are too large to embed and depend on a backbone — flag the user).
    function tagDna(tag) {
        if (!tag) return '';
        return tag.dna || '';
    }

    // Track tags the user selected but the layout silently suppressed (e.g.
    // a vector arm already supplies the ATG, so we drop the N-tag). The
    // user has no visual signal for this, so we surface every suppression
    // as a HIGH warning further down.
    const suppressedTags = [];

    if (state.method === 'type_ii_restriction' || state.method === 'blunt') {
        const e5  = (window.ENZYMES || {})[state.enzyme5p];
        const e3  = (window.ENZYMES || {})[state.enzyme3p];

        // 5' end: 4 nt buffer + RE site. Not translated.
        if (e5) pushSec('vector_5p', `5' ${e5.name} site`, 'AAAA' + e5.recognition);

        // N-term tag (start codon comes from tag if present, else we keep CDS's ATG)
        if (nTag && nTag.dna) {
            pushSec('n_tag', `N-term ${nTag.name}`, 'ATG' + nTag.dna, { translated: true });
            willProvideStart = true;
            if (linker && linker.dna) pushSec('linker_n', `Linker (${linker.name})`, linker.dna, { translated: true });
            cdsInner = stripLeadingAtg(cdsInner);
        }

        // CDS body — strip start if the RE site provides ATG (NcoI / NdeI),
        // and strip stop if a C-term tag is going to add one.
        if (e5 && (e5.recognition === 'CCATGG' || e5.recognition === 'CATATG') && !willProvideStart) {
            cdsInner = stripLeadingAtg(cdsInner);
            willProvideStart = true;
        }
        if (cTag && cTag.dna) {
            cdsInner = stripTrailingStop(cdsInner);
        }
        pushSec('cds', 'CDS', cdsInner, { translated: true });

        // C-term tag
        if (cTag && cTag.dna) {
            if (linker && linker.dna) pushSec('linker_c', `Linker (${linker.name})`, linker.dna, { translated: true });
            // tag DNA + TAA stop; the stop codon makes the whole c_tag a
            // multiple of 3 iff the tag's own DNA was.
            pushSec('c_tag', `C-term ${cTag.name}`, cTag.dna + 'TAA', { translated: true });
            willProvideStop = true;
        }

        // 3' end: RE site + 4 nt buffer. Not translated.
        if (e3) pushSec('vector_3p', `3' ${e3.name} site`, e3.recognition + 'AAAA');

    } else if (state.method === 'golden_gate') {
        const e = (window.ENZYMES || {})[state.ggEnzyme];
        if (e) {
            pushSec('vector_5p', `${e.name} (5')`, 'AAA' + e.recognition + 'A' + (state.gg5pOverhang || 'AATG'));
        }
        if (nTag && nTag.dna) {
            pushSec('n_tag', `N-term ${nTag.name}`, nTag.dna, { translated: true });
            if (linker && linker.dna) pushSec('linker_n', `Linker (${linker.name})`, linker.dna, { translated: true });
        }
        cdsInner = stripLeadingAtg(stripTrailingStop(cdsInner));
        pushSec('cds', 'CDS', cdsInner, { translated: true });
        if (cTag && cTag.dna) {
            if (linker && linker.dna) pushSec('linker_c', `Linker (${linker.name})`, linker.dna, { translated: true });
            pushSec('c_tag', `C-term ${cTag.name}`, cTag.dna, { translated: true });
        }
        if (e) {
            // 3' BsaI cassette on the reverse strand. Uses the full IUPAC
            // complement table so adding a degenerate-site enzyme to the DB
            // won't silently produce a wrong RC.
            const rc = reverseComplementIupac(e.recognition);
            pushSec('vector_3p', `${e.name} (3', RC)`, (state.gg3pOverhang || 'GCTT') + 'A' + rc + 'AAA');
        }

    } else if (state.method === 'gibson' || state.method === 'in_fusion' || state.method === 'slic') {
        const arm = state.gibsonArm || 20;
        if (vector && vector.flanking_5p_max) {
            const fp = vector.flanking_5p_max.slice(-arm);
            pushSec('vector_5p', `${vector.name} 5' arm (${fp.length} bp)`, fp);
        }
        // Vector arm may already supply ATG (NdeI/NcoI-style cassettes).
        // If it does AND the user picked an N-term tag, the previous
        // version silently DROPPED the tag with no signal. We still drop
        // the tag in that case (correct cloning) but now record the
        // suppression so the warnings list can name it.
        const fivePrimeEndsInAtg = vector && vector.flanking_5p_max && vector.flanking_5p_max.toUpperCase().endsWith('ATG');
        if (fivePrimeEndsInAtg) cdsInner = stripLeadingAtg(cdsInner);
        if (vector && vector.flanking_3p_max) cdsInner = stripTrailingStop(cdsInner);

        if (nTag && nTag.dna && !fivePrimeEndsInAtg) {
            pushSec('n_tag', `N-term ${nTag.name}`, 'ATG' + nTag.dna, { translated: true });
            cdsInner = stripLeadingAtg(cdsInner);
        } else if (nTag && nTag.dna && fivePrimeEndsInAtg) {
            suppressedTags.push({
                where: 'N-term',
                name: nTag.name,
                reason: `${vector ? vector.name : 'the chosen vector'} already supplies a start codon (ATG) from its 5' arm, so an N-term fusion tag from this Designer would land BEFORE the vector ATG and never be translated. Pick a vector without an integrated ATG cassette, or add the tag at the C-terminus.`,
            });
        }
        pushSec('cds', 'CDS', cdsInner, { translated: true });
        if (cTag && cTag.dna) {
            if (linker && linker.dna) pushSec('linker_c', `Linker (${linker.name})`, linker.dna, { translated: true });
            pushSec('c_tag', `C-term ${cTag.name}`, cTag.dna, { translated: true });
        }
        if (vector && vector.flanking_3p_max) {
            const tp = vector.flanking_3p_max.slice(0, arm);
            pushSec('vector_3p', `${vector.name} 3' arm (${tp.length} bp)`, tp);
        }

    } else {
        // Fallback / "none" — bare CDS
        pushSec('cds', 'CDS', cdsInner, { translated: true });
    }

    const full = sections.map((s) => s.dna).join('');

    // ---- Warnings ----------------------------------------------------------
    const warnings = [];

    // Frame-correctness: every section we marked translated:true must be a
    // multiple of 3, and their cumulative length must also be a multiple
    // of 3. Either failure shifts every downstream codon and the encoded
    // protein silently becomes garbage. Emit one HIGH warning per offending
    // section, plus one for the cumulative sum if it's wrong despite each
    // individual section being OK (catches the case where, e.g., a 6-bp
    // linker is fine on its own but the user accidentally selected
    // mismatched n/c linker lengths that don't sum cleanly).
    frameViolations.forEach((v) => {
        warnings.push({
            severity: 'high',
            text: `Frame broken: ${v.label} (${v.kind}) ${v.detail} — the encoded protein downstream of this section will be a different sequence than expected.`,
        });
    });
    const translatedLen = sections
        .filter((s) => s.translated)
        .reduce((sum, s) => sum + s.dna.length, 0);
    if (translatedLen > 0 && translatedLen % 3 !== 0 && frameViolations.length === 0) {
        warnings.push({
            severity: 'high',
            text: `Frame broken: the translated region (ATG → stop, ${translatedLen} bp) is not a multiple of 3. Re-check the tag and linker selections.`,
        });
    }

    // Silently-suppressed tags — see the suppression path in the Gibson
    // branch. The user clicked a tag in the dropdown; if we drop it from
    // the assembly without saying so they think they're getting it.
    suppressedTags.forEach((t) => {
        warnings.push({
            severity: 'high',
            text: `${t.where} ${t.name} tag was DROPPED from the assembly: ${t.reason}`,
        });
    });

    // Internal restriction sites for the chosen enzymes
    const enzymeIds = [state.enzyme5p, state.enzyme3p, state.ggEnzyme]
        .filter((id) => id && (window.ENZYMES || {})[id]);
    const hits = (window.scanForInternalSites || (() => []))(cdsInner, enzymeIds);
    hits.forEach((h) => {
        warnings.push({
            severity: 'high',
            text: `Internal ${h.enzymeId} site at nt ${h.position + 1} (${h.motif}) inside the CDS — this enzyme will cut your insert during digestion.`,
        });
    });
    // GC % range check
    const gc = (window.gcPercent || (() => 50))(full);
    if (gc < 35) warnings.push({ severity: 'medium', text: `GC content ${gc.toFixed(1)}% is below 35% — synthesis vendors flag low-GC stretches.` });
    if (gc > 65) warnings.push({ severity: 'medium', text: `GC content ${gc.toFixed(1)}% is above 65% — long high-GC stretches are harder to synthesize.` });
    // Length range check
    if (full.length < 100)   warnings.push({ severity: 'low', text: `Final length ${full.length} bp is very short — most vendors have a 100 bp minimum.` });
    if (full.length > 3500)  warnings.push({ severity: 'medium', text: `Final length ${full.length} bp is over 3.5 kb — synthesis pricing rises sharply past this length.` });

    return { sections, full, warnings, gc };
}

function formattedDnaFor(variantId) {
    const state = cloningState.get(variantId);
    if (!state) return null;
    const built = buildInsert(state);
    return { full: built.full, sections: built.sections };
}

// Hand a designed insert (vector arm + tags + linker + CDS, as assembled by
// the Cloning Designer above) to the Plasmid Editor as a FASTA record. Same
// no-auto-submit posture as sendToCrispr/sendToPrimers/sendToEvolve: the user
// still clicks "Import & map" once they land there.
function sendToPlasmid(seq, label) {
    seq = (seq || '').toUpperCase().replace(/[^ACGTN]/g, '');
    if (!seq) { showToast('Nothing to send.', 'info'); return; }
    const ta = document.getElementById('plasmidInput');
    if (!ta) return;
    ta.value = `>${label}\n${seq}`;
    ta.dispatchEvent(new Event('input', { bubbles: true }));
    location.hash = '#plasmid';
    setTimeout(() => {
        const card = document.getElementById('plasmidInputCard');
        if (card) card.scrollIntoView({ behavior: 'smooth', block: 'start' });
    }, 80);
    showToast(`Loaded ${label} (${seq.length.toLocaleString()} bp) into the Plasmid Editor — click "Import & map" to build it.`, 'info');
}

// CSS.escape polyfill — defensive against arbitrary variant IDs.
function cssEscape(s) {
    return typeof CSS !== 'undefined' && CSS.escape ? CSS.escape(s) : String(s).replace(/[^a-zA-Z0-9_-]/g, '\\$&');
}

// ---- Sequence preview with multi-section coloring ----
function renderSectionedSequenceMulti(sections) {
    const sectionMap = [];
    let pos = 0;
    sections.forEach((s) => {
        sectionMap.push({ start: pos, end: pos + s.dna.length, kind: s.kind, label: s.label });
        pos += s.dna.length;
    });
    const full = sections.map((s) => s.dna).join('').toLowerCase();
    const padWidth = String(full.length).length;
    const charsPerLine = 60;
    const blockSize = 10;
    const out = [];
    for (let i = 0; i < full.length; i += charsPerLine) {
        const num = String(i + 1).padStart(padWidth, ' ');
        let lineHtml = '';
        for (let j = 0; j < charsPerLine && i + j < full.length; j++) {
            if (j > 0 && j % blockSize === 0) lineHtml += ' ';
            const idx = i + j;
            const section = sectionMap.find((s) => idx >= s.start && idx < s.end);
            const cls = section ? `sec-${section.kind}` : 'sec-cds';
            lineHtml += `<span class="${cls}">${escapeHtml(full[idx])}</span>`;
        }
        out.push(`<span class="seq-num">${escapeHtml(num)}</span>  ${lineHtml}`);
    }
    return out.join('\n');
}

// ---- Designer rendering ----
function renderDesigner(variantId) {
    const root = document.querySelector(`.cloning-designer[data-variant="${cssEscape(variantId)}"]`);
    if (!root) return;
    let state = cloningState.get(variantId);
    if (!state) return;

    const methods  = window.CLONING_METHODS || {};
    const method   = methods[state.method] || {};
    const vectors  = window.VECTORS || {};
    const tags     = window.TAGS || {};
    const linkers  = window.LINKERS || {};

    // List vectors compatible with the chosen host context (currently unconstrained).
    const allVectors = Object.entries(vectors);

    // List enzymes filtered by the method's allowed types.
    const enzymeOptions = (window.enzymesForMethod || (() => []))(state.method);

    // Build the controls HTML.
    const controlsHtml = `
        <!-- STEP 1: METHOD ----------------------------------------------- -->
        <div class="designer-step">
            <label class="designer-label">Cloning method</label>
            <select data-designer="method">
                ${Object.values(methods).map((m) => `
                    <option value="${escapeHtml(m.id)}"${m.id === state.method ? ' selected' : ''}>${escapeHtml(m.name)}</option>
                `).join('')}
            </select>
            <div class="designer-hint">${escapeHtml(method.description || '')}</div>
        </div>

        <!-- STEP 2: VECTOR ----------------------------------------------- -->
        <div class="designer-step">
            <label class="designer-label">Destination vector</label>
            <select data-designer="vectorId">
                ${allVectors.map(([id, v]) => `
                    <option value="${escapeHtml(id)}"${id === state.vectorId ? ' selected' : ''}>${escapeHtml(v.name)} · ${escapeHtml(v.host)} · ${escapeHtml(v.promoter)}</option>
                `).join('')}
            </select>
            ${vectors[state.vectorId] ? `
                <div class="designer-hint">
                    <strong>${escapeHtml(vectors[state.vectorId].name)}</strong> · ${vectors[state.vectorId].size_bp} bp · ${escapeHtml(vectors[state.vectorId].selection.join(', '))} ·
                    N-tag: ${escapeHtml(vectors[state.vectorId].fusion_tag.n_term)} · C-tag: ${escapeHtml(vectors[state.vectorId].fusion_tag.c_term)}
                </div>
            ` : ''}
        </div>

        <!-- STEP 3: ENZYMES / OVERHANGS (varies by method) --------------- -->
        ${(state.method === 'type_ii_restriction' || state.method === 'blunt') ? `
            <div class="designer-step designer-step-row">
                <div>
                    <label class="designer-label">5' enzyme</label>
                    <select data-designer="enzyme5p">
                        ${enzymeOptions.map(([id, e]) => `
                            <option value="${escapeHtml(id)}"${id === state.enzyme5p ? ' selected' : ''}>${escapeHtml(e.name)} (${escapeHtml(e.recognition)})</option>
                        `).join('')}
                    </select>
                </div>
                <div>
                    <label class="designer-label">3' enzyme</label>
                    <select data-designer="enzyme3p">
                        ${enzymeOptions.map(([id, e]) => `
                            <option value="${escapeHtml(id)}"${id === state.enzyme3p ? ' selected' : ''}>${escapeHtml(e.name)} (${escapeHtml(e.recognition)})</option>
                        `).join('')}
                    </select>
                </div>
            </div>
        ` : ''}
        ${state.method === 'golden_gate' ? `
            <div class="designer-step designer-step-row">
                <div>
                    <label class="designer-label">Type IIS enzyme</label>
                    <select data-designer="ggEnzyme">
                        ${enzymeOptions.map(([id, e]) => `
                            <option value="${escapeHtml(id)}"${id === state.ggEnzyme ? ' selected' : ''}>${escapeHtml(e.name)} (${escapeHtml(e.recognition)})</option>
                        `).join('')}
                    </select>
                </div>
                <div>
                    <label class="designer-label">5' overhang (4 nt)</label>
                    <input type="text" maxlength="4" minlength="4" pattern="[ACGTacgt]{4}" data-designer="gg5pOverhang" value="${escapeHtml(state.gg5pOverhang)}" />
                </div>
                <div>
                    <label class="designer-label">3' overhang (4 nt)</label>
                    <input type="text" maxlength="4" minlength="4" pattern="[ACGTacgt]{4}" data-designer="gg3pOverhang" value="${escapeHtml(state.gg3pOverhang)}" />
                </div>
            </div>
        ` : ''}
        ${(state.method === 'gibson' || state.method === 'in_fusion' || state.method === 'slic') ? `
            <div class="designer-step">
                <label class="designer-label">Homology arm length (bp)</label>
                <select data-designer="gibsonArm">
                    ${[15, 20, 25, 30, 40].map((n) => `<option value="${n}"${n === state.gibsonArm ? ' selected' : ''}>${n} bp</option>`).join('')}
                </select>
            </div>
        ` : ''}

        <!-- STEP 4: TAGS + LINKER ---------------------------------------- -->
        <div class="designer-step designer-step-row">
            <div>
                <label class="designer-label">N-terminal tag</label>
                <select data-designer="nTag">
                    ${Object.entries(tags).filter(([, t]) => !t.positions || t.positions.includes('n') || t.name === '— none —').map(([id, t]) => `
                        <option value="${escapeHtml(id)}"${id === state.nTag ? ' selected' : ''}>${escapeHtml(t.name)}</option>
                    `).join('')}
                </select>
            </div>
            <div>
                <label class="designer-label">C-terminal tag</label>
                <select data-designer="cTag">
                    ${Object.entries(tags).filter(([, t]) => !t.positions || t.positions.includes('c') || t.name === '— none —').map(([id, t]) => `
                        <option value="${escapeHtml(id)}"${id === state.cTag ? ' selected' : ''}>${escapeHtml(t.name)}</option>
                    `).join('')}
                </select>
            </div>
            <div>
                <label class="designer-label">Linker / cleavage site</label>
                <select data-designer="linker">
                    ${Object.entries(linkers).map(([id, l]) => `
                        <option value="${escapeHtml(id)}"${id === state.linker ? ' selected' : ''}>${escapeHtml(l.name)}</option>
                    `).join('')}
                </select>
            </div>
        </div>
    `;

    // Build the preview + warnings
    const built = buildInsert(state);
    const previewHtml = renderSectionedSequenceMulti(built.sections);

    const sectionsLegend = `
        <span class="legend-swatch legend-vector"></span>vector arm + RE site
        <span class="legend-swatch legend-tag"></span>fusion tag
        <span class="legend-swatch legend-linker"></span>linker / cleavage site
        <span class="legend-swatch legend-cdsBrand"></span>codon-optimized CDS
    `;

    const warningsHtml = built.warnings.length ? `
        <div class="designer-warnings">
            <h5>Warnings · ${built.warnings.length}</h5>
            <ul>
                ${built.warnings.map((w) => `
                    <li class="warn-${escapeHtml(w.severity)}">${escapeHtml(w.text)}</li>
                `).join('')}
            </ul>
        </div>
    ` : `<div class="designer-warnings warn-pass">✓ No design warnings.</div>`;

    root.innerHTML = `
        <div class="designer-controls">${controlsHtml}</div>

        <div class="designer-preview">
            <div class="cloning-meta">
                <span><strong>${built.full.length}</strong> bp final insert</span>
                <span><strong>${built.gc.toFixed(1)}%</strong> GC</span>
                <span class="cloning-legend">${sectionsLegend}</span>
            </div>
            <div class="cloning-preview-block">${previewHtml}</div>
            ${warningsHtml}
        </div>
    `;
}

function wireCloningControls(scope) {
    scope.querySelectorAll('.cloning-designer').forEach((root) => {
        const variantId = root.dataset.variant;
        if (!cloningState.has(variantId)) {
            const variant = (tableState.variants || []).find((v) => v.Variant_ID === variantId);
            cloningState.set(variantId, defaultDesignerState(variant?.Optimized_DNA_Seq || ''));
        }
        renderDesigner(variantId);

        root.addEventListener('change', (e) => {
            const field = e.target?.dataset?.designer;
            if (!field) return;
            const state = cloningState.get(variantId);
            if (!state) return;
            let value = e.target.value;
            if (field === 'gibsonArm') value = parseInt(value, 10);
            if ((field === 'gg5pOverhang' || field === 'gg3pOverhang') &&
                !/^[ACGTacgt]{4}$/.test(value)) {
                // Reject invalid overhang and revert to old value
                e.target.value = state[field];
                return;
            }
            state[field] = value;
            renderDesigner(variantId);
        });

        // Also re-render on `input` for text fields so the preview updates
        // as the user types valid 4-mers.
        root.addEventListener('input', (e) => {
            const field = e.target?.dataset?.designer;
            if (field !== 'gg5pOverhang' && field !== 'gg3pOverhang') return;
            if (!/^[ACGTacgt]{4}$/.test(e.target.value)) return;
            const state = cloningState.get(variantId);
            state[field] = e.target.value;
            renderDesigner(variantId);
        });
    });
}

async function synthesizeDna(dnaSeq, variantId, vendorKey) {
    // Per-session verification gate. First synth-action of the session
    // shows the disclaimer modal with this variant's details; the user
    // must tick "I have visually verified this sequence" to proceed.
    // After that single acknowledgment, subsequent synth actions in the
    // same tab go through without the modal (researcher friction would
    // make the tool unusable otherwise).
    const vendorName = (VENDORS[vendorKey] && VENDORS[vendorKey].name) || vendorKey;
    const len = dnaSeq ? dnaSeq.length : 0;
    const verifyOk = await ensureSynthVerified(`
        <strong>${escapeHtml(variantId)}</strong> &middot;
        ${escapeHtml(String(len))} bp &middot;
        sending to <strong>${escapeHtml(vendorName)}</strong>
    `);
    if (!verifyOk) return;

    // All three vendors (Twist, IDT, GenScript) are external homepage
    // redirects: we copy the DNA to clipboard, then open the vendor's
    // site in a new tab so the user pastes into their order form.
    //
    // The local Twist Gateway in-app flow was removed when we shipped
    // the public site — it required a localhost FastAPI service that
    // doesn't exist in production. The full gateway code is preserved
    // in git history if we ever wire up the real Twist API.
    //
    // SAFETY: if the clipboard write fails we MUST NOT open the vendor
    // tab — the user would paste whatever was on the clipboard before
    // (likely a different variant) into the vendor's order form. Wrong
    // DNA shipped, hard to detect.
    const vendor = VENDORS[vendorKey] || VENDORS.genscript;
    const ok = await copyToClipboardOrToast(dnaSeq, `${variantId} DNA for ${vendor.name}`);
    if (!ok) {
        // copyToClipboardOrToast already showed an error toast naming the
        // failure mode. Do NOT open the vendor tab — wrong DNA would land
        // in their order form.
        return;
    }
    showToast(
        `${variantId}'s DNA sequence copied. Opening ${vendor.name} — ${vendor.hint}`,
        'info',
    );
    setTimeout(() => {
        window.open(vendor.url, '_blank', 'noopener,noreferrer');
    }, 1100);
}

// Download dropdown. Trigger toggles a menu of formats; clicking an item
// kicks off a real browser download via a hidden <a download> link.
function wireDownloadMenu() {
    const trigger = $('#downloadTrigger');
    const menu = $('#downloadMenuItems');
    if (!trigger || !menu) return;

    const closeMenu = () => { menu.hidden = true; trigger.classList.remove('open'); };
    const openMenu  = () => { menu.hidden = false; trigger.classList.add('open'); };

    // Bind once; re-renders of the result table don't recreate the trigger.
    if (trigger.dataset.wired === '1') return;
    trigger.dataset.wired = '1';

    trigger.addEventListener('click', (e) => {
        e.stopPropagation();
        menu.hidden ? openMenu() : closeMenu();
    });

    document.addEventListener('click', (e) => {
        if (!menu.hidden && !e.target.closest('#downloadMenu')) closeMenu();
    });

    document.addEventListener('keydown', (e) => {
        if (e.key === 'Escape' && !menu.hidden) closeMenu();
    });

    // Fire the browser's native download (server sends Content-Disposition:
    // attachment so this drops a file into ~/Downloads, not a navigation).
    const doDownload = (fmt) => {
        const a = document.createElement('a');
        a.href = `/api/download/${state.jobId}?format=${encodeURIComponent(fmt)}`;
        a.download = '';
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
    };

    menu.querySelectorAll('.download-item').forEach((item) => {
        item.addEventListener('click', (e) => {
            e.preventDefault();
            const fmt = item.dataset.format;
            if (!state.jobId || !fmt) return;
            closeMenu();
            // Red Team gate: run the synthesis checks on the full evolved
            // constructs before the library leaves the app. (No essential-gene
            // check here — directed evolution isn't a knockout.) Bypassable.
            const seqs = (typeof tableState !== 'undefined' ? (tableState.variants || []) : [])
                .map(v => v.Optimized_DNA_Seq).filter(Boolean);
            if (!seqs.length || typeof runOracle !== 'function') { doDownload(fmt); return; }
            runOracle({
                seqs: seqs, gene: '',
                actionLabel: 'Before exporting your variant library (' + fmt.toUpperCase() + ')',
                proceed: () => doDownload(fmt),
            });
        });
    });
}

// =============================================================== STATS STRIP
// Compact KPI tiles above the variants table. Researchers (and reviewers
// reading this on behalf of synthesis vendors) should read the library
// quality in three seconds.
function renderStatsStrip(data) {
    const strip = document.getElementById('statsStrip');
    if (!strip) return;
    // Stats describe the evolved library only — the WT pseudo-row would skew
    // every aggregate (zero mutations, zero fitness, etc.).
    const variants = (data.variants || []).filter(v => v.Variant_ID !== 'WT');
    if (!variants.length) { strip.innerHTML = ''; return; }

    const fitness = variants.map(v => Number(v.Predicted_Fitness_Score)).filter(Number.isFinite);
    const gc = variants.map(v => Number(v.GC_Percent)).filter(Number.isFinite);
    const tms = variants.flatMap(v => [Number(v.Primer_Fwd_Tm_C), Number(v.Primer_Rev_Tm_C)]).filter(Number.isFinite);
    const lengths = variants.map(v => Number(v.Length_bp)).filter(Number.isFinite);
    const nMutations = variants.map(v => (v.Mutations_AA || '').split(',').filter(Boolean).length);

    // Library composition: position coverage = how many distinct WT residues
    // are touched at least once; diversity = unique (position, mut_aa) pairs.
    const positionsTouched = new Set();
    const uniqueSubs = new Set();
    variants.forEach(v => {
        (v.Mutations_AA || '').split(',').forEach(m => {
            const match = m.trim().match(/^([A-Z])(\d+)([A-Z\*])$/);
            if (match) {
                positionsTouched.add(match[2]);
                uniqueSubs.add(match[2] + match[3]);
            }
        });
    });

    const mean = (a) => a.length ? a.reduce((s,x)=>s+x,0)/a.length : 0;
    const max  = (a) => a.length ? Math.max(...a) : 0;
    const min  = (a) => a.length ? Math.min(...a) : 0;
    const wtLen = (data.wt_protein || '').length;
    const coveragePct = wtLen ? (positionsTouched.size / wtLen * 100).toFixed(1) : '—';

    const tiles = [
        { label: 'Variants', val: variants.length, sub: `${min(nMutations)}–${max(nMutations)} mutations each · mean ${mean(nMutations).toFixed(1)}` },
        { label: 'Top fitness', val: max(fitness).toFixed(2), sub: `mean ${mean(fitness).toFixed(2)} ΣΔLL` },
        { label: 'Position coverage', val: `${positionsTouched.size}`, sub: `${coveragePct}% of WT (${uniqueSubs.size} unique subs)` },
        { label: 'Mean GC', val: `${mean(gc).toFixed(1)}%`, sub: `${min(gc).toFixed(1)}–${max(gc).toFixed(1)}% range` },
        { label: 'Cooler primer Tm', val: `${min(tms).toFixed(1)}°`, sub: `mean ${mean(tms).toFixed(1)}°C` },
        { label: 'Amplicon', val: `${lengths[0] || '—'} bp`, sub: 'all variants same length' },
    ];

    strip.innerHTML = tiles.map(t => `
        <div class="stat-tile">
            <span class="stat-label">${escapeHtml(t.label)}</span>
            <strong class="stat-val">${escapeHtml(String(t.val))}</strong>
            <span class="stat-sub">${escapeHtml(t.sub)}</span>
        </div>
    `).join('');

    // Tick the count-up animation on every stat-val so the numbers feel
    // like they "land" instead of just appearing. CSS class auto-removes
    // after the keyframe completes (~280ms).
    strip.querySelectorAll('.stat-val').forEach((el) => {
        el.classList.remove('count-up');
        // Force reflow so the re-added class re-triggers the animation.
        void el.offsetWidth;
        el.classList.add('count-up');
        setTimeout(() => el.classList.remove('count-up'), 320);
    });
}

// =============================================================== RUN META
// Pill row of the actual parameters the engine ran with + a copy-paste
// methods paragraph for the Materials & Methods section of a paper.
function renderRunMeta(data) {
    const box = document.getElementById('runMeta');
    if (!box) return;
    const s = data.settings_used || {};
    if (!Object.keys(s).length) { box.hidden = true; return; }
    box.hidden = false;

    const modelLabel = { small: 'ESM-2 35M', medium: 'ESM-2 650M', large: 'ESM-2 3B' }[s.model] || s.model;
    const hostLabel  = { e_coli: 'E. coli', yeast: 'S. cerevisiae', human: 'H. sapiens' }[s.host] || s.host;
    const elapsed = data.elapsed_seconds != null ? `${data.elapsed_seconds}s` : '—';

    const pills = [
        ['Model',  modelLabel],
        ['Percentile', `top ${(100 - s.percentile).toFixed(0)}% (≥ p${s.percentile})`],
        ['K variants', s.k],
        ['Max muts/variant', s.max_mutations],
        ['Min muts/variant', s.min_mutations],
        ['SA restarts', s.restarts],
        ['SA steps/restart', s.steps_per_restart],
        ['Host', hostLabel],
        ['Device', s.device],
        ['Seed', s.seed != null ? s.seed : 'random'],
        ['Wall time', elapsed],
    ];
    const pillHtml = pills.map(([k, v]) => `<span class="run-pill">${escapeHtml(k)} <strong>${escapeHtml(String(v))}</strong></span>`).join('');

    // Auto-generated methods paragraph — copy-paste into a manuscript.
    const wtLen = (data.wt_protein || '').length;
    const wtId  = data.wt_identifier || 'wild-type';
    const methods = `Variants of ${escapeHtml(wtId)} (${wtLen} aa) were designed in silico with ESM-2 ${modelLabel.replace('ESM-2 ', '')} (Lin et al., <cite>Science</cite> 2023) using the wild-type marginal log-likelihood scoring scheme of Meier et al. (<cite>Adv. Neural Inf. Process. Syst.</cite> 2021). Single-point substitutions in the top ${(100 - s.percentile).toFixed(0)}% by ΔLL were retained as the combinatorial search space. ${s.k} multi-mutant variants with ${s.min_mutations}–${s.max_mutations} simultaneous substitutions were generated by simulated annealing (${s.restarts} restarts × ${s.steps_per_restart} steps, geometric cooling) maximizing cumulative ΔLL with stop-codon and duplicate-position penalties. Optimized DNA was reverse-translated using ${hostLabel} codon-usage frequencies and synonymously cleaned of BsaI, BsmBI, and NotI recognition sites for Golden Gate compatibility.`;

    box.innerHTML = `
        <div class="run-meta-pills">${pillHtml}</div>
        <div class="run-methods">
            <div class="run-methods-head">
                <h4>Materials &amp; methods (copy-paste)</h4>
                <button class="copy-btn" data-copy="${escapeHtml(methods.replace(/<[^>]+>/g, ''))}">Copy</button>
            </div>
            <div class="run-methods-body">${methods}</div>
        </div>
    `;
    wireCopyButtons(box);
}

// =============================================================== MUTATION MAP
// Lollipop chart: x = residue position, y = how many variants share a mutation
// at that position. Dots colored by mean ΔLL strength. Standard genomics
// visualization (cBioPortal / ProteinPaint).
function renderMutationMap(data) {
    const root = document.getElementById('mutmapCanvas');
    if (!root) return;
    root.innerHTML = '';

    const wtLen = (data.wt_protein || '').length;
    if (!wtLen) return;

    // Aggregate mutation counts and signed ΔLL contribution per position.
    const counts = new Map();      // position -> count
    const strength = new Map();    // position -> sum of fitness contribution
    let maxCount = 0;
    (data.variants || []).forEach((v) => {
        const muts = (v.Mutations_AA || '').split(',').map(s => s.trim()).filter(Boolean);
        // Per-variant fitness divided by mutation count is our crude per-mut weight.
        const w = Number(v.Predicted_Fitness_Score) / Math.max(1, muts.length);
        muts.forEach((m) => {
            const numMatch = m.match(/[0-9]+/);
            if (!numMatch) return;
            const pos = parseInt(numMatch[0], 10);
            counts.set(pos, (counts.get(pos) || 0) + 1);
            strength.set(pos, (strength.get(pos) || 0) + w);
            if (counts.get(pos) > maxCount) maxCount = counts.get(pos);
        });
    });
    if (!counts.size) {
        root.innerHTML = '<div class="muted" style="padding:16px;text-align:center;">No mutations to plot.</div>';
        return;
    }

    // SVG geometry
    const W = root.clientWidth || 800;
    const H = 140;
    const pad = { top: 14, right: 16, bottom: 28, left: 36 };
    const innerW = W - pad.left - pad.right;
    const innerH = H - pad.top - pad.bottom;

    const xScale = (p) => pad.left + (p - 1) / Math.max(1, wtLen - 1) * innerW;
    const yScale = (c) => pad.top + innerH - (c / maxCount) * innerH;

    // Compute color by strength: brand-200 (low) → brand (mid) → brand-deep (high)
    const strengths = [...strength.values()];
    const sMax = Math.max(...strengths);
    const sMin = Math.min(...strengths);
    const colorFor = (s) => {
        if (sMax === sMin) return '#3D3A34';
        const t = (s - sMin) / (sMax - sMin);
        if (t < 0.33) return '#CFCBC2';
        if (t < 0.66) return '#3D3A34';
        return '#1B1A17';
    };

    // Ticks every ~50 residues, with at least 4 ticks.
    const tickStep = Math.max(10, Math.ceil(wtLen / Math.max(4, Math.min(12, Math.floor(wtLen / 25)))));
    const ticks = [];
    for (let i = 1; i <= wtLen; i += tickStep) ticks.push(i);
    if (ticks[ticks.length - 1] !== wtLen) ticks.push(wtLen);

    const svgNS = 'http://www.w3.org/2000/svg';
    const svg = document.createElementNS(svgNS, 'svg');
    svg.setAttribute('viewBox', `0 0 ${W} ${H}`);
    svg.setAttribute('preserveAspectRatio', 'none');

    // Axis baseline (residue track)
    const baseline = document.createElementNS(svgNS, 'line');
    baseline.setAttribute('x1', pad.left);
    baseline.setAttribute('x2', pad.left + innerW);
    baseline.setAttribute('y1', pad.top + innerH);
    baseline.setAttribute('y2', pad.top + innerH);
    baseline.setAttribute('class', 'mutmap-baseline');
    svg.appendChild(baseline);

    // X axis labels
    const axis = document.createElementNS(svgNS, 'g');
    axis.setAttribute('class', 'mutmap-axis');
    ticks.forEach((t) => {
        const x = xScale(t);
        const tick = document.createElementNS(svgNS, 'line');
        tick.setAttribute('x1', x);
        tick.setAttribute('x2', x);
        tick.setAttribute('y1', pad.top + innerH);
        tick.setAttribute('y2', pad.top + innerH + 4);
        axis.appendChild(tick);
        const lbl = document.createElementNS(svgNS, 'text');
        lbl.setAttribute('x', x);
        lbl.setAttribute('y', pad.top + innerH + 16);
        lbl.setAttribute('text-anchor', 'middle');
        lbl.textContent = String(t);
        axis.appendChild(lbl);
    });

    // Y axis labels (count)
    const yLabels = [maxCount, Math.ceil(maxCount / 2), 1];
    yLabels.forEach((c) => {
        const y = yScale(c);
        const lbl = document.createElementNS(svgNS, 'text');
        lbl.setAttribute('x', pad.left - 8);
        lbl.setAttribute('y', y + 3);
        lbl.setAttribute('text-anchor', 'end');
        lbl.textContent = String(c);
        axis.appendChild(lbl);
    });
    svg.appendChild(axis);

    // Lollipops
    const sorted = [...counts.entries()].sort((a, b) => a[0] - b[0]);
    sorted.forEach(([pos, c]) => {
        const x = xScale(pos);
        const y = yScale(c);
        const stem = document.createElementNS(svgNS, 'line');
        stem.setAttribute('x1', x);
        stem.setAttribute('x2', x);
        stem.setAttribute('y1', pad.top + innerH);
        stem.setAttribute('y2', y);
        stem.setAttribute('class', 'mutmap-stem');
        svg.appendChild(stem);

        const dot = document.createElementNS(svgNS, 'circle');
        dot.setAttribute('cx', x);
        dot.setAttribute('cy', y);
        dot.setAttribute('r', Math.max(3, 3 + c * 0.4));
        dot.setAttribute('fill', colorFor(strength.get(pos)));
        dot.setAttribute('class', 'mutmap-dot');
        const title = document.createElementNS(svgNS, 'title');
        title.textContent = `Position ${pos} · ${c} variant${c === 1 ? '' : 's'} mutate here · Σ contribution ${strength.get(pos).toFixed(2)}`;
        dot.appendChild(title);
        svg.appendChild(dot);
    });

    root.appendChild(svg);
}

// =============================================================== COMMAND PALETTE
// Stub: ⌘K / Ctrl-K opens a minimal prompt. Full palette is a follow-up.
document.addEventListener('keydown', (e) => {
    const isCmdK = (e.metaKey || e.ctrlKey) && e.key.toLowerCase() === 'k';
    if (!isCmdK) return;
    e.preventDefault();
    const trigger = document.getElementById('cmdTrigger');
    if (trigger) {
        trigger.style.borderColor = 'var(--brand)';
        trigger.style.boxShadow = '0 0 0 3px var(--brand-ring)';
        setTimeout(() => {
            trigger.style.borderColor = '';
            trigger.style.boxShadow = '';
        }, 400);
    }
    // Focus paste area as the most common action.
    const ta = document.getElementById('pasteArea');
    if (ta) {
        document.querySelector('.tab[data-tab="paste"]')?.click();
        ta.focus();
    }
});

// =============================================================== IDENTIFY
// NCBI BLAST integration. User clicks "Identify via NCBI BLAST" → backend
// submits the WT protein to NCBI's public web BLAST, we poll until done,
// then render the top hits. Results cached server-side by sequence hash.

let identifyPollHandle = null;

function bindIdentifyButton() {
    const btn = document.getElementById('identifyBtn');
    if (!btn || btn.dataset.wired === '1') return;
    btn.dataset.wired = '1';
    btn.addEventListener('click', startIdentify);
}

// ----------------------------------------------------------------------------
// BLAST consent gate
// ----------------------------------------------------------------------------
// NCBI BLAST sends the wild-type protein sequence to ncbi.nlm.nih.gov, where
// it is logged for operational + security purposes. That's fine for published
// reference proteins and a privacy / IP risk for anything pre-publication or
// proprietary. We require an explicit per-session consent click before any
// such request leaves the machine — same shape as the ESMFold consent below.
// sessionStorage (not localStorage) so consent doesn't silently persist
// across days; closing the tab resets the gate.
const BLAST_CONSENT_KEY = 'turingdna.blast.consent.v1';

function hasBlastConsent() {
    try { return sessionStorage.getItem(BLAST_CONSENT_KEY) === '1'; }
    catch { return false; }
}
function grantBlastConsent() {
    try { sessionStorage.setItem(BLAST_CONSENT_KEY, '1'); } catch {}
}

// Show the BLAST consent modal (#blastConsentModal in index.html).
//
// Was previously rendered inline inside the #identifyPanel div that lives
// at the top of the preview card. Problem: when the user scrolls down to
// click "Identify via NCBI BLAST" from further down the page (CDS picker,
// settings, results), the consent panel pops in ABOVE the viewport — they
// can't see it without scrolling back up. Refactored to a fixed-position
// .modal so the consent always appears centered on whatever the user is
// looking at right now. Markup lives in index.html so the modal can be
// reused if we ever need to re-prompt.
function renderBlastConsentPanel(_unusedPanel, btn) {
    const modal = document.getElementById('blastConsentModal');
    if (!modal) {
        // Shouldn't happen in shipped builds — the markup is in index.html.
        // Fall through to the BLAST request anyway rather than blocking the
        // user behind a missing modal.
        grantBlastConsent();
        startIdentify();
        return;
    }

    modal.hidden = false;
    document.body.style.overflow = 'hidden';

    const close = () => {
        modal.hidden = true;
        document.body.style.overflow = '';
        if (btn) btn.disabled = false;
        document.removeEventListener('keydown', onEsc);
    };
    const onEsc = (e) => {
        if (e.key === 'Escape') close();
    };

    // Wire all cancel surfaces (backdrop, × button, explicit Cancel button).
    // Use .once so re-opening the modal in the same session doesn't stack
    // multiple listeners.
    modal.querySelectorAll('[data-blast-cancel]').forEach((el) => {
        el.addEventListener('click', close, { once: true });
    });

    // Wire the Continue button.
    const continueBtn = modal.querySelector('#blastConsentContinue');
    if (continueBtn) {
        continueBtn.addEventListener('click', () => {
            grantBlastConsent();
            close();
            // Re-enter the flow now that consent is recorded — the gate above
            // is satisfied and the BLAST submission proceeds normally.
            startIdentify();
        }, { once: true });
    }

    // Esc to dismiss.
    document.addEventListener('keydown', onEsc);

    // Focus the primary action for keyboard users.
    if (continueBtn) {
        try { continueBtn.focus({ preventScroll: true }); } catch (_) {}
    }
}

async function startIdentify() {
    if (!state.sessionId) {
        showToast('Load a sequence first.', 'warn');
        return;
    }
    const btn = document.getElementById('identifyBtn');
    const panel = document.getElementById('identifyPanel');
    if (!btn || !panel) return;

    // First-time gate: BLAST sends the sequence to NCBI. Show the consent
    // panel and bail out — the Continue button re-enters this function with
    // consent recorded, so the second pass falls through to submission.
    if (!hasBlastConsent()) {
        btn.disabled = true;
        renderBlastConsentPanel(panel, btn);
        return;
    }

    btn.disabled = true;
    panel.hidden = false;
    panel.innerHTML = `
        <div class="identify-status">
            <span class="identify-spinner"></span>
            <span>Submitting to NCBI…</span>
        </div>
    `;

    try {
        const res = await fetch('/api/identify', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({
                session_id: state.sessionId,
                cds_feature: state.chosenCds,
                // Server-side BLAST consent gate (audit H1). The consent
                // modal in renderBlastConsentPanel sets the sessionStorage
                // flag; we forward it here so the backend can verify
                // the user actually opted in. Anyone bypassing the modal
                // and calling /api/identify directly gets a 403.
                blast_consent: hasBlastConsent(),
            }),
        });
        const data = await res.json();
        if (!res.ok) throw new Error(data.error || 'BLAST submission failed.');
        if (data.cached && data.status === 'done') {
            renderIdentifyResult(data);
            btn.disabled = false;
            return;
        }
        pollIdentify(data.job_id);
    } catch (err) {
        panel.innerHTML = `<div class="identify-error">${escapeHtml(err.message)}</div>`;
        btn.disabled = false;
    }
}

function pollIdentify(jobId) {
    if (identifyPollHandle) clearTimeout(identifyPollHandle);
    identifyPollHandle = setTimeout(async () => {
        try {
            const res = await fetch(`/api/identify/${jobId}`);
            const data = await res.json();
            if (!res.ok) throw new Error(data.error || 'Lost the BLAST job.');
            const panel = document.getElementById('identifyPanel');
            const elapsed = data.elapsed_seconds != null ? data.elapsed_seconds.toFixed(1) : '0.0';
            const phaseLabel = {
                pending: 'Queued',
                submitting: 'Submitting to NCBI',
                running: 'NCBI is searching nr',
                parsing: 'Parsing results',
                done: 'Done',
                error: 'Error',
            }[data.status] || data.status;
            if (data.status === 'done') {
                renderIdentifyResult(data);
                document.getElementById('identifyBtn').disabled = false;
                return;
            }
            if (data.status === 'error') {
                panel.innerHTML = `<div class="identify-error">BLAST failed: ${escapeHtml(data.error || 'unknown error')}</div>`;
                document.getElementById('identifyBtn').disabled = false;
                return;
            }
            panel.innerHTML = `
                <div class="identify-status">
                    <span class="identify-spinner"></span>
                    <span>${escapeHtml(phaseLabel)} · ${escapeHtml(elapsed)}s elapsed (NCBI queues can take 30–90 s)</span>
                </div>
            `;
            pollIdentify(jobId);
        } catch (err) {
            const panel = document.getElementById('identifyPanel');
            if (panel) panel.innerHTML = `<div class="identify-error">${escapeHtml(err.message)}</div>`;
            document.getElementById('identifyBtn').disabled = false;
        }
    }, 2000);
}

function renderIdentifyResult(data) {
    const panel = document.getElementById('identifyPanel');
    if (!panel) return;
    const hits = data.hits || [];
    if (!hits.length) {
        panel.innerHTML = `
            <div class="identify-status">
                <span>No significant NCBI matches at E ≤ 1e-5. This sequence may be de novo / heavily engineered / chimeric, or simply too short for confident hits.</span>
            </div>
        `;
        return;
    }
    const top = hits[0];
    const idPct = Number(top.identity_pct);
    let idClass = 'id-low';
    if (idPct >= 80) idClass = '';
    else if (idPct >= 40) idClass = 'id-mid';

    const ncbiBase = 'https://www.ncbi.nlm.nih.gov/protein/';
    const topNcbiUrl = top.accession ? `${ncbiBase}${encodeURIComponent(top.accession)}` : null;

    const hitRows = hits.slice(0, 5).map((h) => {
        const accLink = h.accession
            ? `<a class="identify-hit-acc" href="${ncbiBase}${encodeURIComponent(h.accession)}" target="_blank" rel="noopener">${escapeHtml(h.accession)}</a>`
            : `<span class="identify-hit-acc">—</span>`;
        return `
            <div class="identify-hit">
                ${accLink}
                <div>
                    <div class="identify-hit-desc">${escapeHtml(h.description)}</div>
                    ${h.organism ? `<div class="identify-hit-org">${escapeHtml(h.organism)}</div>` : ''}
                </div>
                <div class="identify-hit-stats">
                    ${h.identity_pct}% id<br>
                    cov ${h.coverage_pct}%<br>
                    E ${h.evalue.toExponential(1)}
                </div>
            </div>
        `;
    }).join('');

    // If the top hit (or any of the top-5) has a UniProt accession, prepare
    // an AlphaFold structure embed slot. We pick the first UniProt-mapped
    // hit in case the very top is RefSeq-only.
    const afHit = hits.slice(0, 5).find(h => h.uniprot && h.alphafold_url);
    // When the accession came from the Swiss-Prot homolog fallback (nr buried
    // the curated entry), label it honestly: it's the closest *reviewed*
    // protein with a model, not necessarily the exact nr top hit.
    const afHomolog = afHit && afHit.uniprot_via === 'swissprot_homolog';
    const afOrg = afHit ? (afHomolog ? (afHit.uniprot_organism || afHit.organism || '') : (afHit.organism || '')) : '';
    const afMeta = afHit
        ? ('UniProt ' + escapeHtml(afHit.uniprot) + (afOrg ? ' · ' + escapeHtml(afOrg) : '')
           + (afHomolog && afHit.uniprot_identity_pct != null
                ? ' · closest reviewed homolog (' + escapeHtml(String(afHit.uniprot_identity_pct)) + '% id)' : ''))
        : '';
    const afHtml = afHit
        ? `
            <div class="alphafold-wrap">
                <div class="alphafold-head">
                    <h4>AlphaFold predicted structure</h4>
                    <span class="alphafold-meta">${afMeta}</span>
                </div>
                <div class="alphafold-viewer" id="alphafoldViewer" data-pdb-url="${escapeHtml(afHit.alphafold_url)}" data-uniprot="${escapeHtml(afHit.uniprot)}">
                    <div class="alphafold-loading">
                        <span class="identify-spinner"></span>
                        Loading AlphaFold-DB structure…
                    </div>
                </div>
                <div class="alphafold-disclaimer">
                    Predicted structure from <a href="${escapeHtml(afHit.alphafold_page)}" target="_blank" rel="noopener">AlphaFold-DB</a>.
                    ${afHomolog ? 'Resolved as the closest reviewed (Swiss-Prot) protein — a reference scaffold for this family. ' : ''}Drag to rotate · scroll to zoom · double-click to fit.
                    Backbone confidence colored by pLDDT (blue&nbsp;=&nbsp;high, orange&nbsp;=&nbsp;low).
                </div>
            </div>
        `
        : '';

    panel.innerHTML = `
        <div class="identify-headline">
            <strong>${escapeHtml(top.description || 'Top NCBI match')}</strong>
            ${top.organism ? `<span class="organism">${escapeHtml(top.organism)}</span>` : ''}
            <span class="id-pct ${idClass}">${idPct}% identity</span>
        </div>
        <div class="identify-hits">${hitRows}</div>
        <div class="identify-actions">
            ${topNcbiUrl ? `<a class="ghost" target="_blank" rel="noopener" href="${topNcbiUrl}">Open ${escapeHtml(top.accession)} on NCBI</a>` : ''}
            ${afHit ? `<a class="ghost" target="_blank" rel="noopener" href="${escapeHtml(afHit.alphafold_page)}">Open AlphaFold entry</a>` : ''}
        </div>
        ${afHtml}
    `;

    if (afHit) mountAlphaFoldViewer(afHit);
}

// AlphaFold-DB bumps its model version DB-wide over time (…v4 → v6 → …), so
// any hardcoded "model_vN" URL eventually 404s. Critically, Mol*'s
// loadStructureFromUrl does NOT throw on a 404 — it loads the error body,
// ends up with zero structures, removes the loading overlay, and silently
// shows an empty viewer ("won't show predicted models"). So we resolve the
// CURRENT file URL from AlphaFold's prediction API using the accession
// embedded in whatever URL we were handed, with the original as fallback.
// CORS-enabled; works from inside the /app/ iframe.
function _afFormat(url) { return /\.cif(\?|$)/i.test(url || '') ? 'mmcif' : 'pdb'; }
// True only if a structure actually made it into the hierarchy — guards the
// silent-404 case (Mol* doesn't throw on a 404) so we can surface a real
// message instead of a blank viewer.
function _afHasStructure(viewer) {
    try { return (viewer.plugin.managers.structure.hierarchy.current.structures.length || 0) > 0; }
    catch (_) { return false; }
}

// fetch() with an abort timeout + one retry on transient failure (network
// error, 5xx, 429). 404 and other 4xx are returned as-is (not retried).
async function _afFetch(url, tries = 2, timeoutMs = 8000) {
    let lastErr = null;
    for (let i = 0; i < tries; i++) {
        const ctrl = new AbortController();
        const to = setTimeout(() => ctrl.abort(), timeoutMs);
        try {
            const r = await fetch(url, { signal: ctrl.signal });
            clearTimeout(to);
            if (r.ok || (r.status >= 400 && r.status < 500 && r.status !== 429)) return r;
            lastErr = new Error('HTTP ' + r.status);  // 5xx / 429 → retry
        } catch (e) { clearTimeout(to); lastErr = e; }
        if (i < tries - 1) await new Promise(s => setTimeout(s, 450 * (i + 1)));
    }
    throw lastErr || new Error('fetch failed');
}

// Resolve an AF model reference into: the ordered list of candidate model
// URLs to try, plus whether the entry is known to exist. AlphaFold-DB bumps
// model versions per-entry (v4→v6→…) and occasionally has CDN blips, so we
// (1) ask the prediction API for the *current* model URL, then (2) build a
// fallback ladder — alternate format (.cif) and older versions — so a single
// stale/blipping URL doesn't blank the viewer. `exists` is true/false when the
// API answered, null when it couldn't be reached (treated as transient).
async function _afResolve(originalUrl) {
    const acc = ((originalUrl || '').match(/AF-([A-Za-z0-9]+)-F\d+/) || [])[1];
    const out = { candidates: [], exists: null };
    const push = (u) => { if (u && out.candidates.indexOf(u) === -1) out.candidates.push(u); };
    let resolved = originalUrl;
    if (acc) {
        try {
            const r = await _afFetch('https://alphafold.ebi.ac.uk/api/prediction/' + acc, 2, 8000);
            if (r.ok) {
                const j = await r.json();
                out.exists = Array.isArray(j) && j.length > 0;
                const e = (j && j[0]) || {};
                resolved = e.pdbUrl || e.cifUrl || originalUrl;
            } else if (r.status === 404) {
                out.exists = false;
            }
        } catch (_) { /* unreachable → exists stays null (transient) */ }
    }
    push(resolved);
    if (resolved) push(resolved.replace(/\.pdb(\?|$)/i, '.cif$1'));   // alt format
    if (acc) [6, 5, 4].forEach(v => push(`https://alphafold.ebi.ac.uk/files/AF-${acc}-F1-model_v${v}.pdb`));
    return out;
}

// Try each candidate URL until one actually puts a structure in the hierarchy.
async function _afTryLoad(viewer, candidates) {
    for (const u of candidates) {
        try {
            await viewer.loadStructureFromUrl(u, _afFormat(u));
            if (_afHasStructure(viewer)) return true;
        } catch (_) { /* try the next candidate */ }
    }
    return false;
}

// Lazy, resilient Mol* loader. The viewer bundle is ~4.9 MB, so we load it on
// demand (first Fold / AlphaFold click) instead of on every page view, and we
// fall back jsDelivr → unpkg. Resolves with the molstar global once the script
// actually fires its load event (no arbitrary timeout that fails on slow links
// — the old 8 s cutoff was why BOTH viewers "failed to load" so often). Returns
// null only if every source failed; clears the cache so a later click retries.
let _molstarLoad = null;
function ensureMolstar() {
    if (typeof window.molstar !== 'undefined') return Promise.resolve(window.molstar);
    if (_molstarLoad) return _molstarLoad;
    const VER = '5.9.0';
    const jsUrls = [
        `https://cdn.jsdelivr.net/npm/molstar@${VER}/build/viewer/molstar.js`,
        `https://unpkg.com/molstar@${VER}/build/viewer/molstar.js`,
    ];
    const cssUrls = [
        `https://cdn.jsdelivr.net/npm/molstar@${VER}/build/viewer/molstar.css`,
        `https://unpkg.com/molstar@${VER}/build/viewer/molstar.css`,
    ];
    if (!document.querySelector('link[data-molstar]')) {
        const l = document.createElement('link');
        l.rel = 'stylesheet'; l.href = cssUrls[0]; l.setAttribute('data-molstar', '1');
        l.onerror = () => { l.href = cssUrls[1]; };
        document.head.appendChild(l);
    }
    _molstarLoad = new Promise((resolve) => {
        let i = 0;
        const tryNext = () => {
            if (typeof window.molstar !== 'undefined') return resolve(window.molstar);
            if (i >= jsUrls.length) { _molstarLoad = null; return resolve(null); }
            const s = document.createElement('script');
            s.src = jsUrls[i++]; s.async = true;
            s.onload = () => { (typeof window.molstar !== 'undefined') ? resolve(window.molstar) : tryNext(); };
            s.onerror = () => { try { s.remove(); } catch (_) {} tryNext(); };
            document.head.appendChild(s);
        };
        tryNext();
    });
    return _molstarLoad;
}
// Back-compat wrapper used by the AlphaFold mount.
async function _afWaitMolstar() { return ensureMolstar(); }

const _AF_VIEWER_OPTS = {
    layoutIsExpanded: false, layoutShowControls: false, layoutShowRemoteState: false,
    layoutShowSequence: false, layoutShowLog: false, layoutShowLeftPanel: false,
    viewportShowExpand: true, viewportShowSelectionMode: false, viewportShowAnimation: false,
    pdbProvider: 'pdbe', emdbProvider: 'pdbe',
};

// Mol* paints the WebGL canvas on its OWN clear color (default near-white) —
// CSS can't recolor a WebGL canvas, and Viewer.create silently ignores an
// {r,g,b} backgroundColor. Set it through the canvas3d renderer API instead
// (Mol*'s Color is a plain 0xRRGGBB int at runtime) so the 3-D view is dark
// like the rest of the app rather than a white box inside a dark modal.
const _AF_BG = 0x0E141B;
function _afApplyBg(viewer) {
    try { viewer.plugin.canvas3d.setProps({ renderer: { backgroundColor: _AF_BG } }); } catch (_) {}
}

// Honest failure UI. A transient EBI outage gets a "temporarily unreachable +
// Retry" affordance (the model DOES exist, EBI just blipped); a genuine
// absence says so plainly. Never again claim "model doesn't exist" when the
// truth is "EBI was momentarily down."
function _afShowError(host, transient, retry) {
    if (!host) return;
    const wrap = document.createElement('div');
    wrap.className = 'alphafold-loading';
    wrap.textContent = transient
        ? 'AlphaFold-DB is temporarily unreachable — this usually clears in a moment.'
        : 'No AlphaFold model is available for this protein entry.';
    if (transient && typeof retry === 'function') {
        const btn = document.createElement('button');
        btn.type = 'button';
        btn.textContent = 'Retry';
        btn.style.cssText = 'display:block;margin:12px auto 0;padding:8px 20px;border:1px solid currentColor;border-radius:9px;background:transparent;color:inherit;font:inherit;cursor:pointer;min-height:44px';
        btn.addEventListener('click', () => {
            host.innerHTML = '<div class="alphafold-loading">Loading AlphaFold-DB structure…</div>';
            retry();
        });
        wrap.appendChild(btn);
    }
    host.innerHTML = '';
    host.appendChild(wrap);
}

// Mol* viewer mount. Loads the AlphaFold model from the EBI CDN and renders
// it inside #alphafoldViewer. We wait for the molstar global to appear
// (script is loaded async) before mounting.
async function mountAlphaFoldViewer(hit, host) {
    // `host` defaults to the page-level identify embed, but the per-variant
    // AlphaFold modal passes its own host (#foldViewer) so the same resilient
    // loader serves both embeds.
    host = host || document.getElementById('alphafoldViewer');
    if (!host) return;
    const pdbUrl = host.dataset.pdbUrl || (hit && hit.alphafold_url);
    if (!pdbUrl) return;

    const molstar = await _afWaitMolstar();
    if (!molstar) {
        _afShowError(host, true, () => mountAlphaFoldViewer(hit, host));   // CDN blip → retry, don't tell them to refresh
        return;
    }
    try {
        const viewer = await molstar.Viewer.create(host, _AF_VIEWER_OPTS);
        _afApplyBg(viewer);
        const { candidates, exists } = await _afResolve(pdbUrl);
        if (!await _afTryLoad(viewer, candidates)) {
            // exists === false → genuinely no model; otherwise treat as a
            // transient EBI blip and offer a retry.
            _afShowError(host, exists !== false, () => mountAlphaFoldViewer(hit, host));
            return;
        }
        const overlay = host.querySelector('.alphafold-loading');
        if (overlay) overlay.remove();
    } catch (err) {
        _afShowError(host, true, () => mountAlphaFoldViewer(hit, host));
    }
}

// ============================================================================
// ESMFold — per-variant structure prediction
// ----------------------------------------------------------------------------
// Triggered by the .fold-btn on each variant row. POSTs the variant's
// amino-acid sequence to Meta's public ESM Atlas API and renders the
// returned PDB inside #foldViewer using the same Mol* configuration as
// mountAlphaFoldViewer above, so the two embeds look identical.
//
// Endpoint   : https://api.esmatlas.com/foldSequence/v1/pdb/
// Method     : POST
// Body       : raw amino-acid sequence (plain text, no JSON wrapper)
// Response   : raw PDB text
// Constraints: ~400-residue cap on the public endpoint, shared rate limit
//              (returns 429 when throttled).
//
// All client-side — no server changes required for Hostinger / HF static.
// ============================================================================

const ESMFOLD_ENDPOINT  = 'https://api.esmatlas.com/foldSequence/v1/pdb/';
const ESMFOLD_MAX_RES   = 400;

// Tracks the variant ID of the in-flight fold so duplicate clicks coalesce
// and a stale response from a previous variant doesn't overwrite a newer one.
let foldInFlightVariant = null;

async function foldSequenceWithESMFold(sequence) {
    if (!sequence || typeof sequence !== 'string') {
        throw new Error('No protein sequence on this variant.');
    }
    // ESMFold rejects gaps, stops, and lowercase. Strip whitespace and any
    // trailing stop codon symbol; keep only canonical AA letters.
    const cleaned = sequence
        .replace(/\s+/g, '')
        .replace(/\*+$/g, '')
        .toUpperCase()
        .replace(/[^ACDEFGHIKLMNPQRSTVWY]/g, '');
    if (!cleaned) throw new Error('Sequence is empty after cleaning.');
    if (cleaned.length > ESMFOLD_MAX_RES) {
        // Actionable error: tell the user the cap is on Meta's public
        // endpoint (not on us), explain there's a fallback path, and
        // point at the existing BLAST → AlphaFold flow which works for
        // long sequences with no length cap and no Meta data exposure.
        throw new Error(
            `This sequence is ${cleaned.length} aa, but Meta's free ESMFold ` +
            `endpoint accepts only up to ${ESMFOLD_MAX_RES} aa. ` +
            `For longer proteins, click "Identify via NCBI BLAST" — if a ` +
            `UniProt match is found, the AlphaFold reference structure will ` +
            `load automatically and you can examine it alongside the variant.`,
        );
    }

    // Meta's free endpoint is alive but frequently transiently overloaded
    // (500s, the occasional HTML-page-with-200, brief network drops). Auto-retry
    // those a couple of times with backoff before surfacing an error — this is
    // the bulk of "it failed, worked on the 2nd try" reports. Hard errors
    // (413 too-long, 429 rate-limit) are NOT retried.
    const isPdb = (t) => /^(HEADER|ATOM|MODEL|TITLE|REMARK)/m.test(t);
    const ATTEMPTS = 3;
    let lastErr = null;
    for (let attempt = 0; attempt < ATTEMPTS; attempt++) {
        let response;
        try {
            response = await fetch(ESMFOLD_ENDPOINT, {
                method: 'POST',
                headers: { 'Content-Type': 'text/plain' },
                body: cleaned,
            });
        } catch (networkErr) {
            lastErr = new Error('Network error reaching the ESMFold API. Check your connection and try again.');
            await new Promise(r => setTimeout(r, 1200 * (attempt + 1)));
            continue;   // transient — retry
        }
        if (response.status === 413) {
            throw new Error(`Sequence too long for the public ESMFold endpoint (~${ESMFOLD_MAX_RES} aa cap).`);
        }
        if (response.status === 429) {
            throw new Error('Rate-limited by the public ESMFold API. Wait a minute and try again.');
        }
        if (response.status >= 500) {
            lastErr = new Error(`ESMFold server error (${response.status}). The free endpoint is sometimes overloaded.`);
            await new Promise(r => setTimeout(r, 1200 * (attempt + 1)));
            continue;   // transient — retry
        }
        if (!response.ok) {
            const body = await response.text().catch(() => '');
            throw new Error(`ESMFold request failed (${response.status}). ${body.slice(0, 140)}`);
        }
        const pdbText = await response.text();
        if (!isPdb(pdbText)) {
            lastErr = new Error('ESMFold returned an unexpected response (not a PDB).');
            await new Promise(r => setTimeout(r, 1200 * (attempt + 1)));
            continue;   // transient HTML-error page — retry
        }
        return pdbText;
    }
    throw new Error((lastErr && lastErr.message ? lastErr.message + ' ' : '') + 'Tried a few times — the free ESMFold endpoint is busy; please retry shortly.');
}

// Opens #foldModal, fires the fold, mounts Mol* with the returned PDB.
// Resilient to: duplicate clicks (coalesced via foldInFlightVariant),
// the user closing the modal mid-fold, and the user folding a second
// variant before the first one returns (the stale response is dropped).
// Per-session opt-in for sending sequences to Meta's public ESMFold API.
// Mirrors the BLAST / AlphaFold opt-in pattern: once the user has consented
// in a browser session, subsequent Fold clicks proceed without re-prompting.
// Stored in sessionStorage (not localStorage) so it expires when the tab is
// closed — consent doesn't silently persist across days.
const FOLD_CONSENT_KEY = 'turingdna.fold.consent.v1';

function hasFoldConsent() {
    try { return sessionStorage.getItem(FOLD_CONSENT_KEY) === '1'; }
    catch { return false; }
}
function grantFoldConsent() {
    try { sessionStorage.setItem(FOLD_CONSENT_KEY, '1'); } catch {}
}

async function openFoldModal(variant) {
    const modal = document.getElementById('foldModal');
    const sub   = document.getElementById('foldModalSub');
    const host  = document.getElementById('foldViewer');
    if (!modal || !host) return;

    // The modal is shared with the AlphaFold path — reset its chrome to
    // ESMFold and cancel any AlphaFold BLAST poll that was still running.
    _setFoldModalMode('esm', null);
    if (alphaFoldPollHandle) { clearTimeout(alphaFoldPollHandle); alphaFoldPollHandle = null; }

    const aaLen = (variant.Mutant_AA_Seq || '').length;

    // First-time gate: ESMFold sends the variant's protein sequence to Meta.
    // Show an editorial consent panel inside the modal before any network
    // call. Once accepted, this branch is skipped for the rest of the session.
    if (!hasFoldConsent()) {
        if (sub) sub.textContent =
            `${variant.Variant_ID} · ${aaLen} aa · awaiting consent`;
        host.innerHTML = `
            <div class="fold-consent">
                <p class="fold-consent-kicker">&sect; Consent</p>
                <h3 class="fold-consent-title"><em>Send sequence to Meta?</em></h3>
                <p class="fold-consent-body">
                    Predicting a 3-D structure with ESMFold requires sending this
                    variant's amino-acid sequence to <code>api.esmatlas.com</code>,
                    run by Meta AI. The request travels over HTTPS, but the
                    sequence is visible to Meta's servers.
                </p>
                <p class="fold-consent-body">
                    <em>Don't fold variants that are confidential or pre-publication
                    IP.</em> The on-server pipeline (scoring, search, codon
                    optimization) keeps sequences local; only ESMFold and the
                    opt-in BLAST identifier leave the machine.
                </p>
                <div class="fold-consent-actions">
                    <button class="ghost-btn" type="button" data-fold-cancel>Cancel</button>
                    <button class="primary" type="button" data-fold-consent>
                        Continue &middot; remember for this session
                    </button>
                </div>
            </div>
        `;
        modal.hidden = false;
        bindFoldModalDismiss();

        const cancelBtn  = host.querySelector('[data-fold-cancel]');
        const consentBtn = host.querySelector('[data-fold-consent]');
        if (cancelBtn)  cancelBtn.addEventListener('click', closeFoldModal);
        if (consentBtn) consentBtn.addEventListener('click', () => {
            grantFoldConsent();
            // Re-enter the modal flow now that consent is recorded; the gate
            // above is now satisfied and the fold proceeds normally.
            openFoldModal(variant);
        });
        return;
    }

    // Reset the modal to its loading state every time it opens — Mol* leaves
    // canvas children behind that we'd otherwise stack on top of.
    host.innerHTML = `
        <div class="alphafold-loading">
            <span class="identify-spinner"></span>
            Submitting sequence to ESMFold…
        </div>
    `;
    if (sub) sub.textContent = `Folding ${variant.Variant_ID} (${aaLen} aa)…`;
    modal.hidden = false;
    bindFoldModalDismiss();

    // If the same variant is already in flight, just show the modal —
    // don't fire a second request.
    if (foldInFlightVariant === variant.Variant_ID) return;
    foldInFlightVariant = variant.Variant_ID;

    try {
        const pdbText = await foldSequenceWithESMFold(variant.Mutant_AA_Seq || '');
        // If the user opened a different variant mid-fold, drop this result.
        if (foldInFlightVariant !== variant.Variant_ID) return;
        if (sub) sub.textContent =
            `${variant.Variant_ID} · ${aaLen} aa · predicted by ESMFold`;
        await mountESMFoldViewer(host, pdbText);
    } catch (err) {
        host.innerHTML = `
            <div class="alphafold-loading">
                <strong>Couldn't fold this variant.</strong><br>
                <span style="opacity:.75">${escapeHtml(err.message || String(err))}</span>
            </div>
        `;
        if (sub) sub.textContent = 'Folding failed';
        // Toast surfaces the error even if the user has scrolled past the modal.
        if (typeof showToast === 'function') showToast(err.message || 'Folding failed.', 'error');
    } finally {
        if (foldInFlightVariant === variant.Variant_ID) foldInFlightVariant = null;
    }
}

// Mounts Mol* into the given host using raw PDB text rather than a URL.
// Mirrors mountAlphaFoldViewer's options exactly so both embeds match.
async function mountESMFoldViewer(host, pdbText) {
    // Lazy-load Mol* on demand (jsDelivr → unpkg) — waits for the real load
    // event, no fixed timeout.
    host.innerHTML = '<div class="alphafold-loading">Preparing the 3-D viewer…</div>';
    const molstar = await ensureMolstar();
    if (!molstar) {
        host.innerHTML = '<div class="alphafold-loading">Couldn’t load the 3-D viewer (network/CDN issue). Check your connection and try again.</div>';
        return;
    }

    // Clear the placeholder before Mol* mounts its own canvas + UI into the host.
    host.innerHTML = '';
    try {
        const viewer = await molstar.Viewer.create(host, _AF_VIEWER_OPTS);
        _afApplyBg(viewer);   // dark WebGL background, matching the app
        // loadStructureFromData takes raw text directly — second arg is the
        // format ('pdb'), third arg is the isBinary flag.
        await viewer.loadStructureFromData(pdbText, 'pdb', false);
    } catch (err) {
        host.innerHTML =
            `<div class="alphafold-loading">Mol* couldn't render the structure (${escapeHtml(err.message || String(err))}).</div>`;
    }
}

// Wires the #foldModal backdrop, × button, and Esc key to closeFoldModal.
// Idempotent — safe to call on every open.
function bindFoldModalDismiss() {
    document.querySelectorAll('#foldModal [data-close-modal]').forEach((el) => {
        if (el.dataset.wired === '1') return;
        el.dataset.wired = '1';
        el.addEventListener('click', closeFoldModal);
    });
    if (!bindFoldModalDismiss._esc) {
        bindFoldModalDismiss._esc = true;
        document.addEventListener('keydown', (e) => {
            const modal = document.getElementById('foldModal');
            if (e.key === 'Escape' && modal && !modal.hidden) closeFoldModal();
        });
    }
}

function closeFoldModal() {
    const modal = document.getElementById('foldModal');
    if (modal) modal.hidden = true;
    // Mark the in-flight fold as orphaned so its response (if it eventually
    // arrives) won't try to mount into a hidden host.
    foldInFlightVariant = null;
    if (alphaFoldPollHandle) { clearTimeout(alphaFoldPollHandle); alphaFoldPollHandle = null; }
}

// ── AlphaFold path: closest known structure, for proteins ESMFold can't fold ─
// ESMFold (above) folds the EXACT variant but its public endpoint caps at
// ~400 aa. AlphaFold-DB can't fold a novel sequence at all — it serves only
// precomputed models keyed by UniProt accession. So for large (or any)
// proteins we BLAST the wild-type to find the nearest KNOWN protein and show
// ITS AlphaFold-DB model: a reference scaffold for the family, at any length —
// honestly NOT a fold of this variant's specific mutations. We reuse the
// /api/identify BLAST job (cached by sequence hash, so a prior Identify run
// returns instantly) and the same version-resilient Mol* loader as the
// page-level embed.
let alphaFoldPollHandle = null;

// Swap the shared #foldModal between its two engines (chrome only — title +
// disclaimer). `subText === null` leaves the sub-line for the caller to manage.
function _setFoldModalMode(mode, subText) {
    const title = document.getElementById('foldModalTitle');
    const sub   = document.getElementById('foldModalSub');
    const disc  = document.getElementById('foldModalDisclaimer');
    if (mode === 'alphafold') {
        if (title) title.textContent = 'Closest known structure · AlphaFold-DB';
        if (disc) disc.innerHTML =
            'Closest known protein to your <strong>wild-type</strong>, found via ' +
            '<a href="https://blast.ncbi.nlm.nih.gov" target="_blank" rel="noopener">NCBI BLAST</a> ' +
            'and rendered from <a href="https://alphafold.ebi.ac.uk" target="_blank" rel="noopener">AlphaFold-DB</a>. ' +
            'No length cap — the structure path for proteins too large for ESMFold. ' +
            '<strong>This is a reference scaffold for the protein family, not a fold of this variant’s mutations.</strong> ' +
            'Drag to rotate · scroll to zoom · double-click to fit. ' +
            'Backbone confidence colored by pLDDT (blue&nbsp;=&nbsp;high, orange&nbsp;=&nbsp;low).';
    } else {
        if (title) title.textContent = 'Predicted structure · ESMFold';
        if (disc) disc.innerHTML =
            'Predicted by <a href="https://esmatlas.com/about" target="_blank" rel="noopener">ESMFold</a> (Meta AI). ' +
            '<strong>The variant’s amino-acid sequence is sent to <code>api.esmatlas.com</code></strong> ' +
            'over HTTPS — encrypted in transit, visible to Meta’s servers. Do not fold ' +
            'confidential or pre-publication sequences. ' +
            'Drag to rotate · scroll to zoom · double-click to fit. ' +
            'Backbone confidence colored by pLDDT (blue&nbsp;=&nbsp;high, orange&nbsp;=&nbsp;low).';
    }
    if (sub && subText != null) sub.textContent = subText;
}

async function openAlphaFoldModal(variant) {
    const modal = document.getElementById('foldModal');
    const host  = document.getElementById('foldViewer');
    if (!modal || !host) return;

    if (!state.sessionId) {
        showToast('Load and run a sequence first — AlphaFold needs the wild-type to search.', 'warn');
        return;
    }

    // BLAST consent (same per-session opt-in as the page-level Identify): the
    // wild-type sequence is sent to NCBI. Show an in-modal consent step the
    // first time, then remember it for the session.
    if (!hasBlastConsent()) {
        _setFoldModalMode('alphafold', 'awaiting consent');
        host.innerHTML = `
            <div class="fold-consent">
                <p class="fold-consent-kicker">&sect; Consent</p>
                <h3 class="fold-consent-title"><em>Search NCBI for a known structure?</em></h3>
                <p class="fold-consent-body">
                    AlphaFold-DB only holds models for <em>known</em> proteins, so to show
                    one we send your <strong>wild-type</strong> protein sequence to
                    <code>blast.ncbi.nlm.nih.gov</code> to find the closest match, then load
                    its structure from <code>alphafold.ebi.ac.uk</code>. Takes ~30–90&nbsp;s.
                </p>
                <p class="fold-consent-body">
                    <em>Skip this if your sequence is confidential or pre-publication IP.</em>
                    Scoring, search and codon optimization stay on-server; only this opt-in
                    BLAST leaves the machine.
                </p>
                <div class="fold-consent-actions">
                    <button class="ghost-btn" type="button" data-af-cancel>Cancel</button>
                    <button class="primary" type="button" data-af-consent>
                        Continue &middot; remember for this session
                    </button>
                </div>
            </div>
        `;
        modal.hidden = false;
        bindFoldModalDismiss();
        const cancelBtn  = host.querySelector('[data-af-cancel]');
        const consentBtn = host.querySelector('[data-af-consent]');
        if (cancelBtn)  cancelBtn.addEventListener('click', closeFoldModal);
        if (consentBtn) consentBtn.addEventListener('click', () => {
            grantBlastConsent();
            openAlphaFoldModal(variant);   // re-enter now that consent is recorded
        });
        return;
    }

    // Orphan any pending ESMFold response so it can't mount over this one.
    foldInFlightVariant = null;
    if (alphaFoldPollHandle) { clearTimeout(alphaFoldPollHandle); alphaFoldPollHandle = null; }

    _setFoldModalMode('alphafold', 'Searching NCBI for the closest known structure…');
    host.innerHTML = `
        <div class="alphafold-loading">
            <span class="identify-spinner"></span>
            Searching NCBI for the closest known protein… (30–90 s)
        </div>
    `;
    modal.hidden = false;
    bindFoldModalDismiss();

    try {
        const res = await fetch('/api/identify', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({
                session_id: state.sessionId,
                cds_feature: state.chosenCds,
                blast_consent: hasBlastConsent(),
            }),
        });
        const data = await res.json();
        if (!res.ok) throw new Error(data.error || 'BLAST submission failed.');
        if (data.cached && data.status === 'done') { _renderFoldAlphaFold(data, host); return; }
        _pollAlphaFoldModal(data.job_id, host);
    } catch (err) {
        host.innerHTML =
            `<div class="alphafold-loading"><strong>Couldn’t reach NCBI BLAST.</strong><br>` +
            `<span style="opacity:.75">${escapeHtml(err.message || String(err))}</span></div>`;
    }
}

function _pollAlphaFoldModal(jobId, host) {
    if (alphaFoldPollHandle) clearTimeout(alphaFoldPollHandle);
    alphaFoldPollHandle = setTimeout(async () => {
        const modal = document.getElementById('foldModal');
        if (!modal || modal.hidden) return;   // user closed the modal — stop
        try {
            const res = await fetch(`/api/identify/${jobId}`);
            const data = await res.json();
            if (!res.ok) throw new Error(data.error || 'Lost the BLAST job.');
            if (data.status === 'done')  { _renderFoldAlphaFold(data, host); return; }
            if (data.status === 'error') {
                host.innerHTML =
                    `<div class="alphafold-loading"><strong>BLAST failed.</strong><br>` +
                    `<span style="opacity:.75">${escapeHtml(data.error || 'unknown error')}</span></div>`;
                return;
            }
            const elapsed = data.elapsed_seconds != null ? data.elapsed_seconds.toFixed(0) : '0';
            const phase = { pending: 'Queued', submitting: 'Submitting to NCBI',
                            running: 'NCBI is searching nr', parsing: 'Parsing results' }[data.status] || data.status;
            host.innerHTML =
                `<div class="alphafold-loading"><span class="identify-spinner"></span> ` +
                `${escapeHtml(phase)} · ${escapeHtml(elapsed)}s (NCBI queues can take 30–90 s)</div>`;
            _pollAlphaFoldModal(jobId, host);
        } catch (err) {
            host.innerHTML =
                `<div class="alphafold-loading"><strong>Lost the BLAST job.</strong><br>` +
                `<span style="opacity:.75">${escapeHtml(err.message || String(err))}</span></div>`;
        }
    }, 2000);
}

function _renderFoldAlphaFold(data, host) {
    const hits = (data && data.hits) || [];
    // First UniProt-mapped hit in the top 5 (the very top may be RefSeq-only).
    const afHit = hits.slice(0, 5).find(h => h.uniprot && h.alphafold_url);
    const sub = document.getElementById('foldModalSub');
    if (!afHit) {
        const top = hits[0];
        host.innerHTML = `
            <div class="alphafold-loading">
                <strong>No known structure to show.</strong><br>
                <span style="opacity:.8">${hits.length
                    ? 'The closest NCBI match' + (top && top.description ? ' (' + escapeHtml(top.description) + ')' : '') +
                      ' has no UniProt / AlphaFold-DB entry. '
                    : 'No significant NCBI matches — this sequence may be de novo or heavily engineered. '}
                For sequences ≤ ${ESMFOLD_MAX_RES} aa you can fold the exact variant with <em>ESMFold</em>.</span>
            </div>`;
        if (sub) sub.textContent = 'No AlphaFold model available';
        return;
    }
    const afHomolog = afHit.uniprot_via === 'swissprot_homolog';
    const afOrg = afHomolog ? (afHit.uniprot_organism || afHit.organism || '') : (afHit.organism || '');
    if (sub) sub.textContent =
        `Closest known: UniProt ${afHit.uniprot}${afOrg ? ' · ' + afOrg : ''}` +
        (afHomolog && afHit.uniprot_identity_pct != null ? ` · ${afHit.uniprot_identity_pct}% id` : '');
    // Mount straight into #foldViewer (it already carries .alphafold-viewer).
    host.dataset.pdbUrl = afHit.alphafold_url;
    host.dataset.uniprot = afHit.uniprot;
    host.innerHTML =
        '<div class="alphafold-loading"><span class="identify-spinner"></span> Loading AlphaFold-DB structure…</div>';
    mountAlphaFoldViewer(afHit, host);
}

function showToast(message, level = 'info') {
    const existing = document.getElementById('dee-toast');
    if (existing) existing.remove();
    const t = document.createElement('div');
    t.id = 'dee-toast';
    t.className = `toast toast-${level}`;
    // Errors get an "!" glyph instead of the success "✓" — small but means
    // a colorblind user can still tell info / warn / error apart at a glance.
    const glyph = level === 'error' ? '!' : (level === 'warn' ? '⚠' : '✓');
    t.innerHTML = `
        <span class="toast-check">${glyph}</span>
        <span class="toast-msg">${escapeHtml(message)}</span>
    `;
    document.body.appendChild(t);
    requestAnimationFrame(() => t.classList.add('toast-in'));
    // High-stakes failures stay on screen longer so the user actually sees
    // them. 2.4 s is fine for info; clipboard / save errors get 7 s.
    const dwell = level === 'error' ? 7000 : (level === 'warn' ? 4200 : 2400);
    setTimeout(() => {
        t.classList.remove('toast-in');
        t.classList.add('toast-out');
        setTimeout(() => t.remove(), 320);
    }, dwell);
}

function renderDetailPanel(v) {
    const isWt = v.Variant_ID === 'WT';
    const gc = Number(v.GC_Percent);
    const gcWarn = !Number.isNaN(gc) && (gc < 40 || gc > 60)
        ? `<span class="gc-warn">${gc < 40 ? 'low GC' : 'high GC'}</span>`
        : '';
    const annealing = v.Annealing_Temp_C != null ? `${v.Annealing_Temp_C} °C` : '—';
    const fwdTm = v.Primer_Fwd_Tm_C != null ? `${v.Primer_Fwd_Tm_C} °C` : '—';
    const revTm = v.Primer_Rev_Tm_C != null ? `${v.Primer_Rev_Tm_C} °C` : '—';
    const fwdGc = v.Primer_Fwd_GC_Percent != null ? `${v.Primer_Fwd_GC_Percent}%` : '—';
    const revGc = v.Primer_Rev_GC_Percent != null ? `${v.Primer_Rev_GC_Percent}%` : '—';
    // 1-indexed AA positions mutated in this variant — drives the highlight
    // overlays in the mutant-protein and DNA blocks below. Empty for WT.
    const mutPositionList = [];
    const mutPositionSet = new Set();
    (v.Mutations_AA || '').split(',').forEach((m) => {
        const match = m.trim().match(/^[A-Z](\d+)[A-Z\*]$/);
        if (match) {
            const pos = parseInt(match[1], 10);
            mutPositionList.push(pos);
            mutPositionSet.add(pos);
        }
    });
    const mutationsDisplay = isWt
        ? '<span class="muted">— (unmutated)</span>'
        : escapeHtml(v.Mutations_AA || '');
    const proteinHeader = isWt
        ? `Wild-type protein (${(v.Mutant_AA_Seq || '').length} aa)`
        : `Mutant protein (${(v.Mutant_AA_Seq || '').length} aa) · mutations highlighted in brand color`;
    const dnaHeader = isWt
        ? `Codon-optimized wild-type DNA (${v.Length_bp} bp)`
        : `Optimized DNA sequence (${v.Length_bp} bp) · mutated codons highlighted`;

    // Restriction-site honesty banner. The server's ``Restriction_Sites_Unresolved``
    // is the count of forbidden recognition sites STILL PRESENT in the final DNA
    // after synonymous scrubbing (or unchanged if the user manually edited the
    // sequence). Anything > 0 means a Golden Gate / Type IIS assembly will fail
    // when the enzyme cuts inside the insert. We surface this prominently AND
    // gate the Synthesize buttons so a hurried click can't ship a broken insert.
    const reUnresolved = Number(v.Restriction_Sites_Unresolved) || 0;
    const synthBlocked = reUnresolved > 0;
    const restrictionBanner = synthBlocked
        ? `
            <div class="re-warn-banner" role="alert">
                <strong>⚠ ${reUnresolved} forbidden restriction site${reUnresolved > 1 ? 's' : ''} still present</strong>
                <p>This DNA still contains ${reUnresolved} BsaI / BsmBI / NotI recognition site${reUnresolved > 1 ? 's' : ''} that synonymous scrubbing couldn't remove. A Golden Gate / Type IIS assembly will be cut at these positions and the insert will fragment. Edit the DNA to break the offending codons before ordering, or pick a vector that doesn't rely on these enzymes.</p>
            </div>
          `
        : '';

    return `
        <div class="detail-panel${isWt ? ' detail-panel-wt' : ''}${synthBlocked ? ' detail-panel-re-warn' : ''}">
            ${restrictionBanner}
            <div class="detail-section">
                <h4>PCR setup</h4>
                <div class="pcr-summary">
                    <div><span class="pcr-label">Amplicon length</span><span class="pcr-val">${v.Length_bp} bp</span></div>
                    <div><span class="pcr-label">GC content</span><span class="pcr-val">${Number(v.GC_Percent).toFixed(1)}% ${gcWarn}</span></div>
                    <div><span class="pcr-label">Annealing temp</span><span class="pcr-val">${annealing}</span></div>
                    <div><span class="pcr-label">Mutations</span><span class="pcr-val">${mutationsDisplay}</span></div>
                </div>
            </div>

            <div class="detail-section">
                <h4>Primers</h4>
                <div class="primer-grid">
                    <div class="primer-card">
                        <div class="primer-card-head">
                            <span class="primer-label">Forward</span>
                            <span class="primer-direction">5′ → 3′</span>
                        </div>
                        <div class="primer-seq" data-copy="${escapeHtml(v.Primer_Fwd)}">${escapeHtml(v.Primer_Fwd)}</div>
                        <div class="primer-stats">
                            <span>Tm <strong>${fwdTm}</strong></span>
                            <span>GC <strong>${fwdGc}</strong></span>
                            <span>Length <strong>${(v.Primer_Fwd || '').length} bp</strong></span>
                        </div>
                        <div class="primer-actions">
                            <button class="copy-btn" data-copy="${escapeHtml(v.Primer_Fwd)}">Copy</button>
                        </div>
                    </div>

                    <div class="primer-card">
                        <div class="primer-card-head">
                            <span class="primer-label">Reverse</span>
                            <span class="primer-direction">5′ → 3′ (RC of 3′ end)</span>
                        </div>
                        <div class="primer-seq" data-copy="${escapeHtml(v.Primer_Rev)}">${escapeHtml(v.Primer_Rev)}</div>
                        <div class="primer-stats">
                            <span>Tm <strong>${revTm}</strong></span>
                            <span>GC <strong>${revGc}</strong></span>
                            <span>Length <strong>${(v.Primer_Rev || '').length} bp</strong></span>
                        </div>
                        <div class="primer-actions">
                            <button class="copy-btn" data-copy="${escapeHtml(v.Primer_Rev)}">Copy</button>
                        </div>
                    </div>
                </div>
                <div class="primer-actions" style="margin-top:8px">
                    <button class="copy-btn" data-copy="${escapeHtml((v.Primer_Fwd || '') + '\t' + (v.Primer_Rev || ''))}">Copy primer pair (TSV)</button>
                </div>
            </div>

            <div class="detail-section">
                <h4>${proteinHeader}</h4>
                <div class="sequence-block">${formatProteinDiff(v.Mutant_AA_Seq || '', tableState.wtProtein || '', mutPositionSet)}</div>
            </div>

            <!--
                Editable codon-optimized DNA. The textarea is hidden by default
                (read-only view shows the highlighted formatted block); clicking
                "Edit DNA" reveals it, and onInput it validates + persists back
                to tableState.variants[i].Optimized_DNA_Seq so the Cloning
                Designer + Synthesize buttons all see the edited sequence.
            -->
            <div class="detail-section dna-edit-section" data-variant-id="${escapeHtml(v.Variant_ID)}">
                <div class="dna-edit-head">
                    <h4>${dnaHeader}</h4>
                    <div class="dna-edit-actions">
                        <button class="ghost-btn dna-edit-toggle" data-variant="${escapeHtml(v.Variant_ID)}" type="button">Edit DNA</button>
                        <button class="ghost-btn dna-edit-reset" data-variant="${escapeHtml(v.Variant_ID)}" type="button" hidden>Revert</button>
                    </div>
                </div>
                <div class="dna-view" data-variant="${escapeHtml(v.Variant_ID)}">
                    <div class="sequence-block">${formatDna(v.Optimized_DNA_Seq, mutPositionList)}</div>
                </div>
                <div class="dna-edit-wrap" data-variant="${escapeHtml(v.Variant_ID)}" hidden>
                    <!--
                        spellcheck/autocorrect/autocapitalize all OFF so iOS
                        Safari doesn't replace 'ACGT' runs with dictionary
                        words or capitalize the first letter. inputmode=text
                        keeps the on-screen keyboard out of URL/decimal mode.
                    -->
                    <textarea class="dna-edit-textarea" data-variant="${escapeHtml(v.Variant_ID)}"
                              spellcheck="false" autocorrect="off" autocapitalize="off"
                              autocomplete="off" inputmode="text"
                              rows="8">${escapeHtml(v.Optimized_DNA_Seq || '')}</textarea>
                    <div class="dna-edit-stats" data-variant="${escapeHtml(v.Variant_ID)}"></div>
                </div>
            </div>

            <div class="detail-section cloning-section" data-variant-id="${escapeHtml(v.Variant_ID)}">
                <h4>Cloning Designer · prepare for synthesis</h4>
                <p class="cloning-hint">
                    Pick a cloning method, destination vector, restriction enzymes (or
                    Type IIS overhangs), and optional fusion tags. The Designer
                    assembles the full insert in real time, validates it against the
                    vector's MCS, and flags internal restriction-site clashes that
                    would break your digest.
                </p>

                <!-- The Designer container; renderDesigner() fills it. -->
                <div class="cloning-designer" data-variant="${escapeHtml(v.Variant_ID)}"></div>

                <div class="synth-row" style="margin-bottom:10px">
                    <span class="synth-row-label">Continue with this insert</span>
                    <button class="primary" type="button" data-build-plasmid="${escapeHtml(v.Variant_ID)}">Open in Plasmid Editor &rarr;</button>
                </div>
                <div class="synth-row">
                    <span class="synth-row-label">Synthesize via</span>
                    ${Object.entries(VENDORS).map(([key, vendor]) => `
                        <button class="copy-btn synth-btn${synthBlocked ? ' synth-btn-warn' : ''}"
                                data-synth-id="${escapeHtml(v.Variant_ID)}"
                                data-synth-vendor="${escapeHtml(key)}"
                                data-synth-blocked="${synthBlocked ? '1' : '0'}"
                                ${synthBlocked ? `title="This sequence contains ${reUnresolved} unresolvable restriction site(s). Click to override."` : ''}>
                            <span>${escapeHtml(vendor.name)}</span>
                            <svg class="synth-arrow" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true" width="14" height="14">
                                <path d="M7 7h10v10"/><path d="M7 17 17 7"/>
                            </svg>
                        </button>
                    `).join('')}
                </div>
                <div class="primer-actions" style="margin-top:10px">
                    <button class="copy-btn${synthBlocked ? ' synth-btn-warn' : ''}"
                            data-cloning-copy="formatted" data-variant="${escapeHtml(v.Variant_ID)}"
                            data-synth-blocked="${synthBlocked ? '1' : '0'}"
                            ${synthBlocked ? `title="Contains ${reUnresolved} unresolvable restriction site(s)."` : ''}>Copy designed insert</button>
                    <!--
                        These two buttons MUST resolve from live tableState at
                        click time. The previous implementation baked
                        v.Optimized_DNA_Seq / v.Mutant_AA_Seq into data-copy
                        when the panel rendered, so the user could edit the
                        DNA, save, and still copy the pre-edit sequence into
                        their vendor order form. data-copy-live + a variant
                        id keeps the buttons honest — wireCopyButtons reads
                        tableState.variants at the click.
                    -->
                    <button class="copy-btn" data-copy-live="dna" data-variant="${escapeHtml(v.Variant_ID)}">Copy bare CDS</button>
                    <button class="copy-btn" data-copy-live="protein" data-variant="${escapeHtml(v.Variant_ID)}">Copy protein</button>
                </div>
            </div>
        </div>
    `;
}

function formatDna(dna, highlightAaPositions = []) {
    // GenBank/EMBOSS-style layout with optional mutation highlighting:
    //   1  atgccgaaa ttaggccct gaacgtttt gcaggcgaa cggtttcca aagttaata
    //  61  tcgggcatg ...
    // Each line is 6 blocks of 10 nt = 60 nt. AA position N highlights nt
    // positions (N-1)*3 .. (N-1)*3 + 2 (its codon).
    if (!dna) return '';
    const lower = dna.toLowerCase();
    const charsPerLine = 60;
    const blockSize = 10;
    const padWidth = String(lower.length).length;
    // Build a set of nt indices to highlight.
    const hi = new Set();
    for (const aaPos of highlightAaPositions) {
        const start = (aaPos - 1) * 3;
        hi.add(start); hi.add(start + 1); hi.add(start + 2);
    }
    const lines = [];
    for (let i = 0; i < lower.length; i += charsPerLine) {
        const num = String(i + 1).padStart(padWidth, ' ');
        // Build the line char-by-char so we can wrap highlighted nt in spans.
        let lineHtml = '';
        for (let j = 0; j < charsPerLine && i + j < lower.length; j++) {
            if (j > 0 && j % blockSize === 0) lineHtml += ' ';
            const nt = lower[i + j];
            if (hi.has(i + j)) {
                lineHtml += `<span class="pos-mut">${escapeHtml(nt)}</span>`;
            } else {
                lineHtml += escapeHtml(nt);
            }
        }
        lines.push(`<span class="seq-num">${escapeHtml(num)}</span>  ${lineHtml}`);
    }
    return lines.join('\n');
}

function formatProteinDiff(mutantProtein, wtProtein, mutPositions) {
    // Render mutant protein with mutated residues highlighted, tooltip showing
    // WT residue. mutPositions is a Set of 1-indexed AA positions.
    if (!mutantProtein) return '';
    const charsPerLine = 60;
    const blockSize = 10;
    const padWidth = String(mutantProtein.length).length;
    const lines = [];
    for (let i = 0; i < mutantProtein.length; i += charsPerLine) {
        const num = String(i + 1).padStart(padWidth, ' ');
        let lineHtml = '';
        for (let j = 0; j < charsPerLine && i + j < mutantProtein.length; j++) {
            if (j > 0 && j % blockSize === 0) lineHtml += ' ';
            const pos = i + j + 1;  // 1-indexed
            const aa = mutantProtein[i + j];
            if (mutPositions.has(pos)) {
                const wt = wtProtein[i + j] || '?';
                lineHtml += `<span class="pos-mut" title="WT ${wt}${pos}${aa}">${escapeHtml(aa)}</span>`;
            } else {
                lineHtml += escapeHtml(aa);
            }
        }
        lines.push(`<span class="seq-num">${escapeHtml(num)}</span>  ${lineHtml}`);
    }
    return lines.join('\n');
}

// Try to write to the clipboard with a user-visible failure path. When
// the clipboard API rejects (iframe missing permission, insecure context,
// focus lost, browser policy) we previously swallowed the error silently
// — a click on Synthesize would do nothing, the user would open the
// vendor tab themselves, and the WRONG previously-copied bytes would
// land in their order form. Surfacing the failure as a high-visibility
// toast is the bare minimum so the user knows nothing was copied. The
// caller's `await` resolves false on failure so they can also abort
// whatever follow-on action (vendor redirect, modal open) was queued.
async function copyToClipboardOrToast(text, label = 'sequence') {
    if (!text) {
        showToast(`Nothing to copy (${label} is empty).`, 'warn');
        return false;
    }
    try {
        await navigator.clipboard.writeText(text);
        return true;
    } catch (err) {
        const detail = err?.message ? ` (${err.message})` : '';
        showToast(
            `Clipboard write blocked${detail}. The ${label} was NOT copied. ` +
            `Select the sequence in the panel and use ⌘C / Ctrl-C, or grant ` +
            `clipboard permission to this page and retry.`,
            'error',
        );
        return false;
    }
}

// Shared "Materials & methods (copy-paste)" renderer — ported from the
// Directed Evolution runMeta so every engine produces citable, paste-ready
// methods text + run-parameter pills for a thesis/paper. `pills` is
// [[label, value], …]; `methodsHtml` may contain <cite>…</cite>; the Copy
// button copies the plain-text version.
function tdRenderMethods(boxId, pills, methodsHtml) {
    const box = document.getElementById(boxId);
    if (!box) return;
    if (!methodsHtml) { box.hidden = true; box.innerHTML = ''; return; }
    box.hidden = false;
    // Cite the platform itself (in addition to the underlying methods papers),
    // so a researcher's Methods section credits TuringDNA. Appended once here so
    // every tool's methods paragraph carries it; the <a> is stripped for the
    // plain-text copy, leaving "turingdna.com".
    methodsHtml += ' Analyses were performed with TuringDNA (<a href="https://turingdna.com" target="_blank" rel="noopener">turingdna.com</a>).';
    const esc = (s) => (typeof escapeHtml === 'function' ? escapeHtml(String(s)) : String(s));
    const pillHtml = (pills || [])
        .filter((p) => p && p[1] != null && p[1] !== '')
        .map((p) => `<span class="run-pill">${esc(p[0])} <strong>${esc(String(p[1]))}</strong></span>`)
        .join('');
    const plain = methodsHtml.replace(/<[^>]+>/g, '');
    box.innerHTML =
        (pillHtml ? `<div class="run-meta-pills">${pillHtml}</div>` : '') +
        `<div class="run-methods">
            <div class="run-methods-head">
                <h4>Materials &amp; methods (copy-paste)</h4>
                <button class="copy-btn" data-copy="${esc(plain)}">Copy</button>
            </div>
            <div class="run-methods-body">${methodsHtml}</div>
        </div>`;
    if (typeof wireCopyButtons === 'function') wireCopyButtons(box);
}

function wireCopyButtons(scope) {
    // Plain "copy this string to clipboard" buttons. Static payload baked
    // into data-copy at render time. Safe for things that never change
    // (primer sequences, mutation labels, methods text). For anything the
    // user can edit, use data-copy-live below so the click reads live state.
    scope.querySelectorAll('[data-copy]').forEach((el) => {
        if (!el.classList.contains('copy-btn')) return;
        el.addEventListener('click', async (e) => {
            e.stopPropagation();
            const text = el.dataset.copy;
            const ok = await copyToClipboardOrToast(text, 'value');
            if (!ok) return;
            const original = el.innerHTML;
            el.classList.add('copied');
            el.textContent = 'Copied ✓';
            setTimeout(() => {
                el.classList.remove('copied');
                el.innerHTML = original;
            }, 1400);
        });
    });

    // Live-resolving copy buttons — read tableState.variants at click time
    // so a user edit committed via persistEditedDna is reflected immediately.
    // data-copy-live="dna|protein" + data-variant="<Variant_ID>"
    scope.querySelectorAll('[data-copy-live]').forEach((el) => {
        if (!el.classList.contains('copy-btn')) return;
        el.addEventListener('click', async (e) => {
            e.stopPropagation();
            const which = el.dataset.copyLive;
            const variantId = el.dataset.variant;
            const v = (tableState.variants || []).find(x => x.Variant_ID === variantId);
            if (!v) return;
            const text = which === 'dna'
                ? (v.Optimized_DNA_Seq || '')
                : (v.Mutant_AA_Seq || '');
            const label = which === 'dna' ? `${variantId} DNA` : `${variantId} protein`;
            const ok = await copyToClipboardOrToast(text, label);
            if (!ok) return;
            const original = el.innerHTML;
            el.classList.add('copied');
            el.textContent = `Copied ✓ (${text.length} ${which === 'dna' ? 'bp' : 'aa'})`;
            setTimeout(() => {
                el.classList.remove('copied');
                el.innerHTML = original;
            }, 1400);
        });
    });

    // "Copy formatted DNA" — reads the live cloning-state for this variant
    // so the user gets the currently-previewed format (not stale data baked
    // into a data-copy attribute at render time). Honors data-synth-blocked
    // so a sequence with unresolvable restriction sites prompts for
    // confirmation before the bytes hit the clipboard.
    scope.querySelectorAll('[data-cloning-copy]').forEach((el) => {
        if (!el.classList.contains('copy-btn')) return;
        el.addEventListener('click', async (e) => {
            e.stopPropagation();
            const variantId = el.dataset.variant;
            const blocked = el.dataset.synthBlocked === '1';
            const formatted = formattedDnaFor(variantId);
            if (!formatted) return;

            // Per-session verification gate. First copy-insert action of the
            // session shows the disclaimer modal; subsequent copies in the
            // same tab skip it (a research-tool would be unusable with a
            // modal on every click).
            const verifyOk = await ensureSynthVerified(`
                <strong>${escapeHtml(variantId)}</strong> &middot;
                ${escapeHtml(String(formatted.full.length))} bp designed insert &middot;
                to clipboard for vendor order form
            `);
            if (!verifyOk) return;

            // RE-warn confirm still runs AFTER the verification gate so the
            // user sees both pieces of information when both apply.
            if (blocked) {
                const ok = window.confirm(
                    `${variantId} still contains unresolvable restriction sites. ` +
                    `Copying the designed insert anyway?`,
                );
                if (!ok) return;
            }

            const ok = await copyToClipboardOrToast(formatted.full, `${variantId} designed insert`);
            if (!ok) return;
            const original = el.innerHTML;
            el.classList.add('copied');
            el.textContent = `Copied ✓ (${formatted.full.length} bp)`;
            setTimeout(() => {
                el.classList.remove('copied');
                el.innerHTML = original;
            }, 1600);
        });
    });

    // "Open in Plasmid Editor" — sends the live designed insert (the Cloning
    // Designer's current vector/method/tag selection, vector arm through
    // CDS) to the Plasmid Editor as a FASTA record so the user can map it
    // and run restriction analysis on the actual construct, not just the bare CDS.
    scope.querySelectorAll('[data-build-plasmid]').forEach((el) => {
        el.addEventListener('click', (e) => {
            e.stopPropagation();
            const variantId = el.dataset.buildPlasmid;
            const formatted = formattedDnaFor(variantId);
            const seq = formatted ? formatted.full : '';
            sendToPlasmid(seq, `${variantId} designed insert`);
        });
    });

    // Synthesize-via-X buttons — one per vendor, each carrying its vendor
    // key in data-synth-vendor. Sends the *currently-selected* formatted
    // DNA (per the cloning section's dropdown), not the bare CDS, so the
    // vendor receives an order with proper cloning ends already attached.
    //
    // If data-synth-blocked="1" we interpose a native confirm() before any
    // network call or clipboard write. The dialog names the specific
    // problem (unresolvable restriction sites) so a hurried click doesn't
    // ship an insert that the vendor's Golden Gate / Type IIS workflow
    // will fragment on enzyme digestion.
    scope.querySelectorAll('.synth-btn').forEach((el) => {
        el.addEventListener('click', (e) => {
            e.stopPropagation();
            const variantId = el.dataset.synthId;
            const vendorKey = el.dataset.synthVendor;
            const blocked = el.dataset.synthBlocked === '1';
            if (blocked) {
                const ok = window.confirm(
                    `${variantId} still contains unresolvable restriction sites ` +
                    `(BsaI / BsmBI / NotI). Golden Gate or Type IIS assemblies ` +
                    `using these enzymes will cut inside the insert and the ` +
                    `construct will fragment.\n\nProceed anyway?`,
                );
                if (!ok) return;
            }
            const formatted = formattedDnaFor(variantId);
            // Fall back to the bare CDS in the unlikely event the cloning
            // state wasn't seeded (e.g. user clicked the synth button
            // before the dropdown wired up).
            let dna = formatted ? formatted.full : '';
            if (!dna) {
                const v = (tableState.variants || []).find(x => x.Variant_ID === variantId);
                dna = v?.Optimized_DNA_Seq || '';
            }
            synthesizeDna(dna, variantId, vendorKey);
            const original = el.innerHTML;
            el.classList.add('copied');
            el.innerHTML = 'Copied ✓';
            setTimeout(() => {
                el.classList.remove('copied');
                el.innerHTML = original;
            }, 2200);
        });
    });
}

// ============================================================== DNA EDIT
// In-place editing of any variant's codon-optimized DNA. The persistence
// model is atomic: client-side keystrokes update only the live validation
// pills, and the explicit "Save & close" button POSTs the textarea contents
// to /api/variants/<job>/<id>/dna. The server re-derives every column from
// those bytes (translation, mutations diff vs WT, PCR metrics, restriction
// scan), rewrites the library CSV on disk atomically, and returns the new
// row. We replace tableState.variants[i] with that response so what the
// user sees on screen, what /api/download streams, and what gets ordered
// are guaranteed to be the same string. No edit ever lives client-only.
//
// Revert posts the original snapshot through the same endpoint so the
// server matches the screen after a roll-back.

// Snapshot of the server-supplied DNA per variant — taken on first edit so
// Revert always has the pristine sequence even after many save cycles.
const originalDnaSnapshots = new Map();

// Strict ACGT sanitizer + validator. Module-scoped so wireDnaEdit and any
// future caller share one implementation. Returns { clean, dropped, gc, len, warnings }.
const STOP_CODONS_SET = new Set(['TAA', 'TAG', 'TGA']);
function validateDnaEdit(raw) {
    // RNA → DNA before anything else, mirror the server's _clean() so a
    // paste from an mRNA-centric tool doesn't silently lose every U.
    const upper = (raw || '').toUpperCase().replace(/U/g, 'T');

    // Track WHERE each non-ACGT character was so we can tell the user
    // exactly what was dropped and at which 1-indexed position in their
    // typed input (post-whitespace). Zero-width Unicode (ZWSP, BOM, soft
    // hyphen, word joiner) often hides inside PDF/Word pastes and the
    // user will never spot it from a "removed 1 character" warning alone.
    // Strip visible whitespace AND the most common invisible/zero-width
    // characters that PDF/Word copy-paste injects between residues. Codepoints
    // spelled out so future readers can see what we're filtering — these are
    // the ones that have actually burned us in the field:
    //   \s — visible whitespace (space, tab, newline, etc.)
    //   U+00A0 NO-BREAK SPACE         U+00AD SOFT HYPHEN
    //   U+200B ZERO-WIDTH SPACE       U+200C ZERO-WIDTH NON-JOINER
    //   U+200D ZERO-WIDTH JOINER      U+2060 WORD JOINER
    //   U+202F NARROW NO-BREAK SPACE  U+FEFF BYTE ORDER MARK
    const STRIP_RE = /[\s\u00a0\u00ad\u200b\u200c\u200d\u2060\u202f\ufeff]/;
    const dropped = [];
    const cleanChars = [];
    let meaningfulPos = 0;
    for (let i = 0; i < upper.length; i++) {
        const ch = upper[i];
        if (STRIP_RE.test(ch)) continue;
        meaningfulPos += 1;
        if (ch === 'A' || ch === 'C' || ch === 'G' || ch === 'T') {
            cleanChars.push(ch);
        } else {
            dropped.push({ char: ch, codePoint: ch.codePointAt(0), pos: meaningfulPos });
        }
    }
    const clean = cleanChars.join('');
    const warnings = [];

    if (dropped.length) {
        // HIGH severity — any non-ACGT character is a potential silent
        // frame-shift. Show position + identity (with Unicode codepoint for
        // invisibles like ZWSP) so the user can find and fix the typo.
        const names = dropped.slice(0, 6).map((d) => {
            const visible = (d.codePoint >= 0x20 && d.codePoint < 0x7F)
                ? `'${d.char}'`
                : `U+${d.codePoint.toString(16).toUpperCase().padStart(4, '0')}`;
            return `${visible}@${d.pos}`;
        }).join(', ');
        const more = dropped.length > 6 ? ` (+${dropped.length - 6} more)` : '';
        warnings.push({
            severity: 'high',
            text: `Rejected ${dropped.length} non-ACGT character${dropped.length > 1 ? 's' : ''}: ${names}${more}. Save is blocked until these are removed or replaced. (U → T is done automatically; IUPAC codes like R/Y/N must be resolved manually.)`,
        });
    }
    if (clean.length === 0) {
        warnings.push({ severity: 'high', text: 'Sequence is empty.' });
    }
    if (clean.length && clean.length % 3 !== 0) {
        warnings.push({ severity: 'high', text: `Length ${clean.length} bp is not a multiple of 3 — frame will be broken. Save is blocked.` });
    }
    // Premature-stop check: any stop codon BEFORE the last codon.
    let firstPrematureStop = -1;
    for (let i = 0; i + 3 <= clean.length - 3; i += 3) {
        const codon = clean.slice(i, i + 3);
        if (STOP_CODONS_SET.has(codon)) { firstPrematureStop = i; break; }
    }
    if (firstPrematureStop >= 0) {
        // A premature stop is a legitimate nonsense / truncation mutation
        // (e.g. a single-base SNP that creates a stop, or an intentional
        // knockout). Warn, don't block — the variant encodes the truncated
        // product and synthesis is unaffected.
        const aaPos = Math.floor(firstPrematureStop / 3) + 1;
        warnings.push({ severity: 'medium', text: `Premature stop (${clean.slice(firstPrematureStop, firstPrematureStop + 3)}) at codon ${aaPos} — truncates the protein (nonsense mutation). Allowed.` });
    }
    // Terminal stop check — if the final codon isn't TAA/TAG/TGA, warn but
    // don't block (some users edit out the stop intentionally for fusion
    // constructs that read into downstream sequence).
    if (clean.length >= 3 && clean.length % 3 === 0) {
        const lastCodon = clean.slice(-3);
        if (!STOP_CODONS_SET.has(lastCodon)) {
            warnings.push({ severity: 'medium', text: `Last codon (${lastCodon}) is not a stop — translation will read through into anything appended downstream.` });
        }
    }
    const gc = clean.length
        ? ((clean.match(/[GC]/g) || []).length / clean.length) * 100
        : 0;
    if (clean.length && (gc < 35 || gc > 65)) {
        warnings.push({ severity: 'medium', text: `GC ${gc.toFixed(1)}% is outside the 35–65% sweet spot.` });
    }
    return { clean, dropped, gc, len: clean.length, warnings };
}

// Pure "can this be saved?" check. Save button is disabled when this is false.
function isDnaSaveable(result) {
    return result.warnings.every((w) => w.severity !== 'high');
}

function wireDnaEdit(scope, variant) {
    const variantId = variant.Variant_ID;
    const toggle = scope.querySelector(`.dna-edit-toggle[data-variant="${cssEscape(variantId)}"]`);
    const reset  = scope.querySelector(`.dna-edit-reset[data-variant="${cssEscape(variantId)}"]`);
    const view   = scope.querySelector(`.dna-view[data-variant="${cssEscape(variantId)}"]`);
    const wrap   = scope.querySelector(`.dna-edit-wrap[data-variant="${cssEscape(variantId)}"]`);
    const ta     = scope.querySelector(`.dna-edit-textarea[data-variant="${cssEscape(variantId)}"]`);
    const stats  = scope.querySelector(`.dna-edit-stats[data-variant="${cssEscape(variantId)}"]`);
    if (!toggle || !ta || !wrap || !view) return;

    if (!originalDnaSnapshots.has(variantId)) {
        originalDnaSnapshots.set(variantId, variant.Optimized_DNA_Seq || '');
    }

    let inFlight = false;

    function renderStats(result, extra) {
        const sevClass = (s) => `warn-${s}`;
        const summary = `
            <span class="dna-stat-pill"><strong>${result.len}</strong> bp</span>
            <span class="dna-stat-pill">GC <strong>${result.gc.toFixed(1)}%</strong></span>
            <span class="dna-stat-pill">${result.len % 3 === 0 ? 'in-frame ✓' : '<span class="warn-high">frame broken</span>'}</span>
        `;
        const warningsHtml = result.warnings.length
            ? `<ul class="dna-edit-warnings">${result.warnings.map(w => `<li class="${sevClass(w.severity)}">${escapeHtml(w.text)}</li>`).join('')}</ul>`
            : '<div class="dna-edit-ok">Looks good for synthesis. ✓</div>';
        const extraHtml = extra ? `<div class="dna-edit-extra">${extra}</div>` : '';
        stats.innerHTML = summary + warningsHtml + extraHtml;
        // Save button reflects current saveability AND in-flight state.
        toggle.disabled = inFlight || (!wrap.hidden && !isDnaSaveable(result));
    }

    // Initial stats render so the user sees current GC/length pre-edit.
    renderStats(validateDnaEdit(ta.value));

    // Toggle button: opens the textarea, or — when already open — sends the
    // current textarea contents through the atomic save endpoint.
    toggle.addEventListener('click', async (e) => {
        e.stopPropagation();
        const editing = !wrap.hidden;
        if (editing) {
            const result = validateDnaEdit(ta.value);
            if (!isDnaSaveable(result)) {
                renderStats(result, '<span class="warn-high">Fix the high-severity issues above before saving.</span>');
                return;
            }
            inFlight = true;
            renderStats(result, '<span class="dna-edit-saving">Saving — re-deriving translation, primers, RE scan…</span>');
            try {
                await persistEditedDna(variantId, result.clean);
                // The persistEditedDna call replaces tableState.variants[i]
                // with the server's freshly-derived row and re-renders the
                // table. The detail panel for this row is wiped by the
                // re-render, so the user sees the update reflected in the
                // table cells. A toast confirms the save.
            } catch (err) {
                inFlight = false;
                renderStats(result, `<span class="warn-high">Save failed: ${escapeHtml(err.message || String(err))}</span>`);
            }
        } else {
            view.hidden = true;
            wrap.hidden = false;
            toggle.textContent = 'Save & close';
            reset.hidden = false;
            ta.focus();
            const v = ta.value;
            ta.setSelectionRange(v.length, v.length);
            renderStats(validateDnaEdit(ta.value));
        }
    });

    // Revert: post the original snapshot through the same atomic endpoint
    // so the server matches the screen after roll-back.
    reset.addEventListener('click', async (e) => {
        e.stopPropagation();
        if (inFlight) return;
        const original = originalDnaSnapshots.get(variantId) || '';
        ta.value = original;
        const result = validateDnaEdit(original);
        if (!isDnaSaveable(result)) {
            // The original snapshot itself failed validation — that's a bug
            // upstream, but show it rather than silently doing nothing.
            renderStats(result, '<span class="warn-high">Snapshot of the original DNA failed validation — please refresh the page.</span>');
            return;
        }
        inFlight = true;
        renderStats(result, '<span class="dna-edit-saving">Reverting to the original sequence…</span>');
        try {
            await persistEditedDna(variantId, result.clean);
        } catch (err) {
            inFlight = false;
            renderStats(result, `<span class="warn-high">Revert failed: ${escapeHtml(err.message || String(err))}</span>`);
        }
    });

    // Live local validation — keystrokes only update the pills + warnings.
    // No network call until the explicit Save button. This keeps the edit
    // experience snappy and avoids spamming /api/variants while the user
    // is mid-paste.
    ta.addEventListener('input', () => {
        renderStats(validateDnaEdit(ta.value));
    });
}

/**
 * Persist an edited DNA string atomically.
 *
 *   1. POST the edited bytes to /api/variants/<job>/<id>/dna.
 *   2. Server re-derives the full row (translation, mutations diff,
 *      PCR metrics, RE-site scan) and rewrites the library CSV on disk
 *      atomically. Returns the new row.
 *   3. Replace tableState.variants[i] with the server's row.
 *   4. Drop cloningState[variantId] so the Cloning Designer rebuilds.
 *   5. Re-render the variant table (detail panel collapses; user re-opens
 *      to verify). Toast confirms the save with the new metrics.
 *
 * Throws on 4xx/5xx with a user-readable message so the caller can show
 * it inline next to the textarea.
 */
async function persistEditedDna(variantId, newDna) {
    if (!state.jobId) throw new Error('No active job — refresh the page.');
    const url = `/api/variants/${encodeURIComponent(state.jobId)}/${encodeURIComponent(variantId)}/dna`;
    let res, body;
    try {
        res = await fetch(url, {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ dna: newDna }),
        });
        body = await res.json();
    } catch (netErr) {
        throw new Error(`Network error talking to the server: ${netErr?.message || netErr}`);
    }
    if (!res.ok && res.status !== 207) {
        throw new Error(body?.error || `HTTP ${res.status} ${res.statusText}`);
    }
    // 207 = "saved in memory but on-disk CSV rewrite failed". The row was
    // still returned and the in-memory state is correct, but downloads may
    // temporarily diverge. Surface that as a non-fatal warning toast.
    if (res.status === 207) {
        showToast(`Saved on screen but CSV rewrite failed: ${body?.error || ''}`, 'warn');
    }
    const row = body?.row;
    if (!row) throw new Error('Server response missing the updated row.');

    const variants = tableState.variants || [];
    const idx = variants.findIndex(v => v.Variant_ID === variantId);
    if (idx >= 0) variants[idx] = row;

    // Drop the Cloning Designer state for this variant so it rebuilds from
    // the new CDS the next time the detail panel opens.
    if (typeof cloningState !== 'undefined') cloningState.delete(variantId);

    // Re-render the table so the row cells (mutations, GC, length) reflect
    // the new state. This collapses the detail panel — by design — so the
    // user gets clear visual feedback that the save committed.
    if (typeof renderVariantRows === 'function') renderVariantRows();

    const reCount = Number(row.Restriction_Sites_Unresolved) || 0;
    const reHint = reCount > 0 ? ` · ⚠ ${reCount} RE site${reCount > 1 ? 's' : ''}` : '';
    showToast(
        `${variantId} saved · ${row.Length_bp} bp · GC ${Number(row.GC_Percent).toFixed(1)}%${reHint}`,
        reCount > 0 ? 'warn' : 'info',
    );
    return row;
}

// ============================================================== UTIL

function showError(msg, detail) {
    clearError();
    const banner = document.createElement('div');
    banner.className = 'error-banner';
    banner.id = 'errorBanner';

    let locator = '';
    if (detail && typeof detail.line === 'number') {
        locator = `<div>In your paste: <code>line ${detail.line}, column ${detail.col}</code>${
            typeof detail.nt_position === 'number'
                ? ` (nucleotide #${detail.nt_position + 1})`
                : ''
        }.</div>`;
    } else if (detail && typeof detail.nt_position === 'number') {
        locator = `<div>At <code>nucleotide #${detail.nt_position + 1}</code>.</div>`;
    }

    let hint = '';
    if (detail && detail.code === 'premature_stop') {
        hint = `<div class="error-hint">If your sequence really is a clean CDS, check the reading frame (make sure your paste starts exactly at the ATG) and that you aren't on the antisense strand. Otherwise, the ORF picker below will surface real ORFs from your DNA.</div>`;
    } else if (detail && detail.code === 'bad_length') {
        hint = `<div class="error-hint">Trim leading/trailing non-coding sequence so the total length is a multiple of 3.</div>`;
    } else if (detail && detail.code === 'invalid_char') {
        hint = `<div class="error-hint">Looks like there's a non-IUPAC character (a digit, punctuation, or stray Unicode). Often this is GenBank-style line numbers from a copy-paste.</div>`;
    }

    banner.innerHTML = `<strong>Couldn't read your sequence</strong>${escapeHtml(msg).replace(/\n/g, '<br>')}${locator}${hint}`;
    $('#inputCard').appendChild(banner);
    banner.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
}
function clearError() {
    const old = $('#errorBanner');
    if (old) old.remove();
}

function escapeHtml(s) {
    return String(s ?? '')
        .replace(/&/g, '&amp;')
        .replace(/</g, '&lt;')
        .replace(/>/g, '&gt;')
        .replace(/"/g, '&quot;');
}

function capitalize(s) {
    if (!s) return s;
    return s[0].toUpperCase() + s.slice(1);
}

function basename(p) {
    return (p || '').split('/').pop();
}

// ============================================================== QUIT

// Stop-server button removed from the UI as part of the AI-bloat audit
// (it was developer debug surface exposed in production hosting where
// stopping the server doesn't make sense). The /api/shutdown endpoint
// still exists for local CLI use; if a re-introduction is wanted, gate
// it behind a settings page or a localhost-only check, not a permanent
// button in the production sidebar.
const _quitBtn = document.getElementById('quitBtn');
if (_quitBtn) {
    _quitBtn.addEventListener('click', async () => {
        if (!confirm('Stop the TuringDNA engine server?')) return;
        try { await fetch('/api/shutdown', { method: 'POST' }); } catch (_) {}
        document.body.innerHTML = '<div style="padding:48px;font-family:system-ui;color:#4A4742">Server stopped. You can close this tab.</div>';
    });
}



// ════════════════════════════════════════════════════════════════════════
// CRISPR view controller — Cas9 knockout gRNA designer.
// ────────────────────────────────────────────────────────────────────────
// Mirrors the directed-evolution view's shape: paste → submit → table.
// Sign-in gated server-side; UI shows a sign-in notice when anonymous.
// ════════════════════════════════════════════════════════════════════════

(function crisprController() {
    const ta       = document.getElementById('crisprInput');
    const stats    = document.getElementById('crisprInputStats');
    const btn      = document.getElementById('crisprDesignBtn');
    const notice   = document.getElementById('crisprSigninNotice');
    const dlBtn    = document.getElementById('crisprDownloadBtn');
    const resCard  = document.getElementById('crisprResultsCard');
    const resSub   = document.getElementById('crisprResultsSub');
    const tbody    = document.getElementById('crisprTableBody');
    const errBox   = document.getElementById('crisprError');
    const modal    = document.getElementById('crisprSigninModal');

    // Phase 2C-1 — vector picker + vendor buttons (created from
    // /api/crispr/vectors at first design click; we don't pre-fetch
    // so the picker doesn't appear at all for cached old builds).
    const vectorRow    = document.getElementById('crisprVectorRow');
    const vectorSelect = document.getElementById('crisprVector');
    const vectorMeta   = document.getElementById('crisprVectorMeta');
    const vendorRow    = document.getElementById('crisprVendorRow');

    if (!ta || !btn) return;  // CRISPR view not in DOM (older cached build)

    // ─── Phase 2C-2 / 3: base-ruler gutter (matches the design page) ──
    // CRISPR textarea gutter — uses the shared base-ruler reflow: the sequence
    // is wrapped to 10 bases/line and the gutter is numbered by base position
    // (1, 11, 21 …). reflowSeqEditor handles wrapping (incl. on paste, via the
    // input event), caret preservation, and the gutter numbers in one pass.
    const crisprGutter = document.getElementById('crisprPasteGutter');
    function renderCrisprGutter() {
        if (crisprGutter) reflowSeqEditor(ta, crisprGutter);
    }
    if (crisprGutter) {
        ta.addEventListener('input', renderCrisprGutter);
        ta.addEventListener('scroll', () => {
            crisprGutter.scrollTop = ta.scrollTop;
        });
        let _crGutterResizeT;
        window.addEventListener('resize', () => {
            clearTimeout(_crGutterResizeT);
            _crGutterResizeT = setTimeout(renderCrisprGutter, 150);   // re-fit on width change
        });
        renderCrisprGutter();
    }

    let lastSubmittedSequence = null;  // for CSV download
    // Cached lookup: vector_id → vector metadata; populated by the
    // first successful /api/crispr/vectors call.
    let vectorIndex = {};
    let vendorsCache = {};  // vendor_id → { name, url, hint }
    let lastGuides = [];   // most recent guides[] — needed for "Copy all
                            // oligos" button on vendor row.

    // ─── Phase 3 (M1): base-editing mode controller ─────────────────
    // Toggling to "Base edit" reveals the base-editor dropdown (lazy-
    // loaded from /api/crispr/base-editors), and — since base editing is
    // SpCas9-only — locks the nuclease to Cas9 and disables the Cas12a
    // radio. Toggling back restores the Cas12a option.
    const beRow      = document.getElementById('crisprBaseEditorRow');
    const beSelectEl = document.getElementById('crisprBaseEditor');
    const beMeta     = document.getElementById('crisprBaseEditorMeta');
    let _baseEditorsLoaded = false;
    async function ensureBaseEditorsLoaded() {
        if (_baseEditorsLoaded || !beSelectEl) return;
        try {
            const r = await fetch('/api/crispr/base-editors');
            if (!r.ok) throw new Error('base-editors fetch failed');
            const data = await r.json();
            beSelectEl.innerHTML = '';
            (data.editors || []).forEach((e) => {
                const o = document.createElement('option');
                o.value = e.id;
                o.textContent = `${e.name} · ${e.target_base}→${e.result_base} · window ${e.window[0]}–${e.window[1]}`;
                o.dataset.note = e.note || '';
                beSelectEl.appendChild(o);
            });
            if (data.default) beSelectEl.value = data.default;
            _baseEditorsLoaded = true;
            updateBaseEditorMeta();
        } catch (_) { /* soft fail — dropdown just stays empty */ }
    }
    function updateBaseEditorMeta() {
        if (!beMeta || !beSelectEl) return;
        const opt = beSelectEl.options[beSelectEl.selectedIndex];
        const note = opt ? (opt.dataset.note || '') : '';
        beMeta.textContent = note
            ? note + ' Amino-acid consequences appear when a gene symbol (human/mouse) is set or the pasted sequence is a coding sequence (ATG…stop).'
            : '';
    }
    function applyMode(mode) {
        const isBE = mode === 'base_edit';
        if (beRow) beRow.hidden = !isBE;
        // Lock nuclease to Cas9 for base editing.
        const cas9Radio = document.querySelector('input[name="crisprEnzyme"][value="cas9"]');
        const cas12Radio = document.querySelector('input[name="crisprEnzyme"][value="cas12a"]');
        const cas12Label = cas12Radio && cas12Radio.closest('.crispr-enzyme-opt');
        if (isBE) {
            if (cas9Radio) cas9Radio.checked = true;
            if (cas12Radio) cas12Radio.disabled = true;
            if (cas12Label) cas12Label.classList.add('crispr-opt-disabled');
            ensureBaseEditorsLoaded();
        } else {
            if (cas12Radio) cas12Radio.disabled = false;
            if (cas12Label) cas12Label.classList.remove('crispr-opt-disabled');
        }
    }
    document.querySelectorAll('input[name="crisprMode"]').forEach((r) => {
        r.addEventListener('change', () => { if (r.checked) applyMode(r.value); });
    });
    if (beSelectEl) beSelectEl.addEventListener('change', updateBaseEditorMeta);

    // ─── Phase 3 (M2): paste-anything resolver ──────────────────────
    // Type a gene symbol / accession → fill the paste box with the
    // resolved sequence + set the gene context. Raw paste is unchanged.
    const resolveInput = document.getElementById('crisprResolveInput');
    const resolveBtn   = document.getElementById('crisprResolveBtn');
    const resolveChip  = document.getElementById('crisprResolveChip');
    function _showResolveChip(html, isError) {
        if (!resolveChip) return;
        resolveChip.hidden = false;
        resolveChip.className = 'crispr-resolve-chip' + (isError ? ' crispr-resolve-chip-error' : '');
        resolveChip.innerHTML = html;
    }
    async function _doResolve() {
        const text = (resolveInput && resolveInput.value.trim()) || '';
        if (!text) return;
        const organismEl = document.getElementById('crisprOrganism');
        const organism = (organismEl && organismEl.value) || '';
        if (resolveBtn) { resolveBtn.disabled = true; resolveBtn.textContent = 'Fetching…'; }
        try {
            const res = await fetch('/api/crispr/resolve', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ text, organism }),
            });
            const data = await res.json();
            if (res.status === 403 && data.kind === 'signin_required') {
                _openSigninModal();
                return;
            }
            if (!data.ok) {
                _showResolveChip(escapeHtml(data.error || 'Could not resolve that input.'), true);
                return;
            }
            // Fill the paste box + refresh gutter / stats / button state.
            if (ta) {
                ta.value = data.sequence;
                ta.dispatchEvent(new Event('input', { bubbles: true }));
            }
            // Resolved a named gene → set the gene-symbol field so exon
            // context + base-edit AA consequences get the reading frame.
            if (data.kind === 'gene' && data.gene_symbol) {
                const geneEl = document.getElementById('crisprGeneSymbol');
                if (geneEl) geneEl.value = data.gene_symbol;
            }
            _showResolveChip(
                '<span class="crispr-resolve-ok">&check;</span> ' + escapeHtml(data.label),
                false);
        } catch (err) {
            _showResolveChip(escapeHtml(err.message || 'Network error.'), true);
        } finally {
            if (resolveBtn) { resolveBtn.disabled = false; resolveBtn.textContent = 'Fetch'; }
        }
    }
    if (resolveBtn) resolveBtn.addEventListener('click', _doResolve);
    if (resolveInput) resolveInput.addEventListener('keydown', (e) => {
        if (e.key === 'Enter') { e.preventDefault(); _doResolve(); }
    });

    // "Try an example" — preload the GFP CDS as a knockout target, ready to
    // click Design. Populate-only (Design itself is the gated step).
    const exampleBtn = document.getElementById('crisprExampleBtn');
    if (exampleBtn && ta) exampleBtn.addEventListener('click', () => {
        if (resolveInput) resolveInput.value = '';
        if (resolveChip) resolveChip.hidden = true;
        const geneEl = document.getElementById('crisprGeneSymbol');
        if (geneEl) geneEl.value = '';
        ta.value = TD_EXAMPLE_GFP_CDS;
        ta.dispatchEvent(new Event('input', { bubbles: true }));   // refresh gutter + button state
        const design = document.getElementById('crisprDesignBtn');
        (design || ta).scrollIntoView({ behavior: 'smooth', block: 'center' });
    });

    // ─── Phase 2C-1: vector + vendor loader ─────────────────────────
    // Fetches /api/crispr/vectors on first design call, caches in memory
    // for the rest of the session, populates the picker + vendor row.
    let _vectorsLoaded = false;
    let _vectorsLoading = null;
    async function ensureVectorsLoaded(enzyme) {
        if (_vectorsLoaded && vectorSelect && vectorSelect.dataset.enzyme === enzyme) return;
        if (_vectorsLoading) return _vectorsLoading;
        _vectorsLoading = (async () => {
            try {
                const r = await fetch('/api/crispr/vectors?enzyme=' + encodeURIComponent(enzyme || ''));
                if (!r.ok) throw new Error('vectors fetch failed');
                const data = await r.json();
                vendorsCache = data.vendors || {};
                vectorIndex = {};
                if (vectorSelect) {
                    vectorSelect.innerHTML = '';
                    // Default first option = no vector (skip oligo gen).
                    const noopt = document.createElement('option');
                    noopt.value = '';
                    noopt.textContent = '— skip cloning oligos —';
                    vectorSelect.appendChild(noopt);
                    (data.vectors || []).forEach(v => {
                        vectorIndex[v.id] = v;
                        const o = document.createElement('option');
                        o.value = v.id;
                        // Name + Addgene + enzyme + selection — packed into
                        // the dropdown label so users don't need to expand
                        // a tooltip to pick.
                        o.textContent = `${v.name} · Addgene ${v.addgene_id} · ${v.enzyme}`;
                        vectorSelect.appendChild(o);
                    });
                    if (data.default && vectorIndex[data.default]) {
                        vectorSelect.value = data.default;
                    }
                    vectorSelect.dataset.enzyme = enzyme || 'cas9';
                    if (vectorRow) vectorRow.hidden = false;
                    updateVectorMeta();
                }
                renderVendorButtons();
                _vectorsLoaded = true;
            } catch (e) {
                // Soft fail — vector picker just doesn't appear, oligos
                // stay empty in the table.
            } finally {
                _vectorsLoading = null;
            }
        })();
        return _vectorsLoading;
    }

    function updateVectorMeta() {
        if (!vectorSelect || !vectorMeta) return;
        const v = vectorIndex[vectorSelect.value];
        vectorMeta.textContent = v
            ? `${v.description} · selection: ${v.selection}`
            : '';
    }
    if (vectorSelect) {
        vectorSelect.addEventListener('change', updateVectorMeta);
    }

    // ── Header bar: "Order ALL guides from X" ────────────────────────
    // Same gradient-blue treatment as the DE page's .synth-row .synth-btn,
    // so vendors read as primary actions instead of ghost buttons.
    // Each click copies EVERY guide's oligo pair as TSV → opens vendor.
    function renderVendorButtons() {
        if (!vendorRow) return;
        const ids = Object.keys(vendorsCache);
        if (!ids.length) { vendorRow.hidden = true; return; }
        vendorRow.innerHTML =
            '<span class="crispr-vendor-label">Order all guides from</span>' +
            ids.map(k => {
                const v = vendorsCache[k];
                // Gradient blue style + ↗ arrow svg matches DE synth-btn.
                return `<button type="button" class="crispr-vendor-btn crispr-vendor-btn-bulk" data-vendor="${escapeHtml(k)}" title="${escapeHtml(v.hint || '')}">
                    <span>${escapeHtml(v.name)}</span>
                    <svg class="synth-arrow" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true" width="13" height="13">
                        <path d="M7 7h10v10"/><path d="M7 17 17 7"/>
                    </svg>
                </button>`;
            }).join('');
        vendorRow.hidden = false;
        vendorRow.querySelectorAll('.crispr-vendor-btn-bulk').forEach(btn => {
            btn.addEventListener('click', () => {
                const vid = btn.getAttribute('data-vendor');
                const vendor = vendorsCache[vid];
                if (!vendor) return;
                const lines = ['Name\tSequence'];
                lastGuides.forEach(g => {
                    if (!g.sense_oligo || !g.antisense_oligo) return;
                    lines.push(`g${g.rank}_sense\t${g.sense_oligo}`);
                    lines.push(`g${g.rank}_antisense\t${g.antisense_oligo}`);
                });
                if (lines.length === 1) {
                    _showError('No cloning oligos yet — pick a vector and click Design first.');
                    return;
                }
                _vendorOrderClick(btn, vendor, lines.join('\n'),
                    `all ${lastGuides.length} guides`);
            });
        });
    }

    // ── Per-row vendor button helper ─────────────────────────────────
    // Builds the inline-button HTML for the new "Order" table column.
    // 3 compact gradient buttons (Twist / IDT / Synthego), each click
    // copies THIS guide's sense+antisense oligo pair + opens vendor.
    // Empty cell when the guide has no oligos (no vector picked).
    function _renderRowVendors(g) {
        if (!g.sense_oligo || !g.antisense_oligo) {
            return '<span class="muted">—</span>';
        }
        const ids = Object.keys(vendorsCache);
        if (!ids.length) return '<span class="muted">—</span>';
        // Short labels so 3 buttons fit a narrow column. Two-letter
        // abbreviations make the column ~140 px which is bearable.
        const SHORT = { twist: 'TWST', idt: 'IDT', synthego: 'SYN' };
        return '<div class="crispr-row-vendors">' + ids.map(vid => {
            const v = vendorsCache[vid];
            const lbl = SHORT[vid] || v.name.slice(0, 4).toUpperCase();
            return `<button type="button" class="crispr-vendor-btn crispr-vendor-btn-row"
                data-vendor="${escapeHtml(vid)}"
                data-row-rank="${g.rank}"
                title="Order this guide's oligo pair from ${escapeHtml(v.name)} — copies sense + antisense to clipboard, opens ${escapeHtml(v.name)} in a new tab.">${lbl}</button>`;
        }).join('') + '</div>';
    }

    // ── Shared vendor-click action ───────────────────────────────────
    // Writes `tsv` to clipboard, flashes the button to "Copied" with
    // the success color, opens the vendor URL in a new tab after a
    // brief delay so the user sees the confirmation feedback.
    function _vendorOrderClick(btn, vendor, tsv, contextLabel) {
        // Red Team gate before routing oligos to ANY synthesis vendor (Twist,
        // IDT, Synthego, …). The synthesis checks apply regardless of vendor.
        const seqs = (tsv || '').split('\n').slice(1)
            .map(l => (l.split('\t')[1] || '').trim()).filter(Boolean);
        const gene = ((document.getElementById('crisprGeneSymbol') || {}).value || '').trim();
        runOracle({
            seqs: seqs, gene: gene,
            actionLabel: 'Before sending to ' + ((vendor && vendor.name) || 'your synthesis vendor'),
            proceed: () => _vendorOrderDo(btn, vendor, tsv, contextLabel),
        });
    }

    function _vendorOrderDo(btn, vendor, tsv, contextLabel) {
        navigator.clipboard.writeText(tsv).then(() => {
            // Visual confirmation — uses the same .copied class the DE
            // page's .synth-row .synth-btn uses so the green flash
            // reads as "this worked" everywhere in the product.
            btn.classList.add('copied');
            const orig = btn.innerHTML;
            btn.innerHTML = '✓ Copied';
            setTimeout(() => {
                btn.classList.remove('copied');
                btn.innerHTML = orig;
            }, 1800);
            // Toast — same component the DE synthesizeDna flow uses, so
            // users get the same "what just happened" voice everywhere.
            if (typeof showToast === 'function') {
                showToast(
                    `${contextLabel} copied to clipboard. Opening ${vendor.name} — ${vendor.hint || 'paste into their oligo order form.'}`,
                    'info'
                );
            }
        }).catch(() => {
            _showError('Copy blocked — your browser may need clipboard permission. Try clicking inside the page first, then retry.');
        });
        // Small delay before opening the vendor tab so the toast/flash
        // is visible before the user's focus shifts. Same 1.1s the DE
        // synthesizeDna() uses.
        setTimeout(() => {
            window.open(vendor.url, '_blank', 'noopener,noreferrer');
        }, 1100);
    }

    // ─── Sign-in modal ───────────────────────────────────────────────
    // Fires on either:
    //   (a) anon user clicks the CRISPR sidebar tab — proactive nudge,
    //       lets them sign in before they invest effort pasting a seq.
    //   (b) backend returns 403 signin_required on /api/crispr/design —
    //       reactive catch in case (a) missed (frontend can't always
    //       tell who's signed in; auth.js's sessionStorage view can be
    //       stale).
    //
    // Dismissable so signed-in users whose JWT is temporarily out of
    // sync can close it and try again rather than being stuck.

    function _openSigninModal() {
        if (!modal) return;
        modal.hidden = false;
        document.body.style.overflow = 'hidden';
        const close = () => {
            modal.hidden = true;
            document.body.style.overflow = '';
            document.removeEventListener('keydown', onEsc);
        };
        const onEsc = (e) => { if (e.key === 'Escape') close(); };
        modal.querySelectorAll('[data-crispr-signin-close]').forEach((el) => {
            el.addEventListener('click', close, { once: true });
        });
        document.addEventListener('keydown', onEsc);
    }

    // (a) Tab-click hook: any sidebar nav-item linking to #crispr OR
    // #primers (both tools are members-only). Uses a lightweight
    // isSignedIn() heuristic — if it returns false, proactively open the
    // modal. If it returns true (or is wrong and returns false for a
    // signed-in user), the user can dismiss and proceed; case (b) below
    // catches false-positives via the authoritative backend 403.
    document.querySelectorAll('a[href="#crispr"], a[href="#primers"], a[href="#plasmid"]').forEach((a) => {
        a.addEventListener('click', () => {
            const signedIn = (window.TuringAuth && window.TuringAuth.isSignedIn && window.TuringAuth.isSignedIn());
            if (!signedIn) {
                // Defer so the route switch finishes first; otherwise
                // the body-overflow lock fights with the view swap.
                setTimeout(_openSigninModal, 50);
            }
        });
    });

    // (b) Global event from auth.js fetch wrapper. Fires when ANY
    // /api/* call comes back with 403 signin_required.
    window.addEventListener('td:signin-required', _openSigninModal);

    function _cleanedLength(s) {
        return (s || '').replace(/[^ACGTNacgtn]/g, '').length;
    }

    function _updateStats() {
        const nt = _cleanedLength(ta.value);
        stats.textContent = nt ? `${nt.toLocaleString()} nt` : '0 nt';

        // Trust the backend, not a frontend sessionStorage check. The
        // previous version pre-disabled the button + showed a sign-in
        // notice when window.TuringAuth.isSignedIn() returned false —
        // but sessionStorage in the iframe can be empty for legitimately
        // signed-in users (race condition: iframe loaded before the
        // parent wrapper's session-refresh completed, or sessionStorage
        // got cleared by a wrapper reload). The signed-in cookie / JWT
        // that the backend cares about is independent of our
        // sessionStorage view.
        //
        // New behavior: enable the button whenever the user has enough
        // sequence. If they're genuinely anonymous, the backend returns
        // 403 + kind=signin_required and we surface the notice + error
        // banner at THAT point (handled in the submit handler). UX cost:
        // one wasted click for unauthenticated users; UX win: no false
        // "please sign in" for authenticated users.
        if (notice) notice.hidden = true;

        const canSubmit = nt >= 23;
        btn.disabled = !canSubmit;
        const sub = btn.querySelector('.primary-sub');
        if (sub) {
            sub.textContent = nt < 23
                ? 'Paste at least 23 nt'
                : `${nt.toLocaleString()} nt ready`;
        }
    }

    function _clearError() {
        if (!errBox) return;
        errBox.hidden = true;
        errBox.textContent = '';
    }

    function _showError(msg) {
        if (!errBox) return;
        errBox.hidden = false;
        errBox.textContent = msg;
        errBox.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
    }

    ta.addEventListener('input', _updateStats);

    // Persist the user's pasted sequence so it survives the iframe
    // reload that fires when auth.js detects an expired JWT (403 →
    // window.top.location.reload). Same pattern as the directed-
    // evolution resume system; uses a different sessionStorage key.
    const CRISPR_RESUME_KEY = 'td_crispr_resume';
    function _saveCrisprResume(seq) {
        try { sessionStorage.setItem(CRISPR_RESUME_KEY, seq); } catch (_) {}
    }
    function _restoreCrisprResume() {
        try {
            const saved = sessionStorage.getItem(CRISPR_RESUME_KEY);
            if (saved && !ta.value) {
                ta.value = saved;
                _updateStats();
            }
        } catch (_) {}
    }
    function _clearCrisprResume() {
        try { sessionStorage.removeItem(CRISPR_RESUME_KEY); } catch (_) {}
    }
    _restoreCrisprResume();

    btn.addEventListener('click', async () => {
        _clearError();
        const seq = ta.value;
        if (!seq.trim()) return;
        // Stash BEFORE the API call so that if the call's 403 triggers
        // a parent reload (via auth.js's signin_required handler), the
        // user comes back to /app with their sequence already in the
        // paste box. Cleared on successful design or explicit clear.
        _saveCrisprResume(seq);
        btn.disabled = true;
        const labelEl = btn.querySelector('.primary-label');
        const origLabel = labelEl ? labelEl.textContent : '';
        if (labelEl) labelEl.textContent = 'Designing…';

        try {
            // Read the enzyme picker (Phase 1). Defaults to cas9 if the
            // picker isn't in the DOM (cached old build).
            const enzymeRadio = document.querySelector('input[name="crisprEnzyme"]:checked');
            // Phase 3 (M1): editing mode + base editor. Base editing is
            // SpCas9-only, so the mode overrides the nuclease.
            const modeRadio = document.querySelector('input[name="crisprMode"]:checked');
            const mode = (modeRadio && modeRadio.value) || 'knockout';
            const enzyme = mode === 'base_edit'
                ? 'cas9'
                : ((enzymeRadio && enzymeRadio.value) || 'cas9');
            const beSelect = document.getElementById('crisprBaseEditor');
            const base_editor = (mode === 'base_edit' && beSelect && beSelect.value) || '';

            // Phase 2B-1: optional organism + gene symbol for genome
            // off-target + exon-aware annotation. Both safe to omit.
            const organismEl = document.getElementById('crisprOrganism');
            const geneEl     = document.getElementById('crisprGeneSymbol');
            const target_organism = (organismEl && organismEl.value) || '';
            const gene_symbol     = (geneEl && geneEl.value.trim()) || '';

            // Phase 2C-2: progress shell. Indeterminate shimmer + status
            // text + elapsed-time counter. The status copy is tailored
            // to the slowest step the request will hit so the user knows
            // what's taking time (esp. for the ~60-90 s first build of
            // the human genome index).
            const progressShell  = document.getElementById('crisprProgressShell');
            const progressStatus = document.getElementById('crisprProgressStatus');
            const progressElapsed = document.getElementById('crisprProgressElapsed');
            const progressMessage = document.getElementById('crisprProgressMessage');
            let progressTimer = null;
            if (progressShell) {
                progressShell.hidden = false;
                if (progressStatus) {
                    const orgNice = target_organism === 'human' ? 'human exome'
                                  : target_organism === 'mouse' ? 'mouse exome'
                                  : target_organism === 'ecoli' ? 'E. coli genome'
                                  : '';
                    progressStatus.textContent = orgNice
                        ? `Designing guides · checking against the ${orgNice}…`
                        : 'Designing guides…';
                }
                if (progressMessage) {
                    progressMessage.textContent =
                        target_organism === 'human' || target_organism === 'mouse'
                            ? 'First run with this organism takes about a minute while we prepare the reference. Every design after this one in the same session is instant.'
                            : (gene_symbol
                                ? `Looking up ${gene_symbol} exon structure for splice-site and NMD-zone context…`
                                : 'Scoring on-target activity, off-target risk, predicted indel outcomes, base-editor compatibility, and cloning oligos.');
                }
                const t0 = Date.now();
                if (progressElapsed) progressElapsed.textContent = '0.0s';
                progressTimer = setInterval(() => {
                    if (progressElapsed) {
                        const secs = (Date.now() - t0) / 1000;
                        progressElapsed.textContent = `${secs.toFixed(1)}s`;
                    }
                }, 100);
            }
            // Wrap in a try/finally so the spinner ALWAYS hides, even
            // on early returns (signin modal, error, etc.).
            const _hideProgress = () => {
                if (progressTimer) { clearInterval(progressTimer); progressTimer = null; }
                if (progressShell) progressShell.hidden = true;
            };

            // Phase 2C-1: lazy-load the vector catalog on first design
            // click (subsequent clicks reuse the cache). Picker only
            // gets populated AFTER the load, so the first fetch sends
            // an empty vector_id and the columns render without oligos —
            // user picks a vector and re-clicks Design to get oligos.
            // Subsequent designs honor the chosen vector.
            await ensureVectorsLoaded(enzyme);
            const vector_id = (vectorSelect && vectorSelect.value) || '';

            const res = await fetch('/api/crispr/design', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({
                    sequence: seq, enzyme,
                    target_organism, gene_symbol,
                    vector_id,
                    mode, base_editor,
                    max_results: 50,
                }),
            });
            const data = await res.json();
            if (!res.ok) {
                if (data && data.kind === 'signin_required') {
                    // auth.js will also fire the td:signin-required
                    // event which opens the modal — but we also pop it
                    // directly here in case the event handler hasn't
                    // bound yet (e.g., this is the first /api/* call
                    // and the global wrapper raced us).
                    _openSigninModal();
                    return;  // no inline error — modal IS the message
                }
                throw new Error(data.error || 'CRISPR design failed.');
            }
            lastSubmittedSequence = seq;
            _clearCrisprResume();  // success — don't restore stale text next time
            _renderResults(data);
        } catch (err) {
            _showError(err.message || String(err));
        } finally {
            btn.disabled = false;
            if (labelEl) labelEl.textContent = origLabel;
            _updateStats();
            _hideProgress();
        }
    });

    // Phase 2D: small banner above the table, shown only when the
    // genome index isn't ready yet. Inserted just under the results
    // header so it sits between the card-sub text and the table.
    function _renderGenomeStatusBanner(data) {
        let el = document.getElementById('crisprGenomeStatusBanner');
        const status = data && data.genome_index_status;
        const org    = data && data.genome_organism;
        if (status !== 'building') {
            if (el) el.remove();
            return;
        }
        if (!el) {
            el = document.createElement('div');
            el.id = 'crisprGenomeStatusBanner';
            el.className = 'crispr-banner crispr-banner-info';
            // Insert just below the results header so it reads as a
            // continuation of the "ranked sgRNAs" line.
            const tableWrap = resCard.querySelector('.result-table-wrap');
            if (tableWrap && tableWrap.parentNode) {
                tableWrap.parentNode.insertBefore(el, tableWrap);
            } else {
                resCard.appendChild(el);
            }
        }
        const orgName = org === 'human' ? 'Homo sapiens exome'
                      : org === 'mouse' ? 'Mus musculus exome'
                      : (org || 'genome');
        el.innerHTML =
            `<strong>Preparing the ${escapeHtml(orgName)} reference.</strong> ` +
            'This takes about a minute the first time it&rsquo;s used, then it&rsquo;s instant for the rest of your session. ' +
            'Your guides are scored normally &mdash; the <em>Genome off</em> column will fill in after you click <strong>Design</strong> again in a minute or two.';
    }

    // ─── Phase 3 (M3): results UX — sort / filter / explain ─────────
    // The design response is cached so header-click sorting and filter
    // toggles re-render the table WITHOUT re-fetching from the backend.
    let crisprData = null;
    let crisprSort = { key: 'composite_score', dir: 'desc' };
    const crisprFilters = { hideFlagged: false, uniqueOnly: false, stopOnly: false };
    let _crisprSortWired = false;

    const _SORT_NUMERIC = {
        position:          g => g.position,
        composite_score:   g => (typeof g.composite_score === 'number' ? g.composite_score : g.on_target_score),
        on_target_score:   g => g.on_target_score || 0,
        cfd_max_offtarget: g => g.cfd_max_offtarget || 0,
        ko_efficacy:       g => g.ko_efficacy || 0,
        frameshift_pct:    g => g.frameshift_pct || 0,
        top_dominance_pct: g => g.top_dominance_pct || 0,
        be_editability:    g => g.be_editability || 0,
        gc_pct:            g => g.gc_pct || 0,
    };

    function _passesCrisprFilters(g) {
        if (crisprFilters.hideFlagged && (g.flag_high_gc || g.flag_low_gc || g.flag_polyT)) return false;
        if (crisprFilters.uniqueOnly) {
            const selfHit = (g.cfd_max_offtarget || 0) > 0.1;
            const genomeHit = !!g.genome_organism && (g.genome_offtarget_count || 0) > 0;
            if (selfHit || genomeHit) return false;
        }
        if (crisprFilters.stopOnly && !g.be_creates_stop) return false;
        return true;
    }

    function _crisprSortCmp(a, b) {
        const getv = _SORT_NUMERIC[crisprSort.key] || _SORT_NUMERIC.composite_score;
        const dir = crisprSort.dir === 'asc' ? 1 : -1;
        const d = (getv(a) - getv(b)) * dir;
        return d !== 0 ? d : (a.position - b.position);   // stable tiebreak
    }

    // Plain-English "why this guide" explanation, built from the guide's
    // own scores so non-experts can read the table without a glossary.
    function _crisprWhy(g) {
        const isBE = crisprData && crisprData.mode === 'base_edit';
        const p = [];
        p.push(`Targets the <strong>${g.strand === '+' ? 'sense' : 'antisense'}</strong> strand at position <strong>${g.position.toLocaleString()}</strong>.`);
        if (isBE && g.be_editor) {
            if (g.be_edits && g.be_edits.length) {
                p.push(`With ${escapeHtml(g.be_editor.toUpperCase())} it installs <strong>${escapeHtml(g.be_outcome_label)}</strong>`
                    + (g.be_aa_change ? `, predicted to cause <strong>${escapeHtml(g.be_aa_change)}</strong>` : '') + '.');
                if (g.be_creates_stop) p.push('This introduces a premature stop codon — a DSB-free knockout (CRISPR-STOP).');
                else if (g.be_has_bystander) p.push('More than one editable base sits in the window, so expect bystander edits.');
            } else {
                p.push('No editable base falls in this editor&rsquo;s window for this guide.');
            }
            p.push(`Editability is <strong>${(g.be_editability || 0).toFixed(2)}</strong> (higher = the edit is more likely).`);
        } else {
            p.push(`On-target activity <strong>${(g.on_target_score || 0).toFixed(2)}</strong>, predicted knockout efficacy <strong>${(g.ko_efficacy || 0).toFixed(2)}</strong>${g.ko_reasoning ? ' — ' + escapeHtml(g.ko_reasoning) : ''}.`);
            if (typeof g.frameshift_pct === 'number') {
                p.push(`About <strong>${g.frameshift_pct.toFixed(0)}%</strong> of predicted repair outcomes cause a frameshift; the most likely single outcome is <strong>${escapeHtml(g.top_indel_label || '—')}</strong>.`);
            }
        }
        const selfCfd = g.cfd_max_offtarget || 0;
        if (selfCfd > 0.1) p.push(`Caution: a possible off-target sits within your input (CFD ${selfCfd.toFixed(2)}${g.offtarget_count > 1 ? `, ${g.offtarget_count} sites` : ''}).`);
        else p.push('No significant off-target within the pasted sequence.');
        if (g.genome_organism) {
            p.push((g.genome_offtarget_count || 0) === 0
                ? `No coding-region off-target in the ${escapeHtml(g.genome_organism)} genome.`
                : `${g.genome_offtarget_count} genome off-target site(s) (worst CFD ${(g.genome_offtarget_max_cfd || 0).toFixed(2)}).`);
        }
        if (g.exon_context_summary) p.push(escapeHtml(g.exon_context_summary) + '.');
        const watch = [];
        if (g.flag_high_gc) watch.push('high GC (synthesis-difficult)');
        if (g.flag_low_gc) watch.push('low GC (often less active)');
        if (g.flag_polyT) watch.push('a TTTT run (U6 may terminate early)');
        if (watch.length) p.push('Watch-outs: ' + watch.join(', ') + '.');
        p.push('<em>Run your top guides through CRISPOR for whole-genome off-target before ordering.</em>');
        // Phase 3 (M5): structure-view button when the cut maps to a residue
        // AND a human/mouse gene symbol is set (needed to resolve UniProt).
        // When the context is missing, show a hint telling the user exactly
        // what to add to unlock the 3-D view — so the feature is discoverable
        // even on a raw-sequence run where it can't render yet.
        const actions = [];
        const geneEl = document.getElementById('crisprGeneSymbol');
        const orgEl = document.getElementById('crisprOrganism');
        const gene = geneEl ? geneEl.value.trim() : '';
        const org = orgEl ? orgEl.value : '';
        const orgOk = (org === 'human' || org === 'mouse');
        if (!isBE) {
            if (g.cut_residue && gene && orgOk) {
                actions.push(`<button type="button" class="ghost crispr-struct-btn" data-struct-residue="${g.cut_residue}">View 3-D structure · cut at residue ${g.cut_residue}</button>`);
            } else {
                const need = (!gene && !orgOk) ? 'a human or mouse gene symbol and organism'
                           : !gene ? 'a gene symbol'
                           : !orgOk ? 'a human or mouse organism'
                                    : 'a sequence that aligns to the gene&rsquo;s coding region';
                actions.push(`<span class="crispr-struct-hint">Add ${need} above, then re-run, to map this cut onto the 3-D AlphaFold structure.</span>`);
            }
        }
        // Per-guide IP radar — every variation can be checked, not just #1.
        let radarInline = '';
        if (g.spacer) {
            actions.push(`<button type="button" class="ghost crispr-radar-btn" data-radar-rank="${g.rank}">⌖ IP radar · check guide #${g.rank}</button>`);
            radarInline = `<div class="ip-radar-inline" data-radar-banner="${g.rank}" hidden></div>`;
        }
        const actionsHtml = actions.length ? `<div class="crispr-why-actions">${actions.join('')}</div>` : '';
        return '<div class="crispr-why">' + p.join(' ') + actionsHtml + radarInline + '</div>';
    }

    // Filter chips above the table (created once, then updated in place).
    function _renderCrisprFilterBar(isBaseEdit) {
        let bar = document.getElementById('crisprFilterBar');
        if (!bar) {
            bar = document.createElement('div');
            bar.id = 'crisprFilterBar';
            bar.className = 'crispr-filter-bar';
            const tableWrap = resCard.querySelector('.result-table-wrap');
            if (tableWrap && tableWrap.parentNode) tableWrap.parentNode.insertBefore(bar, tableWrap);
            else resCard.appendChild(bar);
            bar.innerHTML =
                '<span class="crispr-filter-label">Filter</span>'
                + '<label class="crispr-filter-chip"><input type="checkbox" data-filter="hideFlagged"> hide flagged (GC / poly-T)</label>'
                + '<label class="crispr-filter-chip"><input type="checkbox" data-filter="uniqueOnly"> unique only (no off-target)</label>'
                + '<label class="crispr-filter-chip crispr-filter-be" data-be-only><input type="checkbox" data-filter="stopOnly"> creates stop only</label>'
                + '<span class="crispr-filter-count" id="crisprFilterCount"></span>';
            bar.querySelectorAll('input[data-filter]').forEach((cb) => {
                cb.addEventListener('change', () => {
                    crisprFilters[cb.getAttribute('data-filter')] = cb.checked;
                    if (crisprData) _renderResults(crisprData, true);
                });
            });
        }
        // The "creates stop only" chip is base-edit specific.
        const beChip = bar.querySelector('[data-be-only]');
        if (beChip) beChip.style.display = isBaseEdit ? '' : 'none';
        if (!isBaseEdit) {
            crisprFilters.stopOnly = false;
            const cb = bar.querySelector('input[data-filter="stopOnly"]');
            if (cb) cb.checked = false;
        }
    }

    function _updateCrisprFilterCount(shown, total) {
        const el = document.getElementById('crisprFilterCount');
        if (el) el.textContent = shown < total ? `showing ${shown} of ${total}` : '';
    }

    // Click-to-sort on table headers carrying data-sort-key (wired once).
    function _wireCrisprSortHeaders() {
        if (_crisprSortWired) return;
        const table = tbody.closest('table');
        if (!table) return;
        table.querySelectorAll('th[data-sort-key]').forEach((th) => {
            th.classList.add('crispr-sortable');
            th.addEventListener('click', () => {
                const key = th.getAttribute('data-sort-key');
                if (crisprSort.key === key) {
                    crisprSort.dir = crisprSort.dir === 'desc' ? 'asc' : 'desc';
                } else {
                    crisprSort = { key, dir: 'desc' };
                }
                if (crisprData) _renderResults(crisprData, true);
            });
        });
        _crisprSortWired = true;
    }

    function _updateCrisprSortIndicators() {
        const table = tbody.closest('table');
        if (!table) return;
        table.querySelectorAll('th[data-sort-key]').forEach((th) => {
            const active = th.getAttribute('data-sort-key') === crisprSort.key;
            th.setAttribute('aria-sort', active ? (crisprSort.dir === 'asc' ? 'ascending' : 'descending') : 'none');
            th.classList.toggle('crispr-sort-active', active);
            th.classList.toggle('crispr-sort-asc', active && crisprSort.dir === 'asc');
        });
    }

    // ─── Phase 3 (M5): structure viewer (Mol* + AlphaFold-DB) ───────
    const structModal = document.getElementById('crisprStructureModal');
    const _structCache = {};  // "org/GENE" → resolved {uniprot, alphafold_url, …}
    if (structModal) {
        structModal.querySelectorAll('[data-crispr-struct-close]').forEach((el) =>
            el.addEventListener('click', () => { structModal.hidden = true; }));
        document.addEventListener('keydown', (e) => {
            if (e.key === 'Escape' && !structModal.hidden) structModal.hidden = true;
        });
    }

    async function _showCrisprStructure(residue) {
        if (!structModal) return;
        const geneEl = document.getElementById('crisprGeneSymbol');
        const orgEl  = document.getElementById('crisprOrganism');
        const gene = geneEl ? geneEl.value.trim() : '';
        const org  = orgEl ? orgEl.value : '';
        if (!gene || (org !== 'human' && org !== 'mouse')) return;
        const meta = document.getElementById('crisprStructureMeta');
        const host = document.getElementById('crisprStructureViewer');
        const disc = document.getElementById('crisprStructureDisclaimer');
        structModal.hidden = false;
        if (meta) meta.innerHTML = `${escapeHtml(gene)} · cut at residue <strong>${residue}</strong>`;
        if (host) host.innerHTML = '<div class="alphafold-loading">Resolving structure…</div>';

        const key = org + '/' + gene.toUpperCase();
        let info = _structCache[key];
        if (!info) {
            try {
                const res = await fetch('/api/crispr/structure', {
                    method: 'POST', headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ organism: org, gene_symbol: gene }),
                });
                const data = await res.json();
                if (res.status === 403 && data.kind === 'signin_required') {
                    structModal.hidden = true; _openSigninModal(); return;
                }
                if (!data.ok) {
                    if (host) host.innerHTML = `<div class="alphafold-loading">${escapeHtml(data.error || 'Could not resolve a structure for this gene.')}</div>`;
                    return;
                }
                info = data; _structCache[key] = info;
            } catch (err) {
                if (host) host.innerHTML = `<div class="alphafold-loading">${escapeHtml(err.message || 'Network error.')}</div>`;
                return;
            }
        }
        if (meta) meta.innerHTML = `${escapeHtml(gene)} · UniProt ${escapeHtml(info.uniprot)} · cut at residue <strong>${residue}</strong>`;
        if (disc) disc.innerHTML = `Predicted structure from <a href="${escapeHtml(info.alphafold_page)}" target="_blank" rel="noopener">AlphaFold-DB</a>. The highlighted residue (${residue}) is the Cas9 cut site mapped through the CDS — approximate, not experimentally determined.`;
        if (host) host.innerHTML = '<div class="alphafold-loading">Loading AlphaFold-DB structure…</div>';
        await _mountCrisprStructure(host, info.alphafold_url, residue);
    }

    async function _mountCrisprStructure(host, pdbUrl, residue) {
        if (!host || !pdbUrl) return;
        const molstar = await _afWaitMolstar();
        if (!molstar) { host.innerHTML = '<div class="alphafold-loading">Mol* viewer failed to load. Refresh and try again.</div>'; return; }
        try {
            const viewer = await molstar.Viewer.create(host, _AF_VIEWER_OPTS);
            _afApplyBg(viewer);
            const { candidates, exists } = await _afResolve(pdbUrl);
            if (!await _afTryLoad(viewer, candidates)) {
                _afShowError(host, exists !== false, () => _mountCrisprStructure(host, pdbUrl, residue));
                return;
            }
            const ov = host.querySelector('.alphafold-loading'); if (ov) ov.remove();
            _highlightResidue(molstar, viewer, residue);
        } catch (err) {
            _afShowError(host, true, () => _mountCrisprStructure(host, pdbUrl, residue));
        }
    }

    // Best-effort residue highlight. Mol*'s low-level selection API is
    // version-sensitive, so this is wrapped: a failure never blanks the
    // structure (which still renders) and the residue is named in the
    // header. We deliberately do NOT move the camera (focusLoci) — a tight
    // single-residue zoom can clip the model; instead we select the
    // residue so it's marked while the whole protein stays in view, and
    // the user can zoom with the built-in Mol* controls.
    function _highlightResidue(molstar, viewer, residue) {
        try {
            const plugin = viewer.plugin;
            const structs = plugin.managers.structure.hierarchy.current.structures;
            if (!structs || !structs.length) return;
            const data = structs[0].cell.obj.data;
            const sel = molstar.Script.getStructureSelection((Q) =>
                Q.struct.generator.atomGroups({
                    'residue-test': Q.core.rel.eq([Q.struct.atomProperty.macromolecular.auth_seq_id(), residue]),
                }), data);
            const loci = molstar.StructureSelection.toLociWithSourceUnits(sel);
            plugin.managers.structure.selection.fromLoci('set', loci);
            plugin.managers.interactivity.lociHighlights.highlightOnly({ loci });
        } catch (_) { /* best-effort — structure + header still inform */ }
    }

    // ─── Live Collision IP Radar (opt-in, per run) ──────────────────
    // Scans recent literature (Europe PMC) for the TOP guide's exact spacer +
    // gene context. Async — never blocks the design or Mol* flow; the result
    // is cached server-side. Only the gene + 20-mer leave the Space.
    const radarBtn = document.getElementById('crisprRadarBtn');
    const radarBanner = document.getElementById('crisprRadarBanner');

    function _radarTopGuide() {
        const guides = (lastGuides && lastGuides.length)
            ? lastGuides : ((crisprData && crisprData.guides) || []);
        if (!guides.length) return null;
        return guides.find(g => g.rank === 1) || guides[0];
    }

    function _radarList(rows) {
        return '<ul class="ip-radar-list">' + rows.map(r => {
            const t = r.url
                ? '<a href="' + escapeHtml(r.url) + '" target="_blank" rel="noopener">' + escapeHtml(r.title || 'Untitled') + '</a>'
                : escapeHtml(r.title || 'Untitled');
            return '<li><span class="ip-radar-match-title">' + t + '</span>' +
                   '<span class="ip-radar-cite">' + escapeHtml(r.cite || '') + '</span></li>';
        }).join('') + '</ul>';
    }

    function _renderRadar(data, top, bannerEl) {
        bannerEl = bannerEl || radarBanner;
        if (!bannerEl) return;
        const matches = (data && data.matches) || [];
        const patents = (data && data.patents) || [];
        const close = '<button type="button" class="ip-radar-x" aria-label="Dismiss">×</button>';

        if (!matches.length && !patents.length) {
            bannerEl.innerHTML =
                '<div class="ip-radar-banner ip-radar-clear">' +
                '<span class="ip-radar-ico" aria-hidden="true">✓</span>' +
                '<div class="ip-radar-body"><strong>No literature overlap found</strong> for guide #' + top.rank +
                '. Scanned recent preprints &amp; papers (Europe PMC). ' +
                '<span class="ip-radar-note">A clean scan isn\'t a freedom-to-operate opinion.</span></div>' +
                close + '</div>';
        } else {
            let body =
                '<strong>Possible prior art — review before you publish or file.</strong>' +
                '<p class="ip-radar-sub">Guide&nbsp;#' + top.rank + ' (<code>' + escapeHtml(top.spacer || '') +
                '</code>) overlaps existing work. A heads-up, <em>not</em> a freedom-to-operate or infringement ' +
                'opinion — confirm with a patent professional.</p>';
            if (matches.length) {
                const rows = matches.slice(0, 3).map(m => {
                    const when = (m.days_ago != null && m.days_ago <= 120)
                        ? (m.days_ago + ' day' + (m.days_ago === 1 ? '' : 's') + ' ago')
                        : (m.year || (m.date || '').slice(0, 4) || '');
                    return { url: m.url, title: m.title,
                             cite: [m.authors || '', m.source || '', when].filter(Boolean).join(' · ') };
                });
                body += '<div class="ip-radar-section">Literature</div>' + _radarList(rows) +
                    (matches.length > 3 ? '<div class="ip-radar-more">+ ' + (matches.length - 3) + ' more</div>' : '');
            }
            if (patents.length) {
                const rows = patents.slice(0, 3).map(p => ({
                    url: p.url, title: p.title,
                    cite: [p.assignee || '', p.year || ''].filter(Boolean).join(' · '),
                }));
                body += '<div class="ip-radar-section">Related patents in this space</div>' + _radarList(rows);
            }
            bannerEl.innerHTML =
                '<div class="ip-radar-banner ip-radar-hit">' +
                '<span class="ip-radar-ico" aria-hidden="true">⚠</span>' +
                '<div class="ip-radar-body">' + body + '</div>' + close + '</div>';
        }
        bannerEl.hidden = false;
        const x = bannerEl.querySelector('.ip-radar-x');
        if (x) x.addEventListener('click', () => { bannerEl.hidden = true; bannerEl.innerHTML = ''; });
    }

    // Run the radar for ANY guide (not just #1). `triggerBtn` is the button
    // that launched it (top "IP radar" button OR a per-guide button in a why
    // panel); `bannerEl` is where the result renders (the top banner, or the
    // inline banner beneath a per-guide button). Defaults keep the top button
    // working exactly as before.
    async function _runRadarFor(guide, triggerBtn, bannerEl) {
        triggerBtn = triggerBtn || radarBtn;
        bannerEl = bannerEl || radarBanner;
        if (!guide) { _showError('Design guides first, then run the IP radar.'); return; }
        if (!bannerEl) return;
        const gene = ((document.getElementById('crisprGeneSymbol') || {}).value || '').trim();
        const mode = (crisprData && crisprData.mode) || 'knockout';
        const orig = triggerBtn ? triggerBtn.innerHTML : '';
        if (triggerBtn) {
            triggerBtn.disabled = true;
            triggerBtn.innerHTML = '<span class="ip-radar-spinner" aria-hidden="true"></span> Scanning…';
        }
        bannerEl.hidden = false;
        bannerEl.innerHTML =
            '<div class="ip-radar-banner ip-radar-scanning">' +
            '<span class="ip-radar-spinner" aria-hidden="true"></span> ' +
            'Scanning recent literature &amp; preprints for overlap with guide #' + guide.rank + '…</div>';
        try {
            const res = await fetch('/api/crispr/ip_radar', {
                method: 'POST', headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ spacer: guide.spacer || '', gene_symbol: gene, mode: mode }),
            });
            if (res.status === 403) { bannerEl.hidden = true; bannerEl.innerHTML = ''; _openSigninModal(); return; }
            const data = await res.json();
            _renderRadar(data, guide, bannerEl);
        } catch (err) {
            bannerEl.innerHTML =
                '<div class="ip-radar-banner ip-radar-error">Couldn\'t reach the literature index just now. ' +
                '<button type="button" class="ip-radar-retry">Retry</button></div>';
            const r = bannerEl.querySelector('.ip-radar-retry');
            if (r) r.addEventListener('click', () => _runRadarFor(guide, triggerBtn, bannerEl));
        } finally {
            if (triggerBtn) {
                triggerBtn.disabled = false;
                triggerBtn.innerHTML = orig;
            }
        }
    }

    if (radarBtn && radarBanner) {
        radarBtn.addEventListener('click', () => _runRadarFor(_radarTopGuide(), radarBtn, radarBanner));
    }

    // ─── Phase 3 (M4): save & revisit designs ───────────────────────
    const saveBtn = document.getElementById('crisprSaveBtn');
    const designsBtn = document.getElementById('crisprDesignsBtn');
    const designsModal = document.getElementById('crisprDesignsModal');
    const designsList = document.getElementById('crisprDesignsList');
    if (designsModal) {
        designsModal.querySelectorAll('[data-crispr-designs-close]').forEach((el) =>
            el.addEventListener('click', () => { designsModal.hidden = true; }));
        document.addEventListener('keydown', (e) => {
            if (e.key === 'Escape' && !designsModal.hidden) designsModal.hidden = true;
        });
    }

    function _currentDesignLabel() {
        const gene = (document.getElementById('crisprGeneSymbol') || {}).value || '';
        const isBE = crisprData && crisprData.mode === 'base_edit';
        const bits = [];
        if (gene) bits.push(gene.toUpperCase());
        bits.push(isBE
            ? ('base edit' + (crisprData.base_editor ? ' · ' + crisprData.base_editor.toUpperCase() : ''))
            : 'knockout');
        if (crisprData && crisprData.input_length) bits.push(crisprData.input_length.toLocaleString() + ' nt');
        return bits.join(' · ') || 'Untitled design';
    }

    if (saveBtn) saveBtn.addEventListener('click', async () => {
        if (!crisprData || !(crisprData.guides && crisprData.guides.length)) {
            _showError('Run a design first, then save it.');
            return;
        }
        const orig = saveBtn.textContent;
        saveBtn.disabled = true; saveBtn.textContent = 'Saving…';
        try {
            const res = await fetch('/api/crispr/save', {
                method: 'POST', headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({
                    label: _currentDesignLabel(),
                    mode: crisprData.mode || 'knockout',
                    enzyme: crisprData.enzyme || '',
                    base_editor: crisprData.base_editor || '',
                    organism: (document.getElementById('crisprOrganism') || {}).value || '',
                    gene_symbol: (document.getElementById('crisprGeneSymbol') || {}).value || '',
                    input_length: crisprData.input_length || 0,
                    guides: crisprData.guides,
                }),
            });
            const data = await res.json();
            if (res.status === 403 && data.kind === 'signin_required') { _openSigninModal(); return; }
            if (!data.ok) { _showError(data.error || 'Could not save the design.'); return; }
            saveBtn.textContent = 'Saved ✓';
            setTimeout(() => { saveBtn.textContent = orig; }, 1600);
        } catch (err) {
            _showError(err.message || 'Could not save the design.');
        } finally {
            saveBtn.disabled = false;
            if (saveBtn.textContent === 'Saving…') saveBtn.textContent = orig;
        }
    });

    // "My designs" button → unified saved-work hub (all four tools).
    if (designsBtn) designsBtn.addEventListener('click', () => {
        if (window.TDSaved && window.TDSaved.open) window.TDSaved.open();
    });

    async function _loadDesign(id) {
        try {
            const res = await fetch('/api/crispr/designs/' + encodeURIComponent(id));
            const data = await res.json();
            if (res.status === 403 && data.kind === 'signin_required') { _openSigninModal(); return; }
            if (!data.ok || !data.design) { _showError('Could not open that design.'); return; }
            const d = data.design;
            // Reflect the saved context in the controls so the table renders
            // in the right mode and later Save/Download use the same settings.
            const modeRadio = document.querySelector(`input[name="crisprMode"][value="${d.mode === 'base_edit' ? 'base_edit' : 'knockout'}"]`);
            if (modeRadio) { modeRadio.checked = true; applyMode(modeRadio.value); }
            if (d.base_editor) { ensureBaseEditorsLoaded().then(() => { const be = document.getElementById('crisprBaseEditor'); if (be) be.value = d.base_editor; }); }
            if (d.organism) { const o = document.getElementById('crisprOrganism'); if (o) o.value = d.organism; }
            if (d.gene_symbol) { const g = document.getElementById('crisprGeneSymbol'); if (g) g.value = d.gene_symbol; }
            _renderResults({
                input_length: d.input_length || 0,
                n_guides: (d.guides || []).length,
                enzyme: d.enzyme || 'cas9',
                mode: d.mode || 'knockout',
                base_editor: d.base_editor || '',
                genome_organism: d.organism || '',
                genome_index_status: 'n/a',
                guides: d.guides || [],
            });
            // Loaded designs don't carry the source sequence, so block the
            // re-design-from-sequence Download until a fresh run.
            lastSubmittedSequence = null;
            if (designsModal) designsModal.hidden = true;
        } catch (err) {
            _showError(err.message || 'Could not open that design.');
        }
    }

    // Expose reopen to the unified saved-work hub.
    window.TDSaved = window.TDSaved || {};
    window.TDSaved.crispr = _loadDesign;

    function _renderCrisprMeta(data) {
        const guides = (data.guides || []);
        if (!guides.length) { tdRenderMethods('crisprRunMeta', [], null); return; }
        const isBE = data.mode === 'base_edit';
        const enzyme = (data.enzyme || 'cas9').toLowerCase();
        const enzLabel = enzyme === 'cas12a' ? 'Cas12a (TTTV PAM)' : 'SpCas9 (NGG PAM)';
        const be = (data.base_editor || '').toUpperCase();
        const org = data.genome_organism || '';
        const top = guides.slice().sort((a, b) => (b.composite_score || 0) - (a.composite_score || 0))[0] || guides[0];
        const strand = (top.strand === '-' || top.strand < 0) ? 'antisense' : 'sense';
        const comp = top.composite_score != null ? Number(top.composite_score).toFixed(2) : '—';
        let m;
        if (isBE) {
            m = `Guide RNAs (n=${guides.length}) were designed in silico for ${enzLabel} base editing with the ${escapeHtml(be) || 'selected'} editor (Komor et al., <cite>Nature</cite> 2016; Gaudelli et al., <cite>Nature</cite> 2017). On-target activity used Doench-style sequence features; per-guide editability was scored over the editor's activity window, with the predicted edit and amino-acid consequence reported. The top-ranked guide (${escapeHtml(top.spacer || '')}, ${strand} strand) was selected.`;
        } else {
            m = `Guide RNAs (n=${guides.length}) were designed in silico for ${enzLabel}. On-target activity was scored from Doench-style sequence features, and off-target potential within the provided sequence by the cutting-frequency-determination (CFD) matrix (Doench et al., <cite>Nat. Biotechnol.</cite> 2016); knockout likelihood was estimated from the predicted indel spectrum (frameshift fraction and out-of-frame dominance). The top-ranked guide (${escapeHtml(top.spacer || '')}, ${strand} strand, composite ${comp})${enzyme === 'cas12a' ? ' was selected' : ' was selected, and cloning oligos were generated for the standard BbsI/BsmBI vector'}. Off-target assessment is limited to the input sequence and is not genome-wide.`;
        }
        tdRenderMethods('crisprRunMeta', [
            ['Mode', isBE ? 'base edit' : 'knockout'],
            ['Enzyme', enzyme === 'cas12a' ? 'Cas12a' : 'SpCas9'],
            ['Base editor', isBE ? be : ''],
            ['Guides', guides.length],
            ['Input', data.input_length ? data.input_length.toLocaleString() + ' nt' : ''],
            ['Organism', org],
        ], m);
    }

    function _renderResults(data, _isRerender) {
        resCard.hidden = false;
        _renderCrisprMeta(data);

        // Phase 3 (M1): swap the table's column set by mode. The base-edit
        // class hides knockout-only columns (.col-ko) and reveals the
        // base-edit columns (.col-be); knockout mode does the reverse.
        const isBaseEdit = data.mode === 'base_edit';
        const table = tbody.closest('table');
        if (table) table.classList.toggle('crispr-table--base-edit', isBaseEdit);

        const editorName = (data.base_editor || '').toUpperCase();
        resSub.textContent = isBaseEdit
            ? `${data.n_guides} guides in ${data.input_length.toLocaleString()} nt · base editing${editorName ? ' · ' + editorName : ''} · ranked by editability`
            : `${data.n_guides} guides found in ${data.input_length.toLocaleString()} nt · ranked by on-target score`;

        // Phase 2D: genome-index status banner. When the user picked
        // human/mouse but the kmer index is still building in the
        // background, the guides come back without genome off-target
        // data. Show a banner so the user knows to refresh in ~2 min
        // rather than thinking the genome search "found nothing."
        _renderGenomeStatusBanner(data);

        // Phase 2C-1: stash guides for the "Copy all oligos" vendor flow,
        // and re-render the vendor row (which may have been hidden if the
        // previous design had no vector picked).
        lastGuides = data.guides || [];
        crisprData = data;
        if (!_isRerender && window.TDCrisprOutcomes) window.TDCrisprOutcomes.populate(data.guides || []);
        renderVendorButtons();

        // Phase 3 (M3): filter bar + sortable headers (created once), then
        // apply the active filters + sort to a working copy. On a fresh
        // design (not a sort/filter re-render) reset to the mode's default
        // ranking so the table opens ranked the way the backend intended.
        _renderCrisprFilterBar(isBaseEdit);
        _wireCrisprSortHeaders();
        if (!_isRerender) {
            crisprSort = isBaseEdit
                ? { key: 'be_editability', dir: 'desc' }
                : { key: 'composite_score', dir: 'desc' };
        }
        const working = (data.guides || []).filter(_passesCrisprFilters).sort(_crisprSortCmp);
        _updateCrisprFilterCount(working.length, (data.guides || []).length);
        _updateCrisprSortIndicators();

        // Phase 3 (M5) discoverability: is the 3-D structure view reachable
        // for this run? It needs a human/mouse gene symbol (to resolve the
        // UniProt accession → AlphaFold model) AND a cut→residue mapping.
        // Computed once here so each row can show a visible "⌖ 3-D" button
        // instead of burying it inside the expandable why-panel.
        const _sGeneEl = document.getElementById('crisprGeneSymbol');
        const _sOrgEl  = document.getElementById('crisprOrganism');
        const _structOrgOk = _sOrgEl ? (_sOrgEl.value === 'human' || _sOrgEl.value === 'mouse') : false;
        const _structCtxOk = !!((_sGeneEl ? _sGeneEl.value.trim() : '') && _structOrgOk && !isBaseEdit);

        const rows = working.map((g) => {
            const flags = [];
            if (g.flag_high_gc) flags.push('high&nbsp;GC');
            if (g.flag_low_gc)  flags.push('low&nbsp;GC');
            if (g.flag_polyT)   flags.push('poly-T');
            const flagsHtml = flags.length
                ? flags.map(f => `<span class="crispr-flag">${f}</span>`).join(' ')
                : '<span class="muted">—</span>';

            // Composite drives the row color (it IS the ranking column).
            // Backward-compat: if backend hasn't been updated yet, fall
            // back to on_target_score so old + new builds both render.
            const composite = (typeof g.composite_score === 'number')
                ? g.composite_score : g.on_target_score;
            const scoreClass = composite >= 0.65
                ? 'crispr-score-good'
                : (composite >= 0.40 ? 'crispr-score-ok' : 'crispr-score-weak');

            // Self-CFD column color: green if unique (0), amber if a
            // weak partial match exists, red if a strong match (>0.5).
            const cfd = (typeof g.cfd_max_offtarget === 'number')
                ? g.cfd_max_offtarget : 0;
            const cfdClass = cfd >= 0.5 ? 'crispr-score-weak'
                            : cfd >= 0.1 ? 'crispr-score-ok'
                                         : 'crispr-score-good';
            const cfdLabel = cfd > 0
                ? `${cfd.toFixed(2)}${g.offtarget_count > 1 ? ' <span class="muted">·' + g.offtarget_count + ' sites</span>' : ''}`
                : '<span class="muted">unique</span>';

            // KO efficacy column: tooltip shows the reasoning so the
            // user can see WHY a guide scored well or poorly.
            const ko = (typeof g.ko_efficacy === 'number') ? g.ko_efficacy : 0;
            const koClass = ko >= 0.55 ? 'crispr-score-good'
                          : ko >= 0.35 ? 'crispr-score-ok'
                                       : 'crispr-score-weak';
            const koTip = g.ko_reasoning ? ` title="${escapeHtml(g.ko_reasoning)}"` : '';

            // Phase 2A — indel prediction columns. Backward-compat:
            // older backend without these fields → empty string display.
            const topIndel = g.top_indel_label || '<span class="muted">—</span>';
            const fsPct = (typeof g.frameshift_pct === 'number') ? g.frameshift_pct : null;
            const fsClass = fsPct === null ? ''
                          : fsPct >= 60 ? 'crispr-score-good'
                          : fsPct >= 40 ? 'crispr-score-ok'
                                        : 'crispr-score-weak';
            const fsDisplay = fsPct === null ? '<span class="muted">—</span>'
                                              : `${fsPct.toFixed(0)}%`;
            // Build a per-row tooltip with the full predicted-indel
            // distribution so the user can hover Top-indel and see the
            // full picture, not just the #1 outcome.
            let indelTip = '';
            if (Array.isArray(g.predicted_indels) && g.predicted_indels.length) {
                const lines = g.predicted_indels
                    .map(p => `${p[0]}: ${(p[1] * 100).toFixed(0)}%`)
                    .join(' · ');
                indelTip = ` title="${escapeHtml(lines)}"`;
            }
            // Dominance: frequency of the single most-likely repair
            // outcome. HIGHER = cleaner (one dominant edit product).
            // Falls back to the old outcome_diversity field for one
            // deploy cycle so cached frontends don't render "—" before
            // they pick up the new key name.
            const dominance = (typeof g.top_dominance_pct === 'number')
                ? g.top_dominance_pct
                : (typeof g.outcome_diversity === 'number' ? null : null);
            const divClass = dominance === null ? ''
                           : dominance >= 40 ? 'crispr-score-good'
                           : dominance >= 25 ? 'crispr-score-ok'
                                             : 'crispr-score-weak';
            const divDisplay = dominance === null ? '<span class="muted">—</span>'
                                                  : `${dominance.toFixed(0)}%`;
            // Base-editor compatibility: show a short chip if at least
            // one editor type works, em-dash otherwise.
            const beDisplay = g.be_summary
                ? `<span class="crispr-flag" title="${escapeHtml(g.be_summary)}">${escapeHtml(g.be_summary.replace(/\s*\|\s*/g, ' / ').replace(/(CBE|ABE):\s*/g, ''))}</span>`
                : '<span class="muted">—</span>';

            // Phase 3 (M1) base-edit cells. Populated only in base-edit
            // mode (CSS hides them in knockout mode, so stray values are
            // harmless). The headline edit, editability, AA consequence,
            // and a clean/bystander/STOP outcome tag.
            const beEditLabel = g.be_outcome_label
                ? `<span title="${escapeHtml(g.be_outcome_label)}">${escapeHtml(g.be_outcome_label)}</span>`
                : '<span class="muted">—</span>';
            const beEd = (typeof g.be_editability === 'number') ? g.be_editability : 0;
            const beEdClass = !g.be_editor ? ''
                            : beEd >= 0.7 ? 'crispr-score-good'
                            : beEd >= 0.4 ? 'crispr-score-ok'
                                          : 'crispr-score-weak';
            const beEdDisplay = !g.be_editor ? '<span class="muted">—</span>'
                              : beEd > 0 ? beEd.toFixed(2)
                                         : '<span class="muted">none</span>';
            const beAa = g.be_aa_change
                ? `<span class="crispr-aa${g.be_creates_stop ? ' crispr-aa-stop' : ''}" title="${escapeHtml(g.be_aa_change)}">${escapeHtml(g.be_aa_change)}</span>`
                : '<span class="muted">—</span>';
            let beOutcome = '<span class="muted">—</span>';
            if (g.be_editor && Array.isArray(g.be_edits) && g.be_edits.length) {
                if (g.be_creates_stop) {
                    beOutcome = '<span class="crispr-be-tag crispr-be-tag-stop" title="Installs a premature stop codon — knockout by base editing (CRISPR-STOP).">STOP</span>';
                } else if (g.be_has_bystander) {
                    beOutcome = '<span class="crispr-be-tag crispr-be-tag-bystander" title="More than one editable base in the window — expect additional bystander edits.">bystander</span>';
                } else {
                    beOutcome = '<span class="crispr-be-tag crispr-be-tag-clean" title="A single editable base in the window — a clean point edit.">clean</span>';
                }
            }

            // Phase 2B-1: genome off-target column. Three render states:
            //   - empty: no organism was searched
            //   - "unique": organism searched, no hits above CFD threshold
            //   - CFD value + count + tooltip with top-hit location
            let genomeDisplay = '<span class="muted">—</span>';
            let genomeClass = '';
            if (g.genome_organism) {
                if ((g.genome_offtarget_count || 0) === 0) {
                    genomeDisplay = '<span class="muted">unique</span>';
                    genomeClass = 'crispr-score-good';
                } else {
                    const maxCfd = g.genome_offtarget_max_cfd || 0;
                    genomeClass = maxCfd >= 0.5 ? 'crispr-score-weak'
                                : maxCfd >= 0.1 ? 'crispr-score-ok'
                                                : 'crispr-score-good';
                    const tip = g.genome_offtarget_top_loc
                        ? ` title="${escapeHtml(g.genome_offtarget_top_loc)}"`
                        : '';
                    genomeDisplay = `<span${tip}>${maxCfd.toFixed(2)} <span class="muted">· ${g.genome_offtarget_count}</span></span>`;
                }
            }

            // Phase 2B-1: exon context column. Empty unless Ensembl
            // returned data AND the input aligned to the gene's CDS.
            let exonDisplay = '<span class="muted">—</span>';
            if (g.exon_context_summary) {
                const nmd = g.in_nmd_zone ? ' crispr-score-good' : '';
                exonDisplay = `<span class="crispr-exon-ctx${nmd}" title="${escapeHtml(g.exon_context_summary)}">${escapeHtml(g.exon_context_summary)}</span>`;
            }

            // Phase 2C-1: cloning oligo columns. Empty when no vector
            // was selected. Each cell wraps the oligo in <code> for the
            // mono font + a Copy button matching the spacer-cell pattern.
            const senseOligo     = g.sense_oligo || '';
            const antisenseOligo = g.antisense_oligo || '';
            // Display the oligo single-line with ellipsis on overflow;
            // tooltip + Copy button carry the full sequence so nothing
            // is hidden from the user.
            const senseCell = senseOligo
                ? `<div class="crispr-oligo-cell">
                       <code class="crispr-oligo" title="${escapeHtml(senseOligo)}">${escapeHtml(senseOligo)}</code>
                       <button class="crispr-copy ghost" type="button" data-copy="${escapeHtml(senseOligo)}">Copy</button>
                   </div>`
                : '<span class="muted">—</span>';
            const antisenseCell = antisenseOligo
                ? `<div class="crispr-oligo-cell">
                       <code class="crispr-oligo" title="${escapeHtml(antisenseOligo)}">${escapeHtml(antisenseOligo)}</code>
                       <button class="crispr-copy ghost" type="button" data-copy="${escapeHtml(antisenseOligo)}">Copy</button>
                   </div>`
                : '<span class="muted">—</span>';

            // Visible 3-D structure button (M5) — shown right in the row when
            // the cut maps to a residue and a human/mouse gene is set, so the
            // viewer is one click away without expanding the why-panel.
            const structMini = (_structCtxOk && g.cut_residue)
                ? `<button type="button" class="crispr-struct-btn crispr-struct-mini" data-struct-residue="${g.cut_residue}" title="View this cut site on the 3-D AlphaFold structure (residue ${g.cut_residue})" aria-label="View 3-D structure, residue ${g.cut_residue}">⌖ 3-D</button>`
                : '';

            return `
                <tr class="crispr-row" data-rank="${g.rank}">
                    <td class="rank"><div class="crispr-rank-cell"><button type="button" class="crispr-why-toggle" data-why="${g.rank}" aria-expanded="false" title="Why this guide?">${g.rank}<span class="crispr-why-caret" aria-hidden="true">›</span></button>${structMini}</div></td>
                    <td data-label="Strand">${g.strand === '+' ? 'sense' : 'antisense'}</td>
                    <td class="num crispr-primary" data-label="Position">${g.position.toLocaleString()}</td>
                    <td class="crispr-spacer crispr-primary" data-label="Spacer">
                        <code>${escapeHtml(g.spacer)}</code>
                        <button class="crispr-copy ghost" type="button" data-copy="${escapeHtml(g.spacer)}">Copy</button>
                    </td>
                    <td data-label="PAM"><code>${escapeHtml(g.pam)}</code></td>
                    <td class="num crispr-primary ${scoreClass}" data-label="Composite">${composite.toFixed(3)}</td>
                    <td class="num crispr-primary" data-label="On-target">${g.on_target_score.toFixed(3)}</td>
                    <td class="num ${cfdClass}" data-label="Self-off">${cfdLabel}</td>
                    <td class="num col-ko crispr-primary ${koClass}" data-label="KO score"${koTip}>${ko.toFixed(2)}</td>
                    <td class="col-ko" data-label="Top indel"${indelTip}><code class="crispr-indel">${escapeHtml(topIndel)}</code></td>
                    <td class="num col-ko ${fsClass}" data-label="FS %">${fsDisplay}</td>
                    <td class="num col-ko ${divClass}" data-label="Dominance">${divDisplay}</td>
                    <td class="col-ko" data-label="Base editor">${beDisplay}</td>
                    <td class="col-be" data-label="Edit">${beEditLabel}</td>
                    <td class="num col-be crispr-primary ${beEdClass}" data-label="Editability">${beEdDisplay}</td>
                    <td class="col-be" data-label="AA change">${beAa}</td>
                    <td class="col-be" data-label="Outcome">${beOutcome}</td>
                    <td class="num ${genomeClass}" data-label="Genome off">${genomeDisplay}</td>
                    <td data-label="Exon context">${exonDisplay}</td>
                    <td data-label="Sense oligo">${senseCell}</td>
                    <td data-label="Antisense oligo">${antisenseCell}</td>
                    <td data-label="Order">${_renderRowVendors(g)}</td>
                    <td class="num" data-label="GC %">${g.gc_pct.toFixed(0)}%</td>
                    <td data-label="Flags">${flagsHtml}</td>
                </tr>
                <tr class="crispr-why-row" data-why-row="${g.rank}" hidden>
                    <td colspan="24">${_crisprWhy(g)}</td>
                </tr>
            `;
        });
        tbody.innerHTML = rows.join('') ||
            '<tr><td colspan="24" class="muted" style="text-align:center;padding:18px">No guides match the current filters.</td></tr>';

        // Mobile card view (<=540px) renders each cell as a "LABEL : value"
        // row. Tag cells whose only content is an em-dash so the card layout
        // can hide them — keeps a phone card from listing a dozen empty fields
        // (genome/exon/cloning columns are blank unless that context was set).
        tbody.querySelectorAll('.crispr-row > td[data-label]').forEach((td) => {
            if (td.textContent.trim() === '—') td.classList.add('crispr-cell-empty');
        });

        // Delegated handler for the per-row vendor buttons. One listener
        // on tbody instead of one per button → cheap, also survives
        // re-renders without leaking.
        tbody.querySelectorAll('.crispr-vendor-btn-row').forEach(btn => {
            btn.addEventListener('click', () => {
                const vid  = btn.getAttribute('data-vendor');
                const rank = parseInt(btn.getAttribute('data-row-rank'), 10);
                const vendor = vendorsCache[vid];
                const g = lastGuides.find(x => x.rank === rank);
                if (!vendor || !g || !g.sense_oligo) return;
                // TSV for just this one guide — sense + antisense rows.
                const tsv = [
                    'Name\tSequence',
                    `g${g.rank}_sense\t${g.sense_oligo}`,
                    `g${g.rank}_antisense\t${g.antisense_oligo}`,
                ].join('\n');
                _vendorOrderClick(btn, vendor, tsv, `guide #${g.rank} (${g.spacer})`);
            });
        });

        // Wire copy buttons.
        tbody.querySelectorAll('[data-copy]').forEach((b) => {
            b.addEventListener('click', async () => {
                const text = b.getAttribute('data-copy') || '';
                try {
                    await navigator.clipboard.writeText(text);
                    const orig = b.textContent;
                    b.textContent = 'Copied';
                    setTimeout(() => { b.textContent = orig; }, 1200);
                } catch (_) {
                    _showError('Copy blocked by browser. Select the spacer text manually.');
                }
            });
        });

        // Phase 3 (M3): "why this guide" expand toggle. Clicking a rank
        // reveals/hides the plain-English explanation row beneath it.
        tbody.querySelectorAll('.crispr-why-toggle').forEach((btn) => {
            btn.addEventListener('click', () => {
                const rank = btn.getAttribute('data-why');
                const row = tbody.querySelector(`tr.crispr-why-row[data-why-row="${rank}"]`);
                const card = btn.closest('tr.crispr-row');
                const open = row ? row.hidden : !(card && card.classList.contains('crispr-row--open'));
                if (row) row.hidden = !open;
                // On mobile the card is collapsed to its primary fields; opening
                // reveals the full field list (CSS) alongside the why panel.
                if (card) card.classList.toggle('crispr-row--open', open);
                btn.setAttribute('aria-expanded', String(open));
                btn.classList.toggle('crispr-why-open', open);
            });
        });

        // Phase 3 (M5): "View 3-D structure" buttons inside the why panels.
        tbody.querySelectorAll('.crispr-struct-btn').forEach((btn) => {
            btn.addEventListener('click', () => {
                const residue = parseInt(btn.getAttribute('data-struct-residue'), 10);
                if (residue) _showCrisprStructure(residue);
            });
        });

        // Per-guide IP radar buttons inside the why panels — runs the radar
        // for THAT guide (not just #1), rendering into its own inline banner
        // beneath the button so the result stays next to the guide it checked.
        tbody.querySelectorAll('.crispr-radar-btn').forEach((btn) => {
            btn.addEventListener('click', () => {
                const rank = parseInt(btn.getAttribute('data-radar-rank'), 10);
                const guides = (lastGuides && lastGuides.length)
                    ? lastGuides : ((crisprData && crisprData.guides) || []);
                const guide = guides.find((g) => g.rank === rank);
                if (!guide) { _showError('Re-run the design, then check this guide.'); return; }
                const banner = tbody.querySelector(`.ip-radar-inline[data-radar-banner="${rank}"]`);
                _runRadarFor(guide, btn, banner);
            });
        });

        // Size the (sticky) "why" panels to the table's visible width so
        // the explanation reads as a viewport-width block, not a 2000px row.
        _sizeCrisprWhyPanels();

        // Scroll into view only on a fresh design — not on sort/filter
        // re-renders, which would yank the viewport on every toggle.
        if (!_isRerender) resCard.scrollIntoView({ behavior: 'smooth', block: 'start' });
    }

    function _sizeCrisprWhyPanels() {
        const wrap = resCard.querySelector('.result-table-wrap');
        if (wrap) wrap.style.setProperty('--crispr-why-w', wrap.clientWidth + 'px');
    }
    // Keep the panels viewport-width on resize / orientation change.
    window.addEventListener('resize', _sizeCrisprWhyPanels);

    // Export menu: CSV (universal, for pipelines/pandas/R) + Excel (.xlsx,
    // locale-safe for ;-delimiter Excel). The trigger toggles the menu; each
    // item downloads in its format. We re-design from the input on download so
    // the file matches exactly what the user saw in the table.
    const dlMenuItems = document.getElementById('crisprDownloadItems');
    if (dlBtn && dlMenuItems) {
        const closeDlMenu = () => { dlMenuItems.hidden = true; dlBtn.setAttribute('aria-expanded', 'false'); };
        dlBtn.addEventListener('click', (e) => {
            e.stopPropagation();
            const willOpen = dlMenuItems.hidden;
            dlMenuItems.hidden = !willOpen;
            dlBtn.setAttribute('aria-expanded', String(willOpen));
        });
        document.addEventListener('click', (e) => {
            if (!dlMenuItems.hidden && !e.target.closest('#crisprDownloadMenu')) closeDlMenu();
        });
        document.addEventListener('keydown', (e) => { if (e.key === 'Escape') closeDlMenu(); });
        dlMenuItems.querySelectorAll('.download-item').forEach((item) => {
            item.addEventListener('click', (e) => {
                e.preventDefault();
                closeDlMenu();
                const fmt = item.dataset.format || 'xlsx';
                if (!lastSubmittedSequence) { doCrisprDownload(fmt); return; }
                // Red Team gate before the file leaves the app.
                const gene = ((document.getElementById('crisprGeneSymbol') || {}).value || '').trim();
                runOracle({
                    seqs: _oracleSeqs(), gene: gene,
                    actionLabel: 'Before exporting ' + fmt.toUpperCase(),
                    proceed: () => doCrisprDownload(fmt),
                });
            });
        });
    }

    async function doCrisprDownload(fmt) {
        if (!lastSubmittedSequence) {
            _showError('Design guides first, then export.');
            return;
        }
        if (fmt !== 'csv' && fmt !== 'xlsx') fmt = 'xlsx';
        try {
            const enzymeRadio = document.querySelector('input[name="crisprEnzyme"]:checked');
            const modeRadio = document.querySelector('input[name="crisprMode"]:checked');
            const mode = (modeRadio && modeRadio.value) || 'knockout';
            const enzyme = mode === 'base_edit'
                ? 'cas9'
                : ((enzymeRadio && enzymeRadio.value) || 'cas9');
            const beSelect = document.getElementById('crisprBaseEditor');
            const base_editor = (mode === 'base_edit' && beSelect && beSelect.value) || '';
            const organismEl = document.getElementById('crisprOrganism');
            const geneEl     = document.getElementById('crisprGeneSymbol');
            const target_organism = (organismEl && organismEl.value) || '';
            const gene_symbol     = (geneEl && geneEl.value.trim()) || '';
            const vector_id = (vectorSelect && vectorSelect.value) || '';
            const res = await fetch('/api/crispr/download', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({
                    sequence: lastSubmittedSequence, enzyme,
                    target_organism, gene_symbol,
                    vector_id,
                    mode, base_editor,
                    format: fmt,
                    max_results: 50,
                }),
            });
            if (!res.ok) {
                throw new Error((fmt === 'csv' ? 'CSV' : 'Excel') + ' export failed.');
            }
            const blob = await res.blob();
            const url = URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.href = url;
            a.download = fmt === 'csv'
                ? 'turingdna_crispr_guides.csv'
                : 'turingdna_crispr_guides.xlsx';
            document.body.appendChild(a);
            a.click();
            document.body.removeChild(a);
            URL.revokeObjectURL(url);
        } catch (err) {
            _showError(err.message || String(err));
        }
    }

    // Initial state — depends on auth being ready. auth.js loads
    // before app.js so window.TuringAuth should exist by now.
    _updateStats();

    // ── Toxicity & Synthesis Oracle wiring (CRISPR) ─────────────────────
    // Collect the sequences an export/order would actually ship (cloning
    // oligos if a vector is set, else the spacers).
    function _oracleSeqs() {
        const gs = (lastGuides && lastGuides.length) ? lastGuides
                 : ((crisprData && crisprData.guides) || []);
        const out = [];
        gs.forEach(g => {
            if (g.sense_oligo) out.push(g.sense_oligo);
            if (g.antisense_oligo) out.push(g.antisense_oligo);
            if (!g.sense_oligo && g.spacer) out.push(g.spacer);
        });
        return out;
    }
    window.__oracleSeqs = _oracleSeqs;   // referenced by the export/order intercepts
})();

// ════════════════════════════════════════════════════════════════════════
// Toxicity & Synthesis Oracle (Red Team) — pre-export validation gate.
// Pure client-side, ZERO dependencies. Synthesis feasibility (Twist-style
// rules: GC / homopolymer / hairpin) + biological toxicity (essential-gene
// lookup). Opens a traffic-light "Red Team Report" before an Export or a
// Send-to-Twist, with an "Acknowledge & export anyway" bypass.
// ════════════════════════════════════════════════════════════════════════

// High-confidence subset of DepMap/Achilles common-essential genes (Hart
// CEGv2 core families: ribosome, proteasome, RNA Pol II core, core
// spliceosome, basal translation/replication, chaperonins, coatomer, +
// canonical oncogenic essentials). Precision over recall — a match is a
// genuine "knocking this out kills the cell" signal. Expandable to the full
// ~2k list. Symbols upper-cased on lookup.
const ESSENTIAL_GENES = new Set([
 'MYC','MYCN','KRAS','CTNNB1','CDK1','CDK7','CDK9','CCNK','PLK1','AURKB','KIF11','TPX2','BUB1B','BUB3','CENPA','INCENP','NUF2','NDC80',
 'PCNA','POLA1','POLD1','POLE','POLR1A','POLR1B','POLR2A','POLR2B','POLR2C','POLR2D','POLR2E','POLR2F','POLR2G','POLR2H','POLR2I','POLR2L','POLR3A',
 'PRIM1','RPA1','RPA2','RPA3','MCM2','MCM3','MCM4','MCM5','MCM6','MCM7','CDC45','GINS1','GINS2','ORC6','RFC2','RFC4','RFC5','TOP1','TOP2A',
 'PSMA1','PSMA2','PSMA3','PSMA4','PSMA5','PSMA6','PSMA7','PSMB1','PSMB2','PSMB3','PSMB4','PSMB5','PSMB6','PSMB7','PSMC1','PSMC2','PSMC3','PSMC4','PSMC5','PSMC6','PSMD1','PSMD2','PSMD3','PSMD4','PSMD6','PSMD7','PSMD11','PSMD12','PSMD14',
 'SF3B1','SF3B2','SF3B3','SF3B5','SF3A1','SF3A2','SF3A3','PRPF8','PRPF19','PRPF31','PRPF38A','SNRNP200','SNRNP70','EFTUD2','BUD31','RBM22','CDC5L','AQR','PLRG1','U2AF1','U2AF2','SNRPD1','SNRPD2','SNRPD3','SNRPB','SNRPE','SNRPF','SNRPG','XAB2',
 'EIF2S1','EIF2S2','EIF2S3','EIF2B1','EIF2B3','EIF2B5','EIF3A','EIF3B','EIF3C','EIF3D','EIF3G','EIF3I','EIF4A3','EIF4G1','EIF5B','EIF6','EEF1A1','EEF2','ETF1','GSPT1','PABPC1',
 'NACA','RPL3','RPL4','RPL5','RPL6','RPL7','RPL7A','RPL8','RPL9','RPL10','RPL10A','RPL11','RPL13','RPL13A','RPL14','RPL15','RPL18','RPL18A','RPL19','RPL23','RPL23A','RPL24','RPL27','RPL27A','RPL30','RPL31','RPL32','RPL34','RPL35','RPL35A','RPL36','RPL37','RPL37A','RPL38','RPLP0','RPLP1','RPLP2',
 'RPS2','RPS3','RPS3A','RPS4X','RPS5','RPS6','RPS7','RPS8','RPS9','RPS11','RPS13','RPS14','RPS15','RPS15A','RPS16','RPS17','RPS18','RPS19','RPS20','RPS23','RPS24','RPS25','RPS27','RPS27A','RPS28','RPSA',
 'NOP56','NOP58','FBL','DKC1','NHP2','RRM1','RRM2','TUBB','TUBA1B','TUBA1C','TUBG1','ACTB','ACTL6A',
 'COPA','COPB1','COPB2','COPZ1','ARCN1','SEC13','NUP93','NUP98','RAN','RANGAP1','XPO1','KPNB1','NSF','SEC61A1','SRP54','SRP72',
 'HSPA5','HSPA8','HSP90AB1','HSP90AA1','CCT2','CCT3','CCT4','CCT5','CCT6A','CCT7','CCT8','TCP1','VCP','RUVBL1','RUVBL2','PHB','PHB2','GAPDH','ATP5F1A','ATP5F1B',
]);

function _orGC(s){ const m = s.match(/[GC]/g); return s.length ? (m ? m.length : 0) / s.length * 100 : 0; }
function _orLocalGC(s, win){
    win = win || 50;
    if (s.length < win) { const g = _orGC(s); return { min: g, max: g }; }
    const pref = [0];
    for (let i = 0; i < s.length; i++) pref.push(pref[i] + (s[i] === 'G' || s[i] === 'C' ? 1 : 0));
    let min = 101, max = -1;
    for (let i = 0; i + win <= s.length; i++) { const g = (pref[i + win] - pref[i]) / win * 100; if (g < min) min = g; if (g > max) max = g; }
    return { min, max };
}
function _orHomopolymer(s){
    let best = { base: '', len: 0 }, run = 1;
    for (let i = 1; i <= s.length; i++) {
        if (i < s.length && s[i] === s[i - 1]) run++;
        else { if (run > best.len) best = { base: s[i - 1], len: run }; run = 1; }
    }
    return best;
}
const _OR_COMP = { A: 'T', T: 'A', G: 'C', C: 'G' };
function _orRevComp(s){ let o = ''; for (let i = s.length - 1; i >= 0; i--) o += (_OR_COMP[s[i]] || 'N'); return o; }
// Lightweight hairpin heuristic: find a k-mer whose reverse-complement occurs
// downstream within a loop window (a stem-loop), then extend to the true stem
// length. O(n·loop) — fine for oligos/variants; no ViennaRNA dependency.
function _orHairpin(s, minStem, maxLoop){
    minStem = minStem || 10; maxLoop = maxLoop || 40;
    const n = s.length; let best = { stem: 0, loop: 0 };
    if (n < 2 * minStem + 3) return best;
    const k = minStem;
    for (let i = 0; i + k <= n; i++) {
        const rc = _orRevComp(s.substr(i, k));
        const from = i + k + 3, to = Math.min(n - k, i + k + maxLoop);
        for (let j = from; j <= to; j++) {
            if (s.substr(j, k) === rc) {
                let stem = k, a = i - 1, b = j + k;
                while (a >= 0 && b < n && _OR_COMP[s[a]] === s[b]) { stem++; a--; b++; }
                if (stem > best.stem) best = { stem: stem, loop: j - (i + k) };
                break;
            }
        }
    }
    return best;
}
function runSynthChecks(seqs){
    let gcMin = 101, gcMax = -1, homo = { len: 0, base: '' }, hair = { stem: 0 }, scanned = 0;
    (seqs || []).forEach(raw => {
        const s = (raw || '').toUpperCase().replace(/[^ACGT]/g, '');
        if (s.length < 12) return;
        scanned++;
        const g = _orGC(s), loc = _orLocalGC(s, 50);
        gcMin = Math.min(gcMin, g, loc.min); gcMax = Math.max(gcMax, g, loc.max);
        const h = _orHomopolymer(s); if (h.len > homo.len) homo = h;
        const hp = _orHairpin(s);    if (hp.stem > hair.stem) hair = hp;
    });
    const flags = [];
    if (!scanned) return flags;
    if (gcMin < 20) flags.push({ level: 'red', title: 'Extreme low GC content', msg: 'A sequence drops to ' + gcMin.toFixed(0) + '% GC (below 20%). Very low GC is hard to synthesize — providers often fail or reject it.' });
    if (gcMax > 65) flags.push({ level: 'red', title: 'Extreme high GC content', msg: 'A sequence reaches ' + gcMax.toFixed(0) + '% GC (above 65%). High GC stalls polymerase during synthesis — expect difficulty or rejection.' });
    if (homo.len > 6) flags.push({ level: 'red', title: 'Homopolymer run', msg: 'A run of ' + homo.len + '×' + homo.base + ' (>6 identical bases) was found. Long single-base runs cause slippage and are a common synthesis-rejection cause.' });
    if (hair.stem >= 12) flags.push({ level: 'red', title: 'Heavy secondary structure', msg: 'Warning: your sequence contains a heavy secondary hairpin structure (' + hair.stem + '-bp stem); synthesis providers are ~90% likely to reject this order.' });
    else if (hair.stem >= 10) flags.push({ level: 'yellow', title: 'Moderate hairpin', msg: 'A moderate hairpin (' + hair.stem + '-bp stem) was detected — it may lower synthesis yield.' });
    return flags;
}
function runEssentialCheck(gene){
    const g = (gene || '').trim().toUpperCase();
    if (g && ESSENTIAL_GENES.has(g))
        return { level: 'yellow', title: 'Targets an essential gene', msg: 'Warning: this sgRNA targets a universally essential gene (' + g + '). Expect near-total cell death in standard lines unless you are running a dropout / viability screen.' };
    return null;
}
function _orClose(){ const m = document.getElementById('oracleModal'); if (m) m.remove(); }
function _showOracleModal(opts){
    _orClose();
    const level = opts.level, flags = opts.flags || [];
    const heading = { red: 'Critical synthesis failure', yellow: 'Proceed with caution', green: 'Clear — no flags' };
    const flagHtml = flags.length ? flags.map(f =>
        '<div class="oracle-flag oracle-' + f.level + '"><span class="oracle-flag-dot" aria-hidden="true"></span>' +
        '<div><strong>' + escapeHtml(f.title) + '</strong><p>' + escapeHtml(f.msg) + '</p></div></div>'
    ).join('') :
        '<div class="oracle-flag oracle-green"><span class="oracle-flag-dot" aria-hidden="true"></span><div><strong>No synthesis or toxicity flags</strong>' +
        '<p>GC content, homopolymers, and secondary structure are within synthesis limits, and the target isn’t a known essential gene.</p></div></div>';
    const goLabel = level === 'green' ? 'Export' : 'Acknowledge & export anyway';
    const overlay = document.createElement('div');
    overlay.id = 'oracleModal'; overlay.className = 'oracle-overlay';
    overlay.innerHTML =
        '<div class="oracle-backdrop"></div>' +
        '<div class="oracle-panel oracle-level-' + level + '" role="dialog" aria-modal="true" aria-labelledby="oracleTitle">' +
          '<div class="oracle-head">' +
            '<span class="oracle-light oracle-light-' + level + '" aria-hidden="true"></span>' +
            '<div class="oracle-head-text"><p class="oracle-kicker">Red Team Report</p>' +
            '<h2 id="oracleTitle">' + heading[level] + '</h2>' +
            '<p class="oracle-sub">' + escapeHtml(opts.actionLabel || 'Before you export') + '</p></div>' +
            '<button type="button" class="oracle-x" aria-label="Cancel">×</button>' +
          '</div>' +
          '<div class="oracle-flags">' + flagHtml + '</div>' +
          '<div class="oracle-foot">' +
            '<button type="button" class="ghost oracle-cancel">Cancel</button>' +
            '<button type="button" class="primary oracle-go' + (level === 'red' ? ' oracle-go-danger' : '') + '">' + goLabel + '</button>' +
          '</div>' +
        '</div>';
    document.body.appendChild(overlay);
    const close = () => _orClose();
    overlay.querySelector('.oracle-backdrop').addEventListener('click', close);
    overlay.querySelector('.oracle-x').addEventListener('click', close);
    overlay.querySelector('.oracle-cancel').addEventListener('click', close);
    overlay.querySelector('.oracle-go').addEventListener('click', () => { close(); if (typeof opts.proceed === 'function') opts.proceed(); });
    document.addEventListener('keydown', function esc(e){ if (e.key === 'Escape') { close(); document.removeEventListener('keydown', esc); } });
}
// Run the Red Team checks and show the report. opts: {seqs, gene, actionLabel, proceed}.
function runOracle(opts){
    const bio = runEssentialCheck(opts.gene);
    const flags = runSynthChecks(opts.seqs).concat(bio ? [bio] : []);
    const level = flags.some(f => f.level === 'red') ? 'red'
                : flags.some(f => f.level === 'yellow') ? 'yellow' : 'green';
    _showOracleModal({ level: level, flags: flags, actionLabel: opts.actionLabel, proceed: opts.proceed });
}

// ============================================================ PRIMER PICKER
// Batch primer triage. Submits all primers to /api/primers/analyze; on-template
// scoring comes back immediately, the optional NCBI specificity scan streams in
// via polling. The "AI pick" is a transparent fitness rubric (Tm/GC/clamp/
// dimer/uniqueness/specificity) — we show the reasoning, never a black box.
(function initPrimerPicker() {
    const analyzeBtn = document.getElementById('primerAnalyze');
    if (!analyzeBtn) return;
    const inputEl    = document.getElementById('primerInput');
    const templateEl = document.getElementById('primerTemplate');
    const scanEl     = document.getElementById('primerScanNcbi');
    const orgRow     = document.getElementById('primerOrganismRow');
    const orgEl      = document.getElementById('primerOrganism');
    const strictEl   = document.getElementById('primerStrict3p');
    const exampleBtn = document.getElementById('primerExample');
    const errEl      = document.getElementById('primerError');
    const warnEl     = document.getElementById('primerWarnings');
    const resCard    = document.getElementById('primerResultsCard');
    const statusEl   = document.getElementById('primerScanStatus');
    const bestEl     = document.getElementById('primerBest');
    const ampEl      = document.getElementById('primerAmplicons');
    const prodEl     = document.getElementById('primerProducts');
    const listEl     = document.getElementById('primerList');
    let pollHandle = null;
    let lastData = null;   // last analyze response — for Save + reopen

    // The organism selector only matters when the specificity scan is on.
    if (scanEl && orgRow) {
        const syncOrg = () => { orgRow.hidden = !scanEl.checked; };
        scanEl.addEventListener('change', syncOrg);
        syncOrg();
    }
    const ORG_LABEL = { human: 'Homo sapiens', mouse: 'Mus musculus', rat: 'Rattus norvegicus',
                        zebrafish: 'Danio rerio', yeast: 'S. cerevisiae', ecoli: 'E. coli',
                        all: 'all sequences (nt)' };

    const esc = (s) => (typeof escapeHtml === 'function' ? escapeHtml(String(s)) : String(s));
    const pct = (f) => Math.round((Number(f) || 0) * 100);

    function showErr(msg) { if (errEl) { errEl.textContent = msg; errEl.hidden = false; } }
    function clearErr() { if (errEl) { errEl.hidden = true; errEl.textContent = ''; } }

    function fitnessBar(f) {
        const p = pct(f);
        const cls = p >= 70 ? 'pf-high' : p >= 45 ? 'pf-mid' : 'pf-low';
        return `<div class="pf-bar"><span class="pf-fill ${cls}" style="width:${p}%"></span></div>`
             + `<span class="pf-num">${p}</span>`;
    }

    function templateBadge(p, hasTemplate) {
        if (!hasTemplate) return '';
        const ot = p.on_template || {};
        if (ot.n_strong_sites === 1) return '<span class="pchip pchip-good">unique on template</span>';
        if ((ot.n_strong_sites || 0) > 1) return `<span class="pchip pchip-warn">${ot.n_strong_sites} sites on template</span>`;
        return '<span class="pchip pchip-bad">no match on template</span>';
    }

    function specBadge(p) {
        const s = p.specificity;
        if (!s) return '';
        // Off-target PRODUCTS (in-silico PCR) are the real signal.
        const n = (s.offtarget_products != null) ? s.offtarget_products : s.strong_offtargets;
        if (n === 0) return '<span class="pchip pchip-good">specific · 0 off-target products</span>';
        if (n <= 2) return `<span class="pchip pchip-warn">${n} off-target product${n === 1 ? '' : 's'}</span>`;
        return `<span class="pchip pchip-bad">${n} off-target products</span>`;
    }

    function renderPrimerCard(p, isBest) {
        const role = p.role ? `<span class="pchip pchip-role">${esc(p.role === 'F' ? 'forward' : 'reverse')}</span>` : '';
        const flags = [];
        if (p.gc_clamp) flags.push('3′ G/C clamp');
        if (p.hairpin >= 6) flags.push(`hairpin (stem ${p.hairpin})`);
        if (p.self_dimer >= 4) flags.push(`3′ self-dimer (${p.self_dimer})`);
        const why = (p.why || []).map(w => `<li>${esc(w)}</li>`).join('');
        return `
          <div class="primer-card${isBest ? ' primer-card-best' : ''}">
            <div class="primer-card-head">
              <div class="primer-card-id">
                ${isBest ? '<span class="pchip pchip-best">★ Recommended</span>' : ''}
                <strong>${esc(p.name)}</strong> ${role}
              </div>
              <div class="primer-fitness">${fitnessBar(p.fitness)}</div>
            </div>
            <code class="primer-seq">${esc(p.seq)}</code>
            <div class="primer-meta">
              <span>${p.length} nt</span><span>GC ${p.gc}%</span>
              <span>Tm ${p.tm != null ? p.tm + '°C' : '—'}</span>
              ${templateBadge(p, _hasTemplate)} ${specBadge(p)}
            </div>
            ${flags.length ? `<div class="primer-flags">${flags.map(f => esc(f)).join(' · ')}</div>` : ''}
            <details class="primer-why"><summary>Why this score</summary><ul>${why}</ul></details>
          </div>`;
    }

    let _hasTemplate = false;
    function _renderPrimerMeta(r) {
        const primers = (r && r.primers) || [];
        if (!primers.length) { tdRenderMethods('primerRunMeta', [], null); return; }
        const tmplLen = ((templateEl && templateEl.value) || '').replace(/\s+/g, '').length;
        const scanned = !!(scanEl && scanEl.checked);
        const org = scanned && orgEl ? (ORG_LABEL[orgEl.value] || orgEl.value) : '';
        const best = primers[0];
        let m = `Candidate primers (n=${primers.length}) were evaluated in silico: melting temperatures by the nearest-neighbor method (SantaLucia, <cite>Proc. Natl. Acad. Sci.</cite> 1998; Allawi &amp; SantaLucia, <cite>Biochemistry</cite> 1997), with GC content and 3&prime;-end stability, and binding assessed by in-silico PCR against a ${tmplLen ? tmplLen.toLocaleString() + '-bp' : 'user-supplied'} template`;
        m += scanned ? `, with a specificity check against ${org || 'the selected genome'} (NCBI).` : `.`;
        if (best) m += ` The top-ranked primer was ${esc(best.name || 'pair 1')} (Tm ${best.tm != null ? best.tm + ' °C' : '—'}, GC ${best.gc != null ? best.gc + '%' : '—'}). Primers were supplied by the user; the tool scores and ranks them.`;
        tdRenderMethods('primerRunMeta', [
            ['Primers', primers.length],
            ['Template', tmplLen ? tmplLen.toLocaleString() + ' bp' : 'none'],
            ['Specificity', scanned ? (org || 'on') : 'off'],
        ], m);
    }

    function render(data) {
        lastData = data;
        const r = data.result || {};
        _hasTemplate = !!r.has_template;
        resCard.hidden = false;
        _renderPrimerMeta(r);

        // Best pick
        const best = (r.primers || [])[0];
        bestEl.innerHTML = best
            ? `<div class="primer-best-head">Top pick: <strong>${esc(best.name)}</strong>
                 <span class="primer-best-score">fitness ${pct(best.fitness)}/100</span></div>`
            : '';

        // Amplicons (pairs)
        if ((r.amplicons || []).length) {
            ampEl.hidden = false;
            ampEl.innerHTML = '<h3 class="primer-sec-title">Primer pairs</h3>' +
                r.amplicons.map((a, i) => `
                  <div class="amp-row${i === 0 ? ' amp-row-best' : ''}">
                    <div class="amp-pair">${i === 0 ? '★ ' : ''}${esc(a.fwd)} <span class="amp-x">+</span> ${esc(a.rev)}</div>
                    <div class="amp-stats">
                      <span>${a.amplicon_bp != null ? a.amplicon_bp.toLocaleString() + ' bp' : 'no amplicon on template'}</span>
                      <span>ΔTm ${a.tm_diff != null ? a.tm_diff + '°C' : '—'}</span>
                      ${a.cross_dimer >= 4 ? `<span class="pchip pchip-bad">cross-dimer ${a.cross_dimer}</span>` : '<span class="pchip pchip-good">no cross-dimer</span>'}
                      <span class="amp-fit">pair ${pct(a.pair_fitness)}/100</span>
                    </div>
                  </div>`).join('');
        } else { ampEl.hidden = true; ampEl.innerHTML = ''; }

        // In-silico PCR results: the user's INTENDED product(s), then any
        // genuine off-target products. Redundant database hits for the same
        // amplicon are already collapsed server-side, so counts are honest.
        if (r.specificity_done) {
            const org = ORG_LABEL[r.organism] || r.organism || 'the selected genome';
            const intended = r.intended_products || [];
            const off = r.offtarget_products || [];
            const seenIn = (pr) => (pr.count > 1
                ? `<span class="prod-seen">seen in ${pr.count} ${esc(org)} records</span>` : '');
            const row = (pr, cls) => `
                  <div class="prod-row ${cls}">
                    <div class="prod-pair">${esc(pr.fwd_name || pr.fwd)} <span class="amp-x">+</span> ${esc(pr.rev_name || pr.rev)}</div>
                    <div class="prod-info"><span class="prod-size">${(pr.size || 0).toLocaleString()} bp</span>
                      <span class="prod-subj">${esc(pr.title || pr.subject)}</span>${seenIn(pr)}</div>
                  </div>`;

            let html = `<h3 class="primer-sec-title">In-silico PCR · ${esc(org)}</h3>`;
            if (intended.length) {
                html += `<div class="primer-intended-head">Intended product${intended.length === 1 ? '' : 's'} ` +
                        `— confirmed in the ${esc(org)} genome:</div>` +
                        intended.map(pr => row(pr, 'prod-row-ok')).join('');
            }
            if (!off.length) {
                html += `<div class="primer-clean">✓ No off-target products predicted in <strong>${esc(org)}</strong>` +
                        `${intended.length ? ' beyond your intended amplicon' : ''}. These primers look specific.</div>`;
            } else {
                html += `<div class="primer-prod-note">${off.length} distinct off-target product${off.length === 1 ? '' : 's'} ` +
                        `your primers could also amplify in ${esc(org)}:</div>` +
                        off.slice(0, 12).map(pr => row(pr, '')).join('') +
                        (off.length > 12 ? `<div class="primer-prod-more">+ ${off.length - 12} more</div>` : '');
            }
            prodEl.hidden = false;
            prodEl.innerHTML = html;
        } else { prodEl.hidden = true; prodEl.innerHTML = ''; }

        // Ranked list
        listEl.innerHTML = '<h3 class="primer-sec-title">All primers · ranked</h3>' +
            (r.primers || []).map((p, i) => renderPrimerCard(p, i === 0)).join('');
    }

    function setScanStatus(state, elapsed) {
        if (!statusEl) return;
        if (state === 'scanning') {
            statusEl.hidden = false;
            statusEl.innerHTML = `<span class="ip-radar-spinner" aria-hidden="true"></span> `
                + `Running in-silico PCR — searching the genome for off-target products…${elapsed != null ? ' · ' + elapsed + 's' : ''} `
                + `<span class="primer-scan-note">(template scores show now; specificity updates when it finishes)</span>`;
        } else if (state === 'done') {
            statusEl.hidden = false;
            statusEl.innerHTML = '<span class="primer-scan-done">✓ In-silico PCR specificity check complete</span>';
            setTimeout(() => { if (statusEl) statusEl.hidden = true; }, 4000);
        } else if (state === 'error') {
            statusEl.hidden = false;
            statusEl.innerHTML = '<span class="primer-scan-err">NCBI scan unavailable — showing template scores only.</span>';
        } else { statusEl.hidden = true; statusEl.innerHTML = ''; }
    }

    function poll(jobId) {
        if (pollHandle) clearTimeout(pollHandle);
        pollHandle = setTimeout(async () => {
            try {
                const res = await fetch('/api/primers/' + jobId);
                const data = await res.json();
                if (!res.ok) throw new Error(data.error || 'lost job');
                render(data);
                if (data.status === 'done') { setScanStatus('done'); return; }
                if (data.status === 'error') { setScanStatus('error'); return; }
                setScanStatus('scanning', data.elapsed_seconds);
                poll(jobId);
            } catch (e) { setScanStatus('error'); }
        }, 3000);
    }

    async function analyze() {
        clearErr();
        if (warnEl) { warnEl.hidden = true; warnEl.innerHTML = ''; }
        const primers = (inputEl.value || '').trim();
        if (!primers) { showErr('Paste at least one primer.'); return; }
        const template = (templateEl.value || '').trim();
        const scan = !!(scanEl && scanEl.checked);
        const organism = (orgEl && orgEl.value) || 'human';
        const strict3p = !!(strictEl && strictEl.checked);
        const orig = analyzeBtn.textContent;
        analyzeBtn.disabled = true;
        analyzeBtn.textContent = 'Analysing…';
        if (pollHandle) { clearTimeout(pollHandle); pollHandle = null; }
        try {
            const res = await fetch('/api/primers/analyze', {
                method: 'POST', headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ primers, template, scan_ncbi: scan, blast_consent: scan, organism, strict_3p: strict3p }),
            });
            const data = await res.json();
            if (res.status === 403 && data.kind === 'signin_required') {
                window.dispatchEvent(new Event('td:signin-required'));
                showErr('Primer Analysis is free with an account — sign in to analyse your primers.');
                return;
            }
            if (!res.ok) { showErr(data.error || 'Analysis failed.'); return; }
            if ((data.warnings || []).length && warnEl) {
                warnEl.hidden = false;
                warnEl.innerHTML = '<strong>Note:</strong> ' + data.warnings.map(esc).join(' · ');
            }
            render(data);
            if (data.status === 'scanning' && data.job_id) {
                setScanStatus('scanning', 0); poll(data.job_id);
            } else { setScanStatus('hide'); }
            resCard.scrollIntoView({ behavior: 'smooth', block: 'start' });
        } catch (e) {
            showErr('Could not reach the analyser. Check your connection and retry.');
        } finally {
            analyzeBtn.disabled = false;
            analyzeBtn.textContent = orig;
        }
    }

    analyzeBtn.addEventListener('click', analyze);
    if (exampleBtn) exampleBtn.addEventListener('click', () => {
        // EGFP-ish demo: two F candidates + one R, with a template they amplify.
        inputEl.value = [
            '>EGFP_F1', 'ATGGTGAGCAAGGGCGAGGA',
            '>EGFP_F2', 'AGCAAGGGCGAGGAGCTGTT',
            '>EGFP_R',  'TTGTGGCGGATCTTGAAGTT',
        ].join('\n');
        templateEl.value =
            'ATGGTGAGCAAGGGCGAGGAGCTGTTCACCGGGGTGGTGCCCATCCTGGTCGAGCTGGACGGCGACGTAAACGGCCACAAGTTCAGCGTGTCCGGCGAGGGCGAGGGCGATGCCACCTACGGCAAGCTGACCCTGAAGTTCATCTGCACCACCGGCAAGCTGCCCGTGCCCTGGCCCACCCTCGTGACCACCCTGACCTACGGCGTGCAGTGCTTCAGCCGCTACCCCGACCACATGAAGCAGCACGACTTCTTCAAGTCCGCCATGCCCGAAGGCTACGTCCAGGAGCGCACCATCTTCTTCAAGGACGACGGCAACTACAAGACCCGCGCCGAGGTGAAGTTCGAGGGCGACACCCTGGTGAACCGCATCGAGCTGAAGGGCATCGACTTCAAGGAGGACGGCAACATCCTGGGGCACAAGCTGGAGTACAACTACAACAGCCACAACGTCTATATCATGGCCGACAAGCAGAAGAACGGCATCAAGGTGAACTTCAAGATCCGCCACAACATCGAGGACGGCAGCGTGCAGCTCGCCGACCACTACCAGCAGAACACCCCCATCGGCGACGGCCCCGTGCTGCTGCCCGACAACCACTACCTGAGCACCCAGTCCGCCCTGAGCAAAGACCCCAACGAGAAGCGCGATCACATGGTCCTGCTGGAGTTCGTGACCGCCGCCGGGATCACTCTCGGCATGGACGAGCTGTACAAGTAA';
        if (scanEl) scanEl.checked = false;
    });

    // ── Export (CSV / Excel) — POST the held result, stream back a file ──
    async function _exportPrimers(fmt) {
        const r = (lastData && lastData.result) || null;
        if (!r || !(r.primers && r.primers.length)) { showErr('Analyse some primers first, then export.'); return; }
        try {
            const res = await fetch('/api/primers/export', {
                method: 'POST', headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ result: r, format: fmt }),
            });
            if (res.status === 403) { window.dispatchEvent(new Event('td:signin-required')); return; }
            if (!res.ok) { showErr('Export failed.'); return; }
            const blob = await res.blob();
            const url = URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.href = url;
            a.download = fmt === 'csv' ? 'turingdna_primers.csv' : 'turingdna_primers.xlsx';
            document.body.appendChild(a); a.click(); a.remove();
            setTimeout(() => URL.revokeObjectURL(url), 1500);
        } catch (e) { showErr('Export failed.'); }
    }
    const pDlBtn = document.getElementById('primerDownloadBtn');
    const pDlItems = document.getElementById('primerDownloadItems');
    if (pDlBtn && pDlItems) {
        pDlBtn.addEventListener('click', (e) => {
            e.stopPropagation();
            const open = pDlItems.hidden;
            pDlItems.hidden = !open;
            pDlBtn.setAttribute('aria-expanded', String(open));
        });
        pDlItems.addEventListener('click', (e) => {
            const it = e.target.closest('[data-format]'); if (!it) return;
            pDlItems.hidden = true; pDlBtn.setAttribute('aria-expanded', 'false');
            _exportPrimers(it.getAttribute('data-format'));
        });
        document.addEventListener('click', () => {
            if (!pDlItems.hidden) { pDlItems.hidden = true; pDlBtn.setAttribute('aria-expanded', 'false'); }
        });
    }

    // ── Save & reopen (unified "My designs" hub) ──
    const saveBtn = document.getElementById('primerSaveBtn');
    function _primerLabel() {
        const n = ((lastData && lastData.result && lastData.result.primers) || []).length;
        const bits = [n + ' primer' + (n === 1 ? '' : 's')];
        if (scanEl && scanEl.checked && orgEl && orgEl.value) bits.push(ORG_LABEL[orgEl.value] || orgEl.value);
        return bits.join(' · ');
    }
    if (saveBtn) saveBtn.addEventListener('click', async () => {
        const r = (lastData && lastData.result) || null;
        if (!r || !(r.primers && r.primers.length)) { showErr('Analyse some primers first, then save.'); return; }
        const orig = saveBtn.textContent;
        saveBtn.disabled = true; saveBtn.textContent = 'Saving…';
        try {
            const tmpl = ((templateEl && templateEl.value) || '').replace(/\s+/g, '');
            const res = await fetch('/api/primers/save', {
                method: 'POST', headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({
                    label: _primerLabel(),
                    organism: (scanEl && scanEl.checked && orgEl) ? orgEl.value : '',
                    template_len: tmpl.length,
                    n_primers: r.primers.length,
                    result: r,
                }),
            });
            const data = await res.json();
            if (res.status === 403 && data.kind === 'signin_required') { window.dispatchEvent(new Event('td:signin-required')); return; }
            if (!data.ok) { showErr(data.error || 'Could not save the primer set.'); return; }
            saveBtn.textContent = 'Saved ✓';
            setTimeout(() => { saveBtn.textContent = orig; }, 1600);
        } catch (e) { showErr(e.message || 'Could not save the primer set.'); }
        finally { saveBtn.disabled = false; if (saveBtn.textContent === 'Saving…') saveBtn.textContent = orig; }
    });

    async function _loadPrimerSet(id) {
        try {
            const res = await fetch('/api/primers/analyses/' + encodeURIComponent(id));
            const data = await res.json();
            if (res.status === 403 && data.kind === 'signin_required') { window.dispatchEvent(new Event('td:signin-required')); return; }
            if (!data.ok || !data.analysis) { showErr('Could not open that primer set.'); return; }
            const a = data.analysis;
            if (location.hash !== '#primers') location.hash = '#primers';
            if (orgEl && a.organism) orgEl.value = a.organism;
            render({ result: a.result || {} });
            if (resCard) resCard.scrollIntoView({ behavior: 'smooth', block: 'start' });
        } catch (e) { showErr('Could not open that primer set.'); }
    }
    window.TDSaved = window.TDSaved || {};
    window.TDSaved.primer = _loadPrimerSet;
})();

// ============================================================ PLASMID STUDIO
// Import GenBank/FASTA/raw → annotated plasmid → SVG circular + linear map,
// restriction analysis (1088 REBASE enzymes), digest → virtual gel, export,
// and a per-user library. Sign-in gated (tab-click modal + backend 403).
(function initPlasmidStudio() {
    const importBtn = document.getElementById('plasmidImport');
    if (!importBtn) return;
    const $ = (id) => document.getElementById(id);
    const inputEl = $('plasmidInput'), fileEl = $('plasmidFile'), errEl = $('plasmidError');
    const resCard = $('plasmidResultsCard'), mapWrap = $('plasmidMapWrap');
    const featuresEl = $('plasmidFeatures'), nameEl = $('plasmidName'), metaEl = $('plasmidMeta');
    const enzGrid = $('plasmidEnzymeGrid'), gelEl = $('plasmidGel');
    const libModal = $('plasmidLibraryModal'), libList = $('plasmidLibraryList');
    const esc = (s) => (typeof escapeHtml === 'function' ? escapeHtml(String(s)) : String(s));
    const pmColor = (c) => (/^#[0-9A-Fa-f]{3,8}$/.test(c) ? c : '#9AA0AA');  // only safe hex into SVG/style

    let plasmid = null;          // current plasmid model
    let restriction = null;      // restriction analysis result
    const selected = new Set();  // selected enzyme names
    let viewMode = 'circular';

    const showErr = (m) => { if (errEl) { errEl.textContent = m; errEl.hidden = false; } };
    const clearErr = () => { if (errEl) { errEl.hidden = true; errEl.textContent = ''; } };
    const signin403 = (data) => (data && data.kind === 'signin_required');

    // ---- geometry helpers (circular) ----
    const TAU = Math.PI * 2;
    function ptAt(pos, len, r, cx, cy) {
        const t = (pos / len) * TAU;
        return [cx + r * Math.sin(t), cy - r * Math.cos(t)];
    }
    function arcPath(a, b, len, r, cx, cy) {
        if (b < a) b += len;
        const span = (b - a) / len;
        if (span >= 0.999) {  // full circle → two half-arcs
            const [x0, y0] = ptAt(a, len, r, cx, cy);
            const [xm, ym] = ptAt(a + len / 2, len, r, cx, cy);
            return `M ${x0.toFixed(2)} ${y0.toFixed(2)} A ${r} ${r} 0 1 1 ${xm.toFixed(2)} ${ym.toFixed(2)} A ${r} ${r} 0 1 1 ${x0.toFixed(2)} ${y0.toFixed(2)}`;
        }
        const [x1, y1] = ptAt(a, len, r, cx, cy);
        const [x2, y2] = ptAt(b % len, len, r, cx, cy);
        const large = span > 0.5 ? 1 : 0;
        return `M ${x1.toFixed(2)} ${y1.toFixed(2)} A ${r} ${r} 0 ${large} 1 ${x2.toFixed(2)} ${y2.toFixed(2)}`;
    }

    function cutSites() {
        // union of selected enzymes' sites → [{pos, name}]
        if (!restriction) return [];
        const out = [];
        restriction.enzymes.forEach((e) => {
            if (selected.has(e.name)) e.sites.forEach((p) => out.push({ pos: p, name: e.name }));
        });
        return out;
    }

    function buildCircularSVG(opt) {
        opt = opt || {};
        const len = plasmid.length, cx = 210, cy = 210, R = 138;
        const feats = plasmid.features || [];
        let svg = `<svg viewBox="0 0 420 420" class="plasmid-svg${opt.mini ? ' plasmid-svg-mini' : ''}" role="img" aria-label="Circular plasmid map">`;
        svg += `<circle cx="${cx}" cy="${cy}" r="${R}" class="pm-backbone"/>`;
        // selection arc — mirrors the sequence selection; updated live via updateSelArc()
        const selD = sel ? arcPath(sel.from - 1, sel.to, len, R, cx, cy) : '';
        svg += `<path id="pmSelArc" class="pm-sel" d="${selD}" fill="none"/>`;
        // ruler ticks
        const ticks = 8;
        for (let i = 0; i < ticks; i++) {
            const pos = Math.round(len * i / ticks);
            const [x1, y1] = ptAt(pos, len, R - 5, cx, cy), [x2, y2] = ptAt(pos, len, R + 5, cx, cy);
            const [lx, ly] = ptAt(pos, len, R - 16, cx, cy);
            svg += `<line x1="${x1.toFixed(1)}" y1="${y1.toFixed(1)}" x2="${x2.toFixed(1)}" y2="${y2.toFixed(1)}" class="pm-tick"/>`;
            svg += `<text x="${lx.toFixed(1)}" y="${ly.toFixed(1)}" class="pm-tick-lbl" text-anchor="middle" dominant-baseline="middle">${pos === 0 ? '1' : pos.toLocaleString()}</text>`;
        }
        // feature arcs (+ strand outside, − inside)
        feats.forEach((f) => {
            const r = R + (f.strand >= 0 ? 9 : -9);
            const d = arcPath(f.start, f.end, len, r, cx, cy);
            svg += `<path d="${d}" class="pm-feat" stroke="${pmColor(f.color)}"><title>${esc(f.name)} · ${esc(f.type)} · ${f.start + 1}–${f.end} (${f.strand >= 0 ? '+' : '−'})</title></path>`;
        });
        // labels for features big enough to deserve one
        feats.forEach((f) => {
            if ((f.end - f.start) / len < 0.04) return;
            const mid = (f.start + (f.end - f.start) / 2) % len;
            const [lx, ly] = ptAt(mid, len, R + 30, cx, cy);
            const [ex, ey] = ptAt(mid, len, R + (f.strand >= 0 ? 13 : -13), cx, cy);
            const anchor = lx < cx - 6 ? 'end' : (lx > cx + 6 ? 'start' : 'middle');
            svg += `<line x1="${ex.toFixed(1)}" y1="${ey.toFixed(1)}" x2="${lx.toFixed(1)}" y2="${ly.toFixed(1)}" class="pm-leader"/>`;
            svg += `<text x="${lx.toFixed(1)}" y="${ly.toFixed(1)}" class="pm-feat-lbl" text-anchor="${anchor}" dominant-baseline="middle">${esc(f.name)}</text>`;
        });
        // cut sites
        cutSites().forEach((c) => {
            const [x1, y1] = ptAt(c.pos, len, R - 12, cx, cy), [x2, y2] = ptAt(c.pos, len, R + 20, cx, cy);
            const [lx, ly] = ptAt(c.pos, len, R + 30, cx, cy);
            const anchor = lx < cx - 6 ? 'end' : (lx > cx + 6 ? 'start' : 'middle');
            svg += `<line x1="${x1.toFixed(1)}" y1="${y1.toFixed(1)}" x2="${x2.toFixed(1)}" y2="${y2.toFixed(1)}" class="pm-cut"/>`;
            svg += `<text x="${lx.toFixed(1)}" y="${ly.toFixed(1)}" class="pm-cut-lbl" text-anchor="${anchor}" dominant-baseline="middle">${esc(c.name)} (${c.pos})</text>`;
        });
        // center
        svg += `<text x="${cx}" y="${cy - 8}" class="pm-center-name" text-anchor="middle">${esc((plasmid.name || 'plasmid').slice(0, 22))}</text>`;
        svg += `<text x="${cx}" y="${cy + 12}" class="pm-center-sub" text-anchor="middle">${len.toLocaleString()} bp · ${esc(plasmid.topology)}</text>`;
        svg += `</svg>`;
        return svg;
    }
    function renderCircular() { mapWrap.innerHTML = buildCircularSVG(); }
    // Companion map shown beside the sequence editor.
    function renderCompanionMap() {
        const host = document.getElementById('seqMini'); if (!host) return;
        host.innerHTML = buildCircularSVG({ mini: true });
        // click the companion map → place the caret / jump there in the sequence
        const svg = host.querySelector('svg');
        if (svg) svg.addEventListener('click', (e) => {
            const r = svg.getBoundingClientRect();
            const px = (e.clientX - r.left) / r.width * 420, py = (e.clientY - r.top) / r.height * 420;
            const ang = Math.atan2(px - 210, -(py - 210));   // 0 at top, clockwise
            let pos = Math.round(((ang < 0 ? ang + TAU : ang) / TAU) * plasmid.length);
            setSel(pos + 1, pos + 1);
        });
    }
    // Cheap live update of just the selection arc (no full map rebuild).
    function updateSelArc() {
        const p = document.getElementById('pmSelArc'); if (!p) return;
        const r = curSel ? curSel : (sel ? [sel.from - 1, sel.to] : null);
        p.setAttribute('d', r && r[1] > r[0] ? arcPath(r[0], r[1], plasmid.length, 138, 210, 210) : '');
    }

    function renderLinear() {
        const len = plasmid.length, W = Math.max(900, 0), H = 150, m = 40, trackY = 80;
        const x = (pos) => m + (pos / len) * (W - 2 * m);
        const feats = plasmid.features || [];
        let svg = `<svg viewBox="0 0 ${W} ${H}" class="plasmid-svg-linear" preserveAspectRatio="xMinYMid meet" role="img" aria-label="Linear plasmid map">`;
        svg += `<line x1="${m}" y1="${trackY}" x2="${W - m}" y2="${trackY}" class="pm-backbone"/>`;
        const ticks = 10;
        for (let i = 0; i <= ticks; i++) {
            const pos = Math.round(len * i / ticks), xx = x(pos);
            svg += `<line x1="${xx.toFixed(1)}" y1="${trackY - 4}" x2="${xx.toFixed(1)}" y2="${trackY + 4}" class="pm-tick"/>`;
            svg += `<text x="${xx.toFixed(1)}" y="${trackY + 18}" class="pm-tick-lbl" text-anchor="middle">${pos === 0 ? '1' : pos.toLocaleString()}</text>`;
        }
        feats.forEach((f) => {
            const x1 = x(f.start), x2 = x(Math.min(f.end, len)), y = f.strand >= 0 ? trackY - 18 : trackY + 6;
            svg += `<rect x="${x1.toFixed(1)}" y="${y}" width="${Math.max(2, x2 - x1).toFixed(1)}" height="12" rx="2" class="pm-feat-rect" fill="${pmColor(f.color)}"><title>${esc(f.name)} · ${f.start + 1}–${f.end}</title></rect>`;
            if ((f.end - f.start) / len >= 0.03)
                svg += `<text x="${((x1 + x2) / 2).toFixed(1)}" y="${(f.strand >= 0 ? y - 3 : y + 22)}" class="pm-feat-lbl" text-anchor="middle">${esc(f.name)}</text>`;
        });
        cutSites().forEach((c) => {
            const xx = x(c.pos);
            svg += `<line x1="${xx.toFixed(1)}" y1="20" x2="${xx.toFixed(1)}" y2="${trackY + 30}" class="pm-cut"/>`;
            svg += `<text x="${xx.toFixed(1)}" y="14" class="pm-cut-lbl" text-anchor="middle">${esc(c.name)}</text>`;
        });
        svg += `</svg>`;
        mapWrap.innerHTML = `<div class="plasmid-linear-scroll">${svg}</div>`;
    }

    function renderMap() {
        const tools = document.getElementById('plasmidSeqTools');
        const layout = mapWrap.closest('.plasmid-layout');
        if (viewMode === 'sequence') {
            if (tools) tools.hidden = false;
            if (layout) layout.classList.add('is-seq');   // give the editor full width
            renderSequence();
        } else {
            if (tools) tools.hidden = true;
            if (layout) layout.classList.remove('is-seq');
            viewMode === 'linear' ? renderLinear() : renderCircular();
        }
    }

    function renderFeatures() {
        const feats = plasmid.features || [];
        if (!feats.length) { featuresEl.innerHTML = '<div class="plasmid-nofeat">No features. (Raw input gets ORF + motif auto-annotation.)</div>'; return; }
        featuresEl.innerHTML = feats.map((f, i) => `
            <div class="plasmid-feat-item" data-fidx="${i}" title="Click to select in the sequence view">
              <span class="pf-swatch" style="background:${pmColor(f.color)}"></span>
              <span class="pf-name">${esc(f.name)}</span>
              <span class="pf-type">${esc(f.type)}</span>
              <span class="pf-pos">${(f.start + 1).toLocaleString()}–${f.end.toLocaleString()} ${f.strand >= 0 ? '(+)' : '(−)'}</span>
            </div>`).join('');
    }

    function renderEnzymes() {
        if (!restriction) { enzGrid.innerHTML = '<span class="field-hint">Loading enzymes…</span>'; return; }
        const cutters = restriction.enzymes.filter((e) => e.count > 0);
        const non = restriction.enzymes.filter((e) => e.count === 0);
        cutters.sort((a, b) => a.count - b.count || a.name.localeCompare(b.name));
        enzGrid.innerHTML = cutters.map((e) => {
            const cls = e.count === 1 ? 'enz-single' : (e.count === 2 ? 'enz-double' : 'enz-multi');
            return `<button type="button" class="plasmid-enz ${cls}${selected.has(e.name) ? ' enz-on' : ''}" data-enz="${esc(e.name)}" title="${e.count} site${e.count === 1 ? '' : 's'} · ${esc(e.overhang || '')}">${esc(e.name)}<span class="enz-count">${e.count}</span></button>`;
        }).join('') + (non.length ? `<span class="plasmid-noncut">+ ${non.length} non-cutters</span>` : '');
    }

    function setMeta() {
        metaEl.textContent = `${plasmid.length.toLocaleString()} bp · ${plasmid.topology} · GC ${plasmid.gc}%`
            + ((plasmid.features || []).length ? ` · ${plasmid.features.length} features` : '');
    }

    function _renderPlasmidMeta() {
        if (!plasmid) { tdRenderMethods('plasmidRunMeta', [], null); return; }
        const feats = (plasmid.features || []).length;
        const enzymes = Array.from(selected || []);
        let m = `The ${(plasmid.length || 0).toLocaleString()}-bp ${plasmid.topology || ''} construct`
            + `${plasmid.name ? ' (' + esc(plasmid.name) + ')' : ''} was annotated and analyzed in silico`
            + `${feats ? ` (${feats} feature${feats === 1 ? '' : 's'})` : ''}. `
            + `Restriction mapping was performed across the REBASE enzyme set`;
        m += enzymes.length
            ? `; a digest with ${enzymes.slice(0, 6).join(', ')}${enzymes.length > 6 ? ', …' : ''} was simulated.`
            : `. Cloning (Gibson / Golden Gate / restriction) can be simulated from the design tab.`;
        m += ` In-silico predictions — verify junctions and digests before committing reagents.`;
        tdRenderMethods('plasmidRunMeta', [
            ['Length', (plasmid.length || 0).toLocaleString() + ' bp'],
            ['Topology', plasmid.topology || ''],
            ['GC', plasmid.gc != null ? plasmid.gc + '%' : ''],
            ['Features', feats || ''],
        ], m);
    }

    function showResults() {
        resCard.hidden = false;
        const wb = $('workbenchHome'); if (wb) wb.hidden = true;   // hub home → construct loaded
        nameEl.value = plasmid.name || 'plasmid';
        setMeta();
        _renderPlasmidMeta();
        sel = null; findHits = []; findIdx = -1; findLen = 0;
        const out = $('plasmidSeqOutput'); if (out) { out.hidden = true; out.innerHTML = ''; }
        const fc = $('plasmidFindCount'); if (fc) fc.textContent = '';
        viewMode = 'circular';
        ['pvCircular', 'pvLinear', 'pvSequence'].forEach((id) => { const b = $(id); if (b) b.classList.toggle('pv-tab-active', id === 'pvCircular'); });
        const tools = $('plasmidSeqTools'); if (tools) tools.hidden = true;
        renderMap(); renderFeatures();
        gelEl.hidden = true; gelEl.innerHTML = '';
        selected.clear();
        enzGrid.innerHTML = '<span class="field-hint">Scanning restriction sites…</span>';
        loadRestriction();
        resCard.scrollIntoView({ behavior: 'smooth', block: 'start' });
    }

    async function loadRestriction() {
        try {
            const res = await fetch('/api/plasmid/restriction', {
                method: 'POST', headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ sequence: plasmid.sequence, topology: plasmid.topology }),
            });
            const data = await res.json();
            if (res.status === 403 && signin403(data)) { window.dispatchEvent(new Event('td:signin-required')); return; }
            if (!res.ok) { enzGrid.innerHTML = '<span class="field-hint">Couldn’t scan enzymes.</span>'; return; }
            restriction = data.analysis;
            renderEnzymes();
        } catch (e) { enzGrid.innerHTML = '<span class="field-hint">Couldn’t reach the enzyme scanner.</span>'; }
    }

    async function doImport(text) {
        clearErr();
        if (!text || !text.trim()) { showErr('Paste a sequence, GenBank, or FASTA record.'); return; }
        const topo = (document.querySelector('input[name="plasmidTopo"]:checked') || {}).value || 'circular';
        const orig = importBtn.textContent; importBtn.disabled = true; importBtn.textContent = 'Importing…';
        try {
            const res = await fetch('/api/plasmid/import', {
                method: 'POST', headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ text, topology: topo, annotate: true }),
            });
            const data = await res.json();
            if (res.status === 403 && signin403(data)) {
                window.dispatchEvent(new Event('td:signin-required'));
                showErr('The Plasmid Editor is free with an account — sign in to import.'); return;
            }
            if (!res.ok) { showErr(data.error || 'Import failed.'); return; }
            plasmid = data.plasmid;
            showResults();
        } catch (e) { showErr('Could not reach the importer. Check your connection and retry.'); }
        finally { importBtn.disabled = false; importBtn.textContent = orig; }
    }

    // Import a binary sequence file (e.g. SnapGene .dna) — base64 payload, parsed
    // server-side. On success the parsed sequence is also dropped into the box so
    // it's visible + editable like every other import.
    async function doImportBinary(b64, filename) {
        clearErr();
        const orig = importBtn.textContent; importBtn.disabled = true; importBtn.textContent = 'Importing…';
        try {
            const res = await fetch('/api/plasmid/import', {
                method: 'POST', headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ b64, filename, annotate: true }),
            });
            const data = await res.json();
            if (res.status === 403 && signin403(data)) {
                window.dispatchEvent(new Event('td:signin-required'));
                showErr('The Plasmid Editor is free with an account — sign in to import.'); return;
            }
            if (!res.ok) { showErr(data.error || 'Import failed.'); return; }
            plasmid = data.plasmid;
            if (inputEl) inputEl.value = plasmid.sequence || '';
            showResults();
        } catch (e) { showErr('Could not reach the importer. Check your connection and retry.'); }
        finally { importBtn.disabled = false; importBtn.textContent = orig; }
    }

    async function doDigest() {
        if (!plasmid) return;
        const enzymes = [...selected];
        if (!enzymes.length) { gelEl.hidden = false; gelEl.innerHTML = '<div class="field-hint">Select one or more enzymes above, then digest.</div>'; return; }
        gelEl.hidden = false; gelEl.innerHTML = '<div class="field-hint">Digesting…</div>';
        try {
            const res = await fetch('/api/plasmid/digest', {
                method: 'POST', headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ sequence: plasmid.sequence, topology: plasmid.topology, enzymes }),
            });
            const data = await res.json();
            if (res.status === 403 && signin403(data)) { window.dispatchEvent(new Event('td:signin-required')); return; }
            if (!res.ok) { gelEl.innerHTML = `<div class="field-hint">${esc(data.error || 'Digest failed.')}</div>`; return; }
            renderGel(data.digest, enzymes);
        } catch (e) { gelEl.innerHTML = '<div class="field-hint">Couldn’t reach the digest engine.</div>'; }
    }

    function renderGel(dg, enzymes) {
        const frags = dg.fragments || [];
        const ladder = [10000, 8000, 6000, 5000, 4000, 3000, 2000, 1500, 1000, 750, 500, 250, 100];
        const H = 320, top = 24, bot = 300;
        const maxbp = Math.max(ladder[0], frags[0] || 1, plasmid.length);
        const minbp = 80;
        const yOf = (bp) => {
            const b = Math.min(Math.max(bp, minbp), maxbp);
            const f = (Math.log10(maxbp) - Math.log10(b)) / (Math.log10(maxbp) - Math.log10(minbp));
            return top + f * (bot - top);
        };
        const lane = (x, w, bands, cls) => bands.map((bp) =>
            `<rect x="${x}" y="${(yOf(bp) - 1.5).toFixed(1)}" width="${w}" height="3" class="${cls}"/>`
            + `<text x="${x + w + 5}" y="${(yOf(bp) + 3).toFixed(1)}" class="gel-bp">${bp.toLocaleString()}</text>`).join('');
        let svg = `<svg viewBox="0 0 360 ${H}" class="gel-svg" role="img" aria-label="Virtual gel">`;
        svg += `<rect x="0" y="0" width="360" height="${H}" class="gel-bg"/>`;
        svg += `<text x="55" y="16" class="gel-lane-lbl" text-anchor="middle">ladder</text>`;
        svg += `<text x="220" y="16" class="gel-lane-lbl" text-anchor="middle">digest</text>`;
        svg += lane(30, 50, ladder, 'gel-band-ladder');
        svg += frags.map((bp) => `<rect x="180" y="${(yOf(bp) - 2).toFixed(1)}" width="80" height="4" class="gel-band"/>`
            + `<text x="265" y="${(yOf(bp) + 3).toFixed(1)}" class="gel-bp gel-bp-frag">${bp.toLocaleString()} bp</text>`).join('');
        svg += `</svg>`;
        gelEl.innerHTML =
            `<h4 class="gel-title">Digest · ${esc(enzymes.join(' + '))} → ${frags.length} fragment${frags.length === 1 ? '' : 's'}</h4>`
            + `<div class="gel-flex"><div class="gel-graphic">${svg}</div>`
            + `<div class="gel-list">${frags.map((b, i) => `<span class="gel-frag-chip">${b.toLocaleString()} bp</span>`).join('')}</div></div>`;
    }

    async function doExport(format) {
        if (!plasmid) return;
        try {
            const res = await fetch('/api/plasmid/export', {
                method: 'POST', headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ sequence: plasmid.sequence, topology: plasmid.topology,
                    name: nameEl.value || plasmid.name, features: plasmid.features, format }),
            });
            if (res.status === 403) { window.dispatchEvent(new Event('td:signin-required')); return; }
            if (!res.ok) { showErr('Export failed.'); return; }
            const blob = await res.blob();
            const url = URL.createObjectURL(blob);
            const a = document.createElement('a');
            const stem = (nameEl.value || plasmid.name || 'plasmid').replace(/[^A-Za-z0-9_.-]/g, '_');
            a.href = url; a.download = `${stem}.${format === 'fasta' ? 'fasta' : 'gb'}`;
            document.body.appendChild(a); a.click(); a.remove();
            setTimeout(() => URL.revokeObjectURL(url), 1000);
        } catch (e) { showErr('Could not reach the exporter.'); }
    }

    async function doSave() {
        if (!plasmid) return;
        const btn = $('plasmidSave'); const orig = btn.textContent; btn.disabled = true; btn.textContent = 'Saving…';
        try {
            const res = await fetch('/api/plasmid/save', {
                method: 'POST', headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ name: nameEl.value || plasmid.name, topology: plasmid.topology,
                    length: plasmid.length, gc: plasmid.gc, source: plasmid.source,
                    sequence: plasmid.sequence, features: plasmid.features }),
            });
            const data = await res.json();
            if (res.status === 403 && signin403(data)) { window.dispatchEvent(new Event('td:signin-required')); return; }
            btn.textContent = data.ok ? 'Saved ✓' : 'Save failed';
            if (!data.ok && data.error) showErr(data.error);
            setTimeout(() => { btn.textContent = orig; }, 2500);
        } catch (e) { btn.textContent = orig; showErr('Could not reach the server.'); }
        finally { btn.disabled = false; }
    }

    async function openLibrary() {
        if (!libModal) return;
        libModal.hidden = false; document.body.style.overflow = 'hidden';
        libList.innerHTML = '<div class="field-hint">Loading…</div>';
        try {
            const res = await fetch('/api/plasmid/library');
            const data = await res.json();
            if (res.status === 403 && signin403(data)) { closeLibrary(); window.dispatchEvent(new Event('td:signin-required')); return; }
            const items = (data.plasmids || []);
            if (!items.length) { libList.innerHTML = '<div class="field-hint">No saved plasmids yet. Import one and hit Save.</div>'; return; }
            libList.innerHTML = items.map((p) => `
                <div class="plasmid-lib-item" data-id="${esc(p.id)}">
                  <div class="lib-main"><strong>${esc(p.name)}</strong>
                    <span class="lib-meta">${(p.length || 0).toLocaleString()} bp · ${esc(p.topology)}${p.gc != null ? ' · GC ' + p.gc + '%' : ''}</span></div>
                  <div class="lib-actions">
                    <button type="button" class="ghost lib-open" data-id="${esc(p.id)}">Open</button>
                    <button type="button" class="lib-del" data-id="${esc(p.id)}" aria-label="Delete">×</button>
                  </div>
                </div>`).join('');
        } catch (e) { libList.innerHTML = '<div class="field-hint">Couldn’t load your library.</div>'; }
    }
    function closeLibrary() { if (libModal) { libModal.hidden = true; document.body.style.overflow = ''; } }

    async function openSaved(id) {
        try {
            const res = await fetch('/api/plasmid/library/' + encodeURIComponent(id));
            const data = await res.json();
            if (!res.ok || !data.ok) { showErr('Couldn’t open that plasmid.'); return; }
            const p = data.plasmid;
            plasmid = { name: p.name, sequence: p.sequence, length: p.length || (p.sequence || '').length,
                        topology: p.topology, gc: p.gc, features: p.features || [], source: p.source };
            closeLibrary();
            if (location.hash !== '#plasmid') location.hash = '#plasmid';
            showResults();
        } catch (e) { showErr('Couldn’t open that plasmid.'); }
    }
    async function deleteSaved(id, el) {
        try {
            const res = await fetch('/api/plasmid/library/' + encodeURIComponent(id), { method: 'DELETE' });
            const data = await res.json();
            if (data.ok && el) el.remove();
        } catch (e) { /* ignore */ }
    }

    // ---- wiring ----
    importBtn.addEventListener('click', () => doImport(inputEl.value));
    if (fileEl) fileEl.addEventListener('change', (e) => {
        const f = e.target.files && e.target.files[0]; if (!f) return;
        const name = (f.name || '').toLowerCase();
        // SnapGene .dna (and kin) are BINARY — read as bytes, base64, and let the
        // server parse them. Text formats (GenBank/FASTA/raw) load into the box.
        const isBinary = /\.(dna|snapgene|xdna)$/.test(name);
        const r = new FileReader();
        if (isBinary) {
            r.onload = () => {
                try {
                    const bytes = new Uint8Array(r.result);
                    let bin = '';
                    const CH = 0x8000;  // chunk to avoid arg-count limits on big files
                    for (let i = 0; i < bytes.length; i += CH) {
                        bin += String.fromCharCode.apply(null, bytes.subarray(i, i + CH));
                    }
                    doImportBinary(btoa(bin), f.name);
                } catch (err) { showErr('Could not read that file.'); }
            };
            r.onerror = () => showErr('Could not read that file.');
            r.readAsArrayBuffer(f);
        } else {
            r.onload = () => { inputEl.value = String(r.result || ''); doImport(inputEl.value); };
            r.onerror = () => showErr('Could not read that file.');
            r.readAsText(f);
        }
        // Reset so re-selecting the SAME file fires "change" again.
        e.target.value = '';
    });
    $('plasmidExample').addEventListener('click', () => {
        // Demo construct: recognizable motifs (T7/M13/lac → auto-annotated) +
        // the AmpR ORF + cloning sites placed so there are real single- AND
        // double-cutters for a multi-band virtual gel.
        const ampR =
            'ATGAGTATTCAACATTTCCGTGTCGCCCTTATTCCCTTTTTTGCGGCATTTTGCCTTCCTGTTTTTGCTCACCCAGAAACGCTGGTGAAAGTAAAAGATGCTGAAGATCAGTTGGGTGCACGAGTGGGTTACATCGAACTGGATCTCAACAGCGGTAAGATCCTTGAGAGTTTTCGCCCCGAAGAACGTTTTCCAATGATGAGCACTTTTAAAGTTCTGCTATGTGGCGCGGTATTATCCCGTATTGACGCCGGGCAAGAGCAACTCGGTCGCCGCATACACTATTCTCAGAATGACTTGGTTGAGTACTCACCAGTCACAGAAAAGCATCTTACGGATGGCATGACAGTAAGAGAATTATGCAGTGCTGCCATAACCATGAGTGATAACACTGCGGCCAACTTACTTCTGACAACGATCGGAGGACCGAAGGAGCTAACCGCTTTTTTGCACAACATGGGGGATCATGTAACTCGCCTTGATCGTTGGGAACCGGAGCTGAATGAAGCCATACCAAACGACGAGCGTGACACCACGATGCCTGTAGCAATGGCAACAACGTTGCGCAAACTATTAACTGGCGAACTACTTACTCTAGCTTCCCGGCAACAATTAATAGACTGGATGGAGGCGGATAAAGTTGCAGGACCACTTCTGCGCTCGGCCCTTCCGGCTGGCTGGTTTATTGCTGATAAATCTGGAGCCGGTGAGCGTGGGTCTCGCGGTATCATTGCAGCACTGGGGCCAGATGGTAAGCCCTCCCGTATCGTAGTTATCTACACGACGGGGAGTCAGGCAACTATGGATGAACGAAATAGACAGATCGCTGAGATAGGTGCCTCACTGATTAAGCATTGGTAA';
        inputEl.value =
            'GAATTC' +                                   // EcoRI #1
            'TAATACGACTCACTATAG' +                        // T7 promoter
            'GTAAAACGACGGCCAGT' +                         // M13 fwd
            'GGATCC' +                                    // BamHI
            'TGGAATTGTGAGCGGATAACAATT' +                  // lac operator
            ampR +
            'AAGCTT' +                                    // HindIII
            'CAGGAAACAGCTATGAC' +                         // M13 rev
            'CTGCAGTCTAGACTCGAG' +                        // PstI / XbaI / XhoI MCS-ish
            'GAATTC' +                                    // EcoRI #2  → EcoRI double-cutter
            // filler past the 2nd EcoRI so the two digest fragments are well
            // separated on the gel (≈970 bp + ≈220 bp) rather than 973 + 6.
            'TGCAACGTTAGCCATGACTGGACTAGGCATTACGGTACCTAAGCGATCCATGGTCAACGTTGACTACGATCGGATCCTAAGCTTACGGATCCAATTGCGTACGATCGTTAGCCATGGACTAGCATTGGCAACGTTACGGATCAGCTAGCTAGCATCGATCGTACGATCAGCTAGCATCGTAGCATCGATCGATCAGCTAGCATCGATCGTAGCTAGCATCGT';
        document.querySelector('input[name="plasmidTopo"][value="circular"]').checked = true;
        doImport(inputEl.value);
    });
    nameEl.addEventListener('input', () => { if (plasmid) plasmid.name = nameEl.value; });
    function setView(mode) {
        viewMode = mode;
        [['circular', 'pvCircular'], ['linear', 'pvLinear'], ['sequence', 'pvSequence']].forEach(([m, id]) => {
            const b = $(id); if (b) b.classList.toggle('pv-tab-active', m === mode);
        });
        renderMap();
    }
    $('pvCircular').addEventListener('click', () => setView('circular'));
    $('pvLinear').addEventListener('click', () => setView('linear'));
    $('pvSequence').addEventListener('click', () => setView('sequence'));
    enzGrid.addEventListener('click', (e) => {
        const b = e.target.closest('.plasmid-enz'); if (!b) return;
        const name = b.getAttribute('data-enz');
        if (selected.has(name)) selected.delete(name); else selected.add(name);
        b.classList.toggle('enz-on');
        renderMap();
    });
    $('plasmidDigestBtn').addEventListener('click', doDigest);
    $('plasmidClearEnz').addEventListener('click', () => { selected.clear(); renderEnzymes(); renderMap(); gelEl.hidden = true; gelEl.innerHTML = ''; });
    $('plasmidSave').addEventListener('click', doSave);
    // "My plasmids" now opens the unified saved-work hub (falls back to the
    // legacy per-tool modal if the hub isn't registered yet).
    $('plasmidLibraryBtn').addEventListener('click', () => {
        if (window.TDSaved && window.TDSaved.open) window.TDSaved.open(); else openLibrary();
    });
    // Expose plasmid reopen to the unified hub.
    window.TDSaved = window.TDSaved || {};
    window.TDSaved.plasmid = openSaved;
    if (libModal) {
        libModal.querySelectorAll('[data-plasmid-lib-close]').forEach((el) => el.addEventListener('click', closeLibrary));
        libList.addEventListener('click', (e) => {
            const o = e.target.closest('.lib-open'), d = e.target.closest('.lib-del');
            if (o) openSaved(o.getAttribute('data-id'));
            else if (d) deleteSaved(d.getAttribute('data-id'), d.closest('.plasmid-lib-item'));
        });
        document.addEventListener('keydown', (e) => { if (e.key === 'Escape' && !libModal.hidden) closeLibrary(); });
    }
    // Export menu (GenBank / FASTA)
    const exportBtn = $('plasmidExportGb');
    if (exportBtn) {
        const menu = document.createElement('div');
        menu.className = 'plasmid-export-menu'; menu.hidden = true;
        menu.innerHTML = '<button type="button" data-fmt="genbank">GenBank (.gb)</button><button type="button" data-fmt="fasta">FASTA (.fasta)</button>';
        exportBtn.parentNode.appendChild(menu);
        // Toggle THIS menu, closing any other toolbar dropdown first (otherwise
        // opening the second one leaves the first stuck open + overlapping —
        // each button's stopPropagation blocked the other's outside-click close).
        exportBtn.addEventListener('click', (e) => {
            e.stopPropagation();
            const open = menu.hidden;
            document.querySelectorAll('.plasmid-export-menu').forEach((m) => { m.hidden = true; });
            menu.hidden = !open;
        });
        menu.addEventListener('click', (e) => { const b = e.target.closest('[data-fmt]'); if (b) { menu.hidden = true; doExport(b.getAttribute('data-fmt')); } });
        document.addEventListener('click', () => { document.querySelectorAll('.plasmid-export-menu').forEach((m) => { m.hidden = true; }); });
    }

    // ───────────────────────── M3: sequence editor ─────────────────────────
    const GCODE = (() => {
        const b = 'TCAG', aa = 'FFLLSSSSYY**CC*WLLLLPPPPHHQQRRRRIIIMTTTTNNKKSSRRVVVVAAAADDEEGGGG';
        const m = {}; let k = 0;
        for (const a of b) for (const c of b) for (const d of b) m[a + c + d] = aa[k++];
        return m;
    })();
    const SEQ_RENDER_CAP = 60000;     // bp — bigger than this, show a notice not a wall
    const SEQ_LINE = 60;
    const EDIT_CAP = 20000;           // bp — full inline per-base editing below this
    let sel = null;                   // {from, to} 1-based inclusive
    let findHits = [], findIdx = -1, findLen = 0;
    // Inline-editor state (Benchling-style click-and-type).
    let caret = null;                 // cursor index 0..len (before base `caret`), or null
    let selAnchor = null;             // anchor for keyboard/drag selection extension
    let dragging = false, dragAnchor = 0;
    let seqSpans = null;              // editable render: NodeList of per-base <span>, indexed by position
    let seqcSpans = null;             // complement-strand spans, indexed by position
    let curSel = null;                // [a,b) 0-based currently painted on spans
    let _rescanT = null;              // debounce timer for restriction rescan during typing

    const rcStr = (s) => s.toUpperCase().replace(/[^ACGTN]/g, '')
        .split('').reverse().map((c) => ({ A: 'T', T: 'A', G: 'C', C: 'G', N: 'N' }[c] || 'N')).join('');
    const gcOf = (s) => { const u = s.toUpperCase(); const n = (u.match(/[ACGT]/g) || []).length;
        return n ? Math.round(1000 * (u.match(/[GC]/g) || []).length / n) / 10 : 0; };
    function translate(dna) {
        const s = dna.toUpperCase(); let out = '';
        for (let i = 0; i + 3 <= s.length; i += 3) out += (GCODE[s.substr(i, 3)] || 'X');
        return out;
    }
    function copyText(t, label) {
        const done = () => showSeqOut(`Copied ${label} (${t.length} bp) to clipboard.`);
        if (navigator.clipboard && navigator.clipboard.writeText) navigator.clipboard.writeText(t).then(done, () => showSeqOut('Copy blocked by the browser.'));
        else showSeqOut('Clipboard not available here.');
    }
    function showSeqOut(html) { const o = $('plasmidSeqOutput'); if (o) { o.hidden = false; o.innerHTML = html; } }

    function _featColorAt(i, feats) { for (const f of feats) if (i >= f.start && i < f.end) return f.color || '#9AA0AA'; return ''; }
    function _inFind(i) { for (const h of findHits) if (i >= h && i < h + findLen) return true; return false; }

    function renderSequence() {
        const seq = plasmid.sequence, len = seq.length, feats = plasmid.features || [];
        syncSelInputs();
        seqSpans = null; seqcSpans = null;
        if (len > SEQ_RENDER_CAP) {
            mapWrap.innerHTML = `<div class="seqed-toobig">This sequence is ${len.toLocaleString()} bp — too long to render in the browser. `
                + `Use Find or the From/To fields to work on a region; export to view the full sequence.</div>`;
            return;
        }
        // Split workspace: sequence on the left, a companion circular map on the
        // right that mirrors the current selection as a highlighted arc.
        mapWrap.innerHTML = '<div class="seqmap">'
            + '<div class="seqmap-seq" id="seqHost"></div>'
            + '<aside class="seqmap-aside"><div class="seqmap-aside-label">Map · selection mirrored</div>'
            + '<div id="seqMini" class="seqmap-mini"></div></aside>'
            + '</div>';
        if (len > EDIT_CAP) renderSeqReadonly(seq, len, feats);
        else renderSeqEditable(seq, len, feats);
        renderCompanionMap();
    }

    // First feature covering each base wins; one pass for the whole sequence.
    function _colorArray(len, feats) {
        const arr = new Array(len).fill('');
        for (const f of feats) {
            const c = /^#[0-9A-Fa-f]{3,8}$/.test(f.color || '') ? f.color : '#9AA0AA';
            const a = Math.max(0, f.start | 0), b = Math.min(len, f.end | 0);
            for (let i = a; i < b; i++) if (!arr[i]) arr[i] = c;
        }
        return arr;
    }

    // Editable per-base render. Top strand (5'→3') is click/type-editable; the
    // complement (3'→5') is shown beneath each line, Benchling-style. Selection
    // highlights both strands.
    const _COMP = { A: 'T', T: 'A', G: 'C', C: 'G', N: 'N' };
    function renderSeqEditable(seq, len, feats) {
        const host = document.getElementById('seqHost') || mapWrap;
        const colors = _colorArray(len, feats);
        const sF = sel ? sel.from - 1 : -1, sT = sel ? sel.to : -1;
        const parts = ['<div class="seqed seqed-edit" tabindex="0" role="textbox" aria-multiline="true" '
            + 'aria-label="DNA sequence — click to place the cursor, type A/C/G/T to edit, drag to select" spellcheck="false">'];
        for (let ls = 0; ls < len; ls += SEQ_LINE) {
            const le = Math.min(ls + SEQ_LINE, len);
            // top strand (editable)
            parts.push(`<div class="seqed-line"><span class="seqed-pos">${(ls + 1).toLocaleString()}</span><span class="seqed-bases">`);
            for (let i = ls; i < le; i++) {
                const c = colors[i];
                const cls = 'seqb' + (c ? ' seqb-feat' : '') + ((i >= sF && i < sT) ? ' seqb-sel' : '') + (_inFind(i) ? ' seqb-find' : '');
                parts.push(`<span class="${cls}" data-i="${i}"${c ? ` style="--featc:${c}"` : ''}>${seq[i]}</span>`);
            }
            parts.push('</span></div>');
            // complement strand (display only, mirrors selection)
            parts.push('<div class="seqed-line seqed-line-comp"><span class="seqed-pos seqed-pos-comp"></span><span class="seqed-bases seqed-comp">');
            for (let i = ls; i < le; i++) {
                parts.push(`<span class="seqc${(i >= sF && i < sT) ? ' seqb-sel' : ''}" data-i="${i}">${_COMP[seq[i]] || 'N'}</span>`);
            }
            parts.push('</span></div>');
        }
        if (len === 0) parts.push('<div class="seqed-line"><span class="seqed-pos">1</span><span class="seqed-bases"></span></div>');
        parts.push('</div>');
        host.innerHTML = parts.join('');
        const container = host.querySelector('.seqed-edit');
        seqSpans = container ? container.querySelectorAll('.seqb') : null;
        seqcSpans = container ? container.querySelectorAll('.seqc') : null;
        curSel = sel ? [sel.from - 1, sel.to] : null;
        placeCaretEl();
        const anchorEl = mapWrap.querySelector('.seqed-caret') || mapWrap.querySelector('.seqb-sel');
        if (anchorEl) anchorEl.scrollIntoView({ block: 'nearest' });
    }

    // Legacy run-based read-only render — kept for sequences above EDIT_CAP.
    function renderSeqReadonly(seq, len, feats) {
        const sF = sel ? sel.from - 1 : -1, sT = sel ? sel.to : -1;
        const styleKey = (i) => `${_featColorAt(i, feats)}|${(i >= sF && i < sT) ? 'S' : ''}${_inFind(i) ? 'F' : ''}`;
        let html = `<div class="seqed seqed-readonly"><div class="seqed-ro-note">Read-only view (over ${EDIT_CAP.toLocaleString()} bp) — use Find or the From/To fields to edit a region.</div>`;
        for (let ls = 0; ls < len; ls += SEQ_LINE) {
            const le = Math.min(ls + SEQ_LINE, len);
            html += `<div class="seqed-line"><span class="seqed-pos">${(ls + 1).toLocaleString()}</span><span class="seqed-bases">`;
            let i = ls;
            while (i < le) {
                const key = styleKey(i); let j = i + 1;
                while (j < le && styleKey(j) === key) j++;
                const [color, flags] = key.split('|');
                const cls = 'seqed-run' + (flags.includes('S') ? ' seqed-sel' : '') + (flags.includes('F') ? ' seqed-find' : '');
                const safe = /^#[0-9A-Fa-f]{3,8}$/.test(color) ? color : '';
                const st = safe ? ` style="--featc:${safe}"` : '';
                html += `<span class="${cls}"${color ? ' data-feat="1"' : ''}${st}>${seq.slice(i, j)}</span>`;
                i = j;
            }
            html += '</span></div>';
        }
        html += '</div>';
        const host = document.getElementById('seqHost') || mapWrap;
        host.innerHTML = html;
        const selRun = host.querySelector('.seqed-sel');
        if (selRun && sel) selRun.scrollIntoView({ block: 'nearest' });
    }

    // ── caret + selection painting (editable mode, no full re-render) ──
    function placeCaretEl() {
        const old = mapWrap.querySelector('.seqed-caret'); if (old) old.remove();
        if (caret == null || !seqSpans) return;
        const car = document.createElement('i'); car.className = 'seqed-caret'; car.setAttribute('aria-hidden', 'true');
        if (caret >= seqSpans.length) {
            // append to the LAST top-strand bases row (not a complement row)
            const lines = mapWrap.querySelectorAll('.seqed-bases:not(.seqed-comp)');
            const last = lines[lines.length - 1]; if (last) last.appendChild(car);
        } else {
            const sp = seqSpans[caret]; sp.parentNode.insertBefore(car, sp);
        }
    }
    function paintSel(a, b) {
        if (!seqSpans) return;
        const clr = (i) => { if (seqSpans[i]) seqSpans[i].classList.remove('seqb-sel'); if (seqcSpans && seqcSpans[i]) seqcSpans[i].classList.remove('seqb-sel'); };
        const set = (i) => { if (seqSpans[i]) seqSpans[i].classList.add('seqb-sel'); if (seqcSpans && seqcSpans[i]) seqcSpans[i].classList.add('seqb-sel'); };
        if (curSel) for (let i = curSel[0]; i < curSel[1] && i < seqSpans.length; i++) clr(i);
        if (a != null && b > a) { for (let i = a; i < b && i < seqSpans.length; i++) set(i); curSel = [a, b]; }
        else curSel = null;
        updateSelArc();   // mirror onto the companion circular map
    }
    function idxFromEvent(e) {
        const sp = e.target.closest && e.target.closest('.seqb, .seqc');
        if (sp) { let i = +sp.getAttribute('data-i'); const r = sp.getBoundingClientRect(); if (e.clientX > r.left + r.width / 2) i += 1; return i; }
        const bl = e.target.closest && e.target.closest('.seqed-bases');
        if (bl) { const ss = bl.querySelectorAll('.seqb, .seqc'); if (ss.length) return (+ss[ss.length - 1].getAttribute('data-i')) + 1; }
        return null;
    }
    function focusEditor() { const c = mapWrap.querySelector('.seqed-edit'); if (c) c.focus({ preventScroll: true }); }
    function caretVisible() { const cr = mapWrap.querySelector('.seqed-caret'); if (cr) cr.scrollIntoView({ block: 'nearest' }); }
    function isEditable() { return viewMode === 'sequence' && plasmid && plasmid.length <= EDIT_CAP; }

    function syncSelInputs() {
        const f = $('plasmidSelFrom'), t = $('plasmidSelTo'), l = $('plasmidSelLen');
        if (sel) { if (f) f.value = sel.from; if (t) t.value = sel.to; if (l) l.textContent = `${(sel.to - sel.from + 1).toLocaleString()} bp selected`; }
        else if (l) l.textContent = '';
    }
    function setSel(from, to) {
        if (!plasmid) return;
        const len = plasmid.length;
        from = Math.max(1, Math.min(len, from | 0)); to = Math.max(1, Math.min(len, to | 0));
        if (to < from) [from, to] = [to, from];
        sel = { from, to };
        if (viewMode === 'sequence') renderSequence(); else setView('sequence');
    }
    function selSeq() { return sel ? plasmid.sequence.slice(sel.from - 1, sel.to) : ''; }

    function runFind() {
        const raw = ($('plasmidFind').value || '').toUpperCase().replace(/[^ACGTN]/g, '');
        findHits = []; findIdx = -1; findLen = raw.length;
        if (raw.length >= 3 && plasmid) {
            const seq = plasmid.sequence;
            const add = (needle) => { let p = seq.indexOf(needle); while (p !== -1) { findHits.push(p); p = seq.indexOf(needle, p + 1); } };
            add(raw); const rc = rcStr(raw); if (rc !== raw) add(rc);
            findHits = [...new Set(findHits)].sort((a, b) => a - b);
        }
        const c = $('plasmidFindCount');
        if (c) c.textContent = findLen < 3 ? '' : (findHits.length ? `${findHits.length} match${findHits.length === 1 ? '' : 'es'}` : 'no matches');
        if (findHits.length) gotoFind(0); else renderSequence();
    }
    function gotoFind(idx) {
        if (!findHits.length) return;
        findIdx = (idx + findHits.length) % findHits.length;
        const h = findHits[findIdx];
        setSel(h + 1, h + findLen);
        const c = $('plasmidFindCount'); if (c) c.textContent = `${findIdx + 1} of ${findHits.length}`;
    }

    // edits: rewrite the sequence + remap features + rescan restriction.
    function applyEdit(newSeq, remap, defer) {
        plasmid.sequence = newSeq.toUpperCase(); plasmid.length = newSeq.length;
        plasmid.features = (plasmid.features || []).map(remap).filter((f) => f && f.end > f.start);
        plasmid.gc = gcOf(newSeq); plasmid.source = plasmid.source || 'raw';
        sel = null; findHits = []; restriction = null; selected.clear();
        setMeta(); _renderPlasmidMeta(); nameEl.value = plasmid.name || nameEl.value;
        renderMap(); renderFeatures();
        gelEl.hidden = true; gelEl.innerHTML = '';
        if (defer) { scheduleRescan(); }
        else { enzGrid.innerHTML = '<span class="field-hint">Re-scanning restriction sites…</span>'; loadRestriction(); }
    }
    // During active typing we don't want a network restriction rescan on every
    // keystroke — debounce it until the user pauses.
    function scheduleRescan() {
        enzGrid.innerHTML = '<span class="field-hint">Editing… restriction sites update when you pause.</span>';
        clearTimeout(_rescanT);
        _rescanT = setTimeout(() => {
            enzGrid.innerHTML = '<span class="field-hint">Re-scanning restriction sites…</span>'; loadRestriction();
        }, 500);
    }
    // Single-applyEdit splice (inline editor): remove [a,b), insert `ins`, remap features.
    function replaceRange(a, b, ins, defer) {
        const seq = plasmid.sequence, shift = ins.length - (b - a);
        const map = (x) => (x <= a ? x : (x >= b ? x + shift : a + Math.min(Math.max(0, x - a), ins.length)));
        applyEdit(seq.slice(0, a) + ins + seq.slice(b), (f) => ({ ...f, start: map(f.start), end: map(f.end) }), defer);
    }
    function deleteRange(a, b) {   // 0-based [a, b)
        const seq = plasmid.sequence; const cut = b - a;
        const map = (x) => (x <= a ? x : (x >= b ? x - cut : a));
        applyEdit(seq.slice(0, a) + seq.slice(b), (f) => ({ ...f, start: map(f.start), end: map(f.end) }));
    }
    function insertAt(p, ins) {    // 0-based position
        const seq = plasmid.sequence; const L = ins.length;
        applyEdit(seq.slice(0, p) + ins + seq.slice(p),
            (f) => ({ ...f, start: f.start < p ? f.start : f.start + L, end: f.end <= p ? f.end : f.end + L }));
    }
    function revcompAll() {
        const seq = plasmid.sequence, len = seq.length;
        applyEdit(rcStr(seq), (f) => ({ ...f, start: len - f.end, end: len - f.start, strand: -(f.strand || 1) }));
    }

    // wiring — Find
    const findEl = $('plasmidFind');
    if (findEl) {
        findEl.addEventListener('input', () => { clearTimeout(findEl._t); findEl._t = setTimeout(runFind, 200); });
        findEl.addEventListener('keydown', (e) => { if (e.key === 'Enter') { e.preventDefault(); gotoFind(findIdx + 1); } });
    }
    if ($('plasmidFindNext')) $('plasmidFindNext').addEventListener('click', () => gotoFind(findIdx + 1));
    if ($('plasmidFindPrev')) $('plasmidFindPrev').addEventListener('click', () => gotoFind(findIdx - 1));
    // selection inputs
    const onSelInput = () => { const f = parseInt($('plasmidSelFrom').value, 10), t = parseInt($('plasmidSelTo').value, 10);
        if (f && t) setSel(f, t); };
    if ($('plasmidSelFrom')) $('plasmidSelFrom').addEventListener('change', onSelInput);
    if ($('plasmidSelTo')) $('plasmidSelTo').addEventListener('change', onSelInput);

    // ── Inline editing: mouse caret/selection + keyboard typing (Benchling-style) ──
    function _editInsert(ins) {
        const len = plasmid.length;
        if (sel) { const a = sel.from - 1, b = sel.to; caret = a + ins.length; replaceRange(a, b, ins, true); }
        else { const p = caret == null ? len : caret; caret = p + ins.length; replaceRange(p, p, ins, true); }
        sel = null; selAnchor = null; caretVisible(); focusEditor();
    }
    mapWrap.addEventListener('mousedown', (e) => {
        if (!isEditable()) return;
        const i = idxFromEvent(e); if (i == null) return;
        e.preventDefault();
        dragging = true; dragAnchor = i; selAnchor = i;
        paintSel(null); sel = null; syncSelInputs();
        caret = i; placeCaretEl(); focusEditor();
    });
    mapWrap.addEventListener('mousemove', (e) => {
        if (!dragging || !isEditable()) return;
        const i = idxFromEvent(e); if (i == null) return;
        const a = Math.min(dragAnchor, i), b = Math.max(dragAnchor, i);
        if (b > a) { caret = null; const c = mapWrap.querySelector('.seqed-caret'); if (c) c.remove(); paintSel(a, b); }
        else { paintSel(null); caret = i; placeCaretEl(); }
    });
    window.addEventListener('mouseup', () => {
        if (!dragging) return; dragging = false;
        sel = curSel ? { from: curSel[0] + 1, to: curSel[1] } : null;
        syncSelInputs();
    });
    mapWrap.addEventListener('paste', (e) => {
        if (!isEditable() || !(e.target.closest && e.target.closest('.seqed-edit'))) return;
        e.preventDefault();
        const txt = ((e.clipboardData || window.clipboardData).getData('text') || '').toUpperCase().replace(/[^ACGTN]/g, '');
        if (txt) _editInsert(txt);
    });
    mapWrap.addEventListener('keydown', (e) => {
        if (!isEditable() || !(e.target.closest && e.target.closest('.seqed-edit'))) return;
        const len = plasmid.length, k = e.key;
        if (/^[acgtnACGTN]$/.test(k) && !e.metaKey && !e.ctrlKey) { e.preventDefault(); _editInsert(k.toUpperCase()); return; }
        if (k === 'Backspace') {
            e.preventDefault();
            if (sel) { const a = sel.from - 1, b = sel.to; caret = a; replaceRange(a, b, '', true); }
            else if (caret > 0) { const c0 = caret; caret = c0 - 1; replaceRange(c0 - 1, c0, '', true); }
            sel = null; selAnchor = null; caretVisible(); focusEditor(); return;
        }
        if (k === 'Delete') {
            e.preventDefault();
            if (sel) { const a = sel.from - 1, b = sel.to; caret = a; replaceRange(a, b, '', true); }
            else if (caret != null && caret < len) { replaceRange(caret, caret + 1, '', true); }
            sel = null; selAnchor = null; caretVisible(); focusEditor(); return;
        }
        if (k === 'ArrowLeft' || k === 'ArrowRight' || k === 'ArrowUp' || k === 'ArrowDown' || k === 'Home' || k === 'End') {
            e.preventDefault();
            let c = caret == null ? (sel ? sel.from - 1 : 0) : caret;
            if (k === 'ArrowLeft') c = Math.max(0, c - 1);
            else if (k === 'ArrowRight') c = Math.min(len, c + 1);
            else if (k === 'ArrowUp') c = Math.max(0, c - SEQ_LINE);
            else if (k === 'ArrowDown') c = Math.min(len, c + SEQ_LINE);
            else if (k === 'Home') c = c - (c % SEQ_LINE);
            else if (k === 'End') c = Math.min(len, c - (c % SEQ_LINE) + SEQ_LINE);
            if (e.shiftKey) {
                if (selAnchor == null) selAnchor = caret == null ? c : caret;
                const a = Math.min(selAnchor, c), b = Math.max(selAnchor, c);
                caret = c; paintSel(a, b); placeCaretEl();
                sel = (b > a) ? { from: a + 1, to: b } : null; syncSelInputs();
            } else { selAnchor = null; paintSel(null); sel = null; syncSelInputs(); caret = c; placeCaretEl(); }
            caretVisible(); return;
        }
        if ((e.metaKey || e.ctrlKey) && k.toLowerCase() === 'a') { e.preventDefault(); if (len) { sel = { from: 1, to: len }; caret = len; selAnchor = 0; renderSequence(); } return; }
        if ((e.metaKey || e.ctrlKey) && k.toLowerCase() === 'c') { if (sel) { e.preventDefault(); copyText(selSeq(), 'selection'); } return; }
        // swallow other single printable keys so they don't scroll / leak into the page
        if (k.length === 1 && !e.metaKey && !e.ctrlKey) e.preventDefault();
    });
    // click a feature → select it (and jump to sequence)
    featuresEl.addEventListener('click', (e) => {
        const item = e.target.closest('.plasmid-feat-item'); if (!item) return;
        const f = (plasmid.features || [])[parseInt(item.getAttribute('data-fidx'), 10)];
        if (f) setSel(f.start + 1, f.end);
    });
    // operations
    const needSel = () => { if (!sel) { showSeqOut('Select a region first (From/To, Find, or click a feature).'); return false; } return true; };
    if ($('seqCopy')) $('seqCopy').addEventListener('click', () => { if (needSel()) copyText(selSeq(), 'selection'); });
    if ($('seqCopyRC')) $('seqCopyRC').addEventListener('click', () => { if (needSel()) copyText(rcStr(selSeq()), 'reverse-complement'); });
    if ($('seqTranslate')) $('seqTranslate').addEventListener('click', () => {
        const dna = sel ? selSeq() : plasmid.sequence;
        const prot = translate(dna);
        showSeqOut(`<div class="seqout-h">Translation (${sel ? 'selection' : 'whole sequence'}, frame 1 · ${prot.length} aa)</div><code class="seqout-prot">${esc(prot)}</code>`);
    });
    if ($('seqAnnotate')) $('seqAnnotate').addEventListener('click', () => {
        if (!needSel()) return;
        const name = prompt('Feature name:', 'my feature'); if (!name) return;
        const type = (prompt('Type (CDS, promoter, terminator, primer_bind, misc_feature…):', 'misc_feature') || 'misc_feature').trim();
        const colors = { cds: '#C7A472', gene: '#C7A472', promoter: '#5FA98A', terminator: '#C77E7E',
            rep_origin: '#E4B45F', primer_bind: '#9AA0AA', tag: '#B07ED9' };
        (plasmid.features = plasmid.features || []).push({
            name: name.slice(0, 60), type: type.toLowerCase(), start: sel.from - 1, end: sel.to, strand: 1,
            color: colors[type.toLowerCase()] || '#9AA0AA', notes: 'user-added',
        });
        plasmid.features.sort((a, b) => a.start - b.start);
        setMeta(); renderMap(); renderFeatures();
        showSeqOut(`Added feature “${esc(name)}” at ${sel.from}–${sel.to}.`);
    });
    if ($('seqDelete')) $('seqDelete').addEventListener('click', () => {
        if (!needSel()) return;
        if (!confirm(`Delete ${sel.to - sel.from + 1} bp (${sel.from}–${sel.to})? Feature coordinates will shift.`)) return;
        deleteRange(sel.from - 1, sel.to);
        showSeqOut('Region deleted; map + restriction sites updated.');
    });
    if ($('seqInsert')) $('seqInsert').addEventListener('click', () => {
        const at = sel ? sel.from : 1;
        const raw = prompt(`Insert sequence BEFORE position ${at} (ACGT):`, ''); if (!raw) return;
        const ins = raw.toUpperCase().replace(/[^ACGTN]/g, '');
        if (!ins) { showSeqOut('No valid DNA to insert.'); return; }
        insertAt(at - 1, ins);
        showSeqOut(`Inserted ${ins.length} bp before position ${at}.`);
    });
    if ($('seqRevComp')) $('seqRevComp').addEventListener('click', () => {
        if (!confirm('Reverse-complement the entire plasmid? Features will be remapped.')) return;
        revcompAll();
        showSeqOut('Whole plasmid reverse-complemented.');
    });

    // ───────────────────────── M4: cloning / assembly ──────────────────────
    let cloneMethod = 'gibson';
    let lastAssembly = null;
    const cloneErr = (m) => { const e = $('cloneError'); if (e) { e.textContent = m; e.hidden = false; } };
    const cloneClearErr = () => { const e = $('cloneError'); if (e) e.hidden = true; };

    function parseFragments(text) {
        text = (text || '').replace(/\r/g, '');
        const frs = [];
        if (text.includes('>')) {
            let name = null, buf = [];
            text.split('\n').forEach((ln) => {
                if (ln.startsWith('>')) { if (name !== null) frs.push({ name, seq: buf.join('') }); name = ln.slice(1).trim() || `fragment ${frs.length + 1}`; buf = []; }
                else if (ln.trim()) buf.push(ln.trim());
            });
            if (name !== null) frs.push({ name, seq: buf.join('') });
        } else {
            text.split('\n').forEach((ln) => {
                ln = ln.trim(); if (!ln) return;
                const m = ln.match(/^([^:,\t]+)[:,\t]\s*([ACGTNacgtn\s]+)$/);
                if (m && !/^[ACGTNacgtn\s]+$/.test(m[1])) frs.push({ name: m[1].trim(), seq: m[2].replace(/\s/g, '') });
                else frs.push({ name: `fragment ${frs.length + 1}`, seq: ln.replace(/\s/g, '') });
            });
        }
        return frs.filter((f) => f.seq);
    }

    function setCloneMethod(m) {
        cloneMethod = m;
        document.querySelectorAll('.clone-method').forEach((b) => b.classList.toggle('clone-method-active', b.getAttribute('data-method') === m));
        $('clonePaneFragments').hidden = (m === 'restriction');
        $('clonePaneRestriction').hidden = (m !== 'restriction');
        $('cloneCircWrap').hidden = (m !== 'gibson');
        $('cloneGgEnzWrap').hidden = (m !== 'golden_gate');
        $('cloneFragHint').innerHTML = (m === 'golden_gate')
            ? 'Paste your <strong>parts</strong> (each flanked by inward-facing Type IIS sites). Matching 4-nt overhangs chain into a circle.'
            : 'Paste your fragments — FASTA, or one per line as <code>name: SEQUENCE</code>. Overlapping ends assemble scarlessly; bare junctions get homology arms designed into the primers.';
    }
    document.querySelectorAll('.clone-method').forEach((b) => b.addEventListener('click', () => setCloneMethod(b.getAttribute('data-method'))));

    if ($('cloneUseCurrent')) $('cloneUseCurrent').addEventListener('click', () => {
        if (!plasmid) { cloneErr('Import a plasmid first to use it as a fragment.'); return; }
        const ta = $('cloneFragments');
        ta.value = (ta.value.trim() ? ta.value.trim() + '\n' : '') + `>${(plasmid.name || 'plasmid')}\n${plasmid.sequence}`;
        cloneClearErr();
    });

    async function runClone() {
        cloneClearErr(); lastAssembly = null;
        const body = { method: cloneMethod };
        if (cloneMethod === 'restriction') {
            body.vector = ($('cloneVector').value || '').trim();
            body.insert = ($('cloneInsert').value || '').trim();
            body.enzyme = ($('cloneReEnzyme').value || '').trim();
            body.vector_topology = $('cloneVecCirc').checked ? 'circular' : 'linear';
            if (!body.vector || !body.insert) { cloneErr('Paste both a vector and an insert.'); return; }
        } else {
            const frags = parseFragments($('cloneFragments').value);
            if (frags.length < 2) { cloneErr('Provide at least two fragments.'); return; }
            body.fragments = frags;
            if (cloneMethod === 'gibson') body.circular = $('cloneCircular').checked;
            if (cloneMethod === 'golden_gate') body.enzyme = $('cloneGgEnzyme').value;
        }
        const btn = $('cloneRun'); const orig = btn.textContent; btn.disabled = true; btn.textContent = 'Assembling…';
        try {
            const res = await fetch('/api/plasmid/clone', {
                method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body),
            });
            const data = await res.json();
            if (res.status === 403 && data.kind === 'signin_required') { window.dispatchEvent(new Event('td:signin-required')); return; }
            if (!res.ok) { cloneErr(data.error || 'Assembly failed.'); return; }
            if (!data.ok) { cloneErr(data.error || 'Couldn’t assemble these fragments.'); $('cloneResult').hidden = true; return; }
            lastAssembly = data;
            renderClone(data);
        } catch (e) { cloneErr('Could not reach the assembler.'); }
        finally { btn.disabled = false; btn.textContent = orig; }
    }

    function renderClone(d) {
        const r = $('cloneResult'); r.hidden = false;
        const junc = (d.junctions || []).map((j) => `
            <div class="clone-junc">
              <span class="cj-pair">${esc(j.left)} → ${esc(j.right)}</span>
              <span class="cj-kind cj-${esc(j.kind)}">${esc(j.kind)}</span>
              <span class="cj-ov">${j.overlap} bp${j.seq ? ' · ' + esc(j.seq.slice(0, 24)) : ''}</span>
            </div>`).join('');
        let primers = '';
        if ((d.primers || []).length) {
            primers = '<h4 class="clone-sub">Assembly primers</h4>' + d.primers.map((p) => `
                <div class="clone-primer">
                  <div class="cp-name">${esc(p.fragment)}</div>
                  <div class="cp-row"><span class="cp-lbl">F</span><code>${esc(p.forward)}</code><span class="cp-meta">${p.forward_len} nt${p.forward_tail ? ' · +' + p.forward_tail + ' tail' : ''}${p.forward_tm ? ' · Tm ' + p.forward_tm + '°C' : ''}</span></div>
                  <div class="cp-row"><span class="cp-lbl">R</span><code>${esc(p.reverse)}</code><span class="cp-meta">${p.reverse_len} nt${p.reverse_tail ? ' · +' + p.reverse_tail + ' tail' : ''}${p.reverse_tm ? ' · Tm ' + p.reverse_tm + '°C' : ''}</span></div>
                </div>`).join('');
        }
        r.innerHTML =
            `<div class="clone-summary"><span class="clone-ok">✓ Assembled</span>
               <strong>${d.length.toLocaleString()} bp</strong> · ${esc(d.topology)} ·
               ${(d.order || []).map(esc).join(' → ')}</div>`
            + ((d.warnings || []).length ? `<div class="clone-warn">${d.warnings.map(esc).join(' ')}</div>` : '')
            + `<div class="clone-junc-list"><h4 class="clone-sub">Junctions</h4>${junc}</div>`
            + primers
            + `<div class="clone-result-actions">
                 <button class="primary" type="button" id="cloneOpen">Open assembled plasmid in the studio →</button>
               </div>`;
        const open = $('cloneOpen');
        if (open) open.addEventListener('click', () => {
            plasmid = { name: 'assembly', sequence: d.assembled, length: d.length,
                        topology: d.topology, gc: gcOf(d.assembled), features: d.features || [], source: 'raw' };
            showResults();
            window.scrollTo({ top: 0, behavior: 'smooth' });
        });
        r.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
    }
    if ($('cloneRun')) $('cloneRun').addEventListener('click', runClone);
    setCloneMethod('gibson');

    // ───────────────────── M5: hand off to CRISPR / Primer Picker ──────────
    // The other tools are separate controllers, so we drive them through their
    // public DOM inputs (set value + fire 'input' so their gutters/stats react)
    // and route via the hash. Works on the whole plasmid or a selected region.
    function _toast(msg) {
        if (typeof showToast === 'function') { showToast(msg, 'info'); return; }
        showSeqOut(msg);
    }
    function sendToCrispr(seq, label) {
        seq = (seq || '').toUpperCase().replace(/[^ACGTN]/g, '');
        if (seq.length < 23) { _toast('Need at least ~23 bp to design CRISPR guides.'); return; }
        const ta = document.getElementById('crisprInput');
        if (!ta) return;
        ta.value = seq; ta.dispatchEvent(new Event('input', { bubbles: true }));
        const gene = document.getElementById('crisprGeneSymbol'); if (gene) gene.value = '';
        location.hash = '#crispr';
        setTimeout(() => { const card = document.getElementById('crisprInputCard'); if (card) card.scrollIntoView({ behavior: 'smooth', block: 'start' }); }, 80);
        _toast(`Loaded ${label} (${seq.length.toLocaleString()} bp) into the CRISPR designer — hit Design.`);
    }
    function sendToPrimers(seq, label) {
        seq = (seq || '').toUpperCase().replace(/[^ACGTN]/g, '');
        if (!seq) { _toast('Nothing to send.'); return; }
        const t = document.getElementById('primerTemplate');
        if (!t) return;
        t.value = seq; t.dispatchEvent(new Event('input', { bubbles: true }));
        location.hash = '#primers';
        setTimeout(() => { const el = document.getElementById('primerInput'); if (el) { el.scrollIntoView({ behavior: 'smooth', block: 'center' }); el.focus(); } }, 80);
        _toast(`Set ${label} (${seq.length.toLocaleString()} bp) as the Primer Analysis template — paste candidate primers.`);
    }
    function sendToEvolve(seq, label) {
        // Hand a construct (or a selected CDS region) to Directed Evolution.
        // We load the Paste tab and let the DE flow do its own CDS-picker /
        // 6-frame ORF discovery on "Use this sequence" — same no-auto-submit
        // posture as the CRISPR / Primer hand-offs.
        seq = (seq || '').toUpperCase().replace(/[^ACGTN]/g, '');
        if (seq.length < 30) { _toast('Need ≥30 bp of coding sequence to evolve a protein.'); return; }
        const ta = document.getElementById('pasteArea');
        if (!ta) return;
        ta.value = seq; ta.dispatchEvent(new Event('input', { bubbles: true }));
        const pasteTab = document.querySelector('.tab[data-tab="paste"]');
        if (pasteTab) pasteTab.click();   // reveal the loaded sequence
        location.hash = '#design';
        setTimeout(() => { ta.scrollIntoView({ behavior: 'smooth', block: 'center' }); ta.focus(); }, 80);
        _toast(`Loaded ${label} (${seq.length.toLocaleString()} bp) into Directed Evolution — click "Use this sequence", then pick the CDS to evolve.`);
    }

    // Toolbar "Use in ▾" menu — acts on the whole plasmid.
    const useBtn = $('plasmidUseBtn');
    if (useBtn) {
        const menu = document.createElement('div');
        menu.className = 'plasmid-export-menu plasmid-use-menu'; menu.hidden = true;
        menu.innerHTML = '<button type="button" data-use="crispr">CRISPR guides</button>'
            + '<button type="button" data-use="primers">Primer Analysis (template)</button>'
            + '<button type="button" data-use="evolve">Directed Evolution (evolve CDS)</button>';
        useBtn.parentNode.appendChild(menu);
        useBtn.addEventListener('click', (e) => {
            e.stopPropagation();
            const open = menu.hidden;
            document.querySelectorAll('.plasmid-export-menu').forEach((m) => { m.hidden = true; });
            menu.hidden = !open;
        });
        menu.addEventListener('click', (e) => {
            const b = e.target.closest('[data-use]'); if (!b || !plasmid) return;
            menu.hidden = true;
            const nm = plasmid.name || 'plasmid';
            const use = b.getAttribute('data-use');
            if (use === 'crispr') sendToCrispr(plasmid.sequence, nm);
            else if (use === 'evolve') sendToEvolve(plasmid.sequence, nm);
            else sendToPrimers(plasmid.sequence, nm);
        });
        document.addEventListener('click', () => { document.querySelectorAll('.plasmid-export-menu').forEach((m) => { m.hidden = true; }); });
    }

    // Sequence-editor region hand-offs — act on the current selection (or whole).
    if ($('seqToCrispr')) $('seqToCrispr').addEventListener('click', () => {
        const seq = sel ? selSeq() : plasmid.sequence;
        sendToCrispr(seq, sel ? `region ${sel.from}–${sel.to}` : (plasmid.name || 'plasmid'));
    });
    if ($('seqToPrimers')) $('seqToPrimers').addEventListener('click', () => {
        const seq = sel ? selSeq() : plasmid.sequence;
        sendToPrimers(seq, sel ? `region ${sel.from}–${sel.to}` : (plasmid.name || 'plasmid'));
    });
    if ($('seqToEvolve')) $('seqToEvolve').addEventListener('click', () => {
        const seq = sel ? selSeq() : plasmid.sequence;
        sendToEvolve(seq, sel ? `region ${sel.from}–${sel.to}` : (plasmid.name || 'plasmid'));
    });
    // Workbench-home "Map & cut" link: already on this view → focus the import box.
    if ($('wbToImport')) $('wbToImport').addEventListener('click', (e) => {
        e.preventDefault();
        const t = $('plasmidInput');
        if (t) { t.scrollIntoView({ behavior: 'smooth', block: 'center' }); t.focus(); }
    });
})();

// ════════════════════════════════════════════════ UNIFIED SAVED-WORK HUB
// One "My designs" panel listing everything saved across all four tools.
// Each tool controller registers its reopen fn on window.TDSaved (above);
// here we render the sections and dispatch row clicks. Backed by
// /api/plasmid/library, /api/crispr/designs, /api/primers/analyses, /api/library.
(function initSavedHub() {
    const modal = document.getElementById('savedModal');
    if (!modal) return;
    const esc = (s) => (typeof escapeHtml === 'function' ? escapeHtml(String(s)) : String(s));
    const fmtDate = (s) => { try { return s ? new Date(s).toLocaleDateString() : ''; } catch (_) { return ''; } };
    window.TDSaved = window.TDSaved || {};
    const KIND_HASH = { plasmid: '#plasmid', crispr: '#crispr', primer: '#primers' };

    // ── Live auto-delete countdown ──
    // Each saved row carries its expires_at; we tick a "44d 23:59:58 left"
    // countdown every second while the hub is open (cleared on close so it
    // never runs in the background).
    let _timer = null;
    function _fmtRemaining(iso) {
        let ms;
        try { ms = new Date(iso).getTime() - Date.now(); } catch (_) { return ''; }
        if (isNaN(ms)) return '';
        if (ms <= 0) return null;                 // expired — next save sweeps it
        const s = Math.floor(ms / 1000);
        const p = (n) => String(n).padStart(2, '0');
        return `${Math.floor(s / 86400)}d ${p(Math.floor((s % 86400) / 3600))}:${p(Math.floor((s % 3600) / 60))}:${p(s % 60)}`;
    }
    function _tickExpiry() {
        modal.querySelectorAll('.saved-expiry[data-exp]').forEach((el) => {
            const iso = el.getAttribute('data-exp');
            const r = _fmtRemaining(iso);
            if (r === null) { el.textContent = 'expiring…'; el.classList.add('saved-expiry-urgent'); return; }
            if (!r) { el.textContent = ''; return; }
            el.textContent = r + ' left';
            el.classList.toggle('saved-expiry-urgent', (new Date(iso).getTime() - Date.now()) < 86400000);
        });
    }
    function _startTimer() { _tickExpiry(); if (!_timer) _timer = setInterval(_tickExpiry, 1000); }
    function _stopTimer() { if (_timer) { clearInterval(_timer); _timer = null; } }

    function close() { _stopTimer(); modal.hidden = true; document.body.style.overflow = ''; }
    function open() { modal.hidden = false; document.body.style.overflow = 'hidden'; loadAll(); _startTimer(); }
    modal.querySelectorAll('[data-saved-close]').forEach((el) => el.addEventListener('click', close));
    document.addEventListener('keydown', (e) => { if (e.key === 'Escape' && !modal.hidden) close(); });

    // signin_required from any section → close + surface the sign-in modal once.
    let _signinFired = false;
    function _maybeSignin(res, data) {
        if (res.status === 403 && data && data.kind === 'signin_required') {
            if (!_signinFired) { _signinFired = true; close(); window.dispatchEvent(new Event('td:signin-required')); }
            return true;
        }
        return false;
    }

    function reopen(kind, id) {
        close();
        const h = KIND_HASH[kind];
        if (h && location.hash !== h) location.hash = h;   // navigate to the tool first
        const fn = window.TDSaved[kind];
        if (typeof fn === 'function') fn(id);
    }

    async function downloadLibrary(id, btn) {
        const orig = btn.textContent; btn.disabled = true; btn.textContent = 'Preparing…';
        try {
            const res = await fetch('/api/library/' + encodeURIComponent(id) + '/download');
            const data = await res.json();
            if (_maybeSignin(res, data)) return;
            if (data.ok && data.url) window.open(data.url, '_blank', 'noopener');
        } catch (_) { /* ignore */ }
        finally { btn.disabled = false; btn.textContent = orig; }
    }

    function savedRow(kind, id, label, meta, opts) {
        opts = opts || {};
        const action = opts.download
            ? `<button type="button" class="saved-dl" data-dl="${esc(id)}">Download CSV</button>` : '';
        const interactive = opts.download ? '' : ' role="button" tabindex="0"';
        let expiry;
        if (opts.expires) {
            let when = '';
            try { when = new Date(opts.expires).toLocaleDateString(); } catch (_) {}
            expiry = `<span class="saved-expiry" data-exp="${esc(opts.expires)}" title="Auto-deletes ${esc(when)}">…</span>`;
        } else {
            expiry = '<span class="saved-expiry saved-expiry-none" title="No expiry on this item">kept</span>';
        }
        return `<div class="saved-row" data-kind="${kind}" data-id="${esc(id)}"${interactive}>` +
            `<span class="saved-row-main"><span class="saved-row-label">${esc(label)}</span>` +
            `<span class="saved-row-meta">${esc(meta)}</span></span>` +
            `<span class="saved-row-side">${expiry}${action}</span></div>`;
    }

    async function loadSection(elId, url, key, render, emptyMsg) {
        const el = document.getElementById(elId);
        if (!el) return;
        el.innerHTML = '<p class="muted">Loading…</p>';
        try {
            const res = await fetch(url);
            const data = await res.json();
            if (_maybeSignin(res, data)) return;
            const items = (data && data[key]) || [];
            el.innerHTML = items.length ? items.map(render).join('') : `<p class="muted">${esc(emptyMsg)}</p>`;
            _tickExpiry();   // paint countdowns immediately, before the 1s interval
        } catch (_) { el.innerHTML = '<p class="muted">Couldn’t load these.</p>'; }
    }

    function loadAll() {
        _signinFired = false;
        loadSection('savedPlasmids', '/api/plasmid/library', 'plasmids',
            (p) => savedRow('plasmid', p.id, p.name || 'plasmid',
                `${(p.length || 0).toLocaleString()} bp · ${p.topology || ''}${p.gc != null ? ' · GC ' + p.gc + '%' : ''}`,
                { expires: p.expires_at }),
            'No saved plasmids yet. Import one and hit Save.');
        loadSection('savedCrispr', '/api/crispr/designs', 'designs',
            (d) => savedRow('crispr', d.id, d.label || 'Untitled design',
                `${d.mode === 'base_edit' ? 'base edit' : 'knockout'} · ${d.n_guides || 0} guides · ${fmtDate(d.created_at)}`,
                { expires: d.expires_at }),
            'No saved CRISPR designs yet. Run a design and click Save.');
        loadSection('savedPrimers', '/api/primers/analyses', 'analyses',
            (a) => savedRow('primer', a.id, a.label || 'Primer set',
                `${a.n_primers || 0} primers${a.template_len ? ' · ' + a.template_len.toLocaleString() + ' bp template' : ''} · ${fmtDate(a.created_at)}`,
                { expires: a.expires_at }),
            'No saved primer sets yet. Analyse primers and click Save.');
        loadSection('savedLibraries', '/api/library', 'libraries',
            (l) => savedRow('library', l.id, l.name || 'Library',
                `${(l.n_variants || 0).toLocaleString()} variants${l.top_fitness != null ? ' · top ' + Number(l.top_fitness).toFixed(2) : ''} · ${fmtDate(l.created_at)}`,
                { download: true, expires: l.expires_at }),
            'No saved evolution libraries yet. Run the engine while signed in.');
    }

    modal.addEventListener('click', (e) => {
        const dl = e.target.closest('.saved-dl');
        if (dl) { e.stopPropagation(); downloadLibrary(dl.getAttribute('data-dl'), dl); return; }
        const row = e.target.closest('.saved-row[role="button"]');
        if (row) reopen(row.getAttribute('data-kind'), row.getAttribute('data-id'));
    });
    modal.addEventListener('keydown', (e) => {
        if (e.key !== 'Enter' && e.key !== ' ') return;
        const row = e.target.closest && e.target.closest('.saved-row[role="button"]');
        if (row) { e.preventDefault(); reopen(row.getAttribute('data-kind'), row.getAttribute('data-id')); }
    });

    window.TDSaved.open = open;
})();

// ── One-time policy-change notice (Privacy/Terms v2.0) ──────────────────
// Shows a dismissible bar until the user acknowledges; choice persists.
(function initPolicyNotice() {
    var KEY = 'td_policy_v2_ack_r2';  // bumped: re-surface the notice now that it carries the export/delete recourse
    var el = document.getElementById('policyNotice');
    if (!el) return;
    try { if (localStorage.getItem(KEY) === '1') return; } catch (e) {}
    el.hidden = false;
    var btn = document.getElementById('policyNoticeClose');
    if (btn) btn.addEventListener('click', function () {
        el.hidden = true;
        try { localStorage.setItem(KEY, '1'); } catch (e) {}
    });
})();

// ── De novo primer design (Primer Analysis tool) ─────────────────────────────
// Self-contained card: template (+ optional target) → Tm-matched F/R pairs from
// POST /api/primers/design, shown as a table + a virtual gel of the products.
(function initPrimerDesign() {
    const $ = (id) => document.getElementById(id);
    const tmpl = $('designTemplate'), btn = $('designBtn'),
          ts = $('designTargetStart'), te = $('designTargetEnd'),
          pmin = $('designProductMin'), pmax = $('designProductMax'),
          results = $('designResults'), gel = $('designGel'),
          err = $('designError'), warn = $('designWarnings'), ex = $('designExample');
    if (!btn || !tmpl) return;
    const esc = (s) => (typeof escapeHtml === 'function' ? escapeHtml(String(s)) : String(s));
    const showErr = (m) => { if (err) { err.hidden = false; err.textContent = m; } };
    const hideErr = () => { if (err) err.hidden = true; };

    function _demoTemplate() {  // deterministic ~540 bp demo so the example always designs
        let s = '', x = 1234567; for (let i = 0; i < 540; i++) { x = (x * 1103515245 + 12345) & 0x7fffffff; s += 'ACGT'[(x >> 16) & 3]; } return s;
    }
    if (ex) ex.onclick = () => { tmpl.value = _demoTemplate(); ts.value = '200'; te.value = '320'; pmin.value = '150'; pmax.value = '450'; };

    function renderGel(pairs) {
        if (!gel) return;
        if (!pairs.length) { gel.hidden = true; gel.innerHTML = ''; return; }
        const ladder = [3000, 2000, 1500, 1000, 750, 500, 400, 300, 200, 100];
        const sizes = pairs.map((p) => p.product_size);
        const H = 300, top = 24, bot = 280, maxbp = Math.max(ladder[0], ...sizes), minbp = 80;
        const yOf = (bp) => { const b = Math.min(Math.max(bp, minbp), maxbp); const f = (Math.log10(maxbp) - Math.log10(b)) / (Math.log10(maxbp) - Math.log10(minbp)); return top + f * (bot - top); };
        let svg = `<svg viewBox="0 0 360 ${H}" class="gel-svg" role="img" aria-label="Predicted PCR products">`;
        svg += `<rect x="0" y="0" width="360" height="${H}" class="gel-bg"/>`;
        svg += `<text x="55" y="16" class="gel-lane-lbl" text-anchor="middle">ladder</text>`;
        svg += `<text x="220" y="16" class="gel-lane-lbl" text-anchor="middle">products</text>`;
        svg += ladder.map((bp) => `<rect x="30" y="${(yOf(bp) - 1.5).toFixed(1)}" width="50" height="3" class="gel-band-ladder"/>`
            + `<text x="85" y="${(yOf(bp) + 3).toFixed(1)}" class="gel-bp">${bp.toLocaleString()}</text>`).join('');
        svg += sizes.map((bp, i) => `<rect x="180" y="${(yOf(bp) - 2).toFixed(1)}" width="80" height="4" class="gel-band"/>`
            + `<text x="265" y="${(yOf(bp) + 3).toFixed(1)}" class="gel-bp gel-bp-frag">#${i + 1} · ${bp.toLocaleString()} bp</text>`).join('');
        svg += `</svg>`;
        gel.hidden = false;
        gel.innerHTML = `<h4 class="gel-title">Predicted products · ${sizes.length} pair${sizes.length === 1 ? '' : 's'}</h4>`
            + `<div class="gel-flex"><div class="gel-graphic">${svg}</div></div>`;
    }

    function renderDesign(j) {
        warn.hidden = !(j.warnings && j.warnings.length);
        if (j.warnings && j.warnings.length) warn.innerHTML = j.warnings.map(esc).join('<br>');
        const pairs = j.pairs || [];
        if (!pairs.length) { results.hidden = true; gel.hidden = true; return; }
        const row = (p, i) => {
            const f = p.forward, r = p.reverse;
            return `<tr>
                <td class="dz-rank">#${i + 1}</td>
                <td><code class="dz-seq">${esc(f.seq)}</code><span class="dz-sub">F · Tm ${f.tm}°C · GC ${f.gc}% · ${f.len} nt</span></td>
                <td><code class="dz-seq">${esc(r.seq)}</code><span class="dz-sub">R · Tm ${r.tm}°C · GC ${r.gc}% · ${r.len} nt</span></td>
                <td class="dz-num">${p.product_size.toLocaleString()} bp</td>
                <td class="dz-num">${p.tm_diff}°C</td>
                <td class="dz-num">${(p.score * 100).toFixed(0)}</td>
            </tr>`;
        };
        results.hidden = false;
        results.innerHTML =
            `<table class="design-table"><thead><tr>
                <th></th><th>Forward (5'→3')</th><th>Reverse (5'→3')</th><th>Product</th><th>ΔTm</th><th>Score</th>
            </tr></thead><tbody>${pairs.map(row).join('')}</tbody></table>`;
        renderGel(pairs);
        tdRenderMethods && tdRenderMethods('designRunMeta', [], null); // (no separate methods box for design)
    }

    btn.onclick = async () => {
        const template = (tmpl.value || '').trim();
        if (!template) { showErr('Paste a template to design primers against.'); return; }
        hideErr(); results.hidden = true; gel.hidden = true; warn.hidden = true;
        btn.disabled = true; const lbl = btn.textContent; btn.textContent = 'Designing…';
        try {
            const body = {
                template,
                target_start: ts.value ? parseInt(ts.value, 10) : null,
                target_end: te.value ? parseInt(te.value, 10) : null,
                settings: {
                    product_min: parseInt(pmin.value || '100', 10),
                    product_max: parseInt(pmax.value || '1000', 10),
                },
            };
            const res = await fetch('/api/primers/design', {
                method: 'POST', headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify(body),
            });
            const j = await res.json().catch(() => ({}));
            if (res.status === 403) { window.dispatchEvent(new Event('td:signin-required')); showErr(j.error || 'Sign in to design primers.'); return; }
            if (!j.ok) { showErr(j.error || 'Design failed — try widening the product-size window.'); return; }
            renderDesign(j);
        } catch (e) { showErr('Couldn’t reach the design engine.'); }
        finally { btn.disabled = false; btn.textContent = lbl; }
    };
})();

// ── Multiplex compatibility check (Primer Analysis tool) ─────────────────────
(function initMultiplexCheck() {
    const $ = (id) => document.getElementById(id);
    const inp = $('mpxInput'), sizes = $('mpxSizes'), btn = $('mpxBtn'),
          out = $('mpxResults'), err = $('mpxError');
    if (!btn || !inp) return;
    const esc = (s) => (typeof escapeHtml === 'function' ? escapeHtml(String(s)) : String(s));
    btn.onclick = async () => {
        const primers = (inp.value || '').trim();
        if (!primers) { err.hidden = false; err.textContent = 'Paste at least two primers.'; return; }
        err.hidden = true; out.hidden = true; btn.disabled = true; const lbl = btn.textContent; btn.textContent = 'Checking…';
        try {
            const products = (sizes.value || '').split(/[,\s]+/).map((x) => parseInt(x, 10))
                .filter((n) => n > 0).map((n, i) => ({ name: 'amp' + (i + 1), size: n }));
            const res = await fetch('/api/primers/multiplex', {
                method: 'POST', headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ primers, products: products.length ? products : undefined }),
            });
            const j = await res.json().catch(() => ({}));
            if (res.status === 403) { window.dispatchEvent(new Event('td:signin-required')); err.hidden = false; err.textContent = j.error || 'Sign in to continue.'; return; }
            if (j.error) { err.hidden = false; err.textContent = j.error; return; }
            out.hidden = false;
            const xd = j.cross_dimers || [], sc = j.size_clashes || [];
            if (!xd.length && !sc.length) {
                out.innerHTML = `<p class="mpx-ok">✓ Compatible — no significant cross-dimers${products.length ? ' or size clashes' : ''} across ${j.n_primers} primers.</p>`;
                return;
            }
            let h = '';
            if (xd.length) h += `<h4 class="mpx-h">Cross-dimers (${xd.length})</h4><ul class="mpx-list">`
                + xd.map((d) => `<li>${esc(d.a)} ${d.self ? '(self)' : '× ' + esc(d.b)} — ${d.run} bp 3′ complementarity</li>`).join('') + '</ul>';
            if (sc.length) h += `<h4 class="mpx-h">Amplicon size clashes (${sc.length})</h4><ul class="mpx-list">`
                + sc.map((c) => `<li>${esc(c.a)} (${c.size_a} bp) vs ${esc(c.b)} (${c.size_b} bp) — Δ${c.delta} bp, hard to resolve</li>`).join('') + '</ul>';
            out.innerHTML = h;
        } catch (e) { err.hidden = false; err.textContent = 'Couldn’t reach the multiplex engine.'; }
        finally { btn.disabled = false; btn.textContent = lbl; }
    };
})();

// ── Local specificity: in-silico PCR vs an uploaded genome (no NCBI) ──────────
(function initLocalSpecificity() {
    const $ = (id) => document.getElementById(id);
    const inp = $('lspecInput'), fa = $('lspecFasta'), file = $('lspecFile'),
          btn = $('lspecBtn'), out = $('lspecResults'), gel = $('lspecGel'), err = $('lspecError');
    if (!btn || !inp) return;
    const esc = (s) => (typeof escapeHtml === 'function' ? escapeHtml(String(s)) : String(s));
    if (file) file.onchange = () => {
        const f = file.files && file.files[0]; if (!f) return;
        if (f.size > 12_000_000) { err.hidden = false; err.textContent = 'File larger than ~12 Mb — use the NCBI scan for human-scale genomes.'; return; }
        const r = new FileReader(); r.onload = () => { fa.value = String(r.result || ''); }; r.readAsText(f);
    };
    function renderGel(sizes) {
        if (!sizes.length) { gel.hidden = true; return; }
        const ladder = [5000, 3000, 2000, 1500, 1000, 750, 500, 300, 200, 100];
        const H = 300, top = 24, bot = 280, maxbp = Math.max(ladder[0], ...sizes), minbp = 80;
        const yOf = (bp) => { const b = Math.min(Math.max(bp, minbp), maxbp); const f = (Math.log10(maxbp) - Math.log10(b)) / (Math.log10(maxbp) - Math.log10(minbp)); return top + f * (bot - top); };
        let svg = `<svg viewBox="0 0 360 ${H}" class="gel-svg" role="img" aria-label="Predicted products">`;
        svg += `<rect x="0" y="0" width="360" height="${H}" class="gel-bg"/>`;
        svg += `<text x="55" y="16" class="gel-lane-lbl" text-anchor="middle">ladder</text><text x="220" y="16" class="gel-lane-lbl" text-anchor="middle">products</text>`;
        svg += ladder.map((bp) => `<rect x="30" y="${(yOf(bp) - 1.5).toFixed(1)}" width="50" height="3" class="gel-band-ladder"/><text x="85" y="${(yOf(bp) + 3).toFixed(1)}" class="gel-bp">${bp.toLocaleString()}</text>`).join('');
        svg += sizes.map((bp) => `<rect x="180" y="${(yOf(bp) - 2).toFixed(1)}" width="80" height="4" class="gel-band"/><text x="265" y="${(yOf(bp) + 3).toFixed(1)}" class="gel-bp gel-bp-frag">${bp.toLocaleString()} bp</text>`).join('');
        svg += `</svg>`;
        gel.hidden = false;
        gel.innerHTML = `<div class="gel-flex"><div class="gel-graphic">${svg}</div></div>`;
    }
    btn.onclick = async () => {
        const primers = (inp.value || '').trim(), fasta = (fa.value || '').trim();
        if (!primers) { err.hidden = false; err.textContent = 'Paste the primers to check.'; return; }
        if (!fasta) { err.hidden = false; err.textContent = 'Paste or upload a genome/FASTA to scan against.'; return; }
        err.hidden = true; out.hidden = true; gel.hidden = true; btn.disabled = true; const lbl = btn.textContent; btn.textContent = 'Scanning…';
        try {
            const res = await fetch('/api/primers/local-specificity', {
                method: 'POST', headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ primers, fasta }),
            });
            const j = await res.json().catch(() => ({}));
            if (res.status === 403) { window.dispatchEvent(new Event('td:signin-required')); err.hidden = false; err.textContent = j.error || 'Sign in to continue.'; return; }
            if (!j.ok) { err.hidden = false; err.textContent = j.error || 'Scan failed.'; return; }
            out.hidden = false;
            const prods = j.products || [];
            const head = j.specific
                ? `<p class="mpx-ok">✓ Specific — exactly one predicted product across ${j.n_records} record(s), ${(j.scanned_bp || 0).toLocaleString()} bp scanned.</p>`
                : `<p class="mpx-warn">${prods.length} predicted product(s) — off-target amplification likely. ${(j.scanned_bp || 0).toLocaleString()} bp scanned.</p>`;
            out.innerHTML = head + (prods.length ? `<ul class="mpx-list">` + prods.map((p) =>
                `<li>${esc(p.title || p.subject)} — ${p.size.toLocaleString()} bp (${esc(p.fwd_name || p.fwd)} → ${esc(p.rev_name || p.rev)})</li>`).join('') + '</ul>' : '');
            renderGel(prods.map((p) => p.size));
        } catch (e) { err.hidden = false; err.textContent = 'Couldn’t reach the specificity engine.'; }
        finally { btn.disabled = false; btn.textContent = lbl; }
    };
})();

// ── CRISPR: log editing efficiency → unified outcomes (cross-user moat) ───────
(function initCrisprOutcomes() {
    const card = document.getElementById('crisprOutcomeCard');
    const list = document.getElementById('crisprOutcomeList');
    const saveBtn = document.getElementById('crisprOutcomeSave');
    const statusEl = document.getElementById('crisprOutcomeStatus');
    if (!card || !list || !saveBtn) return;
    const esc = (s) => (typeof escapeHtml === 'function' ? escapeHtml(String(s)) : String(s));
    let designId = null, guides = [];

    function uuid() {
        try { if (window.crypto && crypto.randomUUID) return crypto.randomUUID(); } catch (e) {}
        return 'cx' + Date.now().toString(16) + Math.random().toString(16).slice(2, 10);
    }
    function setStatus(msg, warn) {
        statusEl.hidden = false; statusEl.textContent = msg;
        statusEl.classList.toggle('round2-status-warn', !!warn);
    }

    function populate(gs) {
        guides = (gs || []).filter((g) => g && g.spacer).slice(0, 50);
        if (!guides.length) { card.hidden = true; return; }
        designId = uuid();
        statusEl.hidden = true;
        list.innerHTML = guides.map((g, i) => {
            const sp = esc(g.spacer);
            return `<div class="ce-row">
                <span class="ce-rank">#${g.rank || i + 1}</span>
                <code class="ce-spacer">${sp}</code>
                <input type="number" class="ce-eff-input" data-spacer="${sp}" min="0" max="100" step="0.1" inputmode="decimal" placeholder="% edit" />
            </div>`;
        }).join('');
        card.hidden = false;
    }

    function collect() {
        const out = [];
        list.querySelectorAll('.ce-eff-input').forEach((inp) => {
            const v = (inp.value || '').trim();
            if (v === '') return;
            const n = parseFloat(v);
            if (isFinite(n)) out.push({ subject: inp.getAttribute('data-spacer'), measured_value: n, outcome: 'measured' });
        });
        return out;
    }

    saveBtn.onclick = async () => {
        const rows = collect();
        if (!rows.length) { setStatus('Enter at least one efficiency value first.', true); return; }
        saveBtn.disabled = true; const lbl = saveBtn.textContent; saveBtn.textContent = 'Saving…';
        try {
            const res = await fetch('/api/outcomes', {
                method: 'POST', headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ tool: 'crispr', design_id: designId, outcomes: rows }),
            });
            const j = await res.json().catch(() => ({}));
            if (res.status === 403) { window.dispatchEvent(new Event('td:signin-required')); setStatus('Sign in to save results.', true); return; }
            if (!j.ok) { setStatus(j.error || 'Couldn’t save — the outcomes table may not be set up yet.', true); return; }
            setStatus(`Saved ✓ ${j.saved} result${j.saved === 1 ? '' : 's'} — thanks, this sharpens guide predictions for everyone.`, false);
        } catch (e) { setStatus('Couldn’t reach the server.', true); }
        finally { saveBtn.disabled = false; saveBtn.textContent = lbl; }
    };

    window.TDCrisprOutcomes = { populate };
})();

// ── Primer + cloning result loggers → unified outcomes (cross-user moat) ──────
(function initOutcomeLoggers() {
    const $ = (id) => document.getElementById(id);
    function uuid() {
        try { if (window.crypto && crypto.randomUUID) return crypto.randomUUID(); } catch (e) {}
        return 'ox' + Date.now().toString(16) + Math.random().toString(16).slice(2, 10);
    }
    function wire(btnId, statusId, buildBody) {
        const btn = $(btnId), st = $(statusId);
        if (!btn) return;
        const set = (m, w) => { st.hidden = false; st.textContent = m; st.classList.toggle('round2-status-warn', !!w); };
        btn.onclick = async () => {
            const body = buildBody(set);
            if (!body) return;
            btn.disabled = true; const lbl = btn.textContent; btn.textContent = 'Saving…';
            try {
                const res = await fetch('/api/outcomes', {
                    method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body),
                });
                const j = await res.json().catch(() => ({}));
                if (res.status === 403) { window.dispatchEvent(new Event('td:signin-required')); set('Sign in to save.', true); return; }
                if (!j.ok) { set(j.error || 'Couldn’t save — the outcomes table may not be set up yet.', true); return; }
                set('Saved ✓ thanks — this sharpens predictions for everyone.', false);
            } catch (e) { set('Couldn’t reach the server.', true); }
            finally { btn.disabled = false; btn.textContent = lbl; }
        };
    }
    // Primer amplification logger
    wire('poSave', 'poStatus', (set) => {
        const f = (($('poFwd').value || '').toUpperCase().replace(/\s+/g, ''));
        const r = (($('poRev').value || '').toUpperCase().replace(/\s+/g, ''));
        if (!f && !r) { set('Enter at least one primer.', true); return null; }
        const subject = [f, r].filter(Boolean).join('|');
        return { tool: 'primer', design_id: uuid(),
                 outcomes: [{ subject, measured_value: parseFloat($('poResult').value), outcome: 'measured' }] };
    });
    // Cloning assembly logger
    wire('coSave', 'coStatus', () => {
        const method = $('coMethod').value;
        const frags = parseInt($('coFrags').value || '2', 10);
        const overlap = parseInt($('coOverlap').value || '25', 10);
        const subject = `${method}|frags=${frags}|overlap=${overlap}`;
        return { tool: 'cloning', design_id: uuid(),
                 outcomes: [{ subject, measured_value: parseFloat($('coResult').value), outcome: 'measured' }] };
    });
})();

// ── Pairwise sequence alignment (Plasmid workbench card → /api/align) ──
(function initAlign() {
    const A = document.getElementById('alignA');
    const B = document.getElementById('alignB');
    const runBtn = document.getElementById('alignRun');
    const out = document.getElementById('alignOutput');
    const stats = document.getElementById('alignStats');
    if (!A || !B || !runBtn || !out) return;
    let mode = 'global';
    document.querySelectorAll('[data-align-mode]').forEach((btn) => {
        btn.addEventListener('click', () => {
            mode = btn.getAttribute('data-align-mode');
            document.querySelectorAll('[data-align-mode]').forEach((b) =>
                b.classList.toggle('clone-method-active', b === btn));
        });
    });
    // Wrap every non-matching residue (mismatch or gap — any column the
    // server's midline doesn't mark "|") in a red span, grouping consecutive
    // runs so a stretch of divergence reads as one highlight. Matching runs
    // stay plain. Per-column status comes from the authoritative midline.
    function colorRow(seqSlice, midSlice) {
        let html = '', run = '', runMismatch = false;
        const flush = () => {
            if (!run) return;
            html += runMismatch
                ? `<span class="align-mm">${escapeHtml(run)}</span>`
                : escapeHtml(run);
            run = '';
        };
        for (let k = 0; k < seqSlice.length; k++) {
            const mismatch = midSlice[k] !== '|';
            if (mismatch !== runMismatch) { flush(); runMismatch = mismatch; }
            run += seqSlice[k];
        }
        flush();
        return html;
    }
    function render(r) {
        const W = 60, aa = r.aligned_a || '', bb = r.aligned_b || '', mid = r.midline || '';
        let html = '';
        for (let i = 0; i < aa.length; i += W) {
            const n = Math.min(i + W, aa.length);
            const pos = String(i + 1), mSlice = mid.slice(i, n);
            html += `<div class="align-block">`
                + `<div class="align-row">${pos} ${colorRow(aa.slice(i, n), mSlice)}</div>`
                + `<div class="align-row align-mid">${' '.repeat(pos.length + 1)}${escapeHtml(mSlice)}</div>`
                + `<div class="align-row">${pos} ${colorRow(bb.slice(i, n), mSlice)}</div></div>`;
        }
        out.innerHTML = html;
        out.hidden = false;
        stats.textContent = `${r.mode} · ${r.identity}% identity · ${r.matches}/${r.length} matches · ${r.gaps} gaps · score ${r.score}`;
    }
    runBtn.addEventListener('click', async () => {
        const a = (A.value || '').trim(), b = (B.value || '').trim();
        if (!a || !b) { stats.textContent = 'Paste two sequences first.'; out.hidden = true; return; }
        runBtn.disabled = true; stats.textContent = 'Aligning…'; out.hidden = true;
        try {
            const res = await fetch('/api/align', {
                method: 'POST', headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ a, b, mode }),
            });
            const data = await res.json().catch(() => ({}));
            if (!res.ok || data.error) { stats.textContent = data.error || `Alignment failed (${res.status}).`; }
            else render(data);
        } catch (e) {
            stats.textContent = 'Network error — try again.';
        } finally { runBtn.disabled = false; }
    });
})();