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

import type { ChoiceRemoval } from "./apiBridge";
export interface ColumnMenuState {
  fieldKey: string;
  anchor: AnchorRect;
  /**
   * Item 12 (R8) β€” which pane this opening lands on. Absent = the action list, i.e. every
   * pre-wave-26 opening. `"edit"` is the kanban's "Add option" door.
   *
   * ⚠ Narrowed to the ONE pane that has a door rather than the whole `MenuPane` union: widening
   * it would let any future caller deep-link into `permissions`, whose entry is gated on the
   * viewer inside the menu's own action list β€” a state you can only reach through a check would
   * become a state you can reach around it.
   */
  pane?: "edit";
}

interface FieldConfigExtra {
  defaultValue?: Field["defaultValue"] | null;
  if?: IfDefinition;
  formula?: string;
  max?: number;
  scope?: FieldScope;
  label?: string;
  colorCodeOptions?: boolean;
  optionColors?: Record<string, string>;
  /**
   * ⭐ Wave-20 owner item 15 (contract C-RENAME) β€” **AN EXPLICIT MAPPING, NEVER A DIFF.**
   *
   * Renaming a choice used to change the DECLARED list and nothing else, so every cell still
   * held the old label and the column went blank-looking: "Blue" was no longer a choice, and
   * the rows that said "Blue" said something the field did not offer. The migration needs to
   * know that Blue BECAME Navy β€” and neither end can infer that from two lists, because
   * "renamed Blue to Navy" and "deleted Blue, added Navy" produce the identical pair
   * (`routes_tables.py` says the same thing from the server's side).
   *
   * It is knowable HERE, and only here: every option row carries a stable `OptionDraft.id`
   * from the moment the editor opens, so a row whose label changed is a RENAME by identity, a
   * new row is an addition, and a removed row is a removal. No guessing, at either end.
   */
  renames?: { from: string; to: string }[];
  /** Wave-18 C5-AUTOFIELD β€” an automation column's configuration, the same way `formula`
   *  carries an expression. Validated host-side (`aios_grid._clean_automation`). */
  automation?: { kind: string; source: "record_url_field" | "self"; urlField?: string };
  /** ⭐⭐ W37-T22 (R4 / C7) β€” the geocode pseudo-kind's bag: which column holds the address.
   *  Carried on `extra` exactly as `automation`/`link`/`rollup` are, and validated host-side by
   *  `aios_grid._clean_geocode`. The created field's `type` is `text` (see `Field.geocode`). */
  geocode?: { addressField: string; country?: string };
  /** ⭐ 2026-08-07 β€” a `link` column's target. REQUIRED for the type: `_clean_field` returns
   *  None for a link with no bag, so a create without this is a column that never appears. */
  link?: {
    table: string;
    on?: string;
    from?: string;
    single?: boolean;
    selectionMode?: "manual" | "automatic";
    selectionFilter?: FilterTree;
    via?: HopViaBag;
  };
  /** ⭐ 2026-08-07 β€” a `rollup` column's aggregate. Same requirement, same reason.
   *  ⭐ 2026-08-09 β€” or, INSTEAD, a `source` binding: the read-through kind, which summarises
   *  rows that were never copied into the workspace. The host's `_clean_rollup` reads `source`
   *  first and returns before it ever looks at `link`, so the two are exclusive by construction
   *  rather than by a rule someone has to remember. */
  rollup?: {
    link?: string; field?: string; fn?: string;
    limit?: number; sortBy?: string; sortDir?: "asc" | "desc";
    distinctBy?: string;
    /** ⭐⭐ 2026-08-09 β€” the PRE-filter: applied before the most-recent window, so "the last 10"
     *  counts only records that already match. `_clean_rollup` refuses a `ref` leaf here (there
     *  is no fixed set yet for a statistic to describe). */
    where?: RollupCondition[];
    whereConj?: "and" | "or";
    conditions?: RollupCondition[];
    conditionConj?: "and" | "or";
    source?: RollupSource;
  };
  /** ⭐ Wave-27 item 13 (R13) β€” a `code` column's language. OPTIONAL, unlike the two bags above
   *  it: `_clean_field` accepts a code column without one and it renders as plain text, so this
   *  is an ordinary edit rather than a create requirement. */
  code?: { language: string };
  /** ⭐⭐ Wave-34 (owner ruling R13) β€” an AI ENRICHMENT column's config. REQUIRED, like `link`
   *  and `rollup` and unlike `code`: `_clean_field` returns None for an `ai_enrich` column with
   *  no bag, because a prompt is the only thing that can ever produce a value here. Shaped
   *  exactly as `core.user_tables._clean_ai_enrich` stores it, so the panel and the store cannot
   *  disagree about a key name. */
  aiEnrich?: {
    prompt: string;
    model?: string;
    maxTokens: number;
    trigger: { mode: string; cron?: string };
    overwrite: string;
  };
}

interface ColumnMenuProps {
  viewControlsReadOnly?: boolean;
  state: ColumnMenuState;
  field: Field;
  /** Every field of the table, for "Change field" (owner item 9): the clicked column can be
   *  swapped for any other field β€” including hidden ones like Notes β€” in place. */
  fields: Field[];
  /**
   * ⭐ 2026-08-07 β€” the OTHER databases a `link` column may point at, with their fields (so the
   * rollup editor can offer real column names rather than a free-text key). Supplied by the host
   * from `GET /tables`, which already filters by `may_open`.
   *
   * ⚠ ABSENT on the Odoo-backed Customer/Product grids, and that is what withdraws the two
   * relational types from their create menu β€” there is no second user table to point at there,
   * so offering "Link to another record" would be offering a column that can never resolve.
   */
  linkTargets?: LinkTarget[];
  /**
   * ⭐⭐ 2026-08-09 β€” the READ-THROUGH rollup's offer (topic β†’ measure β†’ dim β†’ window), fetched
   * by the host from `GET /tables/rollup-sources`.
   *
   * ⚠ EMPTY IS MEANINGFUL AND IS THE COMMON CASE. A tenant with no connected source gets `[]`,
   * and the editor then never renders the mode switch at all β€” a rollup is simply a link fold,
   * as it was before this existed. So this prop is what turns the second kind ON, not a flag.
   */
  rollupSourceOffer?: RollupSourceOffer;
  /** Dedicated typed offer from GET /grid/hop-topics; never derived from rollup sources. */
  hopTopicOffer?: HopTopicOffer;
  locked: boolean;
  /** Product-owned preset fields may still drive view actions, but their schema is immutable. */
  schemaLocked?: boolean;
  /** Linked grids expose personal layout actions only, even when edit callbacks exist. */
  embedded?: boolean;
  canAddField?: boolean;
  columnWidth?: number;
  onColumnWidth?: (width: number) => void;
  /**
   * ⭐⭐ W40-T24 β€” the grid is a `ut_*` runtime database rather than an Odoo-backed topic. It
   * feeds `columnDefinitionOffer` (display.ts), which is this menu's ONE statement of the pre-set
   * definition lock, and EVERY verdict reads it: a shared-definition column on a user database is
   * the user's to reshape, and the identical shape on an Odoo-backed topic is not.
   * ⚠ OPTIONAL and false by default only for the "+" create instance, which has no real subject
   * column β€” it passes `locked`, so its verdicts are the closed ones either way. A real column
   * menu must pass it; defaulting is a convenience for the create door, not a shrug.
   */
  isUserTable?: boolean;
  /** Wave-5 item 1 β€” who is looking. Gates the permissions entry (creator-or-admin). */
  viewer?: Viewer;
  /** Wave-5 item 3 β€” what the CURRENT VIEW does with this field, so the conditional
   *  "Don't sort/filter/group by this field" entries render exactly when they apply. */
  sortedDir: "asc" | "desc" | null;
  isFiltered: boolean;
  isGrouped: boolean;
  /** types.isGroupableField, computed by the caller (it owns lockedKey). */
  groupable: boolean;
  onClose: () => void;
  onNote: (note: string) => void;
  onHide: () => void;
  /** Header drag has a keyboard-equivalent path in this same action surface. */
  onMoveLeft?: () => void;
  onMoveRight?: () => void;
  onCreate: (
    label: string,
    type: FieldType,
    anchorKey: string | null,
    side: "left" | "right" | "end",
    options?: string[],
    measureSpec?: { key: string; window: WindowSpec },
    extra?: FieldConfigExtra
  ) => void;
  /** Swap THIS column for another field, in place (owner item 9). */
  onChangeField: (newKey: string) => void;
  /**
   * Wave-2 item 5: the Change-field window's "New field" half β€” create a fresh overlay field
   * of the chosen type and swap this column for it in one motion. The old field hides exactly
   * as an ordinary change does. Wave-6 item 2 REPLACES this flow on created (`custom_`)
   * fields with `onRetype` below.
   */
  onCreateAndSwap: (
    label: string,
    type: FieldType,
    options?: string[],
    extra?: FieldConfigExtra
  ) => void;
  /**
   * Wave-6 item 2, re-homed by owner item 8 (2026-07-31): supplied for CREATED (`custom_`)
   * fields only β€” the EDIT FIELD pane's type picker RETYPES THIS FIELD IN PLACE (same key,
   * new type/options; values never converted β€” unreadable cells show blank, disclosed in the
   * pane). `extra.label` rides along when the name changed in the same save, so rename+retype
   * is ONE upsert β€” two sequential emits would each read the stale def and revert the other.
   */
  /** ⭐ 2026-08-07 (D-79) β€” flip the C3 profile flag on a `text` column of a `ut_*` table.
   *  Absent on every surface that is not a user table, which is what hides the control. */
  onProfileFlag?: (key: string, on: boolean) => void;
  onRetype?: (
    type: FieldType,
    options?: string[],
    extra?: FieldConfigExtra
  ) => void;
  /**
   * Owner, 2026-09-02 - retire a SAVED option of this choice field, with the cells that hold it.
   * `confirm: false` answers how many cells use it (the warning); `confirm: true` removes the
   * option and clears those values, immediately. Supplied beside `onRetype`, for the same fields,
   * by the same predicate, so a field whose type cannot be edited cannot lose options either.
   */
  onChoiceRemove?: (option: string, confirm: boolean) => Promise<ChoiceRemoval | null>;
  /**
   * ⭐⭐ 2026-08-09 (owner) β€” RECONFIGURE an existing `link`/`rollup` column's bag.
   *
   * A DIFFERENT DOOR FROM `onRetype`, not a variant of it. `onRetype` writes the per-user overlay
   * stratum and refuses anything that is not a `custom_` overlay field; these bags live in the
   * table's SHARED definition and reach it through `PATCH /tables/{key}/fields/{fkey}`. Wiring
   * this through `onRetype` would have meant a Save button that runs and does nothing on exactly
   * the columns the owner was trying to edit.
   *
   * ⚠ Supplied for USER DATABASES only β€” its absence is what withdraws the editor from the
   * Odoo-backed grids, where there is no such endpoint.
   */
  onFieldConfig?: (patch: {
    label?: string;
    type?: FieldType;
    options?: string[];
    colorCodeOptions?: boolean;
    optionColors?: Record<string, string>;
    renames?: { from: string; to: string }[];
    defaultValue?: Field["defaultValue"] | null;
    format?: FieldFormat;
    if?: IfDefinition;
    link?: Record<string, unknown>;
    rollup?: Record<string, unknown>;
  }) => void;
  /** Wave-6 item 5 β€” rename this created field (ordinary field_upsert with a new label).
   *  Supplied for creatable strata only. */
  onRename?: (label: string) => void;
  /**
   * Owner item 8 (2026-07-31) β€” edit a FORMULA field's source in place (the Edit-field pane's
   * per-type editor for the formula type, validated with the field itself as selfKey so a
   * cycle is refused at authoring). `label` rides along exactly like onRetype's β€” one upsert.
   * Supplied for created formula fields only.
   */
  onFormula?: (formula: string, label?: string) => void;
  /** Wave-6 item 4 β€” open straight into the create form at this position (the header "+"
   *  passes "end"). Cancel then CLOSES rather than falling back to the action list. */
  initialPosition?: CreatePosition;
  /**
   * ⭐ WAVE-26 ITEM 12 (owner ruling R8) β€” open straight into a PANE, the way `initialPosition`
   * opens straight into the create form.
   *
   * The kanban's "Add option" door passes `"edit"`. The owner's words were *"its literally the
   * same thing as adding a new option when you click edit field on multi-select"*, and this prop
   * is what makes that literal rather than approximate: the lane editor IS this component's Edit
   * pane, so it writes the SHARED field definition through the same `onRetype` upsert, obeys the
   * same permission wall, carries the same rename-by-row-identity migration and the same colour
   * swatches. A second options editor would have had to re-earn every one of those.
   *
   * Back then CLOSES β€” same rule as `initialPosition`: there is no action list behind a pane
   * that was opened directly.
   */
  initialPane?: MenuPane;
  /** Wave-6 item 9c β€” true on the cohort page: the create forms offer the Scope control
   *  ("This cohort table only" = DEFAULT vs "All customer tables"). */
  scopeChoice?: boolean;
  /** Wave-6 item 11c β€” pin state + actions. `onPinTo` absent when pinning would be a no-op
   *  (identity column, or already the boundary); `onUnpin` absent when nothing is pinned. */
  pinnedTo?: boolean;
  onPinTo?: () => void;
  onUnpin?: () => void;
  /**
   * Wave-2 item 8c: change the PERIOD of a measure-carrying column. Supplied for any field with
   * `.measure` β€” user-created `measure_*` columns and the pre-set measure fields alike. The
   * caller emits the ordinary `field_upsert` (and auto-renames the header when the user never
   * renamed it).
   */
  /**
   * W48C-T12 (go-live QA 2026-09-02): the Edit pane exposes the SAME Metric controls as Create -
   * the Number (which measure) and the Period. `measureKey` rides beside the window when the
   * person picked a different number; absent, the number is unchanged. One upsert either way.
   */
  onPeriod?: (window: WindowSpec, measureKey?: string) => void;
  /**
   * Delete this USER-CREATED column outright (owner gap closed 2026-07-27). Supplied ONLY for
   * the deletable strata (`custom_` overlay fields, `measure_` formula columns) β€” absent means
   * the control is not rendered at all, so a base field cannot even be offered the action.
   */
  onDelete?: () => void;
  /** Owner-only change to C3's server-owned deletion lock. */
  onSetDeletionLock?: (locked: boolean) => void;
  /** Copies a canonical Data path that opens this field's properties. */
  onCopyFieldLink?: () => void;
  /**
   * ⭐⭐ W41-T29 (R6(b)) β€” DROP A COLUMN SOMEBODY ELSE SHARED WITH ME, off my own list. A
   * DIFFERENT ACT from `onDelete`, and therefore a different door: it destroys no definition and
   * no values, and pointing "Remove from my fields" at the delete handler would be a benign word
   * on a destructive action.
   * A host supplies null when no real remove door exists. Shared-with-me fields still lose Delete.
   */
  onRemoveFromMine: (() => void) | null;
  /** ⭐⭐ Wave-34 (R13) β€” run this AI enrichment column over many rows.
   *  `scope` is `"blank"` (only cells still empty) or `"always"` (every row the AI
   *  wrote). OPTIONAL for `onDelete`'s reason: a host that has not wired the door shows
   *  no row, rather than a row that does nothing. */
  onEnrich?: (scope: "blank" | "always") => void;
  /**
   * ⭐⭐ W51-T03 / OWNER RULING R6 β€” duplicate this field as a tenant-owned custom field, through
   * ONE door.
   *
   * β›” IT TAKES NO ARGUMENT ANY MORE, AND THE MISSING ARGUMENT IS THE FEATURE. The prop used to
   * be `(copyValues: boolean) => void`, which forced this menu to state the copy choice as two
   * separate verbs before the reader had even seen the column. Owner, instruction 5: *"'Duplicate
   * definition' and 'Duplicate permitted value' are confusing: one button."* The choice survives
   * where it can be answered β€” the host counts what the column actually holds and either opens the
   * shared confirm dialog with a "Duplicate cells" toggle or, when the column holds nothing,
   * duplicates at once. A menu cannot make that decision because it cannot see the rows.
   */
  onDuplicate?: () => void;
  /** Wave-5 item 10 β€” save a display format. Supplied for number/currency/formula and
   *  date/created_time fields. */
  onFormat?: (format: FieldFormat) => void;
  /**
   * ⭐⭐ WAVE 50 Β· W50-T05 / OWNER RULING R2 β€” set this column's SUMMARY, **AS A VIEW SETTING**.
   *
   * β›” THIS PROP REPLACES `onAggregate`, AND THE RENAME IS THE FEATURE. R2: *"the summary choice
   * is PER VIEW, not per field"*. The old prop took an `AggName | undefined` and its host wrote
   * `field.agg` β€” the store W50-T03 retired β€” so a menu pick and a bar pick disagreed about
   * where the answer lived, and `verify_grid_ux.py`'s own R2 clause said in prose that this
   * control "still does" write the field. It does not any more: the host writes
   * `view.config.summary[colId]`, the same key and the same `SummaryChoice` shape the bar's
   * `onSummaryPick` writes. `resolveSummary` still READS `field.agg` as a legacy fallback, which
   * is what keeps every already-saved view rendering what it was saved with, with no migration.
   *
   * ⚠ "None" is `{ agg: "none" }`, a STORED value rather than an absent key β€” that is how a
   * reader turns a numeric column's Sum default OFF, and why the choice is never `undefined`.
   */
  onSummary?: (choice: SummaryChoice) => void;
  /** ⭐ W50-T05 β€” the view's summary map, so this pane resolves the SAME choice the bar shows
   *  (R2's order: the view's key, then the legacy `field.agg`, then Sum on a numeric family).
   *  Absent = an empty map, which is what a host with no view config in scope has. */
  summary?: SummaryMap;
  /**
   * ⭐⭐ W50-T05 β€” **HOW THIS COLUMN READS: Value, % of total, or Both.**
   *
   * Offered wherever a field write is possible, and the pane itself refuses any column outside
   * `isNumericFieldType` β€” the eligibility test, never a hand-written kind list (ERROR 20).
   *
   * β›” THE HOST MUST ROUTE THIS THROUGH THE DEFINITION DOOR ON A SHARED COLUMN (D-468 / D-275).
   * `CustomerGrid.tsx`'s `saveField` writes the per-user OVERLAY stratum, which forks a `ut_*`
   * shared definition into a private copy of itself; `setFieldConfig` PATCHes the one shared
   * record in place. This prop states the choice and says nothing about the door, which is why
   * the branch is asserted at the host and not here.
   */
  onShowAs?: (showAs: ShowAs) => void;
  /** Wave-5 item 1 β€” Sort by this field (replaces the view's sort), and the conditional
   *  clears (item 3). All of these mutate the EXISTING view config β€” no new host surface. */
  onSort?: (dir: "asc" | "desc") => void;
  onClearSort?: () => void;
  onFilterBy?: () => void;
  onClearFilter?: () => void;
  onGroupByField: () => void;
  onClearGroup: () => void;
  /** Assignable people, from the host's real user list. Empty = the host did not supply one,
   *  and "Assignee" is offered without choices rather than with invented ones. */
  userOptions?: string[];
  /**
   * CG-8's measures, reused as the vocabulary of a FORMULA-MEASURE column (owner item 7):
   * `Sales Β· the last 90 days` as a column the user creates. Empty = the semantic store is
   * unavailable here, and the option is simply not offered (same rule as measure conditions).
   */
  measures?: Measure[];
  /**
   * ⭐⭐ W37-T22 (owner item 15 / R4, contract C7) β€” MAY A GEOCODE COLUMN BE CREATED ON THIS
   * SURFACE? REQUIRED rather than optional-with-a-default, deliberately: a defaulted boolean is
   * how a capability ships silently off at whichever call site somebody forgets, and both call
   * sites for this menu live in one file.
   * β›” It answers "will the bag SURVIVE the create here", NOT "does this table have an address
   * column" β€” the menu ANDs it with the address vocabulary itself. See `TypePicker`'s
   * `offerGeocode` doc for why the two questions currently differ.
   */
  geocodable: boolean;
  /**
   * ⭐⭐ W39-T17 β€” THE SERVER-ISSUED TABLE KEY, and the ONLY reason "Share field" needs a prop at
   * all: a column is not addressable on its own. A field share's oid is
   * `"<table_key>:<field_key>"` (`core.shares.field_oid`), and nothing else in this file knows
   * which database the column lives on β€” the only `topic` here belongs to the rollup source
   * offer, which is a rollup's TARGET topic, not this column's table.
   *
   * β›”β›” IT MUST BE `payload.workspace.storageKey` AND NOTHING ELSE, and a near-miss fails
   * SILENTLY. `core.shares.split_field_oid` fails closed to `(None, None)` on any id it cannot
   * split; `routes_shares._object_ref` then answers `route=None` and `_notify_new_grantees`
   * returns EARLY, so the grant is written and NOBODY IS TOLD. The host's local fallback
   * (`${LOCAL_KEY_PREFIX}${scope}`) is, in `CustomerGrid`'s own words, "a key the server never
   * issues" β€” a share built on one is junk that looks like it worked.
   *
   * ⚠ ABSENT IS A REAL STATE AND IT WITHDRAWS THE ROW. A workspace read that 403s leaves no
   * storageKey, and a query PREVIEW's columns are a projection rather than the database's own;
   * both pass nothing, and the menu then offers no Share entry rather than one that cannot
   * resolve. `shared_overlay` is keyed by exactly this spelling on both sides
   * (`product_table_workspace` for a registry topic, the bare key for a `ut_*` database) and
   * `_object_ref` strips the `_table_workspace` suffix itself, so it travels UNMODIFIED.
   */
  tableKey?: string;
}

type CreatePosition = "left" | "right" | "end";

// ⚠ wave-7 item W4's menu-action icon set + `MenuLabel` MOVED to `icons.tsx` (wave-14
// item 19): the view menu needs the same vocabulary, and two hand-drawn padlocks in two
// files is how one of them ends up a different padlock. `icon=` takes a NAME now.

/**
 * The menu's panes (wave-5 item 2). The NOTE editor and the editors used to render inline in
 * the menu body; each opens its OWN dedicated window. One overlay, one pane at a time;
 * "menu" is the action list.
 *
 * Owner item 8 (2026-07-31): "edit" ABSORBS the former "rename" and "swap" panes β€” one
 * Airtable-grade Edit-field window owning the field's name, its type (with the per-type
 * choices/stars/formula config), and the Change-field control that swaps the column to show
 * another field.
 */
type MenuPane = "menu" | "edit" | "format" | "summary" | "showAs" | "width";

/**
 * How each creatable type reads in the menu. DERIVED from CREATABLE_TYPES rather than listed
 * again: a hand-maintained copy is a third place the vocabulary lives, and the failure mode is
 * silent β€” add a type to the contract, forget this list, and the type is accepted by the host,
 * asserted by the drift gate, and simply never offered to anyone.
 *
 * `Record<FieldType, string>` is what forces it: adding a member to the union without a label
 * here fails `tsc`, so the compiler is the gate and no test has to click a canvas header menu.
 *
 * Wave-8 I20: the map itself MOVED to icons.tsx, beside the per-type glyphs β€” a type's label
 * and its icon are one vocabulary, and splitting them across two files is how they drift.
 * Imported here; the totality guarantee above is unchanged (icons.tsx types it identically).
 */
const FIELD_TYPES = CREATABLE_TYPES.map((value) => ({ value,
  label: value === "if" ? "If statement" : TYPE_LABELS[value] }));

/** Types whose choices are declared in an options editor at creation time.
 *  ⚠ Takes `CreateKind`, not `FieldType`: both PSEUDO-kinds answer false (a Metric's choices
 *  are the measure catalog, a geocode column's are a column pick), and typing it narrower is what
 *  made `tsc` name every one of these call sites when `geocode` landed. That is the check
 *  working. */
function needsOptions(t: CreateKind): boolean {
  return t === "select" || t === "multiselect";
}

function supportsDefaultValue(type: CreateKind): type is FieldType {
  return ["text", "int", "currency", "pct", "select", "date"].includes(type);
}

function defaultValueFromDraft(type: FieldType, value: string): Field["defaultValue"] {
  return ["int", "currency", "pct"].includes(type) && value !== "" ? Number(value) : value;
}

function defaultValueDraftValid(type: CreateKind, value: string): boolean {
  if (value === "") return true;
  if (["int", "currency", "pct"].includes(type)) return Number.isFinite(Number(value));
  return type !== "date" || /^\d{4}-\d{2}-\d{2}$/.test(value);
}

function DefaultValueEditor({ type, enabled, value, options, onEnabled, onValue }: {
  type: FieldType;
  enabled: boolean;
  value: string;
  options: string[];
  onEnabled: (enabled: boolean) => void;
  onValue: (value: string) => void;
}) {
  return <>
    <label className="cg-check-row" style={{ flexDirection: "row" }} title="Used only when a new record omits this field">
      <input type="checkbox" checked={enabled}
        onChange={(event) => onEnabled(event.target.checked)} />
      <span>Default value</span>
    </label>
    {enabled && <label>
      <span>Value</span>
      {type === "select" ? <select className="cg-select" value={value}
        aria-label="Default value" onChange={(event) => onValue(event.target.value)}>
        <option value="">Empty</option>
        {value && !options.includes(value) && <option value={value}>{value}</option>}
        {options.filter((option) => option !== "").map((option) =>
          <option key={option} value={option}>{option}</option>)}
      </select> : <input className="cg-input" value={value} aria-label="Default value"
        aria-invalid={!defaultValueDraftValid(type, value)}
        type={type === "date" ? "date" : ["int", "currency", "pct"].includes(type) ? "number" : "text"}
        step="any" onChange={(event) => onValue(event.target.value)} />}
    </label>}
  </>;
}

interface OptionDraft {
  id: string;
  label: string;
  color: string;
}

const DEFAULT_OPTION_LABELS = ["Not started", "In progress", "Blocked", "Done"];

/**
 * ⭐ WAVE 28 Β· R4 / C1 β€” how a SET-STATISTIC comparison reads in the operator list.
 *
 * β›” KEYED BY `RollupRefOp`, so the day `core.user_tables.ROLLUP_REF_OPS` gains or loses an
 * operator this map fails to compile rather than rendering a bare identifier β€” the same
 * discipline `ROLLUP_FN_LABELS` uses, and the reason the Οƒ picker maps `ROLLUP_REF_OPS` instead
 * of hand-filtering the full operator list.
 * ⚠ The wording names the STATISTIC, not the arithmetic: "2 Οƒ above the mean" is the sentence a
 * person is trying to write, and "is greater than mean + kΒ·stdev" is the implementation of it.
 */
/**
 * ⭐ MIRRORS `core.user_tables.ROLLUP_MAX_SIGMAS`, and `verify_rollup_editor.py` HOLDS THE TWO IN
 * STEP by importing the server's constant and comparing (a real enforcer this time β€” `types.ts`
 * spent a wave claiming one that contained zero occurrences of the word it guarded,
 * [[limit-with-no-enforcer]]).
 *
 * β›” WHY THE CONTROL MUST KNOW THE BOUND AT ALL. `_clean_rollup` REFUSES the whole field outside
 * this range β€” not the leaf, the FIELD β€” so an unbounded box invites a value and then answers a
 * 400 naming a cap the control never mentioned. That is `maxPosts` exactly: it offered 200 while
 * the save door refused anything over 12 ([[default-must-pass-its-own-guard]]). A control must
 * display what it will SEND.
 */
const MAX_SIGMAS = 10;

/** The default when a Οƒ row is born or its box is left empty β€” C1's worked example uses 2. */
const DEFAULT_SIGMAS = 2;

const REF_OP_LABELS: Record<RollupRefOp, string> = {
  gt: "is more than … Οƒ above the mean",
  gte: "is at least … Οƒ above the mean",
  lt: "is less than … Οƒ above the mean",
  lte: "is at most … Οƒ above the mean",
};

/**
 * ⭐⭐ 2026-08-09 (owner) β€” ONE CONDITION LIST, RENDERED TWICE, because a rollup now filters at
 * two different moments and they mean different things.
 *
 * Owner: *"instead of last 12 posts, we also want to make it so its last N record, where the
 * record's Status is video."* That is a filter the WINDOW must respect β€” pick the reels first,
 * then take the last 10 of them. The existing list is the opposite by design (wave 28 / C1 moved
 * it below the window so a `ref: {sigmas}` threshold is a statistic OF the rows being folded), so
 * the two cannot be one control.
 *
 * β›” EXTRACTED RATHER THAN COPIED. Two near-identical 130-line JSX blocks is how one of them
 * keeps offering an operator the other dropped β€” and the operator list here is already the
 * server's (`ROLLUP_REF_OPS`), so a hand-edited second copy would drift from `_clean_rollup`
 * silently ([[one-evaluator-per-question]]).
 * β›” `allowRef` IS A REFUSAL MIRRORED, NOT A UI PREFERENCE. `_clean_rollup` refuses a `ref` leaf
 * in `where` β€” before the window there is no fixed set for a mean to be about β€” so offering the
 * Οƒ operators there would be a control whose only outcome is a 400 on the whole field.
 */
function RollupConditionList({
  title,
  hint,
  conditions,
  onConditions,
  conj,
  onConj,
  targetFields,
  allowRef,
  idPrefix,
}: {
  title: string;
  hint: string;
  conditions: RollupCondition[];
  onConditions: (v: RollupCondition[]) => void;
  conj: "and" | "or";
  onConj: (v: "and" | "or") => void;
  targetFields: { key: string; label: string }[];
  allowRef: boolean;
  idPrefix: string;
}) {
  const patch = (index: number, next: RollupCondition) =>
    onConditions(conditions.map((item, i) => (i === index ? next : item)));
  return (
    <div className="cg-rollup-conditions">
      <div className="cg-rollup-conditions__head">
        <span>{title}</span>
        <button
          type="button"
          className="cg-btn"
          disabled={targetFields.length === 0 || conditions.length >= 20}
          onClick={() => onConditions([
            ...conditions,
            { field: targetFields[0]?.key ?? "", op: "eq", value: "" },
          ])}
        >
          Add condition
        </button>
      </div>
      {conditions.length > 1 ? (
        <select
          className="cg-input"
          aria-label={`Match all or any ${title.toLowerCase()} conditions`}
          value={conj}
          onChange={(event) => onConj(event.target.value as "and" | "or")}
        >
          <option value="and">All conditions must match</option>
          <option value="or">Any condition may match</option>
        </select>
      ) : null}
      {conditions.map((condition, index) => (
        <div className="cg-rollup-condition" key={`${idPrefix}-${index}-${condition.field}`}>
          <select
            className="cg-input"
            aria-label={`${title} condition ${index + 1} column`}
            value={condition.field}
            onChange={(event) => patch(index, { ...condition, field: event.target.value })}
          >
            {targetFields.map((targetField) => (
              <option key={targetField.key} value={targetField.key}>{targetField.label}</option>
            ))}
          </select>
          {/*
            ⭐⭐ WAVE 28 Β· R4 / C1 β€” THE THRESHOLD MAY BE THE SET'S OWN STATISTICS.
            Owner's request (Nurilab): an average of the last 10 posts with outliers trimmed β€”
            "anything beyond 2 sigma". That is not a new aggregator, it is a CONDITION whose
            threshold is computed from the scoped rows themselves: mean + k*stdev of the same
            column, over the window `sortBy`+`limit` kept, BEFORE these conditions filter.

            β›” ONE CONTROL, NOT TWO, AND THAT IS WHAT MAKES THE XOR SAFE. `value` and `ref` may
            never both be present β€” the server refuses the whole FIELD, not just the leaf β€” so
            a separate "compare against…" switch beside the operator would leave the editor
            free to write a `ref` while a stale `value` still rode along, producing a 400 on
            Save that names a key the user never typed. Folding the choice into the operator
            makes the illegal state unrepresentable: picking a plain op WRITES `value` and
            drops `ref`, picking a statistic op does the reverse, and there is no third path.

            ⚠ THE OPS ARE `ROLLUP_REF_OPS`, IMPORTED, never a hand-filtered copy of the full
            list. `eq`/`neq` against a computed float is a coin flip on binary representation
            and `contains` against a number never matches β€” the server draws that line and a
            second copy here would be free to drift from it.
            ⚠ THE `value` IS COMPOUND (`ref:gt`) so the select always resolves to exactly one
            option. A `<select>` whose value matches nothing renders the FIRST option while
            the stored key says otherwise, and the next patch writes the lie back
            ([[cg-condition-builder-items]]).
          */}
          <select
            className="cg-input"
            aria-label={`${title} condition ${index + 1} operator`}
            value={condition.ref ? `ref:${condition.op}` : condition.op}
            onChange={(event) => {
              const raw = event.target.value;
              const isRef = raw.startsWith("ref:");
              const op = (isRef ? raw.slice(4) : raw) as RollupCondition["op"];
              // β›” THE LEAF IS REBUILT, NEVER SPREAD-AND-PATCHED. `{ ...item, ref: undefined }`
              // leaves the key present-and-undefined; `JSON.stringify` drops it today, but the
              // contract is "the key is absent", and relying on a serialiser's treatment of
              // `undefined` to enforce a server-side XOR is a guarantee held by accident.
              patch(index, isRef
                ? { field: condition.field, op,
                    ref: { sigmas: condition.ref?.sigmas ?? DEFAULT_SIGMAS } }
                : { field: condition.field, op, value: condition.value ?? "" });
            }}
          >
            <optgroup label="Compared with a value">
              <option value="eq">is</option>
              <option value="neq">is not</option>
              <option value="contains">contains</option>
              <option value="not_contains">does not contain</option>
              <option value="is_empty">is empty</option>
              <option value="is_not_empty">is not empty</option>
              <option value="gt">is greater than</option>
              <option value="gte">is at least</option>
              <option value="lt">is less than</option>
              <option value="lte">is at most</option>
            </optgroup>
            {allowRef ? (
              <optgroup label="Compared with the set's own spread">
                {ROLLUP_REF_OPS.map((op) => (
                  <option key={op} value={`ref:${op}`}>{REF_OP_LABELS[op]}</option>
                ))}
              </optgroup>
            ) : null}
          </select>
          {condition.ref ? (
            <label className="cg-cond-ref">
              {/* ⚠ A BARE NUMBER BOX WOULD BE A CONTROL THAT WILL NOT SAY WHAT IT SETS. The
                  unit is sigmas and the sign is meaningful (negative selects the LOW tail), so
                  both are printed beside the input rather than left to be inferred from a
                  placeholder. */}
              <input
                className="cg-input"
                type="number"
                step="0.5"
                /* β›” THE SERVER'S OWN BOUND, BOTH WAYS. Outside it `_clean_rollup` refuses the
                   whole FIELD, so an unbounded box would invite a 400 naming a cap it never
                   showed β€” `maxPosts`'s scar, in a control built the same day it was quoted. */
                min={-MAX_SIGMAS}
                max={MAX_SIGMAS}
                aria-label={`${title} condition ${index + 1} standard deviations from the mean`}
                /* ⚠ UNCONTROLLED + COMMIT ON BLUR, the idiom `maxPosts` uses and for its
                   reason: a controlled box patching per keystroke stores "-" as 0 and "1" on
                   the way to "1.5" as a legal value, and `Number("")` is 0 β€” so simply
                   CLEARING the box would silently store "0 sigma", a real but different
                   query, and the field could never be retyped because it snaps back. */
                defaultValue={String(condition.ref.sigmas)}
                onBlur={(event) => {
                  const raw = Number(event.target.value);
                  // Empty/garbage falls back to the default rather than to 0 β€” 0 means "at
                  // the mean" and is a value somebody must choose, never one they land on by
                  // deleting a character.
                  const parsed = event.target.value.trim() === "" || !Number.isFinite(raw)
                    ? DEFAULT_SIGMAS
                    : raw;
                  // CLAMPED, not refused: the box is a dial, and a dial that rejects is a
                  // dead control. The clamp is what makes "displays what it will send" true.
                  const sigmas = Math.max(-MAX_SIGMAS, Math.min(MAX_SIGMAS, parsed));
                  if (String(sigmas) !== event.target.value) event.target.value = String(sigmas);
                  patch(index, { field: condition.field, op: condition.op, ref: { sigmas } });
                }}
              />
              <span>Οƒ from the mean of this column (negative reads below it)</span>
            </label>
          ) : !(["is_empty", "is_not_empty"] as string[]).includes(condition.op) ? (
            <input
              className="cg-input"
              aria-label={`${title} condition ${index + 1} value`}
              value={condition.value ?? ""}
              onChange={(event) => patch(index, {
                field: condition.field, op: condition.op, value: event.target.value,
              })}
            />
          ) : null}
          <button
            type="button"
            className="cg-icon-btn"
            aria-label={`Remove ${title.toLowerCase()} condition ${index + 1}`}
            onClick={() => onConditions(conditions.filter((_item, i) => i !== index))}
          >
            Γ—
          </button>
        </div>
      ))}
      <div className="cg-field-hint">{hint}</div>
    </div>
  );
}

let optionDraftSequence = 0;

function nextOptionDraftId(): string {
  optionDraftSequence += 1;
  return `choice-${optionDraftSequence}`;
}

function optionDrafts(
  labels: string[],
  saved: Record<string, string> | undefined = undefined
): OptionDraft[] {
  return labels.map((label) => ({
    id: nextOptionDraftId(),
    label,
    color:
      normalizeOptionColor(saved?.[label]) ??
      normalizeOptionColor(defaultOptionColor(label))!,
  }));
}

function optionSettings(
  drafts: OptionDraft[],
  type: CreateKind,
  maxOptions: number | null
): { options: string[]; colors: Record<string, string>; capMessage: string | null } {
  const clean = drafts.map((draft) =>
    type === "multiselect" ? draft.label.replace(/,/g, " ") : draft.label
  );
  const parsed = parseOptions(clean.join("\n"), maxOptions);
  const options = parsed.options;
  const firstByLabel = new Map<string, OptionDraft>();
  drafts.forEach((draft, index) => {
    const label = clean[index].trim();
    if (label && !firstByLabel.has(label.toLowerCase()))
      firstByLabel.set(label.toLowerCase(), draft);
  });
  const colors: Record<string, string> = {};
  for (const option of options) {
    const draft = firstByLabel.get(option.toLowerCase());
    const color = normalizeOptionColor(draft?.color);
    // The deterministic fallback is not durable data. Persist only a genuine user override;
    // this keeps an untouched legacy field byte-stable while a renamed row retains its colour.
    if (color && color !== normalizeOptionColor(defaultOptionColor(option)))
      colors[option] = color;
  }
  return { options, colors, capMessage: parsed.message };
}

function optionAppearanceSignature(
  options: string[],
  colors: Record<string, string> | undefined
): string {
  return options
    .map((option) => {
      const custom = colors
        ? Object.entries(colors).find(
            ([label]) => label.trim().toLowerCase() === option.toLowerCase()
          )?.[1]
        : undefined;
      return `${option}\u0000${
        normalizeOptionColor(custom) ?? normalizeOptionColor(defaultOptionColor(option))
      }`;
    })
    .join("\u0001");
}

/**
 * Item 22 (R5) β€” the option COLOUR control: ten brand swatches, no free RGB.
 *
 * It was an `<input type="color">`, which offered sixteen million colours in a product whose
 * whole visual argument is five. The trigger keeps the old 24px circle's footprint (it is the
 * same affordance in the same place) and opens a 5Γ—2 grid: each hue's light `-tint` on the top
 * row, its `-pastel` beneath. A stored colour that is not on the palette marks its NEAREST
 * swatch β€” so the picker says what the value reads as β€” and re-picking is what rewrites it.
 */
function SwatchPicker({
  value,
  disabled,
  label,
  onPick,
}: {
  value: string | undefined;
  disabled?: boolean;
  /** The option this colours, for the accessible name. */
  label: string;
  onPick: (hex: string) => void;
}) {
  const [open, setOpen] = useState(false);
  const ref = useRef<HTMLButtonElement>(null);
  const current = nearestSwatch(value);
  return (
    <>
      <button
        ref={ref}
        type="button"
        className="cg-option-color"
        disabled={disabled}
        style={{ background: current?.bg ?? normalizeOptionColor(value) ?? "#FFFFFF" }}
        aria-label={`Colour for ${label}${current ? ` β€” ${current.label}` : ""}`}
        aria-haspopup="dialog"
        aria-expanded={open}
        title="Change option colour"
        onClick={() => setOpen((o) => !o)}
      />
      {open && ref.current && (
        <AnchoredOverlay
          anchor={ref.current}
          className="cg-pop cg-swatch-pop"
          onDismiss={() => setOpen(false)}
          role="dialog"
          ariaLabel={`Colour for ${label}`}
          dataKind="option-colour"
        >
          <div className="cg-swatch-grid">
            {BRAND_SWATCHES.map((swatch) => (
              <button
                key={swatch.id}
                type="button"
                className={"cg-swatch" + (current?.id === swatch.id ? " is-on" : "")}
                style={{ background: swatch.bg, color: swatch.fg }}
                aria-label={swatch.label}
                aria-pressed={current?.id === swatch.id}
                title={swatch.label}
                onClick={() => {
                  onPick(swatch.bg);
                  setOpen(false);
                }}
              >
                {/* The check is drawn in the swatch's OWN ink, which is also the ink its
                    chips will use β€” so the mark doubles as a preview of readability. */}
                {current?.id === swatch.id && (
                  <svg width="12" height="12" viewBox="0 0 16 16" fill="none" aria-hidden>
                    <path
                      d="m3.5 8.5 3 3 6-6.5"
                      stroke="currentColor"
                      strokeWidth="2"
                      strokeLinecap="round"
                      strokeLinejoin="round"
                    />
                  </svg>
                )}
              </button>
            ))}
          </div>
        </AnchoredOverlay>
      )}
    </>
  );
}

function OptionsEditor({
  idPrefix,
  drafts,
  onDrafts,
  colorCode,
  onColorCode,
  type,
  maxOptions,
  onRemove,
}: {
  idPrefix: string;
  drafts: OptionDraft[];
  onDrafts: (next: OptionDraft[]) => void;
  colorCode: boolean;
  onColorCode: (next: boolean) => void;
  type: CreateKind;
  maxOptions: number | null;
  /** When supplied, the X on a row asks the parent (which may need to warn) instead of
   *  dropping the draft itself. The create pane never supplies it: nothing there is saved. */
  onRemove?: (draft: OptionDraft) => void;
}) {
  const update = (id: string, patch: Partial<OptionDraft>) =>
    onDrafts(drafts.map((draft) => (draft.id === id ? { ...draft, ...patch } : draft)));
  const settings = optionSettings(drafts, type, maxOptions);
  return (
    <div className="cg-options-editor">
      <div className="cg-options-head">
        <strong>Options</strong>
        <label className="cg-option-toggle">
          <input
            type="checkbox"
            checked={colorCode}
            onChange={(event) => onColorCode(event.target.checked)}
          />
          <span>Color-code options</span>
        </label>
      </div>
      <div className="cg-option-list">
        {drafts.map((draft, index) => (
          <div className="cg-option-row" key={draft.id}>
            <SwatchPicker
              value={
                normalizeOptionColor(draft.color) ??
                OPTION_PALETTE[index % OPTION_PALETTE.length].bg
              }
              disabled={!colorCode}
              label={draft.label || `option ${index + 1}`}
              onPick={(hex) => update(draft.id, { color: hex })}
            />
            <input
              id={`${idPrefix}-${draft.id}`}
              className="cg-input cg-option-name"
              type="text"
              maxLength={120}
              value={draft.label}
              placeholder="Option name"
              aria-label={`Option ${index + 1}`}
              onChange={(event) => {
                const label =
                  type === "multiselect"
                    ? event.target.value.replace(/,/g, " ")
                    : event.target.value;
                update(draft.id, { label });
              }}
              onKeyDown={(event) => {
                if (event.key !== "Enter") return;
                event.preventDefault();
                onDrafts([
                  ...drafts,
                  {
                    id: nextOptionDraftId(),
                    label: "",
                    color: OPTION_PALETTE[drafts.length % OPTION_PALETTE.length].bg,
                  },
                ]);
              }}
            />
            <button
              type="button"
              className="cg-option-remove"
              aria-label={`Remove ${draft.label || `option ${index + 1}`}`}
              title="Remove option"
              onClick={() =>
                onRemove
                  ? onRemove(draft)
                  : onDrafts(drafts.filter((item) => item.id !== draft.id))
              }
            >
              <svg viewBox="0 0 16 16" aria-hidden="true">
                <path d="M4 4l8 8M12 4l-8 8" />
              </svg>
            </button>
          </div>
        ))}
      </div>
      <button
        type="button"
        className="cg-option-add"
        onClick={() =>
          onDrafts([
            ...drafts,
            {
              id: nextOptionDraftId(),
              label: "",
              color: OPTION_PALETTE[drafts.length % OPTION_PALETTE.length].bg,
            },
          ])
        }
      >
        Add option
      </button>
      <span className="cg-field-hint">
        {settings.options.length} option{settings.options.length === 1 ? "" : "s"}.
        {type === "multiselect" && " Commas inside an option are not supported."}
      </span>
      {settings.capMessage && (
        <span className="cg-field-hint is-refusal" role="alert">
          {settings.capMessage}
        </span>
      )}
    </div>
  );
}

/**
 * A source-backed choice field may be editable at the record level while its schema stays owned
 * by the database contract.  The normal options editor must not promise a definition write for
 * that field, but hiding its hydrated vocabulary makes an imported value look unconfigured.
 */
function ChoicePreview({ field }: { field: Field }) {
  const options = choiceOptions(field);
  if (options.length === 0) return null;
  return (
    <div className="cg-options-editor cg-options-preview">
      <div className="cg-options-head"><strong>Choices</strong></div>
      <div className="cg-options-preview-list">
        {options.map((option) => (
          <span className="cg-option-preview" key={option}>{option}</span>
        ))}
      </div>
    </div>
  );
}

/**
 * The create-picker's kind: a creatable overlay type, or the FORMULA-MEASURE pseudo-kind.
 * "measure" is deliberately NOT a FieldType β€” a measure column's real type comes from the
 * measure itself (currency/int/pct), and widening the union would let it leak into every
 * switch that renders cells.
 */
type CreateKind = FieldType | "measure" | "geocode";
type PickerKind = CreateKind | RollupPreset;
const PRESET_LABELS: Record<RollupPreset, string> = { count: "Count", lookup: "Lookup" };

/**
 * ⭐⭐ W37-T22 (R4 / C7) β€” the geocode pseudo-kind's picker label, and the address-column families
 * it may read. Declared here beside `CreateKind` because three places consume them (the picker
 * row, the config pane's field list and `canCreate`) and a second spelling of either is how two
 * of them end up disagreeing about what is offered.
 * ⚠ NO DASH of any kind in the label β€” it reaches the screen, and `web_prose` cannot see a
 * wrapped JSX sentence, so this one is on the author.
 *
 * ⭐⭐ W40-T29 (owner instruction 31) β€” SHORTENED TO ONE NOUN. The label used to carry a trailing
 * clause naming where the numbers come from, which is the IMPLEMENTATION read out at someone
 * scanning a list of nouns; every other row in that list is the thing you get, not how it is got,
 * and the source column is picked one control later anyway. The old wording is not repeated here:
 * a rename that leaves its own before-picture in a doc block is how the next reader reinstates it,
 * and `_test/gridUx.test.ts` asserts the whole file is free of it.
 * ⚠ THE IDENTIFIER STAYS. One producer, one consumer, and `verify_grid_ux.py`'s geocode-door scan
 * matches `label: GEOCODE_LABEL` BY NAME, so inlining the string here would blind the gate rather
 * than satisfy it.
 */
const GEOCODE_LABEL = "Coordinates";
const GEOCODE_ADDRESS_TYPES: readonly FieldType[] = ["text", "url", "email", "phone"];

/**
 * Owner item 8 (2026-07-31) β€” the create pane's field-type picker: a find box over an icon
 * listbox, replacing the icon-less native select. Each row wears the SAME mark its column
 * header will wear (`FieldTypeIcon` ← TYPE_SHAPES), so the vocabulary teaches itself. The
 * "measure" pseudo-kind borrows the currency mark: a measure column's real type is
 * currency/int/pct, and inventing a 17th glyph for a pseudo-kind would put a mark on screen
 * that no column ever wears.
 */
function TypePicker({
  value,
  onPick,
  offerMeasure,
  offerGeocode,
  offerPresets,
  isUserTable,
  only,
}: {
  value: PickerKind;
  onPick: (k: PickerKind) => void;
  offerMeasure: boolean;
  /**
   * ⭐⭐ W37-T22 (R4 / C7) β€” offer the geocode pseudo-kind. REQUIRED, not optional: an optional
   * boolean prop defaults to "off" at every call site somebody forgets, which is
   * mounted-but-never-offered wearing a default.
   * β›” IT IS NOT "does this table have a text column". It is "will the bag SURVIVE a create on
   * this surface", and today those differ: on the Odoo customer/product grids a created column
   * takes the overlay path into `aios_grid._field_extras`, which carries the bag; on a `ut_*`
   * database every grid-created column goes to the DEFINITION (W29-T22) through
   * `user_tables._clean_field`, which is a strict allowlist with no `geocode` arm yet and would
   * store the column WITHOUT its configuration. Offering it there would create a field that is
   * named, configured and permanently unable to run, which is the `image`-in-wave-19 failure.
   * ⚠ The caller therefore ANDs the capability with the vocabulary; when `_clean_field` learns
   * the arm (raised as `ASK C-6`), the capability half becomes constant and this reads as
   * "has an address column", which is what W37-T22's `done-when` asks for.
   */
  offerGeocode: boolean;
  /** Presets author a rollup bag and are create-only, never retype options. */
  offerPresets: boolean;
  /** Runtime database surfaces withhold create kinds their server refuses. */
  isUserTable: boolean;
  /** Restrict the list (the Edit-field pane passes RETYPE_TYPES β€” the overlay-editable
   *  strata a created field may become). Absent = every creatable type. */
  only?: readonly FieldType[];
}) {
  const [q, setQ] = useState("");
  const [describedKind, setDescribedKind] = useState<PickerKind | null>(null);
  const needle = q.trim().toLowerCase();
  const offerable = only
    ? FIELD_TYPES.filter((r) => (only as readonly string[]).includes(r.value))
    : FIELD_TYPES;
  const base = offerable.filter((row) => offerableCreateKind(row.value, isUserTable));
  const rows: { value: PickerKind; label: string }[] = [
    ...base,
    ...(offerPresets
      ? ROLLUP_PRESETS.map((preset) => ({ value: preset, label: PRESET_LABELS[preset] }))
      : []),
    // C-NAME (item 9, 2026-08-02): "Formula measure (over a period)" -> "Metric". Two words
    // of jargon and a parenthetical, replaced by the word people already use for the thing.
    // The internal key stays `measure` β€” see the C-NAME amendment in the wave doc.
    ...(offerMeasure
      ? [{ value: "measure" as CreateKind, label: "Metric" }]
      : []),
    // ⭐⭐ W37-T22 (R4 / C7) β€” the geocode pseudo-kind, offered on the same terms the Metric row
    // above it is: exactly when the surface can actually deliver it. The two rows are the whole
    // membership of `CreateKind` beyond `FieldType`, which is why they sit together.
    ...(offerGeocode
      ? [{ value: "geocode" as CreateKind, label: GEOCODE_LABEL }]
      : []),
  ].filter((r) => !needle || r.label.toLowerCase().includes(needle));
  // ⭐⭐ W40-T29 (owner instruction 31) β€” the list stopped being a wall of 22 nouns here, and the
  // grouping is applied to the ALREADY-FILTERED rows on purpose: one find box still reaches both
  // groups, and a group the needle empties is dropped by `groupTypePickerRows` heading and all
  // rather than leaving a label with nothing behind it (R8).
  const groups = groupTypePickerRows(rows);
  return (
    <div className="cg-type-picker">
      <div className="cg-type-search">
        <svg width="13" height="13" 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={q}
          placeholder="Find a field type"
          aria-label="Find a field type"
          onChange={(event) => setQ(event.target.value)}
        />
      </div>
      <div className="cg-type-list" role="listbox" aria-label="Field type">
        {groups.map((group) => (
          // β›” A FRAGMENT, NOT A WRAPPER, and the reason is an accessibility one rather than a
          // layout one. `.cg-type-list` is the flex column that lays the rows out, so a wrapping
          // div would need `display: contents` to stay out of the way β€” which DROPS the element
          // from the accessibility tree, inside the one container that is claiming to be a
          // listbox. `FieldSelect.tsx` reached this conclusion first for its own grouped list
          // ("Pre-set fields" / "Your fields" / "New field"); this follows it rather than
          // inventing a second answer to a question the codebase already settled.
          // ⚠ The heading is `role="presentation"` for the same reason: a listbox's children are
          // options, and a bare div claiming nothing is what keeps the heading out of the option
          // set while leaving it visible. Arrow-key navigation elsewhere collects
          // `button.cg-type-row`, so a non-button child is invisible to it by construction.
          <Fragment key={group.heading ?? "ordinary"}>
            {group.heading && (
              <div className="cg-type-group" role="presentation">
                {group.heading}
              </div>
            )}
            {group.rows.map((r) => (
              <div
                key={r.value}
                role="option"
                aria-selected={value === r.value}
                className="cg-type-option"
              >
                <button
                  type="button"
                  className={"cg-type-row" + (value === r.value ? " is-on" : "")}
                  onClick={() => onPick(r.value)}
                >
                  <FieldTypeIcon
                    type={
                      r.value === "measure" ? "currency" : r.value === "geocode" ? "text"
                        : r.value === "count" || r.value === "lookup" ? "rollup"
                          : r.value === "if" ? "formula" : r.value
                    }
                    size={16}
                  />
                  <span className="cg-type-label">{r.label}</span>
                </button>
                <button
                  type="button"
                  className="cg-type-info"
                  aria-label={`About ${r.label}`}
                  aria-expanded={describedKind === r.value}
                  title={TYPE_DESCRIPTIONS[r.value]}
                  onClick={() => setDescribedKind((current) => current === r.value ? null : r.value)}
                >
                  {/* ⭐⭐ W46-T31 (owner instruction 27) β€” THE ADD-FIELD INFO MARK JOINS THE HOUSE
                      ICON VOCABULARY. It was the literal characters `(i)`, the one glyph in this
                      menu drawn in text while every mark beside it is a 16-viewBox stroked SVG:
                      it inherited the row's font rather than the icon size, could not take the
                      hairline weight, and rendered differently on every platform's font stack.
                      ⚠ THE BUTTON IS UNCHANGED β€” `type`, `className`, `aria-label`,
                      `aria-expanded`, `title` and `onClick` all stay exactly as they were. Only
                      the visible glyph moved from text to a mark, and `aria-hidden` on the svg
                      is what keeps the `aria-label` the single spoken name. */}
                  <svg width="12" height="12" viewBox="0 0 16 16" fill="none" aria-hidden focusable="false" stroke="currentColor" strokeWidth={1.25} strokeLinecap="round" strokeLinejoin="round">
                    <circle cx="8" cy="8" r="5.7" />
                    <path d="M8 7.4v3.4" />
                    <path d="M8 5.2v.1" />
                  </svg>
                </button>
                {describedKind === r.value && (
                  <div className="cg-type-description" role="status">
                    {TYPE_DESCRIPTIONS[r.value]}
                  </div>
                )}
              </div>
            ))}
          </Fragment>
        ))}
        {rows.length === 0 && <div className="cg-pop-note">No matching type.</div>}
      </div>
    </div>
  );
}

/** The Change-field dropdown's "New field" entries. A colon cannot occur in a real field key
 *  (keys are slugs), so the prefix cannot collide with one. */
const NEW_PREFIX = "new:";

/**
 * The types a created field may be retyped TO (the Edit-field pane's type picker): the
 * overlay-editable strata only. `formula` and `created_time` are a DIFFERENT stratum
 * (source 'odoo', host-computed shape) β€” turning an overlay column into one is not a retype,
 * and the host accepts in-place rebuilds on `custom_` overlay defs only.
 */
// Wave-18 C5-AUTOFIELD: `automation` joins the exclusion, and for a reason the two above do not
// share. It IS an overlay type, so the host would accept the retype β€” which is exactly the
// hazard. Retyping a Notes column to Automation hands every row's typed value to the next run to
// overwrite; retyping the other way strands machine-written statuses in a column a person can
// now edit. Neither is a change of TYPE, both are data loss with a tidy name.
const RETYPE_TYPES = CREATABLE_TYPES.filter(
  (t) => !AUDIT_FIELD_TYPES.includes(t) && t !== "formula" && t !== "created_time" && t !== "automation" && t !== "if" && t !== "autonumber"
);

/** The automation kinds a column can carry. v1 is one; the shape is a list so the second is a
 *  line rather than a refactor. Mirrors `aios_grid.AUTOMATION_KINDS` (host-whitelisted). */
const AUTOMATION_KINDS: { key: string; label: string; hint: string }[] = [
  {
    key: "instagram_profile",
    label: "Instagram profile",
    hint: "Reads what is anonymously public about the profile in the chosen URL column, and "
      + "writes the result here. Runs from the Automation surface, on demand or on a schedule.",
  },
];

const DEFAULT_MEASURE_WINDOW: WindowSpec = { kind: "ltm" };

/** The head every pane shares: title line, context line, close X. */
function PaneHead({
  title,
  sub,
  onClose,
}: {
  title: string;
  sub?: string;
  onClose: () => void;
}) {
  return (
    <div className="cg-column-head">
      <div>
        <div className="cg-column-title">{title}</div>
        {sub && <div className="cg-column-type">{sub}</div>}
      </div>
      <button
        type="button"
        className="cg-icon-btn"
        onClick={onClose}
        aria-label="Close column menu"
      >
        Γ—
      </button>
    </div>
  );
}

/**
 * Wave-6 item 9c β€” the Scope control, rendered by BOTH create surfaces on the cohort page
 * (one component so the two doors cannot drift). "This cohort table only" is the DEFAULT β€”
 * the owner's ask: a field made while working a cohort belongs to that work unless the user
 * says otherwise.
 */
function ScopeControl({
  value,
  onValue,
}: {
  value: FieldScope;
  onValue: (v: FieldScope) => void;
}) {
  return (
    <label>
      <span>Scope</span>
      {/* β›” wave17 R1 β€” "cohort" scope means *served ONLY on the cohort TABLE*, and that table
          (the retired `#/cohort` surface) no longer exists. A field created with it today would
          be reachable from nowhere. So it is DISABLED for new selection.

          ⚠ It is still RENDERED, and only disabled when it is not the current value. A `<select>`
          whose `value` matches no option renders the FIRST option instead
          ([[cg-condition-builder-items]]) β€” dropping the row outright would silently re-scope
          every existing cohort-scoped field to global on the next save, which is a data change
          nobody asked for wearing a cosmetic edit's clothes. */}
      <select
        className="cg-select cg-scope-select"
        value={value}
        aria-label="Field scope"
        onChange={(event) => onValue(event.target.value as FieldScope)}
      >
        <option value="cohort" disabled={value !== "cohort"}>
          The cohort table only (retired)
        </option>
        <option value="global">All customer tables</option>
      </select>
    </label>
  );
}

/**
 * Wave-5 items 9/11 β€” the extra editors a new field's type may need, shared VERBATIM by the
 * two create surfaces (insert-field and Change-field's "New field" half) so the two doors
 * cannot drift: a FORMULA gets its source editor with live validation and a reference picker;
 * a RATING gets its star count (the contract's 2..10).
 */
/**
 * ⭐⭐ Wave-34 (R13) β€” the AI enrichment draft, as the panel holds it.
 *
 * FLAT, while the wire bag nests `trigger`. That is deliberate: a form is edited one control at a
 * time and a nested draft makes every setter a two-level spread, which is where a patcher drops a
 * sibling key. `extraFor` does the one nesting at the moment of sending.
 */
// W42-T08: the governed semantic hop optionally carried by a Link field.
export interface HopViaBag {
  topic: string;
  source_dim: string;
  target_dim: string;
  target_key: string;
  scope_key: string;
  measure: string;
  filter: FilterNode[];
  filterConj: Conjunction;
  window: string;
}

export interface HopDraft {
  topic: string;
  sourceDim: string;
  targetDim: string;
  targetKey: string;
  measure: string;
  filter: FilterNode[];
  filterConj: Conjunction;
  window: string;
  scopeKey: string;
}

export const HOP_WINDOW_ALL = "all_time";

export const emptyHopDraft = (): HopDraft => ({
  topic: "", sourceDim: "", targetDim: "", targetKey: "", measure: "",
  filter: [], filterConj: "and", window: HOP_WINDOW_ALL, scopeKey: "",
});

interface HopOffer {
  topics: HopTopic[];
  windows: { key: string; label: string }[];
  scopeKey: string;
  draft: HopDraft;
  onDraft: (patch: Partial<HopDraft>) => void;
}

export function hopVia(
  draft: HopDraft | null | undefined,
  scopeKey: string
): HopViaBag | null {
  if (!draft) return null;
  const topic = draft.topic.trim();
  const sourceDim = draft.sourceDim.trim();
  const targetDim = draft.targetDim.trim();
  const targetKey = draft.targetKey.trim();
  const measure = draft.measure.trim();
  const scope = (draft.scopeKey || scopeKey || "").trim();
  if (!topic || !sourceDim || !targetDim || !targetKey || !measure || !scope) return null;
  return {
    topic,
    source_dim: sourceDim,
    target_dim: targetDim,
    target_key: targetKey,
    scope_key: scope,
    measure,
    filter: draft.filter,
    filterConj: draft.filterConj,
    window: draft.window || HOP_WINDOW_ALL,
  };
}

export const hopIncomplete = (draft: HopDraft | null | undefined, scopeKey: string): boolean =>
  !!draft && draft.topic.trim() !== "" && hopVia(draft, scopeKey) === null;

export function hopDraftFrom(link: unknown): HopDraft {
  const via = (link as { via?: Record<string, unknown> } | null | undefined)?.via;
  const draft = emptyHopDraft();
  if (!via || typeof via !== "object") return draft;
  const text = (value: unknown) => (typeof value === "string" ? value : "");
  return {
    topic: text(via.topic),
    sourceDim: text(via.source_dim),
    targetDim: text(via.target_dim),
    targetKey: text(via.target_key),
    measure: text(via.measure),
    filter: Array.isArray(via.filter) ? (via.filter as FilterNode[]) : [],
    filterConj: via.filterConj === "or" ? "or" : "and",
    window: text(via.window) || HOP_WINDOW_ALL,
    scopeKey: text(via.scope_key),
  };
}

interface AiEnrichDraft {
  prompt: string;
  model: string;
  maxTokens: number;
  mode: string;
  cron: string;
  overwrite: string;
}

/** The three moments an enrichment column can run. Mirrors `AI_ENRICH_TRIGGER_MODES`. */
const AI_ENRICH_MODES: ReadonlyArray<{ value: string; label: string }> = [
  { value: "manual", label: "Only when I ask" },
  { value: "on_change", label: "When a referenced column changes" },
  { value: "schedule", label: "On a schedule" },
];

/**
 * What an AUTOMATIC run may replace. β›” There is no "overwrite anything" option and there must
 * not be: a cell somebody typed into is never overwritten by an agent, whatever is chosen here,
 * so "Every row" means every row THE AI WROTE. The labels say that rather than leaving a user to
 * discover it, because a control that quietly means less than it says is worse than a narrower
 * control (`core.user_tables.ai_enrich_human_authored` is the law it is describing).
 */
const AI_ENRICH_OVERWRITE: ReadonlyArray<{ value: string; label: string }> = [
  { value: "blank", label: "Only rows that are still empty" },
  { value: "stale", label: "Empty rows, and AI answers whose inputs have changed" },
  { value: "always", label: "Every row the AI wrote, every run" },
];

function ExtraTypeEditor({
  kind,
  fields,
  formulaText,
  onFormulaText,
  formulaError,
  maxValue,
  onMaxValue,
  codeLanguage,
  onCodeLanguage,
  aiEnrich,
  onAiEnrich,
  idPrefix,
  automationKind = "instagram_profile",
  onAutomationKind,
  automationUrlField = "",
  onAutomationUrlField,
  linkTargets = [],
  linkTable = "",
  onLinkTable,
  linkSingle = false,
  onLinkSingle,
  linkSelectionMode = "manual",
  onLinkSelectionMode,
  linkSelectionFilter = null,
  onLinkSelectionFilter,
  hop = null,
  rollupPreset = null,
  rollupMode = "link",
  onRollupMode,
  rollupSourceOffer = { topics: [], windows: [] },
  rollupSource = { topic: "", measure: "", groupBy: "", on: "", window: "ytd" },
  onRollupSource,
  rollupLink = "",
  onRollupLink,
  rollupField = "",
  onRollupField,
  rollupFn = "sum",
  onRollupFn,
  rollupLimit = 0,
  onRollupLimit,
  rollupSortBy = "",
  onRollupSortBy,
  rollupDistinctBy = "",
  onRollupDistinctBy,
  rollupWhere = [],
  onRollupWhere,
  rollupWhereConj = "and",
  onRollupWhereConj,
  rollupConditions = [],
  onRollupConditions,
  rollupConditionConj = "and",
  onRollupConditionConj,
}: {
  /** ⚠ `CreateKind`, and this pane renders NOTHING for either pseudo-kind. A Metric's editor is
   *  the Number+Period pair and a geocode column's is the Address column pick, both of which sit
   *  in the create pane beside this mount: this editor dispatches on `FieldType`, and widening it
   *  to hold a kind no stored column ever has would put two vocabularies in one switch. */
  kind: CreateKind;
  fields: Field[];
  formulaText: string;
  onFormulaText: (v: string) => void;
  formulaError: string | null;
  maxValue: number;
  onMaxValue: (n: number) => void;
  /** ⭐ Wave-27 item 13 (R13) β€” the code column's language draft. REQUIRED at every call site,
   *  unlike the `automation` drafts below it: this pane RENDERS a <select> for a `code` kind, and
   *  an unwired one would be a control that configures nothing, which is worse than no control
   *  ([[wrong-parent-not-broken-control]]). Every mount can reach the kind, so every mount says
   *  which draft it is editing. */
  codeLanguage: string;
  onCodeLanguage: (v: string) => void;
  /** ⭐⭐ Wave-34 (R13) β€” the AI enrichment draft. REQUIRED for `codeLanguage`'s exact reason and
   *  one step stronger: this pane renders the ONLY control that can make an `ai_enrich` column
   *  creatable at all, so an unwired mount would render a prompt box that saves nothing and a
   *  Create button that `canCreate` then blocks forever with no visible cause. */
  aiEnrich: AiEnrichDraft;
  onAiEnrich: (patch: Partial<AiEnrichDraft>) => void;
  idPrefix: string;
  /** C5-AUTOFIELD β€” the automation column's config drafts. Optional so the call sites that
   *  cannot reach an automation type (the Change-field "new field" form) need no change. */
  automationKind?: string;
  onAutomationKind?: (v: string) => void;
  automationUrlField?: string;
  onAutomationUrlField?: (v: string) => void;
  /** ⭐ 2026-08-07 β€” the relational drafts. Optional for the same reason the automation ones
   *  are: the Change-field "new field" form reaches these kinds too, and a call site that does
   *  not offer them should need no change. */
  linkTargets?: LinkTarget[];
  linkTable?: string;
  onLinkTable?: (v: string) => void;
  linkSingle?: boolean;
  onLinkSingle?: (v: boolean) => void;
  linkSelectionMode?: "manual" | "automatic";
  onLinkSelectionMode?: (v: "manual" | "automatic") => void;
  linkSelectionFilter?: FilterTree | null;
  onLinkSelectionFilter?: (v: FilterTree | null) => void;
  hop?: HopOffer | null;
  /** Count/Lookup presets reopen in their reduced editor only when the stored bag is exact. */
  rollupPreset?: RollupPreset | null;
  /** ⭐ 2026-08-09 β€” which KIND of rollup is being built. `"link"` folds workspace rows;
   *  `"source"` reads through to a governed Odoo topic without copying a row into the store. */
  rollupMode?: "link" | "source";
  onRollupMode?: (v: "link" | "source") => void;
  rollupSourceOffer?: RollupSourceOffer;
  rollupSource?: RollupSource;
  onRollupSource?: (v: RollupSource) => void;
  rollupLink?: string;
  onRollupLink?: (v: string) => void;
  rollupField?: string;
  onRollupField?: (v: string) => void;
  rollupFn?: RollupFn;
  onRollupFn?: (v: RollupFn) => void;
  rollupLimit?: number;
  onRollupLimit?: (v: number) => void;
  rollupSortBy?: string;
  onRollupSortBy?: (v: string) => void;
  rollupDistinctBy?: string;
  onRollupDistinctBy?: (v: string) => void;
  /** ⭐⭐ 2026-08-09 β€” the PRE-filter (`rollup.where`): which linked records the window may
   *  spend its slots on. Separate from `rollupConditions`, which runs after it. */
  rollupWhere?: RollupCondition[];
  onRollupWhere?: (v: RollupCondition[]) => void;
  rollupWhereConj?: "and" | "or";
  onRollupWhereConj?: (v: "and" | "or") => void;
  rollupConditions?: RollupCondition[];
  onRollupConditions?: (v: RollupCondition[]) => void;
  rollupConditionConj?: "and" | "or";
  onRollupConditionConj?: (v: "and" | "or") => void;
}) {
  if (kind === "formula") {
    // 2026-07-31 (owner item 2): other FORMULA fields are referencable now β€” evaluation is
    // topological and a cycle is refused at validation, so the old exclusion is gone.
    const referencable = offerableFields(fields).filter((f) => f.key !== "__proto__");
    return (
      <>
        {/* ⭐⭐ W50-T06 (owner instruction 5) β€” *"wider when configuring (it expands) and taller
            by default; it behaves like Excel"*. The three-row box with no guidance is gone: the
            editor opens at six rows, grows with what is typed, autocompletes from the C2
            catalogue and shows each function's form while its arguments are being filled in.
            ⚠ The MENU's own 560px width is a `:has(.cg-formula-editor)` rule in
            `styles/wave50/grid.css`, not a class threaded through six `AnchoredOverlay` call
            sites β€” the pane is the thing that knows it needs the room. */}
        <label>
          <span>Formula</span>
          <FormulaEditor
            value={formulaText}
            onChange={onFormulaText}
            fields={referencable.map((f) => ({
              key: f.key, label: f.label, type: f.type,
            }))}
            placeholder={"MAX(0, {revenue_ly} - {revenue_ytd})"}
            ariaLabel="Formula"
          />
        </label>
        <div className="cg-cond-line cg-formula-insert">
          <FieldSelectButton
            ariaLabel="Insert a field reference"
            placeholder="Insert a field reference…"
            // An ACTION picker, not a value one: it never holds a selection, so it stays in
            // the placeholder state and `keepOpen` lets a formula take three references
            // without three trips through the button.
            value={undefined}
            keepOpen
            onChange={(key) =>
              onFormulaText((formulaText + " {" + key + "}").trimStart())
            }
            fields={referencable.map((f) => ({
              key: f.key, label: f.label, type: f.type,
            }))}
          />
        </div>
        {/*
          ⭐ 2026-08-10 β€” THE BLANK TRAP, said before it is hit rather than after.

          `{a} - {b}` is BLANK when `b` is blank, because arithmetic propagates a missing
          operand β€” so the trimmed-average chain the owner built ("views minus the outliers")
          blanks its whole column on exactly the profiles that have NO outlier to subtract,
          which is the majority of them. That reads as "the formula is broken" and the column
          it blanks is the one it was built for.

          The idiom is Excel's own: the AGGREGATE functions skip blanks, so `SUM({b}, 0)` is
          "b, or nothing at all". Shown ALWAYS, never folded into the catalogue's per-function
          documentation β€” a signature is reference, and this is the one sentence that changes
          what somebody types. Kept to one line (DESIGN.md Β§4).
          ⚠ W50-T06 retired the hard-coded list this used to name (and the `showFormulaHelp`
          prop that suppressed it); the rule above outlived both and is unchanged by either.
        */}
        <div className="cg-field-hint cg-formula-blank-hint">
          A blank in any part blanks the whole result. Wrap an optional column as{" "}
          {"SUM({field}, 0)"} to read it as zero.
        </div>
        {/* β›”β›” THE HARD-CODED FUNCTION LIST THAT USED TO SIT HERE IS DELETED, AND ITS DELETION
            IS THE POINT OF THE TICKET, NOT A TIDY-UP. It named thirty functions in prose; the
            runtime carries a hundred and one, so the sentence was already wrong, and every
            function added after it was written made it wronger with nothing able to notice.
            R5 replaced it with a CATALOGUE, and the editor above reads that catalogue: the
            names arrive as a live list and each one documents itself with its own signature and
            description. DESIGN.md Β§4 "never over-explain" then decides the rest β€” a paragraph
            repeating what the signature popover already says is duplication with a second,
            staler authority. `showFormulaHelp` went with it: the prop existed only to suppress
            this block in the edit pane. */}
        {formulaText.trim() !== "" && formulaError ? (
          <div className="cg-field-hint cg-formula-error">{formulaError}</div>
        ) : null}
      </>
    );
  }
  if (kind === "rating") {
    return (
      <label>
        <span>Number of stars</span>
        <input
          id={`${idPrefix}-rating-max`}
          className="cg-input cg-rating-max"
          type="number"
          min={2}
          max={10}
          value={maxValue}
          aria-label="Number of stars"
          onChange={(event) => {
            const n = Math.round(Number(event.target.value));
            onMaxValue(Number.isFinite(n) ? Math.max(2, Math.min(10, n)) : 5);
          }}
        />
      </label>
    );
  }
  if (kind === "code") {
    // ⭐ Wave-27 item 13 (R13) β€” the create form's only code-specific question. The hint is not
    // decoration: "code" in a product that also runs automations invites the assumption that
    // picking a language makes the snippet executable, and R13 is explicit that there is no
    // execution engine. Saying so at the moment of choosing is cheaper than a support answer.
    return (
      <label>
        <span>Language</span>
        <select
          id={`${idPrefix}-code-language`}
          className="cg-select"
          value={codeLanguage}
          aria-label="Code language"
          onChange={(event) => onCodeLanguage(event.target.value)}
        >
          {CODE_LANGUAGES.map((lang) => (
            <option key={lang} value={lang}>
              {CODE_LANGUAGE_LABELS[lang]}
            </option>
          ))}
        </select>
        <span className="cg-field-hint">
          Chooses how the snippet is coloured. It is never run.
        </span>
      </label>
    );
  }
  if (kind === "ai_enrich") {
    // ⭐⭐ WAVE-34 (owner ruling R13) β€” *"a prompt per row that populates text. Detailed
    // configuration in the field's own config, including a token-usage limit."*
    //
    // β›” THE PROMPT IS FIRST AND IT IS THE ONLY REQUIRED CONTROL, because it is the only one
    // without which the column can never hold anything (`_clean_field` refuses the field). The
    // other four all have a working default, so a user who types one sentence and presses Create
    // gets a column that runs.
    // ⚠ Every control below is an EXISTING one (`cg-input`, `cg-select`, `cg-field-hint`,
    // `<label><span>…`): `index.css` belongs to another lane this wave, so this panel is built
    // from the vocabulary already in the file rather than from a rule I cannot add.
    const refs = Array.from(
      new Set((aiEnrich.prompt.match(/\{([a-zA-Z0-9_]{1,60})\}/g) ?? []).map((m) => m.slice(1, -1)))
    );
    const known = new Set(fields.map((f) => f.key));
    const unknown = refs.filter((r) => !known.has(r));
    return (
      <>
        <label>
          <span>Prompt</span>
          <textarea
            id={`${idPrefix}-ai-prompt`}
            className="cg-input"
            rows={3}
            value={aiEnrich.prompt}
            placeholder="Summarise what {name} sells, in one line."
            aria-label="Enrichment prompt"
            onChange={(event) => onAiEnrich({ prompt: event.target.value })}
          />
          {/* β›” THE UNRESOLVED-TOKEN WARNING IS NOT DECORATION. A `{token}` naming no column is
              sent verbatim to the model, which then answers a different question on every row and
              returns text that looks exactly like a correct answer. The server reports it per row
              at run time; saying it here costs one run nobody has paid for yet. */}
          {unknown.length > 0 ? (
            <span className="cg-field-hint">
              {unknown.map((u) => `{${u}}`).join(", ")} is not a column on this database. Wrap a
              column key in braces to put its value into the prompt.
            </span>
          ) : (
            <span className="cg-field-hint">
              Put a column key in braces to use its value, the way a formula does. Each row gets
              its own answer.
            </span>
          )}
        </label>
        <label>
          <span>When it runs</span>
          <select
            id={`${idPrefix}-ai-mode`}
            className="cg-select"
            value={aiEnrich.mode}
            aria-label="When the enrichment runs"
            onChange={(event) => onAiEnrich({ mode: event.target.value })}
          >
            {AI_ENRICH_MODES.map((m) => (
              <option key={m.value} value={m.value}>
                {m.label}
              </option>
            ))}
          </select>
        </label>
        {/* A cadence box only where a cadence is read. A schedule stored under "Only when I ask"
            is a setting the user can see and nothing will ever act on, which is the shape D-246
            wears on the Odoo sync, so the server drops it and this never offers it. */}
        {aiEnrich.mode === "schedule" ? (
          <label>
            <span>Schedule</span>
            <input
              id={`${idPrefix}-ai-cron`}
              className="cg-input"
              value={aiEnrich.cron}
              placeholder="0 6 * * *"
              aria-label="Enrichment schedule"
              onChange={(event) => onAiEnrich({ cron: event.target.value })}
            />
            <span className="cg-field-hint">Minute, hour, day, month, weekday.</span>
          </label>
        ) : null}
        <label>
          <span>Which rows</span>
          <select
            id={`${idPrefix}-ai-overwrite`}
            className="cg-select"
            value={aiEnrich.overwrite}
            aria-label="Which rows a run may fill"
            onChange={(event) => onAiEnrich({ overwrite: event.target.value })}
          >
            {AI_ENRICH_OVERWRITE.map((o) => (
              <option key={o.value} value={o.value}>
                {o.label}
              </option>
            ))}
          </select>
          <span className="cg-field-hint">
            A cell you have typed into is never overwritten by a run, whichever of these is chosen.
          </span>
        </label>
        <label>
          <span>Token limit per row</span>
          <input
            id={`${idPrefix}-ai-tokens`}
            type="number"
            className="cg-input"
            min={16}
            max={4000}
            value={aiEnrich.maxTokens}
            aria-label="Token limit per row"
            onChange={(event) => onAiEnrich({ maxTokens: Number(event.target.value) || 300 })}
          />
          {/* R6's standing rule, at the control rather than in a support answer: a run that hits
              its ceiling STOPS and says how far it got, so this number is the whole budget's
              basis and not a soft target. */}
          <span className="cg-field-hint">
            Also sets the whole run's budget. A run that reaches it stops and reports how many
            rows it filled.
          </span>
        </label>
        <label>
          <span>Model</span>
          <input
            id={`${idPrefix}-ai-model`}
            className="cg-input"
            value={aiEnrich.model}
            placeholder="Leave empty for the default"
            aria-label="Enrichment model"
            onChange={(event) => onAiEnrich({ model: event.target.value })}
          />
          <span className="cg-field-hint">
            Empty uses the cheapest provider configured on this deployment.
          </span>
        </label>
      </>
    );
  }
  if (kind === "created_time") {
    return (
      <div className="cg-field-hint">
        Read-only. When the record was created in the source system.
      </div>
    );
  }
  if (kind === "created_by" || kind === "last_modified_time" || kind === "last_modified_by") {
    return <div className="cg-field-hint">Read-only. {TYPE_DESCRIPTIONS[kind]}</div>;
  }
  if (kind === "automation") {
    // C5-AUTOFIELD β€” the field's GEAR. An automation column has no value the user types, so
    // this pane configures what a RUN does instead: which job, and which column carries the
    // thing it reads. The schedule and the Run-now button are NOT here β€” they belong to the
    // automation itself, on the Automation surface, because one job can fill a column across
    // many records and its cadence is a property of the job, not of the column.
    const urlish = offerableFields(fields).filter(
      (f) => f.type === "url" || f.type === "text"
    );
    const chosen = AUTOMATION_KINDS.find((k) => k.key === automationKind)
      ?? AUTOMATION_KINDS[0];
    return (
      <>
        <label>
          <span>What it reads</span>
          <select
            id={`${idPrefix}-automation-kind`}
            className="cg-input"
            value={automationKind}
            aria-label="Automation kind"
            onChange={(event) => onAutomationKind?.(event.target.value)}
          >
            {AUTOMATION_KINDS.map((k) => (
              <option key={k.key} value={k.key}>
                {k.label}
              </option>
            ))}
          </select>
        </label>
        <label>
          <span>URL column</span>
          <select
            id={`${idPrefix}-automation-url`}
            className="cg-input"
            value={automationUrlField}
            aria-label="URL column"
            onChange={(event) => onAutomationUrlField?.(event.target.value)}
          >
            <option value="">Choose a column…</option>
            {urlish.map((f) => (
              <option key={f.key} value={f.key}>
                {f.label}
              </option>
            ))}
          </select>
        </label>
        <div className="cg-field-hint">{chosen.hint}</div>
        <div className="cg-field-hint">
          Cells here are written by the run and cannot be typed into. A value you entered
          would be replaced by the next run without saying so.
        </div>
        {/* A v1 LIMIT, said out loud rather than discovered. The column can be created on any
            table, but an Instagram automation only accepts a blank database as its target
            (`clean_config('field_instagram')`), because the run writes rows and an Odoo-sourced
            table is read-only at the source. Without this line a user creates the column on
            Customer, goes to Automation, and finds no way to point anything at it. */}
        <div className="cg-field-hint">
          Runs target a blank database. On a connector-backed table this column can be created
          but no automation can write to it yet.
        </div>
      </>
    );
  }
  if (kind === "link") {
    // ⭐ 2026-08-07 β€” Airtable's "Link to another record", and the whole editor is ONE question:
    // which database. The relation itself is then the cell (a set of linked rows).
    const hopTopic = hop?.topics.find((topic) => topic.key === hop.draft.topic);
    const hopTargetFields = linkTargets.find((target) => target.key === linkTable)?.fields
      .filter((candidate) => candidate.type !== "link" && candidate.type !== "rollup") ?? [];
    const hopWindow = hop?.draft.window || HOP_WINDOW_ALL;
    const hopWindowOffered = !!hop?.windows.some((candidate) => candidate.key === hopWindow);
    const selectionFields = linkTargets.find((target) => target.key === linkTable)?.fields ?? [];
    const selectionIssue = linkSelectionFilterIssue(linkSelectionFilter, selectionFields);
    return (
      <>
        <label>
          <span>Database</span>
          <select
            id={`${idPrefix}-link-table`}
            className="cg-input"
            value={linkTable}
            aria-label="Database to link to"
            onChange={(event) => {
              onLinkTable?.(event.target.value);
              if (linkSelectionFilter) onLinkSelectionFilter?.({ conj: "and", nodes: [] });
              hop?.onDraft({ targetKey: "" });
            }}
          >
            <option value="">Choose a database…</option>
            {linkTargets.map((t) => (
              <option key={t.key} value={t.key}>{t.label}</option>
            ))}
          </select>
        </label>
        {linkTargets.length === 0 ? (
          <div className="cg-field-hint">
            There is no other database to link to yet. Create one first, then come back.
          </div>
        ) : null}
        <label>
          <span>How links are chosen</span>
          <select
            id={`${idPrefix}-link-selection-mode`}
            className="cg-input"
            value={linkSelectionMode}
            aria-label="How linked records are selected"
            disabled={!!hop?.draft.topic}
            onPointerDown={(event) => event.stopPropagation()}
            onChange={(event) => onLinkSelectionMode?.(
              event.target.value === "automatic" ? "automatic" : "manual"
            )}
          >
            <option value="manual">Nothing, I will pick the records myself</option>
            <option value="automatic">Set links automatically</option>
          </select>
        </label>
        {hop ? (
          <div className="cg-hop">
            <label className="cg-hop-question">
              <span>Through</span>
              <select
                id={`${idPrefix}-hop-topic`}
                className="cg-input"
                value={hop.draft.topic}
                aria-label="Data to travel through"
                onChange={(event) => {
                  const topic = event.target.value;
                  onLinkSelectionMode?.(topic ? "automatic" : "manual");
                  hop.onDraft({
                    topic,
                    sourceDim: "",
                    targetDim: "",
                    measure: "",
                    filter: [],
                    filterConj: "and",
                  });
                }}
              >
                <option value="">Nothing, link the records directly</option>
                {hop.topics.map((topic) => (
                  <option key={topic.key} value={topic.key}>{topic.label}</option>
                ))}
              </select>
            </label>
            {hop.topics.length === 0 ? (
              <div className="cg-field-hint">No governed data is available to travel through.</div>
            ) : null}
            {hopTopic ? (
              <div className="cg-hop-body">
                <label>
                  <span>Matched from</span>
                  <select
                    id={`${idPrefix}-hop-source-dim`}
                    className="cg-input"
                    value={hop.draft.sourceDim}
                    aria-label="What names a row of this database"
                    onChange={(event) => hop.onDraft({ sourceDim: event.target.value })}
                  >
                    <option value="">Choose the starting match</option>
                    {hopTopic.dims.map((dim) => (
                      <option key={dim.key} value={dim.key}>{dim.label}</option>
                    ))}
                  </select>
                </label>
                <label>
                  <span>Matched to</span>
                  <select
                    id={`${idPrefix}-hop-target-dim`}
                    className="cg-input"
                    value={hop.draft.targetDim}
                    aria-label="What names a row of the other database"
                    onChange={(event) => hop.onDraft({ targetDim: event.target.value })}
                  >
                    <option value="">Choose the destination match</option>
                    {hopTopic.dims.map((dim) => (
                      <option key={dim.key} value={dim.key}>{dim.label}</option>
                    ))}
                  </select>
                </label>
                <label>
                  <span>Column over there</span>
                  <select
                    id={`${idPrefix}-hop-target-key`}
                    className="cg-input"
                    value={hop.draft.targetKey}
                    aria-label="Column in the other database holding that value"
                    onChange={(event) => hop.onDraft({ targetKey: event.target.value })}
                  >
                    <option value="">Choose the destination column</option>
                    {hopTargetFields.map((candidate) => (
                      <option key={candidate.key} value={candidate.key}>{candidate.label}</option>
                    ))}
                  </select>
                </label>
                <label>
                  <span>Measure</span>
                  <select
                    id={`${idPrefix}-hop-measure`}
                    className="cg-input"
                    value={hop.draft.measure}
                    aria-label="Measure"
                    onChange={(event) => hop.onDraft({ measure: event.target.value })}
                  >
                    <option value="">Choose a measure</option>
                    {hopTopic.measures.map((measure) => (
                      <option key={measure.key} value={measure.key}>{measure.label}</option>
                    ))}
                  </select>
                </label>
                {hop.windows.length > 0 ? (
                  <label>
                    <span>Over</span>
                    <select
                      id={`${idPrefix}-hop-window`}
                      className="cg-input"
                      value={hopWindow}
                      aria-label="Date window"
                      onChange={(event) => hop.onDraft({ window: event.target.value })}
                    >
                      {hopWindowOffered ? null : <option value={hopWindow}>{hopWindow}</option>}
                      {hop.windows.map((candidate) => (
                        <option key={candidate.key} value={candidate.key}>{candidate.label}</option>
                      ))}
                    </select>
                  </label>
                ) : null}
                <div className="cg-hop-filter">
                  <span className="cg-type-title">Keep only</span>
                  <FilterBuilderPanel
                    fields={hopTopic.dims}
                    database={hopTopic.key}
                    filters={{ conj: hop.draft.filterConj, nodes: hop.draft.filter }}
                    onChange={(next) => hop.onDraft({
                      filter: filterTreeNodes(next),
                      filterConj: filterTreeConj(next),
                    })}
                  />
                </div>
                {(hop.draft.scopeKey || hop.scopeKey).trim() === "" ? (
                  <div className="cg-field-hint">
                    This database has no usable starting scope, so the hop cannot be saved.
                  </div>
                ) : null}
              </div>
            ) : null}
          </div>
        ) : null}
        <label className="cg-check-row" style={{ flexDirection: "row", alignItems: "center" }}>
          <input
            id={`${idPrefix}-link-selection-filter`}
            type="checkbox"
            checked={linkSelectionFilter !== null}
            disabled={!linkTable}
            onPointerDown={(event) => event.stopPropagation()}
            onChange={(event) => onLinkSelectionFilter?.(
              event.target.checked ? { conj: "and", nodes: [] } : null
            )}
          />
          <span>Limit record selection to records matching a condition</span>
        </label>
        {linkSelectionFilter ? (
          <div className="cg-hop-filter" data-link-selection-filter>
            {/* Keep the shared builder readable in either pane without adding a scroll container. */}
            <style>{`
              .cg-column-menu:has([data-link-selection-filter]) {
                width: min(780px, calc(100vw - 16px));
              }
              .cg-column-menu [data-link-selection-filter] .cg-cond-line {
                flex-wrap: wrap;
              }
              .cg-column-menu [data-link-selection-filter] :is(.cg-cond-row, .cg-cond-group) {
                flex: 1 1 480px;
                max-width: 100%;
              }
              .cg-column-menu [data-link-selection-filter] :is(
                .cg-cond-row, .cg-cond-rhs, .cg-cond-between, .cg-cond-window,
                .cg-cond-anchor, .cg-builder-add, .cg-builder-footer
              ) {
                flex-wrap: wrap;
              }
              .cg-column-menu [data-link-selection-filter] :is(.cg-input, .cg-select) {
                width: auto;
                max-width: 100%;
              }
              .cg-column-menu [data-link-selection-filter] .cg-cond-row > :is(
                .cg-cond-val, .cg-cond-cohorts, .cg-cond-rhs
              ) {
                flex: 1 1 160px;
              }
              .cg-column-menu [data-link-selection-filter] :is(.cg-cond-between, .cg-cond-anchor) {
                flex: 1 1 320px;
                min-width: 0;
                display: flex;
                align-items: center;
                gap: 6px;
              }
              .cg-column-menu [data-link-selection-filter] :is(
                .cg-cond-between, .cg-cond-anchor
              ) > .cg-cond-val {
                flex: 1 1 144px;
              }
              .cg-column-menu [data-link-selection-filter] .cg-cond-anchor-mode {
                flex: 0 0 176px;
              }
              .cg-column-menu [data-link-selection-filter] :is(
                .cg-cond-rhs, .cg-cond-between, .cg-cond-window, .cg-cond-anchor
              ) {
                max-width: 100%;
              }
            `}</style>
            <FilterBuilderPanel
              fields={selectionFields}
              database={linkTable}
              filters={linkSelectionFilter}
              onChange={(next) => onLinkSelectionFilter?.(next)}
            />
            {selectionIssue ? <div className="cg-field-hint" role="status">{selectionIssue}</div> : null}
          </div>
        ) : null}
        <label className="cg-cond-line" style={{ flexDirection: "row", alignItems: "center" }}>
          <input
            type="checkbox"
            checked={linkSingle}
            aria-label="Allow only one linked record"
            onPointerDown={(event) => event.stopPropagation()}
            onChange={(event) => onLinkSingle?.(event.target.checked)}
          />
          <span>Allow only one linked record</span>
        </label>
        {hop?.draft.topic ? null : (
          <div className="cg-field-hint">
            A cell here holds the records you pick. Add a Rollup column afterwards to summarise a
            column of those records: an average, a total, a count.
          </div>
        )}
      </>
    );
  }
  if (kind === "rollup") {
    // ⭐ 2026-08-07 β€” Airtable's rollup, plus the LAST-N window Airtable does not have.
    //
    // The editor reads as the sentence the column answers, in order: through WHICH relation, over
    // WHICH column, folded HOW, and across WHICH records. That last control is the owner's
    // headline ("average Views over last N posts") and Airtable cannot express it β€” its rollup
    // conditions filter by predicate, never by rank.
    const linkFields = offerableFields(fields).filter((f) => f.type === "link");
    const chosenLink = linkFields.find((f) => f.key === rollupLink);
    const target = linkTargets.find((t) => t.key === chosenLink?.link?.table);
    const targetFields = offerableFields(target?.fields ?? []);
    // β›” COUNTALL IS THE ONE FUNCTION WITH NO SOURCE COLUMN β€” it counts linked RECORDS, so the
    // field picker would be a control that configures nothing. Airtable's rule, and ours.
    const needsField = rollupFn !== "countall";
    // ⭐⭐ 2026-08-09 β€” THE SECOND KIND OF ROLLUP. Everything above summarises rows that live in
    // this workspace; a SOURCE rollup summarises rows that were never copied here β€” one grouped
    // SQL query over the governed Odoo model answers every parent row at once. That is the only
    // way a column can total 256,810 order lines, which is 4x what a database here may hold.
    const sourceTopics = rollupSourceOffer.topics;
    const topic = sourceTopics.find((t) => t.key === rollupSource.topic);
    const dim = topic?.dims.find((d) => d.key === rollupSource.groupBy);
    const setSource = (patch: Partial<RollupSource>) =>
      onRollupSource?.({ ...rollupSource, ...patch });
    // ⚠ A join column must hold a SCALAR the group key can equal. Link and rollup columns hold a
    // comma-joined id list and a computed value respectively, so neither can ever match.
    const joinable = offerableFields(fields).filter(
      (f) => f.type !== "link" && f.type !== "rollup" && f.key !== "__proto__"
    );
    const sourceEditor = (
      <>
        <label>
          <span>Odoo data</span>
          <select
            id={`${idPrefix}-rollup-topic`}
            className="cg-input"
            value={rollupSource.topic}
            aria-label="Odoo topic"
            onChange={(event) =>
              // β›” CLEAR THE MEASURE AND THE DIM WITH THE TOPIC. Both are keys OF the topic, so
              // carrying them across a topic change leaves a bag naming a measure the new topic
              // does not have β€” which the save door refuses, on a form that looks complete.
              setSource({ topic: event.target.value, measure: "", groupBy: "" })
            }
          >
            <option value="">Choose what to summarise…</option>
            {sourceTopics.map((t) => (
              <option key={t.key} value={t.key}>{t.label}</option>
            ))}
          </select>
        </label>
        {sourceTopics.length === 0 ? (
          <div className="cg-field-hint">
            No live data sources are available for this workspace. A source rollup reads a
            connected system; this one has none connected yet.
          </div>
        ) : null}
        {topic ? (
          <>
            <label>
              <span>Measure</span>
              <select
                id={`${idPrefix}-rollup-measure`}
                className="cg-input"
                value={rollupSource.measure}
                aria-label="Measure"
                onChange={(event) => setSource({ measure: event.target.value })}
              >
                <option value="">Choose a measure…</option>
                {topic.measures.map((m) => (
                  <option key={m.key} value={m.key}>{m.label}</option>
                ))}
              </select>
            </label>
            <label>
              <span>One row per</span>
              <select
                id={`${idPrefix}-rollup-dim`}
                className="cg-input"
                value={rollupSource.groupBy}
                aria-label="Group by"
                onChange={(event) => setSource({ groupBy: event.target.value })}
              >
                <option value="">Choose a grouping…</option>
                {topic.dims.map((d) => (
                  <option key={d.key} value={d.key}>{d.label}</option>
                ))}
              </select>
            </label>
            <label>
              <span>Matched on</span>
              <select
                id={`${idPrefix}-rollup-on`}
                className="cg-input"
                value={rollupSource.on}
                aria-label="Column to match on"
                onChange={(event) => setSource({ on: event.target.value })}
              >
                <option value="">Choose this database's column…</option>
                {joinable.map((f) => (
                  <option key={f.key} value={f.key}>{f.label}</option>
                ))}
              </select>
            </label>
            {/* ⚠ THE JOIN IS THE ONE THING THE SERVER CANNOT CHECK. It knows the measure exists
                and the dim is groupable; it cannot know that THIS column holds the same kind of
                value the grouping keys by. A wrong match is not an error β€” it is a column of
                blanks. So the control says which kind of value it needs. */}
            {dim ? (
              <div className="cg-field-hint">
                {dim.keyedBy === "id"
                  ? `Pick the column holding the Odoo ID for ${dim.label.toLowerCase()}. Matching on a name instead leaves every cell blank.`
                  : `Pick the column holding the ${dim.label.toLowerCase()} value itself. This grouping keys by its own value, not by an ID.`}
              </div>
            ) : null}
            <label>
              <span>Over</span>
              <select
                id={`${idPrefix}-rollup-window`}
                className="cg-input"
                value={rollupSource.window || "all_time"}
                aria-label="Date window"
                onChange={(event) => setSource({ window: event.target.value })}
              >
                {rollupSourceOffer.windows.map((w) => (
                  <option key={w.key} value={w.key}>{w.label}</option>
                ))}
              </select>
            </label>
            <div className="cg-field-hint">
              Recomputed against live data: the window moves with today's date rather than
              freezing the dates it was created on.
            </div>
          </>
        ) : null}
      </>
    );
    const linkEditor = (
      <>
        {rollupPreset ? (
          <div className="cg-field-hint">{TYPE_DESCRIPTIONS[rollupPreset]}</div>
        ) : null}
        <label>
          <span>Through</span>
          <select
            id={`${idPrefix}-rollup-link`}
            className="cg-input"
            value={rollupLink}
            aria-label="Link column"
            onChange={(event) => onRollupLink?.(event.target.value)}
          >
            <option value="">Choose a link column…</option>
            {linkFields.map((f) => (
              <option key={f.key} value={f.key}>{f.label}</option>
            ))}
          </select>
        </label>
        {linkFields.length === 0 ? (
          <div className="cg-field-hint">
            This database has no link column yet. A rollup summarises records reached through a
            link, so add one of those first.
          </div>
        ) : null}
        {rollupPreset ? null : (
        <label>
          <span>Fold</span>
          <select
            id={`${idPrefix}-rollup-fn`}
            className="cg-input"
            value={rollupFn}
            aria-label="Rollup function"
            onChange={(event) => onRollupFn?.(event.target.value as RollupFn)}
          >
            {ROLLUP_FNS.map((fn) => (
              <option key={fn} value={fn}>{ROLLUP_FN_LABELS[fn]}</option>
            ))}
          </select>
        </label>
        )}
        {needsField ? (
          <label>
            <span>Column</span>
            <select
              id={`${idPrefix}-rollup-field`}
              className="cg-input"
              value={rollupField}
              aria-label="Column to roll up"
              onChange={(event) => onRollupField?.(event.target.value)}
            >
              <option value="">Choose a column…</option>
              {targetFields.map((f) => (
                <option key={f.key} value={f.key}>{f.label}</option>
              ))}
            </select>
          </label>
        ) : null}
        {/*
          ⭐⭐ 2026-08-09 Β· D-99 β€” THE STATE THE OWNER'S REPORT DESCRIBES, SAID OUT LOUD.
          Owner: *"if we want to use Rollup field to apply to the related database, it doesn't
          work. Because the linked Field can't be selected yet."*

          β›” WHAT IS ACTUALLY REACHABLE HERE, measured rather than guessed. The `Through` picker
          offers EVERY link column β€” `linkFields` filters on `f.type === "link"` and excludes
          nothing preset, derived or `automation:`-tagged, so the scouted hypothesis ("the picker
          omits preset links") is refuted at source. What CAN happen is one step later: the
          target is resolved out of `linkTargets`, which is `GET /tables` filtered by
          `user_tables.may_open` (creator, admin, or an explicit share). An automation-OWNED child
          dataset is stamped with a machine owner, so for a user who is neither its creator nor an
          admin it is simply ABSENT from that list β€” and then `targetFields` is `[]`, this Column
          picker holds nothing but its placeholder, and `Add condition` below is disabled.

          ⚠ AND UNTIL NOW IT SAID NOTHING. An empty picker beside a dead button reads as "this
          feature is broken"; it is in fact a permission fact about ONE database, and the fix for
          it is a share, not a bug report. This is the absent-vs-empty third state the automation
          panel already distinguishes ("No view list was offered for that database") β€” the same
          discipline, applied to the surface that actually got reported.
          β›” IT NAMES THE TABLE RATHER THAN APOLOGISING. `chosenLink.link.table` is the key the
          bag points at, and printing it is what turns "it doesn't work" into a thing to go and
          grant.
        */}
        {chosenLink && !target ? (
          <div className="cg-field-hint">
            This link points at <b>{chosenLink.link?.table}</b>, which is not among the databases
            you can open, so its columns cannot be listed here and the conditions below stay
            unavailable. Ask an admin to share that database with you, then reopen this editor.
          </div>
        ) : null}
        {/*
          ⭐⭐ 2026-08-09 (owner) β€” THE PRE-FILTER, ABOVE THE WINDOW, AND THE SCREEN ORDER IS THE
          ORDER OF OPERATIONS. Owner: *"instead of last 12 posts, we also want to make it so its
          last N record, where the record's Status is video."*

          Everything below this block narrows a set that this block has already chosen:
          include β†’ order β†’ how many β†’ deduplicate β†’ then keep only. Reading top to bottom is
          reading what the server does, in sequence. The post-filter list used to sit HERE, above
          the window it runs after, which is the one arrangement that teaches the wrong model.
        */}
        {rollupPreset ? null : (
        <>
        <RollupConditionList
          idPrefix={`${idPrefix}-rollup-where`}
          title="Include records"
          hint={"Applied BEFORE the window below, so β€œlast 10” counts only records that "
            + "match. View filters never change a Rollup’s result."}
          conditions={rollupWhere}
          onConditions={(v) => onRollupWhere?.(v)}
          conj={rollupWhereConj}
          onConj={(v) => onRollupWhereConj?.(v)}
          targetFields={targetFields}
          allowRef={false}
        />
        <label>
          <span>Across</span>
          <select
            id={`${idPrefix}-rollup-sort`}
            className="cg-input"
            value={rollupSortBy}
            aria-label="Which records to include"
            onChange={(event) => onRollupSortBy?.(event.target.value)}
          >
            <option value="">Every linked record</option>
            {targetFields.map((f) => (
              <option key={f.key} value={f.key}>Most recent by {f.label}</option>
            ))}
          </select>
        </label>
        {rollupSortBy ? (
          <label>
            <span>How many</span>
            <input
              type="number"
              className="cg-input"
              min={1}
              value={rollupLimit || 1}
              aria-label="How many records"
              onChange={(event) =>
                onRollupLimit?.(Math.max(1, Number(event.target.value) || 1))
              }
            />
          </label>
        ) : null}
        <label>
          <span>Deduplicate by</span>
          <select
            id={`${idPrefix}-rollup-distinct`}
            className="cg-input"
            value={rollupDistinctBy}
            aria-label="Deduplicate linked records by"
            onChange={(event) => onRollupDistinctBy?.(event.target.value)}
          >
            <option value="">Keep every linked row</option>
            {targetFields.map((f) => (
              <option key={f.key} value={f.key}>One row per {f.label}</option>
            ))}
          </select>
        </label>
        {/* β›” THE RULE STATED AT THE CONTROL, because the server refuses the pair and a refusal
            the user meets after pressing Create is a refusal they had no way to avoid. "The
            last N" with no declared order is not a measurement β€” it is whichever N rows happen
            to sit first in the store. */}
        <div className="cg-field-hint">
          {rollupSortBy
            ? `The ${rollupLimit || 1} most recent linked records, newest first.`
            : "Every linked record. Choose an order above to summarise just the most recent few."}
        </div>
        {rollupDistinctBy ? (
          <div className="cg-field-hint">
            Duplicate linked rows with the same identity count once; the newest row wins when an
            order is selected.
          </div>
        ) : null}
        {/*
          ⭐⭐ WAVE 28 Β· C1 β€” THE POST-FILTER, BELOW THE WINDOW, WHICH IS WHERE IT ALWAYS RAN.
          Only its POSITION on screen moved (2026-08-09), and the move is the point: this list
          selects among the records the window above already kept, so a threshold measured "over
          this set" is measured over exactly those. That is why the Οƒ operators live here and are
          refused in the pre-filter β€” before the window there is no set for a mean to be about.

          ⚠ THE HINT HOLDS LITERAL CHARACTERS, never `\u`-escapes. It shipped to the live Space
          printing `it kept β€” which is what a β€œΟƒ from the mean”` ON SCREEN,
          because the escapes were written with a DOUBLED backslash and the JS string then had
          nothing left to interpret. `tsc` is happy β€” a wrong string is valid TypeScript β€” and no
          gate reads prose. It was caught by opening the deployed pane and LOOKING at it
          ([[ui-invisible-to-assertions]]).
        */}
        <RollupConditionList
          idPrefix={`${idPrefix}-rollup-cond`}
          title="Then keep only"
          hint={"Applied AFTER the window above, over exactly the records it kept, which is "
            + "what a β€œΟƒ from the mean” threshold is measured against."}
          conditions={rollupConditions}
          onConditions={(v) => onRollupConditions?.(v)}
          conj={rollupConditionConj}
          onConj={(v) => onRollupConditionConj?.(v)}
          targetFields={targetFields}
          allowRef
        />
        </>
        )}
        <div className="cg-field-hint">
          Computed for you and refreshed as the linked records change. The cell cannot be typed
          into.
        </div>
      </>
    );
    // β›” THE MODE SWITCH RENDERS ONLY WHEN THERE IS A CHOICE TO MAKE. On a workspace with no
    // connected source the offer is empty, and a two-way toggle whose second option can never
    // work is a control that configures nothing ([[wrong-parent-not-broken-control]]). The link
    // editor is then simply what a rollup is, exactly as it was before this existed.
    if (rollupPreset || !sourceTopics.length) return linkEditor;
    return (
      <>
        <label>
          <span>Summarise</span>
          <select
            id={`${idPrefix}-rollup-mode`}
            className="cg-input"
            value={rollupMode}
            aria-label="What this rollup summarises"
            onChange={(event) => onRollupMode?.(event.target.value as "link" | "source")}
          >
            <option value="link">Records in this workspace</option>
            <option value="source">Live Odoo data</option>
          </select>
        </label>
        <div className="cg-field-hint">
          {rollupMode === "source"
            ? "Answered straight from the source. It can total hundreds of thousands of rows because none of them are copied into this database."
            : "Folds the records a link column reaches, which must already exist in this workspace."}
        </div>
        {rollupMode === "source" ? sourceEditor : linkEditor}
      </>
    );
  }
  return null;
}

export default function ColumnMenu({
  viewControlsReadOnly = false,
  state,
  field,
  fields,
  linkTargets = [],
  rollupSourceOffer = { topics: [], windows: [] },
  hopTopicOffer = { topics: [], windows: [], omissions: [] },
  geocodable,
  locked,
  schemaLocked = false,
  canAddField = true,
  embedded = false,
  columnWidth = 160,
  onColumnWidth,
  isUserTable = false,
  viewer,
  sortedDir,
  isFiltered,
  isGrouped,
  groupable,
  onClose,
  onNote,
  onHide,
  onMoveLeft,
  onMoveRight,
  onCreate,
  onChangeField,
  onCreateAndSwap,
  onProfileFlag,
  onRetype,
  onChoiceRemove,
  onFieldConfig,
  onRename,
  onFormula,
  initialPosition,
  initialPane,
  scopeChoice = false,
  pinnedTo = false,
  onPinTo,
  onUnpin,
  onPeriod,
  onDelete,
  onSetDeletionLock,
  onCopyFieldLink,
  onRemoveFromMine,
  onEnrich,
  onDuplicate,
  onFormat,
  onSummary,
  summary,
  onShowAs,
  onSort,
  onClearSort,
  onFilterBy,
  onClearFilter,
  onGroupByField,
  onClearGroup,
  userOptions = [],
  measures = [],
  tableKey,
}: ColumnMenuProps) {
  const optionLimit = serverOptionLimit(fields);
  const fieldOfferable = isOfferableField(field);
  const hopScopeKey = tableKey === "customer_data"
    ? "customer"
    : tableKey === "product_data"
      ? "product"
      : tableKey ?? "";
  const hopTopics: HopTopic[] = hopTopicOffer.topics;
  /**
   * ⭐⭐ W40-T24 (owner instruction 18, contract C2) β€” the pre-set DEFINITION lock, read from the
   * one place that states it. `display.ts` carries the whole argument, including the measured
   * reason the lock is spelt `isUserSchemaField` and NOT `isPresetField` (nine product_data
   * contract columns, Supplier among them, are declared `source: "overlay"` so that their cells
   * stay typeable, and `isPresetField` answers false for every one).
   *
   * ⚠ ONLY `swap` AND `remove` ARE READ HERE, and that is the design, not an omission: `rename`
   * and `retype` are already enforced at the host by withholding their handlers, and a second
   * refusal in this file could only subtract from a door the host deliberately opened.
   */
  const offer = columnDefinitionOffer(field, { isUserTable, isPrimary: locked });
  const canEditDefinition = !embedded && !schemaLocked && mayEditFieldDefinition(field, viewer);
  /**
   * ⭐⭐ W41-T31 (owner instruction 1, ruling R19) β€” THE DESCRIPTION-ONLY DOOR.
   *
   * Owner: *"A pre-set field's 'Edit field' should not exist except to change the description;
   * the pre-set description is the one place a user adds a description."*
   *
   * β›” A SECOND PREDICATE, NOT A WIDER `canEditDefinition`, and the distinction is the ticket's
   * own instruction. Widening the one above would re-open the Name box, the type picker, the
   * retype, Change field, the period row and the delete β€” every door the pre-set lock closed on
   * purpose β€” to buy one textarea. This one says only "there is a description here to write",
   * and every surface that asks "may this definition change?" keeps getting the same `false`
   * it got before.
   *
   * β›” IT IS THE PRE-SET LOCK IT READS, and only that. `schemaLocked` is
   * `CustomerGrid.isSchemaLocked`, i.e. `automation.preset === true && type !== "rollup"` β€” the
   * client mirror of `core.user_tables.preset_editable`. That is the lock DESIGN section 4 calls
   * the pre-set field: it closes the DEFINITION and leaves the cells as typeable as they were.
   * A locked database and a locked view are different locks and neither is asked about here.
   *
   * ⚠ `onNote` IS A REQUIRED PROP, so the second clause is a runtime seatbelt rather than a real
   * gate β€” but it is the handler the whole pane exists to reach, and `typeof` is how you write
   * that without TS2774 ("this condition will always return true").
   */
  const canEditDescription = !embedded && schemaLocked && typeof onNote === "function";
  /**
   * Either door opens the Edit-field pane; WHICH pane is decided at the render, below. Read by
   * the menu row and by the seed, so the two can never disagree about whether it is on offer.
   *
   * ⚠ THE SEED IS A SECOND GATE and it refused `"edit"` independently of the menu row: on a
   * `schemaLocked` field it forced `"menu"` for EVERY `initialPane`, so a host opening straight
   * onto the edit pane (`viewModes` does) landed a pre-set on the action list instead. Rewritten
   * so the `"edit"` case asks `editPaneOffered` and every OTHER initial pane keeps the blanket
   * `schemaLocked` refusal it had β€” creating a column, not describing one, is what that refused.
   */
  const editPaneOffered = canEditDefinition || canEditDescription;
  const [pane, setPane] = useState<MenuPane>(
    embedded ? "menu" : initialPane === "edit"
      ? (editPaneOffered ? "edit" : "menu")
      : (schemaLocked ? "menu" : initialPane ?? "menu")
  );
  const [note, setNote] = useState(field.note ?? "");
  const [position, setPosition] = useState<CreatePosition | null>(embedded ? null : initialPosition ?? null);
  const [widthDraft, setWidthDraft] = useState(String(Math.round(columnWidth)));
  /** Delete is DESTRUCTIVE (a custom field's stored values go with it) β€” first click arms,
   *  second click fires. Reopening the menu disarms (state is per-mount, keyed by field). */
  const [label, setLabel] = useState("");
  /** Whether the user has typed their own name β€” an auto-suggested measure label must never
   *  overwrite one, but should keep tracking the measure/window until they do. */
  const [labelTouched, setLabelTouched] = useState(false);
  const [kind, setKind] = useState<CreateKind>("text");
  const [createDefaultEnabled, setCreateDefaultEnabled] = useState(false);
  const [createDefaultValue, setCreateDefaultValue] = useState("");
  const [ifDraft, setIfDraft] = useState<IfDefinition>(emptyIfDefinition);
  const [editIf, setEditIf] = useState<IfDefinition>(() => field.if ?? emptyIfDefinition());
  const ifSourceFields = fields.filter((source) => isOfferableField(source));
  const editIfSourceFields = ifSourceFields.filter((source) => source.key !== field.key);
  /** ⭐ W36-T07 β€” the field agent's pane, inside the create pane rather than beside it: it
   *  produces the same definition the form does, so it belongs in the same doorway. */
  const [askAgent, setAskAgent] = useState(false);
  const [createOptionDrafts, setCreateOptionDrafts] = useState<OptionDraft[]>(() =>
    optionDrafts(DEFAULT_OPTION_LABELS)
  );
  const [createColorCode, setCreateColorCode] = useState(true);
  const [measureKey, setMeasureKey] = useState(measures[0]?.key ?? "");
  /** ⭐⭐ W37-T22 (R4 / C7) β€” which column the geocode kind reads. Empty = not chosen yet, which
   *  is what `canCreate` refuses on: a geocode column with no address column is a column no run
   *  can ever fill, the same argument the `automation` URL-column rule makes below. */
  const [geocodeAddressField, setGeocodeAddressField] = useState("");
  /** D-3 β€” the optional country hint. Absent means "anywhere", so an empty box changes nothing and
   *  `canCreate` deliberately does NOT gate on it. */
  const [geocodeCountry, setGeocodeCountry] = useState("");
  const [measureWindow, setMeasureWindow] = useState<WindowSpec>(DEFAULT_MEASURE_WINDOW);
  /** Wave-5 item 9/11 β€” the create form's formula source and rating star count. */
  const [formulaText, setFormulaText] = useState("");
  const [maxValue, setMaxValue] = useState(5);
  /** ⭐ Wave-27 item 13 (R13) β€” the create form's code LANGUAGE. Seeded to `plain`, which is
   *  also what an absent bag means, so creating without touching this stores nothing extra. */
  const [codeLanguage, setCodeLanguage] = useState<string>("plain");
  /**
   * ⭐⭐ Wave-34 (owner ruling R13) β€” the create form's AI ENRICHMENT config.
   *
   * ⚠ ONE BAG AND ONE PATCHER, not six flat props. `link`/`rollup`/`automation` above are each a
   * scatter of `xState`/`onXState` pairs, and the scouted consequence is concrete: the swap form
   * mounts `ExtraTypeEditor` WITHOUT those setters, so choosing one of those kinds there renders
   * a panel whose controls are wired to `undefined`. A single bag cannot be half-passed, so this
   * kind cannot arrive at that door inert.
   * ⚠ The defaults ARE the server's defaults (`AI_ENRICH_DEFAULT_TOKENS = 300`, `mode: manual`,
   * `overwrite: blank`), so creating without touching anything but the prompt stores exactly what
   * the panel showed.
   */
  const [aiEnrich, setAiEnrich] = useState<AiEnrichDraft>(() => ({
    prompt: "",
    model: "",
    maxTokens: 300,
    mode: "manual",
    cron: "",
    overwrite: "blank",
  }));
  /** ⚠ FUNCTIONAL UPDATE, not `setAiEnrich({...aiEnrich, ...patch})`. Two controls in this panel
   *  can change in one tick (picking `schedule` reveals the cron box, which the user then types
   *  into), and a spread over a captured `aiEnrich` would drop whichever landed first. */
  const patchAiEnrich = (patch: Partial<AiEnrichDraft>) =>
    setAiEnrich((prev) => ({ ...prev, ...patch }));
  /** C5-AUTOFIELD β€” the create form's automation config. */
  const [automationKind, setAutomationKind] = useState(AUTOMATION_KINDS[0].key);
  const [automationUrlField, setAutomationUrlField] = useState(
    () => offerableFields(fields).find((f) => f.type === "url")?.key ?? ""
  );
  /**
   * ⭐ 2026-08-07 β€” the create form's LINK and ROLLUP configuration.
   *
   * β›” BOTH KINDS ARE UNCREATABLE WITHOUT THEIR BAG β€” `core.user_tables._clean_field` returns
   * None for a `link` with no `link` bag and for a `rollup` with no `rollup` bag β€” so `canCreate`
   * gates on these below rather than letting the server refuse a column the user just named.
   * That refusal would be silent in the worst way: created, named, configured, gone on reload.
   */
  const [linkTable, setLinkTable] = useState("");
  const [linkSingle, setLinkSingle] = useState(false);
  const [linkSelectionMode, setLinkSelectionMode] = useState<"manual" | "automatic">("manual");
  const [linkSelectionFilter, setLinkSelectionFilter] = useState<FilterTree | null>(null);
  const [hopDraft, setHopDraft] = useState<HopDraft>(emptyHopDraft);
  const patchHopDraft = (patch: Partial<HopDraft>) =>
    setHopDraft((current) => ({ ...current, ...patch }));
  /** ⭐ 2026-08-09 β€” the read-through half. `rollupMode` decides which bag `extraFor` builds;
   *  the two are mutually exclusive because the host's `_clean_rollup` returns the `source`
   *  shape before it ever reads `link`. */
  const [rollupMode, setRollupMode] = useState<"link" | "source">("link");
  const [rollupSource, setRollupSource] = useState<RollupSource>({
    topic: "", measure: "", groupBy: "", on: "", window: "ytd",
  });
  const [rollupLink, setRollupLink] = useState("");
  const [rollupField, setRollupField] = useState("");
  const [rollupFn, setRollupFn] = useState<RollupFn>("sum");
  /** 0 = every linked record (Airtable's only behaviour). Non-zero needs a sort β€” see below. */
  const [rollupLimit, setRollupLimit] = useState(0);
  const [rollupSortBy, setRollupSortBy] = useState("");
  const [rollupDistinctBy, setRollupDistinctBy] = useState("");
  const [rollupWhere, setRollupWhere] = useState<RollupCondition[]>([]);
  const [rollupWhereConj, setRollupWhereConj] = useState<"and" | "or">("and");
  const [rollupConditions, setRollupConditions] = useState<RollupCondition[]>([]);
  const [rollupConditionConj, setRollupConditionConj] = useState<"and" | "or">("and");
  const [rollupPreset, setRollupPreset] = useState<RollupPreset | null>(null);
  const pickKind = (picked: PickerKind) => {
    const preset = picked === "count" || picked === "lookup" ? picked : null;
    setRollupPreset(preset);
    if (!preset) {
      setKind(picked as CreateKind);
      return;
    }
    setKind("rollup");
    setRollupMode("link");
    setRollupFn(ROLLUP_PRESET_FNS[preset]);
    if (preset === "count") setRollupField("");
    setRollupLimit(0);
    setRollupSortBy("");
    setRollupDistinctBy("");
    setRollupWhere([]);
    setRollupConditions([]);
  };
  const [swapTo, setSwapTo] = useState("");
  /** The "New field" half of Change-field keeps its own name/options β€” a half-typed insert
   *  form must not leak into a swap and vice versa. */
  const [swapLabel, setSwapLabel] = useState("");
  const [swapOptionDrafts, setSwapOptionDrafts] = useState<OptionDraft[]>(() =>
    optionDrafts(DEFAULT_OPTION_LABELS)
  );
  const [swapColorCode, setSwapColorCode] = useState(true);
  const [swapFormulaText, setSwapFormulaText] = useState("");
  const [swapMaxValue, setSwapMaxValue] = useState(5);
  /** ⭐ Wave-27 item 13 (R13) β€” the swap form's OWN language draft. It gets one rather than
   *  reading the create form's, because `extraFor` used to close over the create drafts and the
   *  swap path passes its own `src`/`starCount` in for exactly that reason: two forms sharing a
   *  draft means changing a language in one silently changes what the other will save. */
  const [swapCodeLanguage, setSwapCodeLanguage] = useState<string>("plain");
  /** Item 8c β€” the period DRAFT. null = untouched (the field's own window shows). Buffered
   *  behind an Apply rather than emitted per keystroke: a custom range is typed one date at a
   *  time, and each emit is a full host round trip that would repaint the column half-ready. */
  const [periodDraft, setPeriodDraft] = useState<WindowSpec | null>(null);
  /** Format pane draft β€” seeded from the field, saved whole. */
  const [fmtDraft, setFmtDraft] = useState<FieldFormat>(() => ({ ...(field.format ?? {}) }));
  /** Item 9c β€” the create forms' Scope draft. 'cohort' is the DEFAULT per the contract. */
  const [scopeDraft, setScopeDraft] = useState<FieldScope>("cohort");
  /** The Edit pane's NAME draft, seeded from the current label (wave-6 item 5's rename,
   *  re-homed into the Edit-field pane by owner item 8). */
  const [renameDraft, setRenameDraft] = useState(field.label);
  /** Owner item 8 β€” the Edit pane's TYPE draft plus the per-type config drafts: options
   *  prefilled from the field (a select retyped to multi select keeps its choices), star
   *  count from the field's own max, formula source from the field's own source. */
  const [editType, setEditType] = useState<FieldType>(field.type);
  const [editDefaultEnabled, setEditDefaultEnabled] = useState(field.defaultValue !== undefined);
  const [editDefaultValue, setEditDefaultValue] = useState(String(field.defaultValue ?? ""));
  const [editOptionDrafts, setEditOptionDrafts] = useState<OptionDraft[]>(() =>
    optionDrafts(
      choiceOptions(field).length ? choiceOptions(field) : DEFAULT_OPTION_LABELS,
      field.optionColors
    )
  );
  /** Item 15 (C-RENAME) β€” what each option ROW said when the editor opened, by draft id. A ref,
   *  not state: it is the fixed point the renames are measured against and it must not move
   *  while the user types. Seeded from the same call that seeds the drafts, so the two cannot
   *  disagree about which row is which. */
  const editOptionOrigin = useRef<Map<string, string>>(new Map());
  if (editOptionOrigin.current.size === 0 && editOptionDrafts.length)
    editOptionOrigin.current = new Map(
      editOptionDrafts.map((draft) => [draft.id, draft.label.trim()])
    );
  /** W48C-T12 - the Edit pane's NUMBER draft for a Metric column, seeded from the field itself.
   *  The create pane has always offered "Number" beside "Period"; the edit pane offered only the
   *  period, so a saved Metric could never be pointed at a different measure (the go-live QA of
   *  2026-09-02 reproduced exactly that). */
  const [editMeasureKey, setEditMeasureKey] = useState<string>(() => field.measure?.key ?? "");
  /**
   * Owner, 2026-09-02 - REMOVING A SAVED OPTION WARNS, THEN CLEARS ITS CELLS. The X on an option
   * row used to drop the draft and let Save write a shorter list, which orphaned every cell that
   * held the label (they rendered as a value that was no longer an option). Now a row whose
   * ORIGIN label is a saved option asks the server how many cells use it: none, and it is removed
   * at once; some, and a confirmation names the count and the consequence before anything moves.
   * A draft that was never saved simply leaves the list, as before.
   */
  const [pendingRemoval, setPendingRemoval] =
    useState<{ draftId: string; label: string; cells: number } | null>(null);
  const [removalBusy, setRemovalBusy] = useState(false);
  const [removalError, setRemovalError] = useState<string | null>(null);
  const dropEditDraft = (draftId: string) => {
    setEditOptionDrafts((current) => current.filter((item) => item.id !== draftId));
    editOptionOrigin.current.delete(draftId);
  };
  const requestOptionRemoval = async (draft: OptionDraft) => {
    const savedLabel = editOptionOrigin.current.get(draft.id) ?? "";
    const isSaved =
      !!savedLabel &&
      choiceOptions(field).some((o) => o.toLowerCase() === savedLabel.toLowerCase());
    if (!onChoiceRemove || !isSaved) {
      dropEditDraft(draft.id);
      return;
    }
    setRemovalError(null);
    setRemovalBusy(true);
    const probe = await onChoiceRemove(savedLabel, false);
    if (!probe) {
      setRemovalBusy(false);
      setRemovalError("Could not check where this option is used. Reload the database, then try again.");
      return;
    }
    if (probe.cells === 0) {
      const done = await onChoiceRemove(savedLabel, true);
      setRemovalBusy(false);
      if (done?.applied) dropEditDraft(draft.id);
      else setRemovalError("The option was not removed. Reload the database, then try again.");
      return;
    }
    setRemovalBusy(false);
    setPendingRemoval({ draftId: draft.id, label: savedLabel, cells: probe.cells });
  };
  const confirmOptionRemoval = async () => {
    if (!pendingRemoval || !onChoiceRemove) return;
    setRemovalError(null);
    setRemovalBusy(true);
    const done = await onChoiceRemove(pendingRemoval.label, true);
    setRemovalBusy(false);
    if (!done?.applied) {
      setRemovalError("The option was not removed. Reload the database, then try again.");
      return;
    }
    dropEditDraft(pendingRemoval.draftId);
    setPendingRemoval(null);
  };
  const [editColorCode, setEditColorCode] = useState(field.colorCodeOptions !== false);
  const [retypeMaxValue, setRetypeMaxValue] = useState(() => ratingMax(field));
  const [editFormulaText, setEditFormulaText] = useState(() =>
    typeof field.formula === "string" ? field.formula : ""
  );
  /** C5-AUTOFIELD β€” the Edit pane's automation drafts, seeded from the field's own config. */
  const [editAutomationKind, setEditAutomationKind] = useState(
    () => field.automation?.kind ?? AUTOMATION_KINDS[0].key
  );
  const [editAutomationUrlField, setEditAutomationUrlField] = useState(
    () => field.automation?.urlField ?? ""
  );
  /** ⭐ Wave-27 item 13 (R13) β€” the Edit pane's language draft, seeded from the field's own bag
   *  through the shared resolver (never `field.code!.language`: an unconfigured code column is
   *  the common case, and `codeLanguageOf` is the one place that answers what absent means). */
  const [editCodeLanguage, setEditCodeLanguage] = useState<string>(() => codeLanguageOf(field));
  /**
   * ⭐⭐ 2026-08-09 (owner) β€” THE EDIT PANE'S OWN RELATIONAL DRAFT, seeded from the field's bag.
   *
   * Owner: *"even when i click edit field for rollup, it doesn't actually show me the
   * configuration that I use to generate it, it only shows change to a different field."*
   * Exactly right, and it was worse than missing: `RETYPE_TYPES` includes `rollup`, so the pane
   * offered a type picker whose "Rollup" option would re-save the column with NO bag.
   *
   * β›” ONE OBJECT, NOT TWELVE `useState`s, and the reason is seeding. Every draft here must start
   * as what the STORE holds β€” a pane that opens on defaults and then saves them is a pane that
   * silently rewrites a working column the moment somebody opens it to look. One object seeded
   * once from `field.rollup` makes "opened but unchanged" literally equal to the stored bag, so
   * the dirty check below is an object comparison rather than twelve remembered pairs.
   */
  type RollupBag = NonNullable<Field["rollup"]>;
  const [editRollup, setEditRollup] = useState<RollupBag>(() => ({ ...(field.rollup ?? {}) }));
  const patchEditRollup = (patch: Partial<RollupBag>) =>
    setEditRollup((current) => {
      const next = { ...current, ...patch } as RollupBag;
      // β›” AN EMPTY LIST IS AN ABSENT KEY, matching what `extraFor` sends on the create path and
      // what `_clean_rollup` stores. Otherwise "remove the last condition" would save
      // `conditions: []` while the stored bag has no such key, and the column would read as
      // dirty forever.
      for (const key of ["where", "conditions"] as const) {
        if (Array.isArray(next[key]) && next[key]!.length === 0) {
          delete next[key];
          delete next[key === "where" ? "whereConj" : "conditionConj"];
        }
      }
      if (!next.sortBy) {
        // The server refuses a limit with no declared order; dropping both together keeps the
        // draft in a shape that can always be saved.
        delete next.limit;
        delete next.sortDir;
      }
      return next;
    });
  const [editLinkTable, setEditLinkTable] = useState(() => field.link?.table ?? "");
  const [editLinkSingle, setEditLinkSingle] = useState(() => field.link?.single === true);
  const [editLinkSelectionMode, setEditLinkSelectionMode] = useState<"manual" | "automatic">(
    () => field.link?.selectionMode === "automatic" ? "automatic" : "manual"
  );
  const [editLinkSelectionFilter, setEditLinkSelectionFilter] = useState<FilterTree | null>(
    () => field.link?.selectionFilter ?? null
  );
  const [editHopDraft, setEditHopDraft] = useState<HopDraft>(() => hopDraftFrom(field.link));
  const patchEditHopDraft = (patch: Partial<HopDraft>) =>
    setEditHopDraft((current) => ({ ...current, ...patch }));

  const swapToNewType = swapTo.startsWith(NEW_PREFIX)
    ? (swapTo.slice(NEW_PREFIX.length) as FieldType)
    : null;

  const createChoice = optionSettings(createOptionDrafts, kind, optionLimit);
  const options = createChoice.options;
  const swapChoice = swapToNewType
    ? optionSettings(swapOptionDrafts, swapToNewType, optionLimit)
    : { options: [] as string[], colors: {} as Record<string, string>,
        capMessage: null as string | null };
  const swapNewOptions = swapChoice.options;
  /** Owner item 8 β€” the Edit pane's parsed choices for the drafted type. */
  const editChoice = optionSettings(editOptionDrafts, editType, optionLimit);
  const editOptions = editChoice.options;

  // Wave-5 item 9, amended 2026-07-31 (owner item 2) β€” live formula validation for BOTH
  // create surfaces. Refs may now name OTHER formula fields (evaluation is topological);
  // what is refused is a CYCLE, checked against every formula's SOURCE. Both surfaces here
  // CREATE a field, so no cycle is possible yet and no selfKey is passed β€” the retype path
  // (in-place formula edit) would pass the edited field's key.
  const knownKeys = useMemo(
    () => new Set(fields.filter((f) => f.type !== "formula").map((f) => f.key)),
    [fields]
  );
  const formulaSources = useMemo(() => {
    const out = new Map<string, string>();
    for (const f of fields) {
      if (f.type !== "formula") continue;
      const src = typeof f.formula === "string" ? f.formula : "";
      if (src) out.set(f.key, src);
    }
    return out;
  }, [fields]);
  // ⭐⭐ W50-T06 (owner instruction 5) β€” A LEADING `=` IS ACCEPTED AND STRIPPED, and the
  // stripping happens HERE, on the way into the validator, not only on the way into the store.
  // A spreadsheet user's first keystroke in this box is `=`; the runtime does not accept one,
  // so validating the raw text would answer that keystroke with a parse error and the editor
  // would read as broken before a single function had been typed. Stripping at BOTH ends means
  // what is judged is exactly what is saved.
  // ⚠ `formulaEngine.ts` is another lane's file and is deliberately untouched: the runtime's
  // grammar is unchanged, and `=` is an EDITOR affordance rather than a language feature.
  const formulaCheck = useMemo(() => {
    const src = stripLeadingEquals(formulaText);
    return src.trim() === ""
      ? { ok: false, error: "Type a formula", refs: [] as string[] }
      : validateFormula(src, knownKeys, formulaSources);
  }, [formulaText, knownKeys, formulaSources]);
  const swapFormulaCheck = useMemo(() => {
    const src = stripLeadingEquals(swapFormulaText);
    return src.trim() === ""
      ? { ok: false, error: "Type a formula", refs: [] as string[] }
      : validateFormula(src, knownKeys, formulaSources);
  }, [swapFormulaText, knownKeys, formulaSources]);

  const chosenMeasure = measures.find((m) => m.key === measureKey);
  /**
   * ⭐⭐ W37-T22 (R4 / C7) β€” the columns a geocode field may read, and the offer predicate.
   *
   * β›” TWO CONDITIONS, ANDed, and the second is the one a reader will want to delete. `geocodable`
   * says the surface can PERSIST the bag (see `TypePicker`'s `offerGeocode` doc for why the Odoo
   * grids can and a `ut_*` database cannot yet); the address list says the table has something to
   * read. Offering on the vocabulary alone would create a field that is named, configured and
   * permanently unable to run.
   */
  const addressFields = useMemo(
    () => offerableFields(fields).filter(
      (f) => (GEOCODE_ADDRESS_TYPES as readonly string[]).includes(f.type)
    ),
    [fields]
  );
  const offerGeocode = geocodable && addressFields.length > 0;
  /** The suggested name reads as the sentence the column answers: "Sales Β· the last 90 days". */
  const suggestedLabel = chosenMeasure
    ? `${chosenMeasure.label} Β· ${windowLabel(measureWindow)}`
    : "";
  const effectiveLabel =
    kind === "measure" && !labelTouched && !label.trim() ? suggestedLabel : label;
  const createDefaultOffered = isUserTable && supportsDefaultValue(kind);
  const createDefaultValid = !createDefaultOffered || !createDefaultEnabled ||
    defaultValueDraftValid(kind, createDefaultValue);

  // A select/multiselect starts with an empty vocabulary and learns values from the shared write
  // path, so creation and retyping never block on predeclared options. A measure column needs a
  // measure; a formula column needs a formula that PARSES β€” an
  // unparseable formula would be a permanently blank column, refused here rather than shipped.
  const canCreate =
    canAddField &&
    effectiveLabel.trim() !== "" &&
    createDefaultValid &&
    (kind !== "if" || ifDefinitionIssue(ifDraft, ifSourceFields) === null) &&
    (!needsOptions(kind) || createChoice.capMessage === null) &&
    (kind !== "measure" || !!chosenMeasure) &&
    // ⭐⭐ W37-T22 (R4 / C7) β€” a geocode column with no address column to read is a column no run
    // can ever fill: the identical argument the `automation` URL-column rule below makes, and the
    // one the `link`/`rollup`/`ai_enrich` rules make one step harder. Refused here rather than
    // created and then discovered to be inert.
    (kind !== "geocode" || geocodeAddressField !== "") &&
    (kind !== "formula" || formulaCheck.ok) &&
    // C5-AUTOFIELD: an automation column with no URL column to read is a column no run can
    // ever fill β€” the same "permanently blank column" the formula rule above refuses, so it
    // is refused here rather than created and then discovered.
    (kind !== "automation" || automationUrlField !== "") &&
    // ⭐ 2026-08-07 β€” both relational kinds are UNCREATABLE without their bag: `_clean_field`
    // returns None for a `link` with no target and a `rollup` with no link/function, so
    // creating one without this gate produces a column that is named, configured and simply
    // absent on the next read. The same "permanently blank column" argument as the two rules
    // above, one step worse β€” the column does not exist at all.
    // ⭐⭐ Wave-34 (R13) β€” the same argument one kind over: `_clean_field` returns None for an
    // `ai_enrich` column with no prompt, so creating one without this gate produces a column that
    // is named, configured and simply absent on the next read.
    (kind !== "ai_enrich" || aiEnrich.prompt.trim() !== "") &&
    (kind !== "link" || (linkTable !== "" && !hopIncomplete(hopDraft, hopScopeKey) &&
      linkSelectionFilterIssue(linkSelectionFilter,
        linkTargets.find((target) => target.key === linkTable)?.fields ?? []) === null)) &&
    (kind !== "rollup" || (rollupMode === "source"
      // ⭐ 2026-08-09 β€” the read-through bag. ALL FOUR keys are required by `_clean_rollup`
      // (`if not (topic and measure and group_by and on): return None`), and `on` is the one a
      // user forgets: without it the bag names a real measure grouped a real way with nothing
      // to match it to any row, and the field would be refused after Create.
      ? (rollupSource.topic !== "" && rollupSource.measure !== "" &&
         rollupSource.groupBy !== "" && rollupSource.on !== "")
      : (
        rollupLink !== "" &&
        (rollupFn === "countall" || rollupField !== "") &&
        // `latest` without an order is store order wearing a deterministic name.
        (rollupFn !== "latest" || rollupSortBy !== "")
      )));

  const extraFor = (
    t: CreateKind,
    src: string,
    starCount: number,
    lang: string,
    hopSource: HopDraft | null
  ): FieldConfigExtra | undefined => {
    if (t === "if") return { if: ifDraft };
    // W50-T06 β€” the save side of the leading-`=` rule. See `formulaCheck` above.
    if (t === "formula") return { formula: stripLeadingEquals(src).trim() };
    if (t === "rating") return { max: starCount };
    // ⭐ Wave-27 item 13 (R13). The bag is ALWAYS sent, including `plain` β€” the host's
    // `_clean_code` evaluates plain to None and therefore CLEARS the key, which is what makes
    // "switch this column back to Plain text" a change that saves. Omitting it instead would
    // inherit the previous language (the patch path's omit-means-keep rule).
    if (t === "code") return { code: { language: lang } };
    // ⭐⭐ Wave-34 (R13) β€” the enrichment bag, shaped exactly as `_clean_ai_enrich` stores it.
    // ⚠ `cron` TRAVELS ONLY WITH `schedule`, and `model` only when set: the server drops both in
    // those cases anyway, so sending them would put keys in the payload that come back absent,
    // which is how a panel starts looking like it does not save. Same rule the rollup bags above
    // follow for `limit`/`sortBy`.
    if (t === "ai_enrich")
      return {
        aiEnrich: {
          prompt: aiEnrich.prompt.trim(),
          ...(aiEnrich.model.trim() ? { model: aiEnrich.model.trim() } : {}),
          maxTokens: aiEnrich.maxTokens,
          trigger: {
            mode: aiEnrich.mode,
            ...(aiEnrich.mode === "schedule" && aiEnrich.cron.trim()
              ? { cron: aiEnrich.cron.trim() }
              : {}),
          },
          overwrite: aiEnrich.overwrite,
        },
      };
    if (t === "automation")
      return {
        automation: {
          kind: automationKind,
          source: "record_url_field",
          urlField: automationUrlField,
        },
      };
    // ⭐ 2026-08-07 β€” the relational bags, shaped exactly as `_clean_link` / `_clean_rollup`
    // store them. ⚠ NO `on` KEY: a link created from this menu is an ORDINARY one (the user
    // picks records). The DERIVED mode is the automation's, spawned with its join declared β€”
    // offering "join on a column of the other table" here would be a second, harder mental
    // model for the same button.
    if (t === "link") {
      const via = hopVia(hopSource, hopScopeKey);
      return { link: { table: linkTable, selectionMode: linkSelectionMode,
        ...(linkSelectionFilter ? { selectionFilter: linkSelectionFilter } : {}),
        ...(linkSingle ? { single: true } : {}),
        ...(via ? { from: "pid", on: via.target_key, via } : {}) } };
    }
    if (t === "rollup" && rollupMode === "source")
      // β›” THE SOURCE BAG TRAVELS ALONE. `_clean_rollup` reads `source` first and returns
      // immediately, so sending `link`/`fn` alongside it would ship keys the store drops β€”
      // harmless today and exactly the kind of dead payload that later reads as configuration.
      return {
        rollup: {
          source: {
            topic: rollupSource.topic,
            measure: rollupSource.measure,
            groupBy: rollupSource.groupBy,
            on: rollupSource.on,
            // ⚠ `all_time` is sent as an ABSENT window, which is what it means: the validator
            // accepts the literal too, but the bag is smaller and reads as "no window".
            ...(rollupSource.window && rollupSource.window !== "all_time"
              ? { window: rollupSource.window }
              : {}),
          },
        },
      };
    if (t === "rollup")
      return {
        rollup: {
          link: rollupLink,
          ...(rollupFn === "countall" ? {} : { field: rollupField }),
          fn: rollupFn,
          // β›” `limit` AND `sortBy` TRAVEL TOGETHER OR NEITHER TRAVELS. The host refuses a limit
          // with no declared order, so sending one would turn a valid-looking form into a 400.
          ...(rollupSortBy
            ? { sortBy: rollupSortBy, sortDir: "desc" as const,
                limit: rollupLimit || 1 }
            : {}),
          ...(rollupDistinctBy ? { distinctBy: rollupDistinctBy } : {}),
          // β›” EACH LIST TRAVELS WITH ITS OWN CONJUNCTION OR NEITHER TRAVELS β€” `_clean_rollup`
          // stores the pair together, so sending a conj with no list would be a stored key
          // nothing reads, and a list with no conj would take the server's default rather than
          // the one this editor showed.
          ...(rollupWhere.length
            ? { where: rollupWhere, whereConj: rollupWhereConj }
            : {}),
          ...(rollupConditions.length
            ? { conditions: rollupConditions, conditionConj: rollupConditionConj }
            : {}),
        },
      };
    return undefined;
  };
  const optionExtraFor = (
    t: CreateKind,
    colors: Record<string, string>,
    colorCode: boolean
  ): FieldConfigExtra =>
    needsOptions(t)
      ? {
          colorCodeOptions: colorCode,
          ...(Object.keys(colors).length ? { optionColors: colors } : {}),
        }
      : {};
  /** Item 9c β€” the Scope choice rides the create extras only where the page offers it. */
  const withScope = (e?: FieldConfigExtra): FieldConfigExtra | undefined =>
    scopeChoice ? { ...(e ?? {}), scope: scopeDraft } : e;

  const create = () => {
    const clean = effectiveLabel.trim();
    if (!clean || !position || !canCreate) return;
    if (kind === "measure") {
      if (!chosenMeasure) return;
      onCreate(clean, chosenMeasure.type, position === "end" ? null : field.key, position,
               undefined, { key: chosenMeasure.key, window: measureWindow },
               withScope(undefined));
      onClose();
      return;
    }
    // ⭐⭐ W37-T22 (R4 / C7) β€” the geocode PSEUDO-KIND creates a real `text` column carrying its
    // bag, the `measure` branch above's construction. `kind` is not a `FieldType` here, so it
    // cannot be passed through as one; widening `FieldType` instead would drag the name into
    // five vocabularies and a cell renderer for a column that renders as text anyway.
    if (kind === "geocode") {
      if (!geocodeAddressField) return;
      const country = geocodeCountry.trim().toUpperCase();
      onCreate(clean, "text", position === "end" ? null : field.key, position, undefined,
               undefined, withScope({
                 geocode: {
                   addressField: geocodeAddressField,
                   // Absent, never `""`: an empty country is the default's second spelling, and
                   // two spellings of one state is how a round trip starts churning.
                   ...(country ? { country } : {}),
                 },
               }));
      onClose();
      return;
    }
    onCreate(clean, kind, position === "end" ? null : field.key, position,
             needsOptions(kind) ? options : undefined, undefined,
             withScope({
               ...extraFor(kind, formulaText, maxValue, codeLanguage, hopDraft),
               ...optionExtraFor(kind, createChoice.colors, createColorCode),
               ...(createDefaultOffered && createDefaultEnabled
                 ? { defaultValue: defaultValueFromDraft(kind, createDefaultValue) } : {}),
             }));
    onClose();
  };

  const canCreateSwap =
    swapToNewType != null &&
    swapLabel.trim() !== "" &&
    (!needsOptions(swapToNewType) || swapChoice.capMessage === null) &&
    (swapToNewType !== "if" || ifDefinitionIssue(ifDraft, ifSourceFields) === null) &&
    (swapToNewType !== "formula" || swapFormulaCheck.ok) &&
    // ⭐⭐ Wave-34 (R13) β€” the SAME completeness gate `canCreate` carries, on this door too.
    //
    // β›” AND THIS DOOR HAD NO SUCH GATE FOR ANY KIND, WHICH IS A PRE-EXISTING DEFECT I AM NOT
    // FIXING HERE, ONLY REPORTING. `canCreate` refuses a `link` with no target, a `rollup` with
    // no function and an `automation` with no URL column; this predicate refuses none of them,
    // and the swap form's own `<ExtraTypeEditor>` mount passes none of their setters either, so
    // picking one of those three from "Change field" renders a panel wired to nothing and Save
    // ships whatever stale draft the CREATE pane happens to hold. Booked for the register rather
    // than repaired mid-ticket ([[defects-that-mask-each-other]] is why: the missing gate and the
    // missing props hide each other, and fixing one alone arms the other).
    // ⚠ `ai_enrich` cannot arrive here inert, because it is ONE bag and one patcher rather than a
    // scatter of optional setters, so this conjunct is the whole of its half.
    (swapToNewType !== "ai_enrich" || aiEnrich.prompt.trim() !== "");

  const createAndSwap = () => {
    if (!swapToNewType || !canCreateSwap) return;
    onCreateAndSwap(
      swapLabel.trim(),
      swapToNewType,
      needsOptions(swapToNewType) ? swapNewOptions : undefined,
      withScope({
        ...extraFor(swapToNewType, swapFormulaText, swapMaxValue, swapCodeLanguage, null),
        ...optionExtraFor(swapToNewType, swapChoice.colors, swapColorCode),
      })
    );
    onClose();
  };

  // ------------------------------------------------------- owner item 8: Edit-field dirties
  // ONE Save applies whatever changed β€” name, type, choices, stars, formula source β€” and it
  // must leave as ONE upsert when several changed together: sequential emits each read the
  // stale def and the second reverts the first (label rides extra.label / onFormula's label).
  const cleanRename = renameDraft.trim();
  // ⭐ 2026-08-09 β€” `onFieldConfig` is a SECOND door that can rename. `onRename` writes the
  // per-user overlay and is supplied for `custom_` fields only, so a pre-set Rollup β€” now
  // reconfigurable by owner ruling β€” had a configuration it could change and a name it could
  // not. Both ride the same PATCH; the label is part of the definition either way.
  const editNameDirty =
    (!!onRename || !!onFieldConfig) && cleanRename !== "" && cleanRename !== field.label;
  const editNoteDirty = note !== (field.note ?? "");
  const editDefaultOffered = isUserTable && canEditDefinition && !!onFieldConfig &&
    supportsDefaultValue(editType);
  const editDefaultDirty = editDefaultOffered && (
    editDefaultEnabled !== (field.defaultValue !== undefined) ||
    (editDefaultEnabled && editDefaultValue !== String(field.defaultValue ?? ""))
  );
  const editDefaultValid = !editDefaultOffered || !editDefaultEnabled ||
    defaultValueDraftValid(editType, editDefaultValue);
  const editOptionsChanged =
    needsOptions(editType) &&
    editOptions.join("\n") !== choiceOptions(field).join("\n");
  const editAppearanceChanged =
    needsOptions(editType) &&
    (editColorCode !== (field.colorCodeOptions !== false) ||
      optionAppearanceSignature(editOptions, editChoice.colors) !==
        optionAppearanceSignature(choiceOptions(field), field.optionColors));
  const editStarsChanged = editType === "rating" && retypeMaxValue !== ratingMax(field);
  /** The type half was touched: a different type, or the SAME type with edited choices/stars
   *  (the owner's named case β€” "change the list of the single selections"). */
  /** C5-AUTOFIELD β€” the automation config is a property of the column exactly as the choice
   *  list is, so a change to it makes the type half DIRTY and rides the same one upsert. */
  const editAutomationChanged =
    editType === "automation" &&
    field.type === "automation" &&
    (editAutomationKind !== (field.automation?.kind ?? AUTOMATION_KINDS[0].key) ||
      editAutomationUrlField !== (field.automation?.urlField ?? ""));
  const editRetypeTouched =
    onRetype != null &&
    (editType !== field.type || editOptionsChanged || editAppearanceChanged ||
      editStarsChanged || editAutomationChanged);
  const editRetypeValid =
    editType !== "automation" || editAutomationUrlField !== "";
  const editFormulaCheck = useMemo(
    () =>
      stripLeadingEquals(editFormulaText).trim() === ""
        ? { ok: false, error: "Type a formula", refs: [] as string[] }
        : validateFormula(
            stripLeadingEquals(editFormulaText), knownKeys, formulaSources, field.key
          ),
    [editFormulaText, knownKeys, formulaSources, field.key]
  );
  const editFormulaTouched =
    !!onFormula &&
    field.type === "formula" &&
    stripLeadingEquals(editFormulaText).trim() !==
      (typeof field.formula === "string" ? field.formula.trim() : "");
  // A touched-but-invalid half BLOCKS the whole save β€” otherwise Save would apply the name
  // and silently drop the half-finished type change beside it.
  const editBlocked =
    !editDefaultValid ||
    (editRetypeTouched && !editRetypeValid) ||
    (editFormulaTouched && !editFormulaCheck.ok) ||
    (needsOptions(editType) && editChoice.capMessage !== null);
  // Item 21 (2026-08-02) β€” the PERIOD moved into this pane, so its dirty-check has to be
  // computed before the pane's save gate rather than beside the menu's own button. Same three
  // lines, hoisted: `canSaveEdit` reads `periodChanged`, and a `const` read before its
  // initialiser is a TDZ crash at render, not a compile error.
  const currentWindow = field.measure ? normalizeWindow(field.measure.window) : null;
  const draftWindow = periodDraft ? normalizeWindow(periodDraft) : null;
  const periodChanged =
    draftWindow != null &&
    JSON.stringify(draftWindow) !== JSON.stringify(currentWindow);
  const canPeriod = !!field.measure && !!onPeriod;
  const measureChanged =
    canPeriod && !!editMeasureKey && editMeasureKey !== (field.measure?.key ?? "");
  /**
   * ⭐⭐ 2026-08-09 β€” THE RELATIONAL EDIT: is this pane driving a `link`/`rollup` bag?
   *
   * β›” GATED ON `onFieldConfig`, which the host supplies for USER DATABASES ONLY. These bags live
   * in the table's shared definition (`PATCH /tables/{key}/fields/{key}`); there is no such door
   * on the Odoo-backed Customer/Product grids, so offering the editor there would be a form whose
   * Save has nowhere to go.
   */
  const editingRelational =
    !!onFieldConfig && (field.type === "rollup" || field.type === "link");
  /**
   * ⭐⭐ W40-T24 β€” WHERE THE EDIT PANE'S OPENING FOCUS LANDS, decided ONCE.
   *
   * `AnchoredOverlay`'s `initialFocus` is the selector `[data-overlay-autofocus]` and it does
   * `querySelector(...)?.focus()` β€” a MISS is silent, and focus then stays on the grid header
   * button behind the overlay. That is what removing the swap picker from a pre-set column would
   * have caused: the picker carried `overlayAutofocus={!onRename}`, so on Supplier it WAS the
   * pane's focus target, and taking it away leaves a dialog nobody's keyboard is inside. The
   * defect would not show in a screenshot of the fix.
   *
   * Precedence, first match wins, exactly as `querySelector` reads the DOM: the editable Name box
   * Β· the swap picker Β· the Description box, which is the one control a pre-set column still owns.
   * ⚠ It also settles a latent double-marking: an `editingRelational` column with no `onRename`
   * put the attribute on the Name box AND the picker, and which one won was document order rather
   * than a decision.
   */
  const nameIsFocusTarget = !!onRename || editingRelational;
  const editRollupValid =
    field.type !== "rollup" ||
    (editRollup.source
      ? !!(editRollup.source.topic && editRollup.source.measure &&
           editRollup.source.groupBy && editRollup.source.on)
      : !!editRollup.link &&
        (editRollup.fn === "countall" || !!editRollup.field) &&
        (editRollup.fn !== "latest" || !!editRollup.sortBy));
  const editRelationalTouched =
    editingRelational &&
    (field.type === "rollup"
      ? JSON.stringify(editRollup) !== JSON.stringify(field.rollup ?? {})
      : editLinkTable !== (field.link?.table ?? "") ||
        editLinkSingle !== (field.link?.single === true) ||
        editLinkSelectionMode !== (field.link?.selectionMode === "automatic" ? "automatic" : "manual") ||
        JSON.stringify(editLinkSelectionFilter) !== JSON.stringify(field.link?.selectionFilter ?? null) ||
        JSON.stringify(hopVia(editHopDraft, hopScopeKey)) !==
          JSON.stringify(hopVia(hopDraftFrom(field.link), hopScopeKey)));
  const editingIf = !!onFieldConfig && field.type === "if" && !!field.if;
  const editIfTouched = editingIf && JSON.stringify(editIf) !== JSON.stringify(field.if);
  const canSaveEdit =
    /**
     * ⭐ W41-T31 β€” THE DESCRIPTION-ONLY PANE'S WHOLE SAVE CONDITION, and it is one dirty flag
     * because the pane renders one control. The arm below asks four other questions whose
     * answers are all seeded-clean here, and one of them can go WRONG rather than merely
     * useless: a pre-set `link` column is `editingRelational` (the type exclusion in
     * `isSchemaLocked` covers `rollup` only), and that branch also demands `editRollupValid`
     * and a non-empty link table β€” so a pre-set link with a half-filled stored bag would have
     * had Save greyed out with nothing but a description typed into it.
     *
     * β›” THE `else` ARM IS BYTE-IDENTICAL TO WHAT IT WAS. `canEditDescription` requires
     * `schemaLocked`, which forces `canEditDefinition` false, which is what gates the full pane
     * β€” so no field that reaches the arm below can take this branch, and the non-pre-set Save
     * gate is unchanged by construction rather than by inspection.
     */
    canEditDescription
    ? editNoteDirty
    : (!editBlocked &&
    (!editingIf || ifDefinitionIssue(editIf, editIfSourceFields) === null) &&
    // ⭐⭐ Wave-34 (R13) β€” the third door onto the same completeness rule (`canCreate` and
    // `canCreateSwap` are the other two). Retyping a column to AI enrichment without a prompt
    // is refused by the server, so Save is refused here instead: a 400 arriving after the click
    // is the same "named, configured, gone" surprise one layer later.
    (editType !== "ai_enrich" || aiEnrich.prompt.trim() !== "") &&
      (editingRelational
       ? (editRollupValid && (editRelationalTouched || editNameDirty || editNoteDirty) &&
          (field.type !== "link" ||
            (editLinkTable !== "" && !hopIncomplete(editHopDraft, hopScopeKey) &&
              linkSelectionFilterIssue(editLinkSelectionFilter,
                linkTargets.find((target) => target.key === editLinkTable)?.fields ?? []) === null)))
       : (editNameDirty || editRetypeTouched || editDefaultDirty || editFormulaTouched || editIfTouched ||
          (canPeriod && (periodChanged || measureChanged)) || editNoteDirty)));
  /**
   * Item 15 β€” the renames, by ROW IDENTITY. A row that kept its id and changed its label was
   * renamed; a row with an id nobody has seen is new; an id that is gone was deleted. Empty
   * labels are skipped (a row being cleared before it is retyped is not a rename to ""), and a
   * rename to a label that already existed is skipped too β€” that is a MERGE, and merging two
   * choices into one is a different operation from renaming, with a different answer for the
   * cells that held either.
   */
  const optionRenames = (): { from: string; to: string }[] =>
    // A field that was not a choice field before has no values to migrate, and one being
    // retyped AWAY from choices is a different question (its cells stop being options at all).
    needsOptions(editType) && needsOptions(field.type)
      ? choiceRenames(editOptionDrafts, editOptionOrigin.current, choiceOptions(field))
      : [];
  const applyEdit = () => {
    if (!canSaveEdit) return;
    if (editDefaultOffered && onFieldConfig &&
        (editDefaultDirty || editRetypeTouched || editNameDirty)) {
      const renames = optionRenames();
      const value = editDefaultDirty || editType !== field.type
        ? defaultValueFromDraft(editType, editDefaultValue)
        : field.defaultValue;
      onFieldConfig({
        defaultValue: editDefaultEnabled ? value : null,
        ...(editNameDirty ? { label: cleanRename } : {}),
        ...(editRetypeTouched ? {
          type: editType,
          ...(editType === "select" ? {
            options: editOptions,
            colorCodeOptions: editColorCode,
            optionColors: editChoice.colors,
          } : {}),
          ...(renames.length ? { renames } : {}),
        } : {}),
      });
      if (editNoteDirty) onNote(note);
      onClose();
      return;
    }
    if (!canEditDescription && editingIf && onFieldConfig && (editIfTouched || editNameDirty)) {
      onFieldConfig({ if: editIf, ...(editNameDirty ? { label: cleanRename } : {}) });
      if (editNoteDirty) onNote(note);
      onClose();
      return;
    }
    /**
     * β›”β›” W41-T31 β€” THE DESCRIPTION-ONLY SAVE MUST NOT COME THROUGH HERE, and `canEditDescription`
     * is the clause that guarantees it rather than hoping the drafts are clean.
     *
     * This branch is a REBUILD (see the comment inside it): `_clean_rollup` does not merge with
     * the stored bag, so any key this pane did not send comes back as a VALUE, not as
     * "unchanged". The description-only pane renders no relational editor at all, so its
     * `editRollup` / `editLinkTable` drafts are whatever the seeding produced β€” and
     * `editRelationalTouched` compares them by `JSON.stringify`, which a seed that normalises,
     * reorders or defaults a single key would fail. That is not hypothetical: a pre-set `link`
     * column IS `editingRelational` (`isSchemaLocked` excludes `rollup`, not `link`), so the one
     * click meant to save a sentence could have re-emitted the column's link bag.
     *
     * With this guard the save falls through every leg below β€” `editRetypeTouched`,
     * `editFormulaTouched`, `editNameDirty` and `periodChanged` are all seeded-clean and none of
     * their controls is on the pane β€” and lands on the ordinary path's `if (editNoteDirty)
     * onNote(note); onClose();`, which is the one persist site this ticket wants.
     */
    if (!canEditDescription &&
        editingRelational && onFieldConfig && (editRelationalTouched || editNameDirty)) {
      const editVia = hopVia(editHopDraft, hopScopeKey);
      // β›” THE WHOLE BAG, EVERY SAVE. `_clean_rollup` is a pure cleaner over what it receives β€”
      // it does not merge with the stored bag β€” so a partial patch is a REBUILD, and an omitted
      // `limit` would silently become "no limit" rather than "unchanged".
      onFieldConfig({
        ...(editNameDirty ? { label: cleanRename } : {}),
        ...(field.type === "rollup"
          ? { rollup: editRollup as Record<string, unknown> }
          : { link: { ...field.link, table: editLinkTable,
                      selectionMode: editLinkSelectionMode,
                      selectionFilter: editLinkSelectionFilter ?? undefined,
                      ...(field.link?.on
                        ? { on: field.link.on }
                        : editVia ? { on: editVia.target_key } : {}),
                      ...(field.link?.from
                        ? { from: field.link.from }
                        : editVia ? { from: "pid" } : {}),
                      single: editLinkSingle,
                      via: editVia ?? undefined } }),
      });
      if (editNoteDirty) onNote(note);
      onClose();
      return;
    }
    if (editRetypeTouched && onRetype) {
      const renames = optionRenames();
      onRetype(
        editType,
        needsOptions(editType) ? editOptions : undefined,
        {
          ...(renames.length ? { renames } : {}),
          ...(editType === "rating" ? { max: retypeMaxValue } : {}),
          // ⭐ Wave-27 item 13 (R13) β€” always sent for a code column, `plain` included: the
          // host clears the key on plain, so this is what makes the picker reversible.
          ...(editType === "code" ? { code: { language: editCodeLanguage } } : {}),
          ...(needsOptions(editType)
            ? {
                colorCodeOptions: editColorCode,
                ...(Object.keys(editChoice.colors).length
                  ? { optionColors: editChoice.colors }
                  : {}),
              }
            : {}),
          ...(editType === "automation"
            ? {
                automation: {
                  kind: editAutomationKind,
                  source: "record_url_field" as const,
                  urlField: editAutomationUrlField,
                },
              }
            : {}),
          // ⭐⭐ Wave-34 (R13) β€” RETYPING A COLUMN TO AI ENRICHMENT CARRIES ITS BAG, or the
          // server refuses the whole write: `_clean_field` returns None for an `ai_enrich`
          // column with no prompt. The edit pane renders the same panel the create pane does
          // (`ExtraTypeEditor` is mounted with `kind={editType}`), so the draft the user just
          // filled in is the one sent here.
          ...(editType === "ai_enrich"
            ? {
                aiEnrich: {
                  prompt: aiEnrich.prompt.trim(),
                  ...(aiEnrich.model.trim() ? { model: aiEnrich.model.trim() } : {}),
                  maxTokens: aiEnrich.maxTokens,
                  trigger: {
                    mode: aiEnrich.mode,
                    ...(aiEnrich.mode === "schedule" && aiEnrich.cron.trim()
                      ? { cron: aiEnrich.cron.trim() }
                      : {}),
                  },
                  overwrite: aiEnrich.overwrite,
                },
              }
            : {}),
          ...(editNameDirty ? { label: cleanRename } : {}),
        }
      );
    } else if (editFormulaTouched && onFormula) {
      onFormula(stripLeadingEquals(editFormulaText).trim(), editNameDirty ? cleanRename : undefined);
    } else if (editNameDirty && onRename) {
      onRename(cleanRename);
    }
    // Item 21 β€” the period is an INDEPENDENT property of a measure column, not a branch of
    // the identity edit, so it applies ALONGSIDE whatever the chain above did rather than
    // instead of it: renaming "Sales YTD" to "Sales" and re-pointing it at the last 90 days
    // is one edit to the user and must not silently drop half of itself.
    if (canPeriod && (periodChanged || measureChanged))
      onPeriod!(draftWindow ?? field.measure!.window,
                measureChanged ? editMeasureKey : undefined);
    if (editNoteDirty) onNote(note);
    onClose();
  };

  /**
   * Fields this column can be CHANGED to, split per wave-2 item 5: the "Pre-set fields" group
   * (the shared contract's predicate, `source === 'odoo' && !custom`) versus "Your fields" β€”
   * the overlay stratum and user-created columns. Hidden fields included in both: "change this
   * to Notes" is the whole point, and swapping BACK to a hidden custom field is the documented
   * restore path. The locked primary column cannot be swapped.
   *
   * ⭐⭐ W40-T24 β€” NOR CAN A PRE-SET ONE, which is `offer.swap`. This list is what the picker
   * would contain; `swapOffered` is whether the picker exists at all, and it is read twice (the
   * control itself, and the focus fallback that has to know whether the control is there).
   */
  const swapOptions = offerableFields(fields).filter((f) => f.key !== field.key);
  const presetSwap = swapOptions.filter((f) => f.source === "odoo" && !f.custom);
  const yourSwap = swapOptions.filter((f) => !(f.source === "odoo" && !f.custom));
  const swapOffered = offer.swap && swapOptions.length > 0;

  // Item 8c β€” the period draft is valid when it normalizes and differs from what the field
  // already has. Compared through normalizeWindow so `{kind:'ltm'}` and `{kind:'ltm', n:undefined}`
  // read as the same window.
  // ⭐ Wave-23 C8 (owner item 4 / R9) β€” FIRST in the chain, because it is the most specific true
  // thing about the column and the branches below it were saying something false. An
  // `automation` or `metric` column, and every column an automation SPAWNED (the `automation`
  // tag), is overlay-sourced and non-derived, so it fell through to "Editable overlay field" β€”
  // which is what the wash now visibly contradicts. ONE line, no second sentence about what an
  // automation is (R13 / DESIGN.md Β§4): the person reading a column menu is deciding whether to
  // type in it, and "filled by automation" is the whole answer.
  // ⭐ Wave-25 C3/R7 β€” AHEAD of the machine line, because a profile column is the one cell on
  // the row a person is SUPPOSED to fill, and "filled by automation" would say the opposite. It
  // states the consequence rather than the mechanism: clearing this cell also clears the
  // columns the enrichment wrote, and a person who does not know that reads the wipe as a bug.
  // That is the one fact worth a menu line here (DESIGN.md Β§4 β€” never over-explain).
  /**
   * ⭐⭐ 2026-08-10 β€” WHICH SIDE OF THE RELATION IS THIS? (owner: "a linked field should spawn in
   * both databases")
   *
   * The spawn itself was already there β€” `user_tables.sync_reciprocal_link` creates the backlink
   * on the target for every ordinary link, and the two engines declare BOTH directions of their
   * derived links themselves. What was missing is the half a user can actually see: three
   * genuinely different columns all rendered as chips of linked rows and all described as
   * "Editable overlay field", including the computed reciprocal, which is not editable at all.
   *
   * The three, and the one fact that separates them:
   *   ordinary    β€” no `on`, no `inverse`. YOU pick the records. This is the stored truth.
   *   reciprocal  β€” `inverse` names the source field. Computed from the other side's picks;
   *                 typing here is refused (`is_computed_cell`), so saying "editable" was a lie.
   *   derived     β€” `on` names a column in the target that already holds this row's key. The
   *                 engine owns it; there is no picking on either side.
   *
   * ⚠ Read through `isDerivedLink`, never a fourth hand-rolled "does the bag have an `on`" β€”
   * `user_tables`' own note warns that a fourth reader is how one of them keeps answering yes
   * after the others stop.
   * ⚠ AHEAD of `isMachineOwned` for links only. "Filled by automation" is TRUE of a preset
   * derived link and it is the less specific true thing: the reader is deciding whether they can
   * click into this cell and pick something, and which side they are on is that answer.
   */
  const linkTargetLabel =
    field.type === "link"
      ? linkTargets.find((t) => t.key === field.link?.table)?.label ?? ""
      : "";
  const linkSideLine =
    field.type !== "link"
      ? null
      : field.link?.inverse
        ? `Linked from ${linkTargetLabel || "another database"} Β· rows that point here`
        : isDerivedLink(field)
          ? `Links to ${linkTargetLabel || "another database"} Β· matched automatically`
          : `Links to ${linkTargetLabel || "another database"} Β· you pick the records`;
  const typeLineBase = isProfileField(field)
    ? "Instagram profile Β· clearing it clears the enriched columns"
    : linkSideLine
    ? linkSideLine
    : isMachineOwned(field)
    ? "Filled by automation"
    : field.measure
    ? (field.custom && canEditDefinition ? "Metric, definition editable" : "Metric, read-only")
    : field.type === "formula"
      ? "Formula field, computed"
      : field.type === "autonumber"
        ? "Autonumber, read-only"
        : AUDIT_FIELD_TYPES.includes(field.type)
          ? `${TYPE_LABELS[field.type]}, read-only`
        : field.type === "created_time"
          ? "Created time, read-only"
          : field.derived
            ? "Read-only, derived"
            : field.source === "odoo"
              ? "Read-only source field"
              : "Editable overlay field";
  // Item 9c β€” a cohort-scoped def says so wherever its identity is stated (contract:
  // "defs may come back carrying scope: 'cohort' (label it)").
  const typeLine =
    field.scope === "cohort" ? `${typeLineBase} Β· this cohort only` : typeLineBase;

  /** Wave-5 item 10 β€” which format editor this field gets, if any. */
  // An Odoo float column arrives as type "number", outside FieldType, and is a number field.
  const formatKind: "number" | "date" | null =
    field.type === "int" || field.type === "currency" || field.type === "formula" ||
    field.type === "pct" || field.type === "rollup" || (field.type as string) === "number"
      ? "number"
      : field.type === "date" || field.type === "created_time" || field.type === "last_modified_time"
        ? "date"
        : null;
  const canEditNumberPolicy = isUserTable && canEditDefinition && !!onFieldConfig &&
    (field.type === "int" || field.type === "currency" || field.type === "pct");

  /**
   * Item 6 β€” Insert left/right (and Add at end) jump STRAIGHT to the create form: name + type
   * autofocused, and none of the note/change-field/other-column chrome rendered around it.
   */
  // R8: a retained pane or a caller-supplied initial pane cannot expose schema controls.
  if (!embedded) {
  if (position && canAddField) {
    return (
      <AnchoredOverlay
        anchor={state.anchor}
        className="cg-column-menu"
        onDismiss={onClose}
        role="dialog"
        ariaLabel={
          position === "end" ? "Add field" : `Insert field ${position} of ${field.label}`
        }
        // The SAME selector as the full-menu branch, so React reconciling the two states does
        // not re-run the overlay's focus effect (its deps see one constant) β€” which would steal
        // focus to the first button a frame after the name input autofocused.
        initialFocus="[data-overlay-autofocus]"
        dataKind="column-menu"
      >
        <PaneHead
          title={
            position === "end"
              ? "Add field"
              : position === "left"
                ? "Insert field left"
                : "Insert field right"
          }
          sub={position === "end" ? "Added as the last column" : `Next to ${field.label}`}
          onClose={onClose}
        />
        <div className="cg-column-create">
          {/* ⭐⭐ W36-T07 (owner item 10) β€” *"the Field agent needs to have an ability to chat
              with, so the user can further align request"*. The agent fills THIS form rather
              than owning a second creation path: accepting a proposal seeds the name, the kind
              and any options, and the ordinary Add-field button is still what commits them. One
              create door, two ways to reach it.
              β›” R11 β€” the Metric kind is a target the agent can propose, not a thing being
              retired. Every prior instruction to retire it is REVOKED (owner, 2026-08-18). */}
          {askAgent ? (
            <FieldAgentChat
              existing={fields}
              linkTargets={linkTargets}
              database={tableKey}
              onCancel={() => setAskAgent(false)}
              onAccept={(proposal: FieldProposal) => {
                if (proposal.existingField) {
                  if (offerableFields(fields).some((f) => f.key === proposal.existingField)) {
                    onChangeField(proposal.existingField);
                    onClose();
                  }
                  return;
                }
                setLabel(proposal.label);
                setLabelTouched(true);
                pickKind(proposal.kind);
                if (proposal.linkTarget && linkTargets.some((t) => t.key === proposal.linkTarget?.key))
                  setLinkTable(proposal.linkTarget.key);
                if (proposal.options && proposal.options.length)
                  setCreateOptionDrafts(optionDrafts(proposal.options));
                setAskAgent(false);
              }}
            />
          ) : (
            <button
              type="button"
              className="cg-fagent-open"
              onClick={() => setAskAgent(true)}
            >
              Describe it instead, and the field agent will propose one
            </button>
          )}
          <label>
            <span>Name</span>
            <input
              className="cg-input"
              autoFocus
              data-overlay-autofocus
              value={effectiveLabel}
              onChange={(event) => {
                setLabel(event.target.value);
                setLabelTouched(true);
              }}
              onKeyDown={(event) => event.key === "Enter" && create()}
            />
          </label>
          <div className="cg-type-block">
            <span className="cg-type-title">Field type</span>
            {/* Owner item 8 (2026-07-31): every type wears its own mark β€” the same TYPE_SHAPES
                glyph its column header wears. A native <option> cannot hold an SVG (the ruling
                iconShapes.ts records), so the control is a find box over a listbox of real
                rows, Airtable-style. The measure row appears exactly when the host offers
                measures β€” the same availability rule as the filter's measure conditions. */}
            <TypePicker
              value={rollupPreset ?? kind}
              onPick={pickKind}
              offerMeasure={measures.length > 0}
              offerGeocode={offerGeocode}
              offerPresets
              isUserTable={isUserTable}
            />
          </div>
          {kind === "measure" && (
            <>
              {/* C-NAME β€” the row asked "Measure"/"Choose a measure…", which named the
                  INTERNAL concept at the user. What the person is picking is the business
                  number ("Sales", "Gross margin"), so the label says that. */}
              <label>
                <span>Number</span>
                {/* Item 20 (C-FLDSEL) β€” "Choose a number…" was an `<option value="">` that
                    only rendered while nothing was chosen; it is the picker's PLACEHOLDER
                    now, so the prompt is a state of the control rather than a row of the
                    vocabulary that could be picked. */}
                <FieldSelectButton
                  ariaLabel="Number to summarise"
                  placeholder="Choose a number…"
                  value={chosenMeasure ? measureKey : undefined}
                  onChange={setMeasureKey}
                  fields={measures.map((m) => ({
                    key: m.key, label: m.label, type: "measure" as const,
                  }))}
                />
              </label>
              <label>
                <span>Period</span>
                <span className="cg-measure-window">
                  <WindowPicker window={measureWindow} onWindow={setMeasureWindow} />
                </span>
              </label>
              {/* The helper line now carries what the old label's parenthetical was doing β€”
                  "(over a period)" β€” plus an example, because "Metric" alone does not say
                  that the answer moves with the window above it. */}
              <div className="cg-field-hint">
                A total, average or count over the period you choose, such as Sales, last 90
                days. Computed for every customer, and read-only.
              </div>
            </>
          )}
          {/* ⭐⭐ W37-T22 (owner item 15 / R4, contract C7) β€” THE GEOCODE PANE. It sits beside the
              Metric pane above rather than inside `ExtraTypeEditor`, because that editor
              dispatches on `FieldType` and this is a pseudo-kind: putting it there would mean
              widening the editor's own union for a kind no stored column ever has. */}
          {kind === "geocode" && (
            <>
              <label>
                <span>Address column</span>
                <FieldSelectButton
                  ariaLabel="Column holding the address"
                  placeholder="Choose a column…"
                  value={geocodeAddressField || undefined}
                  onChange={setGeocodeAddressField}
                  fields={addressFields.map((f) => ({
                    key: f.key, label: f.label, type: f.type,
                  }))}
                />
              </label>
              <label>
                <span>Country (optional)</span>
                <input
                  type="text"
                  value={geocodeCountry}
                  maxLength={2}
                  placeholder="US"
                  aria-label="Two letter country code the lookup is limited to"
                  onChange={(event) => setGeocodeCountry(event.target.value)}
                />
              </label>
              {/* β›” NO DASH OF ANY KIND in this sentence, and `web_prose` cannot see a wrapped JSX
                  sentence, so it is on the author. ⭐ It says the two things a person cannot
                  discover by clicking: nothing runs by itself (R3, and under R14 the reason is
                  the free geocoder's rate limit rather than a bill), and what the cell will hold
                  (C7, a coordinate pair a map or a formula can read). */}
              <div className="cg-field-hint">
                Fills each row with a latitude and longitude read from the column you choose, so
                the map and any formula can use them. A country code keeps the lookup in one
                place, which matters when a street name exists in several. Nothing is looked up
                until you run it on the records you pick.
              </div>
            </>
          )}
          {kind === "if" && <IfStatementEditor definition={ifDraft} fields={ifSourceFields}
            onChange={setIfDraft} />}
          <ExtraTypeEditor
            aiEnrich={aiEnrich}
            onAiEnrich={patchAiEnrich}
            kind={kind}
            fields={fields}
            formulaText={formulaText}
            onFormulaText={setFormulaText}
            formulaError={formulaCheck.ok ? null : formulaCheck.error ?? null}
            maxValue={maxValue}
            onMaxValue={setMaxValue}
            codeLanguage={codeLanguage}
            onCodeLanguage={setCodeLanguage}
            idPrefix="cg-create"
            automationKind={automationKind}
            onAutomationKind={setAutomationKind}
            automationUrlField={automationUrlField}
            onAutomationUrlField={setAutomationUrlField}
            linkTargets={linkTargets}
            linkTable={linkTable}
            onLinkTable={setLinkTable}
            linkSingle={linkSingle}
            onLinkSingle={setLinkSingle}
            linkSelectionMode={linkSelectionMode}
            onLinkSelectionMode={setLinkSelectionMode}
            linkSelectionFilter={linkSelectionFilter}
            onLinkSelectionFilter={setLinkSelectionFilter}
            hop={{
              topics: hopTopics,
              windows: hopTopicOffer.windows,
              scopeKey: hopScopeKey,
              draft: hopDraft,
              onDraft: patchHopDraft,
            }}
            rollupPreset={rollupPreset}
            rollupMode={rollupMode}
            onRollupMode={setRollupMode}
            rollupSourceOffer={rollupSourceOffer}
            rollupSource={rollupSource}
            onRollupSource={setRollupSource}
            rollupLink={rollupLink}
            onRollupLink={(value) => {
              setRollupLink(value);
              setRollupField("");
              setRollupSortBy("");
              setRollupDistinctBy("");
              // Every condition names a column of the OLD target, so both lists are cleared for
              // the same reason: a leaf pointing at a field the new table does not have is a
              // filter that can only ever match nothing.
              setRollupWhere([]);
              setRollupConditions([]);
            }}
            rollupField={rollupField}
            onRollupField={setRollupField}
            rollupFn={rollupFn}
            onRollupFn={setRollupFn}
            rollupLimit={rollupLimit}
            onRollupLimit={setRollupLimit}
            rollupSortBy={rollupSortBy}
            onRollupSortBy={setRollupSortBy}
            rollupDistinctBy={rollupDistinctBy}
            onRollupDistinctBy={setRollupDistinctBy}
            rollupWhere={rollupWhere}
            onRollupWhere={setRollupWhere}
            rollupWhereConj={rollupWhereConj}
            onRollupWhereConj={setRollupWhereConj}
            rollupConditions={rollupConditions}
            onRollupConditions={setRollupConditions}
            rollupConditionConj={rollupConditionConj}
            onRollupConditionConj={setRollupConditionConj}
          />
          {needsOptions(kind) && (
            <OptionsEditor
              idPrefix="cg-create-option"
              drafts={createOptionDrafts}
              onDrafts={setCreateOptionDrafts}
              colorCode={createColorCode}
              onColorCode={setCreateColorCode}
              type={kind}
              maxOptions={optionLimit}
            />
          )}
          {createDefaultOffered && supportsDefaultValue(kind) && <DefaultValueEditor type={kind}
            enabled={createDefaultEnabled} value={createDefaultValue} options={options}
            onEnabled={setCreateDefaultEnabled} onValue={setCreateDefaultValue} />}
          {kind === "user" && (
            <div className="cg-field-hint">
              {userOptions.length
                ? `${userOptions.length} people can be assigned, from your user list.`
                : "No user list yet, so there is no one to assign."}
            </div>
          )}
          {scopeChoice && <ScopeControl value={scopeDraft} onValue={setScopeDraft} />}
          <div className="cg-form-actions">
            <button
              type="button"
              className="cg-btn cg-btn--primary"
              disabled={!canCreate}
              onClick={create}
            >
              Create field
            </button>
            <button
              type="button"
              className="cg-btn"
              // Opened straight into the form (the header "+")? Cancel means close β€”
              // there is no action list behind it to fall back to.
              onClick={() => (initialPosition ? onClose() : setPosition(null))}
            >
              Cancel
            </button>
          </div>
        </div>
      </AnchoredOverlay>
    );
  }

  // ------------------------------- EDIT FIELD, DESCRIPTION ONLY (W41-T31, instruction 1, R19)
  /**
   * ⭐⭐ A PRE-SET FIELD'S "Edit field", AND IT IS A PANE OF ITS OWN rather than the full one
   * with six things switched off.
   *
   * Owner: *"A pre-set field's 'Edit field' should not exist except to change the description;
   * the pre-set description is the one place a user adds a description. Standardize."* A
   * separate return is what makes the first half literally true: there is no Name box, no type
   * picker, no retype, no Change field, no period row and no delete IN THE TREE, so none of
   * them can be reached by a condition that drifts three waves from now. It is also how the
   * ticket's last clause is proved: the pane below is not touched, so a non-pre-set field's
   * Edit field cannot have changed.
   *
   * β›” MUTUALLY EXCLUSIVE BY CONSTRUCTION, NOT BY ORDERING. `canEditDescription` is true only
   * when `schemaLocked` is, and `canEditDefinition` is false whenever `schemaLocked` is true β€”
   * so no field can satisfy both, and moving this block would change nothing.
   */
  if (pane === "edit" && canEditDescription) {
    return (
      <AnchoredOverlay
        anchor={state.anchor}
        className="cg-column-menu"
        onDismiss={onClose}
        role="dialog"
        ariaLabel={`Edit field ${field.label}`}
        initialFocus="[data-overlay-autofocus]"
        dataKind="column-menu"
      >
        <PaneHead title="Edit field" sub={typeLine} onClose={onClose} />
        <div className="cg-column-create cg-field-edit cg-desc-only">
          {/* DESIGN section 4, the three locks: the mark NAMES WHICH LOCK. This one says
              "definition", so it cannot be read as "you cannot type here" (a locked database)
              nor as a curated row set (a locked view). One line, and it leads with what you
              CAN do, because the pane exists to offer that. Worded once, in `fieldClass.ts`. */}
          <span className="cg-field-hint">{PRESET_DESCRIPTION_ONLY_HINT}</span>
          <label className="cg-edit-description">
            <span>Description</span>
            {/* `field.description` is schema metadata and `field.note` is the workspace edit.
                The editor owns the latter; inherited implementation copy does not belong above
                a user's description input. */}
            {/* β›”β›” MARKED UNCONDITIONALLY, and the full pane's conditional is exactly why.
                There it reads `!nameIsFocusTarget && !swapOffered`, and `nameIsFocusTarget` is
                `!!onRename || editingRelational` β€” true for a pre-set `link` column, which
                `isSchemaLocked` does not exclude. Copied verbatim the attribute would evaluate
                to `undefined` on that column, `initialFocus`'s `querySelector` would match
                nothing, and the dialog would open with the keyboard still on the grid header
                behind it (the W40-T24 defect, and one no gate in this repo can see). Here the
                textarea is the ONLY control before the actions, so it is the focus target
                unconditionally and exactly one element carries the attribute. */}
            <textarea
              className="cg-input"
              rows={3}
              data-overlay-autofocus
              value={note}
              placeholder="Add a description…"
              onChange={(event) => setNote(event.target.value)}
            />
          </label>
          {/* R19 β€” A USER'S EDIT WINS FOREVER, so there has to be a way to give it up.
              β›” GATED ON C8's MARK, STRICTLY (`descriptionResetOffered` in `fieldClass.ts`):
              absent means "not built yet", never "false", so an unbuilt server renders no link
              rather than one claiming an edit exists. It clears the DRAFT and leaves the
              committing to Save, which is this pane's one-Save model everywhere else β€” and
              clearing makes the draft dirty, so Save lights up the moment you click it.
              ⚠ THE SECOND CLAUSE READS THE DRAFT, and the first reads the SAVED field, which is
              why both are here. `descriptionResetOffered` answers "is there a committed edit to
              give up"; once the box is empty β€” cleared by this link, or by hand β€” the link has
              nothing left to do, so it goes rather than sitting there doing visibly nothing on a
              second click. */}
          {descriptionResetOffered(field) && note.trim() !== "" && (
            <button
              type="button"
              className="cg-desc-reset"
              onClick={() => setNote("")}
            >
              {DESCRIPTION_RESET_LABEL}
            </button>
          )}
          <div className="cg-form-actions">
            <button
              type="button"
              className="cg-btn cg-btn--primary"
              disabled={!canSaveEdit}
              onClick={applyEdit}
            >
              Save
            </button>
            <button
              type="button"
              className="cg-btn"
              // Item 12's rule, and this pane can be opened directly too (`viewModes` passes
              // `initialPane="edit"`): Back means close when there is no action list behind it.
              onClick={() => (initialPane ? onClose() : setPane("menu"))}
            >
              Back
            </button>
          </div>
        </div>
      </AnchoredOverlay>
    );
  }

  // ------------------------------------------------------------ EDIT FIELD pane (item 8)
  // Owner item 8 (2026-07-31): ONE window owning the field's identity β€” name, type (with the
  // per-type choices/stars/formula editors), and the Change-field control. Absorbs the former
  // Rename and Change-field panes.
  if (pane === "edit") {
    return (
      <AnchoredOverlay
        anchor={state.anchor}
        className="cg-column-menu"
        onDismiss={onClose}
        role="dialog"
        ariaLabel={`Edit field ${field.label}`}
        initialFocus="[data-overlay-autofocus]"
        dataKind="column-menu"
      >
        <PaneHead title="Edit field" sub={typeLine} onClose={onClose} />
        <div className="cg-column-create cg-field-edit">
          {nameIsFocusTarget ? (
            <label>
              <span>Name</span>
              <input
                className="cg-input"
                autoFocus
                data-overlay-autofocus
                value={renameDraft}
                onChange={(event) => setRenameDraft(event.target.value)}
                onKeyDown={(event) => event.key === "Enter" && applyEdit()}
              />
            </label>
          ) : (
            <label>
              <span>Name</span>
              <input
                className="cg-input"
                value={field.label}
                disabled
                aria-label="Field name (read-only)"
              />
              <span className="cg-field-hint">
                A source field keeps its name and type from the data source.
              </span>
            </label>
          )}
          <label className="cg-edit-description">
            <span>Description</span>
            {/* ⭐⭐ W40-T24 β€” LAST IN THE FOCUS PRECEDENCE, and the only reason it is marked at
                all: on a pre-set column the Name box is disabled and the swap picker is now
                gone, so without this the pane would open with `[data-overlay-autofocus]` matching
                nothing and the keyboard left outside the dialog. The Description is the one
                control a pre-set column still owns, which makes it the honest landing spot as
                well as the available one. `undefined` REMOVES the attribute (React drops it), so
                exactly one element in the pane ever carries it. */}
            <textarea
              className="cg-input"
              rows={3}
              data-overlay-autofocus={
                !nameIsFocusTarget && !swapOffered ? true : undefined
              }
              value={note}
              placeholder="Add a description…"
              onChange={(event) => setNote(event.target.value)}
            />
          </label>
          {!onRetype && needsOptions(field.type) && <ChoicePreview field={field} />}
          {editDefaultOffered && <DefaultValueEditor type={editType}
            enabled={editDefaultEnabled} value={editDefaultValue} options={editOptions}
            onEnabled={setEditDefaultEnabled} onValue={setEditDefaultValue} />}
          {/* C5-AUTOFIELD β€” an EXISTING automation column edits its CONFIG, not its type.
              ⚠ This guard is load-bearing, not tidiness. `automation` is excluded from
              RETYPE_TYPES (see its note), so rendering the picker for one would show a
              listbox whose current value is not among its options β€” the failure recorded in
              [[cg-condition-builder-items]], where a control missing its own value silently
              presents the FIRST option as if it were the selection. One Save later the column
              is a different type and its statuses are editable text. */}
          {/*
            ⭐⭐ 2026-08-09 (owner) β€” AN EXISTING ROLLUP/LINK EDITS ITS CONFIGURATION HERE.

            Owner: *"even when i click edit field for rollup, it doesn't actually show me the
            configuration that I use to generate it, it only shows change to a different field."*
            This branch is that configuration, seeded from the stored bag, and it takes the same
            `ExtraTypeEditor` the create pane uses so the two can never offer different controls
            for the same column.

            β›” IT REPLACES THE TYPE PICKER, exactly as `automation` does one branch down, and for
            the sharper version of that reason. `RETYPE_TYPES` contains `rollup`, so the picker
            rendered here would have let Save re-emit the column with no bag β€” and the host's
            `retypeField` refuses a non-`custom` field outright, so on a pre-set rollup the Save
            button was wired to nothing at all. Changing a rollup INTO another type stays
            available through "Change field" below, which is the door that means "show something
            else in this column".
          */}
          {editingRelational ? (
            <div className="cg-type-block">
              <span className="cg-type-title">
                {field.type === "rollup" ? "Rollup" : "Linked records"}
              </span>
              <ExtraTypeEditor
                aiEnrich={aiEnrich}
                onAiEnrich={patchAiEnrich}
                kind={field.type}
                fields={fields}
                linkTargets={linkTargets}
                formulaText={editFormulaText}
                onFormulaText={setEditFormulaText}
                formulaError={null}
                maxValue={retypeMaxValue}
                onMaxValue={setRetypeMaxValue}
                codeLanguage={editCodeLanguage}
                onCodeLanguage={setEditCodeLanguage}
                idPrefix="cg-edit"
                linkTable={editLinkTable}
                onLinkTable={setEditLinkTable}
                linkSingle={editLinkSingle}
                onLinkSingle={setEditLinkSingle}
                linkSelectionMode={editLinkSelectionMode}
                onLinkSelectionMode={setEditLinkSelectionMode}
                linkSelectionFilter={editLinkSelectionFilter}
                onLinkSelectionFilter={setEditLinkSelectionFilter}
                hop={{
                  topics: hopTopics,
                  windows: hopTopicOffer.windows,
                  scopeKey: hopScopeKey,
                  draft: editHopDraft,
                  onDraft: patchEditHopDraft,
                }}
                rollupPreset={rollupPresetOf(editRollup)}
                rollupSourceOffer={rollupSourceOffer}
                rollupMode={editRollup.source ? "source" : "link"}
                // β›” A MODE SWITCH REPLACES THE BAG, it does not merge into it. `_clean_rollup`
                // reads `source` first and returns before it ever looks at `link`, so a bag
                // carrying both would ship keys the store silently drops β€” dead payload that
                // later reads as configuration.
                onRollupMode={(mode) =>
                  setEditRollup(mode === "source"
                    ? { source: { topic: "", measure: "", groupBy: "", on: "", window: "ytd" } }
                    : { link: "", fn: "sum" })
                }
                rollupSource={editRollup.source ?? {
                  topic: "", measure: "", groupBy: "", on: "", window: "ytd",
                }}
                onRollupSource={(source) => patchEditRollup({ source })}
                rollupLink={editRollup.link ?? ""}
                onRollupLink={(value) =>
                  // Same reset the create pane performs: every other key names a column of the
                  // OLD target, and a leaf pointing at a field the new table lacks is a filter
                  // that can only ever match nothing.
                  setEditRollup({ link: value, fn: editRollup.fn ?? "sum" })
                }
                rollupField={editRollup.field ?? ""}
                onRollupField={(value) => patchEditRollup({ field: value })}
                rollupFn={editRollup.fn ?? "sum"}
                onRollupFn={(value) => patchEditRollup({ fn: value })}
                rollupLimit={editRollup.limit ?? 0}
                onRollupLimit={(value) => patchEditRollup({ limit: value })}
                rollupSortBy={editRollup.sortBy ?? ""}
                onRollupSortBy={(value) =>
                  patchEditRollup(value
                    ? { sortBy: value, sortDir: editRollup.sortDir ?? "desc",
                        limit: editRollup.limit || 1 }
                    : { sortBy: "" })
                }
                rollupDistinctBy={editRollup.distinctBy ?? ""}
                onRollupDistinctBy={(value) => patchEditRollup({ distinctBy: value })}
                rollupWhere={editRollup.where ?? []}
                onRollupWhere={(value) =>
                  patchEditRollup({ where: value,
                                    whereConj: editRollup.whereConj ?? "and" })
                }
                rollupWhereConj={editRollup.whereConj ?? "and"}
                onRollupWhereConj={(value) => patchEditRollup({ whereConj: value })}
                rollupConditions={editRollup.conditions ?? []}
                onRollupConditions={(value) =>
                  patchEditRollup({ conditions: value,
                                    conditionConj: editRollup.conditionConj ?? "and" })
                }
                rollupConditionConj={editRollup.conditionConj ?? "and"}
                onRollupConditionConj={(value) => patchEditRollup({ conditionConj: value })}
              />
            </div>
          ) : field.type === "autonumber" ? (
            <div className="cg-type-block">
              <span className="cg-type-title">Autonumber</span>
            </div>
          ) : AUDIT_FIELD_TYPES.includes(field.type) ? (
            <div className="cg-type-block">
              <span className="cg-type-title">{TYPE_LABELS[field.type]}</span>
              <div className="cg-field-hint">Read-only. {TYPE_DESCRIPTIONS[field.type]}</div>
            </div>
          ) : editingIf ? (
            <IfStatementEditor definition={editIf} fields={editIfSourceFields} onChange={setEditIf} />
          ) : onRetype && field.type === "automation" ? (
            <div className="cg-type-block">
              <span className="cg-type-title">Automation</span>
              <ExtraTypeEditor
                aiEnrich={aiEnrich}
                onAiEnrich={patchAiEnrich}
                kind="automation"
                fields={fields}
                formulaText={editFormulaText}
                onFormulaText={setEditFormulaText}
                formulaError={null}
                maxValue={retypeMaxValue}
                onMaxValue={setRetypeMaxValue}
                codeLanguage={editCodeLanguage}
                onCodeLanguage={setEditCodeLanguage}
                idPrefix="cg-edit"
                automationKind={editAutomationKind}
                onAutomationKind={setEditAutomationKind}
                automationUrlField={editAutomationUrlField}
                onAutomationUrlField={setEditAutomationUrlField}
              />
            </div>
          ) : onRetype ? (
            <>
              <div className="cg-type-block">
                <span className="cg-type-title">Field type</span>
                {/* The same find-box-over-icon-listbox the create pane wears (owner item 8 of
                    the PREVIOUS wave) β€” one control for "pick a type" everywhere. */}
                <TypePicker
                  value={editType}
                  onPick={(k) => setEditType(k as FieldType)}
                  offerMeasure={false}
                  offerPresets={false}
                  isUserTable={isUserTable}
                  offerGeocode={
                    /* β›” FALSE ON PURPOSE, and stated rather than omitted: this is the RETYPE
                       picker, and a geocode column is not a type an existing column can BECOME.
                       Its bag has to be authored, and `canCreateSwap` passes none of the
                       pseudo-kind setters (a pre-existing defect its own comment books). */
                    false
                  }
                  only={RETYPE_TYPES}
                />
              </div>
              {/*
                ⭐⭐ 2026-08-07 (D-79's last half) β€” MARK THIS COLUMN AS AN INSTAGRAM PROFILE.
                Wave 25 shipped this flag's READER everywhere (the type line above, the cell
                validator, R6's clear-on-write, the one-per-table refusal) and never its WRITER,
                so `enrich_instagram` could not be bound to any database somebody made
                themselves β€” the owner's *"on a schedule, enrich these sets of influencer
                names"*. One checkbox; the server door already existed.

                β›” `text` ONLY, and it mirrors `_clean_field` rather than restating a rule: a
                flag on a select or an int would promise a validated handle to a cell nothing
                validates, and the server REFUSES it. Offering it there would be a control whose
                only outcome is a 400.
                ⚠ The one-per-table rule is NOT re-implemented here. The server refuses a second
                one with a sentence naming the column that already has it, and `patchTableField`
                surfaces that sentence verbatim β€” a client copy of the rule is how two doors
                start disagreeing about which column is the profile.
              */}
              {onProfileFlag && editType === "text" && (
                <label className="cg-check-row">
                  <input
                    type="checkbox"
                    checked={isProfileField(field)}
                    onChange={(event) => onProfileFlag(field.key, event.target.checked)}
                  />
                  <span>Instagram profile column</span>
                </label>
              )}
              {onProfileFlag && editType === "text" && (
                <div className="cg-field-hint">
                  {isProfileField(field)
                    ? "Automations enrich from this column. Clearing a cell also clears that "
                      + "row's enriched columns."
                    : "Lets an Enrich step know which column holds the handle. A database has "
                      + "at most one."}
                </div>
              )}
              {editType === "code" && (
                <label>
                  <span>Language</span>
                  <select
                    className="cg-select"
                    value={editCodeLanguage}
                    aria-label="Code language"
                    onChange={(event) => setEditCodeLanguage(event.target.value)}
                  >
                    {/* Explicit `value` on every option: a <select> whose value names nothing
                        renders its FIRST option and reports a choice nobody made. */}
                    {CODE_LANGUAGES.map((lang) => (
                      <option key={lang} value={lang}>
                        {CODE_LANGUAGE_LABELS[lang]}
                      </option>
                    ))}
                  </select>
                  <span className="cg-field-hint">
                    Chooses how the snippet is coloured. It is never run.
                  </span>
                </label>
              )}
              {editType === "rating" && (
                <label>
                  <span>Number of stars</span>
                  <input
                    className="cg-input cg-rating-max"
                    type="number"
                    min={2}
                    max={10}
                    value={retypeMaxValue}
                    aria-label="Number of stars"
                    onChange={(event) => {
                      const n = Math.round(Number(event.target.value));
                      setRetypeMaxValue(
                        Number.isFinite(n) ? Math.max(2, Math.min(10, n)) : 5
                      );
                    }}
                  />
                </label>
              )}
              {needsOptions(editType) && (
                <OptionsEditor
                  idPrefix="cg-edit-option"
                  drafts={editOptionDrafts}
                  onDrafts={setEditOptionDrafts}
                  colorCode={editColorCode}
                  onColorCode={setEditColorCode}
                  type={editType}
                  maxOptions={optionLimit}
                  onRemove={onChoiceRemove ? (draft) => void requestOptionRemoval(draft) : undefined}
                />
              )}
              {needsOptions(editType) && (pendingRemoval || removalError) && (
                <div className="cg-option-confirm" role="alert">
                  {pendingRemoval ? (
                    <>
                      <strong>Remove {pendingRemoval.label}?</strong>
                      <span>{choiceRemovalMessage(pendingRemoval.cells)}</span>
                      <div className="cg-option-confirm-actions">
                        <button
                          type="button"
                          className="cg-btn"
                          disabled={removalBusy}
                          onClick={() => setPendingRemoval(null)}
                        >
                          Cancel
                        </button>
                        <button
                          type="button"
                          className="cg-btn cg-btn--primary"
                          disabled={removalBusy}
                          onClick={() => void confirmOptionRemoval()}
                        >
                          {removalBusy ? "Removing" : "Remove option"}
                        </button>
                      </div>
                    </>
                  ) : (
                    <span>{removalError}</span>
                  )}
                </div>
              )}
              {editType !== field.type && (
                <div className="cg-field-hint">
                  Changes {field.label} into a {TYPE_LABELS[editType].toLowerCase()} field,
                  keeping its name and its values as entered. Cells that cannot be read in
                  the new type show blank.
                </div>
              )}
            </>
          ) : null}
          {/* Item 21 (owner, 2026-08-02) β€” the PERIOD lives here, with the field's other
              properties, instead of floating above the action list on the menu pane. A metric
              column IS "a number over a period": the window is as much a part of its
              definition as its name is, and it was the one property you edited from a
              different window than every other one.
              It shares this pane's ONE Save (`applyEdit` applies it alongside a rename) β€”
              the old "Apply period" button became a second primary action in a pane that
              already had one, which is the ambiguity the move was supposed to remove. */}
          {canPeriod && measures.length > 0 && (
            <label className="cg-edit-measure">
              <span>Number</span>
              {/* W48C-T12 - the SAME picker the create pane renders, same aria-label, so the
                  two flows are equivalent by construction rather than by resemblance. */}
              <FieldSelectButton
                ariaLabel="Number to summarise"
                placeholder="Choose a number…"
                value={editMeasureKey || undefined}
                onChange={setEditMeasureKey}
                fields={measures.map((m) => ({
                  key: m.key, label: m.label, type: "measure" as const,
                }))}
              />
            </label>
          )}
          {canPeriod && (
            <label className="cg-edit-period">
              <span>Period</span>
              <span className="cg-measure-window">
                <WindowPicker
                  window={periodDraft ?? field.measure!.window}
                  onWindow={setPeriodDraft}
                />
              </span>
              <span className="cg-field-hint">
                The window this number is computed over, for every customer.
              </span>
            </label>
          )}
          {!onRetype && field.type === "formula" && onFormula && (
            <ExtraTypeEditor
              aiEnrich={aiEnrich}
              onAiEnrich={patchAiEnrich}
              kind="formula"
              fields={fields}
              formulaText={editFormulaText}
              onFormulaText={setEditFormulaText}
              formulaError={editFormulaCheck.ok ? null : editFormulaCheck.error ?? null}
              maxValue={retypeMaxValue}
              onMaxValue={setRetypeMaxValue}
              codeLanguage={editCodeLanguage}
              onCodeLanguage={setEditCodeLanguage}
              idPrefix="cg-edit"
            />
          )}
          <div className="cg-form-actions">
            <button
              type="button"
              className="cg-btn cg-btn--primary"
              disabled={!canSaveEdit}
              onClick={applyEdit}
            >
              Save
            </button>
            <button
              type="button"
              className="cg-btn"
              // Item 12 β€” opened STRAIGHT into this pane (the kanban's "Add option")? Back means
              // close, exactly as Cancel does in the directly-opened create form: there is no
              // action list behind a pane nobody navigated to.
              onClick={() => (initialPane ? onClose() : setPane("menu"))}
            >
              Back
            </button>
          </div>
          {/* -------- Change field (owner item 9, folded in here by owner item 8) --------
              ⭐⭐ W40-T24 (owner instruction 18, contract C2) β€” GATED ON THE PRE-SET LOCK, which
              it never was. The condition here used to be `!locked` alone, and `locked` means
              "is the pinned primary column" β€” so every contract column on every grid offered to
              be redefined into something else, which is the "choose a field dropdown that makes
              no sense" the owner reported about Supplier and was never only about Supplier.
              It is the SAME predicate that already withholds the Field-type picker and the
              editable Name box, which is what makes this pane say one thing about the column
              instead of three. `offer.swap` carries the `!locked` half (the primary column is the
              row identity and can never be swapped away); `swapOptions.length > 0` stays because
              an empty picker is its own fake affordance. */}
          {swapOffered && (
            <div className="cg-edit-swap">
              <span className="cg-type-title">Change field</span>
              <div className="cg-field-hint">
                Show a different field in this column. The current one is hidden, not lost.
              </div>
              <div className="cg-column-swap">
                {/* Item 20 β€” the ONE picker on this surface that keeps its groups, and it is
                    not a contradiction of the filter list's flatness: those three headings
                    separate DIFFERENT KINDS OF ACT (show a pre-set column Β· show one of yours Β·
                    make a new one), not three flavours of the same noun. The type mark does
                    the work the "New field" labels were doing on their own. */}
                <FieldSelectButton
                  className="cg-swap-select"
                  ariaLabel="Change this column to another field"
                  placeholder="Choose a field…"
                  // Focus falls here when the pane has no editable Name (a read-only source
                  // field): the swap picker is then the pane's first live control. Second in the
                  // precedence `nameIsFocusTarget` documents, and reading THAT rather than
                  // `!onRename` is what keeps the attribute on exactly one element.
                  overlayAutofocus={!nameIsFocusTarget}
                  value={swapTo || undefined}
                  onChange={setSwapTo}
                  fields={[
                    ...presetSwap.map((f) => ({
                      key: f.key, label: f.label, type: f.type, group: "Pre-set fields",
                    })),
                    ...yourSwap.map((f) => ({
                      key: f.key, label: f.label, type: f.type, group: "Your fields",
                    })),
                    ...FIELD_TYPES.map((t) => ({
                      key: NEW_PREFIX + t.value,
                      label: t.label,
                      type: t.value,
                      group: "New field",
                    })),
                  ]}
                />
                {!swapToNewType && (
                  <button
                    type="button"
                    className="cg-btn cg-btn--primary"
                    disabled={!swapTo}
                    onClick={() => {
                      onChangeField(swapTo);
                      onClose();
                    }}
                  >
                    Change
                  </button>
                )}
              </div>
              {/* The "New field" half: name it (and give it choices/its formula/its stars
                  when the type needs them), then create-and-swap in one motion. */}
              {swapToNewType && (
                <div className="cg-column-create cg-swap-create">
                  <label>
                    <span>New {(swapToNewType === "if" ? "If statement" : TYPE_LABELS[swapToNewType]).toLowerCase()} field</span>
                    <input
                      className="cg-input"
                      autoFocus
                      value={swapLabel}
                      placeholder="Field name"
                      onChange={(event) => setSwapLabel(event.target.value)}
                      onKeyDown={(event) => event.key === "Enter" && createAndSwap()}
                    />
                  </label>
                  {swapToNewType === "if" && <IfStatementEditor definition={ifDraft} fields={ifSourceFields}
                    onChange={setIfDraft} />}
                  <ExtraTypeEditor
                    aiEnrich={aiEnrich}
                    onAiEnrich={patchAiEnrich}
                    kind={swapToNewType}
                    fields={fields}
                    formulaText={swapFormulaText}
                    onFormulaText={setSwapFormulaText}
                    formulaError={
                      swapFormulaCheck.ok ? null : swapFormulaCheck.error ?? null
                    }
                    maxValue={swapMaxValue}
                    onMaxValue={setSwapMaxValue}
                    codeLanguage={swapCodeLanguage}
                    onCodeLanguage={setSwapCodeLanguage}
                    idPrefix="cg-swap"
                  />
                  {needsOptions(swapToNewType) && (
                    <OptionsEditor
                      idPrefix="cg-swap-option"
                      drafts={swapOptionDrafts}
                      onDrafts={setSwapOptionDrafts}
                      colorCode={swapColorCode}
                      onColorCode={setSwapColorCode}
                      type={swapToNewType}
                      maxOptions={optionLimit}
                    />
                  )}
                  {swapToNewType === "user" && (
                    <div className="cg-field-hint">
                      {userOptions.length
                        ? `${userOptions.length} people can be assigned.`
                        : "No user list was supplied by the host yet."}
                    </div>
                  )}
                  {scopeChoice && (
                    <ScopeControl value={scopeDraft} onValue={setScopeDraft} />
                  )}
                  <div className="cg-form-actions">
                    <button
                      type="button"
                      className="cg-btn cg-btn--primary"
                      disabled={!canCreateSwap}
                      onClick={createAndSwap}
                    >
                      Create and change
                    </button>
                    <button
                      type="button"
                      className="cg-btn"
                      onClick={() => setSwapTo("")}
                    >
                      Cancel
                    </button>
                  </div>
                </div>
              )}
            </div>
          )}
        </div>
      </AnchoredOverlay>
    );
  }

  // ------------------------------------------------------------------ FORMAT pane (item 10)
  /**
   * ⭐⭐ WAVE-29 T33 (owner item 17) β€” THE COLUMN SUMMARY PANE.
   *
   * A flat list of the six aggregates plus "None", because that is the whole decision β€” there is
   * no draft to reconcile and no Save button to press, so the click IS the answer and the pane
   * closes on it (the same shape as Sort, one group up, and unlike Format, which composes four
   * settings into one bag).
   *
   * β›” THE OPTIONS COME FROM `aggOptions`, never from a list written here. `sum Β· average Β·
   * median Β· min Β· max` are numeric-only and `count` counts ROWS, so a text column offers exactly
   * one row β€” and it offers it, rather than hiding the pane, because "how many records is this
   * group" is the summary a text column CAN answer.
   */
  if (pane === "summary" && onSummary) {
    const options = summaryOptions(field);
    /* ⭐⭐ W50-T05 / R2 β€” THE RESOLVED choice, not `field.agg`. `resolveSummary` answers with the
       view's key first, the legacy field `agg` second and R2's Sum-on-a-numeric-family default
       third, so a column the reader has never touched shows the mark against the aggregate the
       bar is ACTUALLY folding rather than against "None". Reading `field.agg` here is what made
       the header menu and the bottom bar two opinions of one column. */
    const current = resolveSummary(field, summary ?? {});
    return (
      <AnchoredOverlay
        anchor={state.anchor}
        className="cg-column-menu"
        onDismiss={onClose}
        role="dialog"
        ariaLabel={`Summarize ${field.label}`}
        initialFocus="[data-overlay-autofocus]"
        dataKind="column-menu"
      >
        <PaneHead title="Summarize" sub={field.label} onClose={onClose} />
        <div className="cg-menu-list" role="none">
          <button
            type="button"
            data-overlay-autofocus={current.agg === "none" ? true : undefined}
            aria-pressed={current.agg === "none"}
            onClick={() => {
              /* β›” `{ agg: "none" }`, never `undefined`. An absent key means "nobody has chosen",
                 which `resolveSummary` answers with R2's Sum default β€” so clearing by omission
                 would put the total straight back on a numeric column. */
              onSummary({ agg: "none" });
              onClose();
            }}
          >
            <MenuLabel icon="off" text="None" />
          </button>
          {options.map((name) => (
            <button
              key={name}
              type="button"
              data-overlay-autofocus={current.agg === name ? true : undefined}
              aria-pressed={current.agg === name}
              onClick={() => {
                /* Percentile carries its point; every other name is the whole choice. The `p`
                   already in scope is kept so re-picking p75 does not silently become p50. */
                onSummary(name === "percentile" ? { agg: name, p: current.p } : { agg: name });
                onClose();
              }}
            >
              <MenuLabel icon="format" text={summaryLabel({ agg: name, p: current.p })} />
            </button>
          ))}
        </div>
      </AnchoredOverlay>
    );
  }

  /**
   * ⭐⭐ WAVE 50 Β· W50-T05 (instruction 4, R4) β€” **SHOW AS: Value, % of total, or Both.**
   *
   * A flat list of three, the same shape as Summarize one group up: there is no draft to
   * reconcile, so the click IS the answer and the pane closes on it. Sentence case per
   * DESIGN.md Β§2, and the words come from `SHOW_AS_LABELS` so this pane cannot invent a fourth
   * spelling of a mode the formatter already names.
   *
   * β›” ELIGIBILITY IS `isNumericFieldType`, ASKED AT THE MENU ROW BELOW AND NOWHERE ELSE. The
   * done-when lists "number, currency, int, formula, Metric and rollup"; that sentence is the
   * numeric FAMILY, and a list written kind by kind here is the ERROR-20 blank reproduced the
   * first time a kind is added (`resolveSummary`'s note says the same thing about summaries).
   *
   * ⚠ % OF TOTAL IS THE VIEW'S GRAND TOTAL (R4), NOT THE GROUP'S β€” which is what makes the rows
   * and the group headers add to 100% down the grid and the bar read 100%. The base is chosen by
   * `CustomerGrid`, and a column whose summary does not COMPOSE (`SHARE_AGGS` is `sum` and
   * `count` only) shows its value with no share rather than a ratio of two averages.
   */
  if (pane === "showAs" && onShowAs) {
    const current = field.showAs ?? "value";
    return (
      <AnchoredOverlay
        anchor={state.anchor}
        className="cg-column-menu"
        onDismiss={onClose}
        role="dialog"
        ariaLabel={`Show ${field.label} as`}
        initialFocus="[data-overlay-autofocus]"
        dataKind="column-menu"
      >
        <PaneHead title="Show as" sub={field.label} onClose={onClose} />
        <div className="cg-menu-list" role="none">
          {SHOW_AS_MODES.map((mode) => (
            <button
              key={mode}
              type="button"
              data-overlay-autofocus={current === mode ? true : undefined}
              aria-pressed={current === mode}
              onClick={() => {
                onShowAs(mode);
                onClose();
              }}
            >
              <MenuLabel icon="format" text={SHOW_AS_LABELS[mode]} />
            </button>
          ))}
        </div>
      </AnchoredOverlay>
    );
  }

  if (pane === "format" && formatKind) {
    return (
      <AnchoredOverlay
        anchor={state.anchor}
        className="cg-column-menu"
        onDismiss={onClose}
        role="dialog"
        ariaLabel={`Format ${field.label}`}
        initialFocus="[data-overlay-autofocus]"
        dataKind="column-menu"
      >
        <PaneHead title="Field format" sub={field.label} onClose={onClose} />
        <div className="cg-column-create">
          {formatKind === "number" ? (
            <>
              <label>
                <span>Currency symbol</span>
                <select
                  className="cg-select"
                  value={fmtDraft.currencySymbol ?? (field.type === "currency" ? "$" : "")}
                  aria-label="Currency symbol"
                  onChange={(e) => setFmtDraft((d) => ({
                    ...d, currencySymbol: e.target.value as FieldFormat["currencySymbol"],
                  }))}
                >
                  <option value="">None</option>
                  {["$", "EUR", "GBP", "IDR"].map((symbol) => (
                    <option key={symbol} value={symbol}>{symbol}</option>
                  ))}
                </select>
              </label>
              {/* Allow negative is a write policy, so a pre-set field never shows it. */}
              {!schemaLocked && (field.type === "int" || field.type === "currency" || field.type === "pct") && (
                <label className="cg-radio-row" style={{ flexDirection: "row" }}>
                  <input
                    type="checkbox"
                    checked={fmtDraft.allowNegative !== false}
                    disabled={!canEditNumberPolicy}
                    onChange={(e) => setFmtDraft((d) => ({ ...d, allowNegative: e.target.checked }))}
                  />
                  <span>Allow negative numbers</span>
                </label>
              )}
              <label className="cg-radio-row" style={{ flexDirection: "row" }}>
                <input
                  type="checkbox"
                  data-overlay-autofocus
                  checked={fmtDraft.thousands !== false}
                  onChange={(e) =>
                    setFmtDraft((d) => ({ ...d, thousands: e.target.checked }))
                  }
                />
                <span>Thousands separator (12,345)</span>
              </label>
              <label>
                <span>Decimals</span>
                <select
                  className="cg-select"
                  value={
                    Number.isInteger(fmtDraft.decimals) ? String(fmtDraft.decimals) : ""
                  }
                  aria-label="Decimals"
                  onChange={(e) =>
                    setFmtDraft((d) => {
                      const next = { ...d };
                      if (e.target.value === "") delete next.decimals;
                      else next.decimals = Number(e.target.value);
                      return next;
                    })
                  }
                >
                  {/* No decimals key shows the full value; the setting never rounds stored data. */}
                  <option value="">Full value</option>
                  {[0, 1, 2, 3, 4].map((n) => (
                    <option key={n} value={n}>
                      {n}
                    </option>
                  ))}
                </select>
              </label>
              <label className="cg-radio-row" style={{ flexDirection: "row" }}>
                <input
                  type="checkbox"
                  checked={fmtDraft.abbrev === true}
                  onChange={(e) =>
                    setFmtDraft((d) => ({ ...d, abbrev: e.target.checked }))
                  }
                />
                <span>Abbreviate large numbers (34.0M)</span>
              </label>
            </>
          ) : (
            <>
              <label className="cg-radio-row">
                <input
                  type="checkbox"
                  data-overlay-autofocus
                  checked={fmtDraft.time ?? (field.type === "created_time" || field.type === "last_modified_time")}
                  onChange={(e) => setFmtDraft((d) => ({ ...d, time: e.target.checked }))}
                />
                <span>Include the time of day</span>
              </label>
              <label>
                <span>Time zone</span>
                <select
                  className="cg-select"
                  value={fmtDraft.tz === "utc" ? "utc" : "local"}
                  aria-label="Time zone"
                  onChange={(e) =>
                    setFmtDraft((d) => ({ ...d, tz: e.target.value as "local" | "utc" }))
                  }
                >
                  <option value="local">Your local time</option>
                  <option value="utc">UTC</option>
                </select>
              </label>
            </>
          )}
          <div className="cg-form-actions">
            <button
              type="button"
              className="cg-btn cg-btn--primary"
              disabled={JSON.stringify(fmtDraft) === JSON.stringify(field.format ?? {})}
              onClick={() => {
                if (canEditNumberPolicy && fmtDraft.allowNegative !== field.format?.allowNegative)
                  onFieldConfig?.({ format: fmtDraft });
                else onFormat?.(fmtDraft);
                onClose();
              }}
            >
              Save
            </button>
            <button type="button" className="cg-btn" onClick={() => setPane("menu")}>
              Back
            </button>
          </div>
        </div>
      </AnchoredOverlay>
    );
  }

  }

  if (embedded && pane === "width" && onColumnWidth) {
    const width = Number(widthDraft);
    const validWidth = widthDraft.trim() !== "" && Number.isFinite(width) && width >= 50 && width <= 600;
    return (
      <AnchoredOverlay
        anchor={state.anchor}
        className="cg-column-menu"
        onDismiss={onClose}
        dismissOnOutside={false}
        role="dialog"
        ariaLabel={`Column width for ${field.label}`}
        initialFocus="[data-overlay-autofocus]"
        dataKind="column-menu"
      >
        <PaneHead title="Column width" sub={field.label} onClose={onClose} />
        <form className="cg-column-create cg-field-edit" onSubmit={(event) => {
          event.preventDefault();
          if (!validWidth) return;
          onColumnWidth(Math.round(width));
          onClose();
        }}>
          <label>
            <span>Width (px)</span>
            <input
              className="cg-input"
              type="number"
              min={50}
              max={600}
              step={1}
              required
              data-overlay-autofocus
              value={widthDraft}
              onChange={(event) => setWidthDraft(event.target.value)}
            />
          </label>
          <div className="cg-form-actions">
            <button type="submit" className="cg-btn cg-btn--primary" disabled={!validWidth}>Apply</button>
            <button type="button" className="cg-btn" onClick={() => setPane("menu")}>Back</button>
          </div>
        </form>
      </AnchoredOverlay>
    );
  }

  // ------------------------------------------------------------------ the MENU pane
  // Wave-5 items 1/2/3: a flat action list. Editors open their OWN windows (the panes above);
  // nothing edits inline here. Conditional entries render IFF they apply to the current view.
  /**
   * ⭐⭐ W39-T17 β€” THE SHARE ID FOR THIS COLUMN, or `null` if one cannot honestly be built.
   *
   * β›” THREE WAYS IT REFUSES, and every one of them would otherwise produce an id the server
   * accepts and then cannot resolve:
   *   Β· no `tableKey` β€” the host has no SERVER-issued key (see that prop's note: the local
   *     fallback is a key the server never issues, and a grant on one notifies nobody);
   *   Β· an empty one β€” `shares.field_oid` raises on a blank half, so the row must not offer it;
   *   Β· a field key containing `:` β€” `split_field_oid` refuses any oid whose FIELD half carries
   *     the separator, so such a column is not shareable and saying so by omission beats a row
   *     that 404s.
   */
  const shareTable = (tableKey ?? "").trim();
  const shareOid =
    (field.custom || field.shared) && shareTable && field.key && !field.key.includes(":")
      ? `${shareTable}:${field.key}`
      : null;

  /**
   * Open the SHELL's access editor for this column β€” the same dialog, roles and people picker a
   * view or a folder gets (W39-T17's done-when; `shell/ShareDialog.tsx` renders all four kinds).
   *
   * β›”β›” THE EVENT NAME IS A HARD-CODED LITERAL AND MUST STAY ONE. `customer-grid/**` MUST NOT
   * import `shell/**` (this tree is host-neutral β€” the same rule `ViewSidebar.tsx::openShare`
   * states and obeys), so `shareModel.SHARE_OPEN_EVENT` is unreachable from here by design.
   * The literal is spelled once there and once here, and `verify_wiring.py`'s W39-W1 row pins
   * BOTH ENDS precisely because no shared constant can keep them in step.
   * β›” It degrades to NOTHING when no shell is listening: an event nobody hears opens no dialog
   * and throws no error, which is the right failure for a frame-level surface reached from a
   * column menu.
   */
  const openFieldShare = () => {
    if (!shareOid) return;
    window.dispatchEvent(
      new CustomEvent("aios:share-open", {
        detail: { kind: "field", id: shareOid, label: field.label },
      })
    );
  };

  /**
   * ⭐⭐ W39-T17 / R8 β€” MAY THIS VIEWER DELETE THIS COLUMN? The client half of the server's wall,
   * spelled with the same creator/admin identity rule as the server rather than a second
   * one: `createdBy` is a login username while the people picker deals in display names
   * ([[login-resolves-email-writes-do-not]]), and one spelling means a mismatch lands identically
   * in both places instead of differently in each.
   *
   * β›” THE UNSTAMPED CASE ANSWERS "YES" ON PURPOSE, and it is a deliberate under-reach.
   * `routes_tables.delete_shared_field` reads `owner = str(defn.get("createdBy") or "")` and
   * refuses a non-admin when it is blank, so an UNSTAMPED shared column is really admin-only. But
   * the client cannot tell one from a base Odoo column, which carries no `createdBy` either and
   * is deletable by nobody at all β€” firing there would put a refusal on every source field on the
   * grid. So the sentence appears only where the client can NAME the person, which is the only
   * shape in which it is useful.
   * ⚠ IT DOES NOT DISABLE THE DELETE BUTTON, AND THE REASON IS THE `viewer === undefined` LEG,
   * not the stratum. The predicate can only fire where `createdBy` is stamped and differs from
   * the viewer, which IS the server-walled path β€” so "a `custom_` delete is client-side" would be
   * a rationale describing a case that never reaches here. What does reach here is a host that
   * supplied no `viewer` (the payload's field is optional): `mayDeleteField` then answers false
   * for the column's OWN CREATOR, and a disable on that would take a delete away from the one
   * person who certainly has it. Fail-closed is right for a SENTENCE and wrong for a CONTROL.
   * ⚠ So a `ut_*` link/rollup/formula created by somebody else shows this line WITH a live Delete
   * button beside it, and that button 403s. Stated rather than hidden: the server is the wall,
   * this is the courtesy half, and narrowing the button is a separate decision.
   */
  const deleteOwner = (field.createdBy ?? "").trim();
  const mayDeleteField =
    !deleteOwner || (!!viewer && (viewer.isAdmin || deleteOwner === viewer.name));

  /**
   * ⭐⭐ W41-T29 (R6, contract C2) β€” WHAT C1 SAYS ABOUT THIS COLUMN, and what C2 concludes from
   * it. Four consts, read once, consumed only by the Delete row far below.
   *
   * β›” THE BLOCK ABOVE IS UNTOUCHED, ON PURPOSE. `mayDeleteField` there is the wave-39
   * `createdBy` courtesy predicate whose `!deleteOwner` short-circuit is what keeps its sentence
   * off every base Odoo column; swapping it for `mayDeleteFieldRight` would print "Only  or an
   * administrator can delete this field" with a blank name on the entire grid, because C1's
   * `class` key is not on the wire yet (C8). The new predicates NARROW; they replace nothing.
   *
   * β›” C8, AND THE SPLIT IS DELIBERATE. `presetRefusal` is viewer-INDEPENDENT, so R6(a) bites the
   * moment lane A stamps `class` β€” an absolute rule must not wait on a viewer. `canRemove` and
   * the rights check need both halves, and `rightsKnown` is what tells "the predicate said no"
   * from "there was nothing to ask": with no classification the Delete row stands exactly as it
   * does today rather than vanishing because the server half is late.
   *
   * ⚠ R6(a) VS THE 2026-08-09 PRE-SET-ROLLUP RULING, STATED RATHER THAN HIDDEN. That ruling let
   * a pre-set ROLLUP keep its Delete; R6 (wave 41) says a pre-set is deletable by nobody, and it
   * is the newer word, so `class.origin` wins here. If lane A classifies a pre-set rollup as
   * `preset`, its Delete goes β€” which is R6(a) working, and worth a look before the wave closes.
   */
  const fieldC1 = fieldClassOf(field);
  const deletionLocked = fieldDeletionLocked(field);
  const presetRefusal = deleteRefusalReason(fieldC1, viewer);
  const canRemoveFromMine = mayRemoveField(fieldC1, viewer);
  const rightsKnown = fieldC1 !== null && !!viewer;
  const c1AllowsDelete =
    !deletionLocked && !presetRefusal && !canRemoveFromMine &&
    (!rightsKnown || mayDeleteFieldRight(fieldC1, viewer));

  return (
    <AnchoredOverlay
      anchor={state.anchor}
      className="cg-column-menu"
      onDismiss={onClose}
      role="dialog"
      ariaLabel={`Column settings for ${field.label}`}
      initialFocus={embedded ? "first" : "[data-overlay-autofocus]"}
      dismissOnOutside={!embedded}
      dataKind="column-menu"
    >
      <PaneHead title={field.label} sub={embedded ? undefined : typeLine} onClose={onClose} />
      {/* Item 8c β€” any measure-carrying column exposes its PERIOD, the property that defines
          it. Item 21 (2026-08-02) moved the EDITOR into the Edit-field pane; what stays here
          is one line that STATES the period and opens that pane, because the window is the
          first thing you want to know about a metric column and the menu had become the only
          place it was written down. A row, not a control: the menu pane edits nothing inline. */}
      {canPeriod && canEditDefinition && !schemaLocked && (
        <button
          type="button"
          className="cg-column-periodline"
          onClick={() => {
            setRenameDraft(field.label);
            setPane("edit");
          }}
        >
          <span className="cg-swap-label">Period</span>
          <span className="cg-column-periodval">{windowLabel(field.measure!.window)}</span>
        </button>
      )}

      {/* Wave-7 item W4 (contract C6): Airtable's grouping, thin dividers between groups,
          an icon on EVERY action. Presentation only β€” every handler and event is the one it
          was before; entries not in Airtable's list slot into the nearest sensible group. */}
      <div className="cg-column-actions">
        {!embedded && <>
        {/* Owner item 8 (2026-07-31) β€” EDIT FIELD sits at the very top, above Duplicate:
            the one window for the field's name, type (with per-type choices/stars/formula)
            and the Change-field control. Offered on EVERY field β€” what a read-only field
            cannot change, the pane says honestly instead of hiding the door. */}
        {/* ⭐⭐ W41-T31 β€” `editPaneOffered`, the THIRD of the three gates that used to hide this
            row from a pre-set column (the other two are `canEditDefinition` itself and the pane
            seed). A pre-set gets the same row and lands on the description-only pane; every
            other field is unaffected, because `canEditDescription` is false for all of them.
            ⚠ It also gives the MENU pane a focus target on a pre-set for the first time: this
            button carries the only `data-overlay-autofocus` in the action list, so while the
            row was withheld the menu opened with the keyboard left outside the dialog. */}
        {editPaneOffered && (
          <button type="button" data-overlay-autofocus onClick={() => {
            setRenameDraft(field.label);
            setPane("edit");
          }}>
            <MenuLabel icon="rename" text="Edit field" />
          </button>
        )}

        {/* ⭐⭐ W39-T17 β€” SHARE FIELD, directly beneath Edit field, and it opens the SAME dialog
            views and folders already use (one editor, one vocabulary: the R10 ruling behind
            `shell/ShareDialog.tsx`). NOT gated on `schemaLocked`: sharing a column changes no
            schema, it decides who can SEE it, which is the same reason Summary, Sort and Filter
            sit below without that gate.
            β›” NO `data-overlay-autofocus` HERE. The overlay's `initialFocus` selector is exactly
            that attribute, and a second row wearing it makes the opening focus ambiguous.
            β›” NOT GATED ON THE VIEWER EITHER, deliberately. The dialog itself states the refusal
            when `mayAdminister` is false ("NOT A HIDDEN EDITOR β€” a stated refusal"), and a hidden
            row would leave a collaborator guessing why the column they can see is not theirs to
            pass on. The one thing that DOES withdraw it is a missing server table key, because
            without one the id cannot be built. */}
        {onSetDeletionLock && (
          <button type="button" onClick={() => onSetDeletionLock(!deletionLocked)}>
            <MenuLabel
              icon={deletionLocked ? "unlock" : "permissions"}
              text={deletionLocked ? "Clear deletion lock" : "Lock deletion"}
            />
          </button>
        )}
        {onCopyFieldLink && (
          <button type="button" onClick={onCopyFieldLink}>
            <MenuLabel icon="duplicate" text="Copy link to field" />
          </button>
        )}

        {shareOid && (
          <button
            type="button"
            onClick={() => {
              openFieldShare();
              onClose();
            }}
          >
            {/* β›” AN INLINE NODE, NOT A `MenuIcon` NAME, and that is forced rather than chosen.
                 `MenuLabel`'s prop is `MenuIconName | ReactNode` and `ReactNode` admits any
                 string, so `icon="share"` would COMPILE and paint an empty 16px box forever
                 (`MENU_ICONS` has no such key, and `icons.tsx` is not this ticket's file).
                 ⭐⭐ W40-T24 β€” THE GEOMETRY IS `SHARE_SHAPE`, NOT A THREE-NODE GRAPH ANY MORE.
                 The argument that stood here β€” that the graph is "the mark every product uses for
                 this verb" β€” was true of a product where it was the only share drawing. It is not
                 any more: W40-T20 put `SHARE_SHAPE` (two people) on the grid header's shared-field
                 sprite and W40-T21 put it on Share view and Share folder, so this row was the last
                 place one verb spoke in a second drawing β€” a field whose HEADER wears two people,
                 shared from a row wearing a graph. DESIGN.md Β§4's "one mark, one meaning" is the
                 rule and `iconShapes.ts` is the vocabulary; paths as DATA is what stops the two
                 painters drifting, which is exactly what a hand-written copy here would restart.
                 ⚠ Rendered the way `ViewSidebar.ShareMark` renders it β€” same viewBox, same 1.35
                 stroke, same round caps β€” so the rail's share and this one are one mark and not
                 two readings of one array. */}
            <MenuLabel
              icon={
                <svg width={16} height={16} 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>
              }
              text="Share field"
            />
          </button>
        )}

        <div className="cg-menu-sep" role="separator" aria-hidden />

        {/* ⭐⭐ W51-T03 / OWNER RULING R6 + INSTRUCTION 5 β€” ONE DOOR, NOT TWO VERBS.
            W48-T17 shipped "Duplicate definition" and "Duplicate with permitted values" side by
            side, which made the reader answer a question about copy semantics before they had
            seen the column. Cloning a source-backed definition is still safe for W48-T17's
            reason (the result is a new tenant-owned custom field, and the host independently
            intersects any submitted cells with this viewer's scope) β€” what changed is WHERE the
            value question is asked. The host opens the shared confirm dialog with a "Duplicate
            cells" toggle when the column holds values, and duplicates in one click when it holds
            none: a dialog with only one possible answer is a click tax, not a safeguard. */}
        {onDuplicate && (
          <button type="button" onClick={() => { onDuplicate(); onClose(); }}>
            <MenuLabel icon="duplicate" text="Duplicate field" />
          </button>
        )}
        {!viewControlsReadOnly && onMoveLeft && (
          <button type="button" onClick={() => { onMoveLeft(); onClose(); }}>
            <MenuLabel icon="insertLeft" text="Move left" />
          </button>
        )}
        {!viewControlsReadOnly && onMoveRight && (
          <button type="button" onClick={() => { onMoveRight(); onClose(); }}>
            <MenuLabel icon="insertRight" text="Move right" />
          </button>
        )}
        {canAddField && <>
        <button type="button" onClick={() => setPosition("left")}>
          <MenuLabel icon="insertLeft" text="Insert field left" />
        </button>
        <button type="button" onClick={() => setPosition("right")}>
          <MenuLabel icon="insertRight" text="Insert field right" />
        </button>
        <button type="button" onClick={() => setPosition("end")}>
          <MenuLabel icon="addEnd" text="Add field at end" />
        </button>
        </>}

        <div className="cg-menu-sep" role="separator" aria-hidden />

        {/* Group 2 β€” display format. Description now lives in Edit field directly below Name,
            so there is one definition editor instead of two nearby doors. */}
        {/* Field format is display only, so a pre-set column offers it too. */}
        {formatKind && (
          <button type="button" onClick={() => setPane("format")}>
            <MenuLabel icon="format" text="Field format" />
          </button>
        )}
        {/* ⭐ WAVE-29 T33 (owner item 17) β€” the COLUMN SUMMARY. Offered on every column, because
            `count` applies to any type; the numeric folds are filtered per type inside the pane
            by `aggOptions`. ⚠ NOT gated on `schemaLocked`: a summary is a reading of the column,
            not a change to its schema, so it belongs on a pre-set column too β€” the same reason
            Sort and Filter sit below without that gate. */}
        {onSummary && (
          <button type="button" onClick={() => setPane("summary")}>
            {/* ⭐⭐ W50-T05 / R2 β€” THE ROW READS THE RESOLVED CHOICE, NOT `field.agg`. The old
                label said "Summarize this column" whenever the FIELD carried no `agg`, which
                after W50-T03 was true of every column the bar was already totalling by default:
                the menu offered to start something that had been running since the view opened.
                ⚠ "None" is a state a reader chose, so it is named rather than hidden behind the
                invitation β€” the row says what the column does now, in both directions. */}
            <MenuLabel
              icon="format"
              text={`Summary: ${summaryLabel(resolveSummary(field, summary ?? {}))}`}
            />
          </button>
        )}
        {/* ⭐⭐ WAVE 50 Β· W50-T05 (instruction 4) β€” SHOW AS, beside Field format and in the same
            control vocabulary: one menu row that opens one pane, exactly as Format and Summarize
            do (DESIGN.md Β§4 β€” one control shape per rail). ⚠ NOT gated on `schemaLocked`, for
            Summarize's reason: how a number READS is not a change to the column's schema, so it
            belongs on a pre-set column too.
            β›” `isNumericFieldType` IS THE ELIGIBILITY TEST. A share of a total is meaningless on
            text, a date or a checkbox, and a kind list written here would drop `formula`,
            `metric` or `rollup` the way ERROR 20 dropped a formula column from the summary. */}
        {onShowAs && isNumericFieldType(field.type) && (
          <button type="button" onClick={() => setPane("showAs")}>
            <MenuLabel
              icon="format"
              text={`Show as: ${SHOW_AS_LABELS[field.showAs ?? "value"]}`}
            />
          </button>
        )}

        <div className="cg-menu-sep" role="separator" aria-hidden />

        </>}

        {/* Group 3 β€” sort. Direction wording stays the shipped per-type directionLabel. */}
        {!viewControlsReadOnly && onSort && fieldOfferable && <>
          <button type="button" onClick={() => { onSort("asc"); onClose(); }}>
            <MenuLabel
              icon="sortAsc"
              text={`Sort ${directionLabel(field.type, "asc")}`}
            />
          </button>
          <button type="button" onClick={() => { onSort("desc"); onClose(); }}>
            <MenuLabel
              icon="sortDesc"
              text={`Sort ${directionLabel(field.type, "desc")}`}
            />
          </button>
        </>}
        {!viewControlsReadOnly && onClearSort && sortedDir != null && (
          <button type="button" onClick={() => { onClearSort(); onClose(); }}>
            <MenuLabel icon="off" text="Don't sort by this field" />
          </button>
        )}

        <div className="cg-menu-sep" role="separator" aria-hidden />
        {/* Group 4 β€” the view-config group: filter Β· group (+ pin, which also shapes
            the view). */}
        {/* Item 6c: a measure-carrying column's Filter-by seeds the equivalent MEASURE
            condition β€” the designed replacement for filtering the (filterable:false)
            column itself (offered only while the host serves measures, the same
            availability rule as measure conditions). Everything else keeps the plain
            filterable check. */}
        {!viewControlsReadOnly && onFilterBy && fieldOfferable && (field.filterable !== false ||
          (field.measure != null && measures.length > 0)) && (
          <button type="button" onClick={() => { onFilterBy(); onClose(); }}>
            <MenuLabel icon="filter" text="Filter by this field" />
          </button>
        )}
        {!viewControlsReadOnly && onClearFilter && isFiltered && (
          <button type="button" onClick={() => { onClearFilter(); onClose(); }}>
            <MenuLabel icon="off" text="Don't filter by this field" />
          </button>
        )}
        {!viewControlsReadOnly && groupable && !isGrouped && (
          <button type="button" onClick={() => { onGroupByField(); onClose(); }}>
            <MenuLabel icon="group" text="Group by this field" />
          </button>
        )}
        {!viewControlsReadOnly && isGrouped && (
          <button type="button" onClick={() => { onClearGroup(); onClose(); }}>
            <MenuLabel icon="off" text="Don't group by this field" />
          </button>
        )}
        {/* Item 11c β€” pin: freeze the columns up to this one; Unpin restores the identity
            column alone. */}
        {!viewControlsReadOnly && !embedded && onPinTo && !pinnedTo && (
          <button type="button" onClick={() => { onPinTo(); onClose(); }}>
            <MenuLabel icon="pin" text="Pin up to this field" />
          </button>
        )}
        {!viewControlsReadOnly && !embedded && onUnpin && (
          <button type="button" onClick={() => { onUnpin(); onClose(); }}>
            <MenuLabel icon="unpin" text="Unpin all fields" />
          </button>
        )}

        <div className="cg-menu-sep" role="separator" aria-hidden />

        {!viewControlsReadOnly && embedded && onColumnWidth && (
          <button type="button" onClick={() => {
            setWidthDraft(String(Math.round(columnWidth)));
            setPane("width");
          }}>
            <MenuLabel icon="format" text="Column width" />
          </button>
        )}

        {/* Group 5 β€” hide Β· delete. */}
        {!viewControlsReadOnly && <button
          type="button"
          disabled={locked}
          title={locked ? "The primary field stays visible" : undefined}
          onClick={onHide}
        >
          <MenuLabel icon="hide" text="Hide field" />
        </button>}
        {!embedded && <>
        {/* ⭐⭐ WAVE-34 (owner ruling R13) β€” THE BULK RUN, and it is TWO rows rather than one
            because "run this column" is two different questions with two different bills.
            β›” NEITHER LABEL SAYS "everything". `ai_enrich_may_write` refuses a human-edited cell
            under every policy, so "All rows" means every row the AI wrote; saying "all" flat
            would be a control that quietly means less than it says, which is worse than a
            narrower control. The server takes these as `scope: "blank" | "always"`.
            ⚠ `onEnrich` is OPTIONAL, exactly as `onDelete` above it is: a host that has not
            wired the door renders no row rather than a row that does nothing.
            β›” THE GLYPH IS `FieldTypeIcon`, NOT A `MenuIcon` NAME, and that is not a style
            choice. `MenuLabel`'s prop is `MenuIconName | ReactNode`, and `ReactNode` admits
            any string, so `icon="sparkle"` COMPILES and renders an empty glyph box forever
            (`MENU_ICONS` has no such key). Reusing the type icon paints the same mark the
            column header and the add-field picker already wear, from one geometry source, and
            needs no new key in a file no lane owns. [[schema-role-is-not-a-value-wall]] */}
        {field.type === "ai_enrich" && onEnrich && (
          <>
            <button
              type="button"
              title="Fills only the cells that are still empty. Costs nothing for rows that already have an answer."
              onClick={() => onEnrich("blank")}
            >
              <MenuLabel icon={<FieldTypeIcon type="ai_enrich" size={16} />}
                text="Fill rows never filled" />
            </button>
            <button
              type="button"
              title="Re-asks the model for every row the AI wrote. A cell you have typed into is left alone."
              onClick={() => onEnrich("always")}
            >
              <MenuLabel icon={<FieldTypeIcon type="ai_enrich" size={16} />}
                text="Fill all rows again" />
            </button>
          </>
        )}
        {/* ⭐⭐ W40-T24 (contract C2) β€” `offer.remove` IS THE PRE-SET LOCK, ADDED BESIDE the two
            conditions that were already here rather than replacing either. `onDelete` asks
            whether the host wired a delete DOOR at all (it has three, one per stratum) and
            `schemaLocked` is `CustomerGrid.isSchemaLocked`; AND-ing a third refusal can only
            subtract, so nothing is duplicated and no working delete is widened.
            ⚠ On the Odoo grids this is behaviour-neutral: a pre-set column already had no door,
            so Delete never rendered. What changes is that the absence is now the LOCK's answer
            rather than a coincidence of wiring, which is the half of D-413 the client can settle.
            ⚠ The pre-set ROLLUP keeps its Delete, by the 2026-08-09 owner ruling `isSchemaLocked`
            already carries. `columnDefinitionOffer` restates that exception rather than dropping
            it β€” see its note. */}
        {/* ⭐⭐ W41-T29 (R6(b)) β€” REMOVE FROM MY FIELDS, and it stands WHERE Delete would have
            stood. `canRemoveFromMine` has already withdrawn the Delete row below, so the two are
            mutually exclusive by construction rather than by ordering: a column a colleague
            shared with me is theirs to destroy and mine only to hand back.
            β›” NOT `is-danger`, and not `onDelete`. Dropping a share deletes nothing, so it takes
            neither the destructive colour nor the destructive door. Wiring this label to
            `onDelete` would be the one failure this ticket must not ship. */}
        {!schemaLocked && canRemoveFromMine && onRemoveFromMine && (
          <button type="button" title={REMOVE_FIELD_HINT} onClick={onRemoveFromMine}>
            {/* ⚠ A NODE, NOT A NAME, AND `MenuLabel` DOCUMENTS THIS ESCAPE HATCH FOR IT. The
                nearest name in the vocabulary is `hide`, and hiding is a DIFFERENT act this very
                panel already offers on the checkbox: one glyph for both would say a removal is
                reversible from the same place a hide is. The minus mark is the Fields manager's
                own remove mark, so the two surfaces wear one picture. */}
            <MenuLabel
              icon={
                <svg width="16" height="16" viewBox="0 0 16 16" fill="none" aria-hidden>
                  <circle cx="8" cy="8" r="5.7" stroke="currentColor" strokeWidth={1.3} />
                  <path d="M5.5 8h5" stroke="currentColor" strokeWidth={1.3} strokeLinecap="round" />
                </svg>
              }
              text={REMOVE_FIELD_LABEL}
            />
          </button>
        )}
        {/* ⭐⭐ W41-T29 (R6(a)) β€” A PRE-SET SAYS IT CANNOT BE DELETED, instead of a Delete row
            that is simply absent. `c1AllowsDelete` below is what withdraws the row; this is the
            sentence that stops the absence reading as a wiring accident.
            β›” DESIGN Β§4, THE THREE LOCKS: the copy is about the DEFINITION (this column came with
            the database). It is NOT "you cannot type here" β€” that is a LOCKED DATABASE, another
            lock entirely β€” and it is not a locked view. A pre-set field's cells stay typeable.
            β›” `.cg-field-hint`, NOT A `MenuLabel` ROW, for the reason W39-T17 measured two rows
            down: `.cg-column-actions button` is `white-space: nowrap` and `.cg-mi-text`
            ellipsises, so a sentence in a menu row is clipped at exactly the half that carries
            the reason. The 8px inset matches that hint's, so the two align. */}
        {/* β›” GATED ON THE DELETE ROW'S OWN THREE CONDITIONS, and that is the difference between
            an answer and chrome. `columnDefinitionOffer.remove` is FALSE for every base Odoo
            column (`ownShape` false, no `route_order` kind, not a rollup), so those columns never
            had a Delete row for this sentence to explain, and an ungated refusal would grow one
            paragraph on every pre-set column in the product the day lane A stamps `class`.
            The refusal belongs only where a delete WOULD otherwise have stood. Same narrowing
            the Fields manager makes with `deletableKeys?.has(f.key)`, for the same reason. */}
        {presetRefusal && !schemaLocked && offer.remove && onDelete && (
          <p className="cg-field-hint" style={{ padding: "2px 8px 4px" }}>
            {presetRefusal}
          </p>
        )}
        {deletionLocked && !schemaLocked && offer.remove && onDelete && (
          <p className="cg-field-hint" style={{ padding: "2px 8px 4px" }}>
            Deletion is locked. An Owner must clear the deletion lock before this field can be deleted.
          </p>
        )}
        {!schemaLocked && offer.remove && onDelete && c1AllowsDelete && (
          <button
            type="button"
            className="is-danger"
            title={
              /**
               * ⭐ 2026-08-10 β€” THE PRE-SET ROLLUP COMES BACK, and the honest place to say so is
               * here rather than in a tombstone.
               *
               * A pre-set column carries `automation.preset`, and BOTH reconcilers
               * (`_reconcile_ig_graph_fields`, `odoo_relational`'s forward migration) re-declare
               * every field they own on the next run. RECONFIGURING one sticks β€” the custody
               * stamp (`userEdited`) switches the reconciler off for that column β€” but DELETING
               * one leaves nothing behind to carry a stamp, so it is re-added within a tick.
               * β›” NOT FIXED WITH A TOMBSTONE, deliberately: that is a new store key two
               * reconcilers must both consult, and the custody stamp is the precedent for how
               * that goes wrong when only one of them reads it. The delete is not broken β€” it is
               * a delete of something the product re-declares, and the user is told which.
               */
              /**
               * ⭐⭐ W41-T29 (R6(c)) β€” THE ARMED STATE NAMES WHO LOSES IT, and it is prepended as
               * one more branch rather than replacing the four below: unarmed, the question is
               * still "what does this button do to my values", and that is what they answer.
               * β›” NO INDIVIDUAL IS NAMED AND THE COPY SAYS SO. C1 carries no grantee list and C8
               * carries five integers and not one identity, so the impact is the OWNER plus the
               * audience CATEGORY plus counts, closing on "counted rather than named". A tally
               * that reads as exhaustive beside a delete button is worse than no tally.
               */
              field.measure
                ? "Removes this formula column from the workspace."
                : field.automation?.preset === true
                ? "Part of this database's built-in schema. It will be re-created on the " +
                  "next run. Hide it to keep it off the grid."
                : field.type === "rollup" || field.type === "link" ||
                  field.type === "formula"
                ? "Removes this column. No values are lost. It holds none of its own."
                : "Removes this field AND its values on every row."
            }
            /* R6(c) for a reader who cannot hover: `title` is not an accessible name, so the
               armed impact is given one. Unarmed, the visible label is the name it always was. */
            onClick={onDelete}
          >
            <MenuLabel
              icon="trash"
              text="Delete field"
            />
          </button>
        )}
        {/* ⭐⭐ W39-T17 / R8 β€” A FIELD YOU CANNOT DELETE SAYS WHO CAN, which nothing in this menu
            did: the only place a creator was ever named is the permissions pane's parenthetical
            `(created by X)`, which a person has to open a different window to read.
            `routes_tables.delete_shared_field` refuses everyone but the stamped `createdBy` and
            an admin, and it refuses at the SERVER β€” so without this the menu either hides the row
            with no reason given or offers a button whose only outcome is a 403.
            β›” NOT A `MenuLabel` ROW, and the reason is measured in `index.css`:
            `.cg-column-actions button` is `white-space: nowrap` and `.cg-mi-text` ellipsises, so
            a sentence in a menu row would render as "Only alice or an administr…" β€” the half that
            names the person is exactly the half that gets cut. `.cg-field-hint` is this file's
            existing wrapping prose class (36 uses), so no rule is owed in a stylesheet this
            ticket does not own.
            β›” NO DASH IN IT (standing rule 2): the nearest precedent, `ShareDialog`'s own
            refusal, carried two em dashes, and copying its shape is how the dash travels. */}
        {!mayDeleteField && (
          /* ⚠ The 8px inset is INLINE because it is the only thing this row needs from a
             stylesheet and `index.css` is not this ticket's file. `.cg-column-actions` has no
             horizontal padding of its own (its BUTTONS carry `0 8px`), so a bare hint would sit
             8px left of every label above it and read as belonging to the panel rather than to
             the Delete row it explains. */
          <p className="cg-field-hint" style={{ padding: "2px 8px 4px" }}>
            Only {deleteOwner} or an administrator can delete this field.
          </p>
        )}
        </>}
      </div>
    </AnchoredOverlay>
  );
}