File size: 260,675 Bytes
dec006b
52c6936
f530297
 
 
 
 
c1fc133
816fa8a
ce9586e
c1fc133
8873406
 
4cfab62
 
 
c1fc133
2eae9f0
f530297
4cfab62
 
 
 
 
 
 
 
 
 
 
8729c1d
4cfab62
 
23088ad
8729c1d
4cfab62
 
 
f530297
4cfab62
 
23088ad
4cfab62
 
b35f959
 
 
 
 
 
 
 
74f72af
 
 
8729c1d
c1fc133
 
 
4cfab62
19aed6d
 
07a68d0
 
8873406
07a68d0
19aed6d
 
 
 
 
 
4cfab62
 
 
 
 
 
 
 
f530297
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dec006b
8133df9
8729c1d
c1fc133
4cfab62
 
 
 
74f72af
b35f959
4cfab62
 
8729c1d
 
 
b35f959
4cfab62
b35f959
 
4cfab62
 
 
36900c7
4cfab62
36900c7
 
4cfab62
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
23088ad
 
 
 
 
 
 
 
 
 
 
 
 
 
 
74f72af
 
 
 
 
 
 
 
 
 
 
 
8729c1d
 
 
 
 
1d4419b
8729c1d
1d4419b
8729c1d
 
 
1d4419b
8729c1d
 
 
 
1d4419b
8729c1d
 
 
1d4419b
 
 
8729c1d
 
 
1d4419b
8729c1d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1d4419b
 
23088ad
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f530297
 
52c6936
f530297
 
 
 
 
 
52c6936
 
23088ad
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4cfab62
c1fc133
8729c1d
c1fc133
8729c1d
19aed6d
 
 
 
 
 
 
 
 
 
816fa8a
 
4cfab62
f530297
 
 
 
 
 
 
 
 
 
 
 
4cfab62
8729c1d
4cfab62
e174d2c
 
4cfab62
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
19aed6d
 
 
f530297
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
19aed6d
 
 
4cfab62
 
 
 
 
 
 
 
 
 
 
19b91ce
 
4cfab62
 
 
8133df9
4cfab62
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
72b6f27
 
 
4cfab62
 
 
 
 
 
 
 
 
e174d2c
4cfab62
 
 
 
 
 
 
 
 
 
 
 
19aed6d
 
 
 
 
 
 
 
 
 
816fa8a
 
 
 
19b91ce
 
 
816fa8a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
19b91ce
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
19aed6d
 
52c6936
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
19aed6d
 
07a68d0
19aed6d
 
 
 
 
07a68d0
19aed6d
 
 
 
8cbc29f
 
 
 
 
 
 
19aed6d
 
 
 
 
 
 
 
 
 
 
816fa8a
 
19aed6d
 
8cbc29f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
19aed6d
 
 
 
 
 
52c6936
 
 
 
 
19aed6d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8cbc29f
 
 
19aed6d
 
 
 
07a68d0
2eae9f0
 
19aed6d
 
2eae9f0
19aed6d
 
c1fc133
 
816fa8a
c1fc133
 
 
2eae9f0
c1fc133
 
 
 
 
19aed6d
 
 
 
c1fc133
19aed6d
 
2eae9f0
 
 
19b91ce
 
 
2eae9f0
c1fc133
19b91ce
 
c1fc133
 
816fa8a
 
c1fc133
 
2eae9f0
c1fc133
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
816fa8a
19aed6d
 
52c6936
 
 
 
19aed6d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
816fa8a
52c6936
 
07a68d0
52c6936
 
 
 
19aed6d
 
2e7e617
 
 
 
 
19aed6d
 
 
 
8cbc29f
19aed6d
 
82cdb59
8873406
82cdb59
8873406
8cbc29f
 
 
 
 
 
 
 
 
19aed6d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
19b91ce
816fa8a
 
 
 
 
 
19b91ce
19aed6d
52c6936
 
 
8cbc29f
19aed6d
07a68d0
19aed6d
 
52c6936
 
 
2eae9f0
 
 
 
8cbc29f
 
07a68d0
8cbc29f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2eae9f0
 
 
8873406
 
2eae9f0
 
 
 
 
8873406
 
 
 
 
2eae9f0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
19aed6d
816fa8a
 
 
 
 
 
 
 
 
19aed6d
816fa8a
 
 
19aed6d
52c6936
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
19aed6d
 
52c6936
07a68d0
19aed6d
 
 
 
 
07a68d0
19aed6d
8873406
 
 
 
 
82cdb59
 
 
 
 
 
 
 
 
 
 
 
 
816fa8a
 
82cdb59
 
 
 
19aed6d
 
 
 
 
2eae9f0
52c6936
 
 
19aed6d
 
 
19b91ce
19aed6d
 
2eae9f0
 
 
19aed6d
8cbc29f
52c6936
 
 
8cbc29f
52c6936
 
 
19aed6d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c1fc133
19aed6d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
816fa8a
19aed6d
 
 
 
b35f959
19b91ce
 
 
b35f959
 
 
 
 
 
 
19b91ce
b35f959
 
 
 
 
 
 
 
 
 
 
19b91ce
b35f959
 
19aed6d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4cfab62
c1fc133
 
8729c1d
c1fc133
19aed6d
 
 
 
 
 
 
 
816fa8a
4cfab62
 
c1fc133
f530297
4cfab62
c1fc133
4cfab62
 
 
 
c1fc133
4cfab62
 
 
 
 
 
 
19aed6d
f530297
 
19aed6d
 
4cfab62
 
 
 
 
 
 
 
 
 
 
 
 
 
 
72b6f27
 
4cfab62
c1fc133
 
 
 
 
8729c1d
 
 
2e7e617
c1fc133
2e7e617
 
 
 
 
c1fc133
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8729c1d
 
 
 
 
 
 
 
 
 
 
 
 
07a68d0
19aed6d
 
 
 
 
 
 
 
4cfab62
 
 
 
 
 
f530297
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4cfab62
 
 
72b6f27
4cfab62
 
 
 
72b6f27
4cfab62
 
 
 
72b6f27
4cfab62
 
 
 
72b6f27
4cfab62
 
 
 
 
72b6f27
4cfab62
19aed6d
 
19b91ce
c1fc133
 
52c6936
c1fc133
f530297
 
 
 
 
 
 
 
 
 
 
 
 
 
dec006b
 
 
 
 
07a68d0
dec006b
 
 
 
 
 
 
 
f530297
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c1fc133
f530297
 
c1fc133
f530297
816fa8a
 
f530297
 
 
 
 
 
816fa8a
 
f530297
 
 
 
816fa8a
f530297
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
19aed6d
 
 
 
4cfab62
 
 
f530297
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c1fc133
 
 
19aed6d
4cfab62
 
72b6f27
c1fc133
72b6f27
 
 
c1fc133
4cfab62
 
 
 
e174d2c
72b6f27
 
 
b35f959
72b6f27
 
b35f959
72b6f27
 
 
 
b35f959
72b6f27
 
 
 
 
 
 
b35f959
72b6f27
 
 
 
 
 
b35f959
72b6f27
 
 
b35f959
19aed6d
52c6936
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
19b91ce
 
 
 
52c6936
 
 
 
 
19b91ce
4cfab62
 
 
c1fc133
b35f959
 
 
 
 
 
 
 
 
 
 
4cfab62
 
 
 
 
 
 
 
 
 
 
 
 
ce9586e
4cfab62
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ce9586e
 
 
 
 
 
 
 
4cfab62
b35f959
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4cfab62
 
 
 
 
 
 
 
 
 
 
 
74f72af
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8133df9
 
 
 
 
 
 
8729c1d
74f72af
 
 
 
 
 
8133df9
74f72af
 
4cfab62
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c1fc133
4cfab62
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c1fc133
8729c1d
 
 
b35f959
 
 
 
 
 
 
 
 
 
 
 
 
 
74f72af
 
 
 
 
 
 
 
 
 
 
 
 
 
816fa8a
74f72af
 
 
 
 
 
 
 
 
 
 
 
 
816fa8a
74f72af
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
19aed6d
8729c1d
19aed6d
 
 
 
b35f959
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4cfab62
b35f959
4cfab62
 
 
 
 
 
 
 
 
23088ad
 
 
 
 
 
 
 
 
4cfab62
23088ad
4cfab62
 
 
 
 
 
 
 
 
 
 
 
b35f959
 
 
 
 
 
 
 
23088ad
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e174d2c
 
b35f959
 
72b6f27
b35f959
72b6f27
 
 
 
b35f959
72b6f27
 
 
 
 
 
 
 
 
 
b35f959
72b6f27
 
 
 
 
 
 
 
b35f959
19aed6d
 
 
 
 
 
 
 
 
 
19b91ce
 
19aed6d
 
 
 
 
816fa8a
19aed6d
 
 
816fa8a
19aed6d
816fa8a
52c6936
 
 
 
 
 
 
816fa8a
52c6936
 
 
 
816fa8a
52c6936
19aed6d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b35f959
19aed6d
 
 
 
 
 
 
 
 
 
 
 
 
b35f959
52c6936
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
19aed6d
52c6936
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c1fc133
 
 
 
 
 
 
e174d2c
52c6936
 
 
 
 
e174d2c
52c6936
 
 
 
 
 
 
c1fc133
52c6936
c1fc133
 
 
 
 
 
8729c1d
c1fc133
 
 
 
 
 
 
 
 
 
 
8729c1d
c1fc133
 
 
 
 
 
 
 
 
52c6936
 
 
 
 
 
 
 
 
c1fc133
 
52c6936
 
 
 
 
 
 
 
 
 
c1fc133
4cfab62
b35f959
 
 
 
 
 
 
 
 
72b6f27
 
 
 
 
 
 
 
 
 
4cfab62
74f72af
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8133df9
 
74f72af
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4cfab62
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c1fc133
4cfab62
 
 
c1fc133
 
 
 
 
 
 
 
 
 
 
4cfab62
 
 
 
 
 
 
 
 
 
 
 
 
8729c1d
 
 
1d4419b
 
 
 
 
 
4cfab62
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
52c6936
 
 
 
e174d2c
 
52c6936
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1d4419b
 
f530297
 
 
 
1d4419b
 
 
8729c1d
 
f530297
1d4419b
 
 
f530297
 
52c6936
 
 
4cfab62
52c6936
 
 
 
 
 
4cfab62
 
52c6936
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e174d2c
 
 
52c6936
 
 
4cfab62
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f530297
 
 
4cfab62
 
 
74f72af
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c1fc133
 
4cfab62
74f72af
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b35f959
72b6f27
 
 
 
 
 
 
 
 
b35f959
72b6f27
 
 
b35f959
72b6f27
 
b35f959
19aed6d
19b91ce
4cfab62
c1fc133
b35f959
4cfab62
 
 
e174d2c
4cfab62
 
 
 
 
 
c1fc133
4cfab62
52c6936
 
 
 
 
 
 
 
 
 
 
4cfab62
52c6936
4cfab62
 
b35f959
 
 
 
 
 
c1fc133
4cfab62
 
b35f959
4cfab62
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
816fa8a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4cfab62
 
 
 
816fa8a
4cfab62
 
 
ce9586e
 
 
 
4cfab62
dec006b
4cfab62
ce9586e
 
 
4cfab62
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
816fa8a
4cfab62
 
 
19b91ce
4cfab62
19b91ce
816fa8a
 
19b91ce
816fa8a
 
 
 
 
 
 
 
 
19aed6d
 
 
 
 
 
 
 
 
 
816fa8a
 
19aed6d
816fa8a
19b91ce
4cfab62
816fa8a
52c6936
816fa8a
 
52c6936
816fa8a
52c6936
4cfab62
 
 
 
 
 
 
 
 
 
 
 
74f72af
 
 
 
 
 
 
 
 
 
 
8729c1d
4cfab62
 
 
816fa8a
4cfab62
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f530297
 
 
 
4cfab62
 
 
 
 
 
c1fc133
4cfab62
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
52c6936
 
 
 
4cfab62
 
 
52c6936
4cfab62
 
 
 
 
 
 
 
 
 
 
 
 
c1fc133
 
 
 
 
 
 
 
 
 
 
 
 
 
4cfab62
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
36900c7
 
 
 
4cfab62
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b35f959
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e174d2c
4cfab62
 
 
 
 
f530297
 
 
 
 
4cfab62
 
 
 
 
 
 
 
 
 
 
 
 
f530297
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
19aed6d
4cfab62
b35f959
72b6f27
 
b35f959
72b6f27
 
 
 
b35f959
52c6936
23088ad
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4cfab62
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
19aed6d
 
 
 
 
 
 
4cfab62
 
23088ad
 
 
 
74f72af
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
72b6f27
 
 
 
 
 
 
 
 
 
 
 
4cfab62
23088ad
 
 
72b6f27
19aed6d
74f72af
 
 
 
 
 
 
 
 
 
4cfab62
 
23088ad
4cfab62
 
 
 
 
 
 
 
 
 
 
23088ad
4cfab62
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
19aed6d
 
4cfab62
 
23088ad
 
 
 
 
 
19aed6d
4cfab62
19aed6d
4cfab62
 
 
 
 
 
19aed6d
 
 
 
4cfab62
 
 
 
 
 
 
 
74f72af
 
 
 
4cfab62
74f72af
 
 
 
 
 
 
 
 
 
 
 
4cfab62
 
 
 
 
72b6f27
 
4cfab62
 
 
 
 
b35f959
72b6f27
 
b35f959
72b6f27
 
 
 
 
 
 
b35f959
19aed6d
 
4cfab62
 
 
 
19b91ce
4cfab62
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8729c1d
4cfab62
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
19aed6d
4cfab62
 
 
 
23088ad
 
 
 
8729c1d
 
4cfab62
 
 
 
 
 
 
 
 
52c6936
 
c1fc133
 
 
4cfab62
e174d2c
4cfab62
 
 
 
 
 
 
 
8729c1d
 
 
4cfab62
8729c1d
4cfab62
 
 
 
 
 
 
 
 
c1fc133
 
 
4cfab62
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
23088ad
 
 
 
 
 
 
 
4cfab62
 
23088ad
4cfab62
 
 
 
 
 
 
 
 
 
 
c1fc133
52c6936
c1fc133
 
 
52c6936
c1fc133
 
52c6936
4cfab62
 
 
 
23088ad
4cfab62
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
23088ad
e174d2c
4cfab62
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
23088ad
 
 
 
 
 
 
 
 
 
4cfab62
 
 
23088ad
 
4cfab62
23088ad
4cfab62
 
 
 
 
 
 
 
 
 
23088ad
4cfab62
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8729c1d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4cfab62
 
c1fc133
4cfab62
 
23088ad
4cfab62
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b35f959
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4cfab62
 
 
 
 
 
c1fc133
4cfab62
 
 
 
 
 
 
19aed6d
 
4cfab62
 
 
 
 
 
 
 
 
 
 
 
 
 
 
19b91ce
 
19aed6d
4cfab62
c1fc133
52c6936
 
 
c1fc133
52c6936
c1fc133
 
 
52c6936
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c1fc133
 
 
 
 
 
 
 
 
 
 
 
52c6936
 
 
 
 
 
 
 
 
 
c1fc133
 
 
 
 
52c6936
 
 
4cfab62
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b35f959
 
 
 
 
 
 
 
 
 
 
f530297
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b35f959
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4cfab62
 
 
 
 
 
 
 
 
 
 
b35f959
 
 
 
 
 
 
 
 
 
4cfab62
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
23088ad
 
 
 
 
 
 
 
 
 
4cfab62
 
 
 
 
 
 
 
 
23088ad
4cfab62
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
19aed6d
c1fc133
19aed6d
c1fc133
 
 
 
 
8729c1d
 
1d4419b
 
 
 
 
 
19aed6d
 
 
 
 
 
 
 
 
c1fc133
19aed6d
 
 
 
 
 
 
 
 
 
 
 
 
 
82cdb59
 
19aed6d
 
 
 
 
 
 
 
 
 
19b91ce
19aed6d
 
 
 
 
 
 
 
 
 
 
4cfab62
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
23088ad
4cfab62
 
 
 
 
19aed6d
4cfab62
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
19aed6d
4cfab62
 
 
 
 
19b91ce
 
4cfab62
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8729c1d
4cfab62
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
19aed6d
 
 
 
 
 
 
 
 
 
 
 
4cfab62
 
 
 
 
23088ad
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e174d2c
 
 
 
 
 
 
 
 
 
 
 
4cfab62
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
23088ad
 
 
 
 
 
 
 
 
4cfab62
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
23088ad
4cfab62
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
23088ad
 
4cfab62
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
23088ad
 
 
 
 
 
 
 
4cfab62
 
 
 
 
23088ad
4cfab62
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e174d2c
4cfab62
 
 
 
 
 
 
 
 
e174d2c
4cfab62
 
 
 
 
 
 
 
19aed6d
4cfab62
 
 
 
19aed6d
23088ad
19b91ce
 
 
 
 
4cfab62
 
 
23088ad
19b91ce
 
 
 
 
 
 
 
 
 
 
 
 
 
 
19aed6d
 
 
 
 
52c6936
 
 
 
 
19aed6d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f530297
 
 
 
 
19b91ce
19aed6d
 
 
 
 
f530297
19aed6d
f530297
19aed6d
 
 
f530297
 
 
19aed6d
 
 
19b91ce
 
 
 
 
 
f530297
19b91ce
f530297
19b91ce
 
 
f530297
19b91ce
 
 
 
19aed6d
 
 
 
 
 
 
 
 
 
 
 
 
 
4cfab62
 
 
 
 
 
 
 
 
 
 
 
 
23088ad
4cfab62
 
 
 
 
23088ad
4cfab62
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
23088ad
4cfab62
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f530297
dec006b
f530297
 
 
 
 
 
 
 
 
dec006b
 
 
 
 
 
 
f530297
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dec006b
 
 
 
 
f530297
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4cfab62
ce9586e
 
 
 
 
 
 
4cfab62
 
 
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
import PanelToggleIcon from "../shell/PanelToggleIcon";
import "../styles/wave46/rail-select.css";
// ⭐ W50-T09 (owner instruction 10) β€” the data rail's row metrics. TWO IMPORTERS, deliberately:
// `home/HomePage.tsx` side-effect imports this same sheet, because the database glyph rule it
// carries paints on the Home route, which never loads the grid chunk. Do not "tidy" either one
// away β€” a stylesheet that nothing on the route imports does nothing at all.
import "../styles/wave50/rail.css";
import "../styles/wave61/rails.css";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { RailHeaderIcons, useNarrowRailFold, useRailHeaderSlot } from "../shell/railHeader";
import { useRailSelection } from "../ui/useRailSelection";
import { IconTile } from "../ui/IconTile";
import { ConnectorMark } from "../connectors/brandMarks";
import type { ReactNode } from "react";
import type { KeyboardEvent as ReactKeyboardEvent } from "react";
import { AnchoredOverlay } from "./OverlaySurface";
import FolderNameDialog, { FOLDER_NAME_MAX } from "../home/FolderNameDialog";
import { moduleFolderPath } from "../home/homeModel";
import { EXPORT_FORMATS, EXPORT_LABELS, exportSelectionKey } from "./export";
import type { ExportFormat } from "./export";
import type {
  DisplayMode,
  GridFolder,
  SavedView,
  Viewer,
} from "./types";
import {
  isModeFrozen,
  isUndeletableView,
  mayEditView,
  mayFileView,
  mayToggleViewLock,
  viewDisplayMode,
  viewDisplayName,
  viewScopedOutMark,
} from "./types";
import {
  CREATABLE_MODES,
  DatabaseMark,
  MODE_LABELS,
  MODE_TONE,
  SHARE_SHAPE,
} from "./iconShapes";
import { FolderMark, LockMark, MenuLabel, ModeIcon, ToneModeIcon } from "./icons";
/**
 * ⭐⭐ WAVE 41 Β· T38 (owner instruction 17) β€” the stale-workspace signal, from the shared
 * contract module rather than through a new prop.
 *
 * ⚠ `../apiContract` IS NOT `shell/**`. The host-neutral rule this file states and obeys forbids
 * `customer-grid/**` importing `shell/**`; the event-name/dispatch contract is a sibling of the
 * grid, and `FormInterface.tsx` and `ImportDialog.tsx` already reach it the same way.
 */
// ⭐ W47-T11 adds `TOAST_EVENT` on the same channel: a nesting this rail refuses is a sentence
// the user has to read, and the frame already listens here for exactly that.
import { TOAST_EVENT, WORKSPACE_STALE_EVENT, signal } from "../apiContract";
import { ITEM_DELETED_EVENT, itemDeleted, lendWorkspacePeek, openExistingItem, useItemDeletions } from "../starred/starredApi";
// C6 / R52 shares only the address's folder stratum with chrome; dataPath.ts still owns grid paths.
import { readDataAddress } from "../shell/nav";
import type { DeletedItem } from "../starred/starredApi";
import { ROOT_FOLDER_ID } from "./folders";
import {
  folderPath,
  CUSTOM_ORIGIN_KEY,
  dataDatabaseOriginKey,
  dataDatabaseConnector,
  dataOriginLabel,
  groupDataDatabases,
  levelAt,
  pathStorageKey,
  resolveStoredPath,
} from "./dataPath";
import type { DataDatabase, DataDatabaseFolder } from "./dataPath";
// ⭐ W32-T23 (owner item 17) β€” THE BELL, from the shared layer rather than redrawn here.
// The alert row wore `cohortAdd` (a LIST with a plus), which names "add to a cohort" on the
// one row that creates an ALERT β€” a borrowed mark is a small lie a menu repeats every time
// it opens, and `icons.tsx`'s own `upload` header records the last time this bit.
// ⚠ `MenuLabel` takes a NODE for exactly this case: a mark that is not part of the grid's
// menu vocabulary. The Inbox module's header wears the SAME component (`ui/icons.BellIcon`),
// so the bell that opens the Inbox and the bell that fills it cannot drift apart.
import { BellIcon, StarIcon } from "../ui/icons";
/**
 * ⭐⭐ W50-T27 (contract C4) β€” THE TRASH PANEL'S ONE MOUNT IN THE PRODUCT.
 *
 * W50-T26 shipped `views-trash/TrashPanel.tsx` complete and self-contained and mounted it
 * NOWHERE: this file belongs to another lane, so the rail entry was a declared handover, and
 * `platform/verify_shared_views.py` carried a RED-until-wired leg naming exactly this import
 * plus a `<TrashPanel` element. Both halves are below.
 *
 * β›” THE BRIEFED ANCHOR DID NOT EXIST. The handover names "the database `...` menu" as though
 * one were already here; it is not. This file has exactly three ellipsis controls β€” the DATA
 * navigator's folder menu, the VIEW folder menu and the per-view menu β€” and the only control on
 * a database ROW (`.shell-dots`) is rendered by `shell/Shell.tsx` through `renderDatabaseActions`,
 * which is not this fence. So the database-level menu is CREATED here, on the view path row,
 * which is the one row that is about the open database rather than about a view or a folder.
 *
 * β›” A STATIC IMPORT, DELIBERATELY. `TrashPanel` imports only `./trashApi` and `./trash.css`, and
 * this file already compiles into the grid chunk that the panel would be lazily fetched from the
 * moment the rail is on screen β€” a `lazy()` here would buy a Suspense boundary and no split worth
 * having. The measured cost is in the ticket's handoff, because `tsc` cannot see chunk shape
 * ([[tsc-cannot-see-a-broken-code-split]]).
 */
import { TrashPanel } from "../views-trash/TrashPanel";
import { DatabaseFieldsDrawer } from "../settings/ManageDatabase";
/** Folder nesting shares the stamped parent sink and skips its view-only watchdog. */
import { editOutbox, peekWorkspace } from "./apiBridge";
import type { SurfaceScope } from "./apiBridge";
// ⚠ `SHARED_FOLDER_ID` is no longer imported: W34-T25 replaced both of its call sites with
// `isSyntheticFolderId`, and `noUnusedLocals` turns a leftover import into a build error rather
// than into dead weight. The constant itself is still exported and still used by `folders.ts`.
import {
  folderDropIntent,
  folderNesting,
  groupByFolder,
  isSyntheticFolderId,
  // S85-T33: the verdict-level twin, for doors that already hold `mayEdit`. The drag site asks
  // `types.ts::mayFileView`; both must give one answer (verify_folders.py runs the parity).
  mayFileView as mayFileVerdict,
  mayNestFolder,
  reorderFolderIds,
  // ⭐ W41-T35 β€” the SAME key function `groupByFolder` synthesises a shared group with, so the
  // icon map below cannot key one way while the grouping keys another.
} from "./folders";

/* ─────────────────────────────────────────────────────────────────────────────────────────
   Share-view ownership note for the create door.

   View creation now stays private and delegates audience/edit choices to the single Share view
   dialog. Keep this note aligned with that ownership boundary if the sharing surface changes.

   β›” WHY THE PATHS LIVE HERE AND NOT IN `icons.tsx`, stated so a later wave does not "tidy" it
   back: `icons.tsx` renders `MODE_SHAPES` from `iconShapes.ts`, which the glide CANVAS also
   paints β€” geometry with two painters belongs there. These three have exactly ONE call site,
   thirty lines below, and no canvas draws them. `LockMark` and `EyeOffIcon` already carry the
   same argument at their definitions ("paths are inline… no header ever draws this one").
   ⚠ The wave-27 ownership map puts `iconShapes.ts` in session D's fence and leaves `icons.tsx`
   in NOBODY's; a one-call-site component in a file this session owns has zero collision risk,
   and the ask to settle `icons.tsx`'s owner is in the mailbox (C-3).

   The tone follows the STRENGTH of the grant β€” neutral for the private default, blue for the
   open one, green for the deliberate pick β€” and the paint comes from the shared pastel table,
   never a literal, so these can never be the one place in the product with its own colours.
   Outline-only, the register the owner set in 2026-07-29: "it doesn't have a full color, only
   the linings". */
/** head + shoulders, at `x`. One drawing, three uses β€” a second hand-drawn person is how two
 *  marks in one panel end up different heights. */
/* WAVE 20 item 18 (C-SHARE) β€” the system folder every view shared WITH you lands in until
   you file it somewhere of your own. It is the only folder id this component recognises by
   name, and as of wave 21 (item 9) it is DECLARED IN `folders.ts` beside the synthesis that
   produces it β€” a component-local copy of a contract id is a copy that can drift from the
   rule, and the rule is the half a gate can run. */

/**
 * ⭐ W40-T21 β€” THE SHARE GLYPH, drawn from `SHARE_SHAPE` rather than from a second copy of the
 * same paths.
 *
 * This component used to be three hand-written `<path>`s inline in the row below, and W40-T20
 * lifted that exact geometry into `iconShapes.ts` so the grid header's `aiosShared` canvas sprite
 * could paint it too. Leaving the copy here would mean the product carried TWO drawings of one
 * idea, one of which nothing forces to stay in step β€” the precise failure `iconShapes.ts`'s own
 * header calls out ("hand-copying every path into a template literal guarantees the header and
 * the panel eventually disagree"). Same viewBox, same 1.35 stroke as `shapeSource` paints the
 * canvas twin at, so a shared VIEW in this rail and a shared FIELD in a header are one mark.
 *
 * β›” NOT `LockMark`. A share is not one of DESIGN.md Β§4's three locks, and the padlock means a
 * lock (D-254 is the register row for what happens when one glyph carries both ideas).
 */
/**
 * ⭐ W47-T12 β€” how long the rail shows a folder re-parent the host has not confirmed yet.
 *
 * β›” DELIBERATELY NOT `ECHO_RECENT_MS` (120s), which is the window `folders.ts` holds a NAME or a
 * TOMBSTONE for. Those are corrections to a payload that is otherwise right; this is a structural
 * claim about where a folder lives, and if the host refuses it the rail is lying about the shape
 * of the tree for the whole window. Two minutes of that is unacceptable and six seconds is a
 * round trip with room to spare, so a nesting that took hangs on to its place and a nesting that
 * was refused snaps back while the host's own refusal sentence is still on screen.
 */
const NEST_HOLD_MS = 6_000;

// S85-T25: lend the workspace copy, so `openExistingItem` answers a view or database without a read.
lendWorkspacePeek((scope) => peekWorkspace(scope as SurfaceScope));
/** C1 refusal reasons that name a deleted view or member, so the next workspace read drops it. */
const DELETED_TARGET_CODES: readonly string[] = ["target_gone", "view_missing", "view_not_found"];

/**
 * S85-T33 (D-249, R30): THE ONE SENTENCE A REFUSED FOLDER MOVE CARRIES, or `null` to proceed.
 *
 * Every filing door asks here BEFORE it emits, never by reverting after (D-636): a revert-after
 * still leaves an `item_move` on the wire. The doors are the rail drop, the `...` menu's Move to,
 * a view created inside a folder, and the grid's `onItemMove` sink.
 *
 * β›” A READ-ONLY SHARE IS NOT REFUSED. S85-T33 retires W51-T35's R18 refusal: filing writes only
 * the receiver's own placement (`grid_events::_own_ids` admits every view in their rail) and never
 * the owner's view, so a person may drag a view out of "Shared with me" and it stays out.
 * What is left refused is a view that is neither shared with the viewer nor theirs to edit.
 */
export function viewMoveRefusal(view: SavedView, viewer?: Viewer): string | null {
  if (mayFileVerdict(view, mayEditView(view, viewer))) return null;
  return "Only views you can edit or that were shared with you can be moved.";
}

/**
 * S85-T33 (D-233): the scoped-out cohort mark, a funnel struck through. The server emptied this
 * view's filter for this reader, so the mark says why the view shows more rows than its owner's.
 * β›” Not `LockMark`: nothing here is locked, the filter is off.
 */
export function ScopedOutMark({ size = 13 }: { size?: number }) {
  return (
    <svg width={size} height={size} viewBox="0 0 16 16" aria-hidden>
      <path
        d="M2.6 3.4h10.8L9.2 8.3v4.1l-2.4 1.2V8.3z"
        fill="none"
        stroke="currentColor"
        strokeWidth={1.35}
        strokeLinejoin="round"
      />
      <path
        d="M2.8 13.2 13.2 2.8"
        fill="none"
        stroke="currentColor"
        strokeWidth={1.35}
        strokeLinecap="round"
      />
    </svg>
  );
}

function ShareMark({ size = 13 }: { size?: number }) {
  return (
    <svg width={size} height={size} viewBox="0 0 16 16" aria-hidden>
      {SHARE_SHAPE.map((s) =>
        s.fill ? (
          <path key={s.d} d={s.d} fill="currentColor" />
        ) : (
          <path
            key={s.d}
            d={s.d}
            fill="none"
            stroke="currentColor"
            strokeWidth={1.35}
            strokeLinecap="round"
            strokeLinejoin="round"
          />
        )
      )}
    </svg>
  );
}

/*
 * β›” `DatabaseMark` STOOD HERE AND HAS MOVED TO `iconShapes.ts` (W50-T09, ruling R16).
 *
 * R16 puts the outlined database glyph on EVERY listing of a database, which now includes Home.
 * This file compiles into `CustomerGrid-*.js` (1.5 MB), so a Home import of the component from
 * here would have pinned the entire grid to the Home route β€” and `tsc` cannot see that failure
 * ([[tsc-cannot-see-a-broken-code-split]]). Its geometry (`DATABASE_SHAPE_PATHS`) was already in
 * the shared `icons-*.js` chunk Home loads anyway, so the component went to the geometry rather
 * than the geometry to the component. The drawing is unchanged, byte for byte.
 */

/** What the rail's share mark says, once it has been decided that there is one to show. */
export interface ViewShareMark {
  title: string;
  ariaLabel: string;
}

/**
 * ⭐⭐ W40-T21 (owner instruction 2, contract C1) β€” DOES THIS VIEW WEAR THE SHARE MARK, AND WHAT
 * DOES IT SAY?
 *
 * Owner, verbatim: *"A shared View must show the shared/collaborative icon in EVERY account, not
 * only the recipient's. Normalize it regardless of who shares."* So the GLYPH is one glyph in both
 * accounts and the WORDS are what differ, which is why this returns copy rather than a boolean.
 *
 * β›” THE DISCRIMINATOR IS `owner`, AND IT IS AN EXISTING WIRE FIELD, not a new one.
 * `SavedView.owner` is declared as "whose view this is, WHEN IT IS NOT MINE", and
 * `grid_events.py::_granted_views` is its only producer β€” it stamps `shared` / `sharedRole` /
 * `owner` together on the RECIPIENT's leg of `table_workspace`'s merge and on nothing else. C1
 * adds the marker to the caller's OWN leg, where there is no `owner` to stamp because the view is
 * the caller's. So:
 *
 *   Β· `shared` + `owner`  β†’ it reached me by grant. Somebody shared it WITH me.
 *   Β· `shared`, no `owner` β†’ it is mine and I have shared it OUT.
 *   Β· no `shared`          β†’ no mark at all, in either account.
 *
 * β›” THE RECEIVER'S SENTENCE IS NOT REUSED FOR THE OWNER, and that is the trap this ticket exists
 * to avoid: `cg-view-shared`'s shipped copy reads "Shared with you by {owner}", so pointing it at
 * the owner's own leg ships "Shared with you by Farhan" to Farhan. The owner's string is written
 * fresh and reads as sharing OUT.
 *
 * β›” NO ROLE SENTENCE ON THE OWNER'S SIDE. `sharedRole` describes a GRANT β€” what somebody else let
 * me do with their object β€” and it is absent and meaningless on a view I own (`SavedView`'s own
 * note: "on a view that is MINE this is absent and means nothing at all"). Appending "You can edit
 * it." to my own view would be the product telling me something it does not know.
 *
 * β›”β›” WAVE 40 QA β€” THIS FUNCTION SHIPPED READING THE WRONG KEY, AND THAT MADE OWNER
 * INSTRUCTION 2 A NO-OP. It was written expecting C1 to REDEFINE `shared` to mean "this view
 * has grants", and its own note here said it was "safe to ship ahead of the server half" because
 * "nothing stamps `shared` without `owner` today". The server half then landed differently:
 * AM-5 keeps `shared` meaning "granted TO me" and introduces `hasShares` / `sharedOut` as new
 * keys. `platform/core/grid_events.py` writes `shared` on exactly two lines, both inside
 * `_granted_views`, both after `if owner == uname: continue`. So the owner branch below stayed
 * unreachable, a whole-tree grep for `hasShares` returned ZERO hits in `src/`, and the person
 * who shared a view saw no mark and no tooltip. Both lanes passed their own ticket.
 *
 * ⭐ THREE BRANCHES NOW, AND THE THIRD IS NOT A TIDY-UP. `hasShares` does NOT imply
 * `sharedRole`: a view living both in the legacy `__shared__` bucket and in the grant registry
 * reaches its recipient with `hasShares` alone, because the bucket leg outranks the stamped
 * copy. Lane A wrote that warning down against this very function. Without the neutral branch
 * that reader would be told "You shared this view", which they did not.
 *
 * Pure, exported and total, so the decision can be executed rather than eyeballed: the JSX below
 * consumes it and holds no second copy of the rule.
 */
export function viewShareMark(
  view: Pick<
    SavedView,
    "shared" | "owner" | "sharedRole" | "name" | "hasShares" | "sharedOut"
  >
): ViewShareMark | null {
  // The MARK is `hasShares`, the viewer-independent fact. `shared` is kept in the test so a
  // recipient still gets a mark on any leg that stamps the grant without the marker.
  if (!view.hasShares && !view.shared) return null;
  if (view.shared && view.owner) {
    return {
      title:
        `Shared with you by ${view.owner}.` +
        (view.sharedRole === "edit"
          ? " You can edit it."
          : " You can view it, not change it."),
      ariaLabel: `${view.name}, shared with you by ${view.owner}`,
    };
  }
  if (view.sharedOut) {
    return {
      title: "You shared this view. Anyone you gave access to can open it.",
      ariaLabel: `${view.name}, shared by you`,
    };
  }
  // `hasShares` with nothing beside it: this view has grants and this payload does not say
  // whose or on what terms. Say only what is known. Claiming either of the two sentences
  // above would tell somebody something false about their own access.
  return {
    title: "This view is shared.",
    ariaLabel: `${view.name}, shared`,
  };
}

interface ViewSidebarProps {
  scope?: SurfaceScope;
  /** Metadata availability can withhold view writes without changing folder permission. */
  readOnly?: boolean;
  folderReadOnly?: boolean;
  /** Granted databases live in this secondary navigator, never in the global shell rail. */
  databases?: readonly DataDatabase[];
  activeDatabaseKey?: string;
  databaseFolders?: readonly DataDatabaseFolder[];
  onSelectDatabase?: (key: string) => void;
  onDatabaseMove?: (key: string, folderId: string | null) => void;
  onDatabaseFolderRename?: (folderId: string, name: string) => void;
  onDatabaseFolderDelete?: (folderId: string) => void;
  renderDatabaseActions?: (database: DataDatabase) => ReactNode;
  databaseCreateControl?: ReactNode;
  /** S72-T63 / C3: a grid mounted at an address. The rail then never reads `location.hash`. */
  hosted?: boolean;
  views: SavedView[];
  /**
   * ⭐⭐ W50-T11 / D-592 β€” IS THE WORKSPACE STILL IN FLIGHT?
   *
   * β›” AN EMPTY `views` IS TWO DIFFERENT FACTS AND THE RAIL COULD NOT TELL THEM APART. Before
   * `/workspace` answers, `payload` is absent and `views` is `[]`; after it answers, `[]` means
   * a database with no saved views. The rail drew the same nothing for both, so a slow answer
   * read as "there is nothing here" β€” and on a cold or degraded connection that window is not
   * a frame, it is the whole experience. The host already computes the predicate
   * (`CustomerGrid.tsx::workspaceLoading`); this is that one answer, passed rather than
   * re-derived [[one-question-two-normalizers]].
   */
  loading?: boolean;
  activeViewId: string;
  saveState?: "saved" | "saving";
  onSelect: (id: string) => void;
  /** The create door persists a personal source; Share view owns every audience and role. */
  onCreate: (name: string, mode: DisplayMode) => void;
  onRename: (id: string, name: string) => void;
  /** Persist a view's description. "" is a real value β€” it clears it. */
  onNote: (id: string, note: string) => void;
  onDuplicate: (id: string) => void;
  onDelete: (id: string) => void;
  /** Cohorts this user can add to (owner item 6). Empty is fine β€” the menu then only offers
   *  "New cohort…", which is how the first cohort gets created. */
  lists?: { id: string; name: string }[];
  /** Add the customers THIS view currently matches to a cohort. `cohortId` empty = create one
   *  called `name`. The view need not be the active one β€” the caller re-runs the engine for it. */
  onAddToList?: (viewId: string, cohortId: string, name: string) => void;
  /**
   * ⭐ WAVE 21 item 11 (ruling R10) β€” open "Select from file…" for the ACTIVE view.
   *
   * β›” NO ARGUMENTS, and that is the contract rather than an omission. The dialog matches
   * over the rows the GRID holds, which are the active view's; passing a view id here
   * would invite a caller to match one view's list against another's rows and report the
   * difference as missing records. The menu switches views first (see its own note) so
   * this can stay a verb with one subject.
   */
  onSelectFromFile?: () => void;
  /** ⭐ WAVE-29 T25 (owner item 6) β€” open the Import dialog. Supplied only where records may be
   *  added, so a locked database simply has no such row in its menu. */
  onImport?: () => void;
  /**
   * Item 12 (contract C-LOCK) β€” lock a view to a cohort, or `null` to unlock.
   *
   * ⚠ This menu is the ONLY emitter of `cohortLock` in the client. Optional so the rail still
   * compiles and renders wherever the host has not accepted the key β€” the same posture every
   * other optional action here takes, and the reason a half-deployed wave degrades to "the
   * action is absent" rather than to "the action silently does nothing".
   */
  onCohortLock?: (viewId: string, cohortId: string | null) => void;
  /**
   * The TENANT'S today (wave-2 item 4) β€” the payload's `today` string VERBATIM, seeding the
   * default cohort name `<view name> Β· <YYYY-MM-DD>`. Never the browser clock: a viewer a day
   * ahead of the tenant would stamp a cohort with a date the host's own data denies
   * ([[date-window-vocabulary]]). Absent = the name seeds without a date.
   */
  today?: string;
  /**
   * Wave-7 item W2 (contract C2) β€” export THIS view's current matches (filters + sorts,
   * visible fields in display order), generated client-side. Absent on tables where the
   * client does not hold the rows (server-windowed), so the entry never lies.
   */
  onExport?: (viewId: string, format: ExportFormat) => void;
  /** C3 bulk-export path. The caller sends these visible View ids to the server, which evaluates
   * every tab before the browser gives its result to the one XLSX writer. */
  onExportXlsxViews?: (viewIds: string[]) => void;
  /**
   * ⭐ W50-T12 / R11 β€” THE HALF THAT TALKS TO THE SERVER, AND IT RUNS BEFORE THE CLICK.
   *
   * `onExportXlsxViews` above is now purely a DOWNLOAD: it hands over an already-built workbook
   * inside the click gesture and awaits nothing. This is the round trip that used to sit inside
   * it. The pane calls it when the export panel opens and again whenever the ticked set changes,
   * so the file is ready by the time anyone presses the button.
   *
   * β›” SUPPLY BOTH OR NEITHER. With this absent the button below can never become ready and the
   * pane offers a control that refuses forever.
   */
  onPrepareXlsxViews?: (viewIds: string[]) => void;
  /** The key of the workbook that is BUILT AND WAITING, as `exportSelectionKey` names it, or "".
   * The pane compares it with the key of what is currently ticked; equal means the button may be
   * armed, anything else means the selection has moved on and the build has not caught up. */
  xlsxExportReadyKey?: string;
  /** The server-visible saved Views accepted by C3's export endpoint. Rail-only projections
   * (for example an unsaved script result) remain out of the chooser. */
  exportableViewIds?: readonly string[];
  /**
   * Wave-8 I11c (contract C4) β€” folders. All of it is OPTIONAL: a caller that
   * passes no `folders` and no handlers renders exactly the pre-wave-8 flat rail,
   * which is what keeps the cohort page (and any future rail) from having to opt
   * into a feature it does not want.
   */
  folders?: GridFolder[];
  /** The folder a view belongs to RIGHT NOW β€” resolved by the caller through
   *  `resolveFolderId`, so a pending drag and a dangling ref are already handled
   *  before the rail sees them. */
  folderIdOf?: (viewId: string) => string | null;
  /** `parent` is the folder the new one goes inside; null means the top level. */
  onFolderCreate?: (name: string, parent?: string | null) => void;
  onFolderRename?: (folderId: string, name: string) => void;
  onFolderDelete?: (folderId: string) => void;
  onFolderDuplicate?: (folderId: string) => void;
  onItemMove?: (viewId: string, folderId: string | null) => boolean | void;
  /**
   * WAVE 20 item 19 (C-FOLDER-REORDER) β€” the folders, in the order the user just dragged
   * them into. The FULL list every time, never a delta: a partial order cannot say where an
   * unnamed folder went, and the host has to be able to stamp `order` on all of them.
   *
   * Optional like every other folder handler here: a caller that does not pass it gets a
   * rail with no folder drag at all, rather than a grip that lifts a folder and drops it
   * back β€” the posture this whole component takes toward an action nobody can honour.
   */
  onFolderReorder?: (order: string[]) => void;
  /**
   * ⭐ WAVE 27 Β· OWNER ITEM 5 (contract C7) β€” the rail's new VIEW order, whole.
   *
   * β›” REQUIRED, AND THE OPTIONAL VERSION OF THIS EXACT PROP IS WHY. `onFolderReorder` above
   * shipped optional in wave 20: its absence disabled the entire folder drag SILENTLY, every
   * gate stayed green, and folders simply would not move (the note at its call site in
   * `CustomerGrid` records it). A required prop fails `tsc` at the unmounted call site, which
   * is the only version of this rule a person cannot forget.
   */
  onViewReorder: (order: string[]) => void;
  /**
   * ⭐ WAVE 27 Β· OWNER ITEM 21 / RULING R14 β€” `viewId -> how many records match it RIGHT NOW`,
   * for the views that carry an alert. A view with no alert is ABSENT from this map, and that
   * absence is the whole display rule ("alert-on = badge-on").
   *
   * β›” REQUIRED, and `{}` is the honest empty. An optional prop would make "no alerts on this
   * table" and "the caller forgot to compute them" the same state on screen β€” which is the
   * shape wave 20's optional `onFolderReorder` shipped in, and it went unnoticed for a wave.
   * ⚠ ABSENT vs ZERO are DIFFERENT and both are real: absent = no alert, so no badge; `0` = an
   * alert on a view that currently matches nothing, which is exactly the case a user wants to
   * see. `!== undefined` rather than a truthiness test, for that reason.
   */
  alertCounts: Record<string, number>;
  /** ⭐ WAVE 33 Β· T14 (D-205) β€” for a counted view that got NO number, the sentence saying why.
   *  Never both: a row carries a count or a note, and `alertCounts` is checked first. */
  countNotes?: Record<string, string>;
  /* β›” `importantTotal` IS GONE (W35-T27, owner item 9). It carried W33-T16's summed badge at the
     top of this rail; the owner removed the count from everywhere except the view itself, so the
     prop has no reader and its memo in `CustomerGrid` went with it rather than being left to
     compute a value nobody renders [[artifact-with-no-importer]]. */
  /**
   * C4 as AMENDED 2026-07-28 β€” the folder-level bulk "Add to cohort". The caller
   * owns the arithmetic (it holds the engine); the rail owns the confirm.
   * `preview` must return the DEDUPED union plus anything it could not compute,
   * because the amendment is explicit that a partial union is never silent.
   */
  folderAddPreview?: (folderId: string) => {
    pids: number[];
    counted: number;
    skipped: { name: string; why: string }[];
  };
  onFolderAddToList?: (folderId: string, cohortId: string, name: string) => void;
  /**
   * Wave-9 contract C3 (I12) β€” who is looking, so the lock entry appears only for the view's
   * creator or an admin. Absent = the entry never appears (fail-closed), which is also what
   * every caller that has not wired `onToggleLock` gets.
   */
  viewer?: Viewer;
  /** C3 β€” freeze/unfreeze this view's DISPLAY MODE. The host re-checks the actor. */
  onToggleLock?: (viewId: string, locked: boolean) => void;
  /**
   * ⭐⭐ WAVE 32 Β· T24 (owner item 17, ruling R5, contract C4) β€” mark / unmark a view IMPORTANT.
   *
   * ⚠ OPTIONAL, matching every other host callback on this rail: the sidebar is host-neutral and
   * a host that has not wired it simply does not offer the row (rather than offering one that
   * throws). The behaviour is not silently degraded β€” the row is ABSENT, which a reader can see.
   */
  onToggleImportant?: (viewId: string, important: boolean) => void;
  /** Toolbar gear anchor. It opens this rail's actual ellipsis menu, never a copy of its actions. */
  actionAnchor?: HTMLElement | null;
  onActionAnchorConsumed?: () => void;
  /* wave17 R1 / C-LOCKV β€” `cohorts` and `onSelectCohort` are GONE from this component's
     surface. They carried the transient-lock selection for the retired Cohorts section; a
     locked view is now an ordinary member of `views` and is selected by `onSelect` like any
     other, which is the whole point of R1. */
  /** ⭐⭐ OWNER, 2026-08-19 β€” the grid chat's launcher lives in THIS row, beside the minimize
   *  control, exactly as the view agent's does. It was a text pill floating in the gap between
   *  this rail and the grid; the owner called it *"ugly as hell"* and named where it belongs:
   *  *"the same Navigation as the View navigation just beside its minimize icon"*.
   *  ⚠ Optional, and ABSENT rather than disabled when the surface has no database to chat about
   *  (embedded and Query bindings). */
  chatOpen?: boolean;
  /** β›” RENDERED AFTER the minimize toggle, never before it. W35-T28 made that control this
   *  row's FIRST child on purpose and `verify_grid_ux.py`'s views-rail scan asserts the ordering,
   *  so adding beside it is the instruction and re-ordering it would undo a shipped owner item to
   *  satisfy a new one β€” the same rule the view-agent robot follows.
   *  ⚠ IT IS AN ICON, NOT A LABEL. This row is a 26px control strip; the text pill is precisely
   *  what made the old launcher read as bolted on. The sentence it used to show ("Ask about this
   *  data") is now the `aria-label` AND the `title`, so nothing is lost to a screen reader or to
   *  a hover β€” moving a control must not quietly cost its name. */
  onToggleChat?: () => void;
}

interface DataDatabaseNavigatorProps {
  databases: readonly DataDatabase[];
  activeDatabaseKey: string;
  folders: readonly DataDatabaseFolder[];
  onSelect?: (key: string) => void;
  onMove?: (key: string, folderId: string | null) => void;
  onFolderRename?: (folderId: string, name: string) => void;
  onFolderDelete?: (folderId: string) => void;
  renderActions?: (database: DataDatabase) => ReactNode;
  createControl?: ReactNode;
  /** S72-T63 / C3: a hosted rail keeps its folder in state and never reads `location.hash`. */
  hosted?: boolean;
  /** Draws the rail's one header row (C4). It renders before the data tree, so it stays the rail's first child. */
  header?: (path: DataRailPath) => ReactNode;
  children: (path: { canBack: boolean; back: () => void }) => ReactNode;
}

/** The data layer's own place, or null when the view layer owns the header (a database is open). */
interface DataRailPlace {
  name: string;
  canBack: boolean;
  back: () => void;
  canForward: boolean;
  forward: () => void;
}

/** What the header reads: the data place, plus the data history Back the view layer falls back to. */
interface DataRailPath {
  place: DataRailPlace | null;
  canBack: boolean;
  back: () => void;
}

/** One Back control serves both View folders and the enclosing Data path. Keeping its drawing in
 * one component prevents the two path systems from growing separate buttons again. */
function PathBackButton({
  disabled,
  onClick,
}: {
  disabled: boolean;
  onClick: () => void;
}) {
  return (
    <button
      type="button"
      className="cg-path-history-button"
      aria-label="Back"
      title="Back"
      disabled={disabled}
      onClick={onClick}
    >
      <svg width="16" height="16" viewBox="0 0 16 16" fill="none" aria-hidden="true">
        <path
          d="M9.8 3.6 5.4 8l4.4 4.4"
          stroke="currentColor"
          strokeWidth="1.35"
          strokeLinecap="round"
          strokeLinejoin="round"
        />
      </svg>
    </button>
  );
}

/** ⭐ W46-T08 (owner instruction 26) - THE FORWARD TWIN, drawn beside `PathBackButton` and never
 *  apart from it, so the two halves of one history control cannot grow different shapes.
 *  β›” ITS LABEL IS "Forward", NEVER A SECOND "Back": `verify_w45_data_applications.py` counts the
 *  Back control's exact label literal and expects exactly one, so duplicating it is not a
 *  cosmetic slip. Two controls one pixel apart answering to the same name is also, plainly, wrong
 *  for anyone listening rather than looking.
 *  A disabled forward keeps `.cg-path-history-button:disabled`, which dims it rather than merely
 *  refusing the click: nothing ahead has to READ as nothing ahead. */
function PathForwardButton({
  disabled,
  onClick,
}: {
  disabled: boolean;
  onClick: () => void;
}) {
  return (
    <button
      type="button"
      className="cg-path-history-button"
      aria-label="Forward"
      title="Forward"
      disabled={disabled}
      onClick={onClick}
    >
      <svg width="16" height="16" viewBox="0 0 16 16" fill="none" aria-hidden="true">
        <path
          d="M6.2 3.6 10.6 8l-4.4 4.4"
          stroke="currentColor"
          strokeWidth="1.35"
          strokeLinecap="round"
          strokeLinejoin="round"
        />
      </svg>
    </button>
  );
}

type DataNavigatorLevel =
  | { kind: "root" }
  | { kind: "origin"; key: string }
  | { kind: "folder"; id: string }
  | { kind: "database"; key: string };

function dataNavigatorLevelKey(level: DataNavigatorLevel): string {
  if (level.kind === "root") return "root";
  if (level.kind === "origin") return `origin:${level.key}`;
  if (level.kind === "folder") return `folder:${level.id}`;
  return `database:${level.key}`;
}

/** S78-T02 (C1): the Amazon nav facts `/nav` serves. Optional, so a row without them is unchanged. */
type RailDatabase = DataDatabase & {
  group?: string;
  /** `at` null is a read "never synced"; an absent `sync` is unknown and shows nothing. */
  sync?: { at: string | null; empty: boolean | null };
};

/** Windows-style Data path rendered with the same segmented-path anatomy as the View path. */
function DataDatabaseNavigator({
  databases,
  activeDatabaseKey,
  folders,
  onSelect,
  onMove,
  onFolderRename,
  onFolderDelete,
  renderActions,
  createControl,
  hosted = false,
  header,
  children,
}: DataDatabaseNavigatorProps) {
  // S78-T02: declared inside the navigator, because verify_folders runs this function alone in a vm.
  /** C1's group order under the Amazon level. β›” A person reads these: no dash, sentence case. */
  const AMAZON_RAIL_GROUPS = ["Sales", "Fees and payouts", "Inventory", "Listings", "Advertising"];

  /** A table the mirror reads as 0 rows leaves the rail; Fields and Settings still list it. */
  function railListed(database: DataDatabase, activeKey: string): boolean {
    return (database as RailDatabase).sync?.empty !== true || database.key === activeKey;
  }

  /** The muted second line of an Amazon row, in plain words, or null when the fact is unknown. */
  function railSyncLine(database: DataDatabase): string | null {
    const sync = (database as RailDatabase).sync;
    if (!sync) return null;
    if (sync.at === null) return "Never synced";
    const at = new Date(sync.at);
    if (Number.isNaN(at.getTime())) return null;
    return `Synced ${at.toLocaleDateString("en-US", { month: "short", day: "numeric", year: "numeric" })}`;
  }

  /** The five groups in order, each with its databases, or null when no database has a group. */
  function railGroupSections(
    listed: readonly DataDatabase[]
  ): { sections: { label: string; databases: DataDatabase[] }[]; ungrouped: DataDatabase[] } | null {
    const grouped = new Map<string, DataDatabase[]>();
    const ungrouped: DataDatabase[] = [];
    for (const database of listed) {
      const group = (database as RailDatabase).group;
      if (group && AMAZON_RAIL_GROUPS.includes(group)) {
        grouped.set(group, [...(grouped.get(group) ?? []), database]);
      } else {
        ungrouped.push(database);
      }
    }
    if (grouped.size === 0) return null;
    return {
      sections: AMAZON_RAIL_GROUPS.filter((label) => grouped.has(label)).map((label) => ({
        label,
        databases: grouped.get(label) ?? [],
      })),
      ungrouped,
    };
  }

  const [draggedDatabase, setDraggedDatabase] = useState<string | null>(null);
  const [folderMenu, setFolderMenu] = useState<{ folderId: string; anchor: HTMLElement } | null>(
    null
  );
  const [renamingFolder, setRenamingFolder] = useState<string | null>(null);
  const [folderName, setFolderName] = useState("");
  // W46-T04 - the data layer's find box, the twin of the view layer's `viewQuery`. Local and
  // never persisted, for the same reason: a search is a moment, not a setting. It filters the
  // rows of the CURRENT level only (source groups and user folders at the root, databases
  // inside one), so a query never changes where you are standing.
  const [dataQuery, setDataQuery] = useState("");

  const dropDatabase = (event: React.DragEvent<HTMLElement>, folderId: string | null) => {
    if (!onMove) return;
    const key = event.dataTransfer.getData("application/x-aios-database") || draggedDatabase;
    if (!key) return;
    event.preventDefault();
    event.stopPropagation();
    setDraggedDatabase(null);
    onMove(key, folderId);
  };
  const dropProps = (folderId: string | null) =>
    onMove
      ? {
          onDragOver: (event: React.DragEvent<HTMLElement>) => {
            if (!event.dataTransfer.types.includes("application/x-aios-database")) return;
            event.preventDefault();
            event.stopPropagation();
            event.dataTransfer.dropEffect = "move";
          },
          onDrop: (event: React.DragEvent<HTMLElement>) => dropDatabase(event, folderId),
        }
      : {};

  const sourceGroups = useMemo(
    () => groupDataDatabases(databases.filter((database) =>
      !database.folderId && railListed(database, activeDatabaseKey))),
    [databases, activeDatabaseKey]
  );
  const parentOfDatabase = (database: DataDatabase): DataNavigatorLevel =>
    database.folderId
      ? { kind: "folder", id: database.folderId }
      : { kind: "origin", key: dataDatabaseOriginKey(database) };
  const levelsForFolder = (id: string): DataNavigatorLevel[] =>
    moduleFolderPath({ folders }, id).map((folder) => ({ kind: "folder", id: folder.id }));
  const levelsForDatabase = (database: DataDatabase): DataNavigatorLevel[] => [
    { kind: "root" },
    ...(database.folderId ? levelsForFolder(database.folderId) : [parentOfDatabase(database)]),
    { kind: "database", key: database.key },
  ];
  const levelsForAddress = (): DataNavigatorLevel[] => {
    const database = databases.find((candidate) => candidate.key === activeDatabaseKey);
    const folder = hosted ? undefined : readDataAddress().folder;
    if (folder && folders.some((candidate) => candidate.id === folder)) {
      return [
        { kind: "root" },
        ...levelsForFolder(folder),
        ...(database ? [{ kind: "database" as const, key: database.key }] : []),
      ];
    }
    return database ? levelsForDatabase(database) : [{ kind: "root" }];
  };
  const [dataPathState, setDataPathState] = useState<{
    levels: DataNavigatorLevel[];
    at: number;
  }>(() => {
    const levels = levelsForAddress();
    return { levels, at: levels.length - 1 };
  });
  const activePathKey = JSON.stringify(levelsForAddress().map(dataNavigatorLevelKey));
  const activeDataKey = useRef(activePathKey);
  if (activeDataKey.current !== activePathKey) {
    // The Data navigator remains mounted across database changes. Restore its exact source path
    // during render so the newly selected database can never commit under the previous source or
    // folder for one frame; an effect would run after that stale frame had already painted.
    activeDataKey.current = activePathKey;
    const levels = levelsForAddress();
    setDataPathState({ levels, at: levels.length - 1 });
  }
  const seenAddressFolder = useRef<string | undefined>(undefined);
  useEffect(() => {
    // C3: a hosted rail has no address to follow, so it never listens to the page's hash.
    if (hosted) return;
    const syncAddressFolder = () => {
      const levels = levelsForAddress();
      const addressedFolder = [...levels].reverse().find((level) => level.kind === "folder")?.id;
      seenAddressFolder.current = addressedFolder;
      setDataPathState((current) => {
        const standing = current.levels[current.at];
        const standingFolder = standing?.kind === "folder" ? standing.id
          : standing?.kind === "database"
            ? current.levels.slice(0, current.at).reverse().find((level) => level.kind === "folder")?.id
            : undefined;
        // A view-only hash change must not reset history when the rail is already in this folder.
        if (addressedFolder === standingFolder) return current;
        return { levels, at: levels.length - 1 };
      });
    };
    // Folder metadata may arrive after mount. Resolve it once without undoing later rail browsing.
    const folder = readDataAddress().folder;
    if (folder && folder !== seenAddressFolder.current
      && folders.some((candidate) => candidate.id === folder)) syncAddressFolder();
    window.addEventListener("hashchange", syncAddressFolder);
    return () => window.removeEventListener("hashchange", syncAddressFolder);
  }, [activeDatabaseKey, databases, folders, hosted]);
  const dataLevel = dataPathState.levels[dataPathState.at] ?? { kind: "root" as const };
  const canDataBack = dataPathState.at > 0;
  /** W46-T08: the levels array was ALREADY an index into history and `pushDataLevel` already
   *  truncates anything ahead, so Forward here is one derived boolean, not a second state
   *  machine beside this one. */
  const canDataForward = dataPathState.at < dataPathState.levels.length - 1;
  const pushDataLevel = (level: DataNavigatorLevel) => {
    setDataPathState((current) => ({
      levels: [...current.levels.slice(0, current.at + 1), level],
      at: current.at + 1,
    }));
  };
  const stepDataLevel = (delta: number) => {
    setDataPathState((current) => {
      const at = current.at + delta;
      return at < 0 || at >= current.levels.length ? current : { ...current, at };
    });
  };
  // Wave 44 QA / owner ruling: an address is a sequence of exact destinations. A joined label
  // wired only to Back looks like a path but cannot do what a Windows path does.
  const visitDataLevel = (level: DataNavigatorLevel) => {
    if (dataNavigatorLevelKey(level) === dataNavigatorLevelKey(dataLevel)) return;
    pushDataLevel(level);
  };
  // C4 (R89): the header names only the current level, never its path; levels remain history.
  const dataLevelLabel = (level: DataNavigatorLevel): string => {
    if (level.kind === "root") return "All databases";
    if (level.kind === "origin") return dataOriginLabel(level.key);
    if (level.kind === "folder")
      return folders.find((folder) => folder.id === level.id)?.name ?? "Folder";
    return databases.find((database) => database.key === level.key)?.label ?? "Database";
  };
  const openDatabase = (database: DataDatabase) => {
    if (database.externalHref) return;
    // HOTFIX 2026-09-24: open first, check second. W61-T22's existence read took ~5 s on the
    // store and the click waited for it; the shell rail already commits before the check (S65-T09).
    visitDataLevel({ kind: "database", key: database.key });
    onSelect?.(database.key);
    void openExistingItem({ kind: "database", id: database.key }, () => {});
  };
  const pathDatabaseRow = (database: DataDatabase) => {
    const active = database.key === activeDatabaseKey;
    const draggable = !!onMove && !database.protected && database.managedBy !== "loopable";
    const syncLine = railSyncLine(database);
    const content = (
      <>
        <span className="cg-db-mark">
          <IconTile icon={database.icon} surface="rail"><DatabaseMark size={16} /></IconTile>
        </span>
        <ConnectorMark connector={dataDatabaseConnector(database)} size={16} className="lp-source-mark" />
        {syncLine ? (
          // S78-T02 (R11): the true last sync as a quiet second line, the view rows' own pair.
          <span className="cg-view-text">
            <span className="cg-fold-name">{database.label}</span>
            <span className="cg-view-desc" data-rail-sync>{syncLine}</span>
          </span>
        ) : (
          <span className="cg-fold-name">{database.label}</span>
        )}
        {database.locked ? (
          <span
            className="cg-data-database-lock"
            role="img"
            aria-label={`${database.label}, locked database`}
            title="Locked database. Records are managed by its source; fields remain editable."
          >
            <LockMark size={12} />
          </span>
        ) : null}
      </>
    );
    return (
      <div
        key={database.key}
        className={
          "cg-fold cg-data-database" +
          (active ? " is-active" : "") +
          (draggedDatabase === database.key ? " is-dragging" : "")
        }
        draggable={draggable}
        onDragStart={(event) => {
          event.dataTransfer.setData("application/x-aios-database", database.key);
          event.dataTransfer.effectAllowed = "move";
          setDraggedDatabase(database.key);
        }}
        onDragEnd={() => setDraggedDatabase(null)}
      >
        <div className="cg-fold-head">
          {database.externalHref ? (
            <a
              className="cg-fold-toggle"
              href={database.externalHref}
              target="_blank"
              rel="noreferrer"
              aria-label={`Open ${database.label}`}
            >
              {content}
            </a>
          ) : (
            <button
              type="button"
              className="cg-fold-toggle"
              aria-current={active ? "page" : undefined}
              aria-label={`Open database ${database.label}`}
              onClick={() => openDatabase(database)}
            >
              {content}
            </button>
          )}
          {renderActions?.(database)}
        </div>
      </div>
    );
  };

  // CustomerGrid also renders this sidebar in embedded/query surfaces. Keep those surfaces'
  // existing View-only navigator when the shell has not supplied a database contract.
  if (databases.length === 0 || !activeDatabaseKey || !onSelect) {
    return (
      <>
        {header?.({ place: null, canBack: false, back: () => undefined })}
        {children({ canBack: false, back: () => undefined })}
      </>
    );
  }

  const dataNeedle = dataQuery.trim().toLowerCase();
  const matchesNeedle = (label: string) =>
    !dataNeedle || label.toLowerCase().includes(dataNeedle);
  const levelMatches = (
    dataLevel.kind === "origin"
      ? sourceGroups.find((group) => group.key === dataLevel.key)?.databases ?? []
      : dataLevel.kind === "folder"
        ? databases.filter((database) => database.folderId === dataLevel.id)
        : []
  ).filter((database) => matchesNeedle(database.label));
  const levelSourceGroups = sourceGroups.filter((group) => matchesNeedle(group.label));
  const levelFolders = folders.filter((folder) =>
    (dataLevel.kind === "root" || dataLevel.kind === "folder")
    && (folder.parent ?? null) === (dataLevel.kind === "folder" ? dataLevel.id : null)
    && matchesNeedle(folder.name));
  // S78-T02 (C1): only the Amazon level groups by job. Every other origin stays one flat list.
  const railSections = dataLevel.kind === "origin"
    && sourceGroups.find((group) => group.key === dataLevel.key)?.connector === "amazon_sp"
    ? railGroupSections(levelMatches)
    : null;
  // The flat list keeps what no group claims, so a grouped database is drawn exactly once.
  const levelDatabases = railSections ? railSections.ungrouped : levelMatches;
  // β›” A static heading, never a fold: the Data rail is list-replacing (verify_w44 refuses a
  // disclosure tree), so a group is the rail's existing quiet section, `.cg-rail-section`.
  const railGroupRow = (section: { label: string; databases: DataDatabase[] }) => (
    <div key={section.label} className="cg-rail-section cg-data-group" role="group"
      aria-label={`${section.label}, ${section.databases.length} databases`}
      data-rail-group={section.label}>
      <div className="cg-fold-head">
        <span className="cg-view-desc">{section.label}</span>
      </div>
      {section.databases.map(pathDatabaseRow)}
    </div>
  );
  const pathFolderRow = (folder: DataDatabaseFolder) => {
    const members = databases.filter((database) => database.folderId === folder.id);
    const childFolders = folders.filter((child) => child.parent === folder.id);
    const connectors = new Set(members.map(dataDatabaseConnector));
    const connector = connectors.size === 1 ? [...connectors][0] : null;
    return (
      <div key={folder.id} className="cg-fold cg-data-user-folder" {...dropProps(folder.id)}>
        <div className="cg-fold-head">
          <button type="button" className="cg-fold-toggle" aria-label={`Open folder ${folder.name}`}
            onClick={() => pushDataLevel({ kind: "folder", id: folder.id })}>
            <IconTile surface="rail">
              {connector && connector !== "loopable"
                ? <ConnectorMark connector={connector} size={16} className="lp-source-mark" />
                : <FolderMark size={16} />}
            </IconTile>
            <span className="cg-fold-name">{folder.name}</span>
            <span className="cg-fold-count">{members.length + childFolders.length}</span>
          </button>
          {onFolderRename || onFolderDelete ? (
            <button type="button" className="cg-view-more" aria-label={`Actions for ${folder.name}`}
              aria-haspopup="menu" onClick={(event) => {
                setFolderMenu({ folderId: folder.id, anchor: event.currentTarget });
                setRenamingFolder(null);
                setFolderName(folder.name);
              }}>Β·Β·Β·</button>
          ) : null}
        </div>
      </div>
    );
  };

  // C4: the data layer hands the header its place; at the database level the view layer owns it.
  const dataPlace: DataRailPlace | null = dataLevel.kind === "database" ? null : {
    name: dataLevelLabel(dataLevel),
    canBack: canDataBack,
    back: () => stepDataLevel(-1),
    canForward: canDataForward,
    forward: () => stepDataLevel(1),
  };

  return (
    <>
    {header?.({ place: dataPlace, canBack: canDataBack, back: () => stepDataLevel(-1) })}
    <div className="cg-data-tree" data-data-path-tree data-data-path-history>

      {/* ⭐ W46-T04 (owner instruction 12) - THE CREATE DOOR AND THE FIND BOX BELONG TO EVERY
          DATA LEVEL, not to the root alone. The door used to render under
          `dataLevel.kind === "root"`, so drilling into a source group or a user folder left the
          rail with rows and nothing else; the person could see two databases and had no way to
          make a third without walking back out.
          β›” THE GUARD IS `!== "database"`, NOT "always": at the database level this component
          hands off to the view layer through `children`, and that layer draws its OWN
          "+ Create new…" and find box. Rendering here as well would put two of each on one
          screen. Same classes as the view layer's pair (`cg-data-create` wraps the host's
          control; `cg-find-view` is the view layer's own box) because the two layers must be
          indistinguishable in this row, and lookalike classes drift apart. */}
      {dataLevel.kind !== "database" && createControl ? (
        <div className="cg-data-create">{createControl}</div>
      ) : null}
      {dataLevel.kind !== "database" ? (
        <div className="cg-find-view">
          <svg
            className="cg-find-view-icon"
            width="14"
            height="14"
            viewBox="0 0 16 16"
            fill="none"
            aria-hidden="true"
          >
            <circle cx="7" cy="7" r="4.4" stroke="currentColor" strokeWidth="1.35" />
            <path
              d="m10.4 10.4 3.1 3.1"
              stroke="currentColor"
              strokeWidth="1.35"
              strokeLinecap="round"
            />
          </svg>
          <input
            type="text"
            value={dataQuery}
            placeholder="Find…"
            aria-label="Find a database"
            onChange={(event) => setDataQuery(event.target.value)}
            onKeyDown={(event) => {
              if (event.key === "Escape") setDataQuery("");
            }}
          />
        </div>
      ) : null}

      {dataLevel.kind === "root" ? (
        <div className="cg-data-path-level" data-data-level="root">
          {levelSourceGroups.map((group) => (
            <div key={group.key} className="cg-fold cg-data-origin" {...dropProps(null)}>
              <div className="cg-fold-head">
                <button
                  type="button"
                  className="cg-fold-toggle"
                  aria-label={`Open folder ${group.label}`}
                  onClick={() => pushDataLevel({ kind: "origin", key: group.key })}
                >
                  <IconTile surface="rail">
                    {group.connector && group.connector !== "loopable"
                      ? <ConnectorMark connector={group.connector} size={16} className="lp-source-mark" />
                      : <FolderMark size={16} />}
                  </IconTile>
                  {/* ⭐ W54-T48 (R4 / C4) β€” THE FULL NAME ON HOVER, BECAUSE THIS NAME IS NOW THE
                      USER'S. This row used to read the literal "Odoo" for every connected
                      database and could not truncate; it now reads the CONNECTION's keychain
                      label once a tenant has two connections to tell apart, and a label may run
                      to 80 characters against a rail measured to the pixel. `.cg-fold-name`
                      (index.css:5929) is `overflow:hidden; text-overflow:ellipsis;
                      white-space:nowrap`, so "Royal Production (Jakarta warehouse)" reads as
                      "Royal Production (Jakart…" with nothing to open it.
                      ⚠ ON THE SPAN, NOT ON THE BUTTON, and that is the accessibility half. The
                      button's accessible name is its `aria-label` ("Open folder <name>"), which
                      already carries the whole label to a screen reader; a `title` on the button
                      would be a second name competing with it. On the text span it is a POINTER
                      affordance only and adds nothing to the accessibility tree.
                      ⚠ The same treatment the header's `.cg-rail-name` gives a truncatable name
                      (`title={name}`, this file) and the shape `.cg-fold-name` already
                      takes in the view layer below. No CSS: a title needs none. */}
                  <span className="cg-fold-name" title={group.label}>
                    {group.label}
                  </span>
                  <span className="cg-fold-count">{group.databases.length}</span>
                </button>
              </div>
            </div>
          ))}
          {levelFolders.map(pathFolderRow)}
          {dataNeedle && levelSourceGroups.length === 0 && levelFolders.length === 0 ? (
            <div className="cg-fold-empty">No matches.</div>
          ) : null}
        </div>
      ) : dataLevel.kind === "database" ? (
        <div className="cg-data-database-views" data-data-level="database">
          {children({ canBack: canDataBack, back: () => stepDataLevel(-1) })}
        </div>
      ) : (
        <div className="cg-data-path-level" data-data-level={dataLevel.kind}
          {...dropProps(dataLevel.kind === "folder" ? dataLevel.id : null)}>
          {levelFolders.map(pathFolderRow)}
          {levelDatabases.map(pathDatabaseRow)}
          {railSections?.sections.map(railGroupRow)}
          {/* The empty line must say WHY it is empty: under a live query "No databases in this
              folder" is simply false, and a wrong empty state on the control this ticket just
              un-hid is what QA reopens. */}
          {levelMatches.length === 0 && levelFolders.length === 0 ? (
            <div className="cg-fold-empty">
              {dataNeedle ? "No matches." : "No databases in this folder."}
            </div>
          ) : null}
        </div>
      )}

      {folderMenu ? (
        <AnchoredOverlay
          anchor={folderMenu.anchor}
          className="cg-view-menu"
          role="menu"
          ariaLabel="Database folder actions"
          onDismiss={() => setFolderMenu(null)}
          placement="right-start"
        >
          {renamingFolder === folderMenu.folderId ? (
            <form
              className="cg-data-folder-rename"
              onSubmit={(event) => {
                event.preventDefault();
                const clean = folderName.trim().replace(/\s+/g, " ");
                if (clean) onFolderRename?.(folderMenu.folderId, clean);
                setFolderMenu(null);
              }}
            >
              <input
                className="cg-input"
                autoFocus
                value={folderName}
                maxLength={FOLDER_NAME_MAX}
                aria-label="Database folder name"
                onChange={(event) => setFolderName(event.target.value)}
              />
              <button type="submit" className="cg-btn cg-btn--primary" disabled={!folderName.trim()}>
                Save
              </button>
            </form>
          ) : (
            <>
              {onFolderRename ? (
                <button
                  type="button"
                  role="menuitem"
                  onClick={() => setRenamingFolder(folderMenu.folderId)}
                >
                  Rename
                </button>
              ) : null}
              {onFolderDelete ? (
                <button
                  type="button"
                  role="menuitem"
                  className="is-danger"
                  onClick={() => {
                    onFolderDelete(folderMenu.folderId);
                    setFolderMenu(null);
                  }}
                >
                  Delete folder
                </button>
              ) : null}
            </>
          )}
        </AnchoredOverlay>
      ) : null}
    </div>
    </>
  );

}

/**
 * A shared folder group is identified by the granting owner and folder name. The visual mark is
 * fixed by the product, so persisted legacy icon metadata is intentionally not interpreted here.
 * The wire may carry either the legacy folder name or the newer folder record, so both are read.
 *
 * β›” BOTH `name` AND `owner` REQUIRED, unchanged from W34-T25: two colleagues can each share a
 * folder called "Reports", and a group keyed on the name alone merges them under one person's
 * label. The pair IS the identity, which is why `sharedFolderGroupId` takes both.
 */
function sharedFolderRecord(
  view: SavedView
): { name: string; owner: string } | null {
  const via = (view as { sharedFolder?: unknown }).sharedFolder;
  // C9's record shape. `null` is an object in JavaScript and an array is one too, so both are
  // excluded before any key is read off it.
  const record =
    via && typeof via === "object" && !Array.isArray(via)
      ? (via as Record<string, unknown>)
      : null;
  const rawName = typeof via === "string" ? via : record?.name;
  const name = typeof rawName === "string" ? rawName.trim() : "";
  const owner = typeof view.owner === "string" ? view.owner.trim() : "";
  if (!name || !owner) return null;
  return { name, owner };
}

function readRailPath(databaseKey: string): string | null {
  try {
    const stored = localStorage.getItem(pathStorageKey(databaseKey));
    return typeof stored === "string" && stored !== "" ? stored : null;
  } catch {
    return null;
  }
}

function writeRailPath(databaseKey: string, folderId: string | null): void {
  try {
    const key = pathStorageKey(databaseKey);
    if (folderId) localStorage.setItem(key, folderId);
    else localStorage.removeItem(key);
  } catch {
    // Storage is optional; losing this convenience must never take down the navigation.
  }
}

export default function ViewSidebar({
  scope = "customer",
  readOnly = false,
  folderReadOnly = readOnly,
  databases: suppliedDatabases = [],
  activeDatabaseKey = "",
  databaseFolders = [],
  onSelectDatabase,
  onDatabaseMove,
  onDatabaseFolderRename,
  onDatabaseFolderDelete,
  renderDatabaseActions,
  databaseCreateControl,
  hosted = false,
  chatOpen = false,
  onToggleChat,
  views: suppliedViews,
  loading = false,
  activeViewId,
  onSelect: requestSelect,
  onCreate,
  onRename,
  onNote,
  onDuplicate,
  onDelete: requestDelete,
  lists = [],
  onAddToList,
  onSelectFromFile,
  onImport,
  onCohortLock,
  today,
  onExport,
  onExportXlsxViews,
  onPrepareXlsxViews,
  xlsxExportReadyKey,
  exportableViewIds,
  folders: suppliedFolders,
  folderIdOf,
  onFolderCreate,
  onFolderRename,
  onFolderDelete,
  onFolderDuplicate,
  onItemMove,
  onFolderReorder,
  onViewReorder,
  alertCounts,
  countNotes,
  folderAddPreview,
  onFolderAddToList,
  viewer,
  onToggleLock,
  onToggleImportant,
  actionAnchor,
  onActionAnchorConsumed,
}: ViewSidebarProps) {
  const { isDeleted, restore } = useItemDeletions();
  const databases = suppliedDatabases.filter((row) => !isDeleted({ kind: "database", id: row.key }));
  const views = useMemo(() => suppliedViews.filter((row) =>
    !isDeleted({ kind: "view", id: row.id, database: activeDatabaseKey })), [suppliedViews, isDeleted, activeDatabaseKey]);
  const onSelect = (id: string) => {
    /* S85-T25: the view opens in the click's frame and the click reads nothing, so it sends no
       GET /workspace. The rail learns a deleted view from the next workspace change or from a
       C1 op refused on a deleted target (the receipt effect below). */
    requestSelect(id);
  };
  const activeViewGone = !!activeViewId
    && isDeleted({ kind: "view", id: activeViewId, database: activeDatabaseKey });
  useEffect(() => {
    if (activeViewGone && views.length) requestSelect(views[0].id);
  }, [activeViewGone, views, requestSelect]);
  const requestedDeletes = useRef(new Map<string, string>());
  const onDelete = (id: string) => {
    requestedDeletes.current.set(id, activeDatabaseKey);
    requestDelete(id);
  };
  useEffect(() => {
    // onDelete opens the host's confirmation. Emit only after the host removes the row;
    // cancelling or a refusal leaves it present and cannot broadcast a deletion.
    const confirmRemoved = () => {
      for (const [id, database] of requestedDeletes.current) {
        if (database !== activeDatabaseKey) { requestedDeletes.current.delete(id); continue; }
        if (suppliedViews.some((row) => row.id === id)) continue;
        // The parent's removal is optimistic. Confirm absence through the ordinary reader;
        // a 403 keeps the server's message and cannot become a deletion event.
        void openExistingItem({ kind: "view", id, database }, () => {}, { scope });
      }
    };
    const confirmed = (event: Event) => {
      const item = (event as CustomEvent<DeletedItem>).detail;
      if (item?.kind === "view" && item.database === activeDatabaseKey) requestedDeletes.current.delete(item.id);
    };
    window.addEventListener(ITEM_DELETED_EVENT, confirmed);
    window.addEventListener(WORKSPACE_STALE_EVENT, confirmRemoved);
    confirmRemoved();
    return () => {
      window.removeEventListener(ITEM_DELETED_EVENT, confirmed);
      window.removeEventListener(WORKSPACE_STALE_EVENT, confirmRemoved);
    };
  }, [suppliedViews, activeDatabaseKey, scope]);
  useEffect(() => editOutbox.subscribeReceipts((edit, receipt) => {
    if (edit.scope !== scope || edit.kind !== "event" || receipt.id !== edit.id) return;
    const event = edit.payload as { type?: string; viewId?: string } | null;
    // The server's acknowledgement confirms a requested delete, since a workspace copy may lag it.
    if (receipt.ok && event?.type === "view_delete" && event.viewId
        && requestedDeletes.current.get(event.viewId) === activeDatabaseKey) {
      itemDeleted({ kind: "view", id: event.viewId, database: activeDatabaseKey });
      return;
    }
    // A C1 op refused on a deleted target: the next workspace read drops what is gone.
    if (!receipt.ok && receipt.confirmedRefusal && event?.type === "view_op"
        && DELETED_TARGET_CODES.includes(receipt.code ?? "")) signal(WORKSPACE_STALE_EVENT);
  }), [scope, activeDatabaseKey]);
  // The old managed View folder put an origin label inside every database. Origin now
  // belongs one level up in the Data tree, so its views fall back into the database's root group.
  const folders = useMemo(
    () =>
      suppliedFolders?.filter(
        (folder) => (folder as GridFolder & { managedBy?: "loopable" }).managedBy !== "loopable"
      ),
    [suppliedFolders]
  );
  /**
   * I14 β€” creating a view now always knows WHICH KIND of view is being created, because the
   * flyout is the only door in. `null` = not creating; a mode = the name step for that mode.
   */
  const [creating, setCreating] = useState<DisplayMode | null>(null);
  /** I14 β€” the "+ Create new…" flyout's anchor. */
  /* ⚠ W50-T11 widened this from `HTMLButtonElement` to `HTMLElement`: the folder "…" menu's own
     trigger is the SECOND thing that opens this flyout, and `folderMenu.anchor` is already held
     as an `HTMLElement`. `AnchoredOverlay` takes an `HTMLElement`, so nothing downstream narrows. */
  const [createMenu, setCreateMenu] = useState<HTMLElement | null>(null);
  /**
   * ⭐⭐ W50-T11 (owner instruction 21, ruling R12) β€” WHICH FOLDER THE CREATE FLYOUT WAS OPENED
   * FOR, held across its FIRST step.
   *
   * β›” IT CANNOT BE `folderParent`, and that is the whole reason a second piece of state exists.
   * `startView(mode, parent)` WRITES `folderParent` and runs at step TWO β€” after a display mode
   * has been picked. The folder's "…" menu opens the flyout at step ONE, so between the click on
   * "New view in folder" and the click on "Grid" there is nothing holding the destination:
   * writing `folderParent` up front would then be overwritten by `startView`'s own default the
   * moment the mode row fired. This holds the destination for exactly that gap, and the mode rows
   * hand it back to `startView`, so the destination still travels through ONE parameter and
   * `create()` still reads ONE source.
   *
   * ⚠ CLEARED BY THE TOP DOOR AND BY `closeCreate`. "+ Create new…" means the level the rail is
   * standing in (`atId`, in `create()`), never the folder some earlier menu pointed at β€” the same
   * staleness `startView`'s own `setFolderParent` note describes, one step earlier.
   */
  const [createInto, setCreateInto] = useState<string | null>(null);
  const [name, setName] = useState("");
  const [menu, setMenu] = useState<{
    viewId: string;
    anchor: HTMLElement;
  } | null>(null);
  const [renamingId, setRenamingId] = useState<string | null>(null);
  const [noteFor, setNoteFor] = useState<{
    viewId: string;
    anchor: HTMLElement;
  } | null>(null);
  const [noteDraft, setNoteDraft] = useState("");
  const [addFor, setAddFor] = useState<{
    viewId: string;
    anchor: HTMLElement;
  } | null>(null);
  /** Item 12 (C-LOCK) β€” which view's cohort lock the picker is open for. */
  const [lockFor, setLockFor] = useState<{
    viewId: string;
    anchor: HTMLElement;
  } | null>(null);
  const [newListName, setNewListName] = useState("");
  /** W2 β€” the Export format pane, anchored where the "…" menu was. */
  const [exportFor, setExportFor] = useState<{
    viewId: string;
    anchor: HTMLElement;
  } | null>(null);
  /** C3 begins with the View whose menu opened this pane; later picks are explicit. */
  const [exportViewIds, setExportViewIds] = useState<string[]>([]);
  const [exportBulk, setExportBulk] = useState(false);
  // Selection lives in the shared C6 hook below, after the rendered row order is known.
  // The bar still confirms deletion before anything calls onDelete.
  const [railDeleteArmed, setRailDeleteArmed] = useState(false);
  const [railLeftInPlace, setRailLeftInPlace] = useState<readonly string[]>([]);
  /**
   * ⭐ W50-T27 (C4) β€” THE DATABASE MENU AND THE TRASH PANEL, held as two separate anchors.
   *
   * β›” NOT ONE PIECE OF STATE WITH A MODE. The menu closes the instant "Trash" is picked and the
   * panel outlives it, so a single `open: "menu" | "trash"` would have to keep the menu's anchor
   * alive for the panel and dismiss both together; `AnchoredOverlay` would then re-enter its own
   * outside-click layer for a menu nobody can see. Two nulls, two overlays, one anchor ELEMENT
   * shared between them β€” the panel hangs where the control that opened it stands.
   * ⚠ THE ANCHOR IS HOISTED OUT OF THE UPDATER at the call site, like every other menu in this
   * file: React nulls `event.currentTarget` when the handler returns and a functional updater may
   * be re-invoked after that, which is the white-screen defect recorded at the view row's "…".
   */
  const [databaseMenu, setDatabaseMenu] = useState<HTMLElement | null>(null);
  const [trashAnchor, setTrashAnchor] = useState<HTMLElement | null>(null);
  const [fieldsFor, setFieldsFor] = useState<{ key: string; label: string; opener: HTMLElement } | null>(null);
  const activeDatabase = databases.find((database) => database.key === activeDatabaseKey);
  // Connector databases keep their Fields door in their connector's Settings.
  const canManageFields = viewer?.isAdmin === true && scope === activeDatabaseKey
    && !!activeDatabase && activeDatabase.key.startsWith("ut_")
    && dataDatabaseOriginKey(activeDatabase) === CUSTOM_ORIGIN_KEY;
  const closeFields = useCallback(() => {
    const opener = fieldsFor?.opener;
    setFieldsFor(null);
    window.requestAnimationFrame(() => { if (opener?.isConnected) opener.focus(); });
  }, [fieldsFor]);
  useEffect(() => {
    if (fieldsFor && (fieldsFor.key !== activeDatabaseKey || !canManageFields)) closeFields();
  }, [fieldsFor, activeDatabaseKey, canManageFields, closeFields]);
  /**
   * ⭐⭐ W50-T27 / C4 β€” "comes back whole", WITHOUT A RELOAD, and this is the whole wire.
   *
   * `WORKSPACE_STALE_EVENT` is the channel `apiBridge.ts` already binds to
   * `useCustomerData.reread()`, which re-fetches `/workspace` and hands this component a new
   * `views` array. So the restored view reappears in the rail on the next render, carrying the
   * SERVER's copy of itself rather than a row this component guessed at.
   * β›” NO `onSelect(viewId)` HERE. The id has not reached `views` yet at this instant, and asking
   * the host to activate a view it does not hold is how a rail selects nothing and looks broken.
   * The view comes back where it was; opening it is the person's next click.
   * ⚠ `viewId` is READ, not decoration: an empty id means the panel restored nothing, and a
   * refetch fired on that would be the rail claiming an event that did not happen.
   */
  const onTrashRestored = useCallback((viewId: string) => {
    if (!viewId) return;
    restore({ kind: "view", id: viewId, database: activeDatabaseKey });
    signal(WORKSPACE_STALE_EVENT);
    signal(TOAST_EVENT, "That view is back in the rail.");
  }, [restore, activeDatabaseKey]);
  /**
   * ⭐⭐ W50-T27: THE DATABASE-LEVEL "…" CONTROL. C4 (S72-T58) renders it once, in the header's
   * `span.cg-rail-menu` beside the name, so it stays reachable while a view search is live.
   * β›” ABSENT, NOT DISABLED, WITHOUT A DATABASE. `activeDatabaseKey` is "" on the embedded and
   * Query surfaces, and it IS the `table_key` every `/api/v1/tables/{key}/…` route resolves
   * through `user_tables` β€” the registry spelling (`customer_data`, `ut_*`), never
   * `gridScopeFor`'s grid scope. A Trash door with no database behind it could only report an
   * error, and this file's standing posture is to omit an action nobody can honour.
   */
  // `.cg-view-more` ships at opacity 0, and this one instance sits in `span.cg-rail-menu`, never a
  // hover row, so it carries its own `opacity: 1`.
  const databaseActions = activeDatabaseKey ? (
    <button
      type="button"
      className="cg-view-more"
      style={{ opacity: 1 }}
      aria-label="Database actions"
      aria-haspopup="menu"
      aria-expanded={!!databaseMenu}
      onClick={(event) => {
        // β›” THE ANCHOR IS HOISTED OUT OF THE UPDATER, like every other menu in this file: React
        // nulls `event.currentTarget` when the handler returns and may re-invoke a functional
        // updater afterwards, which is the white-screen defect recorded at the view row's "…".
        const anchor = event.currentTarget;
        // The panel is dismissed on every press of this control, so the menu can never stack on
        // top of a panel that came out of the same button.
        setTrashAnchor(null);
        setDatabaseMenu((current) => (current ? null : anchor));
      }}
    >
      Β·Β·Β·
    </button>
  ) : null;
  const xlsxExportViews = useMemo(() => {
    const allowed = new Set(exportableViewIds ?? []);
    return views.filter((view) => allowed.has(view.id));
  }, [views, exportableViewIds]);
  const exportView = exportFor
    ? views.find((view) => view.id === exportFor.viewId)
    : undefined;
  /**
   * ⭐⭐ W50-T12 / R11 β€” THE IDS THIS PANE WOULD EXPORT RIGHT NOW, and there are TWO doors, which
   * is the part that is easy to miss. The bulk door exports the ticked set; the single-View door
   * (rendered when `onExport` is absent, i.e. a server-windowed grid) exports the one View whose
   * menu opened the pane. Preparing only the first would leave the second permanently unready,
   * turning "sometimes silent" into "always refuses" on that surface.
   */
  const exportIntendedIds = useMemo(() => {
    if (!exportView) return [] as string[];
    if (exportBulk) return exportViewIds;
    // ⚠ NOT EVERY OPEN PANE NEEDS A WORKBOOK. When `onExport` is present the single-View Excel
    // row goes through it instead, and that path builds in the browser inside the click with no
    // round trip at all. Preparing here anyway would POST on every export-pane open for a file
    // nobody asks for.
    if (onExport) return [] as string[];
    return exportableViewIds?.includes(exportView.id) ? [exportView.id] : [];
  }, [exportView, exportBulk, exportViewIds, exportableViewIds, onExport]);
  const exportIntendedKey = exportSelectionKey(exportIntendedIds);
  /** True when the workbook waiting in the grid is the workbook this pane would hand over. An
   *  empty selection has a key of its own, so the emptiness is checked separately. */
  const exportReady = exportIntendedIds.length > 0 && xlsxExportReadyKey === exportIntendedKey;
  /**
   * The preparation trigger. It fires on open and on every tick because `exportIntendedKey` is
   * the dependency, and the grid's own handler is idempotent per key, so a re-render or a
   * double-invoked effect costs nothing. ⚠ No debounce: a tick is a deliberate act, the request
   * is one small POST, and a delay here is exactly the wait the owner would feel at the button.
   */
  useEffect(() => {
    if (!onPrepareXlsxViews || !exportIntendedIds.length) return;
    onPrepareXlsxViews([...exportIntendedIds]);
  }, [onPrepareXlsxViews, exportIntendedKey, exportIntendedIds]);
  const [moveFor, setMoveFor] = useState<{
    viewId: string; anchor: HTMLElement; bulk?: boolean;
  } | null>(null);
  const moveView = moveFor ? views.find((view) => view.id === moveFor.viewId) : undefined;
  const addView = addFor ? views.find((view) => view.id === addFor.viewId) : undefined;
  const menuView = menu ? views.find((view) => view.id === menu.viewId) : undefined;
  useEffect(() => {
    if (!actionAnchor || readOnly) return;
    const active = views.find((view) => view.id === activeViewId);
    if (active) setMenu({ viewId: active.id, anchor: actionAnchor });
    onActionAnchorConsumed?.();
  }, [actionAnchor, activeViewId, onActionAnchorConsumed, views, readOnly]);
  /** C4 β€” may this viewer change the menu view's IDENTITY? Courtesy only; the host is the
   *  wall. C3's lock toggle ANDs with this rather than replacing it: the two contracts
   *  compose (C4 says who may edit, C3 says who may freeze the mode). */
  const canEditMenuView = !!menuView && mayEditView(menuView, viewer);
  const canDismissMenuView = !!menuView?.assigned;
  // I11c local UI state. Collapse is deliberately LOCAL (C4: "minimize state
  // local") β€” which folders you have open is a per-person, per-session habit,
  // not a property of the shared workspace.
  /**
   * ⭐⭐ WAVE 41 Β· T34 (instruction 13) β€” THE STATE IS "WHICH FOLDERS THE USER OPENED", AND THE
   * COLLAPSED SET IS DERIVED FROM IT.
   *
   * Owner: *"When a user logs in, a folder defaults to CLOSED, not open."* This used to hold the
   * collapsed ids, so an empty set β€” the state every mount starts in β€” meant every folder OPEN,
   * the exact opposite of the instruction. Inverting the question is what makes the default fall
   * out of the initial state instead of having to be installed into it.
   *
   * β›” WHY NOT SEED THE COLLAPSED SET INSTEAD. `useState(() => new Set(folderIds))` captures the
   * folders present at FIRST RENDER only, and this rail mounts before its workspace lands, so on
   * the real load order it would seed from an EMPTY list and every folder would still open. Every
   * folder arriving later β€” the workspace payload, a newly granted share, a folder T33's nesting
   * reveals β€” would be open too. The `useEffect`-collapses-new-arrivals variant fixes the
   * membership but paints one frame with everything open first, so "on first load every folder is
   * collapsed" would be false for exactly as long as a user can see it.
   *
   * β›” NOTHING BUT THE USER'S OWN TOGGLE EVER REMOVES AN ID FROM HERE, which is the whole of
   * "expanding one and returning later keeps it expanded". A folder that leaves the list and
   * comes back (a live search, a refreshed payload) keeps its id in this set and returns open.
   * The set therefore also retains ids of deleted folders; at `MAX_FOLDERS` = 60 and a lifetime
   * bounded by the component's, that is a rounding error, and pruning it is what would
   * re-introduce the "opened folder silently re-closes" bug.
   *
   * ⚠ SESSION HERE MEANS THE COMPONENT'S LIFETIME, deliberately. There is no localStorage and no
   * server preference, and adding one would defeat instruction 13's own first clause: a
   * preference that survives a reload is a folder that is open when the user next logs in.
   */
  // Recovered from 7f6a1c0 (W42-T43): one location replaces the old expand/collapse tree.
  /**
   * ⭐⭐ W46-T08 (owner instruction 26) - THE VIEW LAYER'S LOCATION IS NOW AN INDEX INTO HISTORY,
   * modelled on `dataPathState` one layer down so the two halves of one rail cannot disagree
   * about what Back and Forward mean.
   *
   * β›” `at` AND `setAt` STAY, deliberately, as a derived value and a derived setter. `setAt` has
   * five call sites (the database switch, both create-into-a-folder paths, the Back control and
   * the folder rows), and w44's gate pins three of those literals. Adding a SECOND history array
   * beside `at` would leave the folder rows advancing the location without truncating, so Forward
   * would walk into a folder nobody just left. Routing every existing caller through one
   * push-and-truncate is the whole point.
   */
  const [viewPath, setViewPath] = useState<{ ids: (string | null)[]; at: number }>(() => {
    const restored = readRailPath(activeDatabaseKey);
    return restored ? { ids: [null, restored], at: 1 } : { ids: [null], at: 0 };
  });
  const at = viewPath.ids[viewPath.at] ?? null;
  const setAt = (next: string | null) =>
    setViewPath((current) =>
      (current.ids[current.at] ?? null) === next
        ? current
        : { ids: [...current.ids.slice(0, current.at + 1), next], at: current.at + 1 }
    );
  const stepViewLevel = (delta: number) =>
    setViewPath((current) => {
      const index = current.at + delta;
      return index < 0 || index >= current.ids.length ? current : { ...current, at: index };
    });
  const canViewBack = viewPath.at > 0;
  const canViewForward = viewPath.at < viewPath.ids.length - 1;
  const railDatabaseRef = useRef(activeDatabaseKey);
  if (railDatabaseRef.current !== activeDatabaseKey) {
    railDatabaseRef.current = activeDatabaseKey;
    const restored = readRailPath(activeDatabaseKey);
    // β›” A DATABASE CHANGE RESTORES A LOCATION, IT DOES NOT TRAVEL TO ONE. Pushing here would
    // carry the previous database's folders into this one's history, and Forward would then point
    // at a folder that does not exist on the database now on screen. The Data navigator resets
    // its own `levels` on the same signal for the same reason.
    setViewPath(restored ? { ids: [null, restored], at: 1 } : { ids: [null], at: 0 });
  }
  const [folderMenu, setFolderMenu] = useState<{ id: string; anchor: HTMLElement } | null>(null);
  const [renamingFolder, setRenamingFolder] = useState<string | null>(null);
  const [creatingFolder, setCreatingFolder] = useState(false);
  const [folderAnchor, setFolderAnchor] = useState<HTMLElement | null>(null);
  /**
   * ⭐⭐ WAVE 41 Β· T33 (instruction 12, R1) β€” WHICH FOLDER THE DRAFT FOLDER GOES INSIDE.
   *
   * ⚠ A SECOND PIECE OF DRAFT STATE RATHER THAN A WIDER `creatingFolder`, because the two
   * answer different questions and one of them is a boolean the whole pane is gated on. Turning
   * `creatingFolder` into `string | null | false` would make "no pane" and "a pane at the top
   * level" the same falsy value, which is W32-T27's absence-holding-two-facts bug in miniature.
   * Cleared by `startFolder` and by `createFolder`, so a folder made inside one folder cannot
   * leave its parent behind for the next one.
   */
  const [folderParent, setFolderParent] = useState<string | null>(null);
  const [confirmDelete, setConfirmDelete] = useState<string | null>(null);
  const [addTarget, setAddTarget] = useState<string | null>(null);
  /** The element the bulk-add pane hangs off. Anchoring to document.body
   *  put it at the bottom of the DOCUMENT rather than beside the folder β€”
   *  painted, and effectively unreachable ([[ui-invisible-to-assertions]]).
   *  Captured from the folder menu before that menu is dismissed. */
  const [addAnchor, setAddAnchor] = useState<HTMLElement | null>(null);
  const [addName, setAddName] = useState("");
  const [dropTarget, setDropTarget] = useState<string | null>(null);
  // Owner item 9 (2026-07-31) β€” "Find a view". Local and never persisted: a search is a
  // moment, not a setting. Filtering runs BEFORE grouping so a folder with no matches
  // simply drops out of the rail while the query is live.
  const [viewQuery, setViewQuery] = useState("");
  // R20 (SDLC 68): remember the desktop fold; narrow expansion lasts only for this visit.
  const [railShut, setRailShut] = useState<boolean>(() => {
    try {
      return localStorage.getItem("aios-views-rail") === "1";
    } catch {
      return false;
    }
  });
  const toggleRail = () =>
    setRailShut((v) => {
      const next = !v;
      try {
        localStorage.setItem("aios-views-rail", next ? "1" : "0");
      } catch {
        // storage can be blocked; the fold still works for the session
      }
      return next;
    });
  const narrow = useNarrowRailFold();
  const [narrowOpen, setNarrowOpen] = useState(false);
  useEffect(() => {
    if (!narrow) setNarrowOpen(false);
  }, [narrow]);
  const folded = narrow ? !narrowOpen : railShut;
  const [railEl, setRailEl] = useState<HTMLElement | null>(null);
  const headerSlot = useRailHeaderSlot("data", railEl);
  const viewNeedle = viewQuery.trim().toLowerCase();
  /**
   * ⭐⭐ WAVE 41 Β· T37 (owner instruction 14) β€” THE FIRST LINK IN THE MEMO CHAIN, AND WITHOUT IT
   * EVERY LINK BELOW IS DEAD.
   *
   * The filter allocates a NEW ARRAY on every render while a search is live. Memoizing the
   * grouping over a freshly-allocated list is a memo that never hits, on inputs that never
   * changed β€” green under every gate and worth nothing. So the list the grouping reads is
   * pinned first, on the only two things that can change it.
   */
  const shownViews = useMemo(
    () =>
      viewNeedle
        // ⭐ W40-T28 β€” searched by what the row SAYS. Filtering on the stored name would leave
        // the default view unfindable by the only name the user has ever seen it under.
        ? views.filter((v) => (viewDisplayName(v) || "").toLowerCase().includes(viewNeedle))
        : views,
    [views, viewNeedle]
  );
  // ── WAVE 20 item 19 (C-FOLDER-REORDER) β€” dragging a FOLDER to reorder the rail ──────
  //
  // ⚠ A PRIVATE dataTransfer MIME, and it is not decoration. The VIEW drag two blocks down
  // carries `text/plain`, and the folder groups already accept that drop ("file this view
  // into me"). Sharing one channel would make every folder drag look like a view drop to
  // the handler that fires first β€” so the two drags are told apart by TYPE, the same
  // discipline the shell nav's own drag uses, and a drop of this type anywhere
  // text-editable types nothing.
  const FOLD_DRAG_TYPE = "application/x-loopable-fold";
  /** The folder being dragged, and the group its insertion line is currently drawn above. */
  const [foldDrag, setFoldDrag] = useState<string | null>(null);
  const [foldOver, setFoldOver] = useState<string | null>(null);
  /**
   * ⭐⭐ W47-T12 (owner instruction 3) β€” THE FOLDER THE DRAG WOULD GO *INSIDE*, as opposed to
   * {@link foldOver}, which is the folder it would land ABOVE.
   *
   * TWO STATES RATHER THAN ONE WITH A MODE, because they paint two different pictures that must
   * never both be on: `foldOver` draws the insertion RULE (`.cg-fold.is-drop-above`) and this one
   * draws the FILL (`.cg-fold.is-drop`). A single "the folder under the pointer" value plus a
   * separate "and this is what it means" flag would let a render read the two halves out of one
   * commit and paint a rule and a fill at once, which is precisely the ambiguity this ticket is
   * about. Every setter below writes both, so exactly one of them is ever non-null.
   *
   * ⚠ IT CARRIES `ok`, AND ONLY `ok` PAINTS. `mayNestFolder` is asked during `dragover`, not only
   * at the drop, so a target that will be refused never lights up β€” a fill under a drop that is
   * about to be rejected is worse than no fill. The refused case is still RECORDED rather than
   * discarded, because `data-fold-drop="refused"` is the difference between "the app has not
   * noticed my pointer" and "it has, and it will not do this", and releasing there says WHY out
   * loud on the toast channel.
   */
  const [foldNest, setFoldNest] = useState<{ id: string; ok: boolean } | null>(null);
  /**
   * ⭐ W47-T12 β€” the re-parent this browser just performed, held until the host echoes it.
   *
   * The rail renders folders from server state, so between the emit and the echo the dragged
   * folder would sit exactly where it was and the gesture would read as "nothing happened" β€” the
   * NO-BLIP law of `folders.ts`, applied to a parent instead of to a name. `folders.ts`'s stamp
   * map cannot carry it: `CustomerGrid` writes those stamps and this event does not go through
   * `CustomerGrid`, so the hold lives beside the gesture that made it.
   *
   * ⚠ IT EXPIRES. A refusal (the store is unreachable, the tree validator says the chain is too
   * deep) never echoes agreement, and a hold with no clock would leave the rail showing a nesting
   * the server does not have until the page was reloaded. So it clears the moment the incoming
   * `folders` prop agrees, and unconditionally a few seconds later whether it agreed or not β€” by
   * which time the host's own refusal toast has already said why the folder moved back.
   */
  const [nestHold, setNestHold] =
    useState<{ id: string; parent: string | null; at: number } | null>(null);
  useEffect(() => editOutbox.subscribeReceipts((edit, receipt) => {
    if (edit.scope !== scope || edit.kind !== "event" || receipt.id !== edit.id ||
        receipt.ok || receipt.code !== "view_revision_stale") return;
    const event = edit.payload as { type?: string; surface?: string; itemId?: string } | null;
    if (event?.type === "item_move" && event.surface === "views")
      setNestHold((current) => current?.id === event.itemId ? null : current);
  }), [scope]);
  const foldsReorderable = !folderReadOnly && !!folders && !!onFolderReorder;
  /**
   * ⭐ W47-T12 β€” nesting needs the folder list and the `item_move` door, and nothing else. It is
   * deliberately NOT gated on `foldersOn` (which also demands `folderIdOf`, a VIEW-placement
   * accessor a folder move never consults) so the gesture cannot be switched off by a prop that
   * has nothing to do with it.
   *
   * Folder identities use the same revision sink without arming the view-only watchdog.
   */
  const foldsNestable = !!folders && !!onItemMove;
  /**
   * Land `draggedId` before `beforeId` (null = last) and emit the new order. The arithmetic
   * lives in `folders.ts` so a gate can run it under node β€” the handler around it is DOM.
   *
   * ⚠ The order is computed from the `folders` PROP, never from the rendered groups: a live
   * "Find a view" query hides folders with no matches, and an order derived from what is on
   * screen would silently drop the hidden ones out of the sequence.
   */
  const reorderFolders = (draggedId: string, beforeId: string | null) => {
    const next = reorderFolderIds((folders ?? []).map((f) => f.id), draggedId, beforeId);
    // `null` is "nothing to say" β€” an unknown id, or a drop that changed nothing.
    if (next) onFolderReorder?.(next);
  };
  // ── ⭐ WAVE 27 Β· OWNER ITEM 5 (contract C7) β€” dragging a VIEW to reorder the rail ────────
  //
  // The owner asked for both lists to be draggable top-to-bottom; folders already were
  // (wave 20 item 19) and views could only be FILED INTO a folder, never moved past each
  // other. This is that drag, built on the same three pieces so the two gestures cannot drift:
  // a private MIME, the shared `reorderFolderIds` arithmetic, and a whole-order emit.
  //
  // β›” THE ARITHMETIC IS REUSED, NOT COPIED. `reorderFolderIds` is id-generic β€” it takes a list
  // of ids, a dragged id and a "before" id, and every clause in it (dropped-on-itself, the
  // not-found fallback, the no-op return) is about SEQUENCES rather than about folders. It is
  // already exercised by `verify_folders.py`, and a second copy here would be a second place
  // for the dropped-on-itself bug that function's own comment records ([[one-evaluator-per-question]]).
  const VIEW_DRAG_TYPE = "application/x-loopable-view";
  const VIEW_SET_DRAG_TYPE = "application/x-loopable-view-set";
  const [viewDrag, setViewDrag] = useState<string | null>(null);
  const [viewOver, setViewOver] = useState<string | null>(null);
  /**
   * Land `draggedId` before `beforeId` and emit the FULL order.
   *
   * ⚠ Computed from the `views` PROP, never from the rendered rows β€” a live "Find a view"
   * query hides non-matching rows, and an order derived from what is on screen would silently
   * drop every hidden view out of the sequence. (The folder half carries the identical note;
   * it is the same trap and this rail has both filters on it.)
   */
  const reorderViews = (draggedId: string, beforeId: string | null) => {
    const next = reorderFolderIds(views.map((v) => v.id), draggedId, beforeId);
    if (next) onViewReorder(next);        // `null` = an unknown id, or a drop that changed nothing
  };
  /**
   * One pair of handlers per VIEW ROW, listening for the view MIME only.
   *
   * β›” `stopPropagation` IS LOAD-BEARING. A view row sits inside its folder group, whose own
   * `onDrop` reads `text/plain` and files the view into that folder. Both types are on this
   * drag, so without this a reorder inside a folder would ALSO re-file the view β€” usually into
   * the folder it is already in, i.e. invisible, until the day it is not.
   * ⚠ WHAT THIS DELIBERATELY DOES NOT DO: change the view's folder. Dropping a view onto a row
   * in another folder reorders it and leaves it where it lives; filing stays a drop on the
   * folder itself. Two gestures, two meanings, rather than one gesture guessing.
   */
  const viewDropHandlers = (viewId: string) => ({
    onDragOver: (e: React.DragEvent) => {
      if (!e.dataTransfer.types.includes(VIEW_DRAG_TYPE)) return;
      e.preventDefault();
      e.stopPropagation();
      e.dataTransfer.dropEffect = "move";
      setViewOver(viewId);
    },
    onDragLeave: () => setViewOver(null),
    onDrop: (e: React.DragEvent) => {
      if (!e.dataTransfer.types.includes(VIEW_DRAG_TYPE)) return;
      const dragged = e.dataTransfer.getData(VIEW_DRAG_TYPE);
      setViewOver(null);
      setViewDrag(null);
      if (!dragged) return;
      e.preventDefault();
      e.stopPropagation();
      reorderViews(dragged, viewId);
    },
  });
  const viewsReorderable = !readOnly && views.length > 1;
  const foldersOn = !folderReadOnly && !!folders && !!folderIdOf && !!onItemMove;
  // Folder structure follows the last workspace, independently of refresh status and edit permission.
  const foldersShown = !!folders && !!folderIdOf;
  /**
   * ⭐⭐ WAVE 41 Β· T33 (instruction 12, R1, C9) β€” THE FOLDER LIST, READ AS A TREE.
   *
   * β›” `nesting.ordered` IS WHAT MAKES NESTING RENDER, and it is the only change the grouping
   * path needed. `groupByFolder` emits one group per folder IN THE ORDER IT IS HANDED THEM, so a
   * depth-first list puts every folder immediately after its parent and the rail only has to
   * indent by `nesting.depth`. The alternative β€” teaching `groupByFolder` about parents β€” would
   * have had to survive its byte-identical `JSON.stringify` assertion, its compiled-artifact
   * negative controls and the cohort rail's four-argument call, for behaviour a sort supplies.
   *
   * ⚠ MEMOIZED WITH THE GROUPING, exactly as this paragraph asked for when it was written:
   * a memoized grouping fed by a freshly-allocated folder order recomputes on every render
   * anyway, so the two are pinned together or neither is (W41-T37, owner instruction 14).
   */
  /**
   * ⭐⭐ W47-T12 β€” THE FOLDER LIST WITH THIS BROWSER'S PENDING RE-PARENT APPLIED.
   *
   * β›” APPLIED HERE, ABOVE `folderNesting`, RATHER THAN TO THE GROUPS BELOW IT, because the
   * parent is not a decoration on a row: it decides `nesting.ordered` (where the folder renders,
   * and in whose subtree), `nesting.depth` (its indent) and every subsequent `mayNestFolder`
   * verdict. Patching the picture further down would move the folder on screen while the model
   * behind the next drag still believed the old tree.
   *
   * ⚠ COPIED, NEVER MUTATED. `folders` is the memoized list `CustomerGrid` reconciled; writing
   * `parent` into that row in place would edit the host's own copy and the hold could then never
   * expire β€” the value it is supposed to expire back to would be gone.
   */
  const foldersHeld = useMemo(() => {
    const list = foldersShown ? (folders as GridFolder[]) : [];
    if (!nestHold) return list;
    if (!list.some((f) => f.id === nestHold.id)) return list;
    return list.map((f) => {
      if (f.id !== nestHold.id) return f;
      const next: GridFolder = { ...f };
      // ⚠ DELETED, not set to `undefined`. `folderNesting` reads anything that is not a known
      // string as the top level, so both spellings RENDER the same β€” but this list is handed on
      // to `groupByFolder`, whose contract with its own tests is byte-identical output, and a
      // row carrying an explicit `undefined` key does not serialise like a row without one.
      if (nestHold.parent) next.parent = nestHold.parent;
      else delete next.parent;
      return next;
    });
  }, [folders, foldersShown, nestHold]);
  const nesting = useMemo(() => folderNesting(foldersHeld), [foldersHeld]);
  /**
   * ⭐ W47-T12 β€” RETIRE THE HOLD. Two exits, and both are needed:
   *   Β· the incoming list AGREES (the echo landed, or another tab did the same move) β€” drop it
   *     immediately, so the rail is reading server state again at the first opportunity;
   *   Β· the clock runs out β€” drop it whether it agreed or not. A refusal never agrees, and this
   *     is what stops a rejected nesting from sitting on screen as a lie until the next reload.
   * The wait is measured from the DROP, not from this render, so a rail whose folder list churns
   * cannot keep restarting the timer and extend the hold indefinitely.
   */
  useEffect(() => {
    if (!nestHold) return;
    const row = (folders ?? []).find((f) => f.id === nestHold.id);
    if (!row || (row.parent ?? null) === nestHold.parent) {
      setNestHold(null);
      return;
    }
    const timer = window.setTimeout(
      () => setNestHold(null),
      Math.max(0, nestHold.at + NEST_HOLD_MS - Date.now())
    );
    return () => window.clearTimeout(timer);
  }, [folders, nestHold]);
  const canFileMenuView =
    foldersOn && !!menuView && mayFileVerdict(menuView, canEditMenuView);
  const moveFolders = useMemo(
    () => nesting.ordered.filter((folder) => !isSyntheticFolderId(folder.id)),
    [nesting]
  );
  /**
   * ⭐⭐ WAVE 41 Β· T37 (owner instruction 14) β€” THE GROUPING RUNS ONCE PER INPUT CHANGE, NOT
   * ONCE PER RENDER.
   *
   * MEASURED on the real component in a headless browser, 52 views over 8 folders: a drag whose
   * pointer crosses a new row on every frame commits 60 times a second, and every one of those
   * commits re-ran this pass β€” 60 regroupings a second, each of them O(views squared), because
   * `folderIdOf` resolves a placement by `views.find(...)` per view. Nothing a `dragover` writes
   * (`dropTarget`, `foldOver`, `viewOver`) is an input to it, so the whole sweep is repeat work.
   *
   * ⚠ THE DEPS ARE THE INPUTS AND NOTHING ELSE. `folderIdOf` is the caller's callback and it
   * carries the placement stamps, so it belongs here; leaving it out would freeze a view in the
   * folder it was dragged out of until something else changed.
   */
  const groups = useMemo(() => groupByFolder(
    shownViews,
    nesting.ordered,
    (v) => (folderIdOf ? folderIdOf(v.id) : null),
    /**
     * ⭐ WAVE 21 item 9 (R12 / contract C1) β€” THE CONSUMER of `shared`.
     *
     * The wire marks each granted view `shared: true` (C1); this is where that mark becomes
     * a place on screen. Passed unconditionally β€” NOT gated on `foldersOn` β€” because the
     * folder machinery is an opt-in feature of the views rail and "who shared this with me"
     * is not: a surface with folders switched off must still be able to show you somebody
     * else's view under a heading that says whose it is.
     *
     * β›”β›” W40-T21 (contract C1) β€” `owner` IS PART OF THE TEST NOW, AND WITHOUT IT THIS GROUP
     * SWALLOWS YOUR OWN VIEWS. C1 widens `shared` from "granted to me" to "this view has
     * grants", which means the caller's own shared-out views arrive carrying it. This group is
     * headed **Shared with me**, so the bare flag would file every view I share OUT under a
     * heading saying somebody shared it with me, and move it out of the folder I put it in.
     * `owner` is stamped only on the recipient's leg (`_granted_views`), so it is exactly the
     * half of `shared` that still means "not mine" β€” the same reading `viewShareMark` above is
     * built on, so the mark and the grouping cannot disagree about who shared what.
     */
    (v) => v.shared === true && !!v.owner,
    /**
     * ⭐⭐ WAVE 34 Β· T25 (ruling R11) β€” WHICH shared folder this view arrived through.
     *
     * ⚠ READ STRUCTURALLY, and that is a deliberate, temporary compromise rather than sloppiness.
     * `core/grid_events.py::_granted_views` has stamped `sharedFolder` on every folder-granted
     * view since `D-37`, its three siblings `shared` / `sharedRole` / `owner` are all declared on
     * `SavedView`, and this one never was: a census of `web/src` found ZERO occurrences before
     * this line. `types.ts` is another session's file this wave (`ASK C-1` is out for the
     * one-line declaration), so rather than block R11 on a type, the field is read through a
     * narrow local shape and validated here. β›” When C-1 lands, delete this cast and take the
     * declared field: a private spelling of a wire field is exactly how two layers drift.
     */
    /**
     * ⭐ W41-T35 β€” THE READ IS `sharedFolderRecord` NOW, and the extraction is the point.
     * The same function answers the icon map below, so the group a view lands in and the mark
     * that group wears cannot be derived from two different readings of one wire field. It
     * still hands `groupByFolder` exactly `{name, owner}` β€” the extra key is ignored there β€”
     * so the grouping is byte-identical to its pre-T35 self.
     */
    (v) => sharedFolderRecord(v),
    /**
     * ⭐⭐ WAVE 40 Β· T28 (owner instruction 30) β€” THE VIEWS THAT PIN ABOVE EVERY FOLDER.
     *
     * Owner: *"when it is not in a folder it must sit at the very top above all folders unless
     * the user moves it down."* `isUndeletableView` is the set, not a fresh id list, because it
     * is already THE answer to "which views are facts about this table rather than the user's
     * own arrangement of it" β€” the per-database default, Starred, and the IG Overview. A second
     * spelling here would be a second place to update the day a fourth pinned view exists.
     *
     * β›” THE YIELD IS INSIDE `groupByFolder`, NOT HERE: it lifts only views with NO stored
     * placement, so filing one into a folder β€” or dropping it onto the ungrouped section below,
     * which stores W32-T27's root sentinel β€” takes it back out of the pin. Passing the predicate
     * unconditionally (not gated on `foldersOn`) matches the shared predicate above: the pin is
     * about the rail's reading order, not about the folder feature being switched on.
     */
    (v) => isUndeletableView(v),
    (v) => v.assigned === true
  ), [shownViews, nesting, folderIdOf]);
  /**
   * ⭐⭐ WAVE 41 Β· T34 (instruction 13) β€” WHICH FOLDERS ARE SHUT RIGHT NOW.
   *
   * Read as "every folder head on screen that the user has not opened", so a folder nobody has
   * touched is closed WHENEVER it appears β€” at mount, and equally when it arrives afterwards.
   * That is the same sentence as `opened` above, from the rendering side, and it is why no
   * effect, no ref of already-seen ids and no second render are needed to hold the default.
   *
   * β›” DERIVED FROM `groups`, NOT FROM `folders`, AND THE CHEVRON IS WHY. `groupByFolder` emits
   * one group per stored folder (empty ones included) AND the synthesised groups β€” "Shared with
   * me", plus one per shared folder β€” which own a folder head and a working disclosure chevron
   * while having no record in `folders` at all. Derived from the stored list, those ids could
   * never enter this set: their chevron would write to `opened` and nothing would ever read it
   * back, so the toggle would be DEAD and the group permanently open. Reading the groups also
   * settles instruction 13 for them the same way it settles it for a stored folder, which is
   * what the user sees: a folder head is a folder head. Collapse is presentation with no write
   * behind it, so `isSyntheticFolderId` β€” the guard that keeps `item_move` / `folder_rename` off
   * these ids β€” has nothing to say here.
   *
   * β›”β›” A LIVE SEARCH YIELDS, and without this clause T34 would silently kill W41-T33. Search
   * hides folders that matched nothing (below) and T33 taught it to KEEP a parent whose child
   * matched. With every folder shut by default, `folderHiddenByCollapse` drops those descendants
   * before they can render and the survivors show as bare heads with no rows: the user types a
   * view's name and the rail answers with chevrons and nothing else, on the very first search of
   * every session. So while a needle is live nothing is collapsed. It is presentation only and
   * it never touches `opened`, so clearing the search returns each folder to exactly the state
   * the user left it in.
   */
  const standableIds = useMemo(
    () => groups.flatMap((group) => (group.folder ? [group.folder.id] : [])),
    [groups]
  );
  const atId = useMemo(() => {
    if (at === null) return null;
    if (viewNeedle) return at;
    return resolveStoredPath(at, standableIds);
  }, [at, standableIds, viewNeedle]);
  useEffect(() => {
    if (activeDatabaseKey && railDatabaseRef.current === activeDatabaseKey)
      writeRailPath(activeDatabaseKey, at);
  }, [activeDatabaseKey, at]);
  const level = useMemo(
    () =>
      levelAt(
        atId,
        foldersShown ? (folders as GridFolder[]) : [],
        shownViews,
        (view) => (folderIdOf ? folderIdOf(view.id) : null)
      ),
    [atId, foldersShown, folders, shownViews, folderIdOf]
  );
  /** The view layer's levels, database first. C4: the header shows only the LAST one's name. */
  const viewPathSegments = useMemo(
    () => [
      {
        id: null as string | null,
        name:
          databases.find((database) => database.key === activeDatabaseKey)?.label ?? "All views",
      },
      ...folderPath(atId, foldersShown ? (folders as GridFolder[]) : []).map((folder) => ({
        id: folder.id as string | null,
        name: folder.name,
      })),
    ],
    [activeDatabaseKey, atId, databases, folders, foldersShown]
  );
  const levelGroups = useMemo(() => {
    const pin: typeof groups = [];
    const heads: typeof groups = [];
    const leaves: typeof groups = [];
    const childIds = new Set(
      atId !== null && isSyntheticFolderId(atId) ? [] : level.folders.map((folder) => folder.id)
    );
    for (const group of groups) {
      const groupId = group.folder?.id ?? null;
      if (viewNeedle) {
        if (group.items.length > 0) leaves.push(group);
        continue;
      }
      if (group.pinned === true) {
        if (atId === null) pin.push(group);
        continue;
      }
      if (groupId === null) {
        if (atId === null) leaves.push(group);
        continue;
      }
      if (groupId === atId) {
        leaves.push(group);
        continue;
      }
      if (isSyntheticFolderId(groupId)) {
        if (atId === null) heads.push(group);
        continue;
      }
      if (childIds.has(groupId)) heads.push(group);
    }
    /**
     * ⭐⭐ W46-T07 (owner instruction 25) - THE DEFAULT VIEW SORTS BELOW FOLDERS.
     * The pinned group (`pin`) carries the unfiled default view; `heads` are the folder heads and
     * `leaves` the loose ungrouped views. The pin now falls AFTER every folder head.
     *
     * β›” THIS REVERSES WAVE 40 Β· T28, whose comment in `folders.ts` quotes owner instruction 30
     * verbatim: "when it is not in a folder it must sit at the very top above all folders unless
     * the user moves it down". Instruction 25 is the NEWER instruction and it wins. Do not
     * "restore" the old order on sight - an unexplained swap is exactly what invites that, which
     * is why this note exists.
     *
     * The reorder is done HERE, at the render site, and NOT in `folders.ts::groupByFolder`:
     * that pure function is shared by more than this rail, and its test
     * (`_test/folders.test.ts`, run by `verify_folders.py`) asserts `railGroups[0].pinned === true`.
     * The test asserts what the FUNCTION RETURNS; this line changes only what the RAIL PAINTS,
     * so the contract and the test both stay true and green.
     *
     * `rows` is both what the row loop paints and what `renderedViewIds` flattens for the
     * shift-click range, so one swap here keeps painted order and selection order identical.
     */
    return { heads, rows: [...heads, ...pin, ...leaves] };
  }, [groups, level, atId, viewNeedle]);
  /**
   * W46-T02 - DOES THIS GROUP RENDER ITS VIEWS AS ROWS? One arrow, read by the row loop below
   * AND by the order the shift-range is measured in. Written twice, the two copies drift and the
   * range stops matching what the person sees, which is the only thing a shift-click means.
   */
  const isLeafGroup = useCallback(
    (group: { folder?: { id: string } | null }) =>
      !group.folder || (group.folder.id ?? null) === atId || !!viewNeedle,
    [atId, viewNeedle]
  );
  /** The ids in RENDER order: pinned, then folder heads, then leaves, flattened as drawn. */
  const renderedViewIds = useMemo(
    () =>
      levelGroups.rows.flatMap((group) =>
        isLeafGroup(group) ? group.items.map((view) => view.id) : []
      ),
    [levelGroups, isLeafGroup]
  );
  const {
    selected: railSelected,
    anchorId: railAnchorId,
    onRowClick: selectRailRow,
    clear: clearSelection,
    isSelected: isRailSelected,
  } = useRailSelection(renderedViewIds);
  /** Editable source Views and recipient-local assignments, never a default/system view. */
  const railDeletable = useMemo(() => {
    const byId = new Map(views.map((view) => [view.id, view]));
    return railSelected
      .map((id) => byId.get(id))
      .filter((view): view is SavedView =>
        !!view && !isUndeletableView(view) && (view.assigned || mayEditView(view, viewer)));
  }, [railSelected, views, viewer]);
  /** The bulk-export path caps a pick at 20 checkboxes; the bar hands it the same 20. */
  const railExportIds = useMemo(() => {
    const allowed = new Set(exportableViewIds ?? []);
    return railSelected.filter((id) => allowed.has(id)).slice(0, 20);
  }, [railSelected, exportableViewIds]);
  const clearRailSel = useCallback(() => {
    clearSelection();
    setRailDeleteArmed(false);
    setRailLeftInPlace([]);
  }, [clearSelection]);
  const railMoveBlocked = railSelected.flatMap((id) => {
    const view = views.find((candidate) => candidate.id === id);
    if (!view) return [];
    const mayEdit = mayEditView(view, viewer);
    return !mayFileVerdict(view, mayEdit) || viewMoveRefusal(view, viewer)
      ? [viewDisplayName(view)] : [];
  });
  const railMoveNotice = railLeftInPlace.length > 0
    ? `Left in place: ${railLeftInPlace.join(", ")}.`
    : railMoveBlocked.length > 0 ? `Will stay in place: ${railMoveBlocked.join(", ")}.` : "";
  const moveRailViews = (ids: readonly string[], folderId: string | null) => {
    const leftInPlace: string[] = [];
    for (const id of ids) {
      const view = views.find((candidate) => candidate.id === id);
      if (!view) continue;
      const mayEdit = mayEditView(view, viewer);
      if (!mayFileVerdict(view, mayEdit) || viewMoveRefusal(view, viewer)) {
        leftInPlace.push(viewDisplayName(view));
        continue;
      }
      // The persist prop accepts a single id; call it once per selected view, in selected order.
      onItemMove?.(id, folderId ?? ROOT_FOLDER_ID);
    }
    clearRailSel();
    setRailLeftInPlace(leftInPlace);
  };
  /**
   * ESCAPE CLEARS THE SELECTION, AND NOTHING ELSE.
   *
   * Scoped three ways so it cannot close something the person did not ask to close. It is only
   * bound while a selection exists; `AnchoredOverlay` already takes Escape on a DOCUMENT CAPTURE
   * listener and stops propagation, so no open menu, export pane or picker ever reaches this
   * bubble-phase handler; and a rename box in flight keeps its own Escape.
   */
  useEffect(() => {
    // The anchor also keeps Escape available when every raw selected row is hidden.
    if (railSelected.length === 0 && railAnchorId === null && railLeftInPlace.length === 0) return;
    const onKey = (event: KeyboardEvent) => {
      if (event.key !== "Escape") return;
      if (renamingId || renamingFolder) return;
      const target = event.target as HTMLElement | null;
      const tag = target?.tagName;
      if (tag === "INPUT" || tag === "TEXTAREA" || target?.isContentEditable) return;
      clearRailSel();
    };
    document.addEventListener("keydown", onKey);
    return () => document.removeEventListener("keydown", onKey);
  }, [railSelected.length, railAnchorId, railLeftInPlace.length, renamingId, renamingFolder, clearRailSel]);
  const folderMenuF = folderMenu ? folders?.find((f) => f.id === folderMenu.id) : undefined;
  /**
   * ⭐⭐ WAVE 41 Β· T33 (instruction 12, R1) β€” MAY THE OPEN FOLDER TAKE ANOTHER FOLDER INSIDE IT?
   *
   * β›” WHERE THE 11TH LEVEL IS REFUSED, and it is refused at the DECISION rather than after it:
   * the menu row that would create the child is the last point at which the user has not yet
   * typed a name, so that is where DESIGN.md Β§4 puts the one line stating the cap. Resolved from
   * the SAME `nesting` the rail renders from, so the verdict and the picture cannot disagree.
   */
  const nestHere = folderMenuF ? mayNestFolder(nesting, folderMenuF.id) : null;
  /**
   * ⭐ WAVE 41 Β· T33 β€” THE ANCESTORS OF EVERY FOLDER A SEARCH MATCHED INSIDE.
   *
   * Item 9's rule ("a folder with no matches is noise") was written when a folder could only
   * hold views. A parent now holds folders too, so its own `items` being empty says nothing
   * about whether anything under it matched β€” and hiding it would orphan the child that did.
   *
   * ⚠ BUILT ONLY WHILE A SEARCH IS LIVE. With no needle the set is never walked and the rule it
   * serves never fires, so the idle rail pays nothing for it.
   */
  const addPreview = addTarget && folderAddPreview ? folderAddPreview(addTarget) : null;
  /**
   * ⭐⭐ W47-T12 (owner instruction 3) β€” PUT `draggedId` INSIDE `parentId`.
   *
   * β›” `mayNestFolder` IS THE ONLY ORACLE, and it is asked here rather than re-derived: it already
   * refuses a shared-folder parent, a self-nest, a move into your own descendant and the eleventh
   * level, and it returns the SENTENCE for each. W47-T11 made the create path speak those same
   * words on the same channel, so the two halves of the owner's instruction refuse in one voice.
   *
   * ⚠ THE SERVER IS A SECOND WALL, NOT A DUPLICATE OF THIS ONE. `mayNestFolder` weighs the
   * PARENT's level plus one; `core/table_store.py::validate_folder_tree` weighs the whole tree
   * after the move, so dragging a folder that has three levels under it onto a level-9 parent
   * passes here and is refused there, by name, with its own sentence on the toast channel. Both
   * refusals are visible; neither invents a second cap.
   */
  const nestFolder = (draggedId: string, parentId: string) => {
    if (!foldsNestable || !draggedId) return;
    const verdict = mayNestFolder(nesting, parentId, draggedId);
    if (!verdict.ok) {
      signal(TOAST_EVENT, verdict.reason || "That folder cannot go inside that one.");
      return;
    }
    // Already there: say nothing. An event that changes nothing still bumps every reader's
    // payload and reconciles to the identical tree β€” `reorderFolderIds`' own rule, one layer up.
    if ((nesting.parent[draggedId] ?? null) === parentId) return;
    setNestHold({ id: draggedId, parent: parentId, at: Date.now() });
    // A pending authoritative reload withholds the move and clears its local preview.
    if (onItemMove?.(draggedId, parentId) === false) setNestHold(null);
  };
  /**
   * ⭐⭐ W47-T12 β€” THE FOLDER HEAD IS WHERE THE GESTURE FORKS, and this is the whole affordance.
   *
   * β›” THE HARD PART OF THIS TICKET IS NOT THE RE-PARENT, IT IS TELLING THE TWO DROPS APART. One
   * drag now means two things, so without a visible fork every reorder becomes an accidental nest
   * and the user has to go hunting for the folder they lost. The fork is geometric and the two
   * pictures already exist in `index.css`, built for exactly these meanings:
   *
   *   Β· the top 8px of the head (or a third of it, whichever is less β€” {@link folderDropIntent})
   *     -> REORDER. `.cg-fold.is-drop-above`: a 2px inset rule along the folder's top edge,
   *     which is wave 20's own indicator and reads as "it lands here".
   *   Β· the rest of the head -> NEST. `.cg-fold.is-drop`: the tint plus dashed outline whose own
   *     comment in index.css glosses it as "drop this INTO me".
   *   Β· everywhere ELSE in the group (the view rows, the space under them) -> REORDER, exactly as
   *     before. That is deliberate: it leaves the big, easy target meaning what it always meant
   *     and asks for deliberate aim only for the new thing.
   *
   * β›” `stopPropagation` ON THE FOLD TYPE ONLY. This element sits inside the group whose
   * `dropHandlers` claim the same MIME and would immediately overwrite the fork with a plain
   * "land above". A VIEW drag (`text/plain`) is deliberately left to bubble, so filing a view by
   * dropping it on a folder head keeps working byte for byte.
   *
   * β›” AND THE DROP CLEARS `foldDrag` ITSELF. A successful nest re-parents this folder, React
   * unmounts the node that started the drag, and the browser never dispatches `dragend` on a
   * removed node β€” the scar W34-T21 left on the view path, where `is-viewdrag`'s 45% opacity
   * stuck permanently. Same shape here, same fix: clear at the drop, not only at `dragend`.
   */
  const foldHeadDropHandlers = (folderId: string) =>
    foldsReorderable
      ? {
          onDragOver: (e: React.DragEvent) => {
            if (!e.dataTransfer.types.includes(FOLD_DRAG_TYPE)) return;
            e.preventDefault();
            e.stopPropagation();
            e.dataTransfer.dropEffect = "move";
            const box = e.currentTarget.getBoundingClientRect();
            if (!foldsNestable
                || folderDropIntent(e.clientY - box.top, box.height) === "before") {
              setFoldNest(null);
              setFoldOver(folderId);
              return;
            }
            setFoldOver(null);
            // ⚠ READ OFF `foldDrag`, NEVER off `dataTransfer`. Every browser puts the payload in
            // protected mode during `dragover` β€” `getData` answers "" until the drop β€” so a
            // verdict asked of the transfer would be a verdict about an empty id, and the fill
            // would light up on targets that are about to refuse.
            setFoldNest({
              id: folderId,
              ok: !!foldDrag && mayNestFolder(nesting, folderId, foldDrag).ok,
            });
          },
          onDragLeave: (e: React.DragEvent) => {
            // The GROUP's `onDragLeave` clears `dropTarget` and `foldOver` and knows nothing
            // about the fork, so the fill would survive the pointer leaving the head.
            //
            // β›” BUT ONLY WHEN THE POINTER REALLY LEFT. `dragleave` BUBBLES, and this head holds
            // a button, a mark and a name span β€” so crossing between them fires a leave on each
            // one that arrives here, and an unguarded clear would blink the fill off and on for
            // the whole time the pointer sits on the very target it is aimed at. `relatedTarget`
            // is where the pointer went; if that is still inside this head, nothing was left.
            // (Null means it went outside the document, which IS a leave.)
            const gone = e.relatedTarget as Node | null;
            if (gone && e.currentTarget.contains(gone)) return;
            setFoldNest(null);
            setFoldOver(null);
          },
          onDrop: (e: React.DragEvent) => {
            if (!e.dataTransfer.types.includes(FOLD_DRAG_TYPE)) return;
            e.preventDefault();
            e.stopPropagation();
            const dragged = e.dataTransfer.getData(FOLD_DRAG_TYPE);
            const box = e.currentTarget.getBoundingClientRect();
            const intent = folderDropIntent(e.clientY - box.top, box.height);
            setFoldNest(null);
            setFoldOver(null);
            setFoldDrag(null);
            setDropTarget(null);
            if (!dragged) return;
            if (!foldsNestable || intent === "before") {
              reorderFolders(dragged, folderId);
              return;
            }
            nestFolder(dragged, folderId);
          },
        }
      : {};
  /**
   * ONE pair of drop handlers per group, serving TWO drags β€” a view being filed into this
   * folder (`text/plain`) and, since wave 20 item 19, a folder being dropped in front of
   * this one (`FOLD_DRAG_TYPE`). They must be one pair rather than two spreads: a second
   * `onDragOver`/`onDrop` on the same element replaces the first, silently, and the drag
   * that lost would simply stop working.
   *
   * The type is read BEFORE anything else, so a folder drag never paints the "file a view
   * in here" fill and a view drag never draws the insertion rule.
   */
  const dropHandlers = (folderId: string | null) =>
    foldersOn || foldsReorderable
      ? {
          onDragOver: (e: React.DragEvent) => {
            if (e.dataTransfer.types.includes(FOLD_DRAG_TYPE)) {
              if (!foldsReorderable) return;
              e.preventDefault();
              e.dataTransfer.dropEffect = "move";
              setFoldOver(folderId ?? "__root__");
              return;
            }
            if (!foldersOn) return;
            e.preventDefault();
            setDropTarget(folderId ?? "__root__");
          },
          onDragLeave: () => {
            setDropTarget(null);
            setFoldOver(null);
          },
          onDrop: (e: React.DragEvent) => {
            if (e.dataTransfer.types.includes(FOLD_DRAG_TYPE)) {
              const dragged = e.dataTransfer.getData(FOLD_DRAG_TYPE);
              setFoldOver(null);
              setFoldDrag(null);
              if (!foldsReorderable || !dragged) return;
              e.preventDefault();
              e.stopPropagation();
              reorderFolders(dragged, folderId);
              return;
            }
            if (!foldersOn) return;
            e.preventDefault();
            setDropTarget(null);
            // ⭐⭐ WAVE 34 Β· T21 (ruling R3) β€” THE ROW STOPS BEING FADED HERE, AND ONLY HERE.
            //
            // Owner: moving a View INTO a folder must not leave the view's icon and row blurred
            // "until i move it around". `viewDrag` is set in the view row's `onDragStart` and was
            // cleared in exactly two places: that row's own `onDragEnd`, and the SIBLING-REORDER
            // drop in `viewDropHandlers`. Filing into a folder is NEITHER β€” it is this handler,
            // which cleared `dropTarget` and never touched `viewDrag`.
            //
            // β›” AND `onDragEnd` CANNOT COVER IT, which is why the fade was permanent rather than
            // one frame long. `onItemMove` below re-parents the row, so React unmounts the node
            // that started the drag and the browser never dispatches `dragend` on a node removed
            // mid-gesture. The state stayed set and the FRESH row rendered wearing
            // `is-viewdrag` (opacity .45) until some later interaction happened to clear it.
            //
            // ⚠ Ordered BEFORE `onItemMove`, and that is free rather than delicate: `onItemMove`
            // is synchronous and React batches both state writes into the same commit, so there
            // is no frame in which the row is re-parented and still faded.
            // verify_grid_ux.py's filed-view-stays-faded control pins these three adjacent lines.
            setViewDrag(null);
            setViewOver(null);
            const id = e.dataTransfer.getData("text/plain");
            const viewSet = e.dataTransfer.getData(VIEW_SET_DRAG_TYPE);
            if (viewSet) {
              let ids: unknown;
              try { ids = JSON.parse(viewSet); } catch { /* Fall back to the single-view payload. */ }
              if (Array.isArray(ids) && ids.length > 0
                && ids.every((id): id is string => typeof id === "string" && id.length > 0)) {
                e.stopPropagation();
                moveRailViews([...new Set<string>(ids)], folderId);
                return;
              }
            }
            // ⭐⭐ W32-T27 (owner item 20) β€” DROPPING ON ROOT SENDS A VALUE, NOT `null`.
            //
            // `null` means "no placement", and `groupByFolder` reads a shared view with no
            // placement as one that arrived by grant β€” so dragging a shared view to the top
            // level put it straight back under "Shared with me". `ROOT_FOLDER_ID` is the
            // receiver saying they filed it here, which is a different fact and now has a
            // different value.
            //
            // ⚠ SENT FOR EVERY ITEM, not only shared ones, and that is deliberate: a rail that
            // emits one shape for a shared view and another for your own has two move paths to
            // keep in step, and the bug being fixed here is exactly what happens when two
            // layers disagree about what absence means. For an unshared view the two are
            // equivalent β€” `groupByFolder` maps the sentinel onto the same root bucket.
            // The refusal is asked BEFORE the emit, so a refused drop snaps back by not moving.
            // A read-only share is not refused (S85-T33, R30). `dropHandlers` is rebuilt every
            // render, so `views` and `viewer` are the current ones.
            const dragged = id ? views.find((view) => view.id === id) : undefined;
            const refusal = dragged ? viewMoveRefusal(dragged, viewer) : null;
            if (refusal) {
              signal(TOAST_EVENT, refusal);
              return;
            }
            if (id) onItemMove?.(id, folderId ?? ROOT_FOLDER_ID);
          },
        }
      : {};
  const noteView = noteFor
    ? views.find((view) => view.id === noteFor.viewId)
    : undefined;
  /*
   * β›”β›” `importantNote` IS DELETED WITH THE BADGE IT LABELLED (W35-T27, owner item 9 / R4).
   *
   * It existed because W34-T20's ruling took the WORD off the rail's summed badge and left a
   * figure with no noun, so the whole sentence moved into that one element's `title` and
   * `aria-label`. Item 9 removes the badge itself, so there is no element left to label. The
   * per-view badges keep their own `countNotes` sentence (see the view row below) β€” that
   * derivation is separate and is untouched.
   *
   * ⚠ D-252's lesson does NOT die here, it moves: "a total that could count nothing must not
   * paint a manufactured 0" now lives entirely in the per-view badge and in E's
   * `GET /starred/counts`, whose `notes` map carries the cause for a view whose count is not
   * free (contract C3). Nothing about it is now stated in two places.
   */

  /**
   * ⭐⭐ W46-T01 β€” A VIEW CREATED INSIDE A FOLDER LANDS IN THAT FOLDER. Filed on arrival.
   *
   * β›” THE PLACEMENT IS NOT PASSED THROUGH `onCreate`, and that is the whole design of this
   * ticket. `onCreate` is `(name, mode)` and its ONE consumer is the grid's `createView`;
   * widening it with a third `parent` argument would declare a contract nothing
   * reads, which is a defect class in this repo rather than a fix. So the destination is applied
   * from here through `onItemMove` β€” the SAME channel the drag drop and the Move-to menu already
   * use, so a view has one way of being filed and not two that can drift apart.
   *
   * ⚠ A REF, NOT STATE. It must not cause a render of its own, and it must survive the render
   * that `onCreate` itself causes. It holds the destination, the ids that existed at the moment
   * Create was pressed, and the typed name, so the arrival can be identified exactly rather than
   * guessed at as "whichever view is new".
   */
  const pendingFileRef = useRef<
    { into: string; before: Set<string>; name: string } | null
  >(null);
  useEffect(() => {
    const pending = pendingFileRef.current;
    if (!pending) return;
    const arrivals = views.filter((view) => !pending.before.has(view.id));
    if (arrivals.length === 0) return;
    // Normally exactly one view arrives. If two land in the same window (a concurrent tab, a
    // refetch), the typed name is the discriminator; with no match this files nothing at all,
    // because moving the wrong view is worse than leaving the new one at the top level.
    const arrived =
      arrivals.length === 1
        ? arrivals[0]
        : arrivals.find((view) => viewDisplayName(view) === pending.name);
    /*
     * β›” CLEARED WHETHER OR NOT IT FILES, and before the guard below can return. A destination
     * that outlived its own attempt would fire again on the next unrelated change to `views` and
     * move a view nobody asked to move.
     */
    pendingFileRef.current = null;
    if (!arrived) return;
    // The same verdict every other filing door asks, so a view that cannot be filed by dragging
    // cannot be filed by being born here either.
    /**
     * ⭐⭐ W50-T11 / D-249 β€” AND IT SAYS SO. This return was silent, and a silent refusal on a
     * door the user just used reads as the app losing the click: they pick "New view in folder",
     * the view appears at the top level, and nothing anywhere explains why. DESIGN Β§4 asks a
     * refusal to be a plain sentence naming its subject, so this one gives the reason rather than
     * reporting that something failed.
     *
     * This door asks `viewMoveRefusal`, the helper every filing door asks (S85-T33). The arrival
     * is a view this user just created, so it is their own and the helper returns null.
     */
    const refusal = viewMoveRefusal(arrived, viewer);
    if (refusal) {
      signal(TOAST_EVENT, refusal);
      return;
    }
    onItemMove?.(arrived.id, pending.into);
  }, [views, viewer, onItemMove]);

  const create = () => {
    /*
     * β›” CLEARED FIRST, on every attempt. If an earlier create never produced a view (the host
     * refused it, or the pane was abandoned mid-flight), its destination must not survive to
     * catch some unrelated view that arrives later.
     */
    pendingFileRef.current = null;
    const value = name.trim();
    if (!value || !creating) return;
    /*
     * The destination is re-checked HERE, at the commit, exactly as `createFolder` re-checks its
     * own parent below: the pane outlives the click that opened it, and the folder it was pointed
     * at can be deleted or arrive a level deeper from another tab while the name is being typed.
     * A refused destination leaves the view at the top level, which is where a view can always go.
     *
     * ⚠ TWO SOURCES, IN THIS ORDER. `folderParent` is the explicit destination a door set when it
     * opened the pane; `atId` is the folder the rail is currently standing in, which is what the
     * ordinary "+ Create new" door means by "here". Root is `null` from both, and then the effect
     * above is inert and the view is created at the root as before.
     */
    const wanted = folderParent ?? atId;
    const into = wanted && mayNestFolder(nesting, wanted).ok ? wanted : null;
    if (into)
      pendingFileRef.current = {
        into,
        before: new Set(views.map((view) => view.id)),
        name: value,
      };
    // Views start as a personal source. The Share view dialog is the single place where people
    // choose the audience and role, so creation never embeds a second access model.
    onCreate(value, creating);
    // Filing into a folder the rail is not standing in has to OPEN it, or the view is created
    // invisibly β€” the same regression T34 recorded for folders, one surface over.
    if (into && into !== atId) setAt(into);
    setName("");
    setCreating(null);
    // WAVE 20 item 20 β€” the two steps share ONE panel, so the anchor outlives step 1 and
    // has to be released here. Left set, the flyout would spring back to the type chooser
    // the instant the view was created.
    setCreateMenu(null);
  };

  /** Item 20 β€” abandon the whole flyout, from either step. Escape, an outside click and
   *  Cancel all mean the same thing ("I am not creating anything"), so they call one
   *  function rather than three combinations of setters β€” and abandoning drops the DRAFT
   *  too, or the next "+ Create new…" would hand back a half-filled form from a decision
   *  the user already walked away from. */
  const closeCreate = () => {
    setCreating(null);
    setCreateMenu(null);
    // W50-T11 β€” abandoning the flyout drops its DESTINATION too, for the same reason it already
    // drops the draft name: the next opening must not inherit a decision the user walked away from.
    setCreateInto(null);
    setName("");
  };

  /**
   * ⭐⭐ W47-T11 (owner instruction 3) β€” WHERE A NEW FOLDER ACTUALLY GOES, answered ONCE for both
   * the pane's label and the Create click, so the form cannot name one destination and the
   * commit quietly choose another.
   *
   * β›” `folderParent ?? atId` IS THE FIX, and the missing half was the whole of what the owner
   * reported as *"Creating a folder inside a folder needs to work, it doesn't for now. Only view
   * works."* `create` (views, above) has always read BOTH sources; this door read only the
   * explicit one, so "+ Create new" then "Folder" while the rail was standing three levels down
   * built a folder at the TOP LEVEL. Both doors now mean the same thing by "here", which is why
   * one worked and the other did not.
   *
   * ⚠ THE PARENT IS RESOLVED AT THE COMMIT, not trusted from when the pane opened (W41-T33's
   * reason, unchanged): the pane outlives the click that pointed it somewhere, and that folder
   * can be deleted or arrive a level deeper from another tab while the name is being typed.
   *
   * ⚠ A PARENT THE TREE CANNOT RESOLVE STILL FALLS TO THE ROOT IN SILENCE, exactly as it did
   * before, and only the verdicts a person can actually cause are spoken. `atId` is returned raw
   * while a search needle is live, so an unresolvable id is a stale path rather than a placement
   * anyone chose; refusing it by name would replace the old lie with a new one.
   */
  const folderDestOf = (
    wanted: string | null
  ): { into: string | null; refusal: string | null } => {
    if (!wanted) return { into: null, refusal: null };
    if (!isSyntheticFolderId(wanted) && !nesting.depth[wanted])
      return { into: null, refusal: null };
    const verdict = mayNestFolder(nesting, wanted);
    if (verdict.ok) return { into: wanted, refusal: null };
    /*
     * The CAUSE comes from `mayNestFolder`, which is the one place that decides it; the OUTCOME
     * and the next step are added here, because a sentence that explains the cap and stops
     * leaves the user hunting for a folder that was never made. Same shape as the refusals
     * `core/grid_events.py` already sends from the other wall.
     */
    return {
      into: null,
      refusal:
        `${verdict.reason ?? "That folder cannot hold another folder."} `
        + "Nothing was created, so pick a different place for it and try again.",
    };
  };
  const folderDest = folderDestOf(folderParent ?? atId);

  const createFolder = (name: string) => {
    const value = name.trim();
    if (!value) return;
    /*
     * ⭐⭐ W47-T11 β€” A REFUSED NESTING IS SAID OUT LOUD AND NOTHING IS WRITTEN.
     *
     * β›” THIS LINE USED TO READ `mayNestFolder(...).ok ? folderParent : null`, which put the
     * folder at the top level with no word said. From outside that is indistinguishable from
     * "creating a folder inside a folder does not work": the user aimed at a folder, pressed
     * Create, and found the result somewhere else. The pane is deliberately LEFT OPEN with the
     * typed name in it, so the choice between cancelling and aiming somewhere else is still
     * theirs to make.
     */
    if (folderDest.refusal) {
      signal(TOAST_EVENT, folderDest.refusal);
      return;
    }
    const into = folderDest.into;
    /**
     * ⭐⭐ WAVE 41 Β· T34 β€” FILING A FOLDER INTO ONE OPENS IT, or the new folder is created
     * INVISIBLY.
     *
     * β›” THIS IS T34's OWN REGRESSION ON T33, and it only exists once folders default to shut.
     * A collapsed folder KEEPS ITS HEAD (`folderHiddenByCollapse` reads ancestors only), so its
     * "…" menu β€” and T33's "New folder inside" row on it β€” stays reachable while it is closed.
     * Create a folder in there and `folderHiddenByCollapse` finds the shut parent above the new
     * child and renders it as null: the user names a folder, presses Create, and the rail does
     * not move. Before T34 the parent was open by default and the path could not be walked.
     *
     * ⚠ THE PARENT ALONE IS ENOUGH, no ancestor walk. The head that carries this menu renders
     * only when NO ancestor of it is collapsed, so reaching this line already proves every
     * folder above `into` is open.
     *
     * ⚠ IT CAN ONLY ADD. Nothing here removes an id, so this cannot close a folder the user
     * opened, and the same-set short-circuit keeps a repeat create from re-rendering the rail.
     */
    if (into) setAt(into);
    onFolderCreate?.(value, into);
    setCreatingFolder(false);
    setFolderAnchor(null);
    setFolderParent(null);
  };

  /**
   * WAVE 20 item 20 β€” the view door keeps the anchor, because the name step
   * now renders in the SAME anchored box the type chooser used. The old comment ("close
   * the flyout first, or the menu sits on top of the input") described the bug the owner
   * reported from the other side: the two steps of one action were drawn in two different
   * places, one beside the rail and one inside it, so step 2 read as an unrelated form.
   * One panel, two contents, one geometry.
   *
   * The folder door closes the menu and opens the shared naming popup at that same trigger.
   */
  /**
   * ⭐ W46-T01 β€” IT TAKES A PARENT, exactly as its sibling `startFolder` already does, and the
   * default is the same `null`.
   *
   * ⚠ THE `setFolderParent` IS LOAD-BEARING EVEN THOUGH EVERY CALLER TAKES THE DEFAULT.
   * `startFolder(folderMenuF.id)` sets `folderParent` and nothing clears it when that pane is
   * abandoned, so opening the create menu afterwards would find a stale folder id sitting there
   * and `create` would file the new view into a folder the user walked away from. Setting it here
   * makes "+ Create new" mean the level the rail is actually standing in, every time.
   */
  const startView = (mode: DisplayMode, parent: string | null = null) => {
    setCreatingFolder(false);
    setFolderParent(parent);
    setCreating(mode);
  };
  /**
   * ⭐⭐ W41-T33 β€” ONE DOOR, TWO DESTINATIONS. "+ Create new" opens the pane at the top level;
   * a folder's own "..." menu opens the SAME pane pointed at that folder. DESIGN.md Β§4: a
   * nested folder is made by the control that already makes folders, not by a second form.
   */
  const startFolder = (parent: string | null = null) => {
    setFolderAnchor(createMenu ?? folderMenu?.anchor ?? null);
    setCreateMenu(null);
    setCreating(null);
    setFolderParent(parent);
    setCreatingFolder(true);
  };

  /**
   * WAVE 20 items 18/23/26 (R10, C-SHARE) β€” open the access editor for a view or a
   * folder.
   *
   * ⚠ A WINDOW EVENT, NOT A PROP, and not for convenience. The dialog is the SHELL's
   * (one editor for views, folders and databases β€” R10 asks for one vocabulary), and
   * this tree is host-neutral: `customer-grid/**` must not import a shell. The frame
   * already listens on this channel for toasts and staleness; this is one more note on
   * it. The literal is spelled once here and once in `shell/shareModel.ts`, which is
   * where it becomes a shared constant when S3 publishes it in `apiContract.ts`
   * (amendment A-S4-4).
   *
   * β›” It degrades to NOTHING when no shell is listening (the Streamlit-era bare grid):
   * a dispatched event nobody hears opens no dialog and throws no error β€” which is the
   * right failure for a frame-level surface reached from a rail.
   */
  const openShare = (kind: "view" | "folder", id: string, label: string) => {
    window.dispatchEvent(
      new CustomEvent("aios:share-open", { detail: { kind, id, label } })
    );
  };

  const onMenuKeyDown = (event: ReactKeyboardEvent<HTMLElement>) => {
    if (!["ArrowDown", "ArrowUp", "Home", "End"].includes(event.key)) return;
    const items = [
      ...event.currentTarget.querySelectorAll<HTMLButtonElement>('[role="menuitem"]'),
    ];
    if (!items.length) return;
    event.preventDefault();
    const current = items.indexOf(document.activeElement as HTMLButtonElement);
    const next =
      event.key === "Home"
        ? 0
        : event.key === "End"
          ? items.length - 1
          : event.key === "ArrowDown"
            ? (current + 1) % items.length
            : (current - 1 + items.length) % items.length;
    items[next]?.focus();
  };

  /**
   * ⭐⭐ S72-T58 / C4 (owner instruction 39, R89): THE RAIL'S ONE HEADER ROW. Back, Forward, the
   * current place's name, the database "…" menu, then Minimize views and Ask about this data.
   * The name is the last level only, never a path. `DataDatabaseNavigator` renders this first,
   * so `.cg-views-top` stays the rail's first child and the data history stays inside it.
   */
  const railPlace = ({ place, canBack: canDataBack, back: stepDataBack }: DataRailPath) => {
    const name = place?.name ?? viewPathSegments[viewPathSegments.length - 1]?.name ?? "All views";
    return (
      <>
        <PathBackButton
          disabled={place ? !place.canBack : !canViewBack && atId === null && !canDataBack}
          onClick={place ? place.back : () => {
            // History first. The parent walk is unreachable (`ids[0]` is null) and stays so Back never pushes.
            if (canViewBack) stepViewLevel(-1);
            else if (atId !== null) setAt(level.parent);
            else stepDataBack();
          }}
        />
        <PathForwardButton
          disabled={place ? !place.canForward : !canViewForward}
          onClick={place ? place.forward : () => stepViewLevel(1)}
        />
        <span className="cg-rail-name" aria-current="page" title={name}>{name}</span>
        {!place && databaseActions ? <span className="cg-rail-menu">{databaseActions}</span> : null}
      </>
    );
  };
  const railHeader = (path: DataRailPath) => (
    <>
      {/* Owner item 11 β€” the rail's own minimize control: the same three-bars glyph as the
          shell nav's, because the two rails are one idea ("a navigation bar folds"). */}
      <div className="cg-views-top">
        {!folded && railPlace(path)}
        <button
          type="button"
          className="cg-rail-toggle"
          aria-label={folded ? "Expand views" : "Minimize views"}
          aria-expanded={!folded}
          title={folded ? "Expand views" : "Minimize views"}
          onClick={narrow ? () => setNarrowOpen((open) => !open) : toggleRail}
        >
          <PanelToggleIcon open={!folded} />
        </button>
        {/* R20 (SDLC 68) reverses W40-T22's folded-state hide: Ask moves to the C9 header
            slot when folded. Keep the W37 C6 chat-toggle class literal unchanged. */}
        {onToggleChat && !folded && (
          <button
            type="button"
            className={"cg-chat-toggle" + (chatOpen ? " is-on" : "")}
            aria-label={chatOpen ? "Close the chat about this data"
                                 : "Ask about this data"}
            aria-expanded={chatOpen}
            title={chatOpen ? "Close the chat about this data" : "Ask about this data"}
            onClick={onToggleChat}
          >
            <svg width="16" height="16" viewBox="0 0 16 16" fill="none" aria-hidden="true">
              <path d="M13.4 9.2c0 1.5-1.3 2.7-2.9 2.7H6.9l-3 2.1v-2.3a2.8 2.8 0 0 1-1.3-2.3V5.1c0-1.5 1.3-2.7 2.9-2.7h5c1.6 0 2.9 1.2 2.9 2.7z"
                    stroke="currentColor" strokeWidth="1.3" strokeLinejoin="round" />
              <path d="M5.9 7.2h4.2" stroke="currentColor" strokeWidth="1.3"
                    strokeLinecap="round" />
            </svg>
          </button>
        )}
        {/* β›”β›” THE DATABASE'S OWN TOTAL IS DELETED FROM THIS ROW (W35-T27, owner item 9 / R4).
            Owner, verbatim: *"remove [the important count] anywhere else but the View itself."*
            W33-T16 put a summed badge here and W34-T20 stripped its label; item 9 removes the
            badge outright. **The PER-VIEW badge on each view row is untouched** β€” that is what
            "the View itself" means, and it is the half that survives.
            ⚠ C4 (S72-T58) puts Back, Forward and the place name before the toggle in this row.
            β›” `verify_grid_ux.py`'s `[VIEWS RAIL]` scan is INVERTED, not deleted: it asserts the
            badge's ABSENCE from this row and its PRESENCE on the view rows, so re-adding one
            reds it. */}
        {/* I13 β€” the "Views / All changes saved" header block is GONE and everything moved up. */}
      </div>

    </>
  );

  return (
    <>
    <aside
      ref={setRailEl}
      className={"cg-views" + (folded ? " is-collapsed" : "")
        + (folded && headerSlot ? " is-header-folded" : "")
        + (narrow && narrowOpen ? " is-narrow-open" : "")}
      aria-label={databases.length ? "Record and View navigation" : "Views"}
    >
      <DataDatabaseNavigator
        databases={databases}
        activeDatabaseKey={activeDatabaseKey}
        folders={databaseFolders}
        onSelect={onSelectDatabase}
        onMove={onDatabaseMove}
        onFolderRename={onDatabaseFolderRename}
        onFolderDelete={onDatabaseFolderDelete}
        renderActions={renderDatabaseActions}
        createControl={databaseCreateControl}
        hosted={hosted}
        header={railHeader}
      >
        {() => (
          <>

      {/* A live view search states its scope. The header keeps the place name and the "…" menu. */}
      {viewNeedle ? (
        <div className="cg-fold-empty" data-view-folder-path>
          Showing matches in every folder
        </div>
      ) : null}

      {/* I14 β€” "+ Create new…", left-aligned, opening a flyout to the RIGHT of the rail that
          lists every creatable view type AND "Folder".

          Wave-10 item 12: the second door β€” a separate "+ New folder" link that used to sit
          directly under this one β€” is DELETED. It was a duplicate of the flyout's own Folder
          row, so the rail offered two controls that did the same thing. `startFolder()` still
          has exactly one caller (the flyout row); only the redundant entry point is gone.
          ⚠ wave17 R1 β€” the reason `.cg-fold-new` was kept has EXPIRED. It survived wave 10
          because `CohortSidebar.tsx` rendered its own "+ New folder" under that class and had
          no create-flyout to fold it into; that file is deleted this wave, so the class now has
          no consumer in this tree. Left in index.css rather than swept blind: a CSS rule with
          no consumer is inert, and hunting one down mid-wave is how a rule something else still
          reads gets removed. Named here so the sweep is a decision, not a discovery.

          ⭐⭐ WAVE 47 T10 (owner instruction 1) β€” `cg-link-btn cg-create-btn` AND THE TWO SPANS
          BELOW ARE NOW READ BY A SECOND CALL SITE. The owner walked from a database into a
          folder path and saw one job in two treatments, and named THIS one as the keeper. So
          `shell/NavExtras.tsx::CreateNewRow` β€” the door the data layer mounts through
          `createControl`, one level up in this same rail β€” renders exactly this markup instead
          of its old `.shell-newfolder` register.
          β›” CONSEQUENCE FOR ANY LATER EDIT HERE: these class names are a shared contract now,
          not private to this button. Changing the treatment means changing both call sites, and
          moving it to a local class re-opens the drift the owner reported. */}
      {!folderReadOnly && <div className="cg-create-new">
        <button
          type="button"
          className="cg-link-btn cg-create-btn"
          disabled={readOnly}
          aria-haspopup="menu"
          aria-expanded={!!createMenu}
          onClick={(event) => {
            // β›” THE ANCHOR IS HOISTED OUT OF THE UPDATER β€” the same line that took the whole
            // app white from the view row's "…" (see the long note at that button). React
            // nulls `event.currentTarget` when the handler returns and may re-invoke a
            // functional updater afterwards, so `setCreateMenu(cur => … event.currentTarget)`
            // can store null. Item 20 made this panel outlive a single click β€” it now carries
            // the name step too β€” so a randomly-nulled anchor would close a form mid-typing
            // rather than merely mis-place a menu.
            const anchor = event.currentTarget;
            if (createMenu) {
              closeCreate();
              return;
            }
            // Every open starts at the type chooser: `creating` left set by an abandoned
            // flyout would re-enter at step 2 for a kind nobody just picked.
            setCreating(null);
            // W50-T11 β€” and at NO destination. This door means "here", which `create()` reads
            // off `atId`; a folder left over from the "…" menu would file the view somewhere
            // the user is not standing.
            setCreateInto(null);
            setCreateMenu(anchor);
          }}
        >
          <span className="cg-create-icon" aria-hidden="true">+</span>
          <span className="cg-create-label">Create new…</span>
        </button>
      </div>}

      {/* Owner item 9 β€” "Find a view". Borderless on the white rail (no box until it is
          being used); focus paints the brand-purple outline. Clearing the query restores
          the full rail β€” filtering never persists. */}
      <div className="cg-find-view">
        <svg
          className="cg-find-view-icon"
          width="14"
          height="14"
          viewBox="0 0 16 16"
          fill="none"
          aria-hidden="true"
        >
          <circle cx="7" cy="7" r="4.4" stroke="currentColor" strokeWidth="1.35" />
          <path
            d="m10.4 10.4 3.1 3.1"
            stroke="currentColor"
            strokeWidth="1.35"
            strokeLinecap="round"
          />
        </svg>
        {/* W46-T04 - the PLACEHOLDER reads "Find…" so this box and the data layer's twin are
            the same control to the eye; the ACCESSIBLE NAME stays "Find a view", because a
            screen reader gets no layer context from three dots and because
            `verify_w45_data_applications.py` indexes on that exact literal. */}
        <input
          type="text"
          value={viewQuery}
          placeholder="Find…"
          aria-label="Find a view"
          onChange={(event) => setViewQuery(event.target.value)}
          onKeyDown={(event) => {
            if (event.key === "Escape") setViewQuery("");
          }}
        />
      </div>

      {/* β›” WAVE 20 item 20 β€” THE CREATE FORM NO LONGER RENDERS HERE. It is the flyout's
          second step, inside the same `AnchoredOverlay` (below, next to the type list it
          follows). This comment stands in for the moved markup because the move IS the
          item: two steps of one action that used to appear in two different places. */}
      {foldersOn && onFolderCreate && creatingFolder && (
        <FolderNameDialog
          anchor={folderAnchor}
          title={folderDest.into && folders?.find((folder) => folder.id === folderDest.into)
            ? `New folder in ${folders.find((folder) => folder.id === folderDest.into)!.name}`
            : "New folder"}
          siblingNames={(folders ?? []).filter((folder) =>
            (nesting.parent[folder.id] ?? null) === folderDest.into).map((folder) => folder.name)}
          onSubmit={createFolder}
          onDismiss={() => {
            setCreatingFolder(false);
            setFolderAnchor(null);
            setFolderParent(null);
          }}
        />
      )}

      {/* I14 β€” the flyout. To the RIGHT (placement right-start), every creatable view type
          with its own pastel mark, and Folder LAST behind a separator: it is not a view, and
          the owner put it at the bottom of the list rather than among them. */}
      {createMenu && (
        <AnchoredOverlay
          anchor={createMenu}
          className="cg-view-menu cg-create-flyout"
          placement="right-start"
          // WAVE 20 item 20 β€” ONE panel, two contents. A menu of choices and a form are
          // different KINDS of thing to a screen reader even when they are one box to the
          // eye, so the role and the label follow the step rather than being frozen at the
          // panel's first purpose.
          role={creating ? "dialog" : "menu"}
          ariaLabel={
            creating ? `New ${MODE_LABELS[creating].toLowerCase()} view` : "Create new"
          }
          onDismiss={closeCreate}
          // β›” THE ARROW-KEY HANDLER IS STEP 1's ONLY. `onMenuKeyDown` swallows
          // ArrowUp/ArrowDown to walk `[role=menuitem]`; over a text input that is the
          // cursor keys refusing to move through what you just typed.
          {...(creating ? {} : { onKeyDown: onMenuKeyDown })}
          dataKind={creating ? "create-new-name" : "create-new"}
        >
          {creating ? (
            <div className="cg-view-create cg-create-form">
              <label htmlFor="cg-new-view">
                {/* The prompt NAMES the kind picked one step ago β€” the panel replaced its
                    own contents, so without this the box gives no sign that "Calendar" was
                    ever chosen. */}
                New {MODE_LABELS[creating].toLowerCase()} view
              </label>
              <input
                id="cg-new-view"
                className="cg-input"
                autoFocus
                // The overlay's own initial-focus effect fires on MOUNT, and this panel does
                // not re-mount between the two steps β€” so the input carries `autoFocus` (React
                // focuses it when it mounts) and the marker the other in-panel forms use.
                data-overlay-autofocus
                value={name}
                placeholder="e.g. Florida at risk"
                onChange={(event) => setName(event.target.value)}
                onKeyDown={(event) => {
                  if (event.key === "Enter") create();
                  // Escape is handled by the overlay layer too; both mean "abandon", and
                  // calling the same closer twice is idempotent.
                  if (event.key === "Escape") closeCreate();
                }}
              />
              <p className="cg-create-share-note">
                This view starts private. After you create it, use Share view to choose who can
                view or edit it.
              </p>
              <div className="cg-form-actions">
                <button
                  type="button"
                  className="cg-btn cg-btn--primary"
                  onClick={create}
                  disabled={!name.trim()}
                >
                  Create
                </button>
                <button type="button" className="cg-btn" onClick={closeCreate}>
                  Cancel
                </button>
              </div>
            </div>
          ) : (
            <>
              {/**
                * ⭐⭐ WAVE 41 Β· T39 (instruction 5) β€” FOLDER IS THE FIRST ROW, ABOVE GRID VIEW.
                *
                * Owner: *"In '+ Create new', Folder goes to the top, above Grid view."* Grid view
                * is `CREATABLE_MODES[0]`, so "above Grid view" is above the WHOLE map, not a
                * position inside it.
                *
                * β›” THE ROSTER IS NOT REORDERED, and that is the point of moving the JSX instead.
                * `CREATABLE_MODES` is the one list `verify_icons.py` pins by exact join, the mode
                * dropdown reads for its column order, and `icons.test.ts` compares against
                * `aios_grid.py::DISPLAY_MODES`. Folder is not a display mode at all β€” it has no
                * entry there to move β€” so the reading order of this ONE flyout is a fact about
                * this flyout, and it belongs here.
                *
                * ⚠ THE SEPARATOR TRAVELS WITH THE ROW, inside the same gate, and it now sits
                * BELOW Folder rather than above it. Left where it was it would have been the
                * flyout's first child, drawing a rule against the top edge whenever folders are
                * off; kept inside the fragment it cannot orphan, because the only thing that can
                * render it is the row it divides.
                */}
              {foldersOn && onFolderCreate && (
                <>
                  <button
                    type="button"
                    role="menuitem"
                    className="cg-create-row"
                    onClick={() => startFolder()}
                  >
                    <FolderMark size={16} />
                    <span>Folder</span>
                  </button>
                  <div className="cg-menu-sep" role="separator" aria-hidden />
                </>
              )}
              {CREATABLE_MODES.map((mode) => (
                <button
                  key={mode}
                  type="button"
                  role="menuitem"
                  className="cg-create-row"
                  /* ⭐ W50-T11 β€” the destination the flyout was OPENED with. `null` from the
                     rail's own "+ Create new…" door (it clears `createInto`), so this call is
                     byte-equivalent to the shipped `startView(mode)` on that path; the folder
                     "…" menu's "New view in folder" is the caller that supplies a folder id. */
                  onClick={() => startView(mode, createInto)}
                >
                  {/* size 16 β€” item 13's "bigger icons", and the SAME 16 the view rows use,
                      so a Calendar is one mark at one size on this whole surface. */}
                  <ToneModeIcon mode={mode} tone={MODE_TONE[mode]} size={16} />
                  <span>{MODE_LABELS[mode]}</span>
                </button>
              ))}
            </>
          )}
        </AnchoredOverlay>
      )}

      <div className="cg-view-list cg-views-scroll">
        {/**
          * ⭐⭐ W50-T11 / D-592 β€” WHILE `/workspace` IS IN FLIGHT THE RAIL DRAWS A SKELETON, NOT
          * AN EMPTY LIST.
          *
          * β›” THE EMPTY LIST IS A CLAIM, AND IT WAS BEING MADE BEFORE THE ANSWER ARRIVED.
          * `views` is `[]` both before `/workspace` answers and when a database genuinely has no
          * saved views, and the rail rendered the same nothing for both. On a cold container or a
          * degraded database that window has been measured in MINUTES, so "this database has no
          * views" was the whole experience rather than one frame of it.
          *
          * β›” AND ONLY WHILE THERE IS NOTHING TO SHOW (`views.length === 0`). A re-read triggered
          * by a write must not blank a populated rail β€” `useCustomerData.ts::reread` holds exactly
          * that line for the payload ("absent stays absent β€” never blank a live panel"), and a
          * skeleton painted over rows the user is reading would break it from the other side.
          *
          * ⚠ IT BORROWS THE SHELL'S OWN SKELETON CLASSES, deliberately, and this rail adds no
          * stylesheet of its own for it. `shell/navExtras.css` declares `.shell-rail-skeleton*`
          * UNSCOPED (only the `.shell-nav.is-rail-loading > *` hider is scoped to the nav), so the
          * marks paint here unchanged β€” and a second, near-identical `cg-` skeleton beside it is
          * how the two navigation rails start looking like two products.
          */}
        {loading && views.length === 0 ? (
          <div className="shell-rail-skeleton" role="status" aria-label="Loading views">
            {[0, 1, 2, 3, 4].map((row) => (
              <div className="shell-rail-skeleton-row" key={row} aria-hidden="true">
                <span className="shell-rail-skeleton-mark" />
                <span className="shell-rail-skeleton-bar" />
              </div>
            ))}
          </div>
        ) : null}
        {levelGroups.rows.map((group) => {
        const gid = group.folder?.id ?? null;
        /**
         * ⭐⭐ WAVE 41 Β· T33 (instruction 12, R1) β€” HOW DEEP THIS FOLDER SITS, AND WHETHER IT
         * SHOWS AT ALL.
         *
         * ⚠ A SYNTHETIC GROUP HAS NO ENTRY IN `nesting` and must not acquire one: `__shared__`
         * and every `__sharedfld__:` group are a reading of the view list, not records, so they
         * fall to level 1 and to "not hidden" β€” which is exactly where they rendered before this
         * ticket. The same is true of both `folder: null` groups.
         */
        const asLeaves = isLeafGroup(group);
        /**
         * ⭐⭐ WAVE 40 Β· T28 (owner instruction 30) β€” THE PIN GROUP: the unfiled default views,
         * rendered above every folder.
         *
         * β›” IT IS A SECOND `folder: null` GROUP, so every expression below that reads
         * `gid ?? "__root__"` now has TWO groups answering to it and each one has to be told
         * which it is. That is not cosmetic: `dropTarget`, `foldOver` and `viewDrag` all
         * compare against that same fallback string, so leaving them alone would paint the
         * drop fill and the folder insertion rule on THIS section every time the user hovered
         * the real ungrouped section below it β€” one hover, two highlights, and only one of them
         * is where the item would land.
         *
         * ⚠ SO `isRoot` EXCLUDES IT, and that is the load-bearing line. `isRoot` is what grants
         * the drag-time drop AREA (`is-viewdrop`), and there must be exactly ONE of those: it is
         * the surface a user drops the default view onto to move it down, and a second one that
         * files it right back where it started would make the gesture unreachable.
         */
        const isPinnedGroup = group.pinned === true;
        const isRoot = gid === null && !isPinnedGroup;
        /**
         * ⭐ WAVE 21 item 9 (R12/C1) β€” "Shared with me" IS NOT A STORED FOLDER, and every
         * folder affordance below has to know it.
         *
         * The group is synthesised from `shared: true` views (`folders.ts`), so there is no
         * record behind it: a drop would emit `item_move(viewId, "__shared__")` and persist
         * a folderId naming a folder that does not exist, and a folder-drag would send an
         * order containing an id `reorderFolderIds` was never given. Both write nonsense the
         * server would store. The row menu was already suppressed for this id in wave 20;
         * the DRAG surfaces were not, because nothing ever constructed the group.
         */
        // ⭐ W34-T25 (R11): `isSyntheticFolderId`, NOT `=== SHARED_FOLDER_ID`. There is more than
        // one synthesised group now (one per shared FOLDER), and a rail that suppressed writes on
        // "Shared with me" while offering them on a colleague's folder would emit `item_move` /
        // `folder_rename` / `folder_delete` against an id that exists in nobody's store.
        const isSynthetic = isSyntheticFolderId(gid);
        // C1 injects this system-owned folder into the ordinary folder list. It remains
        // readable and expandable, but no generic rename, move, delete, or menu control is
        // offered for it. Keep the additive wire fact local until its broader type owner lands.
        const isManaged =
          (group.folder as (GridFolder & { managedBy?: "loopable" }) | undefined)?.managedBy ===
          "loopable";
        const isLevelFolder = asLeaves && gid !== null && !isSynthetic && !viewNeedle;
        return (
        <div
          /* ⭐ W40-T28 β€” a key of its own. Both this group and the ungrouped section have a null
             folder, so the old `gid ?? "__root__"` would give React two children with the same
             key and it would reconcile one over the other. */
          key={isPinnedGroup ? "__pinned__" : gid ?? "__root__"}
          /**
           * ⭐⭐ W47-T12 β€” WHICH OF THE TWO THINGS THIS DROP WOULD DO, in a word, on the element.
           *
           * β›” AN ATTRIBUTE RATHER THAN A THIRD CLASS, and the reason is a fence rather than a
           * preference: this ticket may not add a CSS rule, so a class nothing styles would be
           * invisible and a class something styles would need that rule. The two PICTURES are
           * `.is-drop` (nest) and `.is-drop-above` (reorder), which already exist; this says the
           * same thing in a form a person driving the gesture, or a headless check, can read
           * without measuring pixels β€” including the one state that paints NOTHING on purpose,
           * `refused`, which is otherwise indistinguishable from the app not noticing the pointer.
           *
           * ⚠ ABSENT unless a folder drag is actually in flight, so the idle rail's DOM is
           * byte-identical to the pre-T12 one.
           */
          data-fold-drop={
            foldDrag === null
              ? undefined
              : foldNest && foldNest.id === gid
                ? (foldNest.ok ? "nest" : "refused")
                : !isPinnedGroup && foldOver === (gid ?? "__root__") && foldDrag !== gid
                  ? "before"
                  : undefined
          }
          /**
           * ⭐⭐ WAVE 41 Β· T33 (instruction 12) β€” A NESTED FOLDER IS THIS ROW, INDENTED.
           *
           * DESIGN.md Β§4: new nav joins the existing rhythm and never introduces a control
           * shape. 12px is not a new number either β€” it is the step `.cg-fold .cg-view-row`
           * already uses to set a view in from its folder head, so a folder inside a folder
           * lands exactly where a view inside a folder lands, one level on.
           *
           * ⚠ INLINE BECAUSE THE DEPTH IS DATA, not because the rail is short of a class. A
           * stylesheet would need one rule per level to a cap the model owns, and the two
           * numbers would then have to be kept equal by hand.
           */
          className={
            /* ⭐ W40-T28 β€” `gid === null`, not `isRoot`: the pin group wears the SAME class as
               the ungrouped section (no head, the rail's measured root indent) because it is the
               same shape of thing rendered in a different place. DESIGN.md Β§4 β€” this is an
               existing element joining the existing rhythm, not a new control shape. */
            (asLeaves ? "cg-fold-root" : "cg-fold") +
            // ⭐⭐ W47-T12 β€” THE SECOND READER OF THIS FILL, and it is the same sentence.
            // `.is-drop` has meant "drop this INTO me" since wave 8 (index.css says so in as many
            // words); a folder about to be nested is that sentence with a folder in it, so the
            // rail gains a meaning without gaining a vocabulary. `foldNest.ok` gates it: a target
            // `mayNestFolder` will refuse never lights up, it only records `data-fold-drop`.
            (!isPinnedGroup
             && (dropTarget === (gid ?? "__root__")
                 || (!!foldNest && foldNest.ok && foldNest.id === gid))
              ? " is-drop"
              : "") +
            // Item 19 β€” the insertion rule reads "the folder you are dragging lands HERE":
            // above this folder, or above the ungrouped section, which is after them all.
            (!isPinnedGroup && foldOver === (gid ?? "__root__") && foldDrag && foldDrag !== gid
              ? " is-drop-above"
              : "") +
            // β›” `foldDrag !== null` FIRST. `gid` is null for the UNGROUPED section and
            // `foldDrag` idles at null, so a bare `foldDrag === gid` is `null === null` β€” TRUE
            // from first paint, with no drag anywhere. The ungrouped section (which is where
            // most people's views live) rendered at `opacity: .45` permanently, and the symptom
            // is not "a folder looks dragged" but "my view NAMES are faded, as if hidden" β€”
            // which is why it read as a colour bug rather than a drag-state bug.
            //
            // The `is-drop-above` line above got this right (`&& foldDrag &&`), which is the
            // tell: two conditions written minutes apart, one guarded and one not.
            (!isPinnedGroup && foldDrag !== null && foldDrag === gid ? " is-folddrag" : "") +
            // ⭐⭐ WAVE 34 Β· T22 (ruling R4) β€” THE ROOT SECTION IS A DROP TARGET WITH NO PIXELS.
            //
            // β›” THIS IS THE HALF `D-249` DOES NOT NAME, and on its own it reproduces the owner's
            // whole report. `groupByFolder` ALWAYS pushes the root group, so a user who has filed
            // every view into folders gets `<div class="cg-fold-root">` with no head, no rows and
            // no min-height: a ZERO-PIXEL drop zone. The drag starts fine (that is B1's fix) and
            // there is physically nowhere to release it. Even a POPULATED root is barely better β€”
            // this element has no padding, so its box is exactly the union of its rows, and each
            // row's own `onDragOver` calls `stopPropagation` to claim the reorder gesture. The
            // only surface that ever meant "file at the top level" was the sliver between rows.
            //
            // So while a VIEW drag is in flight the root section is given real height and a real
            // strip below its last row (index.css `.cg-fold-root.is-viewdrop`). The hover paint is
            // the existing `.is-drop` rule: this ticket supplies the AREA, not a second vocabulary.
            //
            // ⚠ `viewDrag !== null` explicitly, never a bare truthiness test on a value that idles
            // at `null` beside a `gid` that is `null` for this very section β€” that is the
            // `foldDrag === gid` trap two lines up, which faded the whole ungrouped section
            // permanently once already. `isRoot` is a separate boolean, so the two cannot collide.
            (isRoot && viewDrag !== null ? " is-viewdrop" : "") +
            (isLevelFolder && viewDrag !== null ? " is-viewdrop" : "")
          }
          {/* No drop handlers on the synthetic group β€” see `isSynthetic`. Spreading `{}`
              rather than branching the element keeps ONE render path for every group.
              ⭐ W40-T28 β€” nor on the pin group, for a different reason: it is a READING of the
              view list ("these have no placement"), so a drop on it would emit
              `item_move(id, ROOT_FOLDER_ID)` β€” a stored placement, which is the very thing that
              takes a view OUT of this group. The drop would file the view and then move it
              somewhere else on screen. The ungrouped section below is the one root target. */
          ...(isSynthetic || isManaged || isPinnedGroup ? {} : dropHandlers(gid))}
        >
          {group.folder && !asLeaves && (
            <div
              className="cg-fold-head"
              // ── Item 19 β€” the folder itself is the drag handle ─────────────────────
              // Draggable only while it is renameable-idle: a `draggable` ancestor eats
              // the text selection inside an input, so dragging would win over editing
              // the name you just opened.
              draggable={
                foldsReorderable && !isSynthetic && !isManaged &&
                renamingFolder !== group.folder.id
              }
              onDragStart={(e) => {
                e.dataTransfer.setData(FOLD_DRAG_TYPE, group.folder!.id);
                e.dataTransfer.effectAllowed = "move";
                setFoldDrag(group.folder!.id);
              }}
              onDragEnd={() => {
                setFoldDrag(null);
                setFoldOver(null);
                // ⭐ W47-T12 β€” the fork's own state joins the two it was modelled on. A drag
                // abandoned over a folder head would otherwise leave the "will nest" fill lit
                // with nothing being dragged.
                setFoldNest(null);
              }}
              /* ⭐⭐ W47-T12 β€” THE TWO-BAND FORK, on the head and only on the head. Spread LAST so
                 it is unmistakable that these add `onDragOver` / `onDragLeave` / `onDrop` and
                 replace none of the three handlers above: this element had no drop handlers at
                 all before this ticket, which is why the group underneath could claim every
                 folder drop as "land above me".
                 β›” AND NOT ON A SYNTHESISED OR MANAGED HEAD, matching the group's own spread two
                 dozen lines up. "Shared with me" and a colleague's shared folder are a READING of
                 the view list with no record behind them, so a nest would emit `item_move` naming
                 a parent that exists in nobody's store and a reorder would send an order carrying
                 an id `reorderFolderIds` was never given. `mayNestFolder` refuses the first in
                 words; the second has no such wall, so the gesture simply is not offered here. */
              {...(isSynthetic || isManaged ? {} : foldHeadDropHandlers(group.folder.id))}
            >
              {/* β›” NO DRAG GRIP, and that is a decision rather than an omission. A grip in
                  flow shifts the folder's name to the right, and this rail's indent is
                  MEASURED to the pixel (index.css: "root view name 41.00px / folder header
                  48.36px" β€” the whole point of the wave-10 item-2 fix); the gutter it would
                  otherwise hide in is already occupied by the disclosure chevron, whose
                  open/shut state is the only one this row has. The view rows above have been
                  draggable with no handle since wave 8, so a folder that drags the same way
                  is the vocabulary this list already teaches, not a hidden feature. */}
              <button
                type="button"
                className="cg-fold-toggle"
                /**
                 * ⚠ W41-T34 β€” THE CLICK IS READ OFF `shut`, THE STATE THE CHEVRON IS DRAWING,
                 * not off membership of `opened`.
                 *
                 * With no search live the two are the same sentence and this behaves exactly as
                 * the old symmetric toggle did. They come apart during a SEARCH, which shows
                 * every folder open whatever `opened` holds: keyed on membership, clicking the
                 * chevron of a folder the user had never opened would ADD it β€” the row would not
                 * move, because the search is still forcing it open, and the folder would then be
                 * open once the search cleared. The user pressed "close" and got "open", one
                 * gesture later. Reading the drawn state makes the click mean what it looks like.
                 */
                aria-label={`Open folder ${group.folder.name}`}
                onClick={() => setAt(group.folder!.id)}
              >
                {/* size 16 β€” one mark box across the whole rail (view rows, flyout rows and
                    now folder headers), which is what lets item 2's text alignment be exact
                    rather than approximately right. */}
                <FolderMark size={16} />
                {renamingFolder === group.folder.id ? (
                  <input
                    className="cg-input cg-fold-rename"
                    autoFocus
                    defaultValue={group.folder.name}
                    onClick={(e) => e.stopPropagation()}
                    onBlur={(e) => {
                      const v = e.target.value.trim();
                      if (v && v !== group.folder!.name) onFolderRename?.(group.folder!.id, v);
                      setRenamingFolder(null);
                    }}
                    onKeyDown={(e) => {
                      if (e.key === "Enter") e.currentTarget.blur();
                      if (e.key === "Escape") setRenamingFolder(null);
                    }}
                  />
                ) : (
                  <span
                    className="cg-fold-name"
                    /* ⭐ W34-T25 (R11) β€” WHOSE folder this is, on the folder itself.
                       A synthesised shared-folder group looks exactly like one of the reader's
                       own folders otherwise, and two people can share folders with the SAME
                       NAME. The owner rides on every projected view (`_granted_views` stamps
                       `owner`), so the group can answer it without a second wire field. Left as
                       a `title` rather than painted into the name: the rail's indent is measured
                       to the pixel and a second line here would push every view row. */
                    title={
                      isSynthetic && group.items[0]?.owner
                        ? `Shared with you by ${group.items[0].owner}`
                        : undefined
                    }
                  >
                    {group.folder.name}
                  </span>
                )}
                {/* β›” WAVE 20 item 21 β€” THE VIEW COUNT IS DELETED, and the item is not
                    really about the number. `.cg-view-more` (the "…" beside this button)
                    ships `opacity: 0` and is revealed by `.cg-view-row:hover`; a folder
                    head is not a view row, so NO rule ever revealed it β€” the folder's
                    actions button was painted at zero opacity in every state but keyboard
                    focus. The badge is what the owner saw sitting where the control should
                    have been. Deleting it and making the "…" unconditionally visible (one
                    rule in this wave's S4 region) are the two halves of one fix.
                    ⚠ `.cg-fold-count` in index.css now has no consumer in this tree. Left
                    in place rather than swept blind β€” same posture as `.cg-fold-new` above
                    β€” and booked in the S4 mailbox so the sweep is a decision, not a
                    discovery. The NAV rail's own count stays: that rail reveals its "…" on
                    hover already, so it never had this defect and item 21 never named it. */}
              </button>
              {/* β›” THE SYSTEM FOLDER HAS NO ACTIONS (item 18 / C-SHARE). "Shared with
                  me" is not the reader's folder: it cannot be renamed into something
                  else, duplicated into a second copy of other people's work, or
                  deleted β€” the contract calls it undeletable, and a menu whose every
                  row the server would refuse is three fake affordances rather than
                  one. Views MOVE OUT of it normally (that is per-receiver placement),
                  which is the only thing anyone needs to do to it. */}
              {/* ⭐ W34-T25 (R11) β€” widened from `=== SHARED_FOLDER_ID` to EVERY synthesised
                  group, for the reason the block above gives: a colleague's shared folder is no
                  more the reader's to rename, duplicate or delete than "Shared with me" is, and
                  every row of that menu would be refused by a server that has no such folder. */}
              {folderReadOnly || isSynthetic || isManaged ? null : (
              <button
                type="button"
                className="cg-view-more"
                aria-label={`Actions for folder ${group.folder.name}`}
                aria-haspopup="menu"
                onClick={(e) => {
                  // β›” HOISTED OUT OF THE UPDATER β€” see the view menu's twin below. React
                  // nulls `currentTarget` when the handler returns, and a functional
                  // updater can be re-invoked AFTER that.
                  const anchor = e.currentTarget;
                  setFolderMenu((cur) =>
                    cur?.id === group.folder!.id ? null : { id: group.folder!.id, anchor }
                  );
                }}
              >
                Β·Β·Β·
              </button>
              )}
            </div>
          )}
          {asLeaves &&
        group.items.map((view) => {
          const active = view.id === activeViewId;
          const renaming = renamingId === view.id;
          const mode = viewDisplayMode(view);
          // W40-T21 β€” resolved ONCE, here rather than inside the row's JSX. The badge slice below
          // is a bounded scan subject in `verify_grid_ux.py`, and a rule inlined there would grow
          // it for no benefit; the decision itself lives in `viewShareMark`.
          const shareMark = viewShareMark(view);
          // S85-T33 (D-233): the server emptied this view's filter for this reader.
          const scopedOut = viewScopedOutMark(view);
          return (
            <div
              // Item 12 (C-LOCK) β€” `cg-view-lockset` marks a view locked to a cohort. The
              // rail is where someone chooses which table to open, and a locked view shows a
              // different row set than its siblings for a reason no filter states; the mark
              // is what makes that visible before the click rather than after it.
              className={
                "cg-view-row" +
                (active ? " is-active" : "") +
                // W46-T02 - in the shift-selected range. Distinct from `is-active`, which says
                // "this is the table you are looking at" and can be true at the same time.
                (isRailSelected(view.id) ? " is-railsel" : "") +
                (viewDrag && isRailSelected(viewDrag) && railSelected.length > 1
                  && isRailSelected(view.id) ? " is-rail-multidrag" : "") +
                (view.config?.cohortLock ? " cg-view-lockset" : "") +
                (view.assigned ? " cg-view-lockset" : "") +
                // ⭐ ITEM 5 (C7) β€” the same two marks the folder drag uses: the row being
                // carried fades, and the row it would land ABOVE draws an insertion rule.
                (viewDrag === view.id ? " is-viewdrag" : "") +
                (viewOver === view.id && viewDrag && viewDrag !== view.id
                  ? " is-drop-above"
                  : "")
              }
              key={view.id}
              // S85-T33 (D-249, R30): `types.ts::mayFileView`, NOT `mayEditView`, and this is
              // its only call site. A read-only share must be able to begin a drag, because
              // filing writes only this viewer's placement.
              draggable={(foldersOn || viewsReorderable) && !renaming
                         && mayFileView(view, viewer)}
              onDragStart={(e) => {
                // β›” TWO TYPES ON ONE DRAG, and that is the discrimination C7 asks for.
                // `text/plain` is the FILE-INTO-A-FOLDER channel the folder groups already
                // listen on and must keep working; `VIEW_DRAG_TYPE` is what a view ROW listens
                // for. Sharing one channel would make a reorder look like a file-into to
                // whichever handler fired first β€” the same collision `FOLD_DRAG_TYPE` exists to
                // prevent one level up.
                e.dataTransfer.setData("text/plain", view.id);
                e.dataTransfer.setData(VIEW_DRAG_TYPE, view.id);
                if (isRailSelected(view.id) && railSelected.length > 1) {
                  e.dataTransfer.setData(VIEW_SET_DRAG_TYPE, JSON.stringify(railSelected));
                }
                e.dataTransfer.effectAllowed = "move";
                setViewDrag(view.id);
              }}
              // ⚠ A DRAG THAT ENDS ANYWHERE clears the marks. Without this, releasing over a
              // non-drop target leaves the row faded and an insertion rule painted, and the
              // rail looks stuck mid-gesture until the next render happens to clear it.
              onDragEnd={() => {
                setViewDrag(null);
                setViewOver(null);
              }}
              {...viewDropHandlers(view.id)}
            >
              {renaming ? (
                <input
                  className="cg-view-rename cg-input"
                  autoFocus
                  /* ⭐⭐ W40-T28 β€” THE BOX OPENS ON WHAT THE ROW SAYS, AND THE NO-OP TEST READS
                     THE SAME STRING. Seeding this from `view.name` while the row reads "Default
                     view" would show the user a name they have never seen; worse, the guard
                     below would then compare their untouched "Default view" against the stored
                     "All customers", call it a change, and PERSIST it β€” after which the name is
                     no longer the host's mint and `viewDisplayName` stops resolving it. Opening
                     rename and pressing Enter would permanently defeat the display rule. */
                  defaultValue={viewDisplayName(view)}
                  onBlur={(event) => {
                    const next = event.target.value.trim();
                    if (next && next !== viewDisplayName(view)) onRename(view.id, next);
                    setRenamingId(null);
                  }}
                  onKeyDown={(event) => {
                    if (event.key === "Enter") event.currentTarget.blur();
                    if (event.key === "Escape") setRenamingId(null);
                  }}
                />
              ) : (
                <button
                  type="button"
                  className="cg-view-main"
                  // Selection gestures stay in the rail; only a plain click opens the view.
                  onClick={(event) => {
                    selectRailRow(view.id, {
                      shiftKey: event.shiftKey, ctrlKey: event.ctrlKey, metaKey: event.metaKey,
                    });
                    setRailDeleteArmed(false);
                    setRailLeftInPlace([]);
                    if (!event.shiftKey && !event.ctrlKey && !event.metaKey) onSelect(view.id);
                  }}
                  // Item 9 kept this tooltip rather than dropping it as redundant: BOTH lines
                  // ellipsis at 188px, so the hover is now the only way to read either one in
                  // full. It used to show the note INSTEAD of the name, which meant a
                  // described view could not have its own truncated name revealed at all.
                  title={view.note ? `${viewDisplayName(view)}: ${view.note}` : viewDisplayName(view)}
                >
                  {/* I12 β€” the row wears the view's CURRENT display mode, not a kind dot.
                      Same geometry the mode switcher and the create flyout use, so "what
                      Calendar looks like" is one drawing everywhere on this surface.

                      Wave-10 item 3 β€” and now the same PAINT, not just the same geometry.
                      The flyout has always drawn these marks in pastel (`ToneModeIcon`);
                      the list drew the bare `ModeIcon` and index.css forced `--lp-muted`
                      over it, so a view created as a blue Grid or a yellow Calendar landed
                      in the rail GREY. There is no per-view "creation colour" to restore β€”
                      `MODE_TONE` is a static mode→tone map, never a persisted field
                      (amendment A-1) β€” so painting the current mode's tone here reproduces
                      what the flyout showed, by construction. */}
                  <ToneModeIcon mode={mode} tone={MODE_TONE[mode]} size={16} />
                  {/* Wave-10 item 9 β€” name, then the description as a quiet second line.
                      Wrapped in one column so the icon and the lock stay on the ROW axis
                      while the text stacks; without the wrapper the note would become a
                      third flex sibling and sit beside the name. Both lines ellipsis rather
                      than wrap: a rail this narrow turns a wrapped sentence into a
                      four-line row and the list stops being scannable. */}
                  <span className="cg-view-text">
                    <span className="cg-view-name">{viewDisplayName(view)}</span>
                    {view.assigned ? <span className="cg-view-desc">Assigned filter locked</span> : null}
                    {view.note && (
                      <span className="cg-view-desc">{view.note}</span>
                    )}
                  </span>
                  {/* ⭐ WAVE 27 Β· OWNER ITEM 21 / RULING R14 β€” ALERT ON = BADGE ON.
                      The LIVE number of records matching this view's filter, in the red
                      accent, shown for exactly the views that carry an alert. Deleting the
                      alert removes it, because the badge is not stored anywhere β€” it is a
                      rendering of `alertCounts`, which is keyed by the alerts the server
                      lists.
                      β›” OUTSIDE `.cg-view-text`, deliberately. That element is the ellipsising
                      COLUMN holding the name over its description; a badge inside it becomes
                      part of the run that gets cut off, so the one number the user asked to
                      always see is the first thing to disappear on a long name. On the row
                      axis it takes its width first and the NAME ellipsises around it β€” which
                      is the correct priority and what the 188px budget is for. */}
                  {alertCounts[view.id] !== undefined && (
                    <span
                      className="cg-view-count"
                      // ⭐ WAVE 32 Β· T24 (R5) β€” ONE badge, TWO reasons it can be here, and the
                      // hover has to say WHICH. A view marked important shows the identical red
                      // pill as an alerted one (deliberately β€” R5 asks for the same number in the
                      // same place), so a single sentence about alerting would tell a reader who
                      // marked a view that they had created an alert they did not create. The
                      // number is the same fact; the promise attached to it is not.
                      // ⭐ W35-T26 (R4): the word on screen is STAR. The stored key is still
                      // `config.important` β€” R4 makes them ONE flag, so renaming the key would
                      // create the second store the ruling forbids.
                      title={
                        view.config?.important
                          ? `${alertCounts[view.id].toLocaleString()} records match this view. `
                            + `You starred it.`
                          : `${alertCounts[view.id].toLocaleString()} records match this `
                            + `view. You are alerted when a new one arrives.`
                      }
                    >
                      {alertCounts[view.id].toLocaleString()}
                    </span>
                  )}
                  {/* ⭐⭐ WAVE 33 Β· T14 (D-205) β€” THE ROW SAYS WHY THERE IS NO NUMBER.
                      β›” The badge above is switched off on a server-windowed grid and on a view
                      whose measure the server has not answered β€” both correct (the browser holds
                      ONE window; a count from it would be a page's size wearing a scope's name),
                      and both previously SILENT. An absent badge and "nothing matches" read the
                      same, on exactly the big Odoo grids the owner has been chasing.
                      ⭐ R6's second sentence is the rule: a limit that cannot be removed must be
                      REPORTED with its cause. So the mark stays visible and carries the sentence
                      instead of a number β€” never an invented count.
                      ⚠ Mutually exclusive with the badge by construction (`alertCounts` is
                      checked first), so a row can never wear both a count and an excuse. */}
                  {alertCounts[view.id] === undefined && countNotes?.[view.id] && (
                    <span
                      className="cg-view-count is-unknown"
                      title={countNotes[view.id]}
                      aria-label={countNotes[view.id]}
                    >
                      {/* ⚠ W34-T26 (R6): an ASCII hyphen, not the EN DASH this shipped with.
                          The en dash is exactly the character the standing rule bans from copy
                          that reaches a screen, and `web_prose` CANNOT SEE IT: its JSX pass
                          requires the text run to contain no newline, and this span has enough
                          attributes that Prettier puts the closing `>` on its own line. Reported
                          to A in mailbox C-3 as a structural hole rather than worked around
                          silently. ⭐ It is also what makes T20's header badge and this one ONE
                          mark rather than two that merely claim to match. */}
                      -
                    </span>
                  )}
                  {/* ⭐ wave17 R1 / C-LOCKV β€” ONE mark, TWO meanings, and they are genuinely
                      different things that both read as "locked":

                        Β· `kind === "locked"` β€” the view's ROWS are a hand-curated set. This is
                          what the retired Cohorts section used to say, and it is the more
                          consequential of the two: it explains why this view shows fewer
                          records than its siblings, which no filter chip accounts for.
                        Β· `isModeFrozen` β€” the view's DISPLAY MODE is frozen (the legacy
                          `locked` flag). It says nothing about which rows are here.

                      A locked view does NOT get the legacy flag set (the host's projection says
                      so explicitly), so most rows have exactly one reason. When a row has both,
                      the row-set meaning leads and the title carries the other β€” never two
                      padlocks side by side, which would read as a bug. */}
                  {/* ⭐ WAVE 20 item 23 (C-SHARE) β€” THE SECOND MARK, beside the padlock
                      and never instead of it. They answer different questions: the lock
                      says what this view may become, this says how it got to you. A
                      view someone shared with you is one you can be looking at without
                      having made it β€” the single most useful thing the rail can tell you
                      before the click.
                      ⚠ WAVE 21 (item 9, R12/C1): the narrowed cast this used to need is
                      gone β€” `shared`, `sharedRole` and `owner` are declared on `SavedView`
                      and the server now projects them. The mark also says WHICH GRANT: a
                      read-only share and an editable one look identical in the rail
                      otherwise, and the reader's first question on finding a menu with no
                      Rename in it is why.
                      ⭐⭐ W40-T21 (owner instruction 2 / C1) β€” AND IT IS THE SAME MARK IN BOTH
                      ACCOUNTS NOW. Owner: *"A shared View must show the shared/collaborative icon
                      in EVERY account, not only the recipient's."* One glyph, two sentences: the
                      recipient's still names who shared it, the owner's reads as sharing OUT.
                      Which one, and whether there is a mark at all, is `viewShareMark` β€” a pure
                      exported function, so the rule can be executed rather than read off JSX.
                      The geometry is `SHARE_SHAPE`, the ONE share drawing the grid header's
                      canvas sprite paints too; this row used to hold a second copy of it. */}
                  {shareMark ? (
                    <span
                      className="cg-view-shared"
                      role="img"
                      aria-label={shareMark.ariaLabel}
                      title={shareMark.title}
                    >
                      <ShareMark />
                    </span>
                  ) : null}
                  {(view.kind === "locked" || isModeFrozen(view)) && (
                    <span
                      className="cg-view-lock"
                      // Not aria-hidden: "this view is frozen" is information, and the row's
                      // accessible name is the only place a non-sighted user can receive it.
                      role="img"
                      aria-label={
                        view.kind === "locked"
                          ? `${viewDisplayName(view)}, a locked view`
                          : `${MODE_LABELS[mode]} view, locked`
                      }
                      title={
                        view.kind === "locked"
                          ? "Locked: this view shows only the records locked into it. " +
                            "Filters, sorts and columns still narrow within them." +
                            (isModeFrozen(view)
                              ? ` It also stays a ${MODE_LABELS[mode].toLowerCase()}.`
                              : "")
                          : `Locked: this view stays a ${MODE_LABELS[
                              mode
                            ].toLowerCase()}. Filters, sorts and columns are still editable.`
                      }
                    >
                      <LockMark />
                    </span>
                  )}
                  {/* S85-T33 (D-233): the scoped-out cohort mark, last in the row. Inline style
                      because index.css is outside this ticket; it copies `.cg-view-lock`, and a
                      preceding mark already took the auto margin. */}
                  {scopedOut ? (
                    <span
                      className="cg-view-scopedout"
                      role="img"
                      aria-label={scopedOut.ariaLabel}
                      title={scopedOut.title}
                      style={{
                        flex: "0 0 auto",
                        display: "inline-flex",
                        alignItems: "center",
                        marginLeft:
                          shareMark || view.kind === "locked" || isModeFrozen(view) ? 0 : "auto",
                        paddingLeft: 4,
                        color: "var(--lp-muted)",
                      }}
                    >
                      <ScopedOutMark />
                    </span>
                  ) : null}
                </button>
              )}
              {!readOnly && <button
                type="button"
                className="cg-view-more"
                aria-label={`Actions for ${viewDisplayName(view)}`}
                aria-haspopup="menu"
                aria-expanded={menu?.viewId === view.id}
                onClick={(event) => {
                  /**
                   * β›” THE ANCHOR IS READ HERE, NOT INSIDE THE UPDATER β€” and that one line
                   * is the difference between this rail working and the whole app going
                   * white. Found by _qa_live_rail.py on 2026-08-04, reproduced on the
                   * shipped build.
                   *
                   * React sets `event.currentTarget = null` the moment this handler
                   * returns (`executeDispatch`'s finally). A FUNCTIONAL updater is not
                   * guaranteed to run inside the handler: the eager-state path evaluates
                   * it once, synchronously, while `currentTarget` is still the button β€”
                   * but React re-invokes it when it processes the queue for real, and by
                   * then it is null. The menu therefore opened correctly and only died
                   * later, on a re-render triggered by something else entirely β€” which is
                   * why a white screen appeared one interaction AFTER the click that
                   * caused it. `AnchoredOverlay` then did `"getBoundingClientRect" in
                   * null` and took the tree down with it.
                   */
                  const anchor = event.currentTarget;
                  /**
                   * ⭐⭐ WAVE 41 Β· T38 (owner instruction 17) β€” ASK FOR A FRESHER ANSWER BEFORE
                   * WITHHOLDING THE MENU'S EDIT ROWS.
                   *
                   * β›” THIS IS WHERE THE OWNER MEETS THE DEFECT. Rename, Description and Delete
                   * are all gated on `canEditMenuView`, so a stale permission copy does not
                   * refuse a rename, it removes the entry that starts one β€” *"will not let a
                   * view be renamed until a refresh"*, exactly. `viewer` and every view's
                   * `sharedRole` ride the payload, which is re-read only on a stale signal, and
                   * nothing raises one on a timer.
                   *
                   * ⚠ ONLY ON THE NEGATIVE, which keeps this cheap and keeps it honest: a view
                   * this reader can already edit needs no second opinion, so the extra
                   * `/workspace` read happens on the minority of rows and only where the menu is
                   * about to show less than it might. The menu stays open while the read lands,
                   * so the rows appear under the user's cursor without a reload.
                   */
                  if (!mayEditView(view, viewer)) signal(WORKSPACE_STALE_EVENT);
                  setMenu((current) =>
                    current?.viewId === view.id ? null : { viewId: view.id, anchor }
                  );
                }}
              >
                Β·Β·Β·
              </button>}
              {/* Wave-10 item 9 inverted this: the description now renders HERE, on the
                  row, and the across-the-table banner in CustomerGrid is gone. Still one
                  place, not two β€” and now it is the place that names the view, and EVERY
                  view shows its own, not just the active one. */}
            </div>
          );
        })}
        {group.folder && asLeaves && group.items.length === 0
          && levelGroups.heads.length === 0 && (
          <div className="cg-fold-empty">Empty. Drag a view here.</div>
        )}
        </div>
        );
        })}

      {/* ⭐ wave17 R1 / C-LOCKV β€” THE "COHORTS" SECTION IS GONE, and nothing replaced it here.
          Wave 15 projected each cohort as a transient row under its own heading, which made a
          locked view a second-class object: it could not be renamed, filed into a folder,
          reordered, sorted or shared, because it was not a view. R1: it IS a view. The host
          projects each one into the SAME list above (`locked_view_projection` β€” id preserved,
          `config.cohortLock` naming its own id), so every one of those capabilities arrives for
          free and this section has nothing left to render.
          The lock MARK moved onto the ordinary view row, where `kind === "locked"` drives it. */}
      </div>
      </>
      )}
      </DataDatabaseNavigator>

      {/* W46-T02 - The selection bar names the rendered selection and its bulk actions.
          β›” DELETE ASKS ONCE, AND THE ASK IS NOT DECORATION: there is no store history behind a
          deleted view, so the confirm is the only thing standing between a mis-shift and work
          that cannot be brought back. `onDelete` is called from the armed branch alone. */}
      {!readOnly && (railSelected.length > 0 || railLeftInPlace.length > 0) && (
        <div className="cg-railsel" role="group" aria-label="Selected views">
          {railSelected.length === 0 ? (
            <button type="button" onClick={clearRailSel}>Dismiss</button>
          ) : railDeleteArmed ? (
            <>
              <span className="cg-railsel-ask">
                {railDeletable.length === 1
                  ? "Delete 1 view? This cannot be undone."
                  : `Delete ${railDeletable.length} views? This cannot be undone.`}
                {railSelected.length > railDeletable.length
                  && ` ${railSelected.length - railDeletable.length} of them cannot be deleted `
                     + `and will stay.`}
              </span>
              <button
                type="button"
                className="is-danger"
                onClick={() => {
                  for (const view of railDeletable) onDelete(view.id);
                  clearRailSel();
                }}
              >
                Delete
              </button>
              <button type="button" onClick={() => setRailDeleteArmed(false)}>
                Keep them
              </button>
            </>
          ) : (
            <>
              <span className="cg-railsel-count">
                {railSelected.length === 1
                  ? "1 view selected"
                  : `${railSelected.length} views selected`}
              </span>
              {onExportXlsxViews && (
                <button
                  type="button"
                  disabled={railExportIds.length === 0}
                  onClick={(event) => {
                    // β›” HOISTED BEFORE THE setState, the scar the folder menu records above:
                    // React nulls `currentTarget` once the handler returns.
                    const anchor = event.currentTarget;
                    // ONE export panel, not two: this opens the existing bulk pane with the
                    // selection already ticked, so the formats, the 20-view cap and the tab
                    // rule all stay where they were written.
                    setExportViewIds([...railExportIds]);
                    setExportBulk(true);
                    setExportFor({ viewId: railExportIds[0], anchor });
                  }}
                >
                  Export
                </button>
              )}
              {foldersOn && (
                <button
                  type="button"
                  className="cg-railsel-move"
                  onClick={(event) => {
                    const anchor = event.currentTarget;
                    setMoveFor({ viewId: railSelected[0], anchor, bulk: true });
                  }}
                >
                  Move to folder
                </button>
              )}
              <button
                type="button"
                className="is-danger"
                disabled={railDeletable.length === 0}
                onClick={() => setRailDeleteArmed(true)}
              >
                Delete
              </button>
            </>
          )}
          {railMoveNotice && (
            <span className="cg-railsel-left" role="status" title={railMoveNotice}>
              {railMoveNotice}
            </span>
          )}
        </div>
      )}

      {/* I11c β€” the folder "…" menu. Rename Β· Add to cohort Β· Duplicate Β· Delete.
          WAVE 20 item 22 β€” every row now carries the SAME icon vocabulary the view row's
          menu uses (`MenuLabel` over `MENU_ICONS`), and Delete is red AT REST rather than
          only once armed. Two menus that do the same kind of thing to two kinds of object
          were drawn in two registers: one with icons and a red delete, one with neither.
          ⚠ NO NEW CSS FOR THE COLOUR: this overlay already wears `cg-view-menu`, so adding
          `is-danger` to the button reuses `.cg-view-menu button.is-danger` β€” the exact rule
          that paints the view row's Delete, which is what "matching" has to mean. The
          `cg-menu-item--danger` class stays for its armed background. */}
      {folderMenu && folderMenuF && (
        <AnchoredOverlay
          anchor={folderMenu.anchor}
          className="cg-view-menu"
          placement="bottom-end"
          role="menu"
          ariaLabel={`Actions for folder ${folderMenuF.name}`}
          onDismiss={() => {
            setFolderMenu(null);
            setConfirmDelete(null);
          }}
          dataKind="folder-menu"
        >
          {/* ⭐⭐ WAVE 41 Β· T33 (owner instruction 12, ruling R1) β€” A FOLDER INSIDE THIS FOLDER.
              β›” AND THE PLACE THE 11TH LEVEL IS REFUSED. DESIGN.md Β§4 asks for one short line
              stating the cap, put where the decision is made rather than on a landing pane β€” so
              the row states it IN ITS OWN LABEL and goes inert, which is the idiom the Delete row
              three items down already uses to say a whole sentence at the moment of the click.
              An enabled row that opened a form only to reject the name at the end would spend
              the user's typing to tell them something knowable before they started. */}
          {/* ⚠ `foldersOn` as well as the callback, matching the create PANE's own gate three
              hundred lines up. Without it a rail with the folder machinery switched off would
              offer a row whose pane never renders, and `nesting` (built from an empty list in
              that case) would answer every verdict with "that folder is no longer here". */}
          {/* ⭐⭐ W50-T11 (owner instruction 21, ruling R12) β€” NEW VIEW IN FOLDER.
              Owner, R12: *"The new-view door that leaves the view closed: the folder's `...`
              menu, New view in folder."* Before this row the folder menu could make a FOLDER
              inside a folder and nothing else, so the only way to put a view in a folder was to
              create it at the top level and then drag it β€” the gesture R13 reports as broken.
              β›” IT REUSES THE ONE CREATE FLYOUT rather than growing a second form. DESIGN Β§4,
              and the same sentence T33 wrote for "New folder inside": a view is made by the
              control that already makes views, pointed at a destination. So this row opens the
              SAME two-step panel the rail's own door opens β€” anchored on the folder's own "…"
              button, so the pane sits beside the folder it will file into β€” and hands the mode
              rows the destination through `createInto`.
              ⚠ NO `foldersOn` GATE OF ITS OWN and none is missing: this whole menu only renders
              for a stored folder, which cannot exist with the folder machinery off. */}
          <button
            type="button"
            role="menuitem"
            className="cg-menu-item"
            onClick={() => {
              // Step one, every time: a `creating` left set by an abandoned flyout would
              // re-enter at the name form for a kind nobody just picked.
              setCreating(null);
              setCreatingFolder(false);
              setCreateInto(folderMenuF.id);
              setCreateMenu(folderMenu.anchor);
              setFolderMenu(null);
            }}
          >
            <MenuLabel icon="addEnd" text="New view in folder" />
          </button>
          {foldersOn && onFolderCreate && nestHere && (
            <button
              type="button"
              role="menuitem"
              className="cg-menu-item"
              disabled={!nestHere.ok}
              title={nestHere.reason}
              onClick={() => {
                startFolder(folderMenuF.id);
                setFolderMenu(null);
              }}
            >
              <MenuLabel icon="addEnd" text={nestHere.ok ? "New folder inside" : nestHere.reason!} />
            </button>
          )}
          <button
            type="button"
            role="menuitem"
            className="cg-menu-item"
            onClick={() => {
              setRenamingFolder(folderMenuF.id);
              setFolderMenu(null);
            }}
          >
            <MenuLabel icon="rename" text="Rename" />
          </button>
          {/* ⭐⭐ WAVE 41 Β· T35 (owner instruction 11) β€” CHANGE ICON, BETWEEN RENAME AND DUPLICATE.
              The ticket asks for it there and "Add to cohort" already sat inside that span (C4 as
              amended 2026-07-28), so it goes DIRECTLY BELOW RENAME rather than displacing a
              shipped row: renaming a folder and remarking it are the same kind of edit to the
              same object, and the pair now reads as one block above the actions that COPY, SHARE
              or DELETE it. The ticket's ordering holds either way; this reading also groups.
              ⚠ THE ROW WEARS THE FOLDER'S OWN CURRENT MARK, passed as a NODE the way "Share
              folder" passes `ShareMark`. `MENU_ICONS` has no glyph for this and `icons.tsx` is
              not this ticket's to extend β€” but more to the point, the honest picture of "change
              this icon" IS this icon, and it makes the row say which mark is about to change. */}
          {folderAddPreview && onFolderAddToList && (
            <button
              type="button"
              role="menuitem"
              className="cg-menu-item"
              onClick={() => {
                setAddTarget(folderMenuF.id);
                setAddAnchor(folderMenu.anchor);
                setAddName(today ? `${folderMenuF.name} Β· ${today}` : folderMenuF.name);
                setFolderMenu(null);
              }}
            >
              <MenuLabel icon="cohortAdd" text="Add to cohort" />
            </button>
          )}
          {onFolderDuplicate && (
            <button
              type="button"
              role="menuitem"
              className="cg-menu-item"
              onClick={() => {
                onFolderDuplicate(folderMenuF.id);
                setFolderMenu(null);
              }}
            >
              <MenuLabel icon="duplicate" text="Duplicate folder and its views" />
            </button>
          )}
          {/* WAVE 20 item 18 (R10) β€” a folder shares, and its views ride along
              (the server's rule, stated in C-SHARE; this row only opens the editor).
              ⭐ W40-T21 (D-254) β€” THE PADLOCK IS GONE FROM THIS ROW. Sharing is not one of
              DESIGN.md Β§4's three locks, and Β§4 is explicit that "a surface painting one lock
              where another applies tells the user something false" β€” so the mark was false, not
              merely ambiguous. A `title` reading "this is access, not a lock" would have existed
              only to correct its own icon, which Β§4's "never over-explain" forbids: fix the mark
              and the sentence is unnecessary. Now it wears `SHARE_SHAPE`, the same drawing as the
              rail's share mark and the grid header's `aiosShared` sprite. Passed as a NODE, the
              way the Star and alert rows pass theirs, so a glyph no other menu row needs costs
              the shared `MENU_ICONS` vocabulary nothing. */}
          <button
            type="button"
            role="menuitem"
            className="cg-menu-item"
            onClick={() => {
              openShare("folder", folderMenuF.id, folderMenuF.name);
              setFolderMenu(null);
            }}
          >
            <MenuLabel icon={<ShareMark size={16} />} text="Share folder" />
          </button>
          {onFolderDelete && (
            <button
              type="button"
              role="menuitem"
              className={
                "cg-menu-item cg-menu-item--danger is-danger" +
                (confirmDelete === folderMenuF.id ? " is-armed" : "")
              }
              onClick={() => {
                if (confirmDelete !== folderMenuF.id) {
                  setConfirmDelete(folderMenuF.id);
                  return;
                }
                onFolderDelete(folderMenuF.id);
                setConfirmDelete(null);
                setFolderMenu(null);
              }}
            >
              {/* The ARMED label is a whole sentence and the menu row is `nowrap` with a
                  260px ceiling, so it used to run out of the panel. It wraps while armed
                  (one rule in the S4 region) rather than being ellipsised: a confirmation
                  the reader cannot finish reading is not a confirmation. */}
              <MenuLabel
                icon="trash"
                text={
                  confirmDelete === folderMenuF.id
                    ? "Delete folder? Its views move to the top level."
                    : "Delete folder"
                }
              />
            </button>
          )}
        </AnchoredOverlay>
      )}

      {moveFor && moveView && (() => {
        const currentId = moveFor.bulk ? undefined : folderIdOf ? folderIdOf(moveFor.viewId) : null;
        const fileInto = (folderId: string | null) => {
          if (moveFor.bulk) {
            moveRailViews(railSelected, folderId);
            setMoveFor(null);
            return;
          }
          // The `...` menu's Move to asks the same helper the drag does, BEFORE the emit, so
          // there is no placement to take back. A read-only share files here too (S85-T33).
          const refusal = viewMoveRefusal(moveView, viewer);
          if (refusal) {
            signal(TOAST_EVENT, refusal);
            setMoveFor(null);
            return;
          }
          onItemMove?.(moveFor.viewId, folderId ?? ROOT_FOLDER_ID);
          setMoveFor(null);
        };
        return (
          <AnchoredOverlay
            anchor={moveFor.anchor}
            className="cg-pop"
            placement="bottom-end"
            role="dialog"
            ariaLabel={moveFor.bulk ? "Move selected views to a folder" : `Move ${viewDisplayName(moveView)} to a folder`}
            onDismiss={() => setMoveFor(null)}
            dataKind="view-move-to"
          >
            <div className="cg-pop-title">Move to</div>
            <div className="cg-pop-list" data-full-folder-path-picker>
              <button
                type="button"
                className={
                  "cg-pick-row" +
                  (currentId === null || currentId === ROOT_FOLDER_ID ? " is-on" : "")
                }
                onClick={() => fileInto(null)}
              >
                <FolderMark size={16} />
                {databases.find((database) => database.key === activeDatabaseKey)?.label ??
                  "Database"}
              </button>
              {moveFolders.map((folder) => (
                <button
                  type="button"
                  key={folder.id}
                  className={"cg-pick-row" + (folder.id === currentId ? " is-on" : "")}
                  style={{ paddingLeft: 6 + (nesting.depth[folder.id] ?? 0) * 12 }}
                  title={folderPath(folder.id, moveFolders).map((part) => part.name).join(" / ")}
                  onClick={() => fileInto(folder.id)}
                >
                  <FolderMark size={16} />
                  {folder.name}
                </button>
              ))}
              {moveFolders.length === 0 ? (
                <div className="cg-pop-note">There are no folders in this database yet.</div>
              ) : null}
            </div>
          </AnchoredOverlay>
        );
      })()}

      {/* Item 12 (C-LOCK) β€” the lock picker. Lists the cohorts this reader can see, marks the
          current one, and offers Unlock when there is one: a lock removable only from
          somewhere other than where it was applied is a trap, and the owner asked for a
          feature, not a one-way door. */}
      {lockFor && onCohortLock && (() => {
        const target = views.find((v) => v.id === lockFor.viewId);
        const current = target?.config?.cohortLock;
        return (
          <AnchoredOverlay
            anchor={lockFor.anchor}
            className="cg-pop cg-lock-pop"
            placement="bottom-start"
            role="dialog"
            ariaLabel="Lock this view to a locked view"
            onDismiss={() => setLockFor(null)}
            dataKind="view-cohort-lock"
          >
            <div className="cg-pop-title">Lock to a locked view</div>
            <div className="cg-pop-note">
              This view can then only ever show the records locked into the view you pick. Filters still narrow
              within it, and the lock cannot be removed as a condition.
            </div>
            {(lists ?? []).map((l) => (
              <button
                type="button"
                key={l.id}
                className={"cg-pick-row" + (l.id === current ? " is-on" : "")}
                onClick={() => {
                  onCohortLock(lockFor.viewId, l.id);
                  setLockFor(null);
                }}
              >
                {l.name}
              </button>
            ))}
            {current && (
              <button
                type="button"
                className="cg-pick-row cg-lock-clear"
                onClick={() => {
                  onCohortLock(lockFor.viewId, null);
                  setLockFor(null);
                }}
              >
                Unlock and show the whole table again
              </button>
            )}
          </AnchoredOverlay>
        );
      })()}
      {/* C4 as amended β€” the folder-level bulk add. The confirm pane states the
          DEDUPED union and names every view it could not compute, because a
          partial union that looks complete is the failure this pane exists to
          prevent ([[no-unverifiable-aggregates]]). */}
      {addTarget && addAnchor && addPreview && onFolderAddToList && (
        <AnchoredOverlay
          anchor={addAnchor ?? undefined}
          className="cg-pop cg-fold-addpop"
          placement="bottom-start"
          role="dialog"
          ariaLabel="Add this folder's customers to a locked view"
          onDismiss={() => setAddTarget(null)}
          dataKind="folder-add-to-list"
        >
          <div className="cg-pop-title">Add to cohort</div>
          <div className="cg-pop-note">
            {addPreview.pids.length.toLocaleString()} customer
            {addPreview.pids.length === 1 ? "" : "s"} from {addPreview.counted.toLocaleString()}{" "}
            view{addPreview.counted === 1 ? "" : "s"} in this folder, counted once each.
          </div>
          {addPreview.skipped.length > 0 && (
            <div className="cg-pop-note cg-fold-skipped">
              Not included:
              {addPreview.skipped.map((sk) => (
                <span key={sk.name} className="cg-fold-skip">
                  {sk.name}: {sk.why}
                </span>
              ))}
            </div>
          )}
          {(lists ?? []).map((l) => (
            <button
              type="button"
              key={l.id}
              className="cg-pick-row"
              onClick={() => {
                onFolderAddToList(addTarget, l.id, l.name);
                setAddTarget(null);
              }}
            >
              {l.name}
            </button>
          ))}
          <div className="cg-view-create">
            <label htmlFor="cg-fold-new-list">Lock records into a new view</label>
            <input
              id="cg-fold-new-list"
              className="cg-input"
              data-overlay-autofocus
              value={addName}
              onChange={(e) => setAddName(e.target.value)}
              onKeyDown={(e) => {
                if (e.key === "Enter" && addName.trim()) {
                  onFolderAddToList(addTarget, "", addName.trim());
                  setAddTarget(null);
                }
              }}
            />
            <button
              type="button"
              className="cg-btn cg-btn--primary"
              disabled={!addName.trim() || addPreview.pids.length === 0}
              onClick={() => {
                onFolderAddToList(addTarget, "", addName.trim());
                setAddTarget(null);
              }}
            >
              Create and add
            </button>
          </div>
        </AnchoredOverlay>
      )}

      {menu && menuView && (
        <AnchoredOverlay
          anchor={menu.anchor}
          className="cg-view-menu"
          placement="bottom-end"
          role="menu"
          ariaLabel={`Actions for ${viewDisplayName(menuView)}`}
          onDismiss={() => setMenu(null)}
          onKeyDown={onMenuKeyDown}
          dataKind="saved-view-menu"
        >
          {/* W2 (C2): Export sits ABOVE the rename/delete group, thin divider between. */}
          {(onExport || onExportXlsxViews || onImport) && (
            <>
              {/* ⭐ WAVE-29 T32 (owner item 16 / R10) β€” the DATA group's header.
                  The owner's complaint was that Export "looks like an orphan": it is already the
                  FIRST row of this menu and the divider under it is the only one, but every row
                  is styled identically, so the divider reads as a stray line rather than as the
                  end of a group. A header names the group instead.
                  β›” NOT A TOOLBAR BUTTON (R10) β€” a standalone Export was deliberately removed on
                  2026-08-03 so this menu is the ONE door; item 6's Import joins it here.
                  ⚠ INLINE STYLE, and it is a fence decision rather than a preference: this menu
                  has no group-header class anywhere in the stylesheet, and `index.css` belongs to
                  another session this wave. Tokens only, so it cannot invent a colour. */}
              <div
                role="presentation"
                style={{
                  padding: "6px 10px 2px",
                  fontSize: "10px",
                  fontWeight: 600,
                  letterSpacing: "0.02em",
                  color: "var(--lp-muted)",
                }}
              >
                Data
              </div>
              {(onExport || onExportXlsxViews) && (
                <button
                  type="button"
                  role="menuitem"
                  onClick={() => {
                    setExportFor({ viewId: menuView.id, anchor: menu.anchor });
                    setExportBulk(false);
                    setExportViewIds([]);
                    setMenu(null);
                  }}
                >
                  <MenuLabel icon="download" text="Export" />
                </button>
              )}
              {/* ⭐ WAVE-29 T25 (owner item 6) β€” IMPORT, beside Export, because they are the same
                  question in two directions and this menu is the ONE door for both (a standalone
                  Export button was deliberately removed on 2026-08-03; a second Import entry
                  anywhere else would re-open that).
                  ⚠ Supplied only on an EDITABLE database β€” the host passes `undefined` when
                  records are not mutable, which is what keeps the row off a locked one rather
                  than a check repeated here.
                  ⚠ `cohortAdd` is the nearest glyph the registry has; there is no upload mark
                  and `icons.tsx` is not this session's to extend. */}
              {onImport && (
                <button
                  type="button"
                  role="menuitem"
                  onClick={() => {
                    onImport();
                    setMenu(null);
                  }}
                >
                  <MenuLabel icon="upload" text="Import" />
                </button>
              )}
              <div className="cg-menu-sep" role="separator" aria-hidden />
              {/* …and the VIEW group's own header, so the divider now sits BETWEEN two named
                  groups rather than under one lonely row. R10 asks for both names. */}
              <div
                role="presentation"
                style={{
                  padding: "2px 10px 2px",
                  fontSize: "10px",
                  fontWeight: 600,
                  letterSpacing: "0.02em",
                  color: "var(--lp-muted)",
                }}
              >
                View
              </div>
            </>
          )}
          {/* I17 (C4) β€” the view's IDENTITY (name, description, deletion) is what the view
              permission governs. Duplicate is deliberately NOT gated: making your own copy
              changes nothing about this view, and it is how someone without edit rights gets a
              version they can work in.
              β›” W34-T22 REMOVED "folder" FROM THAT LIST, and the removal is the point rather
              than a tidy-up. Filing a view writes a PLACEMENT into the reader's own workspace
              stratum and never touches the owner's object, so it is navigation rather than an
              identity edit; the drag site asks `mayFileView` now (`types.ts`) while every row
              below still asks `mayEditView`. Left as a correction rather than deleted, because
              a sentence three hundred lines from the code it describes is exactly the shape that
              went stale unnoticed here. */}
          {canEditMenuView && (
            <button
              type="button"
              role="menuitem"
              onClick={() => {
                setRenamingId(menuView.id);
                setMenu(null);
              }}
            >
              <MenuLabel icon="rename" text="Rename" />
            </button>
          )}
          {canEditMenuView && (
            <button
              type="button"
              role="menuitem"
              onClick={() => {
                setNoteDraft(menuView.note ?? "");
                setNoteFor({ viewId: menuView.id, anchor: menu.anchor });
                setMenu(null);
              }}
            >
              <MenuLabel
                icon="description"
                text={menuView.note ? "Edit description" : "Add description"}
              />
            </button>
          )}
          <button
            type="button"
            role="menuitem"
            onClick={() => {
              onDuplicate(menuView.id);
              setMenu(null);
            }}
          >
            <MenuLabel icon="duplicate" text="Duplicate" />
          </button>
          {canFileMenuView && (
            <button
              type="button"
              role="menuitem"
              onClick={() => {
                setMoveFor({ viewId: menuView.id, anchor: menu.anchor });
                setMenu(null);
              }}
            >
              <MenuLabel icon={<FolderMark size={16} />} text="Move to" />
            </button>
          )}
          {/* WAVE 20 items 23/26 (R10) β€” "who else can reach this view", the same
              editor a folder and a database open. Deliberately NOT gated on
              `canEditMenuView`: the server decides who may administer (owner or
              admin) and says so in the dialog, and hiding the row from everyone else
              would hide the ANSWER too β€” "who has this?" is a fair question for
              anyone the view was shared with.
              ⭐ W40-T21 (D-254) β€” THE PADLOCK IS GONE FROM THIS ROW TOO, for the reason spelled
              out on the Share folder row: sharing is none of DESIGN.md Β§4's three locks, so the
              padlock was a false mark rather than an ambiguous one, and correcting it in a
              `title` would have been Β§4's "never over-explain" instead of a fix.
              ⚠ `verify_wiring.py` (W39-T29) used to IDENTIFY this row by the whole `MenuLabel`
              literal, `icon=` included, while checking that this row is offered outside the
              edit-only predicate. That pinned the GLYPH as part of a row identity rather than as
              the claim; it is retargeted at the row's label alone in the same change
              [[a-gate-that-pins-a-spelling-not-a-claim]]. The label below must therefore keep its
              exact spelling, which `verify_icons`'s T23 leg pins as well.
              β›” AND IT IS NOT SPELLED OUT IN THIS COMMENT ON PURPOSE. Both gates read the row
              through `code_only`, which strips comments precisely so prose cannot answer a
              question asked about code; a note repeating the row's own identity verbatim is the
              string that would satisfy the scan if that stripping were ever weakened. */}
          {!menuView.assigned && (
            <button
              type="button"
              role="menuitem"
              onClick={() => {
                openShare("view", menuView.id, viewDisplayName(menuView));
                setMenu(null);
              }}
            >
              <MenuLabel icon={<ShareMark size={16} />} text="Share view" />
            </button>
          )}
          {/* WAVE 20 item 25 (C-ALERT) β€” the door that MAKES an alert, on the view it
              watches. It belongs here and nowhere else: an alert IS "tell me when a
              record enters THIS view", so the only place the question has an obvious
              subject is the view's own menu.
              ⚠ The frame answers, because this rail does not know its own topic (it
              holds views; the scope key belongs to the route) β€” and because the server
              refuses a view with no active filter, which is a message the frame is
              already in the business of showing. */}
          {/* ⭐⭐ WAVE 32 Β· T24 (owner item 17, ruling R5, contract C4) β€” the one mark.
              β›” ABOVE the alert row, which is the done-when's own word and not a nicety: the two
              rows produce THE SAME red pill in the rail, and the cheap, private, instantly
              reversible one has to be reachable before the one that creates a stored server-side
              alert. Offered first, a user who only wanted to keep an eye on a number never has
              to make an alert to get one.
              β›” ONE MARK. W32-R5 is explicit: no second severity, no colour variants β€”
              `verify_icons` asserts the absence of a second one so it cannot arrive by
              copy-paste from this very row. The label FLIPS rather than the state being implied,
              because a "star this" label on an already-starred view reads as a label for the view.

              ⭐⭐ W35-T26 (owner item 9 / R4) β€” THE LABEL IS "STAR" NOW, AND ONLY THE LABEL.
              Owner: star and mark-important are ONE idea and ONE flag, and the word on screen is
              **Star**. So this pair reads Star / Unstar, the glyph was ALREADY a star (W33-T15),
              and the STORED key stays `config.important` β€” renaming the key would create exactly
              the second store R4 forbids, and would 400 every view already marked.
              ⚠ `verify_icons.py`'s T24 leg PINS these two strings and is A's file, so it reds on
              this rename until A retargets it at the CLAIM (one mark, above the alert row) rather
              than the spelling [[a-gate-that-pins-a-spelling-not-a-claim]]. Raised as `ASK C-10`. */}
          {onToggleImportant && (
            <button
              type="button"
              role="menuitem"
              onClick={() => {
                onToggleImportant(menuView.id, !menuView.config?.important);
                setMenu(null);
              }}
            >
              {/* ⭐ WAVE 33 Β· T15 (D-206) β€” A STAR, NOT A PADLOCK.
                  β›” This row shipped wearing MenuIcon `permissions` / `unlock` β€” a padlock that
                  three other rows in these same menus ALSO wore, untitled. Marking a view
                  important is none of the three locks (DESIGN.md Β§4): it freezes no record, no
                  column and no row set. So the answer is to drop the lock, not to title it β€” a
                  title naming a lock that does not exist would be believed.
                  ⭐ W40-T21 (D-254) finished the job this row started: the two SHARE rows took
                  the same treatment (sharing is not a lock either, so they wear the share glyph
                  now), and "Lock to a locked view" β€” the one row of the four that really is a
                  lock β€” keeps the padlock and names WHICH lock in its title. So the count in the
                  sentence above is history, not a description of these menus today.
                  ⚠ Passed as a NODE, exactly the way the alert row below passes `<BellIcon/>`:
                  `MenuLabel` takes `MenuIconName | ReactNode`, so a glyph no other menu row needs
                  costs the shared `MENU_ICONS` vocabulary nothing.
                  ⚠ `filled` is what says the view IS marked, so the pair still reads mark/unmark.
                  ⚠ `verify_icons`'s T24 leg pins this row's position above the alert row, which
                  does not move here; W35-T26 changes only the two LABEL strings. */}
              <MenuLabel
                icon={<StarIcon size={16} filled={!!menuView.config?.important} />}
                text={menuView.config?.important ? "Unstar" : "Star"}
              />
            </button>
          )}
          <button
            type="button"
            role="menuitem"
            onClick={() => {
              window.dispatchEvent(
                new CustomEvent("aios:alert-create", {
                  detail: { viewId: menuView.id, label: viewDisplayName(menuView) },
                })
              );
              setMenu(null);
            }}
          >
            <MenuLabel icon={<BellIcon size={16} />} text="Alert me about new records" />
          </button>
          {/* ⭐ WAVE 21 item 11 (ruling R10) β€” "paste a list of names and tick those
              records". It belongs in the VIEW's menu because the view is what decides
              which records are on the table to be found, and the result says so.

              ⚠ IT SELECTS THE VIEW FIRST when this is not the active one. The dialog
              matches over the rows the grid currently holds, so offering it on a view
              nobody is looking at would tick records in a DIFFERENT view's row set and
              report misses against the wrong table. Switching first makes the menu's
              subject and the dialog's subject the same object β€” and it is what clicking
              the row would have done anyway. */}
          {onSelectFromFile && (
            <button
              type="button"
              role="menuitem"
              onClick={() => {
                if (menuView.id !== activeViewId) onSelect(menuView.id);
                onSelectFromFile();
                setMenu(null);
              }}
            >
              <MenuLabel icon="cohortAdd" text="Select from file" />
            </button>
          )}
          {onAddToList && (
            <button
              type="button"
              role="menuitem"
              onClick={() => {
                // Item 4: `<view name> Β· <today>`, today from the PAYLOAD verbatim. No date
                // when the host sent none β€” never the browser clock.
                setNewListName(today ? `${viewDisplayName(menuView)} Β· ${today}`
                  : viewDisplayName(menuView));
                setAddFor({ viewId: menuView.id, anchor: menu.anchor });
                setMenu(null);
              }}
            >
              <MenuLabel icon="cohortAdd" text="Add to locked view" />
            </button>
          )}
          {/* Item 12 (C-LOCK) β€” LOCK the view to a cohort. This menu is the ONLY emitter of
              `cohortLock`, which is why it lands after RECORD's engine: an emitter for an
              engine that cannot yet read the key writes a config that silently does nothing.

              Deliberately NOT beside "Add to locked view" in meaning, though it sits beside it
              in the menu: that one COPIES today's matches into a set; this one makes the set the
              view's permanent boundary. The submenu lists the sets and offers Unlock when
              one is already set, because a lock that cannot be removed from the same place it
              was applied is a trap.

              β›” wave17 R1 β€” HIDDEN ON A LOCKED VIEW ITSELF, and this is not tidiness. A
              projected locked view's lock IS its identity: `aios_grid.views_from_defs` re-stamps
              `config.cohortLock = view.id` on EVERY READ, unconditionally, so a lock chosen here
              would be accepted by the UI, sent, and then silently overwritten by the host on the
              next payload. The rail would show no change and nothing would go red β€” the
              present-and-silently-inert affordance this file's own posture forbids. An action
              the server will not honour must be ABSENT, not merely ineffective.

              ⭐ W40-T21 (D-254) β€” THE ONE ROW OF THE THREE THAT REALLY IS A LOCK, so it KEEPS the
              padlock and gains the title Β§4 asks of anything wearing the shared mark: it names
              WHICH of the three locks it means. The locked-view kind, the row set, and not the
              other two β€” a locked database forbids adding, deleting and editing RECORDS, a
              pre-set field freezes one COLUMN, and painting either meaning here would tell the
              user something false. */}
          {onCohortLock && lists.length > 0 && canEditMenuView &&
            menuView.kind !== "locked" && (
            <button
              type="button"
              role="menuitem"
              title="Locked view: the records in it become a fixed set. Fields and other views are untouched."
              onClick={() => {
                setLockFor({ viewId: menuView.id, anchor: menu.anchor });
                setMenu(null);
              }}
            >
              <MenuLabel
                icon="permissions"
                text={menuView.config?.cohortLock ? "Change the lock" : "Lock to a locked view"}
              />
            </button>
          )}
          {/* I12 (C3) β€” freeze the DISPLAY MODE. Offered only to the creator or an admin,
              and only a courtesy: the host enforces the same rule, because a hidden control
              is still a reachable event. */}
          {onToggleLock && menuView.kind !== "system" && canEditMenuView &&
            mayToggleViewLock(menuView, viewer) && (
            <button
              type="button"
              role="menuitem"
              onClick={() => {
                onToggleLock(menuView.id, !isModeFrozen(menuView));
                setMenu(null);
              }}
            >
              {/* The FROZEN action wears the mode's own mark rather than a second padlock:
                  "Lock as Kanban" beside the kanban glyph says what gets frozen, which a
                  padlock cannot. Unlocking is the undo, so it takes the open shackle. */}
              <MenuLabel
                icon={
                  isModeFrozen(menuView)
                    ? "unlock"
                    : <ModeIcon mode={viewDisplayMode(menuView)} size={16} />
                }
                text={
                  isModeFrozen(menuView)
                    ? "Unlock view"
                    : `Lock as ${MODE_LABELS[viewDisplayMode(menuView)]}`
                }
              />
            </button>
          )}
          {/* ⚠ Delete is gated on the HOST's actual rule, NOT on `locked`. C3 widens `locked`
              to every view and defines it as mode-frozen only; leaving Delete on it would hide
              the entry for a user-frozen Kanban that the host would happily delete. */}
          {!isUndeletableView(menuView) && (canEditMenuView || canDismissMenuView) && (
            <button
              type="button"
              role="menuitem"
              className="is-danger"
              onClick={() => {
                onDelete(menuView.id);
                setMenu(null);
              }}
            >
              <MenuLabel icon="trash" text={canDismissMenuView ? "Dismiss" : "Delete"} />
            </button>
          )}
        </AnchoredOverlay>
      )}

      {/* W2 (C2) β€” the format pane: CSV Β· Excel Β· PDF Β· JSON, keyboard-navigable like
          the menu it came from. Rows/columns are the view's CURRENT matches and visible
          fields; generation is client-side (the grid already holds the answer). */}
      {exportFor && exportView && (onExport || onExportXlsxViews) && (
        <AnchoredOverlay
          anchor={exportFor.anchor}
          className="cg-view-menu"
          placement="bottom-end"
          role="dialog"
          ariaLabel={`Export ${viewDisplayName(exportView)}`}
          onDismiss={() => {
            setExportFor(null);
            setExportBulk(false);
            setExportViewIds([]);
          }}
          onKeyDown={onMenuKeyDown}
          dataKind="view-export"
        >
          <div className="cg-pop-title cg-export-title">Export {viewDisplayName(exportView)}</div>
          {onExportXlsxViews && !exportBulk && (
            <button
              type="button"
              role="menuitem"
              onClick={() => {
                setExportBulk(true);
                setExportViewIds(
                  exportableViewIds?.includes(exportView.id) ? [exportView.id] : []
                );
              }}
            >
              Bulk select
            </button>
          )}
          {onExportXlsxViews && exportBulk && (
            <div className="cg-pop-body">
              <div className="cg-pop-note">Each selected View becomes its own Excel tab.</div>
              {xlsxExportViews.map((view) => {
                const selected = exportViewIds.includes(view.id);
                return (
                  /* W46-T03: its OWN class, not `cg-radio-row`. These are checkboxes, and the
                     radio class carries no font-size at all, so the rows were inheriting the
                     17px root while `.cg-pop-title` and `.cg-pop-note` beside them sit at
                     `--lp-fs-2xs`. `rail-select.css` puts the whole panel on one step. */
                  <label key={view.id} className="cg-export-view-row">
                    <input
                      type="checkbox"
                      checked={selected}
                      disabled={(selected && exportViewIds.length === 1) ||
                        (!selected && exportViewIds.length >= 20)}
                      onChange={() =>
                        setExportViewIds((current) => selected
                          ? current.filter((id) => id !== view.id)
                          : [...current, view.id])
                      }
                    />
                    <span>{viewDisplayName(view)}</span>
                  </label>
                );
              })}
            </div>
          )}
          {EXPORT_FORMATS.map((format) => {
            /* ⭐ W50-T12 / R11 β€” BOTH Excel doors are gated on READINESS, and both hand over a
               workbook that is already built. The click does no network work at all: that is
               what makes the download reachable from inside the gesture, which is the whole of
               the fix. While the build is in flight the button says so rather than pretending
               to be idle, because a control that looks live and does nothing is the defect. */
            if (format === "xlsx" && exportBulk && onExportXlsxViews) {
              return (
                <button
                  key={format}
                  type="button"
                  role="menuitem"
                  disabled={!exportReady}
                  onClick={() => {
                    onExportXlsxViews(exportIntendedIds);
                    setExportFor(null);
                  }}
                >
                  {exportReady || !exportViewIds.length
                    ? "Export Excel"
                    : "Preparing your workbook"}
                </button>
              );
            }
            if (format === "xlsx" && !exportBulk && !onExport && onExportXlsxViews) {
              return (
                <button
                  key={format}
                  type="button"
                  role="menuitem"
                  disabled={!exportReady}
                  onClick={() => {
                    onExportXlsxViews(exportIntendedIds);
                    setExportFor(null);
                  }}
                >
                  {exportReady ? "Export Excel" : "Preparing your workbook"}
                </button>
              );
            }
            if (!onExport || (exportBulk && format !== "xlsx")) return null;
            return (
              <button
                key={format}
                type="button"
                role="menuitem"
                onClick={() => {
                  onExport(exportView.id, format);
                  setExportFor(null);
                }}
              >
                {EXPORT_LABELS[format]}
              </button>
            );
          })}
        </AnchoredOverlay>
      )}

      {/* Add to cohort β€” the view's CURRENT matches become fixed members of a cohort. Worded
          as a one-time copy ("Add ... to") rather than a link, because that is what it is:
          the cohort does not track the view afterwards, which is the entire difference
          between a cohort and a saved view. */}
      {addFor && addView && onAddToList && (
        <AnchoredOverlay
          anchor={addFor.anchor}
          className="cg-pop cg-add-list-pop"
          placement="bottom-end"
          role="dialog"
          ariaLabel={`Add ${viewDisplayName(addView)} to a locked view`}
          onDismiss={() => setAddFor(null)}
          dataKind="add-to-list"
        >
          <div className="cg-pop-title">Add to cohort</div>
          <div className="cg-pop-note">
            Adds the customers <strong>{viewDisplayName(addView)}</strong> matches right now. The cohort
            stays fixed as the data changes.
          </div>
          {lists.map((l) => (
            <button
              type="button"
              key={l.id}
              className="cg-pick-row"
              onClick={() => {
                onAddToList(addView.id, l.id, l.name);
                setAddFor(null);
              }}
            >
              {l.name}
            </button>
          ))}
          <div className="cg-view-create">
            <label htmlFor="cg-new-list">Lock records into a new view</label>
            <input
              id="cg-new-list"
              className="cg-input"
              data-overlay-autofocus
              value={newListName}
              placeholder="e.g. Q3 call plan"
              onChange={(event) => setNewListName(event.target.value)}
              onKeyDown={(event) => {
                if (event.key === "Enter" && newListName.trim()) {
                  onAddToList(addView.id, "", newListName.trim());
                  setAddFor(null);
                }
              }}
            />
            <div className="cg-form-actions">
              <button
                type="button"
                className="cg-btn cg-btn--primary"
                disabled={!newListName.trim()}
                onClick={() => {
                  onAddToList(addView.id, "", newListName.trim());
                  setAddFor(null);
                }}
              >
                Create and add
              </button>
            </div>
          </div>
        </AnchoredOverlay>
      )}

      {/* Description editor β€” mirrors the column menu's field-note interaction so the
          two "explain this thing" affordances behave identically. */}
      {noteFor && noteView && (
        <AnchoredOverlay
          anchor={noteFor.anchor}
          className="cg-pop cg-view-note-pop"
          placement="bottom-end"
          role="dialog"
          ariaLabel={`Description for ${viewDisplayName(noteView)}`}
          onDismiss={() => setNoteFor(null)}
          dataKind="saved-view-note"
        >
          <div className="cg-pop-title">Description</div>
          <label className="cg-column-note">
            {/* Wave-10 item 9 moved the description off the grid and onto the view's row,
                so this sentence had to move with it β€” it described a banner that no longer
                exists. */}
            {/* ⚠ W34-T26 β€” "the view name", not "this view's name", and the apostrophe is the
                whole reason. `web_prose`'s TypeScript walk has no parser: an apostrophe in JSX
                TEXT opens a single-quoted string it never closes, so the walk ran from here to
                the end of this region, swallowing ~37 lines (this span's tail, the <textarea>
                and its attributes, two <button>s and a `//` comment). It then reported the em
                dash inside that swallowed COMMENT as a finding on this line: mislocated, and a
                false positive by the gate's own contract, since comments are exempt.
                β›” THE POINT OF THIS EDIT IS NOT THE GREEN. A walker that believes it is inside a
                string also SKIPS every real string after it, so those 37 lines were unscanned;
                removing the apostrophe restores the gate's sight over them. The underlying defect
                is `verify_prose.py`'s and is reported to A (post C-3; lane B raised the same
                thing as B-3, measuring 248 lines lost in one file). Do NOT rewrite the COMMENTS
                it reports to silence it, which is the version of this that destroys reasoning. */}
            <span>Shown under the view name in the list.</span>
            <textarea
              data-overlay-autofocus
              value={noteDraft}
              maxLength={2000}
              placeholder="What is this list for?…"
              onChange={(event) => setNoteDraft(event.target.value)}
            />
          </label>
          <div className="cg-form-actions">
            <button
              type="button"
              className="cg-btn cg-btn--primary"
              // Enabled whenever the text CHANGED β€” including changing it to empty,
              // which is how a description is removed. Never compared against the
              // template seed, only against what is currently stored.
              disabled={noteDraft === (noteView.note ?? "")}
              onClick={() => {
                onNote(noteView.id, noteDraft);
                setNoteFor(null);
              }}
            >
              Save description
            </button>
            <button
              type="button"
              className="cg-btn"
              onClick={() => setNoteFor(null)}
            >
              Cancel
            </button>
          </div>
        </AnchoredOverlay>
      )}

      {/* Database actions share the existing menu row and focus styles. */}
      {databaseMenu ? (
        <AnchoredOverlay
          anchor={databaseMenu}
          className="cg-view-menu"
          role="menu"
          ariaLabel="Database actions"
          onDismiss={() => setDatabaseMenu(null)}
          placement="bottom-end"
        >
          {!readOnly && canManageFields && activeDatabase ? <button type="button" role="menuitem"
            onClick={() => {
              setFieldsFor({ key: activeDatabase.key, label: activeDatabase.label, opener: databaseMenu });
              setDatabaseMenu(null);
            }}>
            Fields
          </button> : null}
          <button
            type="button"
            role="menuitem"
            onClick={() => {
              // The panel takes the SAME anchor: it belongs to the control that was pressed,
              // not to a menu row that is about to stop existing.
              setTrashAnchor(databaseMenu);
              setDatabaseMenu(null);
            }}
          >
            Trash
          </button>
        </AnchoredOverlay>
      ) : null}

      {fieldsFor && canManageFields && fieldsFor.key === activeDatabaseKey ? (
        <DatabaseFieldsDrawer key={fieldsFor.key} databaseKey={fieldsFor.key}
          databaseLabel={fieldsFor.label} onBack={closeFields} />
      ) : null}

      {/* ⭐⭐ W50-T27 (C4) β€” THE PANEL ITSELF.
          β›” AN EMPTY `className`, AND IT IS A DECISION RATHER THAN AN OMISSION β€” `AnchoredOverlay`
          declares the prop REQUIRED, so "" is written out where every other overlay in this file
          names a surface. `AnchoredOverlay` stamps `cg-overlay` unconditionally, and that class
          sets a z-index and nothing else; `.vt-panel` already carries this panel's whole surface
          (background, hairline border, radius, overflow) from `views-trash/trash.css`. Adding
          `cg-view-menu` here would drag in `index.css`'s `.cg-view-menu button { width: 100% }`
          β€” a DESCENDANT selector β€” and stretch the panel's two tabs and every Restore button
          across the box, and `cg-pop` would frame an already-framed panel inside a second border.
          The child IS the surface, which is the only version of
          [[a-portal-overlay-carries-its-own-surface]] that does not need new CSS, and new CSS is
          outside this ticket's two files.
          ⚠ `role="dialog"`, not `menu`: this is a working surface with tabs, a list and its own
          controls, and calling it a menu would tell a screen reader to expect menu items. */}
      {trashAnchor && activeDatabaseKey ? (
        <AnchoredOverlay
          anchor={trashAnchor}
          className=""
          role="dialog"
          ariaLabel="Trash"
          onDismiss={() => setTrashAnchor(null)}
          placement="bottom-end"
          dataKind="view-trash"
        >
          <TrashPanel tableKey={activeDatabaseKey} onRestored={onTrashRestored} />
        </AnchoredOverlay>
      ) : null}
    </aside>
    {folded && <RailHeaderIcons
      owner="data"
      anchor={railEl}
      onExpand={narrow ? () => setNarrowOpen(true) : toggleRail}
      chatOpen={chatOpen}
      onToggleChat={onToggleChat}
    />}
    </>
  );
}